From 82571a8aecc74c9ee80365e15807748417bf789f Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 14:44:43 +0200 Subject: [PATCH 01/11] stm32cube: update stm32c0 to cube version V1.2.0 Update Cube version for STM32C0xx series on https://github.com/STMicroelectronics from version v1.1.0 to version v1.2.0 Signed-off-by: Guillaume Gautier --- stm32cube/stm32c0xx/CMakeLists.txt | 7 +- stm32cube/stm32c0xx/README | 8 +- .../drivers/include/Legacy/stm32_hal_legacy.h | 74 +- .../stm32c0xx/drivers/include/stm32c0xx_hal.h | 124 +- .../drivers/include/stm32c0xx_hal_adc.h | 701 +- .../drivers/include/stm32c0xx_hal_conf.h | 14 +- .../drivers/include/stm32c0xx_hal_cortex.h | 16 +- .../drivers/include/stm32c0xx_hal_crc.h | 2 +- .../drivers/include/stm32c0xx_hal_def.h | 6 +- .../drivers/include/stm32c0xx_hal_dma.h | 75 +- .../drivers/include/stm32c0xx_hal_dma_ex.h | 10 +- .../drivers/include/stm32c0xx_hal_exti.h | 23 +- .../drivers/include/stm32c0xx_hal_flash.h | 44 +- .../drivers/include/stm32c0xx_hal_flash_ex.h | 2 +- .../drivers/include/stm32c0xx_hal_gpio.h | 2 +- .../drivers/include/stm32c0xx_hal_gpio_ex.h | 192 +- .../drivers/include/stm32c0xx_hal_hcd.h | 602 ++ .../drivers/include/stm32c0xx_hal_i2c.h | 2 - .../drivers/include/stm32c0xx_hal_i2c_ex.h | 16 +- .../drivers/include/stm32c0xx_hal_iwdg.h | 1 - .../drivers/include/stm32c0xx_hal_pcd.h | 629 ++ .../drivers/include/stm32c0xx_hal_pcd_ex.h | 87 + .../drivers/include/stm32c0xx_hal_pwr.h | 27 + .../drivers/include/stm32c0xx_hal_pwr_ex.h | 228 +- .../drivers/include/stm32c0xx_hal_rcc.h | 713 +- .../drivers/include/stm32c0xx_hal_rcc_ex.h | 457 +- .../drivers/include/stm32c0xx_hal_rtc.h | 109 +- .../drivers/include/stm32c0xx_hal_rtc_ex.h | 57 +- .../drivers/include/stm32c0xx_hal_smbus.h | 2 - .../drivers/include/stm32c0xx_hal_smbus_ex.h | 7 + .../drivers/include/stm32c0xx_hal_spi.h | 26 +- .../drivers/include/stm32c0xx_hal_spi_ex.h | 2 +- .../drivers/include/stm32c0xx_hal_tim.h | 58 +- .../drivers/include/stm32c0xx_hal_uart.h | 5 +- .../drivers/include/stm32c0xx_hal_usart.h | 5 +- .../drivers/include/stm32c0xx_hal_usart_ex.h | 2 +- .../drivers/include/stm32c0xx_ll_adc.h | 968 ++- .../drivers/include/stm32c0xx_ll_bus.h | 433 +- .../drivers/include/stm32c0xx_ll_crc.h | 22 +- .../drivers/include/stm32c0xx_ll_crs.h | 810 ++ .../drivers/include/stm32c0xx_ll_dma.h | 448 +- .../drivers/include/stm32c0xx_ll_dmamux.h | 346 +- .../drivers/include/stm32c0xx_ll_exti.h | 435 +- .../drivers/include/stm32c0xx_ll_gpio.h | 57 +- .../drivers/include/stm32c0xx_ll_i2c.h | 15 +- .../drivers/include/stm32c0xx_ll_iwdg.h | 15 +- .../drivers/include/stm32c0xx_ll_pwr.h | 255 +- .../drivers/include/stm32c0xx_ll_rcc.h | 395 +- .../drivers/include/stm32c0xx_ll_rtc.h | 215 +- .../drivers/include/stm32c0xx_ll_spi.h | 114 +- .../drivers/include/stm32c0xx_ll_system.h | 299 +- .../drivers/include/stm32c0xx_ll_tim.h | 69 +- .../drivers/include/stm32c0xx_ll_usb.h | 911 ++ .../drivers/include/stm32c0xx_ll_utils.h | 87 +- .../drivers/include/stm32c0xx_ll_wwdg.h | 13 +- .../stm32c0xx/drivers/src/stm32c0xx_hal.c | 31 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_adc.c | 116 +- .../drivers/src/stm32c0xx_hal_adc_ex.c | 10 +- .../drivers/src/stm32c0xx_hal_cortex.c | 82 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_crc.c | 4 +- .../drivers/src/stm32c0xx_hal_crc_ex.c | 2 - .../stm32c0xx/drivers/src/stm32c0xx_hal_dma.c | 5 +- .../drivers/src/stm32c0xx_hal_dma_ex.c | 3 - .../drivers/src/stm32c0xx_hal_exti.c | 9 +- .../drivers/src/stm32c0xx_hal_flash_ex.c | 66 +- .../drivers/src/stm32c0xx_hal_gpio.c | 32 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_hcd.c | 2881 ++++++ .../stm32c0xx/drivers/src/stm32c0xx_hal_i2c.c | 214 +- .../drivers/src/stm32c0xx_hal_i2c_ex.c | 6 + .../stm32c0xx/drivers/src/stm32c0xx_hal_i2s.c | 78 +- .../drivers/src/stm32c0xx_hal_iwdg.c | 4 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_pcd.c | 2241 +++++ .../drivers/src/stm32c0xx_hal_pcd_ex.c | 331 + .../stm32c0xx/drivers/src/stm32c0xx_hal_pwr.c | 18 +- .../drivers/src/stm32c0xx_hal_pwr_ex.c | 99 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_rcc.c | 112 +- .../drivers/src/stm32c0xx_hal_rcc_ex.c | 399 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_rtc.c | 70 +- .../drivers/src/stm32c0xx_hal_rtc_ex.c | 9 +- .../drivers/src/stm32c0xx_hal_smartcard.c | 2 +- .../drivers/src/stm32c0xx_hal_smbus.c | 7 +- .../drivers/src/stm32c0xx_hal_smbus_ex.c | 8 + .../stm32c0xx/drivers/src/stm32c0xx_hal_spi.c | 419 +- .../drivers/src/stm32c0xx_hal_spi_ex.c | 2 +- .../stm32c0xx/drivers/src/stm32c0xx_hal_tim.c | 31 +- .../drivers/src/stm32c0xx_hal_tim_ex.c | 64 +- .../src/stm32c0xx_hal_timebase_tim_template.c | 5 +- .../drivers/src/stm32c0xx_hal_uart.c | 41 +- .../drivers/src/stm32c0xx_hal_uart_ex.c | 2 +- .../drivers/src/stm32c0xx_hal_usart.c | 17 +- .../drivers/src/stm32c0xx_hal_usart_ex.c | 2 +- .../drivers/src/stm32c0xx_hal_wwdg.c | 1 - .../stm32c0xx/drivers/src/stm32c0xx_ll_adc.c | 19 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_crc.c | 2 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_crs.c | 101 + .../stm32c0xx/drivers/src/stm32c0xx_ll_dma.c | 27 + .../stm32c0xx/drivers/src/stm32c0xx_ll_exti.c | 89 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_gpio.c | 33 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_i2c.c | 15 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_rcc.c | 118 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_rtc.c | 8 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_spi.c | 16 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_tim.c | 31 +- .../drivers/src/stm32c0xx_ll_usart.c | 2 +- .../stm32c0xx/drivers/src/stm32c0xx_ll_usb.c | 1485 ++++ .../drivers/src/stm32c0xx_ll_utils.c | 54 +- stm32cube/stm32c0xx/release_note.html | 353 +- stm32cube/stm32c0xx/soc/stm32c011xx.h | 258 +- stm32cube/stm32c0xx/soc/stm32c031xx.h | 259 +- stm32cube/stm32c0xx/soc/stm32c071xx.h | 7739 +++++++++++++++++ stm32cube/stm32c0xx/soc/stm32c0xx.h | 7 +- stm32cube/stm32c0xx/soc/system_stm32c0xx.c | 28 +- 112 files changed, 25277 insertions(+), 3032 deletions(-) create mode 100644 stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_hcd.h create mode 100644 stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd.h create mode 100644 stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd_ex.h create mode 100644 stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crs.h create mode 100644 stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_usb.h create mode 100644 stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_hcd.c create mode 100644 stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd.c create mode 100644 stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd_ex.c create mode 100644 stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crs.c create mode 100644 stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usb.c create mode 100644 stm32cube/stm32c0xx/soc/stm32c071xx.h diff --git a/stm32cube/stm32c0xx/CMakeLists.txt b/stm32cube/stm32c0xx/CMakeLists.txt index 64c105f94..74dba0ffe 100644 --- a/stm32cube/stm32c0xx/CMakeLists.txt +++ b/stm32cube/stm32c0xx/CMakeLists.txt @@ -1,5 +1,5 @@ # Copyright (c) 2023 Benjamin Björnsson -# Copyright (c) 2023 STMicroelectronics +# Copyright (c) 2020 STMicroelectronics # # SPDX-License-Identifier: Apache-2.0 @@ -18,11 +18,14 @@ zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_EXTI drivers/src/stm32c0xx_hal zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_FLASH drivers/src/stm32c0xx_hal_flash.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_FLASH_EX drivers/src/stm32c0xx_hal_flash_ex.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_GPIO drivers/src/stm32c0xx_hal_gpio.c) +zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_HCD drivers/src/stm32c0xx_hal_hcd.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_I2C drivers/src/stm32c0xx_hal_i2c.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_I2C_EX drivers/src/stm32c0xx_hal_i2c_ex.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_I2S drivers/src/stm32c0xx_hal_i2s.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_IRDA drivers/src/stm32c0xx_hal_irda.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_IWDG drivers/src/stm32c0xx_hal_iwdg.c) +zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_PCD drivers/src/stm32c0xx_hal_pcd.c) +zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_PCD_EX drivers/src/stm32c0xx_hal_pcd_ex.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_PWR drivers/src/stm32c0xx_hal_pwr.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_PWR_EX drivers/src/stm32c0xx_hal_pwr_ex.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_RTC drivers/src/stm32c0xx_hal_rtc.c) @@ -42,6 +45,7 @@ zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_USART_EX drivers/src/stm32c0xx zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_WWDG drivers/src/stm32c0xx_hal_wwdg.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_ADC drivers/src/stm32c0xx_ll_adc.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_CRC drivers/src/stm32c0xx_ll_crc.c) +zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_CRS drivers/src/stm32c0xx_ll_crs.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_DMA drivers/src/stm32c0xx_ll_dma.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_EXTI drivers/src/stm32c0xx_ll_exti.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_GPIO drivers/src/stm32c0xx_ll_gpio.c) @@ -52,4 +56,5 @@ zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_RTC drivers/src/stm32c0xx_ll_rt zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_SPI drivers/src/stm32c0xx_ll_spi.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_TIM drivers/src/stm32c0xx_ll_tim.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_USART drivers/src/stm32c0xx_ll_usart.c) +zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_USB drivers/src/stm32c0xx_ll_usb.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_LL_UTILS drivers/src/stm32c0xx_ll_utils.c) diff --git a/stm32cube/stm32c0xx/README b/stm32cube/stm32c0xx/README index ac8c5ba54..4d75fc955 100644 --- a/stm32cube/stm32c0xx/README +++ b/stm32cube/stm32c0xx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubec0.html Status: - version v1.1.0 + version v1.2.0 Purpose: ST Microelectronics official MCU package for STM32C0 series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeC0 Commit: - 8731fa98190b337c01e2a4c3d3a725fe6bf3c04a + 291f417c07b8e6f997a555b4abafa861551d22e3 Maintained-by: External @@ -40,10 +40,6 @@ Patch List: -Added stm32cube/stm32c0xx/drivers/include/stm32_assert.h -Removed unused stm32cube/stm32c0xx/drivers/include/stm32_assert_template.h - *Renamed LL_RCC_HCLK_DIV_X to LL_RCC_SYSCLK_DIV_X - Impacted files drivers/include/stm32c0xx_ll_rcc.h - Internal reference 157185. - *Fix to remove PAGESIZE definition which conflicts with POSIX Impacted files: drivers/include/Legacy/stm32_hal_legacy.h diff --git a/stm32cube/stm32c0xx/drivers/include/Legacy/stm32_hal_legacy.h b/stm32cube/stm32c0xx/drivers/include/Legacy/stm32_hal_legacy.h index 104ddd813..3069dae41 100644 --- a/stm32cube/stm32c0xx/drivers/include/Legacy/stm32_hal_legacy.h +++ b/stm32cube/stm32c0xx/drivers/include/Legacy/stm32_hal_legacy.h @@ -548,6 +548,16 @@ extern "C" { #define OB_SRAM134_RST_ERASE OB_SRAM_RST_ERASE #define OB_SRAM134_RST_NOT_ERASE OB_SRAM_RST_NOT_ERASE #endif /* STM32U5 */ +#if defined(STM32U0) +#define OB_USER_nRST_STOP OB_USER_NRST_STOP +#define OB_USER_nRST_STDBY OB_USER_NRST_STDBY +#define OB_USER_nRST_SHDW OB_USER_NRST_SHDW +#define OB_USER_nBOOT_SEL OB_USER_NBOOT_SEL +#define OB_USER_nBOOT0 OB_USER_NBOOT0 +#define OB_USER_nBOOT1 OB_USER_NBOOT1 +#define OB_nBOOT0_RESET OB_NBOOT0_RESET +#define OB_nBOOT0_SET OB_NBOOT0_SET +#endif /* STM32U0 */ /** * @} @@ -796,6 +806,21 @@ extern "C" { #define GPIO_AF0_S2DSTOP GPIO_AF0_SRDSTOP #define GPIO_AF11_LPGPIO GPIO_AF11_LPGPIO1 #endif /* STM32U5 */ + +#if defined(STM32WBA) +#define GPIO_AF11_RF_ANTSW0 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW1 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO1 GPIO_AF11_RF +#define GPIO_AF11_RF_IO2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO3 GPIO_AF11_RF +#define GPIO_AF11_RF_IO4 GPIO_AF11_RF +#define GPIO_AF11_RF_IO5 GPIO_AF11_RF +#define GPIO_AF11_RF_IO6 GPIO_AF11_RF +#define GPIO_AF11_RF_IO7 GPIO_AF11_RF +#define GPIO_AF11_RF_IO8 GPIO_AF11_RF +#define GPIO_AF11_RF_IO9 GPIO_AF11_RF +#endif /* STM32WBA */ /** * @} */ @@ -1239,10 +1264,10 @@ extern "C" { #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 -#if defined(STM32H5) +#if defined(STM32H5) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_BKP_SRAM TAMP_DEVICESECRETS_ERASE_BKPSRAM -#endif /* STM32H5 */ +#endif /* STM32H5 || STM32H7RS */ #if defined(STM32WBA) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE @@ -1254,10 +1279,10 @@ extern "C" { #define TAMP_SECRETDEVICE_ERASE_ALL TAMP_DEVICESECRETS_ERASE_ALL #endif /* STM32WBA */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_DISABLE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_ENABLE TAMP_SECRETDEVICE_ERASE_ALL -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ #if defined(STM32F7) #define RTC_TAMPCR_TAMPXE RTC_TAMPER_ENABLE_BITS_MASK @@ -1595,6 +1620,8 @@ extern "C" { #define ETH_MAC_SMALL_FIFO_RW_ACTIVE 0x00000006U /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE 0x00000001U /* MAC MII receive protocol engine active */ +#define ETH_TxPacketConfig ETH_TxPacketConfigTypeDef /* Transmit Packet Configuration structure definition */ + /** * @} */ @@ -1805,7 +1832,7 @@ extern "C" { #define HAL_FMPI2CEx_AnalogFilter_Config HAL_FMPI2CEx_ConfigAnalogFilter #define HAL_FMPI2CEx_DigitalFilter_Config HAL_FMPI2CEx_ConfigDigitalFilter -#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) ((cmd == ENABLE)? \ +#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd) == ENABLE)? \ HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): \ HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) @@ -1987,12 +2014,12 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Functions HAL RTC Aliased Functions maintained for legacy purpose * @{ */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define HAL_RTCEx_SetBoothardwareKey HAL_RTCEx_LockBootHardwareKey #define HAL_RTCEx_BKUPBlock_Enable HAL_RTCEx_BKUPBlock #define HAL_RTCEx_BKUPBlock_Disable HAL_RTCEx_BKUPUnblock #define HAL_RTCEx_Erase_SecretDev_Conf HAL_RTCEx_ConfigEraseDeviceSecrets -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ /** * @} @@ -2307,8 +2334,8 @@ extern "C" { #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F302xE) || defined(STM32F302xC) +#endif +#if defined(STM32F302xE) || defined(STM32F302xC) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_ENABLE_RISING_EDGE() : \ @@ -2341,8 +2368,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) +#endif +#if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP3) ? __HAL_COMP_COMP3_EXTI_ENABLE_RISING_EDGE() : \ @@ -2399,8 +2426,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP5) ? __HAL_COMP_COMP5_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP6) ? __HAL_COMP_COMP6_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP7_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F373xC) ||defined(STM32F378xx) +#endif +#if defined(STM32F373xC) ||defined(STM32F378xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE() : \ @@ -2417,7 +2444,7 @@ extern "C" { __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) -# endif +#endif #else #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) @@ -2719,6 +2746,12 @@ extern "C" { #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET +#if defined(STM32C0) +#define __HAL_RCC_APB1_FORCE_RESET __HAL_RCC_APB1_GRP1_FORCE_RESET +#define __HAL_RCC_APB1_RELEASE_RESET __HAL_RCC_APB1_GRP1_RELEASE_RESET +#define __HAL_RCC_APB2_FORCE_RESET __HAL_RCC_APB1_GRP2_FORCE_RESET +#define __HAL_RCC_APB2_RELEASE_RESET __HAL_RCC_APB1_GRP2_RELEASE_RESET +#endif /* STM32C0 */ #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET @@ -3642,8 +3675,12 @@ extern "C" { #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 +#if defined(STM32U0) +#define RCC_SYSCLKSOURCE_STATUS_PLLR RCC_SYSCLKSOURCE_STATUS_PLLCLK +#endif + #if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) || \ - defined(STM32WL) || defined(STM32C0) + defined(STM32WL) || defined(STM32C0) || defined(STM32U0) #define RCC_RTCCLKSOURCE_NO_CLK RCC_RTCCLKSOURCE_NONE #else #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK @@ -3745,8 +3782,10 @@ extern "C" { #define __HAL_RCC_GET_DFSDM_SOURCE __HAL_RCC_GET_DFSDM1_SOURCE #define RCC_DFSDM1CLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 #define RCC_SWPMI1CLKSOURCE_PCLK RCC_SWPMI1CLKSOURCE_PCLK1 +#if !defined(STM32U0) #define RCC_LPTIM1CLKSOURCE_PCLK RCC_LPTIM1CLKSOURCE_PCLK1 #define RCC_LPTIM2CLKSOURCE_PCLK RCC_LPTIM2CLKSOURCE_PCLK1 +#endif #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM1AUDIOCLKSOURCE_I2S1 #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM1AUDIOCLKSOURCE_I2S2 @@ -3892,7 +3931,7 @@ extern "C" { */ #if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || \ defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || \ - defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) + defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) #else #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #endif @@ -4215,6 +4254,9 @@ extern "C" { #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_BREAKINPUTSOURCE_DFSDM TIM_BREAKINPUTSOURCE_DFSDM1 + +#define TIM_OCMODE_ASSYMETRIC_PWM1 TIM_OCMODE_ASYMMETRIC_PWM1 +#define TIM_OCMODE_ASSYMETRIC_PWM2 TIM_OCMODE_ASYMMETRIC_PWM2 /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal.h index 4da66cb54..5959f02cf 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal.h @@ -95,6 +95,21 @@ typedef enum #define HAL_BIND_WLCSP14_PING1_PA12 LL_PINMUX_WLCSP14_PING1_PA12 /*!< STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA12 */ #define HAL_BIND_WLCSP14_PINJ3_PA3 LL_PINMUX_WLCSP14_PINJ3_PA3 /*!< STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA3 */ #define HAL_BIND_WLCSP14_PINJ3_PA4 LL_PINMUX_WLCSP14_PINJ3_PA4 /*!< STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA4 */ +#elif (DEV_ID == 0x493UL) +#define HAL_BIND_WLCSP19_PINH3_PF2 LL_PINMUX_WLCSP19_PINH3_PF2 /*!< STM32C071 WLCSP19 package, PinH3 assigned to GPIO PF2 */ +#define HAL_BIND_WLCSP19_PINH3_PA0 LL_PINMUX_WLCSP19_PINH3_PA0 /*!< STM32C071 WLCSP19 package, PinH3 assigned to GPIO PA0 */ +#define HAL_BIND_WLCSP19_PINB1_PA14 LL_PINMUX_WLCSP19_PINB1_PA14 /*!< STM32C071 WLCSP19 package, PinB1 assigned to GPIO PA14 */ +#define HAL_BIND_WLCSP19_PINB1_PA15 LL_PINMUX_WLCSP19_PINB1_PA15 /*!< STM32C071 WLCSP19 package, PinB1 assigned to GPIO PA15 */ +#define HAL_BIND_TSSOP20_PIN19_PA14 LL_PINMUX_TSSOP20_PIN19_PA14 +#define HAL_BIND_TSSOP20_PIN19_PA15 LL_PINMUX_TSSOP20_PIN19_PA15 +#define HAL_BIND_TSSOP20_PIN20_PB6 LL_PINMUX_TSSOP20_PIN20_PB6 /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB6 */ +#define HAL_BIND_TSSOP20_PIN20_PB3 LL_PINMUX_TSSOP20_PIN20_PB3 /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB3 */ +#define HAL_BIND_TSSOP20_PIN20_PB4 LL_PINMUX_TSSOP20_PIN20_PB4 /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB4 */ +#define HAL_BIND_TSSOP20_PIN20_PB5 LL_PINMUX_TSSOP20_PIN20_PB5 /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB5 */ +#define HAL_BIND_WLCSP19_PINB3_PB LL_PINMUX_WLCSP19_PINB3_PB7 /*!< STM32C071 WLCSP19 package, PinH2 assigned to GPIO PB7 */ +#define HAL_BIND_WLCSP19_PINB3_PB8 LL_PINMUX_WLCSP19_PINB3_PB8 /*!< STM32C071 WLCSP19 package, PinH2 assigned to GPIO PB8 */ +#define HAL_BIND_TSSOP20_PIN1_PB7 LL_PINMUX_TSSOP20_PIN1_PB7 /*!< STM32C071 TSSOP20 package, Pin1 assigned to GPIO PB7 */ +#define HAL_BIND_TSSOP20_PIN1_PB8 LL_PINMUX_TSSOP20_PIN1_PB8 /*!< STM32C071 TSSOP20 package, Pin1 assigned to GPIO PB8 */ #endif /* DEV_ID == 0x443UL */ /** @@ -110,7 +125,7 @@ typedef enum #define HAL_BIND_SO8_PIN5 LL_PINMUX_SO8_PIN5 /*!< STM32C011 SO8 package, GPIO Pin5 multiplexer */ #define HAL_BIND_SO8_PIN8 LL_PINMUX_SO8_PIN8 /*!< STM32C011 SO8 package, GPIO Pin8 multiplexer */ #define HAL_BIND_WLCSP12_PINE2 LL_PINMUX_WLCSP12_PINE2 /*!< STM32C011 WLCSP12 package, GPIO PinE2 multiplexer */ -#define HAL_BIND_WLCSP12_PINF1 LL_PINMUX_WLCSP12_PINF1 /*!< STM32C011 WLCSP12 package, GPIO PinF1 multiplexer*/ +#define HAL_BIND_WLCSP12_PINF1 LL_PINMUX_WLCSP12_PINF1 /*!< STM32C011 WLCSP12 package, GPIO PinF1 multiplexer */ #elif (DEV_ID == 0x453UL) #define HAL_BIND_WLCSP14_PINF2 LL_PINMUX_WLCSP14_PINF2 /*!< STM32C031 WLCSP14 package, GPIO PinF2 multiplexer */ #define HAL_BIND_WLCSP14_PING3 LL_PINMUX_WLCSP14_PING3 /*!< STM32C031 WLCSP14 package, GPIO PinG3 multiplexer */ @@ -118,11 +133,17 @@ typedef enum #define HAL_BIND_WLCSP14_PINH2 LL_PINMUX_WLCSP14_PINH2 /*!< STM32C031 WLCSP14 package, GPIO PinH2 multiplexer */ #define HAL_BIND_WLCSP14_PING1 LL_PINMUX_WLCSP14_PING1 /*!< STM32C031 WLCSP14 package, GPIO PinG1 multiplexer */ #define HAL_BIND_WLCSP14_PINJ3 LL_PINMUX_WLCSP14_PINJ3 /*!< STM32C031 WLCSP14 package, GPIO PinJ3 multiplexer */ +#elif (DEV_ID == 0x493UL) +#define HAL_BIND_WLCSP19_PINH3 LL_PINMUX_WLCSP19_PINH3 /*!< STM32C071 WLCSP19 package, GPIO PinH3 multiplexer */ +#define HAL_BIND_WLCSP19_PINB1 LL_PINMUX_WLCSP19_PINB1 /*!< STM32C071 WLCSP19 package, GPIO PinB1 multiplexer */ +#define HAL_BIND_TSSOP20_PIN19 LL_PINMUX_TSSOP20_PIN19 /*!< STM32C071 TSSOP20 package, GPIO Pin19 multiplexer */ +#define HAL_BIND_TSSOP20_PIN20 LL_PINMUX_TSSOP20_PIN20 /*!< STM32C071 TSSOP20 package, GPIO Pin20 multiplexer */ +#define HAL_BIND_WLCSP19_PINB3 LL_PINMUX_WLCSP19_PINB3 /*!< STM32C071 WLCSP19 package, GPIO PinB3 multiplexer */ +#define HAL_BIND_TSSOP20_PIN1 LL_PINMUX_TSSOP20_PIN1 /*!< STM32C071 TSSOP20 package, GPIO Pin1 multiplexer */ #endif /* DEV_ID == 0x443UL */ - /** +/** * @} - */ - + */ /** * @} @@ -204,7 +225,9 @@ typedef enum /** @brief Fast mode Plus driving capability on a specific GPIO */ #define SYSCFG_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C1_FMP /*!< Enable Fast mode Plus on I2C1 */ - +#if defined(I2C2) +#define SYSCFG_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C2_FMP /*!< Enable Fast mode Plus on I2C2 */ +#endif /* I2C2 */ /** * @} */ @@ -220,18 +243,30 @@ typedef enum #define HAL_SYSCFG_ITLINE5 0x00000005U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE6 0x00000006U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE7 0x00000007U /*!< Internal define for macro handling */ +#if defined(USB) +#define HAL_SYSCFG_ITLINE8 0x00000008U /*!< Internal define for macro handling */ +#endif /* USB */ #define HAL_SYSCFG_ITLINE9 0x00000009U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE10 0x0000000AU /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE11 0x0000000BU /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE12 0x0000000CU /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE13 0x0000000DU /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE14 0x0000000EU /*!< Internal define for macro handling */ +#if defined(TIM2) +#define HAL_SYSCFG_ITLINE15 0x0000000FU /*!< Internal define for macro handling */ +#endif /* TIM2 */ #define HAL_SYSCFG_ITLINE16 0x00000010U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE19 0x00000013U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE21 0x00000015U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE22 0x00000016U /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE23 0x00000017U /*!< Internal define for macro handling */ +#if defined(I2C2) +#define HAL_SYSCFG_ITLINE24 0x00000018U /*!< Internal define for macro handling */ +#endif /* I2C2 */ #define HAL_SYSCFG_ITLINE25 0x00000019U /*!< Internal define for macro handling */ +#if defined(SPI2) +#define HAL_SYSCFG_ITLINE26 0x0000001AU /*!< Internal define for macro handling */ +#endif /* SPI2 */ #define HAL_SYSCFG_ITLINE27 0x0000001BU /*!< Internal define for macro handling */ #define HAL_SYSCFG_ITLINE28 0x0000001CU /*!< Internal define for macro handling */ @@ -239,6 +274,9 @@ typedef enum #define HAL_ITLINE_RTC ((HAL_SYSCFG_ITLINE2 << 0x18U) | SYSCFG_ITLINE2_SR_RTC) /*!< RTC Interrupt */ #define HAL_ITLINE_FLASH_ITF ((HAL_SYSCFG_ITLINE3 << 0x18U) | SYSCFG_ITLINE3_SR_FLASH_ITF) /*!< Flash ITF Interrupt */ #define HAL_ITLINE_CLK_CTRL ((HAL_SYSCFG_ITLINE4 << 0x18U) | SYSCFG_ITLINE4_SR_CLK_CTRL) /*!< CLK Control Interrupt */ +#if defined(CRS) +#define HAL_ITLINE_CRS ((HAL_SYSCFG_ITLINE4 << 0x18U) | SYSCFG_ITLINE4_SR_CRS) /*!< CRS Interrupt */ +#endif /* CRS */ #define HAL_ITLINE_EXTI0 ((HAL_SYSCFG_ITLINE5 << 0x18U) | SYSCFG_ITLINE5_SR_EXTI0) /*!< External Interrupt 0 */ #define HAL_ITLINE_EXTI1 ((HAL_SYSCFG_ITLINE5 << 0x18U) | SYSCFG_ITLINE5_SR_EXTI1) /*!< External Interrupt 1 */ #define HAL_ITLINE_EXTI2 ((HAL_SYSCFG_ITLINE6 << 0x18U) | SYSCFG_ITLINE6_SR_EXTI2) /*!< External Interrupt 2 */ @@ -255,21 +293,40 @@ typedef enum #define HAL_ITLINE_EXTI13 ((HAL_SYSCFG_ITLINE7 << 0x18U) | SYSCFG_ITLINE7_SR_EXTI13) /*!< EXTI13 Interrupt */ #define HAL_ITLINE_EXTI14 ((HAL_SYSCFG_ITLINE7 << 0x18U) | SYSCFG_ITLINE7_SR_EXTI14) /*!< EXTI14 Interrupt */ #define HAL_ITLINE_EXTI15 ((HAL_SYSCFG_ITLINE7 << 0x18U) | SYSCFG_ITLINE7_SR_EXTI15) /*!< EXTI15 Interrupt */ +#if defined(USB) +#define HAL_ITLINE_USB ((HAL_SYSCFG_ITLINE8 << 0x18U) | SYSCFG_ITLINE8_SR_USB) /*!< USB Interrupt */ +#endif /* USB */ #define HAL_ITLINE_DMA1_CH1 ((HAL_SYSCFG_ITLINE9 << 0x18U) | SYSCFG_ITLINE9_SR_DMA1_CH1) /*!< DMA1 Channel 1 Interrupt */ #define HAL_ITLINE_DMA1_CH2 ((HAL_SYSCFG_ITLINE10 << 0x18U) | SYSCFG_ITLINE10_SR_DMA1_CH2) /*!< DMA1 Channel 2 Interrupt */ #define HAL_ITLINE_DMA1_CH3 ((HAL_SYSCFG_ITLINE10 << 0x18U) | SYSCFG_ITLINE10_SR_DMA1_CH3) /*!< DMA1 Channel 3 Interrupt */ #define HAL_ITLINE_DMAMUX ((HAL_SYSCFG_ITLINE11 << 0x18U) | SYSCFG_ITLINE11_SR_DMAMUX) /*!< DMAMUX Interrupt */ +#if defined(SYSCFG_ITLINE11_SR_DMA1_CH4) +#define HAL_ITLINE_DMA1_CH4 ((HAL_SYSCFG_ITLINE11 << 0x18U) | SYSCFG_ITLINE11_SR_DMA1_CH4) /*!< DMA1 Channel 4 Interrupt */ +#endif /* SYSCFG_ITLINE11_SR_DMA1_CH4 */ +#if defined(SYSCFG_ITLINE11_SR_DMA1_CH5) +#define HAL_ITLINE_DMA1_CH5 ((HAL_SYSCFG_ITLINE11 << 0x18U) | SYSCFG_ITLINE11_SR_DMA1_CH5) /*!< DMA1 Channel 5 Interrupt */ +#endif /* SYSCFG_ITLINE11_SR_DMA1_CH5 */ #define HAL_ITLINE_ADC ((HAL_SYSCFG_ITLINE12 << 0x18U) | SYSCFG_ITLINE12_SR_ADC) /*!< ADC Interrupt */ #define HAL_ITLINE_TIM1_BRK ((HAL_SYSCFG_ITLINE13 << 0x18U) | SYSCFG_ITLINE13_SR_TIM1_BRK) /*!< TIM1 BRK Interrupt */ #define HAL_ITLINE_TIM1_UPD ((HAL_SYSCFG_ITLINE13 << 0x18U) | SYSCFG_ITLINE13_SR_TIM1_UPD) /*!< TIM1 UPD Interrupt */ #define HAL_ITLINE_TIM1_TRG ((HAL_SYSCFG_ITLINE13 << 0x18U) | SYSCFG_ITLINE13_SR_TIM1_TRG) /*!< TIM1 TRG Interrupt */ #define HAL_ITLINE_TIM1_CCU ((HAL_SYSCFG_ITLINE13 << 0x18U) | SYSCFG_ITLINE13_SR_TIM1_CCU) /*!< TIM1 CCU Interrupt */ +#define HAL_ITLINE_TIM1_CC ((HAL_SYSCFG_ITLINE14 << 0x18U) | SYSCFG_ITLINE14_SR_TIM1_CC) /*!< TIM1 CC Interrupt */ +#if defined(TIM2) +#define HAL_ITLINE_TIM2 ((HAL_SYSCFG_ITLINE15 << 0x18U) | SYSCFG_ITLINE15_SR_TIM2) /*!< TIM2 Interrupt */ +#endif /* TIM2 */ #define HAL_ITLINE_TIM3 ((HAL_SYSCFG_ITLINE16 << 0x18U) | SYSCFG_ITLINE16_SR_TIM3_GLB) /*!< TIM3 Interrupt */ #define HAL_ITLINE_TIM14 ((HAL_SYSCFG_ITLINE19 << 0x18U) | SYSCFG_ITLINE19_SR_TIM14_GLB) /*!< TIM14 Interrupt */ #define HAL_ITLINE_TIM16 ((HAL_SYSCFG_ITLINE21 << 0x18U) | SYSCFG_ITLINE21_SR_TIM16_GLB) /*!< TIM16 Interrupt */ #define HAL_ITLINE_TIM17 ((HAL_SYSCFG_ITLINE22 << 0x18U) | SYSCFG_ITLINE22_SR_TIM17_GLB) /*!< TIM17 Interrupt */ #define HAL_ITLINE_I2C1 ((HAL_SYSCFG_ITLINE23 << 0x18U) | SYSCFG_ITLINE23_SR_I2C1_GLB) /*!< I2C1 Interrupt */ +#if defined(I2C2) +#define HAL_ITLINE_I2C2 ((HAL_SYSCFG_ITLINE24 << 0x18U) | SYSCFG_ITLINE24_SR_I2C2_GLB) /*!< I2C1 Interrupt */ +#endif /* I2C2 */ #define HAL_ITLINE_SPI1 ((HAL_SYSCFG_ITLINE25 << 0x18U) | SYSCFG_ITLINE25_SR_SPI1) /*!< SPI1 Interrupt */ +#if defined(SPI2) +#define HAL_ITLINE_SPI2 ((HAL_SYSCFG_ITLINE26 << 0x18U) | SYSCFG_ITLINE25_SR_SPI2) /*!< SPI1 Interrupt */ +#endif /* SPI2 */ #define HAL_ITLINE_USART1 ((HAL_SYSCFG_ITLINE27 << 0x18U) | SYSCFG_ITLINE27_SR_USART1_GLB) /*!< USART1 GLB Interrupt */ #define HAL_ITLINE_USART2 ((HAL_SYSCFG_ITLINE28 << 0x18U) | SYSCFG_ITLINE28_SR_USART2_GLB) /*!< USART2 GLB Interrupt */ @@ -293,50 +350,55 @@ typedef enum /** @brief Freeze and Unfreeze Peripherals in Debug mode */ +#if defined(DBG_APB_FZ1_DBG_TIM2_STOP) +#define __HAL_DBGMCU_FREEZE_TIM2() SET_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_TIM2_STOP) +#define __HAL_DBGMCU_UNFREEZE_TIM2() CLEAR_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_TIM2_STOP) +#endif /* DBG_APB_FZ1_DBG_TIM2_STOP */ + #if defined(DBG_APB_FZ1_DBG_TIM3_STOP) #define __HAL_DBGMCU_FREEZE_TIM3() SET_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_TIM3_STOP) #define __HAL_DBGMCU_UNFREEZE_TIM3() CLEAR_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_TIM3_STOP) -#endif +#endif /* DBG_APB_FZ1_DBG_TIM3_STOP */ #if defined(DBG_APB_FZ1_DBG_RTC_STOP) #define __HAL_DBGMCU_FREEZE_RTC() SET_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_RTC_STOP) #define __HAL_DBGMCU_UNFREEZE_RTC() CLEAR_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_RTC_STOP) -#endif +#endif /* DBG_APB_FZ1_DBG_RTC_STOP */ #if defined(DBG_APB_FZ1_DBG_WWDG_STOP) #define __HAL_DBGMCU_FREEZE_WWDG() SET_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_WWDG_STOP) #define __HAL_DBGMCU_UNFREEZE_WWDG() CLEAR_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_WWDG_STOP) -#endif +#endif /* DBG_APB_FZ1_DBG_RTC_STOP */ #if defined(DBG_APB_FZ1_DBG_IWDG_STOP) #define __HAL_DBGMCU_FREEZE_IWDG() SET_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_IWDG_STOP) #define __HAL_DBGMCU_UNFREEZE_IWDG() CLEAR_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_IWDG_STOP) -#endif +#endif /* DBG_APB_FZ1_DBG_IWDG_STOP */ #if defined(DBG_APB_FZ1_DBG_I2C1_SMBUS_TIMEOUT_STOP) #define __HAL_DBGMCU_FREEZE_I2C1_TIMEOUT() SET_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_I2C1_SMBUS_TIMEOUT_STOP) #define __HAL_DBGMCU_UNFREEZE_I2C1_TIMEOUT() CLEAR_BIT(DBG->APBFZ1, DBG_APB_FZ1_DBG_I2C1_SMBUS_TIMEOUT_STOP) -#endif +#endif /* DBG_APB_FZ1_DBG_I2C1_SMBUS_TIMEOUT_STOP */ #if defined(DBG_APB_FZ2_DBG_TIM1_STOP) #define __HAL_DBGMCU_FREEZE_TIM1() SET_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM1_STOP) #define __HAL_DBGMCU_UNFREEZE_TIM1() CLEAR_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM1_STOP) -#endif +#endif /* DBG_APB_FZ2_DBG_TIM1_STOP */ #if defined(DBG_APB_FZ2_DBG_TIM14_STOP) #define __HAL_DBGMCU_FREEZE_TIM14() SET_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM14_STOP) #define __HAL_DBGMCU_UNFREEZE_TIM14() CLEAR_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM14_STOP) -#endif +#endif /* DBG_APB_FZ2_DBG_TIM14_STOP */ #if defined(DBG_APB_FZ2_DBG_TIM16_STOP) #define __HAL_DBGMCU_FREEZE_TIM16() SET_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM16_STOP) #define __HAL_DBGMCU_UNFREEZE_TIM16() CLEAR_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM16_STOP) -#endif +#endif /* DBG_APB_FZ2_DBG_TIM16_STOP */ #if defined(DBG_APB_FZ2_DBG_TIM17_STOP) #define __HAL_DBGMCU_FREEZE_TIM17() SET_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM17_STOP) #define __HAL_DBGMCU_UNFREEZE_TIM17() CLEAR_BIT(DBG->APBFZ2, DBG_APB_FZ2_DBG_TIM17_STOP) -#endif +#endif /* DBG_APB_FZ2_DBG_TIM17_STOP */ /** * @} @@ -363,7 +425,7 @@ typedef enum /** @brief Embedded SRAM mapped at 0x00000000 */ #define __HAL_SYSCFG_REMAPMEMORY_SRAM() \ - MODIFY_REG(SYSCFG->CFGR1, SYSCFG_CFGR1_MEM_MODE, (SYSCFG_CFGR1_MEM_MODE_1|SYSCFG_CFGR1_MEM_MODE_0)) + MODIFY_REG(SYSCFG->CFGR1, SYSCFG_CFGR1_MEM_MODE, (SYSCFG_CFGR1_MEM_MODE_1 | SYSCFG_CFGR1_MEM_MODE_0)) /** * @brief Return the boot mode as configured by user. @@ -381,13 +443,17 @@ typedef enum /** @brief Fast-mode Plus driving capability enable/disable macros * @param __FASTMODEPLUS__ This parameter can be a value of @ref SYSCFG_FastModePlus_GPIO */ -#define __HAL_SYSCFG_FASTMODEPLUS_ENABLE(__FASTMODEPLUS__) do {assert_param(IS_SYSCFG_FASTMODEPLUS((__FASTMODEPLUS__)));\ - SET_BIT(SYSCFG->CFGR1, (__FASTMODEPLUS__));\ - }while(0U) +#define __HAL_SYSCFG_FASTMODEPLUS_ENABLE(__FASTMODEPLUS__) \ + do { \ + assert_param(IS_SYSCFG_FASTMODEPLUS((__FASTMODEPLUS__)));\ + SET_BIT(SYSCFG->CFGR1, (__FASTMODEPLUS__));\ + }while(0U) -#define __HAL_SYSCFG_FASTMODEPLUS_DISABLE(__FASTMODEPLUS__) do {assert_param(IS_SYSCFG_FASTMODEPLUS((__FASTMODEPLUS__)));\ - CLEAR_BIT(SYSCFG->CFGR1, (__FASTMODEPLUS__));\ - }while(0U) +#define __HAL_SYSCFG_FASTMODEPLUS_DISABLE(__FASTMODEPLUS__) \ + do { \ + assert_param(IS_SYSCFG_FASTMODEPLUS((__FASTMODEPLUS__)));\ + CLEAR_BIT(SYSCFG->CFGR1, (__FASTMODEPLUS__));\ + }while(0U) /** @brief selection of the modulation envelope signal macro, using bits [7:6] of SYSCFG_CFGR1 register @@ -486,7 +552,18 @@ typedef enum ((PIN) == HAL_BIND_WLCSP14_PING1_PA12)|| \ ((PIN) == HAL_BIND_WLCSP14_PINJ3_PA3) || \ ((PIN) == HAL_BIND_WLCSP14_PINJ3_PA4)) -#endif +#elif (DEV_ID == 0x493UL) +#define IS_HAL_SYSCFG_PINBINDING(PIN) (((PIN) == LL_PINMUX_WLCSP19_PINH3_PF2) || \ + ((PIN) == LL_PINMUX_WLCSP19_PINH3_PA0) || \ + ((PIN) == LL_PINMUX_WLCSP19_PINB1_PA14) || \ + ((PIN) == LL_PINMUX_WLCSP19_PINB1_PA15) || \ + ((PIN) == LL_PINMUX_TSSOP20_PIN20_PB6) || \ + ((PIN) == LL_PINMUX_TSSOP20_PIN20_PB3) || \ + ((PIN) == LL_PINMUX_TSSOP20_PIN20_PB4) || \ + ((PIN) == LL_PINMUX_TSSOP20_PIN20_PB5) || \ + ((PIN) == LL_PINMUX_WLCSP19_PINB3_PB7) || \ + ((PIN) == LL_PINMUX_WLCSP19_PINB3_PB8)) +#endif /* DEV_ID == 0x443UL | DEV_ID == 0x453UL | DEV_ID == 0x493UL */ /** * @} */ @@ -575,9 +652,6 @@ extern HAL_TickFreqTypeDef uwTickFreq; */ /* SYSCFG Control functions ****************************************************/ - -void HAL_SYSCFG_EnableIOAnalogSwitchBooster(void); -void HAL_SYSCFG_DisableIOAnalogSwitchBooster(void); void HAL_SYSCFG_EnableRemap(uint32_t PinRemap); void HAL_SYSCFG_DisableRemap(uint32_t PinRemap); void HAL_SYSCFG_SetPinBinding(uint32_t pin_binding); diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_adc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_adc.h index b501f7ec1..ffe4f3679 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_adc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_adc.h @@ -62,27 +62,33 @@ typedef struct /** * @brief Structure definition of ADC instance and ADC group regular. * @note Parameters of this structure are shared within 2 scopes: - * - Scope entire ADC (differentiation done for compatibility with some other STM32 series featuring ADC groups regular and injected): ClockPrescaler, Resolution, DataAlign, + * - Scope entire ADC (differentiation done for compatibility with some other STM32 series featuring ADC + * groups regular and injected): ClockPrescaler, Resolution, DataAlign, * ScanConvMode, EOCSelection, LowPowerAutoWait. * - Scope ADC group regular: ContinuousConvMode, NbrOfConversion, DiscontinuousConvMode, * ExternalTrigConv, ExternalTrigConvEdge, DMAContinuousRequests, Overrun, OversamplingMode, Oversampling. * @note The setting of these parameters by function HAL_ADC_Init() is conditioned to ADC state. * ADC state can be either: * - For all parameters: ADC disabled - * - For all parameters except 'ClockPrescaler' and 'Resolution': ADC enabled without conversion on going on group regular. + * - For all parameters except 'ClockPrescaler' and 'Resolution': ADC enabled without conversion on going on + * group regular. * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed - * without error reporting (as it can be the expected behavior in case of intended action to update another parameter - * (which fulfills the ADC state condition) on the fly). + * without error reporting (as it can be the expected behavior in case of intended action to update another + * parameter (which fulfills the ADC state condition) on the fly). */ typedef struct { - uint32_t ClockPrescaler; /*!< Select ADC clock source (synchronous clock derived from APB clock or asynchronous clock derived from system clock or PLL (Refer to reference manual for list of clocks available)) and clock prescaler. + uint32_t ClockPrescaler; /*!< Select ADC clock source (synchronous clock derived from APB clock or asynchronous + clock derived from system clock or PLL (Refer to reference manual for list of + clocks available)) and clock prescaler. This parameter can be a value of @ref ADC_HAL_EC_COMMON_CLOCK_SOURCE. Note: The ADC clock configuration is common to all ADC instances. - Note: In case of synchronous clock mode based on HCLK/1, the configuration must be enabled only - if the system clock has a 50% duty clock cycle (APB prescaler configured inside RCC - must be bypassed and PCLK clock must have 50% duty cycle). Refer to reference manual for details. - Note: In case of usage of asynchronous clock, the selected clock must be preliminarily enabled at RCC top level. + Note: In case of synchronous clock mode based on HCLK/1, the configuration must + be enabled only if the system clock has a 50% duty clock cycle (APB + prescaler configured inside RCC must be bypassed and PCLK clock must have + 50% duty cycle). Refer to reference manual for details. + Note: In case of usage of asynchronous clock, the selected clock must be + preliminarily enabled at RCC top level. Note: This parameter can be modified only if all ADC instances are disabled. */ uint32_t Resolution; /*!< Configure the ADC resolution. @@ -93,15 +99,16 @@ typedef struct This parameter can be a value of @ref ADC_HAL_EC_DATA_ALIGN */ uint32_t ScanConvMode; /*!< Configure the sequencer of ADC group regular. - On this STM32 series, ADC group regular sequencer both modes "fully configurable" or "not fully configurable" are - available: + On this STM32 series, ADC group regular sequencer both modes "fully configurable" + or "not fully configurable" are available: - sequencer configured to fully configurable: sequencer length and each rank affectation to a channel are configurable. - Sequence length: Set number of ranks in the scan sequence. - Sequence direction: Unless specified in parameters, sequencer scan direction is forward (from rank 1 to rank n). - sequencer configured to not fully configurable: - sequencer length and each rank affectation to a channel are fixed by channel HW number. + sequencer length and each rank affectation to a channel are fixed by channel + HW number. - Sequence length: Number of ranks in the scan sequence is defined by number of channels set in the sequence, rank of each channel is fixed by channel HW number. @@ -109,102 +116,156 @@ typedef struct - Sequence direction: Unless specified in parameters, sequencer scan direction is forward (from lowest channel number to highest channel number). - This parameter can be associated to parameter 'DiscontinuousConvMode' to have main sequence subdivided in successive parts. - Sequencer is automatically enabled if several channels are set (sequencer cannot be disabled, as it can be the case on other STM32 devices): + This parameter can be associated to parameter 'DiscontinuousConvMode' to have + main sequence subdivided in successive parts. Sequencer is automatically enabled + if several channels are set (sequencer cannot be disabled, as it can be the case + on other STM32 devices): If only 1 channel is set: Conversion is performed in single mode. If several channels are set: Conversions are performed in sequence mode. This parameter can be a value of @ref ADC_Scan_mode */ - uint32_t EOCSelection; /*!< Specify which EOC (End Of Conversion) flag is used for conversion by polling and interruption: end of unitary conversion or end of sequence conversions. + uint32_t EOCSelection; /*!< Specify which EOC (End Of Conversion) flag is used for conversion by polling and + interruption: end of unitary conversion or end of sequence conversions. This parameter can be a value of @ref ADC_EOCSelection. */ - FunctionalState LowPowerAutoWait; /*!< Select the dynamic low power Auto Delay: new conversion start only when the previous - conversion (for ADC group regular) has been retrieved by user software, + FunctionalState LowPowerAutoWait; /*!< Select the dynamic low power Auto Delay: new conversion start only when the + previous conversion (for ADC group regular) has been retrieved by user software, using function HAL_ADC_GetValue(). - This feature automatically adapts the frequency of ADC conversions triggers to the speed of the system that reads the data. Moreover, this avoids risk of overrun - for low frequency applications. + This feature automatically adapts the frequency of ADC conversions triggers to + the speed of the system that reads the data. Moreover, this avoids risk of + overrun for low frequency applications. This parameter can be set to ENABLE or DISABLE. - Note: It is not recommended to use with interruption or DMA (HAL_ADC_Start_IT(), HAL_ADC_Start_DMA()) since these modes have to clear immediately the EOC flag (by CPU to free the IRQ pending event or by DMA). - Auto wait will work but fort a very short time, discarding its intended benefit (except specific case of high load of CPU or DMA transfers which can justify usage of auto wait). - Do use with polling: 1. Start conversion with HAL_ADC_Start(), 2. Later on, when ADC conversion data is needed: - use HAL_ADC_PollForConversion() to ensure that conversion is completed and HAL_ADC_GetValue() to retrieve conversion result and trig another conversion start. */ - - FunctionalState LowPowerAutoPowerOff; /*!< Select the auto-off mode: the ADC automatically powers-off after a conversion and automatically wakes-up when a new conversion is triggered (with startup time between trigger and start of sampling). - This feature can be combined with automatic wait mode (parameter 'LowPowerAutoWait'). - This parameter can be set to ENABLE or DISABLE. - Note: If enabled, this feature also turns off the ADC dedicated 14 MHz RC oscillator (HSI14) */ - - FunctionalState ContinuousConvMode; /*!< Specify whether the conversion is performed in single mode (one conversion) or continuous mode for ADC group regular, - after the first ADC conversion start trigger occurred (software start or external trigger). - This parameter can be set to ENABLE or DISABLE. */ - - uint32_t NbrOfConversion; /*!< Specify the number of ranks that will be converted within the regular group sequencer. + Note: It is not recommended to use with interruption or DMA (HAL_ADC_Start_IT(), + HAL_ADC_Start_DMA()) since these modes have to clear immediately the EOC + flag (by CPU to free the IRQ pending event or by DMA). + Auto wait will work but fort a very short time, discarding its intended + benefit (except specific case of high load of CPU or DMA transfers which + can justify usage of auto wait). + Do use with polling: 1. Start conversion with HAL_ADC_Start(), 2. Later on, + when ADC conversion data is needed: + use HAL_ADC_PollForConversion() to ensure that conversion is completed and + HAL_ADC_GetValue() to retrieve conversion result and trig another + conversion start. */ + + FunctionalState LowPowerAutoPowerOff; /*!< Select the auto-off mode: the ADC automatically powers-off after a + conversion and automatically wakes-up when a new conversion is triggered + (with startup time between trigger and start of sampling). + This feature can be combined with automatic wait mode + (parameter 'LowPowerAutoWait'). + This parameter can be set to ENABLE or DISABLE. */ + + FunctionalState ContinuousConvMode; /*!< Specify whether the conversion is performed in single mode (one conversion) + or continuous mode for ADC group regular, after the first ADC conversion + start trigger occurred (software start or external trigger). This parameter + can be set to ENABLE or DISABLE. */ + + uint32_t NbrOfConversion; /*!< Specify the number of ranks that will be converted within the regular group + sequencer. This parameter is dependent on ScanConvMode: - sequencer configured to fully configurable: Number of ranks in the scan sequence is configurable using this parameter. - Note: After the first call of 'HAL_ADC_Init()', each rank corresponding to parameter "NbrOfConversion" must be set using 'HAL_ADC_ConfigChannel()'. - Afterwards, when all needed sequencer ranks are set, parameter 'NbrOfConversion' can be updated without modifying configuration of sequencer ranks - (sequencer ranks above 'NbrOfConversion' are discarded). + Note: After the first call of 'HAL_ADC_Init()', each rank corresponding to + parameter "NbrOfConversion" must be set using 'HAL_ADC_ConfigChannel()'. + Afterwards, when all needed sequencer ranks are set, parameter + 'NbrOfConversion' can be updated without modifying configuration of + sequencer ranks (sequencer ranks above 'NbrOfConversion' are discarded). - sequencer configured to not fully configurable: - Number of ranks in the scan sequence is defined by number of channels set in the sequence. This parameter is discarded. + Number of ranks in the scan sequence is defined by number of channels set in + the sequence. This parameter is discarded. This parameter must be a number between Min_Data = 1 and Max_Data = 8. - Note: This parameter must be modified when no conversion is on going on regular group (ADC disabled, or ADC enabled without continuous mode or external trigger that could launch a conversion). */ - - FunctionalState DiscontinuousConvMode; /*!< Specify whether the conversions sequence of ADC group regular is performed in Complete-sequence/Discontinuous-sequence - (main sequence subdivided in successive parts). - Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. - Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. - This parameter can be set to ENABLE or DISABLE. - Note: On this STM32 series, ADC group regular number of discontinuous ranks increment is fixed to one-by-one. */ - - uint32_t ExternalTrigConv; /*!< Select the external event source used to trigger ADC group regular conversion start. - If set to ADC_SOFTWARE_START, external triggers are disabled and software trigger is used instead. + Note: This parameter must be modified when no conversion is on going on regular + group (ADC disabled, or ADC enabled without continuous mode or external + trigger that could launch a conversion). */ + + FunctionalState DiscontinuousConvMode; /*!< Specify whether the conversions sequence of ADC group regular is performed + in Complete-sequence/Discontinuous-sequence (main sequence subdivided in + successive parts). + Discontinuous mode is used only if sequencer is enabled (parameter + 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. + Discontinuous mode can be enabled only if continuous mode is disabled. + If continuous mode is enabled, this parameter setting is discarded. + This parameter can be set to ENABLE or DISABLE. + Note: On this STM32 series, ADC group regular number of discontinuous + ranks increment is fixed to one-by-one. */ + + uint32_t ExternalTrigConv; /*!< Select the external event source used to trigger ADC group regular conversion + start. + If set to ADC_SOFTWARE_START, external triggers are disabled and software trigger + is used instead. This parameter can be a value of @ref ADC_regular_external_trigger_source. Caution: external trigger source is common to all ADC instances. */ - uint32_t ExternalTrigConvEdge; /*!< Select the external event edge used to trigger ADC group regular conversion start. + uint32_t ExternalTrigConvEdge; /*!< Select the external event edge used to trigger ADC group regular conversion start If trigger source is set to ADC_SOFTWARE_START, this parameter is discarded. This parameter can be a value of @ref ADC_regular_external_trigger_edge */ - FunctionalState DMAContinuousRequests; /*!< Specify whether the DMA requests are performed in one shot mode (DMA transfer stops when number of conversions is reached) - or in continuous mode (DMA transfer unlimited, whatever number of conversions). - This parameter can be set to ENABLE or DISABLE. - Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached. */ + FunctionalState DMAContinuousRequests; /*!< Specify whether the DMA requests are performed in one shot mode (DMA + transfer stops when number of conversions is reached) or in continuous + mode (DMA transfer unlimited, whatever number of conversions). + This parameter can be set to ENABLE or DISABLE. + Note: In continuous mode, DMA must be configured in circular mode. + Otherwise an overrun will be triggered when DMA buffer maximum + pointer is reached. */ uint32_t Overrun; /*!< Select the behavior in case of overrun: data overwritten or preserved (default). This parameter can be a value of @ref ADC_HAL_EC_REG_OVR_DATA_BEHAVIOR. - Note: In case of overrun set to data preserved and usage with programming model with interruption (HAL_Start_IT()): ADC IRQ handler has to clear - end of conversion flags, this induces the release of the preserved data. If needed, this data can be saved in function - HAL_ADC_ConvCpltCallback(), placed in user program code (called before end of conversion flags clear). + Note: In case of overrun set to data preserved and usage with programming model + with interruption (HAL_Start_IT()): ADC IRQ handler has to clear end of + conversion flags, this induces the release of the preserved data. If + needed, this data can be saved in function HAL_ADC_ConvCpltCallback(), + placed in user program code (called before end of conversion flags clear) Note: Error reporting with respect to the conversion mode: - - Usage with ADC conversion by polling for event or interruption: Error is reported only if overrun is set to data preserved. If overrun is set to data - overwritten, user can willingly not read all the converted data, this is not considered as an erroneous case. - - Usage with ADC conversion by DMA: Error is reported whatever overrun setting (DMA is expected to process all data from data register). */ + - Usage with ADC conversion by polling for event or interruption: Error is + reported only if overrun is set to data preserved. If overrun is set to + data overwritten, user can willingly not read all the converted data, + this is not considered as an erroneous case. + - Usage with ADC conversion by DMA: Error is reported whatever overrun + setting (DMA is expected to process all data from data register). */ uint32_t SamplingTimeCommon1; /*!< Set sampling time common to a group of channels. Unit: ADC clock cycles - Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). - Note: On this STM32 family, two different sampling time settings are available, each channel can use one of these two settings. On some other STM32 devices, this parameter in channel wise and is located into ADC channel initialization structure. + Conversion time is the addition of sampling time and processing time + (12.5 ADC clock cycles at ADC resolution 12 bits, + 10.5 cycles at 10 bits, + 8.5 cycles at 8 bits, + 6.5 cycles at 6 bits). + Note: On this STM32 family, two different sampling time settings are available, + each channel can use one of these two settings. On some other STM32 devices + this parameter in channel wise and is located into ADC channel + initialization structure. This parameter can be a value of @ref ADC_HAL_EC_CHANNEL_SAMPLINGTIME - Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), - sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) - Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: few tens of microseconds). */ + Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor) + sampling time constraints must be respected (sampling time can be adjusted + in function of ADC clock frequency and sampling time setting) + Refer to device datasheet for timings values, parameters TS_vrefint, + TS_vbat, TS_temp (values rough order: few tens of microseconds). */ uint32_t SamplingTimeCommon2; /*!< Set sampling time common to a group of channels, second common setting possible. Unit: ADC clock cycles - Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). - Note: On this STM32 family, two different sampling time settings are available, each channel can use one of these two settings. On some other STM32 devices, this parameter in channel wise and is located into ADC channel initialization structure. + Conversion time is the addition of sampling time and processing time + (12.5 ADC clock cycles at ADC resolution 12 bits, + 10.5 cycles at 10 bits, + 8.5 cycles at 8 bits, + 6.5 cycles at 6 bits). + Note: On this STM32 family, two different sampling time settings are available, + each channel can use one of these two settings. On some other STM32 devices + this parameter in channel wise and is located into ADC channel + initialization structure. This parameter can be a value of @ref ADC_HAL_EC_CHANNEL_SAMPLINGTIME - Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), - sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) - Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: few tens of microseconds). */ + Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor) + sampling time constraints must be respected (sampling time can be adjusted + in function of ADC clock frequency and sampling time setting) + Refer to device datasheet for timings values, parameters TS_vrefint, + TS_vbat, TS_temp (values rough order: few tens of microseconds). */ FunctionalState OversamplingMode; /*!< Specify whether the oversampling feature is enabled or disabled. This parameter can be set to ENABLE or DISABLE. - Note: This parameter can be modified only if there is no conversion is ongoing on ADC group regular. */ + Note: This parameter can be modified only if there is no conversion is + ongoing on ADC group regular. */ ADC_OversamplingTypeDef Oversampling; /*!< Specify the Oversampling parameters. - Caution: this setting overwrites the previous oversampling configuration if oversampling is already enabled. */ + Caution: this setting overwrites the previous oversampling configuration + if oversampling is already enabled. */ uint32_t TriggerFrequencyMode; /*!< Set ADC trigger frequency mode. This parameter can be a value of @ref ADC_HAL_EC_REG_TRIGGER_FREQ. @@ -225,16 +286,19 @@ typedef struct * ADC state can be either: * - For all parameters: ADC disabled or enabled without conversion on going on regular group. * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed - * without error reporting (as it can be the expected behavior in case of intended action to update another parameter (which fulfills the ADC state condition) - * on the fly). + * without error reporting (as it can be the expected behavior in case of intended action to update another + * parameter (which fulfills the ADC state condition) on the fly). */ typedef struct { uint32_t Channel; /*!< Specify the channel to configure into ADC regular group. This parameter can be a value of @ref ADC_HAL_EC_CHANNEL - Note: Depending on devices and ADC instances, some channels may not be available on device package pins. Refer to device datasheet for channels availability. */ + Note: Depending on devices and ADC instances, some channels may not be available + on device package pins. Refer to device datasheet for channels + availability. */ - uint32_t Rank; /*!< Add or remove the channel from ADC regular group sequencer and specify its conversion rank. + uint32_t Rank; /*!< Add or remove the channel from ADC regular group sequencer and specify its + conversion rank. This parameter is dependent on ScanConvMode: - sequencer configured to fully configurable: Channels ordering into each rank of scan sequence: @@ -242,18 +306,26 @@ typedef struct - sequencer configured to not fully configurable: rank of each channel is fixed by channel HW number. (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). - Despite the channel rank is fixed, this parameter allow an additional possibility: to remove the selected rank (selected channel) from sequencer. + Despite the channel rank is fixed, this parameter allow an additional + possibility: to remove the selected rank (selected channel) from sequencer. This parameter can be a value of @ref ADC_HAL_EC_REG_SEQ_RANKS */ uint32_t SamplingTime; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles Conversion time is the addition of sampling time and processing time - (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). + (12.5 ADC clock cycles at ADC resolution 12 bits, + 10.5 cycles at 10 bits, + 8.5 cycles at 8 bits, + 6.5 cycles at 6 bits). This parameter can be a value of @ref ADC_HAL_EC_SAMPLINGTIME_COMMON - Note: On this STM32 family, two different sampling time settings are available (refer to parameters "SamplingTimeCommon1" and "SamplingTimeCommon2"), each channel can use one of these two settings. - - Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), - sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) + Note: On this STM32 family, two different sampling time settings are available + (refer to parameters "SamplingTimeCommon1" and "SamplingTimeCommon2"), + each channel can use one of these two settings. + + Note: In case of usage of internal measurement channels (VrefInt/Vbat/ + TempSensor), sampling time constraints must be respected (sampling time + can be adjusted in function of ADC clock frequency and sampling time + setting) Refer to device datasheet for timings values. */ } ADC_ChannelConfTypeDef; @@ -262,48 +334,62 @@ typedef struct * @brief Structure definition of ADC analog watchdog * @note The setting of these parameters by function HAL_ADC_AnalogWDGConfig() is conditioned to ADC state. * ADC state can be either: - * - For all parameters except 'HighThreshold', 'LowThreshold': ADC disabled or ADC enabled without conversion on going on ADC groups regular. + * - For all parameters except 'HighThreshold', 'LowThreshold': ADC disabled or ADC enabled without conversion + on going on ADC groups regular. * - For parameters 'HighThreshold', 'LowThreshold': ADC enabled with conversion on going on regular. */ typedef struct { uint32_t WatchdogNumber; /*!< Select which ADC analog watchdog is monitoring the selected channel. - For Analog Watchdog 1: Only 1 channel can be monitored (or overall group of channels by setting parameter 'WatchdogMode') - For Analog Watchdog 2 and 3: Several channels can be monitored (by successive calls of 'HAL_ADC_AnalogWDGConfig()' for each channel) + For Analog Watchdog 1: Only 1 channel can be monitored (or overall group of channels + by setting parameter 'WatchdogMode') + For Analog Watchdog 2 and 3: Several channels can be monitored (by successive calls + of 'HAL_ADC_AnalogWDGConfig()' for each channel) This parameter can be a value of @ref ADC_HAL_EC_AWD_NUMBER. */ uint32_t WatchdogMode; /*!< Configure the ADC analog watchdog mode: single/all/none channels. - For Analog Watchdog 1: Configure the ADC analog watchdog mode: single channel or all channels, ADC group regular. - For Analog Watchdog 2 and 3: Several channels can be monitored by applying successively the AWD init structure. + For Analog Watchdog 1: Configure the ADC analog watchdog mode: single channel or all + channels, ADC group regular. + For Analog Watchdog 2 and 3: Several channels can be monitored by applying + successively the AWD init structure. This parameter can be a value of @ref ADC_analog_watchdog_mode. */ uint32_t Channel; /*!< Select which ADC channel to monitor by analog watchdog. - For Analog Watchdog 1: this parameter has an effect only if parameter 'WatchdogMode' is configured on single channel (only 1 channel can be monitored). - For Analog Watchdog 2 and 3: Several channels can be monitored. To use this feature, call successively the function HAL_ADC_AnalogWDGConfig() for each channel to be added (or removed with value 'ADC_ANALOGWATCHDOG_NONE'). + For Analog Watchdog 1: this parameter has an effect only if parameter 'WatchdogMode' + is configured on single channel (only 1 channel can be + monitored). + For Analog Watchdog 2 and 3: Several channels can be monitored. To use this feature, + call successively the function HAL_ADC_AnalogWDGConfig() + for each channel to be added (or removed with value + 'ADC_ANALOGWATCHDOG_NONE'). This parameter can be a value of @ref ADC_HAL_EC_CHANNEL. */ FunctionalState ITMode; /*!< Specify whether the analog watchdog is configured in interrupt or polling mode. This parameter can be set to ENABLE or DISABLE */ uint32_t HighThreshold; /*!< Configure the ADC analog watchdog High threshold value. - Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number - between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. - Note: Analog watchdog 2 and 3 are limited to a resolution of 8 bits: if ADC resolution is 12 bits - the 4 LSB are ignored, if ADC resolution is 10 bits the 2 LSB are ignored. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a + number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F + respectively. + Note: Analog watchdog 2 and 3 are limited to a resolution of 8 bits: if ADC + resolution is 12 bits the 4 LSB are ignored, if ADC resolution is 10 bits the 2 + LSB are ignored. Note: If ADC oversampling is enabled, ADC analog watchdog thresholds are impacted: the comparison of analog watchdog thresholds is done on oversampling final computation (after ratio and shift application): ADC data register bitfield [15:4] (12 most significant bits). */ uint32_t LowThreshold; /*!< Configures the ADC analog watchdog Low threshold value. - Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number - between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. - Note: Analog watchdog 2 and 3 are limited to a resolution of 8 bits: if ADC resolution is 12 bits - the 4 LSB are ignored, if ADC resolution is 10 bits the 2 LSB are ignored. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a + number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F + respectively. + Note: Analog watchdog 2 and 3 are limited to a resolution of 8 bits: if ADC + resolution is 12 bits the 4 LSB are ignored, if ADC resolution is 10 bits the 2 + LSB are ignored. Note: If ADC oversampling is enabled, ADC analog watchdog thresholds are impacted: the comparison of analog watchdog thresholds is done on oversampling final computation (after ratio and shift application): - ADC data register bitfield [15:4] (12 most significant bits). */ + ADC data register bitfield [15:4] (12 most significant bits).*/ } ADC_AnalogWDGConfTypeDef; /** @defgroup ADC_States ADC States @@ -321,7 +407,7 @@ typedef struct /* States of ADC global scope */ #define HAL_ADC_STATE_RESET (0x00000000UL) /*!< ADC not yet initialized or disabled */ #define HAL_ADC_STATE_READY (0x00000001UL) /*!< ADC peripheral ready for use */ -#define HAL_ADC_STATE_BUSY_INTERNAL (0x00000002UL) /*!< ADC is busy due to an internal process (initialization, calibration) */ +#define HAL_ADC_STATE_BUSY_INTERNAL (0x00000002UL) /*!< ADC is busy from internal process (ex : calibration, ...) */ #define HAL_ADC_STATE_TIMEOUT (0x00000004UL) /*!< TimeOut occurrence */ /* States of ADC errors */ @@ -330,25 +416,37 @@ typedef struct #define HAL_ADC_STATE_ERROR_DMA (0x00000040UL) /*!< DMA error occurrence */ /* States of ADC group regular */ -#define HAL_ADC_STATE_REG_BUSY (0x00000100UL) /*!< A conversion on ADC group regular is ongoing or can occur (either by continuous mode, - external trigger, low power auto power-on (if feature available), multimode ADC master control (if feature available)) */ +#define HAL_ADC_STATE_REG_BUSY (0x00000100UL) /*!< A conversion on ADC group regular is ongoing or can occur + (either by continuous mode, external trigger, low power + auto power-on (if feature available), multimode ADC master + control (if feature available)) */ #define HAL_ADC_STATE_REG_EOC (0x00000200UL) /*!< Conversion data available on group regular */ #define HAL_ADC_STATE_REG_OVR (0x00000400UL) /*!< Overrun occurrence */ -#define HAL_ADC_STATE_REG_EOSMP (0x00000800UL) /*!< Not available on this STM32 series: End Of Sampling flag raised */ +#define HAL_ADC_STATE_REG_EOSMP (0x00000800UL) /*!< Not available on this STM32 series: End Of Sampling flag + raised */ /* States of ADC group injected */ -#define HAL_ADC_STATE_INJ_BUSY (0x00001000UL) /*!< Not available on this STM32 series: A conversion on group injected is ongoing or can occur (either by auto-injection mode, - external trigger, low power auto power-on (if feature available), multimode ADC master control (if feature available))*/ -#define HAL_ADC_STATE_INJ_EOC (0x00002000UL) /*!< Not available on this STM32 series: Conversion data available on group injected */ -#define HAL_ADC_STATE_INJ_JQOVF (0x00004000UL) /*!< Not available on this STM32 series: Injected queue overflow occurrence */ +#define HAL_ADC_STATE_INJ_BUSY (0x00001000UL) /*!< Not available on this STM32 series: A conversion on group + injected is ongoing or can occur (either by auto-injection + mode, external trigger, low power auto power-on (if feature + available), multimode ADC master control (if feature + available))*/ +#define HAL_ADC_STATE_INJ_EOC (0x00002000UL) /*!< Not available on this STM32 series: Conversion data + available on group injected */ +#define HAL_ADC_STATE_INJ_JQOVF (0x00004000UL) /*!< Not available on this STM32 series: Injected queue overflow + occurrence */ /* States of ADC analog watchdogs */ #define HAL_ADC_STATE_AWD1 (0x00010000UL) /*!< Out-of-window occurrence of ADC analog watchdog 1 */ -#define HAL_ADC_STATE_AWD2 (0x00020000UL) /*!< Not available on this STM32 series: Out-of-window occurrence of ADC analog watchdog 2 */ -#define HAL_ADC_STATE_AWD3 (0x00040000UL) /*!< Not available on this STM32 series: Out-of-window occurrence of ADC analog watchdog 3 */ +#define HAL_ADC_STATE_AWD2 (0x00020000UL) /*!< Not available on this STM32 series: Out-of-window occurrence + of ADC analog watchdog 2 */ +#define HAL_ADC_STATE_AWD3 (0x00040000UL) /*!< Not available on this STM32 series: Out-of-window occurrence + of ADC analog watchdog 3 */ /* States of ADC multi-mode */ -#define HAL_ADC_STATE_MULTIMODE_SLAVE (0x00100000UL) /*!< Not available on this STM32 series: ADC in multimode slave state, controlled by another ADC master (when feature available) */ +#define HAL_ADC_STATE_MULTIMODE_SLAVE (0x00100000UL) /*!< Not available on this STM32 series: ADC in multimode slave + state, controlled by another ADC master (when feature + available) */ /** @@ -364,17 +462,20 @@ typedef struct __ADC_HandleTypeDef typedef struct #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */ { - ADC_TypeDef *Instance; /*!< Register base address */ - ADC_InitTypeDef Init; /*!< ADC initialization parameters and regular conversions setting */ - DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ - HAL_LockTypeDef Lock; /*!< ADC locking object */ - __IO uint32_t State; /*!< ADC communication state (bitmap of ADC states) */ - __IO uint32_t ErrorCode; /*!< ADC Error code */ - - uint32_t ADCGroupRegularSequencerRanks; /*!< ADC group regular sequencer memorization of ranks setting, used in mode "fully configurable" (refer to parameter 'ScanConvMode') */ + ADC_TypeDef *Instance; /*!< Register base address */ + ADC_InitTypeDef Init; /*!< ADC initialization parameters and regular conversions setting */ + DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ + HAL_LockTypeDef Lock; /*!< ADC locking object */ + __IO uint32_t State; /*!< ADC communication state (bitmap of ADC states) */ + __IO uint32_t ErrorCode; /*!< ADC Error code */ + + uint32_t ADCGroupRegularSequencerRanks; /*!< ADC group regular sequencer memorization of ranks + setting, used in mode "fully configurable" (refer to + parameter 'ScanConvMode') */ #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1) void (* ConvCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC conversion complete callback */ - void (* ConvHalfCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC conversion DMA half-transfer callback */ + void (* ConvHalfCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC conversion DMA half-transfer + callback */ void (* LevelOutOfWindowCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC analog watchdog 1 callback */ void (* ErrorCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC error callback */ void (* LevelOutOfWindow2Callback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC analog watchdog 2 callback */ @@ -398,8 +499,8 @@ typedef enum HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID = 0x06U, /*!< ADC analog watchdog 2 callback ID */ HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID = 0x07U, /*!< ADC analog watchdog 3 callback ID */ HAL_ADC_END_OF_SAMPLING_CB_ID = 0x08U, /*!< ADC end of sampling callback ID */ - HAL_ADC_MSPINIT_CB_ID = 0x09U, /*!< ADC Msp Init callback ID */ - HAL_ADC_MSPDEINIT_CB_ID = 0x0AU /*!< ADC Msp DeInit callback ID */ + HAL_ADC_MSPINIT_CB_ID = 0x09U, /*!< ADC Msp Init callback ID */ + HAL_ADC_MSPDEINIT_CB_ID = 0x0AU /*!< ADC Msp DeInit callback ID */ } HAL_ADC_CallbackIDTypeDef; /** @@ -438,22 +539,39 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_COMMON_CLOCK_SOURCE ADC common - Clock source * @{ */ -#define ADC_CLOCK_SYNC_PCLK_DIV1 (LL_ADC_CLOCK_SYNC_PCLK_DIV1) /*!< ADC synchronous clock derived from AHB clock without prescaler. This configuration must be enabled only if PCLK has a 50% duty clock cycle (APB prescaler configured inside the RCC must be bypassed and the system clock must by 50% duty cycle) */ -#define ADC_CLOCK_SYNC_PCLK_DIV2 (LL_ADC_CLOCK_SYNC_PCLK_DIV2) /*!< ADC synchronous clock derived from AHB clock with prescaler division by 2 */ -#define ADC_CLOCK_SYNC_PCLK_DIV4 (LL_ADC_CLOCK_SYNC_PCLK_DIV4) /*!< ADC synchronous clock derived from AHB clock with prescaler division by 4 */ - -#define ADC_CLOCK_ASYNC_DIV1 (LL_ADC_CLOCK_ASYNC_DIV1) /*!< ADC asynchronous clock without prescaler */ -#define ADC_CLOCK_ASYNC_DIV2 (LL_ADC_CLOCK_ASYNC_DIV2) /*!< ADC asynchronous clock with prescaler division by 2 */ -#define ADC_CLOCK_ASYNC_DIV4 (LL_ADC_CLOCK_ASYNC_DIV4) /*!< ADC asynchronous clock with prescaler division by 4 */ -#define ADC_CLOCK_ASYNC_DIV6 (LL_ADC_CLOCK_ASYNC_DIV6) /*!< ADC asynchronous clock with prescaler division by 6 */ -#define ADC_CLOCK_ASYNC_DIV8 (LL_ADC_CLOCK_ASYNC_DIV8) /*!< ADC asynchronous clock with prescaler division by 8 */ -#define ADC_CLOCK_ASYNC_DIV10 (LL_ADC_CLOCK_ASYNC_DIV10) /*!< ADC asynchronous clock with prescaler division by 10 */ -#define ADC_CLOCK_ASYNC_DIV12 (LL_ADC_CLOCK_ASYNC_DIV12) /*!< ADC asynchronous clock with prescaler division by 12 */ -#define ADC_CLOCK_ASYNC_DIV16 (LL_ADC_CLOCK_ASYNC_DIV16) /*!< ADC asynchronous clock with prescaler division by 16 */ -#define ADC_CLOCK_ASYNC_DIV32 (LL_ADC_CLOCK_ASYNC_DIV32) /*!< ADC asynchronous clock with prescaler division by 32 */ -#define ADC_CLOCK_ASYNC_DIV64 (LL_ADC_CLOCK_ASYNC_DIV64) /*!< ADC asynchronous clock with prescaler division by 64 */ -#define ADC_CLOCK_ASYNC_DIV128 (LL_ADC_CLOCK_ASYNC_DIV128) /*!< ADC asynchronous clock with prescaler division by 128 */ -#define ADC_CLOCK_ASYNC_DIV256 (LL_ADC_CLOCK_ASYNC_DIV256) /*!< ADC asynchronous clock with prescaler division by 256 */ +#define ADC_CLOCK_SYNC_PCLK_DIV1 (LL_ADC_CLOCK_SYNC_PCLK_DIV1) /*!< ADC synchronous clock from AHB clock + without prescaler. This configuration must be enabled only if PCLK has + a 50% duty clock cycle (APB prescaler configured inside the RCC must + be bypassed and the system clock must by 50% duty cycle) */ +#define ADC_CLOCK_SYNC_PCLK_DIV2 (LL_ADC_CLOCK_SYNC_PCLK_DIV2) /*!< ADC synchronous clock from AHB clock + with prescaler division by 2 */ +#define ADC_CLOCK_SYNC_PCLK_DIV4 (LL_ADC_CLOCK_SYNC_PCLK_DIV4) /*!< ADC synchronous clock from AHB clock + with prescaler division by 4 */ + +#define ADC_CLOCK_ASYNC_DIV1 (LL_ADC_CLOCK_ASYNC_DIV1) /*!< ADC asynchronous clock without + prescaler */ +#define ADC_CLOCK_ASYNC_DIV2 (LL_ADC_CLOCK_ASYNC_DIV2) /*!< ADC asynchronous clock with prescaler + division by 2 */ +#define ADC_CLOCK_ASYNC_DIV4 (LL_ADC_CLOCK_ASYNC_DIV4) /*!< ADC asynchronous clock with prescaler + division by 4 */ +#define ADC_CLOCK_ASYNC_DIV6 (LL_ADC_CLOCK_ASYNC_DIV6) /*!< ADC asynchronous clock with prescaler + division by 6 */ +#define ADC_CLOCK_ASYNC_DIV8 (LL_ADC_CLOCK_ASYNC_DIV8) /*!< ADC asynchronous clock with prescaler + division by 8 */ +#define ADC_CLOCK_ASYNC_DIV10 (LL_ADC_CLOCK_ASYNC_DIV10) /*!< ADC asynchronous clock with prescaler + division by 10 */ +#define ADC_CLOCK_ASYNC_DIV12 (LL_ADC_CLOCK_ASYNC_DIV12) /*!< ADC asynchronous clock with prescaler + division by 12 */ +#define ADC_CLOCK_ASYNC_DIV16 (LL_ADC_CLOCK_ASYNC_DIV16) /*!< ADC asynchronous clock with prescaler + division by 16 */ +#define ADC_CLOCK_ASYNC_DIV32 (LL_ADC_CLOCK_ASYNC_DIV32) /*!< ADC asynchronous clock with prescaler + division by 32 */ +#define ADC_CLOCK_ASYNC_DIV64 (LL_ADC_CLOCK_ASYNC_DIV64) /*!< ADC asynchronous clock with prescaler + division by 64 */ +#define ADC_CLOCK_ASYNC_DIV128 (LL_ADC_CLOCK_ASYNC_DIV128) /*!< ADC asynchronous clock with prescaler + division by 128 */ +#define ADC_CLOCK_ASYNC_DIV256 (LL_ADC_CLOCK_ASYNC_DIV256) /*!< ADC asynchronous clock with prescaler + division by 256 */ /** * @} */ @@ -472,8 +590,10 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_DATA_ALIGN ADC conversion data alignment * @{ */ -#define ADC_DATAALIGN_RIGHT (LL_ADC_DATA_ALIGN_RIGHT)/*!< ADC conversion data alignment: right aligned (alignment on data register LSB bit 0)*/ -#define ADC_DATAALIGN_LEFT (LL_ADC_DATA_ALIGN_LEFT) /*!< ADC conversion data alignment: left aligned (alignment on data register MSB bit 15)*/ +#define ADC_DATAALIGN_RIGHT (LL_ADC_DATA_ALIGN_RIGHT) /*!< ADC conversion data alignment: right aligned + (alignment on data register LSB bit 0)*/ +#define ADC_DATAALIGN_LEFT (LL_ADC_DATA_ALIGN_LEFT) /*!< ADC conversion data alignment: left aligned + (alignment on data register MSB bit 15)*/ /** * @} */ @@ -494,14 +614,25 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /* as default setting equivalent to scan enable. */ /* In case of migration from another STM32 device, the user will be */ /* warned of change of setting choices with assert check. */ -#define ADC_SCAN_DISABLE (0x00000000UL) /*!< Sequencer set to fully configurable: only the rank 1 is enabled (no scan sequence on several ranks) */ -#define ADC_SCAN_ENABLE (ADC_CFGR1_CHSELRMOD) /*!< Sequencer set to fully configurable: sequencer length and each rank affectation to a channel are configurable. */ - -#define ADC_SCAN_SEQ_FIXED (ADC_SCAN_SEQ_FIXED_INT) /*!< Sequencer set to not fully configurable: sequencer length and each rank affectation to a channel are fixed by channel HW number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). Scan direction forward: from channel 0 to channel 18 */ -#define ADC_SCAN_SEQ_FIXED_BACKWARD (ADC_SCAN_SEQ_FIXED_INT | ADC_CFGR1_SCANDIR) /*!< Sequencer set to not fully configurable: sequencer length and each rank affectation to a channel are fixed by channel HW number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). Scan direction backward: from channel 18 to channel 0 */ - -#define ADC_SCAN_DIRECTION_FORWARD (ADC_SCAN_SEQ_FIXED) /* For compatibility with other STM32 devices */ -#define ADC_SCAN_DIRECTION_BACKWARD (ADC_SCAN_SEQ_FIXED_BACKWARD) /* For compatibility with other STM32 devices */ +/* Sequencer set to fully configurable */ +#define ADC_SCAN_DISABLE (0x00000000UL) /*!< Sequencer set to fully configurable: + only the rank 1 is enabled (no scan sequence on several ranks) */ +#define ADC_SCAN_ENABLE (ADC_CFGR1_CHSELRMOD) /*!< Sequencer set to fully configurable: + sequencer length and each rank affectation to a channel are configurable. */ + +/* Sequencer set to not fully configurable */ +#define ADC_SCAN_SEQ_FIXED (ADC_SCAN_SEQ_FIXED_INT) /*!< Sequencer set to not fully configurable: + sequencer length and each rank affectation to a channel are fixed by + channel HW number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). + Scan direction forward: from channel 0 to channel 18 */ +#define ADC_SCAN_SEQ_FIXED_BACKWARD (ADC_SCAN_SEQ_FIXED_INT \ + | ADC_CFGR1_SCANDIR) /*!< Sequencer set to not fully configurable: + sequencer length and each rank affectation to a channel are fixed by + channel HW number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). + Scan direction backward: from channel 18 to channel 0 */ + +#define ADC_SCAN_DIRECTION_FORWARD (ADC_SCAN_SEQ_FIXED) /* For compatibility with other STM32 series */ +#define ADC_SCAN_DIRECTION_BACKWARD (ADC_SCAN_SEQ_FIXED_BACKWARD) /* For compatibility with other STM32 series */ /** * @} */ @@ -510,23 +641,41 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to * @{ */ /* ADC group regular trigger sources for all ADC instances */ -#define ADC_SOFTWARE_START (LL_ADC_REG_TRIG_SOFTWARE) /*!< ADC group regular conversion trigger internal: SW start. */ -#define ADC_EXTERNALTRIG_T1_TRGO2 (LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) /*!< ADC group regular conversion trigger from external peripheral: TIM1 TRGO. Trigger edge set to rising edge (default setting). */ -#define ADC_EXTERNALTRIG_T1_CC4 (LL_ADC_REG_TRIG_EXT_TIM1_CH4) /*!< ADC group regular conversion trigger from external peripheral: TIM1 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ +#define ADC_SOFTWARE_START (LL_ADC_REG_TRIG_SOFTWARE) /*!< ADC group regular conversion + trigger internal: SW start. */ +#define ADC_EXTERNALTRIG_T1_TRGO2 (LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) /*!< ADC group regular conversion + trigger from external peripheral: TIM1 TRGO. + Trigger edge set to rising edge (default setting). */ +#define ADC_EXTERNALTRIG_T1_CC4 (LL_ADC_REG_TRIG_EXT_TIM1_CH4) /*!< ADC group regular conversion + trigger from external peripheral: TIM1 channel 4 event + (capture compare: input capture or output capture). + Trigger edge set to rising edge (default setting). */ #if defined(TIM2) -#define ADC_EXTERNALTRIG_T2_TRGO (LL_ADC_REG_TRIG_EXT_TIM2_TRGO) /*!< ADC group regular conversion trigger from external peripheral: TIM2 TRGO. Trigger edge set to rising edge (default setting). */ -#endif -#define ADC_EXTERNALTRIG_T3_TRGO (LL_ADC_REG_TRIG_EXT_TIM3_TRGO) /*!< ADC group regular conversion trigger from external peripheral: TIM3 TRGO. Trigger edge set to rising edge (default setting). */ +#define ADC_EXTERNALTRIG_T2_TRGO (LL_ADC_REG_TRIG_EXT_TIM2_TRGO) /*!< ADC group regular conversion + trigger from external peripheral: TIM2 TRGO. + Trigger edge set to rising edge (default setting). */ +#endif /* TIM2 */ +#define ADC_EXTERNALTRIG_T3_TRGO (LL_ADC_REG_TRIG_EXT_TIM3_TRGO) /*!< ADC group regular conversion + trigger from external peripheral: TIM3 TRGO. + Trigger edge set to rising edge (default setting). */ #if defined(TIM4) -#define ADC_EXTERNALTRIG_T4_TRGO (LL_ADC_REG_TRIG_EXT_TIM4_TRGO) /*!< ADC group regular conversion trigger from external peripheral: TIM4 TRGO. Trigger edge set to rising edge (default setting). */ -#endif +#define ADC_EXTERNALTRIG_T4_TRGO (LL_ADC_REG_TRIG_EXT_TIM4_TRGO) /*!< ADC group regular conversion + trigger from external peripheral: TIM4 TRGO. + Trigger edge set to rising edge (default setting). */ +#endif /* TIM4 */ #if defined(TIM6) -#define ADC_EXTERNALTRIG_T6_TRGO (LL_ADC_REG_TRIG_EXT_TIM6_TRGO) /*!< ADC group regular conversion trigger from external peripheral: TIM6 TRGO. Trigger edge set to rising edge (default setting). */ -#endif +#define ADC_EXTERNALTRIG_T6_TRGO (LL_ADC_REG_TRIG_EXT_TIM6_TRGO) /*!< ADC group regular conversion + trigger from external peripheral: TIM6 TRGO. + Trigger edge set to rising edge (default setting). */ +#endif /* TIM6 */ #if defined(TIM15) -#define ADC_EXTERNALTRIG_T15_TRGO (LL_ADC_REG_TRIG_EXT_TIM15_TRGO) /*!< ADC group regular conversion trigger from external peripheral: TIM15 TRGO. Trigger edge set to rising edge (default setting). */ -#endif -#define ADC_EXTERNALTRIG_EXT_IT11 (LL_ADC_REG_TRIG_EXT_EXTI_LINE11) /*!< ADC group regular conversion trigger from external peripheral: external interrupt line 11. Trigger edge set to rising edge (default setting). */ +#define ADC_EXTERNALTRIG_T15_TRGO (LL_ADC_REG_TRIG_EXT_TIM15_TRGO) /*!< ADC group regular conversion + trigger from external peripheral: TIM15 TRGO. + Trigger edge set to rising edge (default setting). */ +#endif /* TIM15 */ +#define ADC_EXTERNALTRIG_EXT_IT11 (LL_ADC_REG_TRIG_EXT_EXTI_LINE11) /*!< ADC group regular conversion + trigger from external peripheral: external interrupt line 11. + Trigger edge set to rising edge (default setting). */ /** * @} */ @@ -534,10 +683,14 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_regular_external_trigger_edge ADC group regular trigger edge (when external trigger is selected) * @{ */ -#define ADC_EXTERNALTRIGCONVEDGE_NONE (0x00000000UL) /*!< Regular conversions hardware trigger detection disabled */ -#define ADC_EXTERNALTRIGCONVEDGE_RISING (LL_ADC_REG_TRIG_EXT_RISING) /*!< ADC group regular conversion trigger polarity set to rising edge */ -#define ADC_EXTERNALTRIGCONVEDGE_FALLING (LL_ADC_REG_TRIG_EXT_FALLING) /*!< ADC group regular conversion trigger polarity set to falling edge */ -#define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING (LL_ADC_REG_TRIG_EXT_RISINGFALLING) /*!< ADC group regular conversion trigger polarity set to both rising and falling edges */ +#define ADC_EXTERNALTRIGCONVEDGE_NONE (0x00000000UL) /*!< Regular conversions hardware + trigger detection disabled */ +#define ADC_EXTERNALTRIGCONVEDGE_RISING (LL_ADC_REG_TRIG_EXT_RISING) /*!< ADC group regular conversion + trigger polarity set to rising edge */ +#define ADC_EXTERNALTRIGCONVEDGE_FALLING (LL_ADC_REG_TRIG_EXT_FALLING) /*!< ADC group regular conversion + trigger polarity set to falling edge */ +#define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING (LL_ADC_REG_TRIG_EXT_RISINGFALLING) /*!< ADC group regular conversion + trigger polarity set to both rising and falling edges */ /** * @} */ @@ -545,8 +698,8 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_EOCSelection ADC sequencer end of unitary conversion or sequence conversions * @{ */ -#define ADC_EOC_SINGLE_CONV (ADC_ISR_EOC) /*!< End of unitary conversion flag */ -#define ADC_EOC_SEQ_CONV (ADC_ISR_EOS) /*!< End of sequence conversions flag */ +#define ADC_EOC_SINGLE_CONV (ADC_ISR_EOC) /*!< End of unitary conversion flag */ +#define ADC_EOC_SEQ_CONV (ADC_ISR_EOS) /*!< End of sequence conversions flag */ /** * @} */ @@ -554,8 +707,10 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_REG_OVR_DATA_BEHAVIOR ADC group regular - Overrun behavior on conversion data * @{ */ -#define ADC_OVR_DATA_PRESERVED (LL_ADC_REG_OVR_DATA_PRESERVED) /*!< ADC group regular behavior in case of overrun: data preserved */ -#define ADC_OVR_DATA_OVERWRITTEN (LL_ADC_REG_OVR_DATA_OVERWRITTEN) /*!< ADC group regular behavior in case of overrun: data overwritten */ +#define ADC_OVR_DATA_PRESERVED (LL_ADC_REG_OVR_DATA_PRESERVED) /*!< ADC group regular behavior in case + of overrun: data preserved */ +#define ADC_OVR_DATA_OVERWRITTEN (LL_ADC_REG_OVR_DATA_OVERWRITTEN) /*!< ADC group regular behavior in case + of overrun: data overwritten */ /** * @} */ @@ -563,8 +718,14 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_REG_SEQ_RANKS ADC group regular - Sequencer ranks * @{ */ -#define ADC_RANK_CHANNEL_NUMBER (0x00000001U) /*!< Setting relevant if parameter "ScanConvMode" is set to sequencer not fully configurable: Enable the rank of the selected channels. Number of ranks in the sequence is defined by number of channels enabled, rank of each channel is defined by channel number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...) */ -#define ADC_RANK_NONE (0x00000002U) /*!< Setting relevant if parameter "ScanConvMode" is set to sequencer not fully configurable: Disable the selected rank (selected channel) from sequencer */ +#define ADC_RANK_CHANNEL_NUMBER (0x00000001U) /*!< Setting relevant if parameter "ScanConvMode" is set + to sequencer not fully configurable: Enable the rank of the selected + channels. Number of ranks in the sequence is defined by number of channels + enabled, rank of each channel is defined by channel number + (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...) */ +#define ADC_RANK_NONE (0x00000002U) /*!< Setting relevant if parameter "ScanConvMode" + is set to sequencer not fully configurable: Disable the selected rank + (selected channel) from sequencer */ #define ADC_REGULAR_RANK_1 (LL_ADC_REG_RANK_1) /*!< ADC group regular sequencer rank 1 */ #define ADC_REGULAR_RANK_2 (LL_ADC_REG_RANK_2) /*!< ADC group regular sequencer rank 2 */ @@ -581,8 +742,10 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_SAMPLINGTIME_COMMON ADC instance - Sampling time common to a group of channels * @{ */ -#define ADC_SAMPLINGTIME_COMMON_1 (LL_ADC_SAMPLINGTIME_COMMON_1) /*!< Set sampling time common to a group of channels: sampling time nb 1 */ -#define ADC_SAMPLINGTIME_COMMON_2 (LL_ADC_SAMPLINGTIME_COMMON_2) /*!< Set sampling time common to a group of channels: sampling time nb 2 */ +#define ADC_SAMPLINGTIME_COMMON_1 (LL_ADC_SAMPLINGTIME_COMMON_1) /*!< Set sampling time common to a group of + channels: sampling time nb 1 */ +#define ADC_SAMPLINGTIME_COMMON_2 (LL_ADC_SAMPLINGTIME_COMMON_2) /*!< Set sampling time common to a group of + channels: sampling time nb 2 */ /** * @} */ @@ -590,14 +753,14 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_CHANNEL_SAMPLINGTIME Channel - Sampling time * @{ */ -#define ADC_SAMPLETIME_1CYCLE_5 (LL_ADC_SAMPLINGTIME_1CYCLE_5) /*!< Sampling time 1.5 ADC clock cycle */ -#define ADC_SAMPLETIME_3CYCLES_5 (LL_ADC_SAMPLINGTIME_3CYCLES_5) /*!< Sampling time 3.5 ADC clock cycles */ -#define ADC_SAMPLETIME_7CYCLES_5 (LL_ADC_SAMPLINGTIME_7CYCLES_5) /*!< Sampling time 7.5 ADC clock cycles */ -#define ADC_SAMPLETIME_12CYCLES_5 (LL_ADC_SAMPLINGTIME_12CYCLES_5) /*!< Sampling time 12.5 ADC clock cycles */ -#define ADC_SAMPLETIME_19CYCLES_5 (LL_ADC_SAMPLINGTIME_19CYCLES_5) /*!< Sampling time 19.5 ADC clock cycles */ -#define ADC_SAMPLETIME_39CYCLES_5 (LL_ADC_SAMPLINGTIME_39CYCLES_5) /*!< Sampling time 39.5 ADC clock cycles */ -#define ADC_SAMPLETIME_79CYCLES_5 (LL_ADC_SAMPLINGTIME_79CYCLES_5) /*!< Sampling time 79.5 ADC clock cycles */ -#define ADC_SAMPLETIME_160CYCLES_5 (LL_ADC_SAMPLINGTIME_160CYCLES_5) /*!< Sampling time 160.5 ADC clock cycles */ +#define ADC_SAMPLETIME_1CYCLE_5 (LL_ADC_SAMPLINGTIME_1CYCLE_5) /*!< Sampling time 1.5 ADC clock cycle */ +#define ADC_SAMPLETIME_3CYCLES_5 (LL_ADC_SAMPLINGTIME_3CYCLES_5) /*!< Sampling time 3.5 ADC clock cycles */ +#define ADC_SAMPLETIME_7CYCLES_5 (LL_ADC_SAMPLINGTIME_7CYCLES_5) /*!< Sampling time 7.5 ADC clock cycles */ +#define ADC_SAMPLETIME_12CYCLES_5 (LL_ADC_SAMPLINGTIME_12CYCLES_5) /*!< Sampling time 12.5 ADC clock cycles */ +#define ADC_SAMPLETIME_19CYCLES_5 (LL_ADC_SAMPLINGTIME_19CYCLES_5) /*!< Sampling time 19.5 ADC clock cycles */ +#define ADC_SAMPLETIME_39CYCLES_5 (LL_ADC_SAMPLINGTIME_39CYCLES_5) /*!< Sampling time 39.5 ADC clock cycles */ +#define ADC_SAMPLETIME_79CYCLES_5 (LL_ADC_SAMPLINGTIME_79CYCLES_5) /*!< Sampling time 79.5 ADC clock cycles */ +#define ADC_SAMPLETIME_160CYCLES_5 (LL_ADC_SAMPLINGTIME_160CYCLES_5) /*!< Sampling time 160.5 ADC clock cycles */ /** * @} */ @@ -605,33 +768,34 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_CHANNEL ADC instance - Channel number * @{ */ -#define ADC_CHANNEL_0 (LL_ADC_CHANNEL_0) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN0 */ -#define ADC_CHANNEL_1 (LL_ADC_CHANNEL_1) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN1 */ -#define ADC_CHANNEL_2 (LL_ADC_CHANNEL_2) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN2 */ -#define ADC_CHANNEL_3 (LL_ADC_CHANNEL_3) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN3 */ -#define ADC_CHANNEL_4 (LL_ADC_CHANNEL_4) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN4 */ -#define ADC_CHANNEL_5 (LL_ADC_CHANNEL_5) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN5 */ -#define ADC_CHANNEL_6 (LL_ADC_CHANNEL_6) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN6 */ -#define ADC_CHANNEL_7 (LL_ADC_CHANNEL_7) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN7 */ -#define ADC_CHANNEL_8 (LL_ADC_CHANNEL_8) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN8 */ -#define ADC_CHANNEL_9 (LL_ADC_CHANNEL_9) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN9 */ -#define ADC_CHANNEL_10 (LL_ADC_CHANNEL_10) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN10 */ -#define ADC_CHANNEL_11 (LL_ADC_CHANNEL_11) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN11 */ -#define ADC_CHANNEL_12 (LL_ADC_CHANNEL_12) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN12 */ -#define ADC_CHANNEL_13 (LL_ADC_CHANNEL_13) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN13 */ -#define ADC_CHANNEL_14 (LL_ADC_CHANNEL_14) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN14 */ -#define ADC_CHANNEL_15 (LL_ADC_CHANNEL_15) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN15 */ -#define ADC_CHANNEL_16 (LL_ADC_CHANNEL_16) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN16 */ -#define ADC_CHANNEL_17 (LL_ADC_CHANNEL_17) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN17 */ -#define ADC_CHANNEL_18 (LL_ADC_CHANNEL_18) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN18 */ -#define ADC_CHANNEL_19 (LL_ADC_CHANNEL_19) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN19 */ -#define ADC_CHANNEL_20 (LL_ADC_CHANNEL_20) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN20 */ -#define ADC_CHANNEL_21 (LL_ADC_CHANNEL_21) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN21 */ -#define ADC_CHANNEL_22 (LL_ADC_CHANNEL_22) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN22 */ -#define ADC_CHANNEL_VREFINT (LL_ADC_CHANNEL_VREFINT) /*!< ADC internal channel connected to VrefInt: Internal voltage reference. */ -#define ADC_CHANNEL_TEMPSENSOR (LL_ADC_CHANNEL_TEMPSENSOR) /*!< ADC internal channel connected to Temperature sensor. */ -#define ADC_CHANNEL_VDDA (LL_ADC_CHANNEL_VDDA) /*!< ADC internal channel connected to VDDA */ -#define ADC_CHANNEL_VSSA (LL_ADC_CHANNEL_VSSA) /*!< ADC internal channel connected to VSSA */ +#define ADC_CHANNEL_0 (LL_ADC_CHANNEL_0) /*!< External channel (GPIO pin) ADCx_IN0 */ +#define ADC_CHANNEL_1 (LL_ADC_CHANNEL_1) /*!< External channel (GPIO pin) ADCx_IN1 */ +#define ADC_CHANNEL_2 (LL_ADC_CHANNEL_2) /*!< External channel (GPIO pin) ADCx_IN2 */ +#define ADC_CHANNEL_3 (LL_ADC_CHANNEL_3) /*!< External channel (GPIO pin) ADCx_IN3 */ +#define ADC_CHANNEL_4 (LL_ADC_CHANNEL_4) /*!< External channel (GPIO pin) ADCx_IN4 */ +#define ADC_CHANNEL_5 (LL_ADC_CHANNEL_5) /*!< External channel (GPIO pin) ADCx_IN5 */ +#define ADC_CHANNEL_6 (LL_ADC_CHANNEL_6) /*!< External channel (GPIO pin) ADCx_IN6 */ +#define ADC_CHANNEL_7 (LL_ADC_CHANNEL_7) /*!< External channel (GPIO pin) ADCx_IN7 */ +#define ADC_CHANNEL_8 (LL_ADC_CHANNEL_8) /*!< External channel (GPIO pin) ADCx_IN8 */ +#define ADC_CHANNEL_9 (LL_ADC_CHANNEL_9) /*!< External channel (GPIO pin) ADCx_IN9 */ +#define ADC_CHANNEL_10 (LL_ADC_CHANNEL_10) /*!< External channel (GPIO pin) ADCx_IN10 */ +#define ADC_CHANNEL_11 (LL_ADC_CHANNEL_11) /*!< External channel (GPIO pin) ADCx_IN11 */ +#define ADC_CHANNEL_12 (LL_ADC_CHANNEL_12) /*!< External channel (GPIO pin) ADCx_IN12 */ +#define ADC_CHANNEL_13 (LL_ADC_CHANNEL_13) /*!< External channel (GPIO pin) ADCx_IN13 */ +#define ADC_CHANNEL_14 (LL_ADC_CHANNEL_14) /*!< External channel (GPIO pin) ADCx_IN14 */ +#define ADC_CHANNEL_15 (LL_ADC_CHANNEL_15) /*!< External channel (GPIO pin) ADCx_IN15 */ +#define ADC_CHANNEL_16 (LL_ADC_CHANNEL_16) /*!< External channel (GPIO pin) ADCx_IN16 */ +#define ADC_CHANNEL_17 (LL_ADC_CHANNEL_17) /*!< External channel (GPIO pin) ADCx_IN17 */ +#define ADC_CHANNEL_18 (LL_ADC_CHANNEL_18) /*!< External channel (GPIO pin) ADCx_IN18 */ +#define ADC_CHANNEL_19 (LL_ADC_CHANNEL_19) /*!< External channel (GPIO pin) ADCx_IN19 */ +#define ADC_CHANNEL_20 (LL_ADC_CHANNEL_20) /*!< External channel (GPIO pin) ADCx_IN20 */ +#define ADC_CHANNEL_21 (LL_ADC_CHANNEL_21) /*!< External channel (GPIO pin) ADCx_IN21 */ +#define ADC_CHANNEL_22 (LL_ADC_CHANNEL_22) /*!< External channel (GPIO pin) ADCx_IN22 */ +#define ADC_CHANNEL_VREFINT (LL_ADC_CHANNEL_VREFINT) /*!< Internal channel VrefInt: + Internal voltage reference. */ +#define ADC_CHANNEL_TEMPSENSOR (LL_ADC_CHANNEL_TEMPSENSOR) /*!< Internal channel Temperature sensor. */ +#define ADC_CHANNEL_VDDA (LL_ADC_CHANNEL_VDDA) /*!< Internal channel VDDA */ +#define ADC_CHANNEL_VSSA (LL_ADC_CHANNEL_VSSA) /*!< Internal channel VSSA */ /** * @} */ @@ -649,9 +813,11 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_analog_watchdog_mode ADC Analog Watchdog Mode * @{ */ -#define ADC_ANALOGWATCHDOG_NONE (0x00000000UL) /*!< No analog watchdog selected */ -#define ADC_ANALOGWATCHDOG_SINGLE_REG (ADC_CFGR1_AWD1SGL | ADC_CFGR1_AWD1EN) /*!< Analog watchdog applied to a regular group single channel */ -#define ADC_ANALOGWATCHDOG_ALL_REG (ADC_CFGR1_AWD1EN) /*!< Analog watchdog applied to regular group all channels */ +#define ADC_ANALOGWATCHDOG_NONE (0x00000000UL) /*!< ADC AWD not selected */ +#define ADC_ANALOGWATCHDOG_SINGLE_REG (ADC_CFGR1_AWD1SGL | ADC_CFGR1_AWD1EN) /*!< ADC AWD applied to a regular + group single channel */ +#define ADC_ANALOGWATCHDOG_ALL_REG (ADC_CFGR1_AWD1EN) /*!< ADC AWD applied to regular + group all channels */ /** * @} */ @@ -659,14 +825,18 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_OVS_RATIO Oversampling - Ratio * @{ */ -#define ADC_OVERSAMPLING_RATIO_2 (LL_ADC_OVS_RATIO_2) /*!< ADC oversampling ratio of 2 (2 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_4 (LL_ADC_OVS_RATIO_4) /*!< ADC oversampling ratio of 4 (4 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_8 (LL_ADC_OVS_RATIO_8) /*!< ADC oversampling ratio of 8 (8 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_16 (LL_ADC_OVS_RATIO_16) /*!< ADC oversampling ratio of 16 (16 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_32 (LL_ADC_OVS_RATIO_32) /*!< ADC oversampling ratio of 32 (32 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_64 (LL_ADC_OVS_RATIO_64) /*!< ADC oversampling ratio of 64 (64 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_128 (LL_ADC_OVS_RATIO_128) /*!< ADC oversampling ratio of 128 (128 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define ADC_OVERSAMPLING_RATIO_256 (LL_ADC_OVS_RATIO_256) /*!< ADC oversampling ratio of 256 (256 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ +/** + * @note The oversampling ratio is the number of ADC conversions performed, sum of these conversions data is computed + * to result as the ADC oversampling conversion data (before potential shift) + */ +#define ADC_OVERSAMPLING_RATIO_2 (LL_ADC_OVS_RATIO_2) /*!< ADC oversampling ratio 2 */ +#define ADC_OVERSAMPLING_RATIO_4 (LL_ADC_OVS_RATIO_4) /*!< ADC oversampling ratio 4 */ +#define ADC_OVERSAMPLING_RATIO_8 (LL_ADC_OVS_RATIO_8) /*!< ADC oversampling ratio 8 */ +#define ADC_OVERSAMPLING_RATIO_16 (LL_ADC_OVS_RATIO_16) /*!< ADC oversampling ratio 16 */ +#define ADC_OVERSAMPLING_RATIO_32 (LL_ADC_OVS_RATIO_32) /*!< ADC oversampling ratio 32 */ +#define ADC_OVERSAMPLING_RATIO_64 (LL_ADC_OVS_RATIO_64) /*!< ADC oversampling ratio 64 */ +#define ADC_OVERSAMPLING_RATIO_128 (LL_ADC_OVS_RATIO_128) /*!< ADC oversampling ratio 128 */ +#define ADC_OVERSAMPLING_RATIO_256 (LL_ADC_OVS_RATIO_256) /*!< ADC oversampling ratio 256 */ /** * @} */ @@ -674,15 +844,19 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_OVS_SHIFT Oversampling - Data shift * @{ */ -#define ADC_RIGHTBITSHIFT_NONE (LL_ADC_OVS_SHIFT_NONE) /*!< ADC oversampling no shift (sum of the ADC conversions data is not divided to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_1 (LL_ADC_OVS_SHIFT_RIGHT_1) /*!< ADC oversampling shift of 1 (sum of the ADC conversions data is divided by 2 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_2 (LL_ADC_OVS_SHIFT_RIGHT_2) /*!< ADC oversampling shift of 2 (sum of the ADC conversions data is divided by 4 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_3 (LL_ADC_OVS_SHIFT_RIGHT_3) /*!< ADC oversampling shift of 3 (sum of the ADC conversions data is divided by 8 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_4 (LL_ADC_OVS_SHIFT_RIGHT_4) /*!< ADC oversampling shift of 4 (sum of the ADC conversions data is divided by 16 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_5 (LL_ADC_OVS_SHIFT_RIGHT_5) /*!< ADC oversampling shift of 5 (sum of the ADC conversions data is divided by 32 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_6 (LL_ADC_OVS_SHIFT_RIGHT_6) /*!< ADC oversampling shift of 6 (sum of the ADC conversions data is divided by 64 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_7 (LL_ADC_OVS_SHIFT_RIGHT_7) /*!< ADC oversampling shift of 7 (sum of the ADC conversions data is divided by 128 to result as the ADC oversampling conversion data) */ -#define ADC_RIGHTBITSHIFT_8 (LL_ADC_OVS_SHIFT_RIGHT_8) /*!< ADC oversampling shift of 8 (sum of the ADC conversions data is divided by 256 to result as the ADC oversampling conversion data) */ +/** + * @note The sum of the ADC conversions data is divided by "Rightbitshift" number to result as the ADC oversampling + * conversion data) + */ +#define ADC_RIGHTBITSHIFT_NONE (LL_ADC_OVS_SHIFT_NONE) /*!< ADC oversampling no shift */ +#define ADC_RIGHTBITSHIFT_1 (LL_ADC_OVS_SHIFT_RIGHT_1) /*!< ADC oversampling right shift of 1 ranks */ +#define ADC_RIGHTBITSHIFT_2 (LL_ADC_OVS_SHIFT_RIGHT_2) /*!< ADC oversampling right shift of 2 ranks */ +#define ADC_RIGHTBITSHIFT_3 (LL_ADC_OVS_SHIFT_RIGHT_3) /*!< ADC oversampling right shift of 3 ranks */ +#define ADC_RIGHTBITSHIFT_4 (LL_ADC_OVS_SHIFT_RIGHT_4) /*!< ADC oversampling right shift of 4 ranks */ +#define ADC_RIGHTBITSHIFT_5 (LL_ADC_OVS_SHIFT_RIGHT_5) /*!< ADC oversampling right shift of 5 ranks */ +#define ADC_RIGHTBITSHIFT_6 (LL_ADC_OVS_SHIFT_RIGHT_6) /*!< ADC oversampling right shift of 6 ranks */ +#define ADC_RIGHTBITSHIFT_7 (LL_ADC_OVS_SHIFT_RIGHT_7) /*!< ADC oversampling right shift of 7 ranks */ +#define ADC_RIGHTBITSHIFT_8 (LL_ADC_OVS_SHIFT_RIGHT_8) /*!< ADC oversampling right shift of 8 ranks */ /** * @} */ @@ -690,8 +864,10 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_OVS_DISCONT_MODE Oversampling - Discontinuous mode * @{ */ -#define ADC_TRIGGEREDMODE_SINGLE_TRIGGER (LL_ADC_OVS_REG_CONT) /*!< ADC oversampling discontinuous mode: continuous mode (all conversions of oversampling ratio are done from 1 trigger) */ -#define ADC_TRIGGEREDMODE_MULTI_TRIGGER (LL_ADC_OVS_REG_DISCONT) /*!< ADC oversampling discontinuous mode: discontinuous mode (each conversion of oversampling ratio needs a trigger) */ +#define ADC_TRIGGEREDMODE_SINGLE_TRIGGER (LL_ADC_OVS_REG_CONT) /*!< ADC oversampling discontinuous mode: + continuous mode (all conversions of OVS ratio are done from 1 trigger) */ +#define ADC_TRIGGEREDMODE_MULTI_TRIGGER (LL_ADC_OVS_REG_DISCONT) /*!< ADC oversampling discontinuous mode: + discontinuous mode (each conversion of OVS ratio needs a trigger) */ /** * @} */ @@ -699,25 +875,36 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /** @defgroup ADC_HAL_EC_REG_TRIGGER_FREQ ADC group regular - Trigger frequency mode * @{ */ -#define ADC_TRIGGER_FREQ_HIGH (LL_ADC_TRIGGER_FREQ_HIGH) /*!< ADC trigger frequency mode set to high frequency. Note: ADC trigger frequency mode must be set to low frequency when a duration is exceeded before ADC conversion start trigger event (between ADC enable and ADC conversion start trigger event or between two ADC conversion start trigger event). Duration value: Refer to device datasheet, parameter "tIdle". */ -#define ADC_TRIGGER_FREQ_LOW (LL_ADC_TRIGGER_FREQ_LOW) /*!< ADC trigger frequency mode set to low frequency. Note: ADC trigger frequency mode must be set to low frequency when a duration is exceeded before ADC conversion start trigger event (between ADC enable and ADC conversion start trigger event or between two ADC conversion start trigger event). Duration value: Refer to device datasheet, parameter "tIdle". */ + +/** + * @note ADC trigger frequency mode must be set to low frequency when a duration is exceeded before ADC conversion + * start trigger event (between ADC enable and ADC conversion start trigger event or between two ADC conversion + * start trigger event). + * Duration value: Refer to device datasheet, parameter "tIdle". + */ +#define ADC_TRIGGER_FREQ_HIGH (LL_ADC_TRIGGER_FREQ_HIGH) /*!< Trigger frequency mode set to high frequency. */ +#define ADC_TRIGGER_FREQ_LOW (LL_ADC_TRIGGER_FREQ_LOW) /*!< Trigger frequency mode set to low frequency. */ /** * @} */ - /** @defgroup ADC_Event_type ADC Event type * @{ */ +/** + * @note Analog watchdog 1 is available on all stm32 series + * Analog watchdog 2 and 3 are not available on all series + */ #define ADC_EOSMP_EVENT (ADC_FLAG_EOSMP) /*!< ADC End of Sampling event */ -#define ADC_AWD1_EVENT (ADC_FLAG_AWD1) /*!< ADC Analog watchdog 1 event (main analog watchdog, present on all STM32 series) */ -#define ADC_AWD2_EVENT (ADC_FLAG_AWD2) /*!< ADC Analog watchdog 2 event (additional analog watchdog, not present on all STM32 series) */ -#define ADC_AWD3_EVENT (ADC_FLAG_AWD3) /*!< ADC Analog watchdog 3 event (additional analog watchdog, not present on all STM32 series) */ +#define ADC_AWD1_EVENT (ADC_FLAG_AWD1) /*!< ADC Analog watchdog 1 event (main analog watchdog) */ +#define ADC_AWD2_EVENT (ADC_FLAG_AWD2) /*!< ADC Analog watchdog 2 event (additional analog watchdog) */ +#define ADC_AWD3_EVENT (ADC_FLAG_AWD3) /*!< ADC Analog watchdog 3 event (additional analog watchdog) */ #define ADC_OVR_EVENT (ADC_FLAG_OVR) /*!< ADC overrun event */ /** * @} */ -#define ADC_AWD_EVENT ADC_AWD1_EVENT /*!< ADC Analog watchdog 1 event: Naming for compatibility with other STM32 devices having only one analog watchdog */ +#define ADC_AWD_EVENT ADC_AWD1_EVENT /*!< ADC Analog watchdog 1 event: Naming for compatibility + with other STM32 devices having only one analog watchdog */ /** @defgroup ADC_interrupts_definition ADC interrupts definition * @{ @@ -729,8 +916,11 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to #define ADC_IT_EOS ADC_IER_EOSIE /*!< ADC End of regular sequence of conversions interrupt source */ #define ADC_IT_OVR ADC_IER_OVRIE /*!< ADC overrun interrupt source */ #define ADC_IT_AWD1 ADC_IER_AWD1IE /*!< ADC Analog watchdog 1 interrupt source (main analog watchdog) */ -#define ADC_IT_AWD2 ADC_IER_AWD2IE /*!< ADC Analog watchdog 2 interrupt source (additional analog watchdog) */ -#define ADC_IT_AWD3 ADC_IER_AWD3IE /*!< ADC Analog watchdog 3 interrupt source (additional analog watchdog) */ +#define ADC_IT_AWD2 ADC_IER_AWD2IE /*!< ADC Analog watchdog 2 interrupt source (additional analog + watchdog) */ +#define ADC_IT_AWD3 ADC_IER_AWD3IE /*!< ADC Analog watchdog 3 interrupt source (additional analog + watchdog) */ +#define ADC_IT_EOCAL ADC_IER_EOCALIE /*!< ADC End of Calibration interrupt source */ /** * @} */ @@ -747,6 +937,7 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to #define ADC_FLAG_AWD1 ADC_ISR_AWD1 /*!< ADC Analog watchdog 1 flag */ #define ADC_FLAG_AWD2 ADC_ISR_AWD2 /*!< ADC Analog watchdog 2 flag */ #define ADC_FLAG_AWD3 ADC_ISR_AWD3 /*!< ADC Analog watchdog 3 flag */ +#define ADC_FLAG_EOCAL ADC_ISR_EOCAL /*!< ADC End of Calibration interrupt flag */ /** * @} */ @@ -916,11 +1107,20 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING) ) +#if defined(TIM2) +#define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIG_T1_TRGO2) || \ + ((REGTRIG) == ADC_EXTERNALTRIG_T1_CC4) || \ + ((REGTRIG) == ADC_EXTERNALTRIG_T2_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIG_T3_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIG_EXT_IT11) || \ + ((REGTRIG) == ADC_SOFTWARE_START)) +#else #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIG_T1_TRGO2) || \ ((REGTRIG) == ADC_EXTERNALTRIG_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIG_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIG_EXT_IT11) || \ ((REGTRIG) == ADC_SOFTWARE_START)) +#endif /* TIM2 */ #define IS_ADC_EOC_SELECTION(EOC_SELECTION) (((EOC_SELECTION) == ADC_EOC_SINGLE_CONV) || \ ((EOC_SELECTION) == ADC_EOC_SEQ_CONV)) @@ -1024,7 +1224,8 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to /* Combination of all post-conversion flags bits: EOC/EOS, OVR, AWD */ #define ADC_FLAG_POSTCONV_ALL (ADC_FLAG_AWD | ADC_FLAG_OVR | ADC_FLAG_EOS | ADC_FLAG_EOC) -#define ADC_SCAN_SEQ_FIXED_INT 0x80000000U /* Internal definition to differentiate sequencer setting fixed or configurable */ +/* Internal definition to differentiate sequencer setting fixed or configurable */ +#define ADC_SCAN_SEQ_FIXED_INT 0x80000000U /** * @} @@ -1311,8 +1512,10 @@ typedef void (*pADC_CallbackTypeDef)(ADC_HandleTypeDef *hadc); /*!< pointer to * comparison with internal channel parameter to be done * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). * (3) ADC channels available on STM32C031xx device only. - * @retval Value "0" if the channel corresponds to a parameter definition of a ADC external channel (channel connected to a GPIO pin). - * Value "1" if the channel corresponds to a parameter definition of a ADC internal channel. + * @retval Value "0" if the channel corresponds to a parameter definition of a + * ADC external channel (channel connected to a GPIO pin). + * Value "1" if the channel corresponds to a parameter definition of + * a ADC internal channel. */ #define __HAL_ADC_IS_CHANNEL_INTERNAL(__CHANNEL__) \ __LL_ADC_IS_CHANNEL_INTERNAL((__CHANNEL__)) @@ -1572,13 +1775,15 @@ __LL_ADC_CALC_VREFANALOG_VOLTAGE((__VREFINT_ADC_DATA__),\ * user board environment or can be calculated using ADC measurement * and ADC helper macro @ref __LL_ADC_CALC_VREFANALOG_VOLTAGE(). * @note ADC measurement data must correspond to a resolution of 12bits - * (full scale digital value 4095). If not the case, the data must be - * preliminarily rescaled to an equivalent resolution of 12 bits. - * @param __TEMPSENSOR_TYP_AVGSLOPE__ Device datasheet data: Temperature sensor slope typical value (unit: uV/DegCelsius). - * On STM32C0, refer to device datasheet parameter "Avg_Slope". - * @param __TEMPSENSOR_TYP_CALX_V__ Device datasheet data: Temperature sensor voltage typical value (at temperature and Vref+ defined in parameters below) (unit: mV). - * On STM32C0, refer to device datasheet parameter "V30" (corresponding to TS_CAL1). - * @param __TEMPSENSOR_CALX_TEMP__ Device datasheet data: Temperature at which temperature sensor voltage (see parameter above) is corresponding (unit: mV) + * @param __TEMPSENSOR_TYP_AVGSLOPE__ Device datasheet data: Temperature sensor slope typical value + * (unit: uV/DegCelsius). + * On this STM32 series, refer to device datasheet parameter "Avg_Slope". + * @param __TEMPSENSOR_TYP_CALX_V__ Device datasheet data: Temperature sensor voltage typical value (at + * temperature and Vref+ defined in parameters below) (unit: mV). + * On this STM32 series, refer to device datasheet parameter "V30" + * (corresponding to TS_CAL1). + * @param __TEMPSENSOR_CALX_TEMP__ Device datasheet data: Temperature at which temperature sensor voltage (see + * parameter above) is corresponding (unit: mV) * @param __VREFANALOG_VOLTAGE__ Analog voltage reference (Vref+) voltage (unit: mV) * @param __TEMPSENSOR_ADC_DATA__ ADC conversion data of internal temperature sensor (unit: digital value). * @param __ADC_RESOLUTION__ ADC resolution at which internal temperature sensor voltage has been measured. @@ -1667,6 +1872,8 @@ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc); void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc); void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc); void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); +void HAL_ADC_CalibrationCpltCallback(ADC_HandleTypeDef *hadc); +void HAL_ADC_ADCReadyCallback(ADC_HandleTypeDef *hadc); /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_conf.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_conf.h index ba22efb5b..22ea0a0ee 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_conf.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_conf.h @@ -87,7 +87,7 @@ extern "C" { * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) -#define HSE_VALUE (48000000U) /*!< Value of the External oscillator in Hz */ +#define HSE_VALUE (24000000U) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) @@ -103,6 +103,18 @@ extern "C" { #define HSI_VALUE (48000000U) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ +/** + * @brief Internal High Speed oscillator (HSI48) value for USB FS, SDMMC and RNG. + * This internal oscillator is mainly dedicated to provide a high precision clock to + * the USB peripheral by means of a special Clock Recovery System (CRS) circuitry. + * When the CRS is not used, the HSI48 RC oscillator runs on it default frequency + * which is subject to manufacturing process variations. + */ +#if !defined (HSI48_VALUE) +#define HSI48_VALUE 48000000U /*!< Value of the Internal High Speed oscillator for USB FS/SDMMC/RNG in Hz. + The real value my vary depending on manufacturing process variations.*/ +#endif /* HSI48_VALUE */ + /** * @brief Internal Low Speed oscillator (LSI) value. */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_cortex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_cortex.h index 9316a6fe3..026bdcd96 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_cortex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_cortex.h @@ -272,6 +272,8 @@ void HAL_SYSTICK_Callback(void); #if (__MPU_PRESENT == 1U) void HAL_MPU_Enable(uint32_t MPU_Control); void HAL_MPU_Disable(void); +void HAL_MPU_EnableRegion(uint32_t RegionNumber); +void HAL_MPU_DisableRegion(uint32_t RegionNumber); void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ /** @@ -332,6 +334,18 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); ((NUMBER) == MPU_REGION_NUMBER6) || \ ((NUMBER) == MPU_REGION_NUMBER7)) +#if defined(STM32C071xx) +#define IS_MPU_REGION_SIZE(SIZE) (((SIZE) == MPU_REGION_SIZE_256B) || \ + ((SIZE) == MPU_REGION_SIZE_512B) || \ + ((SIZE) == MPU_REGION_SIZE_1KB) || \ + ((SIZE) == MPU_REGION_SIZE_2KB) || \ + ((SIZE) == MPU_REGION_SIZE_4KB) || \ + ((SIZE) == MPU_REGION_SIZE_8KB) || \ + ((SIZE) == MPU_REGION_SIZE_16KB) || \ + ((SIZE) == MPU_REGION_SIZE_32KB) || \ + ((SIZE) == MPU_REGION_SIZE_64KB) || \ + ((SIZE) == MPU_REGION_SIZE_128KB)) +#else #define IS_MPU_REGION_SIZE(SIZE) (((SIZE) == MPU_REGION_SIZE_256B) || \ ((SIZE) == MPU_REGION_SIZE_512B) || \ ((SIZE) == MPU_REGION_SIZE_1KB) || \ @@ -340,7 +354,7 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); ((SIZE) == MPU_REGION_SIZE_8KB) || \ ((SIZE) == MPU_REGION_SIZE_16KB) || \ ((SIZE) == MPU_REGION_SIZE_32KB)) - +#endif /* STM32C071xx */ #define IS_MPU_SUB_REGION_DISABLE(SUBREGION) ((SUBREGION) < (uint16_t)0x00FFU) #endif /* __MPU_PRESENT */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_crc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_crc.h index cf4e879bc..a5d40690b 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_crc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_crc.h @@ -318,7 +318,7 @@ uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t /** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions * @{ */ -HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); +HAL_CRC_StateTypeDef HAL_CRC_GetState(const CRC_HandleTypeDef *hcrc); /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_def.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_def.h index fef30a8f6..d0000c912 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_def.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_def.h @@ -118,7 +118,7 @@ typedef enum #endif /* __GNUC__ */ -/* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ +/* Macro to align variable on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ /* GNU Compiler */ #if defined (__GNUC__) #ifndef __ALIGN_END @@ -172,7 +172,7 @@ typedef enum */ #define __RAM_FUNC __attribute__((section(".RamFunc"))) -#endif +#endif /* __CC_ARM */ /** * @brief __NOINLINE definition @@ -189,7 +189,7 @@ typedef enum */ #define __NOINLINE _Pragma("optimize = no_inline") -#endif +#endif /* __CC_ARM | __GNUC__ */ #ifdef __cplusplus diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma.h index 49485ac5b..a24e5b957 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma.h @@ -175,7 +175,6 @@ typedef struct __DMA_HandleTypeDef */ #define DMA_REQUEST_MEM2MEM 0U /*!< memory to memory transfer */ - #define DMA_REQUEST_GENERATOR0 1U /*!< DMAMUX request generator 0 */ #define DMA_REQUEST_GENERATOR1 2U /*!< DMAMUX request generator 1 */ #define DMA_REQUEST_GENERATOR2 3U /*!< DMAMUX request generator 2 */ @@ -183,14 +182,30 @@ typedef struct __DMA_HandleTypeDef #define DMA_REQUEST_ADC1 5U /*!< DMAMUX ADC1 request */ #define DMA_REQUEST_I2C1_RX 10U /*!< DMAMUX I2C1 RX request */ #define DMA_REQUEST_I2C1_TX 11U /*!< DMAMUX I2C1 TX request */ +#if defined(I2C2) +#define DMA_REQUEST_I2C2_RX 12U /*!< DMAMUX I2C2 RX request */ +#define DMA_REQUEST_I2C2_TX 13U /*!< DMAMUX I2C2 TX request */ +#endif /* I2C2 */ #define DMA_REQUEST_SPI1_RX 16U /*!< DMAMUX SPI1 RX request */ #define DMA_REQUEST_SPI1_TX 17U /*!< DMAMUX SPI1 TX request */ +#if defined(SPI2) +#define DMA_REQUEST_SPI2_RX 18U /*!< DMAMUX SPI2 RX request */ +#define DMA_REQUEST_SPI2_TX 19U /*!< DMAMUX SPI2 TX request */ +#endif /* SPI2 */ #define DMA_REQUEST_TIM1_CH1 20U /*!< DMAMUX TIM1 CH1 request */ #define DMA_REQUEST_TIM1_CH2 21U /*!< DMAMUX TIM1 CH2 request */ #define DMA_REQUEST_TIM1_CH3 22U /*!< DMAMUX TIM1 CH3 request */ #define DMA_REQUEST_TIM1_CH4 23U /*!< DMAMUX TIM1 CH4 request */ #define DMA_REQUEST_TIM1_TRIG_COM 24U /*!< DMAMUX TIM1 TRIG COM request */ #define DMA_REQUEST_TIM1_UP 25U /*!< DMAMUX TIM1 UP request */ +#if defined(TIM2) +#define DMA_REQUEST_TIM2_CH1 26U /*!< DMAMUX TIM2 CH1 request */ +#define DMA_REQUEST_TIM2_CH2 27U /*!< DMAMUX TIM2 CH2 request */ +#define DMA_REQUEST_TIM2_CH3 28U /*!< DMAMUX TIM2 CH3 request */ +#define DMA_REQUEST_TIM2_CH4 29U /*!< DMAMUX TIM2 CH4 request */ +#define DMA_REQUEST_TIM2_TRIG 30U /*!< DMAMUX TIM2 TRIG request */ +#define DMA_REQUEST_TIM2_UP 31U /*!< DMAMUX TIM2 UP request */ +#endif /* TIM2 */ #define DMA_REQUEST_TIM3_CH1 32U /*!< DMAMUX TIM3 CH1 request */ #define DMA_REQUEST_TIM3_CH2 33U /*!< DMAMUX TIM3 CH2 request */ #define DMA_REQUEST_TIM3_CH3 34U /*!< DMAMUX TIM3 CH3 request */ @@ -207,7 +222,6 @@ typedef struct __DMA_HandleTypeDef #define DMA_REQUEST_USART1_TX 51U /*!< DMAMUX USART1 TX request */ #define DMA_REQUEST_USART2_RX 52U /*!< DMAMUX USART2 RX request */ #define DMA_REQUEST_USART2_TX 53U /*!< DMAMUX USART2 TX request */ - /** * @} */ @@ -307,6 +321,18 @@ typedef struct __DMA_HandleTypeDef #define DMA_FLAG_TC3 DMA_ISR_TCIF3 #define DMA_FLAG_HT3 DMA_ISR_HTIF3 #define DMA_FLAG_TE3 DMA_ISR_TEIF3 +#if defined(DMA1_Channel4) +#define DMA_FLAG_GI4 DMA_ISR_GIF4 +#define DMA_FLAG_TC4 DMA_ISR_TCIF4 +#define DMA_FLAG_HT4 DMA_ISR_HTIF4 +#define DMA_FLAG_TE4 DMA_ISR_TEIF4 +#endif /* DMA1_Channel4 */ +#if defined(DMA1_Channel5) +#define DMA_FLAG_GI5 DMA_ISR_GIF5 +#define DMA_FLAG_TC5 DMA_ISR_TCIF5 +#define DMA_FLAG_HT5 DMA_ISR_HTIF5 +#define DMA_FLAG_TE5 DMA_ISR_TEIF5 +#endif /* DMA1_Channel5 */ /** * @} @@ -348,43 +374,76 @@ typedef struct __DMA_HandleTypeDef * @param __HANDLE__ DMA handle * @retval The specified transfer complete flag index. */ - +#if defined(DMA1_Channel5) +#define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ + (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ + DMA_FLAG_TC5) +#else #define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ DMA_FLAG_TC3) +#endif /* DMA1_Channel5 */ /** * @brief Return the current DMA Channel half transfer complete flag. * @param __HANDLE__ DMA handle * @retval The specified half transfer complete flag index. */ - +#if defined(DMA1_Channel5) +#define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ + (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ + DMA_FLAG_HT5) +#else #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ DMA_FLAG_HT3) - +#endif /* DMA1_Channel5 */ /** * @brief Return the current DMA Channel transfer error flag. * @param __HANDLE__ DMA handle * @retval The specified transfer error flag index. */ +#if defined(DMA1_Channel5) +#define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ + (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ + DMA_FLAG_TE5) +#else #define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ DMA_FLAG_TE3) +#endif /* DMA1_Channel5 */ /** * @brief Return the current DMA Channel Global interrupt flag. * @param __HANDLE__ DMA handle * @retval The specified transfer error flag index. */ +#if defined(DMA1_Channel5) +#define __HAL_DMA_GET_GI_FLAG_INDEX(__HANDLE__)\ + (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_GI1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_GI2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_GI3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_GI4 :\ + DMA_FLAG_GI5) +#else #define __HAL_DMA_GET_GI_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_GI1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_GI2 :\ - DMA_ISR_GIF3) + DMA_FLAG_GI3) +#endif /* DMA1_Channel5 */ /** * @brief Get the DMA Channel pending flags. @@ -395,7 +454,7 @@ typedef struct __DMA_HandleTypeDef * @arg DMA_FLAG_HTIFx: Half transfer complete flag * @arg DMA_FLAG_TEIFx: Transfer error flag * @arg DMA_FLAG_GIFx: Global interrupt flag - * Where x can be 1_3 to select the DMA Channel flag. + * Where x can be 1_5 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) @@ -409,7 +468,7 @@ typedef struct __DMA_HandleTypeDef * @arg DMA_FLAG_HTIFx: Half transfer complete flag * @arg DMA_FLAG_TEIFx: Transfer error flag * @arg DMA_FLAG_GIFx: Global interrupt flag - * Where x can be 1_3 to select the DMA Channel flag. + * Where x can be 1_5 to select the DMA Channel flag. * @retval None */ #define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR |= (__FLAG__)) diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma_ex.h index d74bdfbc3..cf45d5704 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_dma_ex.h @@ -65,7 +65,6 @@ typedef struct uint32_t RequestNumber; /*!< Specifies the number of DMA request that will be authorized after a sync event This parameter must be a number between Min_Data = 1 and Max_Data = 32 */ - } HAL_DMA_MuxSyncConfigTypeDef; @@ -116,6 +115,9 @@ typedef struct #define HAL_DMAMUX1_SYNC_DMAMUX1_CH0_EVT 16U /*!< Synchronization Signal is DMAMUX1 Channel0 Event */ #define HAL_DMAMUX1_SYNC_DMAMUX1_CH1_EVT 17U /*!< Synchronization Signal is DMAMUX1 Channel1 Event */ #define HAL_DMAMUX1_SYNC_DMAMUX1_CH2_EVT 18U /*!< Synchronization Signal is DMAMUX1 Channel2 Event */ +#if defined(STM32C071xx) +#define HAL_DMAMUX1_SYNC_DMAMUX1_CH3_EVT 19U /*!< Synchronization Signal is DMAMUX1 Channel3 Event */ +#endif /* STM32C071xx */ #define HAL_DMAMUX1_SYNC_TIM14_OC 22U /*!< Synchronization Signal is TIM14 OC */ /** @@ -129,7 +131,6 @@ typedef struct #define HAL_DMAMUX_SYNC_RISING DMAMUX_CxCR_SPOL_0 /*!< synchronize with rising edge events */ #define HAL_DMAMUX_SYNC_FALLING DMAMUX_CxCR_SPOL_1 /*!< synchronize with falling edge events */ #define HAL_DMAMUX_SYNC_RISING_FALLING DMAMUX_CxCR_SPOL /*!< synchronize with rising and falling edge events */ - /** * @} */ @@ -156,8 +157,10 @@ typedef struct #define HAL_DMAMUX1_REQ_GEN_DMAMUX1_CH0_EVT 16U /*!< Request generator Signal is DMAMUX1 Channel0 Event */ #define HAL_DMAMUX1_REQ_GEN_DMAMUX1_CH1_EVT 17U /*!< Request generator Signal is DMAMUX1 Channel1 Event */ #define HAL_DMAMUX1_REQ_GEN_DMAMUX1_CH2_EVT 18U /*!< Request generator Signal is DMAMUX1 Channel2 Event */ +#if defined(STM32C071xx) +#define HAL_DMAMUX1_REQ_GEN_DMAMUX1_CH3_EVT 19U /*!< Request generator Signal is DMAMUX1 Channel3 Event */ +#endif /* STM32C071xx */ #define HAL_DMAMUX1_REQ_GEN_TIM14_OC 22U /*!< Request generator Signal is TIM14 OC */ - /** * @} */ @@ -169,7 +172,6 @@ typedef struct #define HAL_DMAMUX_REQ_GEN_RISING DMAMUX_RGxCR_GPOL_0 /*!< generate request on rising edge events */ #define HAL_DMAMUX_REQ_GEN_FALLING DMAMUX_RGxCR_GPOL_1 /*!< generate request on falling edge events */ #define HAL_DMAMUX_REQ_GEN_RISING_FALLING DMAMUX_RGxCR_GPOL /*!< generate request on rising and falling edge events */ - /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_exti.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_exti.h index 35188bb5b..8f5b696d3 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_exti.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_exti.h @@ -119,6 +119,13 @@ typedef struct #define EXTI_LINE_29 (EXTI_RESERVED | EXTI_REG1 | 0x1DU) #define EXTI_LINE_30 (EXTI_RESERVED | EXTI_REG1 | 0x1EU) #define EXTI_LINE_31 (EXTI_DIRECT | EXTI_REG1 | 0x1FU) +#if defined(EXTI_IMR2_IM36) +#define EXTI_LINE_32 (EXTI_RESERVED | EXTI_REG2 | 0x00U) +#define EXTI_LINE_33 (EXTI_RESERVED | EXTI_REG2 | 0x01U) +#define EXTI_LINE_34 (EXTI_CONFIG | EXTI_REG2 | 0x02U) +#define EXTI_LINE_35 (EXTI_RESERVED | EXTI_REG2 | 0x03U) +#define EXTI_LINE_36 (EXTI_DIRECT | EXTI_REG2 | 0x04U) +#endif /* EXTI_IMR2_IM36 */ /** * @} */ @@ -151,9 +158,9 @@ typedef struct #define EXTI_GPIOA 0x00000000u #define EXTI_GPIOB 0x00000001u #define EXTI_GPIOC 0x00000002u -#if defined(STM32C031xx) +#if defined(GPIOD) #define EXTI_GPIOD 0x00000003u -#endif /* STM32C031xx */ +#endif /* GPIOD */ #define EXTI_GPIOF 0x00000005u /** * @} @@ -208,9 +215,11 @@ typedef struct /** * @brief EXTI Line number */ - +#if defined(EXTI_IMR2_IM36) +#define EXTI_LINE_NB 37uL +#else #define EXTI_LINE_NB 32uL - +#endif /* EXTI_IMR2_IM36 */ /** * @} */ @@ -236,18 +245,18 @@ typedef struct ((__EXTI_LINE__) == EXTI_TRIGGER_FALLING)) #define IS_EXTI_CONFIG_LINE(__EXTI_LINE__) (((__EXTI_LINE__) & EXTI_CONFIG) != 0x00U) -#if defined(STM32C031xx) +#if defined(GPIOD) #define IS_EXTI_GPIO_PORT(__PORT__) (((__PORT__) == EXTI_GPIOA) || \ ((__PORT__) == EXTI_GPIOB) || \ ((__PORT__) == EXTI_GPIOC) || \ ((__PORT__) == EXTI_GPIOD) || \ ((__PORT__) == EXTI_GPIOF)) -#elif defined(STM32C011xx) +#else #define IS_EXTI_GPIO_PORT(__PORT__) (((__PORT__) == EXTI_GPIOA) || \ ((__PORT__) == EXTI_GPIOB) || \ ((__PORT__) == EXTI_GPIOC) || \ ((__PORT__) == EXTI_GPIOF)) -#endif /* STM32C031xx */ +#endif /* GPIOD */ #define IS_EXTI_GPIO_PIN(__PIN__) ((__PIN__) < 16u) /** diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash.h index 2d0f376db..6e66e792c 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash.h @@ -280,18 +280,32 @@ typedef struct #define OB_USER_IWDG_STDBY FLASH_OPTR_IWDG_STDBY /*!< Independent watchdog counter freeze in standby mode */ #define OB_USER_WWDG_SW FLASH_OPTR_WWDG_SW /*!< Window watchdog selection */ +#if defined(FLASH_OPTR_HSE_NOT_REMAPPED) +#define OB_USER_HSE_NOT_REMAPPED FLASH_OPTR_HSE_NOT_REMAPPED /*!< Remap HSE source from PF to PC */ +#endif /* FLASH_OPTR_HSE_NOT_REMAPPED */ #define OB_USER_RAM_PARITY_CHECK FLASH_OPTR_RAM_PARITY_CHECK /*!< Sram parity check control */ +#define OB_USER_SECURE_MUXING_EN FLASH_OPTR_SECURE_MUXING_EN /*!< Multiple-bonding security enable */ #define OB_USER_NBOOT_SEL FLASH_OPTR_nBOOT_SEL /*!< Boot Selection */ #define OB_USER_NBOOT1 FLASH_OPTR_nBOOT1 /*!< nBoot1 configuration */ #define OB_USER_NBOOT0 FLASH_OPTR_nBOOT0 /*!< nBoot0 configuration */ #define OB_USER_NRST_MODE FLASH_OPTR_NRST_MODE /*!< Reset pin configuration */ #define OB_USER_INPUT_RESET_HOLDER FLASH_OPTR_IRHEN /*!< Internal reset holder enable */ +#if defined(FLASH_OPTR_HSE_NOT_REMAPPED) #define OB_USER_ALL (OB_USER_BOR_EN | OB_USER_BOR_LEV | OB_USER_NRST_STOP | \ OB_USER_NRST_STDBY | OB_USER_NRST_SHDW | OB_USER_IWDG_SW | \ OB_USER_IWDG_STOP | OB_USER_IWDG_STDBY | OB_USER_WWDG_SW | \ - OB_USER_RAM_PARITY_CHECK | OB_USER_NBOOT_SEL | OB_USER_NBOOT1 | \ + OB_USER_HSE_NOT_REMAPPED | OB_USER_RAM_PARITY_CHECK | \ + OB_USER_SECURE_MUXING_EN | OB_USER_NBOOT_SEL | OB_USER_NBOOT1 | \ OB_USER_NBOOT0 | OB_USER_NRST_MODE | OB_USER_INPUT_RESET_HOLDER) /*!< all option bits */ +#else +#define OB_USER_ALL (OB_USER_BOR_EN | OB_USER_BOR_LEV | OB_USER_NRST_STOP | \ + OB_USER_NRST_STDBY | OB_USER_NRST_SHDW | OB_USER_IWDG_SW | \ + OB_USER_IWDG_STOP | OB_USER_IWDG_STDBY | OB_USER_WWDG_SW | \ + OB_USER_RAM_PARITY_CHECK | OB_USER_SECURE_MUXING_EN | \ + OB_USER_NBOOT_SEL | OB_USER_NBOOT1 | \ + OB_USER_NBOOT0 | OB_USER_NRST_MODE | OB_USER_INPUT_RESET_HOLDER) /*!< all option bits */ +#endif /* FLASH_OPTR_HSE_NOT_REMAPPED */ /** * @} */ @@ -395,6 +409,17 @@ typedef struct * @} */ +#if defined(FLASH_OPTR_HSE_NOT_REMAPPED) +/** @defgroup FLASH_OB_USER_HSE_REMAP FLASH Option Bytes User HSE REMAP + * @{ + */ +#define OB_HSE_NOT_REMAPPED_ENABLE 0x00000000U /*!< HSE Remap enable */ +#define OB_HSE_NOT_REMAPPED_DISABLE FLASH_OPTR_HSE_NOT_REMAPPED /*!< HSE Remap disable */ +/** + * @} + */ +#endif /* FLASH_OPTR_HSE_NOT_REMAPPED */ + /** @defgroup FLASH_OB_USER_SRAM_PARITY FLASH Option Bytes User SRAM parity * @{ */ @@ -404,6 +429,15 @@ typedef struct * @} */ +/** @defgroup FLASH_OB_USER_SECURE_MUXING_EN FLASH Option Bytes User Multiple-bonding security + * @{ + */ +#define OB_SECURE_MUXING_ENABLE FLASH_OPTR_SECURE_MUXING_EN /*!< Multiple-bonding security enable */ +#define OB_SECURE_MUXING_DISABLE 0x00000000U /*!< Multiple-bonding security disable */ +/** + * @} + */ + /** @defgroup FLASH_OB_USER_nBOOT_SEL FLASH Option Bytes User Boot0 Selection * @{ */ @@ -692,17 +726,11 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); */ #define FLASH_SIZE_DATA_REGISTER FLASHSIZE_BASE -#define FLASH_SIZE ((((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0xFFFFU)) ? 0x8000U : \ - ((((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x0000U)) ? 0x8000U : \ - (((uint32_t)(*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) & (0x00FFU)) << 10U))) - #define FLASH_BANK_SIZE (FLASH_SIZE) /*!< FLASH Bank Size */ #define FLASH_PAGE_SIZE 0x00000800U /*!< FLASH Page Size, 2 KBytes */ - -#define FLASH_PAGE_NB 16U - +#define FLASH_PAGE_NB (FLASH_BANK_SIZE / FLASH_PAGE_SIZE) /*!< Number of pages per bank */ #define FLASH_TIMEOUT_VALUE 1000U /*!< FLASH Execution Timeout, 1 s */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash_ex.h index f201900df..558eea0f1 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_flash_ex.h @@ -62,7 +62,7 @@ extern "C" { /** @addtogroup FLASHEx_Exported_Functions_Group1 * @{ */ -HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError); +HAL_StatusTypeDef HAL_FLASHEx_Erase(const FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError); HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit); void HAL_FLASHEx_EnableDebugger(void); void HAL_FLASHEx_DisableDebugger(void); diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio.h index 61f4c1d23..635bf8cc9 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio.h @@ -263,7 +263,7 @@ typedef enum #define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) #define IS_GPIO_COMMON_PIN(__RESETMASK__, __SETMASK__) \ - (((uint32_t)(__RESETMASK__) & (uint32_t)(__SETMASK__)) == 0x00u) + (((uint32_t)(__RESETMASK__) & (uint32_t)(__SETMASK__)) == 0x00u) #define IS_GPIO_PIN(__PIN__) ((((uint32_t)(__PIN__) & GPIO_PIN_MASK) != 0x00u) &&\ (((uint32_t)(__PIN__) & ~GPIO_PIN_MASK) == 0x00u)) diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio_ex.h index e42a17033..0efd54d74 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_gpio_ex.h @@ -46,8 +46,6 @@ extern "C" { * @{ */ -#if defined(STM32C011xx) -/*------------------------- STM32C011xx --------------------------------------*/ /** * @brief AF 0 selection */ @@ -57,125 +55,21 @@ extern "C" { #define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< SPI1 Alternate Function mapping */ #define GPIO_AF0_I2S1 ((uint8_t)0x00) /*!< I2S1 Alternate Function mapping */ #define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< USART1 Alternate Function mapping */ - -/** - * @brief AF 1 selection - */ -#define GPIO_AF1_IR ((uint8_t)0x01) /*!< IR Alternate Function mapping */ -#define GPIO_AF1_OSC ((uint8_t)0x01) /*!< OSC (By pass and Enable) Alternate Function mapping */ -#define GPIO_AF1_TIM1 ((uint8_t)0x01) /*!< TIM1 Alternate Function mapping */ -#define GPIO_AF1_TIM3 ((uint8_t)0x01) /*!< TIM3 Alternate Function mapping */ -#define GPIO_AF1_USART1 ((uint8_t)0x01) /*!< USART1 Alternate Function mapping */ -#define GPIO_AF1_USART2 ((uint8_t)0x01) /*!< USART2 Alternate Function mapping */ - -/** - * @brief AF 2 selection - */ -#define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< TIM1 Alternate Function mapping */ -#define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< TIM16 Alternate Function mapping */ -#define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< TIM17 Alternate Function mapping */ - -/** - * @brief AF 3 selection - */ -#define GPIO_AF3_MCO2 ((uint8_t)0x03) /*!< MCO2 Alternate Function mapping */ -#define GPIO_AF3_TIM3 ((uint8_t)0x03) /*!< TIM3 Alternate Function mapping */ -/** - * @brief AF 4 selection - */ -#define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< TIM14 Alternate Function mapping */ -#define GPIO_AF4_USART2 ((uint8_t)0x04) /*!< USART2 Alternate Function mapping */ -#define GPIO_AF4_USART1 ((uint8_t)0x04) /*!< USART1 Alternate Function mapping */ - -/** - * @brief AF 5 selection - */ -#define GPIO_AF5_I2S ((uint8_t)0x05) /*!< I2S Alternate Function mapping */ -#define GPIO_AF5_USART1 ((uint8_t)0x05) /*!< USART1 Alternate Function mapping */ -#define GPIO_AF5_TIM1 ((uint8_t)0x05) /*!< TIM1 Alternate Function mapping */ -#define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< TIM16 Alternate Function mapping */ -#define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< TIM17 Alternate Function mapping */ - -/** - * @brief AF 6 selection - */ -#define GPIO_AF6_I2C1 ((uint8_t)0x06) /*!< I2C1 Alternate Function mapping */ - -/** - * @brief AF 7 selection - */ -#define GPIO_AF7_EVENTOUT ((uint8_t)0x07) /*!< EVENTOUT Alternate Function mapping */ -#define GPIO_AF7_I2C1 ((uint8_t)0x07) /*!< I2C1 Alternate Function mapping */ - -/** - * @brief AF 8 selection - */ -#define GPIO_AF8_I2S1 ((uint8_t)0x08) /*!< I2S1 Alternate Function mapping */ -#define GPIO_AF8_SPI1 ((uint8_t)0x08) /*!< SPI1 Alternate Function mapping */ -#define GPIO_AF8_IR ((uint8_t)0x08) /*!< IR Alternate Function mapping */ -/** - * @brief AF 9 selection - */ -#define GPIO_AF9_TIM1 ((uint8_t)0x09) /*!< TIM1 Alternate Function mapping */ -#define GPIO_AF9_USART2 ((uint8_t)0x09) /*!< USART2 Alternate Function mapping */ -#define GPIO_AF9_SPI1 ((uint8_t)0x09) /*!< SPI1 Alternate Function mapping */ -#define GPIO_AF9_I2S1 ((uint8_t)0x09) /*!< I2S1 Alternate Function mapping */ -/** - * @brief AF 10 selection - */ -#define GPIO_AF10_TIM1 ((uint8_t)0x0A) /*!< TIM1 Alternate Function mapping */ -#define GPIO_AF10_I2C1 ((uint8_t)0x0A) /*!< I2C1 Alternate Function mapping */ -#define GPIO_AF10_SPI1 ((uint8_t)0x0A) /*!< SPI1 Alternate Function mapping */ -#define GPIO_AF10_TIM16 ((uint8_t)0x0A) /*!< TIM16 Alternate Function mapping */ -#define GPIO_AF10_TIM17 ((uint8_t)0x0A) /*!< TIM17 Alternate Function mapping */ -/** - * @brief AF 11 selection - */ -#define GPIO_AF11_TIM1 ((uint8_t)0x0B) /*!< TIM1 Alternate Function mapping */ -#define GPIO_AF11_TIM3 ((uint8_t)0x0B) /*!< TIM3 Alternate Function mapping */ -#define GPIO_AF11_MCO2 ((uint8_t)0x0B) /*!< MCO2 Alternate Function mapping */ -/** - * @brief AF 12 selection - */ -#define GPIO_AF12_TIM3 ((uint8_t)0x0C) /*!< TIM3 Alternate Function mapping */ -#define GPIO_AF12_USART1 ((uint8_t)0x0C) /*!< USART1 Alternate Function mapping */ -/** - * @brief AF 13 selection - */ -#define GPIO_AF13_TIM14 ((uint8_t)0x0D) /*!< TIM14 Alternate Function mapping */ -#define GPIO_AF13_TIM3 ((uint8_t)0x0D) /*!< TIM3 Alternate Function mapping */ -/** - * @brief AF 14 selection - */ -#define GPIO_AF14_USART1 ((uint8_t)0x0E) /*!< USART1 Alternate Function mapping */ -#define GPIO_AF14_I2C1 ((uint8_t)0x0E) /*!< I2C1 Alternate Function mapping */ -#define GPIO_AF14_TIM16 ((uint8_t)0x0E) /*!< TIM16 Alternate Function mapping */ -/** - * @brief AF 15 selection - */ -#define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /*!< EVENTOUT Alternate Function mapping */ -#define GPIO_AF15_MCO2 ((uint8_t)0x0F) /*!< MCO2 Alternate Function mapping */ -#define GPIO_AF15_TIM17 ((uint8_t)0x0F) /*!< TIM17 Alternate Function mapping */ - -#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x0F) -#endif /* STM32C011xx */ - -#if defined(STM32C031xx) -/*------------------------- STM32C031xx --------------------------------------*/ -/** - * @brief AF 0 selection - */ +#if !defined(STM32C011xx) #define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /*!< EVENTOUT Alternate Function mapping */ #define GPIO_AF0_IR ((uint8_t)0x00) /*!< IR Alternate Function mapping */ -#define GPIO_AF0_MCO ((uint8_t)0x00) /*!< MCO (MCO1 and MCO2) Alternate Function mapping */ #define GPIO_AF0_OSC ((uint8_t)0x00) /*!< OSC (By pass and Enable) Alternate Function mapping */ -#define GPIO_AF0_OSC32 ((uint8_t)0x00) /*!< OSC32 (By pass and Enable) Alternate Function mapping */ -#define GPIO_AF0_SWJ ((uint8_t)0x00) /*!< SWJ (SWD) Alternate Function mapping */ -#define GPIO_AF0_SPI1 ((uint8_t)0x00) /*!< SPI1 Alternate Function mapping */ -#define GPIO_AF0_I2S1 ((uint8_t)0x00) /*!< I2S1 Alternate Function mapping */ #define GPIO_AF0_TIM14 ((uint8_t)0x00) /*!< TIM14 Alternate Function mapping */ -#define GPIO_AF0_USART1 ((uint8_t)0x00) /*!< USART1 Alternate Function mapping */ +#endif /* !STM32C011xx */ +#if defined(STM32C031xx) || defined(STM32C071xx) #define GPIO_AF0_USART2 ((uint8_t)0x00) /*!< USART2 Alternate Function mapping */ +#endif /* STM32C031xx | STM32C071xx */ +#if defined(SPI2) +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /*!< SPI2 Alternate Function mapping */ +#endif /* SPI2 */ +#if defined(CRS) +#define GPIO_AF0_CRS ((uint8_t)0x00) /*!< CRS Alternate Function mapping */ +#endif /* CRS */ /** * @brief AF 1 selection @@ -191,21 +85,39 @@ extern "C" { * @brief AF 2 selection */ #define GPIO_AF2_TIM1 ((uint8_t)0x02) /*!< TIM1 Alternate Function mapping */ +#if !defined(STM32C011xx) #define GPIO_AF2_TIM14 ((uint8_t)0x02) /*!< TIM14 Alternate Function mapping */ +#endif /* STM32C011xx */ #define GPIO_AF2_TIM16 ((uint8_t)0x02) /*!< TIM16 Alternate Function mapping */ #define GPIO_AF2_TIM17 ((uint8_t)0x02) /*!< TIM17 Alternate Function mapping */ +#if defined(USB_DRD_FS) +#define GPIO_AF2_USB ((uint8_t)0x02) /*!< USB Alternate Function mapping */ +#endif /* USB_DRD_FS */ /** * @brief AF 3 selection */ #define GPIO_AF3_MCO2 ((uint8_t)0x03) /*!< MCO2 Alternate Function mapping */ #define GPIO_AF3_TIM3 ((uint8_t)0x03) /*!< TIM3 Alternate Function mapping */ +#if defined(SPI2) +#define GPIO_AF3_SPI2 ((uint8_t)0x03) /*!< SPI2 Alternate Function mapping */ +#endif /* SPI2 */ +#if defined(TIM2) +#define GPIO_AF3_TIM2 ((uint8_t)0x03) /*!< TIM2 Alternate Function mapping */ +#endif /* TIM2 */ + /** * @brief AF 4 selection */ #define GPIO_AF4_TIM14 ((uint8_t)0x04) /*!< TIM14 Alternate Function mapping */ #define GPIO_AF4_USART2 ((uint8_t)0x04) /*!< USART2 Alternate Function mapping */ #define GPIO_AF4_USART1 ((uint8_t)0x04) /*!< USART1 Alternate Function mapping */ +#if defined(CRS) +#define GPIO_AF4_CRS ((uint8_t)0x04) /*!< CRS Alternate Function mapping */ +#endif /* CRS */ +#if defined(SPI2) +#define GPIO_AF4_SPI2 ((uint8_t)0x04) /*!< SPI2 Alternate Function mapping */ +#endif /* SPI2 */ /** * @brief AF 5 selection @@ -215,24 +127,48 @@ extern "C" { #define GPIO_AF5_TIM1 ((uint8_t)0x05) /*!< TIM1 Alternate Function mapping */ #define GPIO_AF5_TIM16 ((uint8_t)0x05) /*!< TIM16 Alternate Function mapping */ #define GPIO_AF5_TIM17 ((uint8_t)0x05) /*!< TIM17 Alternate Function mapping */ +#if defined(TIM2) +#define GPIO_AF5_TIM2 ((uint8_t)0x05) /*!< TIM2 Alternate Function mapping */ +#endif /* TIM2 */ +#if defined(SPI2) +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /*!< SPI2 Alternate Function mapping */ +#endif /* SPI2 */ +#if defined(I2C2) +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /*!< I2C2 Alternate Function mapping */ +#endif /* I2C2 */ /** * @brief AF 6 selection */ #define GPIO_AF6_I2C1 ((uint8_t)0x06) /*!< I2C1 Alternate Function mapping */ +#if defined(TIM2) +#define GPIO_AF6_TIM2 ((uint8_t)0x06) /*!< TIM2 Alternate Function mapping */ +#endif /* TIM2 */ +#if defined(SPI2) +#define GPIO_AF6_SPI2 ((uint8_t)0x06) /*!< SPI2 Alternate Function mapping */ +#endif /* SPI2 */ +#if defined(I2C2) +#define GPIO_AF6_I2C2 ((uint8_t)0x06) /*!< I2C2 Alternate Function mapping */ +#endif /* I2C2 */ +#if defined(USB_DRD_FS) +#define GPIO_AF6_USB ((uint8_t)0x06) /*!< USB Alternate Function mapping */ +#endif /* USB_DRD_FS */ /** * @brief AF 7 selection */ #define GPIO_AF7_EVENTOUT ((uint8_t)0x07) /*!< EVENTOUT Alternate Function mapping */ #define GPIO_AF7_I2C1 ((uint8_t)0x07) /*!< I2C1 Alternate Function mapping */ - /** * @brief AF 8 selection */ #define GPIO_AF8_I2S1 ((uint8_t)0x08) /*!< I2S1 Alternate Function mapping */ #define GPIO_AF8_SPI1 ((uint8_t)0x08) /*!< SPI1 Alternate Function mapping */ #define GPIO_AF8_IR ((uint8_t)0x08) /*!< IR Alternate Function mapping */ +#if defined(I2C2) +#define GPIO_AF8_I2C2 ((uint8_t)0x08) /*!< I2C2 Alternate Function mapping */ +#endif /* I2C2 */ + /** * @brief AF 9 selection */ @@ -240,6 +176,7 @@ extern "C" { #define GPIO_AF9_USART2 ((uint8_t)0x09) /*!< USART2 Alternate Function mapping */ #define GPIO_AF9_SPI1 ((uint8_t)0x09) /*!< SPI1 Alternate Function mapping */ #define GPIO_AF9_I2S1 ((uint8_t)0x09) /*!< I2S1 Alternate Function mapping */ + /** * @brief AF 10 selection */ @@ -248,37 +185,46 @@ extern "C" { #define GPIO_AF10_SPI1 ((uint8_t)0x0A) /*!< SPI1 Alternate Function mapping */ #define GPIO_AF10_TIM16 ((uint8_t)0x0A) /*!< TIM16 Alternate Function mapping */ #define GPIO_AF10_TIM17 ((uint8_t)0x0A) /*!< TIM17 Alternate Function mapping */ + /** * @brief AF 11 selection */ #define GPIO_AF11_TIM1 ((uint8_t)0x0B) /*!< TIM1 Alternate Function mapping */ #define GPIO_AF11_TIM3 ((uint8_t)0x0B) /*!< TIM3 Alternate Function mapping */ #define GPIO_AF11_MCO2 ((uint8_t)0x0B) /*!< MCO2 Alternate Function mapping */ + /** * @brief AF 12 selection */ #define GPIO_AF12_TIM3 ((uint8_t)0x0C) /*!< TIM3 Alternate Function mapping */ #define GPIO_AF12_USART1 ((uint8_t)0x0C) /*!< USART1 Alternate Function mapping */ +#if defined(STM32C071xx) +#define GPIO_AF12_SPI2 ((uint8_t)0x0C) /*!< SPI2 Alternate Function mapping */ +#endif /* STM32C071xx */ + /** * @brief AF 13 selection */ #define GPIO_AF13_TIM14 ((uint8_t)0x0D) /*!< TIM14 Alternate Function mapping */ #define GPIO_AF13_TIM3 ((uint8_t)0x0D) /*!< TIM3 Alternate Function mapping */ + /** * @brief AF 14 selection */ #define GPIO_AF14_USART1 ((uint8_t)0x0E) /*!< USART1 Alternate Function mapping */ #define GPIO_AF14_I2C1 ((uint8_t)0x0E) /*!< I2C1 Alternate Function mapping */ #define GPIO_AF14_TIM16 ((uint8_t)0x0E) /*!< TIM16 Alternate Function mapping */ + /** * @brief AF 15 selection */ #define GPIO_AF15_EVENTOUT ((uint8_t)0x0F) /*!< EVENTOUT Alternate Function mapping */ #define GPIO_AF15_MCO2 ((uint8_t)0x0F) /*!< MCO2 Alternate Function mapping */ +#if defined(STM32C011xx) || defined(STM32C031xx) || defined(STM32C071xx) #define GPIO_AF15_TIM17 ((uint8_t)0x0F) /*!< TIM17 Alternate Function mapping */ - +#endif /* STM32C011xx | STM32C031xx | STM32C071xx */ #define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x0F) -#endif /* STM32C031xx */ + /** * @} */ @@ -295,18 +241,18 @@ extern "C" { /** @defgroup GPIOEx_Get_Port_Index GPIOEx Get Port Index * @{ */ -#if defined(STM32C011xx) +#if defined(GPIOD) #define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0UL :\ ((__GPIOx__) == (GPIOB))? 1UL :\ ((__GPIOx__) == (GPIOC))? 2UL :\ + ((__GPIOx__) == (GPIOD))? 3UL :\ ((__GPIOx__) == (GPIOF))? 5UL : 6UL) -#elif defined(STM32C031xx) +#else #define GPIO_GET_INDEX(__GPIOx__) (((__GPIOx__) == (GPIOA))? 0UL :\ ((__GPIOx__) == (GPIOB))? 1UL :\ ((__GPIOx__) == (GPIOC))? 2UL :\ - ((__GPIOx__) == (GPIOD))? 3UL :\ ((__GPIOx__) == (GPIOF))? 5UL : 6UL) -#endif /* STM32C011xx */ +#endif /* GPIOD */ /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_hcd.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_hcd.h new file mode 100644 index 000000000..f853e297e --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_hcd.h @@ -0,0 +1,602 @@ +/** + ****************************************************************************** + * @file stm32c0xx_hal_hcd.h + * @author MCD Application Team + * @brief Header file of HCD HAL module. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32C0xx_HAL_HCD_H +#define STM32C0xx_HAL_HCD_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_ll_usb.h" + +#if defined (USB_DRD_FS) +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +/** @addtogroup HCD HCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup HCD_Exported_Types HCD Exported Types + * @{ + */ + +/** @defgroup HCD_Exported_Types_Group1 HCD State Structure definition + * @{ + */ +typedef enum +{ + HAL_HCD_STATE_RESET = 0x00, + HAL_HCD_STATE_READY = 0x01, + HAL_HCD_STATE_ERROR = 0x02, + HAL_HCD_STATE_BUSY = 0x03, + HAL_HCD_STATE_TIMEOUT = 0x04 +} HCD_StateTypeDef; + +typedef USB_DRD_TypeDef HCD_TypeDef; +typedef USB_DRD_CfgTypeDef HCD_InitTypeDef; +typedef USB_DRD_HCTypeDef HCD_HCTypeDef; +typedef USB_DRD_URBStateTypeDef HCD_URBStateTypeDef; +typedef USB_DRD_HCStateTypeDef HCD_HCStateTypeDef; + +typedef enum +{ + HCD_HCD_STATE_DISCONNECTED = 0x00U, + HCD_HCD_STATE_CONNECTED = 0x01U, + HCD_HCD_STATE_RESETED = 0x02U, + HCD_HCD_STATE_RUN = 0x03U, + HCD_HCD_STATE_SUSPEND = 0x04U, + HCD_HCD_STATE_RESUME = 0x05U, +} HCD_HostStateTypeDef; + +/* PMA lookup Table size depending on PMA Size + * 8Bytes each Block 32Bit in each word + */ +#define PMA_BLOCKS ((USB_DRD_PMA_SIZE) / (8U * 32U)) + +/** + * @} + */ + +/** @defgroup HCD_Exported_Types_Group2 HCD Handle Structure definition + * @{ + */ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) +typedef struct __HCD_HandleTypeDef +#else +typedef struct +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ +{ + HCD_TypeDef *Instance; /*!< Register base address */ + HCD_InitTypeDef Init; /*!< HCD required parameters */ + HCD_HCTypeDef hc[16]; /*!< Host channels parameters */ + + uint32_t ep0_PmaAllocState; /*!< EP0 PMA allocation State (allocated, virtual Ch, EP0 direction) */ + uint16_t phy_chin_state[8]; /*!< Physical Channel in State (Used/Free) */ + uint16_t phy_chout_state[8]; /*!< Physical Channel out State (Used/Free)*/ + uint32_t PMALookupTable[PMA_BLOCKS]; /*PMA LookUp Table */ + HCD_HostStateTypeDef HostState; /*!< USB current state DICONNECT/CONNECT/RUN/SUSPEND/RESUME */ + + HAL_LockTypeDef Lock; /*!< HCD peripheral status */ + __IO HCD_StateTypeDef State; /*!< HCD communication state */ + __IO uint32_t ErrorCode; /*!< HCD Error code */ + void *pData; /*!< Pointer Stack Handler */ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + void (* SOFCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD SOF callback */ + void (* ConnectCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Connect callback */ + void (* DisconnectCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Disconnect callback */ + void (* PortEnabledCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Port Enable callback */ + void (* PortDisabledCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Port Disable callback */ + void (* HC_NotifyURBChangeCallback)(struct __HCD_HandleTypeDef *hhcd, uint8_t chnum, + HCD_URBStateTypeDef urb_state); /*!< USB OTG HCD Host Channel Notify URB Change callback */ + + void (* MspInitCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Msp Init callback */ + void (* MspDeInitCallback)(struct __HCD_HandleTypeDef *hhcd); /*!< USB OTG HCD Msp DeInit callback */ +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ +} HCD_HandleTypeDef; +/** + * @} + */ + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup HCD_Exported_Constants HCD Exported Constants + * @{ + */ + +/** @defgroup HCD_Speed HCD Speed + * @{ + */ +#define HCD_SPEED_FULL USBH_FSLS_SPEED +#define HCD_SPEED_LOW USBH_FSLS_SPEED +/** + * @} + */ + +/** @defgroup HCD_Device_Speed HCD Device Speed + * @{ + */ +#define HCD_DEVICE_SPEED_HIGH 0U +#define HCD_DEVICE_SPEED_FULL 1U +#define HCD_DEVICE_SPEED_LOW 2U +/** + * @} + */ + +/** @defgroup HCD_PHY_Module HCD PHY Module + * @{ + */ +#define HCD_PHY_ULPI 1U +#define HCD_PHY_EMBEDDED 2U +/** + * @} + */ + +/** @defgroup HCD_Error_Code_definition HCD Error Code definition + * @brief HCD Error Code definition + * @{ + */ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) +#define HAL_HCD_ERROR_INVALID_CALLBACK (0x00000010U) /*!< Invalid Callback error */ +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup HCD_Exported_Macros HCD Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +#define __HAL_HCD_ENABLE(__HANDLE__) (void)USB_EnableGlobalInt ((__HANDLE__)->Instance) +#define __HAL_HCD_DISABLE(__HANDLE__) (void)USB_DisableGlobalInt ((__HANDLE__)->Instance) + +#define __HAL_HCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance)\ + & (__INTERRUPT__)) == (__INTERRUPT__)) +#define __HAL_HCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->ISTR) &= ~(__INTERRUPT__)) +#define __HAL_HCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0U) + +#define __HAL_HCD_GET_CHNUM(__HANDLE__) (((__HANDLE__)->Instance->ISTR) & USB_ISTR_IDN) +#define __HAL_HCD_GET_CHDIR(__HANDLE__) (((__HANDLE__)->Instance->ISTR) & USB_ISTR_DIR) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup HCD_Exported_Functions HCD Exported Functions + * @{ + */ + +/** @defgroup HCD_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd); +HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd); +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 HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num); + +HAL_StatusTypeDef HAL_HCD_HC_Close(HCD_HandleTypeDef *hhcd, uint8_t ch_num); + +void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd); +void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd); + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) +/** @defgroup HAL_HCD_Callback_ID_enumeration_definition HAL USB OTG HCD Callback ID enumeration definition + * @brief HAL USB OTG HCD Callback ID enumeration definition + * @{ + */ +typedef enum +{ + HAL_HCD_SOF_CB_ID = 0x01, /*!< USB HCD SOF callback ID */ + HAL_HCD_CONNECT_CB_ID = 0x02, /*!< USB HCD Connect callback ID */ + HAL_HCD_DISCONNECT_CB_ID = 0x03, /*!< USB HCD Disconnect callback ID */ + HAL_HCD_PORT_ENABLED_CB_ID = 0x04, /*!< USB HCD Port Enable callback ID */ + HAL_HCD_PORT_DISABLED_CB_ID = 0x05, /*!< USB HCD Port Disable callback ID */ + + HAL_HCD_MSPINIT_CB_ID = 0x06, /*!< USB HCD MspInit callback ID */ + HAL_HCD_MSPDEINIT_CB_ID = 0x07 /*!< USB HCD MspDeInit callback ID */ + +} HAL_HCD_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup HAL_HCD_Callback_pointer_definition HAL USB OTG HCD Callback pointer definition + * @brief HAL USB OTG HCD Callback pointer definition + * @{ + */ + +typedef void (*pHCD_CallbackTypeDef)(HCD_HandleTypeDef *hhcd); /*!< pointer to a common USB OTG HCD callback function */ +typedef void (*pHCD_HC_NotifyURBChangeCallbackTypeDef)(HCD_HandleTypeDef *hhcd, + uint8_t epnum, + HCD_URBStateTypeDef urb_state); /*!< pointer to USB OTG HCD host channel callback */ +/** + * @} + */ + +HAL_StatusTypeDef HAL_HCD_RegisterCallback(HCD_HandleTypeDef *hhcd, + HAL_HCD_CallbackIDTypeDef CallbackID, + pHCD_CallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_HCD_UnRegisterCallback(HCD_HandleTypeDef *hhcd, + HAL_HCD_CallbackIDTypeDef CallbackID); + +HAL_StatusTypeDef HAL_HCD_RegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd, + pHCD_HC_NotifyURBChangeCallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_HCD_UnRegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* I/O operation functions ***************************************************/ +/** @addtogroup HCD_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +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); + +HAL_StatusTypeDef HAL_HCD_HC_SetHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t addr, uint8_t PortNbr); + +HAL_StatusTypeDef HAL_HCD_HC_ClearHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num); + +/* Non-Blocking mode: Interrupt */ +void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd); +void HAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd); +void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd); +void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd); +void HAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd); +void HAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd); + +void HAL_HCD_SuspendCallback(HCD_HandleTypeDef *hhcd); +void HAL_HCD_ResumeCallback(HCD_HandleTypeDef *hhcd); + +void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, + HCD_URBStateTypeDef urb_state); +/** + * @} + */ + +/* Peripheral Control functions **********************************************/ +/** @addtogroup HCD_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd); +HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd); +HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd); + +HAL_StatusTypeDef HAL_HCD_Suspend(HCD_HandleTypeDef *hhcd); +HAL_StatusTypeDef HAL_HCD_Resume(HCD_HandleTypeDef *hhcd); +HAL_StatusTypeDef HAL_HCD_ResumePort(HCD_HandleTypeDef *hhcd); + +/** + * @} + */ + +/* Peripheral State functions ************************************************/ +/** @addtogroup HCD_Exported_Functions_Group4 Peripheral State functions + * @{ + */ +HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef const *hhcd); +HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef const *hhcd, uint8_t chnum); +HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef const *hhcd, uint8_t chnum); +uint32_t HAL_HCD_HC_GetXferCount(HCD_HandleTypeDef const *hhcd, uint8_t chnum); +uint32_t HAL_HCD_GetCurrentFrame(HCD_HandleTypeDef *hhcd); +uint32_t HAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd); + + +/* PMA Allocation functions **********************************************/ +/** @addtogroup PMA Allocation + * @{ + */ +HAL_StatusTypeDef HAL_HCD_PMAlloc(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint16_t ch_kind, uint16_t mps); + +HAL_StatusTypeDef HAL_HCD_PMADeAlloc(HCD_HandleTypeDef *hhcd, uint8_t ch_num); +HAL_StatusTypeDef HAL_HCD_PMAReset(HCD_HandleTypeDef *hhcd); + +/** + * @} + */ + + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup HCD_Private_Macros HCD Private Macros + * @{ + */ + +#define HCD_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define HCD_MAX(a, b) (((a) > (b)) ? (a) : (b)) + +/** @defgroup HCD_LOGICAL_CHANNEL HCD Logical Channel + * @{ + */ +#define HCD_LOGICAL_CH_NOT_OPENED 0xFFU +#define HCD_FREE_CH_NOT_FOUND 0xFFU +/** + * @} + */ + +/** @defgroup HCD_ENDP_Kind HCD Endpoint Kind + * @{ + */ +#define HCD_SNG_BUF 0U +#define HCD_DBL_BUF 1U +/** + * @} + */ + +/* Powerdown exit count */ +#define HCD_PDWN_EXIT_CNT 0x100U + +/* Set Channel */ +#define HCD_SET_CHANNEL USB_DRD_SET_CHEP + +/* Get Channel Register */ +#define HCD_GET_CHANNEL USB_DRD_GET_CHEP + + +/** + * @brief free buffer used from the application realizing it to the line + * toggles bit SW_BUF in the double buffered endpoint register + * @param USBx USB device. + * @param bChNum, bDir + * @retval None + */ +#define HCD_FREE_USER_BUFFER USB_DRD_FREE_USER_BUFFER + +/** + * @brief Set the Setup bit in the corresponding channel, when a Setup + transaction is needed. + * @param USBx USB device. + * @param bChNum + * @retval None + */ +#define HAC_SET_CH_TX_SETUP USB_DRD_CHEP_TX_SETUP + +/** + * @brief sets the status for tx transfer (bits STAT_TX[1:0]). + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @param wState new state + * @retval None + */ +#define HCD_SET_CH_TX_STATUS USB_DRD_SET_CHEP_TX_STATUS + +/** + * @brief sets the status for rx transfer (bits STAT_TX[1:0]) + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @param wState new state + * @retval None + */ +#define HCD_SET_CH_RX_STATUS USB_DRD_SET_CHEP_RX_STATUS +/** + * @brief gets the status for tx/rx transfer (bits STAT_TX[1:0] + * /STAT_RX[1:0]) + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval status + */ +#define HCD_GET_CH_TX_STATUS USB_DRD_GET_CHEP_TX_STATUS +#define HCD_GET_CH_RX_STATUS USB_DRD_GET_CHEP_RX_STATUS +/** + * @brief Sets/clears CH_KIND bit in the Channel register. + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define HCD_SET_CH_KIND USB_DRD_SET_CH_KIND +#define HCD_CLEAR_CH_KIND USB_DRD_CLEAR_CH_KIND +#define HCD_SET_BULK_CH_DBUF HCD_SET_CH_KIND +#define HCD_CLEAR_BULK_CH_DBUF HCD_CLEAR_CH_KIND + +/** + * @brief Clears bit ERR_RX in the Channel register + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define HCD_CLEAR_RX_CH_ERR USB_DRD_CLEAR_CHEP_RX_ERR + +/** + * @brief Clears bit ERR_TX in the Channel register + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define HCD_CLEAR_TX_CH_ERR USB_DRD_CLEAR_CHEP_TX_ERR +/** + * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define HCD_CLEAR_RX_CH_CTR USB_DRD_CLEAR_RX_CHEP_CTR +#define HCD_CLEAR_TX_CH_CTR USB_DRD_CLEAR_TX_CHEP_CTR + +/** + * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define HCD_RX_DTOG USB_DRD_RX_DTOG +#define HCD_TX_DTOG USB_DRD_TX_DTOG +/** + * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define HCD_CLEAR_RX_DTOG USB_DRD_CLEAR_RX_DTOG +#define HCD_CLEAR_TX_DTOG USB_DRD_CLEAR_TX_DTOG + +/** + * @brief sets counter for the tx/rx buffer. + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @param wCount Counter value. + * @retval None + */ +#define HCD_SET_CH_TX_CNT USB_DRD_SET_CHEP_TX_CNT +#define HCD_SET_CH_RX_CNT USB_DRD_SET_CHEP_RX_CNT + +/** + * @brief gets counter of the tx buffer. + * @param USBx USB peripheral instance register address. + * @param bChNum channel Number. + * @retval Counter value + */ +#define HCD_GET_CH_TX_CNT USB_DRD_GET_CHEP_TX_CNT + +/** + * @brief gets counter of the rx buffer. + * @param Instance USB peripheral instance register address. + * @param bChNum channel Number. + * @retval Counter value + */ +__STATIC_INLINE uint16_t HCD_GET_CH_RX_CNT(HCD_TypeDef *Instance, uint16_t bChNum) +{ + uint32_t HostCoreSpeed; + uint32_t ep_reg = USB_DRD_GET_CHEP(Instance, bChNum); + __IO uint32_t count = 10U; + + /* Get Host core Speed */ + HostCoreSpeed = USB_GetHostSpeed(Instance); + + /* Count depends on device LS */ + if ((HostCoreSpeed == USB_DRD_SPEED_LS) || ((ep_reg & USB_CHEP_LSEP) == USB_CHEP_LSEP)) + { + count = (70U * (HAL_RCC_GetHCLKFreq() / 1000000U)) / 100U; + } + + if (count > 15U) + { + count = HCD_MAX(10U, (count - 15U)); + } + + /* WA: few cycles for RX PMA descriptor to update */ + while (count > 0U) + { + count--; + } + + return (uint16_t)USB_DRD_GET_CHEP_RX_CNT((Instance), (bChNum)); +} + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @param bDir endpoint dir EP_DBUF_OUT = OUT + * EP_DBUF_IN = IN + * @param wCount: Counter value + * @retval None + */ +#define HCD_SET_CH_DBUF0_CNT USB_DRD_SET_CHEP_DBUF0_CNT +#define HCD_SET_CH_DBUF1_CNT USB_DRD_SET_CHEP_DBUF1_CNT +#define HCD_SET_CH_DBUF_CNT USB_DRD_SET_CHEP_DBUF_CNT + + +/** + * @brief gets counter of the rx buffer0. + * @param Instance USB peripheral instance register address. + * @param bChNum channel Number. + * @retval Counter value + */ +__STATIC_INLINE uint16_t HCD_GET_CH_DBUF0_CNT(const HCD_TypeDef *Instance, uint16_t bChNum) +{ + UNUSED(Instance); + __IO uint32_t count = 10U; + + /* WA: few cycles for RX PMA descriptor to update */ + while (count > 0U) + { + count--; + } + + return (uint16_t)USB_DRD_GET_CHEP_DBUF0_CNT((Instance), (bChNum)); +} + +/** + * @brief gets counter of the rx buffer1. + * @param Instance USB peripheral instance register address. + * @param bChNum channel Number. + * @retval Counter value + */ +__STATIC_INLINE uint16_t HCD_GET_CH_DBUF1_CNT(const HCD_TypeDef *Instance, uint16_t bChNum) +{ + UNUSED(Instance); + __IO uint32_t count = 10U; + + /* WA: few cycles for RX PMA descriptor to update */ + while (count > 0U) + { + count--; + } + + return (uint16_t)USB_DRD_GET_CHEP_DBUF1_CNT((Instance), (bChNum)); +} + + +/** + * @} + */ +/* Private functions prototypes ----------------------------------------------*/ + +/** + * @} + */ +/** + * @} + */ +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32C0xx_HAL_HCD_H */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c.h index 446944221..6e9157e9e 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c.h @@ -118,8 +118,6 @@ typedef enum HAL_I2C_STATE_BUSY_RX_LISTEN = 0x2AU, /*!< Address Listen Mode and Data Reception process is ongoing */ HAL_I2C_STATE_ABORT = 0x60U, /*!< Abort user request ongoing */ - HAL_I2C_STATE_TIMEOUT = 0xA0U, /*!< Timeout state */ - HAL_I2C_STATE_ERROR = 0xE0U /*!< Error */ } HAL_I2C_StateTypeDef; diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c_ex.h index 7979bd0da..ca4dbcf3e 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_i2c_ex.h @@ -65,7 +65,17 @@ extern "C" { #define I2C_FASTMODEPLUS_PB8 (uint32_t)(0x00000010U | I2C_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus PB8 not supported */ #define I2C_FASTMODEPLUS_PB9 (uint32_t)(0x00000012U | I2C_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus PB9 not supported */ #endif /* SYSCFG_CFGR1_I2C_PB8_FMP */ +#if defined(SYSCFG_CFGR1_I2C_PC14_FMP) +#define I2C_FASTMODEPLUS_PC14 SYSCFG_CFGR1_I2C_PC14_FMP /*!< Enable Fast Mode Plus on PC14 */ +#else +#define I2C_FASTMODEPLUS_PC14 (uint32_t)(0x00000014U | I2C_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus PC14 not supported */ +#endif /* SYSCFG_CFGR1_I2C_PC14_FMP */ #define I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C1_FMP /*!< Enable Fast Mode Plus on I2C1 pins */ +#if defined(SYSCFG_CFGR1_I2C2_FMP) +#define I2C_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C2_FMP /*!< Enable Fast Mode Plus on I2C2 pins */ +#else +#define I2C_FASTMODEPLUS_I2C2 (uint32_t)(0x00000200U | I2C_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus I2C2 not supported */ +#endif /* SYSCFG_CFGR1_I2C2_FMP */ /** * @} */ @@ -97,6 +107,7 @@ HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_ /** * @} */ +#if defined(I2C_CR1_WUPEN) /** @addtogroup I2CEx_Exported_Functions_Group2 WakeUp Mode Functions * @{ @@ -106,6 +117,7 @@ HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp(I2C_HandleTypeDef *hi2c); /** * @} */ +#endif /* I2C_CR1_WUPEN */ /** @addtogroup I2CEx_Exported_Functions_Group3 Fast Mode Plus Functions * @{ @@ -144,7 +156,9 @@ void HAL_I2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus); (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9) || \ - (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1)) + (((__CONFIG__) & (I2C_FASTMODEPLUS_PC14)) == I2C_FASTMODEPLUS_PC14) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C2)) == I2C_FASTMODEPLUS_I2C2)) /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_iwdg.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_iwdg.h index 4f8b3f1f2..2eb7fbc0c 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_iwdg.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_iwdg.h @@ -235,4 +235,3 @@ HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); #endif #endif /* STM32C0xx_HAL_IWDG_H */ - diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd.h new file mode 100644 index 000000000..ce10c814e --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd.h @@ -0,0 +1,629 @@ +/** + ****************************************************************************** + * @file stm32c0xx_hal_pcd.h + * @author MCD Application Team + * @brief Header file of PCD HAL module. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32C0xx_HAL_PCD_H +#define STM32C0xx_HAL_PCD_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_ll_usb.h" + +#if defined (USB_DRD_FS) + +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup PCD_Exported_Types PCD Exported Types + * @{ + */ + +/** + * @brief PCD State structure definition + */ +typedef enum +{ + HAL_PCD_STATE_RESET = 0x00, + HAL_PCD_STATE_READY = 0x01, + HAL_PCD_STATE_ERROR = 0x02, + HAL_PCD_STATE_BUSY = 0x03, + HAL_PCD_STATE_TIMEOUT = 0x04 +} PCD_StateTypeDef; + +/* Device LPM suspend state */ +typedef enum +{ + LPM_L0 = 0x00, /* on */ + LPM_L1 = 0x01, /* LPM L1 sleep */ + LPM_L2 = 0x02, /* suspend */ + LPM_L3 = 0x03, /* off */ +} PCD_LPM_StateTypeDef; + +typedef enum +{ + PCD_LPM_L0_ACTIVE = 0x00, /* on */ + PCD_LPM_L1_ACTIVE = 0x01, /* LPM L1 sleep */ +} PCD_LPM_MsgTypeDef; + +typedef enum +{ + PCD_BCD_ERROR = 0xFF, + PCD_BCD_CONTACT_DETECTION = 0xFE, + PCD_BCD_STD_DOWNSTREAM_PORT = 0xFD, + PCD_BCD_CHARGING_DOWNSTREAM_PORT = 0xFC, + PCD_BCD_DEDICATED_CHARGING_PORT = 0xFB, + PCD_BCD_DISCOVERY_COMPLETED = 0x00, + +} PCD_BCD_MsgTypeDef; + +typedef USB_DRD_TypeDef PCD_TypeDef; +typedef USB_DRD_CfgTypeDef PCD_InitTypeDef; +typedef USB_DRD_EPTypeDef PCD_EPTypeDef; + +/** + * @brief PCD Handle Structure definition + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +typedef struct __PCD_HandleTypeDef +#else +typedef struct +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + PCD_TypeDef *Instance; /*!< Register base address */ + PCD_InitTypeDef Init; /*!< PCD required parameters */ + __IO uint8_t USB_Address; /*!< USB Address */ + PCD_EPTypeDef IN_ep[8]; /*!< IN endpoint parameters */ + PCD_EPTypeDef OUT_ep[8]; /*!< OUT endpoint parameters */ + HAL_LockTypeDef Lock; /*!< PCD peripheral status */ + __IO PCD_StateTypeDef State; /*!< PCD communication state */ + __IO uint32_t ErrorCode; /*!< PCD Error code */ + uint32_t Setup[12]; /*!< Setup packet buffer */ + PCD_LPM_StateTypeDef LPM_State; /*!< LPM State */ + uint32_t BESL; + + + uint32_t lpm_active; /*!< Enable or disable the Link Power Management . + This parameter can be set to ENABLE or DISABLE */ + + uint32_t battery_charging_active; /*!< Enable or disable Battery charging. + This parameter can be set to ENABLE or DISABLE */ + void *pData; /*!< Pointer to upper stack Handler */ + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + void (* SOFCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD SOF callback */ + void (* SetupStageCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Setup Stage callback */ + void (* ResetCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Reset callback */ + void (* SuspendCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Suspend callback */ + void (* ResumeCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Resume callback */ + void (* ConnectCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Connect callback */ + void (* DisconnectCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Disconnect callback */ + + void (* DataOutStageCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD Data OUT Stage callback */ + void (* DataInStageCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD Data IN Stage callback */ + void (* ISOOUTIncompleteCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD ISO OUT Incomplete callback */ + void (* ISOINIncompleteCallback)(struct __PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< USB OTG PCD ISO IN Incomplete callback */ + void (* BCDCallback)(struct __PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg); /*!< USB OTG PCD BCD callback */ + void (* LPMCallback)(struct __PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); /*!< USB OTG PCD LPM callback */ + + void (* MspInitCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Msp Init callback */ + void (* MspDeInitCallback)(struct __PCD_HandleTypeDef *hpcd); /*!< USB OTG PCD Msp DeInit callback */ +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +} PCD_HandleTypeDef; + +/** + * @} + */ + +/* Include PCD HAL Extended module */ +#include "stm32c0xx_hal_pcd_ex.h" + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Constants PCD Exported Constants + * @{ + */ + +/** @defgroup PCD_Speed PCD Speed + * @{ + */ +#define PCD_SPEED_FULL USBD_FS_SPEED +/** + * @} + */ + +/** @defgroup PCD_PHY_Module PCD PHY Module + * @{ + */ +#define PCD_PHY_ULPI 1U +#define PCD_PHY_EMBEDDED 2U +#define PCD_PHY_UTMI 3U +/** + * @} + */ + +/** @defgroup PCD_Error_Code_definition PCD Error Code definition + * @brief PCD Error Code definition + * @{ + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +#define HAL_PCD_ERROR_INVALID_CALLBACK (0x00000010U) /*!< Invalid Callback error */ +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup PCD_Exported_Macros PCD Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +#define __HAL_PCD_ENABLE(__HANDLE__) (void)USB_EnableGlobalInt ((__HANDLE__)->Instance) +#define __HAL_PCD_DISABLE(__HANDLE__) (void)USB_DisableGlobalInt ((__HANDLE__)->Instance) + +#define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) \ + ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) + + +#define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->ISTR)\ + &= (uint16_t)(~(__INTERRUPT__))) + +#define __HAL_USB_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR2 |= USB_WAKEUP_EXTI_LINE +#define __HAL_USB_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR2 &= ~(USB_WAKEUP_EXTI_LINE) + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PCD_Exported_Functions PCD Exported Functions + * @{ + */ + +/* Initialization/de-initialization functions ********************************/ +/** @addtogroup PCD_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd); +void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); +void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +/** @defgroup HAL_PCD_Callback_ID_enumeration_definition HAL USB OTG PCD Callback ID enumeration definition + * @brief HAL USB OTG PCD Callback ID enumeration definition + * @{ + */ +typedef enum +{ + HAL_PCD_SOF_CB_ID = 0x01, /*!< USB PCD SOF callback ID */ + HAL_PCD_SETUPSTAGE_CB_ID = 0x02, /*!< USB PCD Setup Stage callback ID */ + HAL_PCD_RESET_CB_ID = 0x03, /*!< USB PCD Reset callback ID */ + HAL_PCD_SUSPEND_CB_ID = 0x04, /*!< USB PCD Suspend callback ID */ + HAL_PCD_RESUME_CB_ID = 0x05, /*!< USB PCD Resume callback ID */ + HAL_PCD_CONNECT_CB_ID = 0x06, /*!< USB PCD Connect callback ID */ + HAL_PCD_DISCONNECT_CB_ID = 0x07, /*!< USB PCD Disconnect callback ID */ + + HAL_PCD_MSPINIT_CB_ID = 0x08, /*!< USB PCD MspInit callback ID */ + HAL_PCD_MSPDEINIT_CB_ID = 0x09 /*!< USB PCD MspDeInit callback ID */ + +} HAL_PCD_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup HAL_PCD_Callback_pointer_definition HAL USB OTG PCD Callback pointer definition + * @brief HAL USB OTG PCD Callback pointer definition + * @{ + */ + +typedef void (*pPCD_CallbackTypeDef)(PCD_HandleTypeDef *hpcd); /*!< pointer to a common USB OTG PCD callback function */ +typedef void (*pPCD_DataOutStageCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD Data OUT Stage callback */ +typedef void (*pPCD_DataInStageCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD Data IN Stage callback */ +typedef void (*pPCD_IsoOutIncpltCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD ISO OUT Incomplete callback */ +typedef void (*pPCD_IsoInIncpltCallbackTypeDef)(PCD_HandleTypeDef *hpcd, uint8_t epnum); /*!< pointer to USB OTG PCD ISO IN Incomplete callback */ +typedef void (*pPCD_LpmCallbackTypeDef)(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); /*!< pointer to USB OTG PCD LPM callback */ +typedef void (*pPCD_BcdCallbackTypeDef)(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg); /*!< pointer to USB OTG PCD BCD callback */ + +/** + * @} + */ + +HAL_StatusTypeDef HAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd, HAL_PCD_CallbackIDTypeDef CallbackID, + pPCD_CallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, HAL_PCD_CallbackIDTypeDef CallbackID); + +HAL_StatusTypeDef HAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataOutStageCallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd); + +HAL_StatusTypeDef HAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataInStageCallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd); + +HAL_StatusTypeDef HAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoOutIncpltCallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd); + +HAL_StatusTypeDef HAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoInIncpltCallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd); + +HAL_StatusTypeDef HAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback); +HAL_StatusTypeDef HAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd); + +HAL_StatusTypeDef HAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback); +HAL_StatusTypeDef HAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +/** + * @} + */ + +/* I/O operation functions ***************************************************/ +/* Non-Blocking mode: Interrupt */ +/** @addtogroup PCD_Exported_Functions_Group2 Input and Output operation functions + * @{ + */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); +void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); + +void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); + +void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +/** + * @} + */ + +/* Peripheral Control functions **********************************************/ +/** @addtogroup PCD_Exported_Functions_Group3 Peripheral Control functions + * @{ + */ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); +HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); +HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); +uint32_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef const *hpcd, uint8_t ep_addr); +/** + * @} + */ + +/* Peripheral State functions ************************************************/ +/** @addtogroup PCD_Exported_Functions_Group4 Peripheral State functions + * @{ + */ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef const *hpcd); +/** + * @} + */ + +/** + * @} + */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup PCD_Private_Constants PCD Private Constants + * @{ + */ +/** @defgroup USB_EXTI_Line_Interrupt USB EXTI line interrupt + * @{ + */ + + +#define USB_WAKEUP_EXTI_LINE (0x1U << 4) /*!< USB FS EXTI Line WakeUp Interrupt */ + + +/** + * @} + */ + +/** @defgroup PCD_EP0_MPS PCD EP0 MPS + * @{ + */ +#define PCD_EP0MPS_64 EP_MPS_64 +#define PCD_EP0MPS_32 EP_MPS_32 +#define PCD_EP0MPS_16 EP_MPS_16 +#define PCD_EP0MPS_08 EP_MPS_8 +/** + * @} + */ + +/** @defgroup PCD_ENDP PCD ENDP + * @{ + */ +#define PCD_ENDP0 0U +#define PCD_ENDP1 1U +#define PCD_ENDP2 2U +#define PCD_ENDP3 3U +#define PCD_ENDP4 4U +#define PCD_ENDP5 5U +#define PCD_ENDP6 6U +#define PCD_ENDP7 7U +/** + * @} + */ + +/** @defgroup PCD_ENDP_Kind PCD Endpoint Kind + * @{ + */ +#define PCD_SNG_BUF 0U +#define PCD_DBL_BUF 1U +/** + * @} + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PCD_Private_Macros PCD Private Macros + * @{ + */ + +/* PMA RX counter */ +#ifndef PCD_RX_PMA_CNT +#define PCD_RX_PMA_CNT 10U +#endif /* PCD_RX_PMA_CNT */ + +/* SetENDPOINT */ +#define PCD_SET_ENDPOINT USB_DRD_SET_CHEP + +/* GetENDPOINT Register value*/ +#define PCD_GET_ENDPOINT USB_DRD_GET_CHEP + + +/** + * @brief free buffer used from the application realizing it to the line + * toggles bit SW_BUF in the double buffered endpoint register + * @param USBx USB device. + * @param bEpNum, bDir + * @retval None + */ +#define PCD_FREE_USER_BUFFER USB_DRD_FREE_USER_BUFFER + +/** + * @brief sets the status for tx transfer (bits STAT_TX[1:0]). + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param wState new state + * @retval None + */ +#define PCD_SET_EP_TX_STATUS USB_DRD_SET_CHEP_TX_STATUS + +/** + * @brief sets the status for rx transfer (bits STAT_TX[1:0]) + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param wState new state + * @retval None + */ +#define PCD_SET_EP_RX_STATUS USB_DRD_SET_CHEP_RX_STATUS + +/** + * @brief Sets/clears directly EP_KIND bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_KIND USB_DRD_SET_CHEP_KIND +#define PCD_CLEAR_EP_KIND USB_DRD_CLEAR_CHEP_KIND +#define PCD_SET_BULK_EP_DBUF PCD_SET_EP_KIND +#define PCD_CLEAR_BULK_EP_DBUF PCD_CLEAR_EP_KIND + + +/** + * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @retval None + */ +#define PCD_CLEAR_RX_EP_CTR USB_DRD_CLEAR_RX_CHEP_CTR +#define PCD_CLEAR_TX_EP_CTR USB_DRD_CLEAR_TX_CHEP_CTR +/** + * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @retval None + */ +#define PCD_RX_DTOG USB_DRD_RX_DTOG +#define PCD_TX_DTOG USB_DRD_TX_DTOG +/** + * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @retval None + */ +#define PCD_CLEAR_RX_DTOG USB_DRD_CLEAR_RX_DTOG +#define PCD_CLEAR_TX_DTOG USB_DRD_CLEAR_TX_DTOG + +/** + * @brief Sets address in an endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param bAddr Address. + * @retval None + */ +#define PCD_SET_EP_ADDRESS USB_DRD_SET_CHEP_ADDRESS + +/** + * @brief sets address of the tx/rx buffer. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param wAddr address to be set (must be word aligned). + * @retval None + */ +#define PCD_SET_EP_TX_ADDRESS USB_DRD_SET_CHEP_TX_ADDRESS +#define PCD_SET_EP_RX_ADDRESS USB_DRD_SET_CHEP_RX_ADDRESS + +/** + * @brief sets counter for the tx/rx buffer. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param wCount Counter value. + * @retval None + */ +#define PCD_SET_EP_TX_CNT USB_DRD_SET_CHEP_TX_CNT +#define PCD_SET_EP_RX_CNT USB_DRD_SET_CHEP_RX_CNT + +/** + * @brief gets counter of the tx buffer. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @retval Counter value + */ +#define PCD_GET_EP_TX_CNT USB_DRD_GET_CHEP_TX_CNT + +/** + * @brief gets counter of the rx buffer. + * @param Instance USB peripheral instance register address. + * @param bEpNum channel Number. + * @retval Counter value + */ +__STATIC_INLINE uint16_t PCD_GET_EP_RX_CNT(const PCD_TypeDef *Instance, uint16_t bEpNum) +{ + UNUSED(Instance); + __IO uint32_t count = PCD_RX_PMA_CNT; + + /* WA: few cycles for RX PMA descriptor to update */ + while (count > 0U) + { + count--; + } + + return (uint16_t)USB_DRD_GET_CHEP_RX_CNT((Instance), (bEpNum)); +} + +/** + * @brief Sets addresses in a double buffer endpoint. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param wBuf0Addr: buffer 0 address. + * @param wBuf1Addr = buffer 1 address. + * @retval None + */ +#define PCD_SET_EP_DBUF_ADDR USB_DRD_SET_CHEP_DBUF_ADDR + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param USBx USB peripheral instance register address. + * @param bEpNum Endpoint Number. + * @param bDir endpoint dir EP_DBUF_OUT = OUT + * EP_DBUF_IN = IN + * @param wCount: Counter value + * @retval None + */ +#define PCD_SET_EP_DBUF0_CNT USB_DRD_SET_CHEP_DBUF0_CNT +#define PCD_SET_EP_DBUF1_CNT USB_DRD_SET_CHEP_DBUF1_CNT +#define PCD_SET_EP_DBUF_CNT USB_DRD_SET_CHEP_DBUF_CNT + +/** + * @brief gets counter of the rx buffer0. + * @param Instance USB peripheral instance register address. + * @param bEpNum channel Number. + * @retval Counter value + */ +__STATIC_INLINE uint16_t PCD_GET_EP_DBUF0_CNT(const PCD_TypeDef *Instance, uint16_t bEpNum) +{ + UNUSED(Instance); + __IO uint32_t count = PCD_RX_PMA_CNT; + + /* WA: few cycles for RX PMA descriptor to update */ + while (count > 0U) + { + count--; + } + + return (uint16_t)USB_DRD_GET_CHEP_DBUF0_CNT((Instance), (bEpNum)); +} + +/** + * @brief gets counter of the rx buffer1. + * @param Instance USB peripheral instance register address. + * @param bEpNum channel Number. + * @retval Counter value + */ +__STATIC_INLINE uint16_t PCD_GET_EP_DBUF1_CNT(const PCD_TypeDef *Instance, uint16_t bEpNum) +{ + UNUSED(Instance); + __IO uint32_t count = PCD_RX_PMA_CNT; + + /* WA: few cycles for RX PMA descriptor to update */ + while (count > 0U) + { + count--; + } + + return (uint16_t)USB_DRD_GET_CHEP_DBUF1_CNT((Instance), (bEpNum)); +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32C0xx_HAL_PCD_H */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd_ex.h new file mode 100644 index 000000000..4befe7de4 --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pcd_ex.h @@ -0,0 +1,87 @@ +/** + ****************************************************************************** + * @file stm32c0xx_hal_pcd_ex.h + * @author MCD Application Team + * @brief Header file of PCD HAL Extension module. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32C0xx_HAL_PCD_EX_H +#define STM32C0xx_HAL_PCD_EX_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_hal_def.h" + +#if defined (USB_DRD_FS) +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PCDEx + * @{ + */ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macros -----------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PCDEx_Exported_Functions PCDEx Exported Functions + * @{ + */ +/** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions + * @{ + */ + + +HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr, + uint16_t ep_kind, uint32_t pmaadress); + + +HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd); + + +HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd); +void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd); + +void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg); +void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +#endif /* STM32C0xx_HAL_PCD_EX_H */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr.h index 5b9ecafa6..fa47c918f 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr.h @@ -57,16 +57,25 @@ extern "C" { #define PWR_WAKEUP_PIN2 PWR_CR3_EWUP2 /*!< Wakeup pin 2 (with high level detection) */ #define PWR_WAKEUP_PIN3 PWR_CR3_EWUP3 /*!< Wakeup pin 3 (with high level detection) */ #define PWR_WAKEUP_PIN4 PWR_CR3_EWUP4 /*!< Wakeup pin 4 (with high level detection) */ +#if defined(PWR_CR3_EWUP5) +#define PWR_WAKEUP_PIN5 PWR_CR3_EWUP5 /*!< Wakeup pin 5 (with high level detection) */ +#endif /* PWR_CR3_EWUP5 */ #define PWR_WAKEUP_PIN6 PWR_CR3_EWUP6 /*!< Wakeup pin 6 (with high level detection) */ #define PWR_WAKEUP_PIN1_HIGH PWR_CR3_EWUP1 /*!< Wakeup pin 1 (with high level detection) */ #define PWR_WAKEUP_PIN2_HIGH PWR_CR3_EWUP2 /*!< Wakeup pin 2 (with high level detection) */ #define PWR_WAKEUP_PIN3_HIGH PWR_CR3_EWUP3 /*!< Wakeup pin 3 (with high level detection) */ #define PWR_WAKEUP_PIN4_HIGH PWR_CR3_EWUP4 /*!< Wakeup pin 4 (with high level detection) */ +#if defined(PWR_CR3_EWUP5) +#define PWR_WAKEUP_PIN5_HIGH PWR_CR3_EWUP5 /*!< Wakeup pin 5 (with high level detection) */ +#endif /* PWR_CR3_EWUP5*/ #define PWR_WAKEUP_PIN6_HIGH PWR_CR3_EWUP6 /*!< Wakeup pin 6 (with high level detection) */ #define PWR_WAKEUP_PIN1_LOW ((PWR_CR4_WP1 << PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP1) /*!< Wakeup pin 1 (with low level detection) */ #define PWR_WAKEUP_PIN2_LOW ((PWR_CR4_WP2 << PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP2) /*!< Wakeup pin 2 (with low level detection) */ #define PWR_WAKEUP_PIN3_LOW ((PWR_CR4_WP3 << PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP3) /*!< Wakeup pin 3 (with low level detection) */ #define PWR_WAKEUP_PIN4_LOW ((PWR_CR4_WP4 << PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP4) /*!< Wakeup pin 4 (with low level detection) */ +#if defined(PWR_CR3_EWUP5) +#define PWR_WAKEUP_PIN5_LOW ((PWR_CR4_WP5 << PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP5) /*!< Wakeup pin 5 (with low level detection) */ +#endif /* PWR_CR3_EWUP5 */ #define PWR_WAKEUP_PIN6_LOW ((PWR_CR4_WP6 << PWR_WUP_POLARITY_SHIFT) | PWR_CR3_EWUP6) /*!< Wakeup pin 6 (with low level detection) */ /** * @} @@ -124,11 +133,17 @@ extern "C" { #define PWR_FLAG_WUF2 (0x00010000u | PWR_SR1_WUF2) /*!< Wakeup event on wakeup pin 2 */ #define PWR_FLAG_WUF3 (0x00010000u | PWR_SR1_WUF3) /*!< Wakeup event on wakeup pin 3 */ #define PWR_FLAG_WUF4 (0x00010000u | PWR_SR1_WUF4) /*!< Wakeup event on wakeup pin 4 */ +#if defined(PWR_CR3_EWUP5) +#define PWR_FLAG_WUF5 (0x00010000u | PWR_SR1_WUF5) /*!< Wakeup event on wakeup pin 5 */ +#endif /* PWR_CR3_EWUP5 */ #define PWR_FLAG_WUF6 (0x00010000u | PWR_SR1_WUF6) /*!< Wakeup event on wakeup pin 6 */ #define PWR_FLAG_WUF (0x00010000u | PWR_SR1_WUF) /*!< Wakeup event on all wakeup pin */ #define PWR_FLAG_SB (0x00010000u | PWR_SR1_SBF) /*!< Standby flag */ #define PWR_FLAG_WUFI (0x00010000u | PWR_SR1_WUFI) /*!< Wakeup on internal wakeup line */ #define PWR_FLAG_FLASH_READY (0x00020000u | PWR_SR2_FLASH_RDY) /*!< Flash ready */ +#if defined(PWR_PVM_SUPPORT) +#define PWR_FLAG_PVMO_USB (0x00020000u | PWR_SR2_PVMO_VDDIO2) /*!< Power Voltage Monitoring output */ +#endif /* PWR_PVM_SUPPORT */ /** * @} */ @@ -148,8 +163,12 @@ extern "C" { * was received from the WKUP pin 1. * @arg PWR_FLAG_WUF2: Wake Up Flag 2. Indicates that a wakeup event * was received from the WKUP pin 2. + * @arg PWR_FLAG_WUF3: Wake Up Flag 3. Indicates that a wakeup event + * was received from the WKUP pin 3. * @arg PWR_FLAG_WUF4: Wake Up Flag 4. Indicates that a wakeup event * was received from the WKUP pin 4. + * @arg PWR_FLAG_WUF5: Wake Up Flag 5. Indicates that a wakeup event + * was received from the WKUP pin 5. (*) * @arg PWR_FLAG_WUF6: Wake Up Flag 6. Indicates that a wakeup event * was received from the WKUP pin 6. * @arg PWR_FLAG_SB: StandBy Flag. Indicates that the system @@ -159,6 +178,9 @@ extern "C" { * OR a combination of following values: * @arg PWR_FLAG_FLASH_READY: Flash is ready. Indicates whether flash * can be used or not + * @arg PWR_FLAG_PVMO_USB: Peripheral Voltage Monitoring Output. Indicates whether VDDUSB voltage + * is below or above PVM threshold. (*) + * @note (*) Availability depends on devices * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_PWR_GET_FLAG(__FLAG__) (((__FLAG__) & 0x00010000u) ?\ @@ -174,12 +196,17 @@ extern "C" { * was received from the WKUP pin 1. * @arg PWR_FLAG_WUF2: Wake Up Flag 2. Indicates that a wakeup event * was received from the WKUP pin 2. + * @arg PWR_FLAG_WUF3: Wake Up Flag 3. Indicates that a wakeup event + * was received from the WKUP pin 3. * @arg PWR_FLAG_WUF4: Wake Up Flag 4. Indicates that a wakeup event * was received from the WKUP pin 4. + * @arg PWR_FLAG_WUF5: Wake Up Flag 5. Indicates that a wakeup event + * was received from the WKUP pin 5. (*) * @arg PWR_FLAG_WUF6: Wake Up Flag 6. Indicates that a wakeup event * was received from the WKUP pin 6. * @arg PWR_FLAG_SB: Standby Flag. Indicates that the system * entered Standby mode. + * @note (*) Availability depends on devices * @retval None */ #define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->SCR = (__FLAG__)) diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr_ex.h index 33fc1ec05..8f425fe5a 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_pwr_ex.h @@ -37,7 +37,67 @@ extern "C" { */ /* Exported types ------------------------------------------------------------*/ +/** @defgroup PWREx_Exported_Types PWR Extended Exported Types + * @{ + */ + +#if defined(PWR_PVM_SUPPORT) +/** + * @brief PWR PVM configuration structure definition + */ +typedef struct +{ + uint32_t PVMType; /*!< PVMType: Specifies which voltage is monitored and against which threshold. + This parameter can be a value of @ref PWREx_PVM_Type. + @arg @ref PWR_PVM_USB Peripheral Voltage Monitoring USB enable */ + + uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. + This parameter can be a value of @ref PWREx_PVM_Mode. */ +} PWR_PVMTypeDef; +#endif /* PWR_PVM_SUPPORT */ +/** + * @} + */ /* Exported constants --------------------------------------------------------*/ +#if defined(PWR_PVM_SUPPORT) +/** @defgroup PWREx_PVM_Type Peripheral Voltage Monitoring type + * @{ + */ +#define PWR_PVM_USB PWR_CR2_PVM_VDDIO2_0 /*!< Peripheral Voltage Monitoring enable for USB peripheral: Enable to keep + the USB peripheral voltage monitoring under control (power domain Vddio2) */ +/** + * @} + */ +/** @defgroup PWREx_PVM_Mode PWR PVM interrupt and event mode + * @{ + */ +#define PWR_PVM_MODE_NORMAL ((uint32_t)0x00000000) /*!< basic mode is used */ +#define PWR_PVM_MODE_IT_RISING ((uint32_t)0x00010001) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define PWR_PVM_MODE_IT_FALLING ((uint32_t)0x00010002) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define PWR_PVM_MODE_IT_RISING_FALLING ((uint32_t)0x00010003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define PWR_PVM_MODE_EVENT_RISING ((uint32_t)0x00020001) /*!< Event Mode with Rising edge trigger detection */ +#define PWR_PVM_MODE_EVENT_FALLING ((uint32_t)0x00020002) /*!< Event Mode with Falling edge trigger detection */ +#define PWR_PVM_MODE_EVENT_RISING_FALLING ((uint32_t)0x00020003) /*!< Event Mode with Rising/Falling edge trigger detection */ +/** + * @} + */ +/** @defgroup PWR_PVM_EXTI_LINE PWR PVM external interrupt line + * @{ + */ +#define PWR_EXTI_LINE_PVM (EXTI_IMR2_IM34) /*!< External interrupt line 34 connected to PVM */ +/** + * @} + */ + +/** @defgroup PWR_PVM_EVENT_LINE PWR PVM event line + * @{ + */ +#define PWR_EVENT_LINE_PVM (EXTI_EMR2_EM34) /*!< Event line 34 connected to PVM */ +/** + * @} + */ +#endif /* PWR_PVM_SUPPORT */ + /** @defgroup PWREx_Exported_Constants PWR Extended Exported Constants * @{ */ @@ -83,9 +143,9 @@ extern "C" { #define PWR_GPIO_A (0x00000000u) /*!< GPIO port A */ #define PWR_GPIO_B (0x00000001u) /*!< GPIO port B */ #define PWR_GPIO_C (0x00000002u) /*!< GPIO port C */ -#if defined(STM32C031xx) +#if defined(GPIOD) #define PWR_GPIO_D (0x00000003u) /*!< GPIO port D */ -#endif /* STM32C031xx */ +#endif /* GPIOD */ #define PWR_GPIO_F (0x00000005u) /*!< GPIO port F */ /** * @} @@ -100,12 +160,153 @@ extern "C" { * @} */ +/** @addtogroup PWR_Flag PWR Status Flags + * @brief Elements values convention: 0000 00XX 000Y YYYYb + * - Y YYYY : Flag position in the XX register (5 bits) + * - XX : Status register (2 bits) + * - 01: SR1 register + * - 10: SR2 register + * The only exception is PWR_FLAG_WU, encompassing all + * wake-up flags and set to PWR_SR1_WUF. + * @{ + */ +#if defined(PWR_PVM_SUPPORT) +#define PWR_FLAG_PVMOUSB (0x00020000u | PWR_SR2_PVMO_USB) /*!< USB Peripheral Voltage Monitoring output */ +#endif /* PWR_PVM_SUPPORT */ +/** + * @} + */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ +/** @addtogroup PWREx_Exported_Macros PWR Extended Exported Macros + * @{ + */ +#if defined(PWR_PVM_SUPPORT) +/** + * @brief Enable the PVM Extended Interrupt Line. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_ENABLE_IT() SET_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Disable the PVM Extended Interrupt Line. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_DISABLE_IT() CLEAR_BIT(EXTI->IMR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Enable the PVM Event Line. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_ENABLE_EVENT() SET_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM) + +/** + * @brief Disable the PVM Event Line. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_DISABLE_EVENT() CLEAR_BIT(EXTI->EMR2, PWR_EVENT_LINE_PVM) + +/** + * @brief Enable the PVM Extended Interrupt Rising Trigger. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_ENABLE_RISING_EDGE() SET_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Disable the PVM Extended Interrupt Rising Trigger. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_DISABLE_RISING_EDGE() CLEAR_BIT(EXTI->RTSR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Enable the PVM Extended Interrupt Falling Trigger. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_ENABLE_FALLING_EDGE() SET_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Disable the PVM Extended Interrupt Falling Trigger. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_DISABLE_FALLING_EDGE() CLEAR_BIT(EXTI->FTSR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Enable the PVM Extended Interrupt Rising & Falling Trigger. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_ENABLE_RISING_FALLING_EDGE() \ + do { \ + __HAL_PWR_PVM_EXTI_ENABLE_RISING_EDGE(); \ + __HAL_PWR_PVM_EXTI_ENABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Disable the PVM Extended Interrupt Rising & Falling Trigger. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_DISABLE_RISING_FALLING_EDGE() \ + do { \ + __HAL_PWR_PVM_EXTI_DISABLE_RISING_EDGE(); \ + __HAL_PWR_PVM_EXTI_DISABLE_FALLING_EDGE(); \ + } while(0U) + +/** + * @brief Generate a Software interrupt on selected EXTI line. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_GENERATE_SWIT() SET_BIT(EXTI->SWIER2, PWR_EXTI_LINE_PVM) + +/** + * @brief Check whether or not the PVM EXTI interrupt Rising flag is set. + * @retval EXTI PVM Line Status. + */ +#define __HAL_PWR_PVM_EXTI_GET_RISING_FLAG() (EXTI->RPR2 & PWR_EXTI_LINE_PVM) + +/** + * @brief Check whether or not the PVM EXTI interrupt Falling flag is set. + * @retval EXTI PVM Line Status. + */ +#define __HAL_PWR_PVM_EXTI_GET_FALLING_FLAG() (EXTI->FPR2 & PWR_EXTI_LINE_PVM) + +/** + * @brief Clear the PVM EXTI interrupt Rising flag. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_CLEAR_RISING_FLAG() WRITE_REG(EXTI->RPR2, PWR_EXTI_LINE_PVM) + +/** + * @brief Clear the PVM EXTI interrupt Falling flag. + * @retval None + */ +#define __HAL_PWR_PVM_EXTI_CLEAR_FALLING_FLAG() WRITE_REG(EXTI->FPR2, PWR_EXTI_LINE_PVM) +#endif /* PWR_PVM_SUPPORT */ +/** + * @} + */ + +/* Private define ------------------------------------------------------------*/ +/** @defgroup PWR_Extended_Private_Defines PWR Extended Private Defines + * @{ + */ + +/** @defgroup PWREx_PVM_Mode_Mask PWR PVM Mode Mask + * @{ + */ +#define PVM_MODE_IT ((uint32_t)0x00010000) /*!< Mask for interruption yielded by PVM threshold crossing */ +#define PVM_MODE_EVT ((uint32_t)0x00020000) /*!< Mask for event yielded by PVM threshold crossing */ +#define PVM_RISING_EDGE ((uint32_t)0x00000001) /*!< Mask for rising edge set as PVM trigger */ +#define PVM_FALLING_EDGE ((uint32_t)0x00000002) /*!< Mask for falling edge set as PVM trigger */ +/** + * @} + */ + +/** + * @} + */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup PWREx_Private_Macros PWR Extended Private Macros * @{ @@ -113,25 +314,35 @@ extern "C" { #define IS_PWR_GPIO_BIT_NUMBER(__BIT_NUMBER__) ((((__BIT_NUMBER__) & 0x0000FFFFu) != 0x00u) && \ (((__BIT_NUMBER__) & 0xFFFF0000u) == 0x00u)) -#if defined(STM32C031xx) +#if defined(GPIOD) #define IS_PWR_GPIO(__GPIO__) (((__GPIO__) == PWR_GPIO_A) || \ ((__GPIO__) == PWR_GPIO_B) || \ ((__GPIO__) == PWR_GPIO_C) || \ ((__GPIO__) == PWR_GPIO_D) || \ ((__GPIO__) == PWR_GPIO_F)) -#elif defined (STM32C011xx) +#else #define IS_PWR_GPIO(__GPIO__) (((__GPIO__) == PWR_GPIO_A) || \ ((__GPIO__) == PWR_GPIO_B) || \ ((__GPIO__) == PWR_GPIO_C) || \ ((__GPIO__) == PWR_GPIO_F)) -#endif /* STM32C031xx */ +#endif /* GPIOD */ #define IS_PWR_FLASH_POWERDOWN(__MODE__) ((((__MODE__) & (PWR_FLASHPD_SLEEP | PWR_FLASHPD_STOP)) != 0x00u) && \ (((__MODE__) & ~(PWR_FLASHPD_SLEEP | PWR_FLASHPD_STOP)) == 0x00u)) #define IS_PWR_BKP(__BKP__) ((__BKP__) < PWR_BKP_NUMBER) +#if defined(PWR_PVM_SUPPORT) +#define IS_PWR_PVM_TYPE(TYPE) ((TYPE) == PWR_PVM_USB) +#define IS_PWR_PVM_MODE(MODE) (((MODE) == PWR_PVM_MODE_NORMAL) ||\ + ((MODE) == PWR_PVM_MODE_IT_RISING) ||\ + ((MODE) == PWR_PVM_MODE_IT_FALLING) ||\ + ((MODE) == PWR_PVM_MODE_IT_RISING_FALLING) ||\ + ((MODE) == PWR_PVM_MODE_EVENT_RISING) ||\ + ((MODE) == PWR_PVM_MODE_EVENT_FALLING) ||\ + ((MODE) == PWR_PVM_MODE_EVENT_RISING_FALLING)) +#endif /* PWR_PVM_SUPPORT */ /** * @} @@ -163,6 +374,13 @@ uint32_t HAL_PWREx_BKUPRead(uint32_t BackupRegister); /* Low Power modes configuration functions ************************************/ void HAL_PWREx_EnterSHUTDOWNMode(void); +#if defined(PWR_PVM_SUPPORT) +/* Power voltage monitoring configuration functions ***************************/ +void HAL_PWREx_EnablePVMUSB(void); +void HAL_PWREx_DisablePVMUSB(void); +HAL_StatusTypeDef HAL_PWREx_ConfigPVM(PWR_PVMTypeDef *sConfigPVM); +#endif /* PWR_PVM_SUPPORT */ + /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc.h index 2a790412d..dd0ee5d2a 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc.h @@ -53,11 +53,14 @@ extern "C" { #define RCC_CR_REG_INDEX 1U #define RCC_CSR1_REG_INDEX 2U #define RCC_CSR2_REG_INDEX 3U +#if defined(RCC_HSI48_SUPPORT) +#define RCC_CRRCR_REG_INDEX 4U +#endif /* RCC_HSI48_SUPPORT */ #define RCC_FLAG_MASK 0x1FU /* Define used for IS_RCC_CLOCKTYPE() */ -#define RCC_CLOCKTYPE_ALL (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1) /*!< All clocktype to configure */ +#define RCC_CLOCKTYPE_ALL (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1) /*!< All clocktype to configure */ /** * @} */ @@ -67,11 +70,22 @@ extern "C" { * @{ */ -#define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)) +#if defined(RCC_CR_HSIUSB48ON) +#define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) \ + (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)) +#else +#define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) \ + (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)) +#endif /* RCC_CR_HSIUSB48ON */ #define IS_RCC_HSE(__HSE__) (((__HSE__) == RCC_HSE_OFF) || ((__HSE__) == RCC_HSE_ON) || \ ((__HSE__) == RCC_HSE_BYPASS)) @@ -81,6 +95,10 @@ extern "C" { #define IS_RCC_HSI(__HSI__) (((__HSI__) == RCC_HSI_OFF) || ((__HSI__) == RCC_HSI_ON)) +#if defined(RCC_CR_HSIUSB48ON) +#define IS_RCC_HSI48(__HSI48__) (((__HSI48__) == RCC_HSI48_OFF) || ((__HSI48__) == RCC_HSI48_ON)) +#endif /* RCC_CR_HSIUSB48ON */ + #define IS_RCC_HSI_CALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= (uint32_t)127U) #define IS_RCC_HSIDIV(__DIV__) (((__DIV__) == RCC_HSI_DIV1) || ((__DIV__) == RCC_HSI_DIV2) || \ @@ -93,13 +111,27 @@ extern "C" { #define IS_RCC_CLOCKTYPE(__CLK__) ((((__CLK__)\ & RCC_CLOCKTYPE_ALL) != 0x00UL) && (((__CLK__) & ~RCC_CLOCKTYPE_ALL) == 0x00UL)) - +#if defined(RCC_HSI48_SUPPORT) +#define IS_RCC_SYSCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_HSI) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_HSE) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_HSIUSB48) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_LSE) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_LSI)) +#else #define IS_RCC_SYSCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_HSI) || \ ((__SOURCE__) == RCC_SYSCLKSOURCE_HSE) || \ ((__SOURCE__) == RCC_SYSCLKSOURCE_LSE) || \ ((__SOURCE__) == RCC_SYSCLKSOURCE_LSI)) - +#endif /* RCC_HSI48_SUPPORT */ + +#if defined(RCC_CR_SYSDIV) +#define IS_RCC_SYSCLK(SYSCLK) (((SYSCLK) == RCC_SYSCLK_DIV1) || ((SYSCLK) == RCC_SYSCLK_DIV2) || \ + ((SYSCLK) == RCC_SYSCLK_DIV3) || ((SYSCLK) == RCC_SYSCLK_DIV4) || \ + ((SYSCLK) == RCC_SYSCLK_DIV5) || ((SYSCLK) == RCC_SYSCLK_DIV6) || \ + ((SYSCLK) == RCC_SYSCLK_DIV7) || ((SYSCLK) == RCC_SYSCLK_DIV8)) +#else #define IS_RCC_SYSCLK(SYSCLK) ((SYSCLK) == RCC_SYSCLK_DIV1) +#endif /* RCC_CR_SYSDIV */ #define IS_RCC_HCLK(HCLK) (((HCLK) == RCC_HCLK_DIV1) || ((HCLK) == RCC_HCLK_DIV2) || \ ((HCLK) == RCC_HCLK_DIV4) || ((HCLK) == RCC_HCLK_DIV8) || \ @@ -123,7 +155,7 @@ extern "C" { ((__MCOX__) == RCC_MCO2_PA8) || \ ((__MCOX__) == RCC_MCO2_PA10) || \ ((__MCOX__) == RCC_MCO2_PA14)) -#elif defined(STM32C031xx) +#else #define IS_RCC_MCO(__MCOX__) (((__MCOX__) == RCC_MCO1_PA8) || \ ((__MCOX__) == RCC_MCO1_PA9) || \ ((__MCOX__) == RCC_MCO1_PF2) || \ @@ -132,30 +164,69 @@ extern "C" { ((__MCOX__) == RCC_MCO2_PA14) || \ ((__MCOX__) == RCC_MCO2_PA15) || \ ((__MCOX__) == RCC_MCO2_PB2)) -#endif +#endif /* STM32C011xx */ + +#if defined(RCC_CR_HSIUSB48ON) +#define IS_RCC_MCO1SOURCE(__SOURCE__) (((__SOURCE__) == RCC_MCO1SOURCE_NOCLOCK) || \ + ((__SOURCE__) == RCC_MCO1SOURCE_SYSCLK) || \ + ((__SOURCE__) == RCC_MCO1SOURCE_HSI48) || \ + ((__SOURCE__) == RCC_MCO1SOURCE_HSI) || \ + ((__SOURCE__) == RCC_MCO1SOURCE_HSE) || \ + ((__SOURCE__) == RCC_MCO1SOURCE_LSI) || \ + ((__SOURCE__) == RCC_MCO1SOURCE_LSE)) +#else #define IS_RCC_MCO1SOURCE(__SOURCE__) (((__SOURCE__) == RCC_MCO1SOURCE_NOCLOCK) || \ ((__SOURCE__) == RCC_MCO1SOURCE_SYSCLK) || \ ((__SOURCE__) == RCC_MCO1SOURCE_HSI) || \ ((__SOURCE__) == RCC_MCO1SOURCE_HSE) || \ ((__SOURCE__) == RCC_MCO1SOURCE_LSI) || \ ((__SOURCE__) == RCC_MCO1SOURCE_LSE)) +#endif /* RCC_CR_HSIUSB48ON */ +#if defined(RCC_CR_HSIUSB48ON) +#define IS_RCC_MCO2SOURCE(__SOURCE__) (((__SOURCE__) == RCC_MCO2SOURCE_NOCLOCK) || \ + ((__SOURCE__) == RCC_MCO2SOURCE_SYSCLK) || \ + ((__SOURCE__) == RCC_MCO2SOURCE_HSI48) || \ + ((__SOURCE__) == RCC_MCO2SOURCE_HSI) || \ + ((__SOURCE__) == RCC_MCO2SOURCE_HSE) || \ + ((__SOURCE__) == RCC_MCO2SOURCE_LSI) || \ + ((__SOURCE__) == RCC_MCO2SOURCE_LSE)) +#else #define IS_RCC_MCO2SOURCE(__SOURCE__) (((__SOURCE__) == RCC_MCO2SOURCE_NOCLOCK) || \ ((__SOURCE__) == RCC_MCO2SOURCE_SYSCLK) || \ ((__SOURCE__) == RCC_MCO2SOURCE_HSI) || \ ((__SOURCE__) == RCC_MCO2SOURCE_HSE) || \ ((__SOURCE__) == RCC_MCO2SOURCE_LSI) || \ ((__SOURCE__) == RCC_MCO2SOURCE_LSE)) +#endif /* RCC_CR_HSIUSB48ON */ +#if defined(RCC_CFGR_MCOPRE_3) +#define IS_RCC_MCODIV(__DIV__) (((__DIV__) == RCC_MCODIV_1) || ((__DIV__) == RCC_MCODIV_2) || \ + ((__DIV__) == RCC_MCODIV_4) || ((__DIV__) == RCC_MCODIV_8) || \ + ((__DIV__) == RCC_MCODIV_16)|| ((__DIV__) == RCC_MCODIV_32) || \ + ((__DIV__) == RCC_MCODIV_64)|| ((__DIV__) == RCC_MCODIV_128) || \ + ((__DIV__) == RCC_MCODIV_256)|| ((__DIV__) == RCC_MCODIV_512) || \ + ((__DIV__) == RCC_MCODIV_1024)) +#else #define IS_RCC_MCODIV(__DIV__) (((__DIV__) == RCC_MCODIV_1) || ((__DIV__) == RCC_MCODIV_2) || \ ((__DIV__) == RCC_MCODIV_4) || ((__DIV__) == RCC_MCODIV_8) || \ ((__DIV__) == RCC_MCODIV_16)|| ((__DIV__) == RCC_MCODIV_32) || \ ((__DIV__) == RCC_MCODIV_64)|| ((__DIV__) == RCC_MCODIV_128)) +#endif /* RCC_CFGR_MCOPRE_3 */ +#if defined(RCC_CFGR_MCO2PRE_3) +#define IS_RCC_MCO2DIV(__DIV__) (((__DIV__) == RCC_MCO2DIV_1) || ((__DIV__) == RCC_MCO2DIV_2) || \ + ((__DIV__) == RCC_MCO2DIV_4) || ((__DIV__) == RCC_MCO2DIV_8) || \ + ((__DIV__) == RCC_MCO2DIV_16)|| ((__DIV__) == RCC_MCO2DIV_32) || \ + ((__DIV__) == RCC_MCO2DIV_64)|| ((__DIV__) == RCC_MCO2DIV_128) || \ + ((__DIV__) == RCC_MCO2DIV_256)|| ((__DIV__) == RCC_MCO2DIV_512) || \ + ((__DIV__) == RCC_MCO2DIV_1024)) +#else #define IS_RCC_MCO2DIV(__DIV__) (((__DIV__) == RCC_MCO2DIV_1) || ((__DIV__) == RCC_MCO2DIV_2) || \ ((__DIV__) == RCC_MCO2DIV_4) || ((__DIV__) == RCC_MCO2DIV_8) || \ ((__DIV__) == RCC_MCO2DIV_16)|| ((__DIV__) == RCC_MCO2DIV_32) || \ ((__DIV__) == RCC_MCO2DIV_64)|| ((__DIV__) == RCC_MCO2DIV_128)) +#endif /* RCC_CFGR_MCO2PRE_3 */ #define IS_RCC_LSE_DRIVE(__DRIVE__) (((__DRIVE__) == RCC_LSEDRIVE_LOW) || \ ((__DRIVE__) == RCC_LSEDRIVE_MEDIUMLOW) || \ @@ -198,6 +269,11 @@ typedef struct uint32_t LSIState; /*!< The new state of the LSI. This parameter can be a value of @ref RCC_LSI_Config */ +#if defined(RCC_CR_HSIUSB48ON) + uint32_t HSI48State; /*!< The new state of the HSI48 (only applicable to STM32C071xx devices). + This parameter can be a value of @ref RCC_HSI48_Config */ + +#endif /* RCC_CR_HSIUSB48ON */ } RCC_OscInitTypeDef; /** @@ -212,13 +288,13 @@ typedef struct This parameter can be a value of @ref RCC_System_Clock_Source */ uint32_t SYSCLKDivider; /*!< The system clock divider. This parameter can be - a value of @ref RCC_SYS_Clock_Source */ + a value of @ref RCC_SYS_Clock_Divider */ uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). - This parameter can be a value of @ref RCC_HCLK_Clock_Source */ + This parameter can be a value of @ref RCC_HCLK_Clock_Divider */ uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). - This parameter can be a value of @ref RCC_APB1_Clock_Source */ + This parameter can be a value of @ref RCC_APB1_Clock_Divider */ } RCC_ClkInitTypeDef; @@ -240,6 +316,9 @@ typedef struct #define RCC_OSCILLATORTYPE_HSI 0x00000002U /*!< HSI to configure */ #define RCC_OSCILLATORTYPE_LSE 0x00000004U /*!< LSE to configure */ #define RCC_OSCILLATORTYPE_LSI 0x00000008U /*!< LSI to configure */ +#if defined(RCC_CR_HSIUSB48ON) +#define RCC_OSCILLATORTYPE_HSI48 0x00000010U /*!< HSI48 to configure */ +#endif /* RCC_CR_HSIUSB48ON */ /** * @} */ @@ -247,9 +326,9 @@ typedef struct /** @defgroup RCC_HSE_Config HSE Config * @{ */ -#define RCC_HSE_OFF 0x00000000U /*!< HSE clock deactivation */ -#define RCC_HSE_ON RCC_CR_HSEON /*!< HSE clock activation */ -#define RCC_HSE_BYPASS ((uint32_t)(RCC_CR_HSEBYP | RCC_CR_HSEON)) /*!< External clock source for HSE clock */ +#define RCC_HSE_OFF 0x00000000U /*!< HSE clock deactivation */ +#define RCC_HSE_ON RCC_CR_HSEON /*!< HSE clock activation */ +#define RCC_HSE_BYPASS ((uint32_t)(RCC_CR_HSEBYP | RCC_CR_HSEON)) /*!< External clock source for HSE clock */ /** * @} */ @@ -257,9 +336,9 @@ typedef struct /** @defgroup RCC_LSE_Config LSE Config * @{ */ -#define RCC_LSE_OFF 0x00000000U /*!< LSE clock deactivation */ -#define RCC_LSE_ON RCC_CSR1_LSEON /*!< LSE clock activation */ -#define RCC_LSE_BYPASS ((uint32_t)(RCC_CSR1_LSEBYP | RCC_CSR1_LSEON)) /*!< External clock source for LSE clock */ +#define RCC_LSE_OFF 0x00000000U /*!< LSE clock deactivation */ +#define RCC_LSE_ON RCC_CSR1_LSEON /*!< LSE clock activation */ +#define RCC_LSE_BYPASS ((uint32_t)(RCC_CSR1_LSEBYP | RCC_CSR1_LSEON)) /*!< External clock source for LSE clock */ /** * @} */ @@ -277,14 +356,14 @@ typedef struct /** @defgroup RCC_HSI_Div HSI Div * @{ */ -#define RCC_HSI_DIV1 0x00000000U /*!< HSI clock is not divided */ -#define RCC_HSI_DIV2 RCC_CR_HSIDIV_0 /*!< HSI clock is divided by 2 */ -#define RCC_HSI_DIV4 RCC_CR_HSIDIV_1 /*!< HSI clock is divided by 4 */ -#define RCC_HSI_DIV8 (RCC_CR_HSIDIV_1|RCC_CR_HSIDIV_0) /*!< HSI clock is divided by 8 */ -#define RCC_HSI_DIV16 RCC_CR_HSIDIV_2 /*!< HSI clock is divided by 16 */ -#define RCC_HSI_DIV32 (RCC_CR_HSIDIV_2|RCC_CR_HSIDIV_0) /*!< HSI clock is divided by 32 */ -#define RCC_HSI_DIV64 (RCC_CR_HSIDIV_2|RCC_CR_HSIDIV_1) /*!< HSI clock is divided by 64 */ -#define RCC_HSI_DIV128 (RCC_CR_HSIDIV_2|RCC_CR_HSIDIV_1|RCC_CR_HSIDIV_0) /*!< HSI clock is divided by 128 */ +#define RCC_HSI_DIV1 0x00000000U /*!< HSI clock is not divided */ +#define RCC_HSI_DIV2 RCC_CR_HSIDIV_0 /*!< HSI clock is divided by 2 */ +#define RCC_HSI_DIV4 RCC_CR_HSIDIV_1 /*!< HSI clock is divided by 4 */ +#define RCC_HSI_DIV8 (RCC_CR_HSIDIV_1|RCC_CR_HSIDIV_0) /*!< HSI clock is divided by 8 */ +#define RCC_HSI_DIV16 RCC_CR_HSIDIV_2 /*!< HSI clock is divided by 16 */ +#define RCC_HSI_DIV32 (RCC_CR_HSIDIV_2|RCC_CR_HSIDIV_0) /*!< HSI clock is divided by 32 */ +#define RCC_HSI_DIV64 (RCC_CR_HSIDIV_2|RCC_CR_HSIDIV_1) /*!< HSI clock is divided by 64 */ +#define RCC_HSI_DIV128 (RCC_CR_HSIDIV_2|RCC_CR_HSIDIV_1|RCC_CR_HSIDIV_0) /*!< HSI clock is divided by 128 */ /** * @} */ @@ -299,6 +378,16 @@ typedef struct * @} */ +#if defined(RCC_CR_HSIUSB48ON) +/** @defgroup RCC_HSI48_Config HSI48 Config + * @{ + */ +#define RCC_HSI48_OFF 0x00000000U /*!< HSI48 clock deactivation */ +#define RCC_HSI48_ON RCC_CR_HSIUSB48ON /*!< HSI48 clock activation */ +/** + * @} + */ +#endif /* RCC_CR_HSIUSB48ON */ /** @defgroup RCC_System_Clock_Type System Clock Type * @{ @@ -315,6 +404,9 @@ typedef struct */ #define RCC_SYSCLKSOURCE_HSI 0x00000000U /*!< HSI selection as system clock */ #define RCC_SYSCLKSOURCE_HSE RCC_CFGR_SW_0 /*!< HSE selection as system clock */ +#if defined(RCC_HSI48_SUPPORT) +#define RCC_SYSCLKSOURCE_HSIUSB48 RCC_CFGR_SW_1 /*!< HSIUSB48 selection used as system clock */ +#endif /* RCC_HSI48_SUPPORT */ #define RCC_SYSCLKSOURCE_LSI (RCC_CFGR_SW_1 | RCC_CFGR_SW_0) /*!< LSI selection as system clock */ #define RCC_SYSCLKSOURCE_LSE RCC_CFGR_SW_2 /*!< LSE selection as system clock */ /** @@ -324,48 +416,60 @@ typedef struct /** @defgroup RCC_System_Clock_Source_Status System Clock Source Status * @{ */ -#define RCC_SYSCLKSOURCE_STATUS_HSI 0x00000000U /*!< HSI used as system clock */ -#define RCC_SYSCLKSOURCE_STATUS_HSE RCC_CFGR_SWS_0 /*!< HSE used as system clock */ -#define RCC_SYSCLKSOURCE_STATUS_LSI (RCC_CFGR_SWS_1 | RCC_CFGR_SWS_0) /*!< LSI used as system clock */ -#define RCC_SYSCLKSOURCE_STATUS_LSE RCC_CFGR_SWS_2 /*!< LSE used as system clock */ +#define RCC_SYSCLKSOURCE_STATUS_HSI 0x00000000U /*!< HSI used as system clock */ +#define RCC_SYSCLKSOURCE_STATUS_HSE RCC_CFGR_SWS_0 /*!< HSE used as system clock */ +#if defined(RCC_HSI48_SUPPORT) +#define RCC_SYSCLKSOURCE_STATUS_HSIUSB48 RCC_CFGR_SWS_1 /*!< HSIUSB48 used as system clock */ +#endif /* RCC_HSI48_SUPPORT */ +#define RCC_SYSCLKSOURCE_STATUS_LSI (RCC_CFGR_SWS_1 | RCC_CFGR_SWS_0) /*!< LSI used as system clock */ +#define RCC_SYSCLKSOURCE_STATUS_LSE RCC_CFGR_SWS_2 /*!< LSE used as system clock */ /** * @} */ -/** @defgroup RCC_SYS_Clock_Source RCC SYS Clock Source +/** @defgroup RCC_SYS_Clock_Divider RCC SYS Clock Divider * @{ */ -#define RCC_SYSCLK_DIV1 0x00000000U /*!< SYSCLK not divided */ - +#if defined(RCC_CR_SYSDIV) +#define RCC_SYSCLK_DIV1 0x00000000U /*!< SYSCLK not divided */ +#define RCC_SYSCLK_DIV2 RCC_CR_SYSDIV_0 /*!< SYSCLK is divided by 2 */ +#define RCC_SYSCLK_DIV3 RCC_CR_SYSDIV_1 /*!< SYSCLK is divided by 3 */ +#define RCC_SYSCLK_DIV4 (RCC_CR_SYSDIV_1 | RCC_CR_SYSDIV_0) /*!< SYSCLK is divided by 4 */ +#define RCC_SYSCLK_DIV5 RCC_CR_SYSDIV_2 /*!< SYSCLK is divided by 5 */ +#define RCC_SYSCLK_DIV6 (RCC_CR_SYSDIV_2 | RCC_CR_SYSDIV_0) /*!< SYSCLK is divided by 6 */ +#define RCC_SYSCLK_DIV7 (RCC_CR_SYSDIV_2 | RCC_CR_SYSDIV_1) /*!< SYSCLK is divided by 7 */ +#define RCC_SYSCLK_DIV8 (RCC_CR_SYSDIV_2 | RCC_CR_SYSDIV_1 | RCC_CR_SYSDIV_0) /*!< SYSCLK is divided by 8 */ +#else +#define RCC_SYSCLK_DIV1 0x00000000U /*!< SYSCLK not divided */ +#endif /* RCC_CR_SYSDIV */ /** * @} */ -/** @defgroup RCC_HCLK_Clock_Source RCC HCLK Clock Source +/** @defgroup RCC_HCLK_Clock_Divider RCC HCLK Clock Divider * @{ */ -#define RCC_HCLK_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_HCLK_DIV2 RCC_CFGR_HPRE_3 /*!< HCLK divided by 2 */ -#define RCC_HCLK_DIV4 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 4 */ -#define RCC_HCLK_DIV8 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 8 */ -#define RCC_HCLK_DIV16 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 16 */ -#define RCC_HCLK_DIV64 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2) /*!< HCLK divided by 64 */ -#define RCC_HCLK_DIV128 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 128 */ -#define RCC_HCLK_DIV256 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 256 */ -#define RCC_HCLK_DIV512 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 512 */ +#define RCC_HCLK_DIV1 0x00000000U /*!< HCLK not divided */ +#define RCC_HCLK_DIV2 RCC_CFGR_HPRE_3 /*!< HCLK divided by 2 */ +#define RCC_HCLK_DIV4 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 4 */ +#define RCC_HCLK_DIV8 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 8 */ +#define RCC_HCLK_DIV16 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 16 */ +#define RCC_HCLK_DIV64 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2) /*!< HCLK divided by 64 */ +#define RCC_HCLK_DIV128 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 128 */ +#define RCC_HCLK_DIV256 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 256 */ +#define RCC_HCLK_DIV512 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 512 */ /** * @} */ -/** @defgroup RCC_APB1_Clock_Source RCC APB1 Clock Source +/** @defgroup RCC_APB1_Clock_Divider RCC APB1 Clock Divider * @{ */ -#define RCC_APB1_DIV1 0x00000000U /*!< APB not divided */ -#define RCC_APB1_DIV2 RCC_CFGR_PPRE_2 /*!< APB divided by 2 */ -#define RCC_APB1_DIV4 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_0) /*!< APB divided by 4 */ -#define RCC_APB1_DIV8 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1) /*!< APB divided by 4 */ -#define RCC_APB1_DIV16 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1 | RCC_CFGR_PPRE_0) /*!< APB divided by 16 */ - +#define RCC_APB1_DIV1 0x00000000U /*!< APB not divided */ +#define RCC_APB1_DIV2 RCC_CFGR_PPRE_2 /*!< APB divided by 2 */ +#define RCC_APB1_DIV4 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_0) /*!< APB divided by 4 */ +#define RCC_APB1_DIV8 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1) /*!< APB divided by 4 */ +#define RCC_APB1_DIV16 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1 | RCC_CFGR_PPRE_0) /*!< APB divided by 16 */ /** * @} */ @@ -373,10 +477,10 @@ typedef struct /** @defgroup RCC_RTC_Clock_Source RTC Clock Source * @{ */ -#define RCC_RTCCLKSOURCE_NONE 0x00000000U /*!< No clock configured for RTC */ -#define RCC_RTCCLKSOURCE_LSE RCC_CSR1_RTCSEL_0 /*!< LSE oscillator clock used as RTC clock */ -#define RCC_RTCCLKSOURCE_LSI RCC_CSR1_RTCSEL_1 /*!< LSI oscillator clock used as RTC clock */ -#define RCC_RTCCLKSOURCE_HSE_DIV32 RCC_CSR1_RTCSEL /*!< HSE oscillator clock divided by 32 used as RTC clock */ +#define RCC_RTCCLKSOURCE_NONE 0x00000000U /*!< No clock configured for RTC */ +#define RCC_RTCCLKSOURCE_LSE RCC_CSR1_RTCSEL_0 /*!< LSE oscillator clock used as RTC clock */ +#define RCC_RTCCLKSOURCE_LSI RCC_CSR1_RTCSEL_1 /*!< LSI oscillator clock used as RTC clock */ +#define RCC_RTCCLKSOURCE_HSE_DIV32 RCC_CSR1_RTCSEL /*!< HSE oscillator clock divided by 32 used as RTC clock */ /** * @} */ @@ -404,25 +508,33 @@ typedef struct /* @endcond */ #define RCC_MCO1_PA8 (RCC_MCO1_INDEX |\ - (GPIO_AF0_MCO << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_8) + (GPIO_AF0_MCO << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_8) #define RCC_MCO1_PA9 (RCC_MCO1_INDEX |\ - (GPIO_AF0_MCO << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_9) + (GPIO_AF0_MCO << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_9) #define RCC_MCO1_PF2 (RCC_MCO1_INDEX |\ - (GPIO_AF0_MCO << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOF) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_2) + (GPIO_AF0_MCO << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOF) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_2) #define RCC_MCO1 RCC_MCO1_PA8 /*!< Alias for compatibility */ #define RCC_MCO2_PA8 (RCC_MCO2_INDEX |\ - (GPIO_AF15_MCO2 << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_8) + (GPIO_AF15_MCO2 << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_8) #define RCC_MCO2_PA10 (RCC_MCO2_INDEX |\ - (GPIO_AF3_MCO2 << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_10) + (GPIO_AF3_MCO2 << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_10) #define RCC_MCO2_PA14 (RCC_MCO2_INDEX |\ - (GPIO_AF11_MCO2 << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_14) -#if defined(STM32C031xx) + (GPIO_AF11_MCO2 << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_14) +#if !defined(STM32C011xx) #define RCC_MCO2_PA15 (RCC_MCO2_INDEX |\ - (GPIO_AF3_MCO2 << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_15) + (GPIO_AF3_MCO2 << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOA) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_15) #define RCC_MCO2_PB2 (RCC_MCO2_INDEX |\ - (GPIO_AF3_MCO2 << RCC_MCO_GPIOAF_POS) | (GPIO_GET_INDEX(GPIOB) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_2) -#endif + (GPIO_AF3_MCO2 << RCC_MCO_GPIOAF_POS) | \ + (GPIO_GET_INDEX(GPIOB) << RCC_MCO_GPIOPORT_POS) | GPIO_PIN_2) +#endif /* STM32C011xx */ #define RCC_MCO2 RCC_MCO2_PA10 /*!< Alias for compatibility */ #define RCC_MCO RCC_MCO1 /*!< MCO1 to be compliant with other families with 1 MCO*/ @@ -439,6 +551,9 @@ typedef struct #define RCC_MCO1SOURCE_HSE RCC_CFGR_MCOSEL_2 /*!< HSE selection as MCO1 source */ #define RCC_MCO1SOURCE_LSI (RCC_CFGR_MCOSEL_1|RCC_CFGR_MCOSEL_2) /*!< LSI selection as MCO1 source */ #define RCC_MCO1SOURCE_LSE (RCC_CFGR_MCOSEL_0|RCC_CFGR_MCOSEL_1|RCC_CFGR_MCOSEL_2) /*!< LSE selection as MCO1 source */ +#if defined(RCC_HSI48_SUPPORT) +#define RCC_MCO1SOURCE_HSI48 RCC_CFGR_MCOSEL_3 /*!< HSI48 selection as MCO1 source */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ @@ -452,20 +567,28 @@ typedef struct #define RCC_MCO2SOURCE_HSE RCC_CFGR_MCO2SEL_2 /*!< HSE selection as MCO2 source */ #define RCC_MCO2SOURCE_LSI (RCC_CFGR_MCO2SEL_1|RCC_CFGR_MCO2SEL_2) /*!< LSI selection as MCO2 source */ #define RCC_MCO2SOURCE_LSE (RCC_CFGR_MCO2SEL_0|RCC_CFGR_MCO2SEL_1|RCC_CFGR_MCO2SEL_2) /*!< LSE selection as MCO2 source */ +#if defined(RCC_HSI48_SUPPORT) +#define RCC_MCO2SOURCE_HSI48 RCC_CFGR_MCO2SEL_3 /*!< HSI48 selection as MCO2 source */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ /** @defgroup RCC_MCO1_Clock_Prescaler MCO1 Clock Prescaler * @{ */ -#define RCC_MCODIV_1 0x00000000U /*!< MCO not divided */ -#define RCC_MCODIV_2 RCC_CFGR_MCOPRE_0 /*!< MCO divided by 2 */ -#define RCC_MCODIV_4 RCC_CFGR_MCOPRE_1 /*!< MCO divided by 4 */ -#define RCC_MCODIV_8 (RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 8 */ -#define RCC_MCODIV_16 RCC_CFGR_MCOPRE_2 /*!< MCO divided by 16 */ -#define RCC_MCODIV_32 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 32 */ -#define RCC_MCODIV_64 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1) /*!< MCO divided by 64 */ -#define RCC_MCODIV_128 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 128 */ +#define RCC_MCODIV_1 0x00000000U /*!< MCO not divided */ +#define RCC_MCODIV_2 RCC_CFGR_MCOPRE_0 /*!< MCO divided by 2 */ +#define RCC_MCODIV_4 RCC_CFGR_MCOPRE_1 /*!< MCO divided by 4 */ +#define RCC_MCODIV_8 (RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 8 */ +#define RCC_MCODIV_16 RCC_CFGR_MCOPRE_2 /*!< MCO divided by 16 */ +#define RCC_MCODIV_32 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 32 */ +#define RCC_MCODIV_64 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1) /*!< MCO divided by 64 */ +#define RCC_MCODIV_128 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 128 */ +#if defined(RCC_CFGR_MCOPRE_3) +#define RCC_MCODIV_256 RCC_CFGR_MCOPRE_3 /*!< MCO divided by 256 */ +#define RCC_MCODIV_512 (RCC_CFGR_MCOPRE_3 | RCC_CFGR_MCOPRE_0) /*!< MCO divided by 512 */ +#define RCC_MCODIV_1024 (RCC_CFGR_MCOPRE_3 | RCC_CFGR_MCOPRE_1) /*!< MCO divided by 1024*/ +#endif /* RCC_CFGR_MCOPRE_3 */ /** * @} */ @@ -473,14 +596,19 @@ typedef struct /** @defgroup RCC_MCO2_Clock_Prescaler MCO2 Clock Prescaler * @{ */ -#define RCC_MCO2DIV_1 0x00000000U /*!< MCO not divided */ -#define RCC_MCO2DIV_2 RCC_CFGR_MCO2PRE_0 /*!< MCO divided by 2 */ -#define RCC_MCO2DIV_4 RCC_CFGR_MCO2PRE_1 /*!< MCO divided by 4 */ -#define RCC_MCO2DIV_8 (RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 8 */ -#define RCC_MCO2DIV_16 RCC_CFGR_MCO2PRE_2 /*!< MCO divided by 16 */ -#define RCC_MCO2DIV_32 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 32 */ -#define RCC_MCO2DIV_64 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1) /*!< MCO divided by 64 */ -#define RCC_MCO2DIV_128 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 128 */ +#define RCC_MCO2DIV_1 0x00000000U /*!< MCO not divided */ +#define RCC_MCO2DIV_2 RCC_CFGR_MCO2PRE_0 /*!< MCO divided by 2 */ +#define RCC_MCO2DIV_4 RCC_CFGR_MCO2PRE_1 /*!< MCO divided by 4 */ +#define RCC_MCO2DIV_8 (RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 8 */ +#define RCC_MCO2DIV_16 RCC_CFGR_MCO2PRE_2 /*!< MCO divided by 16 */ +#define RCC_MCO2DIV_32 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 32 */ +#define RCC_MCO2DIV_64 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1) /*!< MCO divided by 64 */ +#define RCC_MCO2DIV_128 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 128 */ +#if defined(RCC_CFGR_MCO2PRE_3) +#define RCC_MCO2DIV_256 RCC_CFGR_MCO2PRE_3 /*!< MCO divided by 256 */ +#define RCC_MCO2DIV_512 (RCC_CFGR_MCO2PRE_3 | RCC_CFGR_MCO2PRE_0) /*!< MCO divided by 512 */ +#define RCC_MCO2DIV_1024 (RCC_CFGR_MCO2PRE_3 | RCC_CFGR_MCO2PRE_1) /*!< MCO divided by 1024*/ +#endif /* RCC_CFGR_MCO2PRE_3 */ /** * @} */ @@ -494,6 +622,9 @@ typedef struct #define RCC_IT_HSERDY RCC_CIFR_HSERDYF /*!< HSE Ready Interrupt flag */ #define RCC_IT_CSS RCC_CIFR_CSSF /*!< HSE Clock Security System Interrupt flag */ #define RCC_IT_LSECSS RCC_CIFR_LSECSSF /*!< LSE Clock Security System Interrupt flag */ +#if defined(RCC_HSI48_SUPPORT) +#define RCC_IT_HSI48RDY RCC_CIFR_HSIUSB48RDYF /*!< HSI48 Ready Interrupt flag */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ @@ -510,6 +641,10 @@ typedef struct /* Flags in the CR register */ #define RCC_FLAG_HSIRDY ((RCC_CR_REG_INDEX << 5U) | RCC_CR_HSIRDY_Pos) /*!< HSI Ready flag */ #define RCC_FLAG_HSERDY ((RCC_CR_REG_INDEX << 5U) | RCC_CR_HSERDY_Pos) /*!< HSE Ready flag */ +#if defined(RCC_HSI48_SUPPORT) +/* Flags in the CR register */ +#define RCC_FLAG_HSI48RDY ((CR_REG_INDEX << 5U) | RCC_CR_HSI48RDY_Pos) /*!< HSI48 Ready flag */ +#endif /* RCC_HSI48_SUPPORT */ /* Flags in the CSR1 register */ #define RCC_FLAG_LSERDY ((RCC_CSR1_REG_INDEX << 5U) | RCC_CSR1_LSERDY_Pos) /*!< LSE Ready flag */ @@ -622,7 +757,7 @@ typedef struct tmpreg = READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOCEN); \ UNUSED(tmpreg); \ } while(0U) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN); \ @@ -630,7 +765,7 @@ typedef struct tmpreg = READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN); \ UNUSED(tmpreg); \ } while(0U) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->IOPENR, RCC_IOPENR_GPIOFEN); \ @@ -642,23 +777,31 @@ typedef struct #define __HAL_RCC_GPIOA_CLK_DISABLE() CLEAR_BIT(RCC->IOPENR, RCC_IOPENR_GPIOAEN) #define __HAL_RCC_GPIOB_CLK_DISABLE() CLEAR_BIT(RCC->IOPENR, RCC_IOPENR_GPIOBEN) #define __HAL_RCC_GPIOC_CLK_DISABLE() CLEAR_BIT(RCC->IOPENR, RCC_IOPENR_GPIOCEN) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_CLK_DISABLE() CLEAR_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_CLK_DISABLE() CLEAR_BIT(RCC->IOPENR, RCC_IOPENR_GPIOFEN) /** * @} */ -/** @defgroup RCC_APB1_Clock_Enable_Disable APB1 Peripheral Clock Enable Disable +/** @defgroup RCC_APB1_GRP1_Clock_Enable_Disable APB1_GRP1 Peripheral Clock Enable Disable * @brief Enable or disable the APB1 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ - +#if defined(TIM2) +#define __HAL_RCC_TIM2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg; \ + SET_BIT(RCC->APBENR1, RCC_APBENR1_TIM2EN); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APBENR1, RCC_APBENR1_TIM2EN); \ + UNUSED(tmpreg); \ + } while(0) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -684,6 +827,36 @@ typedef struct UNUSED(tmpreg); \ } while(0U) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_CLK_ENABLE() do { \ + __IO uint32_t tmpreg; \ + SET_BIT(RCC->APBENR1, RCC_APBENR1_USBEN); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APBENR1, RCC_APBENR1_USBEN); \ + UNUSED(tmpreg); \ + } while(0U) +#endif /* USB_DRD_FS */ + +#if defined(SPI2) +#define __HAL_RCC_SPI2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg; \ + SET_BIT(RCC->APBENR1, RCC_APBENR1_SPI2EN); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APBENR1, RCC_APBENR1_SPI2EN); \ + UNUSED(tmpreg); \ + } while(0) +#endif /* SPI2 */ + +#if defined(CRS) +#define __HAL_RCC_CRS_CLK_ENABLE() do { \ + __IO uint32_t tmpreg; \ + SET_BIT(RCC->APBENR1, RCC_APBENR1_CRSEN); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APBENR1, RCC_APBENR1_CRSEN); \ + UNUSED(tmpreg); \ + } while(0) +#endif /* CRS */ + #define __HAL_RCC_USART2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APBENR1, RCC_APBENR1_USART2EN); \ @@ -692,7 +865,6 @@ typedef struct UNUSED(tmpreg); \ } while(0U) - #define __HAL_RCC_I2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APBENR1, RCC_APBENR1_I2C1EN); \ @@ -701,6 +873,16 @@ typedef struct UNUSED(tmpreg); \ } while(0U) +#if defined(I2C2) +#define __HAL_RCC_I2C2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg; \ + SET_BIT(RCC->APBENR1, RCC_APBENR1_I2C2EN); \ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APBENR1, RCC_APBENR1_I2C2EN); \ + UNUSED(tmpreg); \ + } while(0) +#endif /* I2C2 */ + #define __HAL_RCC_DBGMCU_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APBENR1, RCC_APBENR1_DBGEN); \ @@ -716,19 +898,34 @@ typedef struct tmpreg = READ_BIT(RCC->APBENR1, RCC_APBENR1_PWREN); \ UNUSED(tmpreg); \ } while(0U) - +#if defined(TIM2) +#define __HAL_RCC_TIM2_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_TIM2EN) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_TIM3EN) #define __HAL_RCC_RTCAPB_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_RTCAPBEN) #define __HAL_RCC_WWDG_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_WWDGEN) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_USBEN) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_SPI2EN) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_CRSEN) +#endif /* CRS */ #define __HAL_RCC_USART2_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_USART2EN) #define __HAL_RCC_I2C1_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_I2C1EN) +#if defined(I2C2) +#define __HAL_RCC_I2C2_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_I2C2EN) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_DBGEN) #define __HAL_RCC_PWR_CLK_DISABLE() CLEAR_BIT(RCC->APBENR1, RCC_APBENR1_PWREN) /** * @} */ -/** @defgroup RCC_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable - * @brief Enable or disable the APB2 peripheral clock. + +/** @defgroup RCC_APB1_GRP2_Clock_Enable_Disable APB1_GRP2 Peripheral Clock Enable Disable + * @brief Enable or disable the APB1_GRP2 peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. @@ -774,7 +971,6 @@ typedef struct UNUSED(tmpreg); \ } while(0U) - #define __HAL_RCC_TIM16_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ SET_BIT(RCC->APBENR2, RCC_APBENR2_TIM16EN); \ @@ -799,7 +995,6 @@ typedef struct UNUSED(tmpreg); \ } while(0U) - #define __HAL_RCC_SYSCFG_CLK_DISABLE() CLEAR_BIT(RCC->APBENR2, RCC_APBENR2_SYSCFGEN) #define __HAL_RCC_TIM1_CLK_DISABLE() CLEAR_BIT(RCC->APBENR2, RCC_APBENR2_TIM1EN) #define __HAL_RCC_SPI1_CLK_DISABLE() CLEAR_BIT(RCC->APBENR2, RCC_APBENR2_SPI1EN) @@ -808,7 +1003,6 @@ typedef struct #define __HAL_RCC_TIM16_CLK_DISABLE() CLEAR_BIT(RCC->APBENR2, RCC_APBENR2_TIM16EN) #define __HAL_RCC_TIM17_CLK_DISABLE() CLEAR_BIT(RCC->APBENR2, RCC_APBENR2_TIM17EN) #define __HAL_RCC_ADC_CLK_DISABLE() CLEAR_BIT(RCC->APBENR2, RCC_APBENR2_ADCEN) - /** * @} */ @@ -820,15 +1014,13 @@ typedef struct * using it. * @{ */ +#define __HAL_RCC_DMA1_IS_CLK_ENABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN) != 0U) +#define __HAL_RCC_FLASH_IS_CLK_ENABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_FLASHEN) != 0U) +#define __HAL_RCC_CRC_IS_CLK_ENABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN) != 0U) -#define __HAL_RCC_DMA1_IS_CLK_ENABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN) != RESET) -#define __HAL_RCC_FLASH_IS_CLK_ENABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_FLASHEN) != RESET) -#define __HAL_RCC_CRC_IS_CLK_ENABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN) != RESET) - -#define __HAL_RCC_DMA1_IS_CLK_DISABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN) == RESET) -#define __HAL_RCC_FLASH_IS_CLK_DISABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_FLASHEN) == RESET) -#define __HAL_RCC_CRC_IS_CLK_DISABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN) == RESET) - +#define __HAL_RCC_DMA1_IS_CLK_DISABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN) == 0U) +#define __HAL_RCC_FLASH_IS_CLK_DISABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_FLASHEN) == 0U) +#define __HAL_RCC_CRC_IS_CLK_DISABLED() (READ_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN) == 0U) /** * @} */ @@ -840,56 +1032,83 @@ typedef struct * using it. * @{ */ -#define __HAL_RCC_GPIOA_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOAEN) != RESET) -#define __HAL_RCC_GPIOB_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOBEN) != RESET) -#define __HAL_RCC_GPIOC_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOCEN) != RESET) -#if defined (STM32C031xx) -#define __HAL_RCC_GPIOD_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN) != RESET) -#endif -#define __HAL_RCC_GPIOF_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOFEN) != RESET) - -#define __HAL_RCC_GPIOA_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOAEN) == RESET) -#define __HAL_RCC_GPIOB_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOBEN) == RESET) -#define __HAL_RCC_GPIOC_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOCEN) == RESET) -#if defined (STM32C031xx) -#define __HAL_RCC_GPIOD_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN) == RESET) -#endif -#define __HAL_RCC_GPIOF_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOFEN) == RESET) - +#define __HAL_RCC_GPIOA_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOAEN) != 0U) +#define __HAL_RCC_GPIOB_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOBEN) != 0U) +#define __HAL_RCC_GPIOC_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOCEN) != 0U) +#if defined (GPIOD) +#define __HAL_RCC_GPIOD_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN) != 0U) +#endif /* GPIOD */ +#define __HAL_RCC_GPIOF_IS_CLK_ENABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOFEN) != 0U) + +#define __HAL_RCC_GPIOA_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOAEN) == 0U) +#define __HAL_RCC_GPIOB_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOBEN) == 0U) +#define __HAL_RCC_GPIOC_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOCEN) == 0U) +#if defined (GPIOD) +#define __HAL_RCC_GPIOD_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIODEN) == 0U) +#endif /* GPIOD */ +#define __HAL_RCC_GPIOF_IS_CLK_DISABLED() (READ_BIT(RCC->IOPENR, RCC_IOPENR_GPIOFEN) == 0U) /** * @} */ -/** @defgroup RCC_APB1_Clock_Enabled_Disabled_Status APB1 Peripheral Clock Enabled or Disabled Status - * @brief Check whether the APB1 peripheral clock is enabled or not. +/** @defgroup RCC_APB1_GRP1_Clock_Enabled_Disabled_Status APB1_GRP1 Peripheral Clock Enabled or Disabled Status + * @brief Check whether the APB1_GRP1 peripheral clock is enabled or not. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ - +#if defined(TIM2) +#define __HAL_RCC_TIM2_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_TIM2EN) != 0U) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_TIM3EN) != 0U) #define __HAL_RCC_RTCAPB_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_RTCAPBEN) != 0U) #define __HAL_RCC_WWDG_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_WWDGEN) != 0U) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_USBEN) != 0U) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_SPI2EN) != 0U) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_CRSEN) != 0U) +#endif /* CRS */ #define __HAL_RCC_USART2_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_USART2EN) != 0U) #define __HAL_RCC_I2C1_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_I2C1EN) != 0U) +#if defined(I2C2) +#define __HAL_RCC_I2C2_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_I2C2EN) != 0U) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_DBGEN) != 0U) #define __HAL_RCC_PWR_IS_CLK_ENABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_PWREN) != 0U) +#if defined(TIM2) +#define __HAL_RCC_TIM2_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_TIM2EN) == 0U) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_TIM3EN) == 0U) #define __HAL_RCC_RTCAPB_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_RTCAPBEN) == 0U) #define __HAL_RCC_WWDG_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_WWDGEN) == 0U) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_USBEN) == 0U) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_SPI2EN) == 0U) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_CRSEN) == 0U) +#endif /* CRS */ #define __HAL_RCC_USART2_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_USART2EN) == 0U) #define __HAL_RCC_I2C1_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_I2C1EN) == 0U) +#if defined(I2C2) +#define __HAL_RCC_I2C2_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_I2C2EN) == 0U) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_DBGEN) == 0U) #define __HAL_RCC_PWR_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR1, RCC_APBENR1_PWREN) == 0U) - /** * @} */ -/** @defgroup RCC_APB2_Clock_Enabled_Disabled_Status APB2 Peripheral Clock Enabled or Disabled Status - * @brief Check whether the APB2 peripheral clock is enabled or not. +/** @defgroup RCC_APB1_GRP2_Clock_Enabled_Disabled_Status APB1_GRP2 Peripheral Clock Enabled or Disabled Status + * @brief Check whether the APB1_GRP2 peripheral clock is enabled or not. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. @@ -912,12 +1131,10 @@ typedef struct #define __HAL_RCC_TIM16_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR2, RCC_APBENR2_TIM16EN) == 0U) #define __HAL_RCC_TIM17_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR2, RCC_APBENR2_TIM17EN) == 0U) #define __HAL_RCC_ADC_IS_CLK_DISABLED() (READ_BIT(RCC->APBENR2, RCC_APBENR2_ADCEN) == 0U) - /** * @} */ - /** @defgroup RCC_AHB_Force_Release_Reset AHB Peripheral Force Release Reset * @brief Force or release AHB1 peripheral reset. * @{ @@ -931,7 +1148,6 @@ typedef struct #define __HAL_RCC_DMA1_RELEASE_RESET() CLEAR_BIT(RCC->AHBRSTR, RCC_AHBRSTR_DMA1RST) #define __HAL_RCC_FLASH_RELEASE_RESET() CLEAR_BIT(RCC->AHBRSTR, RCC_AHBRSTR_FLASHRST) #define __HAL_RCC_CRC_RELEASE_RESET() CLEAR_BIT(RCC->AHBRSTR, RCC_AHBRSTR_CRCRST) - /** * @} */ @@ -944,51 +1160,79 @@ typedef struct #define __HAL_RCC_GPIOA_FORCE_RESET() SET_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOARST) #define __HAL_RCC_GPIOB_FORCE_RESET() SET_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOBRST) #define __HAL_RCC_GPIOC_FORCE_RESET() SET_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOCRST) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_FORCE_RESET() SET_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIODRST) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_FORCE_RESET() SET_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOFRST) #define __HAL_RCC_IOP_RELEASE_RESET() WRITE_REG(RCC->IOPRSTR, 0x00000000U) #define __HAL_RCC_GPIOA_RELEASE_RESET() CLEAR_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOARST) #define __HAL_RCC_GPIOB_RELEASE_RESET() CLEAR_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOBRST) #define __HAL_RCC_GPIOC_RELEASE_RESET() CLEAR_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOCRST) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_RELEASE_RESET() CLEAR_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIODRST) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_RELEASE_RESET() CLEAR_BIT(RCC->IOPRSTR, RCC_IOPRSTR_GPIOFRST) - /** * @} */ -/** @defgroup RCC_APB1_Force_Release_Reset APB1 Peripheral Force Release Reset - * @brief Force or release APB1 peripheral reset. +/** @defgroup RCC_APB1_GRP1_Force_Release_Reset APB1_GRP1 Peripheral Force Release Reset + * @brief Force or release APB1_GRP1 peripheral reset. * @{ */ -#define __HAL_RCC_APB1_FORCE_RESET() WRITE_REG(RCC->APBRSTR1, 0xFFFFFFFFU) - +#define __HAL_RCC_APB1_GRP1_FORCE_RESET() WRITE_REG(RCC->APBRSTR1, 0xFFFFFFFFU) +#if defined(TIM2) +#define __HAL_RCC_TIM2_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_TIM2RST) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_TIM3RST) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_USBRST) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_SPI2RST) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_CRSRST) +#endif /* CRS */ #define __HAL_RCC_USART2_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_USART2RST) #define __HAL_RCC_I2C1_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_I2C1RST) +#if defined(I2C2) +#define __HAL_RCC_I2C2_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_I2C2RST) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_DBGRST) #define __HAL_RCC_PWR_FORCE_RESET() SET_BIT(RCC->APBRSTR1, RCC_APBRSTR1_PWRRST) -#define __HAL_RCC_APB1_RELEASE_RESET() WRITE_REG(RCC->APBRSTR1, 0x00000000U) +#define __HAL_RCC_APB1_GRP1_RELEASE_RESET() WRITE_REG(RCC->APBRSTR1, 0x00000000U) +#if defined(TIM2) +#define __HAL_RCC_TIM2_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_TIM2RST) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_TIM3RST) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_USBRST) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_SPI2RST) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_CRSRST) +#endif /* CRS */ #define __HAL_RCC_USART2_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_USART2RST) #define __HAL_RCC_I2C1_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_I2C1RST) +#if defined(I2C2) +#define __HAL_RCC_I2C2_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_I2C2RST) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_DBGRST) #define __HAL_RCC_PWR_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR1, RCC_APBRSTR1_PWRRST) - /** * @} */ -/** @defgroup RCC_APB2_Force_Release_Reset APB2 Peripheral Force Release Reset - * @brief Force or release APB2 peripheral reset. + +/** @defgroup RCC_APB1_GRP2_Force_Release_Reset APB1_GRP2 Peripheral Force Release Reset + * @brief Force or release APB1_GRP2 peripheral reset. * @{ */ -#define __HAL_RCC_APB2_FORCE_RESET() WRITE_REG(RCC->APBRSTR2, 0xFFFFFFFFU) +#define __HAL_RCC_APB1_GRP2_FORCE_RESET() WRITE_REG(RCC->APBRSTR2, 0xFFFFFFFFU) #define __HAL_RCC_SYSCFG_FORCE_RESET() SET_BIT(RCC->APBRSTR2, RCC_APBRSTR2_SYSCFGRST) #define __HAL_RCC_TIM1_FORCE_RESET() SET_BIT(RCC->APBRSTR2, RCC_APBRSTR2_TIM1RST) #define __HAL_RCC_SPI1_FORCE_RESET() SET_BIT(RCC->APBRSTR2, RCC_APBRSTR2_SPI1RST) @@ -998,7 +1242,7 @@ typedef struct #define __HAL_RCC_TIM17_FORCE_RESET() SET_BIT(RCC->APBRSTR2, RCC_APBRSTR2_TIM17RST) #define __HAL_RCC_ADC_FORCE_RESET() SET_BIT(RCC->APBRSTR2, RCC_APBRSTR2_ADCRST) -#define __HAL_RCC_APB2_RELEASE_RESET() WRITE_REG(RCC->APBRSTR2, 0x00000000U) +#define __HAL_RCC_APB1_GRP2_RELEASE_RESET() WRITE_REG(RCC->APBRSTR2, 0x00000000U) #define __HAL_RCC_SYSCFG_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR2, RCC_APBRSTR2_SYSCFGRST) #define __HAL_RCC_TIM1_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR2, RCC_APBRSTR2_TIM1RST) #define __HAL_RCC_SPI1_RELEASE_RESET() CLEAR_BIT(RCC->APBRSTR2, RCC_APBRSTR2_SPI1RST) @@ -1019,7 +1263,6 @@ typedef struct * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ - #define __HAL_RCC_DMA1_CLK_SLEEP_ENABLE() SET_BIT(RCC->AHBSMENR, RCC_AHBSMENR_DMA1SMEN) #define __HAL_RCC_FLASH_CLK_SLEEP_ENABLE() SET_BIT(RCC->AHBSMENR, RCC_AHBSMENR_FLASHSMEN) #define __HAL_RCC_SRAM_CLK_SLEEP_ENABLE() SET_BIT(RCC->AHBSMENR, RCC_AHBSMENR_SRAMSMEN) @@ -1029,7 +1272,6 @@ typedef struct #define __HAL_RCC_FLASH_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->AHBSMENR, RCC_AHBSMENR_FLASHSMEN) #define __HAL_RCC_SRAM_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->AHBSMENR, RCC_AHBSMENR_SRAMSMEN) #define __HAL_RCC_CRC_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->AHBSMENR, RCC_AHBSMENR_CRCSMEN) - /** * @} */ @@ -1042,55 +1284,84 @@ typedef struct * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ - #define __HAL_RCC_GPIOA_CLK_SLEEP_ENABLE() SET_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOASMEN) #define __HAL_RCC_GPIOB_CLK_SLEEP_ENABLE() SET_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOBSMEN) #define __HAL_RCC_GPIOC_CLK_SLEEP_ENABLE() SET_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOCSMEN) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_CLK_SLEEP_ENABLE() SET_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIODSMEN) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_CLK_SLEEP_ENABLE() SET_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOFSMEN) #define __HAL_RCC_GPIOA_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOASMEN) #define __HAL_RCC_GPIOB_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOBSMEN) #define __HAL_RCC_GPIOC_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOCSMEN) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIODSMEN) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOFSMEN) /** * @} */ -/** @defgroup RCC_APB1_Clock_Sleep_Enable_Disable APB1 Peripheral Clock Sleep Enable Disable - * @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. +/** @defgroup RCC_APB1_GRP1_Clock_Sleep_Enable_Disable APB1_GRP1 Peripheral Clock Sleep Enable Disable + * @brief Enable or disable the APB1_GRP1 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ +#if defined(TIM2) +#define __HAL_RCC_TIM2_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM2SMEN) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM3SMEN) #define __HAL_RCC_RTCAPB_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_RTCAPBSMEN) #define __HAL_RCC_WWDG_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_WWDGSMEN) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USBSMEN) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_SPI2SMEN) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_CRSSMEN) +#endif /* CRS */ #define __HAL_RCC_USART2_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USART2SMEN) #define __HAL_RCC_I2C1_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C1SMEN) +#if defined(I2C2) +#define __HAL_RCC_I2C2_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C2SMEN) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_DBGSMEN) #define __HAL_RCC_PWR_CLK_SLEEP_ENABLE() SET_BIT(RCC->APBSMENR1, RCC_APBSMENR1_PWRSMEN) +#if defined(TIM2) +#define __HAL_RCC_TIM2_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM2SMEN) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM3SMEN) #define __HAL_RCC_RTCAPB_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_RTCAPBSMEN) #define __HAL_RCC_WWDG_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_WWDGSMEN) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USBSMEN) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_SPI2SMEN) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_CRSSMEN) +#endif /* CRS */ #define __HAL_RCC_USART2_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USART2SMEN) #define __HAL_RCC_I2C1_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C1SMEN) +#if defined(I2C2) +#define __HAL_RCC_I2C2_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C2SMEN) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_DBGSMEN) #define __HAL_RCC_PWR_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR1, RCC_APBSMENR1_PWRSMEN) - /** * @} */ -/** @defgroup RCC_APB2_Clock_Sleep_Enable_Disable APB2 Peripheral Clock Sleep Enable Disable - * @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. + +/** @defgroup RCC_APB1_GRP2_Clock_Sleep_Enable_Disable APB1_GRP2 Peripheral Clock Sleep Enable Disable + * @brief Enable or disable the APB1_GRP2 peripheral clock during Low Power (Sleep) mode. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. @@ -1114,7 +1385,6 @@ typedef struct #define __HAL_RCC_TIM16_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR2 , RCC_APBSMENR2_TIM16SMEN) #define __HAL_RCC_TIM17_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR2 , RCC_APBSMENR2_TIM17SMEN) #define __HAL_RCC_ADC_CLK_SLEEP_DISABLE() CLEAR_BIT(RCC->APBSMENR2 , RCC_APBSMENR2_ADCSMEN) - /** * @} */ @@ -1128,7 +1398,6 @@ typedef struct * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ - #define __HAL_RCC_DMA1_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->AHBSMENR, RCC_AHBSMENR_DMA1SMEN) != RESET) #define __HAL_RCC_FLASH_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->AHBSMENR, RCC_AHBSMENR_FLASHSMEN)!= RESET) #define __HAL_RCC_SRAM_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->AHBSMENR, RCC_AHBSMENR_SRAMSMEN) != RESET) @@ -1138,8 +1407,6 @@ typedef struct #define __HAL_RCC_FLASH_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->AHBSMENR, RCC_AHBSMENR_FLASHSMEN) == RESET) #define __HAL_RCC_SRAM_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->AHBSMENR, RCC_AHBSMENR_SRAMSMEN) == RESET) #define __HAL_RCC_CRC_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->AHBSMENR, RCC_AHBSMENR_CRCSMEN) == RESET) - - /** * @} */ @@ -1152,69 +1419,91 @@ typedef struct * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ - - #define __HAL_RCC_GPIOA_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOASMEN)!= RESET) #define __HAL_RCC_GPIOB_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOBSMEN)!= RESET) #define __HAL_RCC_GPIOC_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOCSMEN)!= RESET) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIODSMEN)!= RESET) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOFSMEN)!= RESET) - #define __HAL_RCC_GPIOA_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOASMEN) == RESET) #define __HAL_RCC_GPIOB_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOBSMEN) == RESET) #define __HAL_RCC_GPIOC_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOCSMEN) == RESET) -#if defined (STM32C031xx) +#if defined (GPIOD) #define __HAL_RCC_GPIOD_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIODSMEN) == RESET) -#endif +#endif /* GPIOD */ #define __HAL_RCC_GPIOF_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->IOPSMENR, RCC_IOPSMENR_GPIOFSMEN) == RESET) - /** * @} */ -/** @defgroup RCC_APB1_Clock_Sleep_Enabled_Disabled_Status APB1 Peripheral Clock Sleep Enabled or Disabled Status - * @brief Check whether the APB1 peripheral clock during Low Power (Sleep) mode is enabled or not. +/** @defgroup RCC_APB1_GRP1_Clock_Sleep_Enabled_Disabled_Status APB1_GRP1 Peripheral Clock Sleep Enabled or Disabled Status + * @brief Check whether the APB1_GRP1 peripheral clock during Low Power (Sleep) mode is enabled or not. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ - +#if defined(TIM2) +#define __HAL_RCC_TIM2_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM2SMEN) != RESET) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM3SMEN) != RESET) #define __HAL_RCC_RTCAPB_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_RTCAPBSMEN) != RESET) #define __HAL_RCC_WWDG_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_WWDGSMEN) != RESET) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USBSMEN) != RESET) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_SPI2SMEN) != RESET) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_CRSSMEN) != RESET) +#endif /* CRS */ #define __HAL_RCC_USART2_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USART2SMEN) != RESET) #define __HAL_RCC_I2C1_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C1SMEN) != RESET) +#if defined(I2C2) +#define __HAL_RCC_I2C2_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C2SMEN) != RESET) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_DBGSMEN) != RESET) #define __HAL_RCC_PWR_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_PWRSMEN) != RESET) - +#if defined(TIM2) +#define __HAL_RCC_TIM2_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM2SMEN) == RESET) +#endif /* TIM2 */ #define __HAL_RCC_TIM3_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_TIM3SMEN) == RESET) #define __HAL_RCC_RTCAPB_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_RTCAPBSMEN) == RESET) #define __HAL_RCC_WWDG_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_WWDGSMEN) == RESET) +#if defined (USB_DRD_FS) +#define __HAL_RCC_USB_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USBSMEN) == RESET) +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define __HAL_RCC_SPI2_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_SPI2SMEN) == RESET) +#endif /* SPI2 */ +#if defined(CRS) +#define __HAL_RCC_CRS_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_CRSSMEN) == RESET) +#endif /* CRS */ #define __HAL_RCC_USART2_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_USART2SMEN) == RESET) #define __HAL_RCC_I2C1_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C1SMEN) == RESET) +#if defined(I2C2) +#define __HAL_RCC_I2C2_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_I2C2SMEN) == RESET) +#endif /* I2C2 */ #define __HAL_RCC_DBGMCU_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_DBGSMEN) == RESET) #define __HAL_RCC_PWR_IS_CLK_SLEEP_DISABLED() (READ_BIT(RCC->APBSMENR1, RCC_APBSMENR1_PWRSMEN) == RESET) - /** * @} */ -/** @defgroup RCC_APB2_Clock_Sleep_Enabled_Disabled_Status APB2 Peripheral Clock Sleep Enabled or Disabled Status - * @brief Check whether the APB2 peripheral clock during Low Power (Sleep) mode is enabled or not. +/** @defgroup RCC_APB1_GRP2_Clock_Sleep_Enabled_Disabled_Status APB1_GRP2 Peripheral Clock Sleep Enabled or Disabled Status + * @brief Check whether the APB1_GRP2 peripheral clock during Low Power (Sleep) mode is enabled or not. * @note Peripheral clock gating in SLEEP mode can be used to further reduce * power consumption. * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. * @note By default, all peripheral clocks are enabled during SLEEP mode. * @{ */ - #define __HAL_RCC_SYSCFG_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR2 , RCC_APBSMENR2_SYSCFGSMEN) != RESET) #define __HAL_RCC_TIM1_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR2 , RCC_APBSMENR2_TIM1SMEN) != RESET) #define __HAL_RCC_SPI1_IS_CLK_SLEEP_ENABLED() (READ_BIT(RCC->APBSMENR2 , RCC_APBSMENR2_SPI1SMEN) != RESET) @@ -1236,7 +1525,6 @@ typedef struct * @} */ - /** @defgroup RCC_RTC_Domain_Reset RCC RTC Domain Reset * @{ */ @@ -1249,7 +1537,6 @@ typedef struct #define __HAL_RCC_BACKUPRESET_FORCE() SET_BIT(RCC->CSR1, RCC_CSR1_RTCRST) #define __HAL_RCC_BACKUPRESET_RELEASE() CLEAR_BIT(RCC->CSR1, RCC_CSR1_RTCRST) - /** * @} */ @@ -1265,7 +1552,6 @@ typedef struct #define __HAL_RCC_RTC_ENABLE() SET_BIT(RCC->CSR1, RCC_CSR1_RTCEN) #define __HAL_RCC_RTC_DISABLE() CLEAR_BIT(RCC->CSR1, RCC_CSR1_RTCEN) - /** * @} */ @@ -1343,10 +1629,10 @@ typedef struct * - RCC_CR_HSIDIV_2 HSI oscillator divided by 2 * - RCC_CR_HSIDIV_4 HSI oscillator divided by 4 (default after reset) * - RCC_CR_HSIDIV_8 HSI oscillator divided by 8 - * - RCC_CR_HSIDIV_8 HSI oscillator divided by 16 - * - RCC_CR_HSIDIV_8 HSI oscillator divided by 32 - * - RCC_CR_HSIDIV_8 HSI oscillator divided by 64 - * - RCC_CR_HSIDIV_8 HSI oscillator divided by 128 + * - RCC_CR_HSIDIV_16 HSI oscillator divided by 16 + * - RCC_CR_HSIDIV_32 HSI oscillator divided by 32 + * - RCC_CR_HSIDIV_64 HSI oscillator divided by 64 + * - RCC_CR_HSIDIV_128 HSI oscillator divided by 128 */ #define __HAL_RCC_GET_HSI_DIVIDER() ((uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSIDIV))) @@ -1437,6 +1723,18 @@ typedef struct CLEAR_BIT(RCC->CSR1, RCC_CSR1_LSEBYP); \ } \ } while(0U) +#if defined(RCC_CR_HSIUSB48ON) +/** @brief Macros to enable or disable the Internal High Speed 48MHz oscillator (HSI48). + * @note The HSI48 is stopped by hardware when entering STOP and STANDBY modes. + * @note After enabling the HSI48, the application software should wait on HSI48RDY + * flag to be set indicating that HSI48 clock is stable. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +#define __HAL_RCC_HSI48_ENABLE() SET_BIT(RCC->CR, RCC_CR_HSIUSB48ON) + +#define __HAL_RCC_HSI48_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_HSIUSB48ON) +#endif /* RCC_CR_HSIUSB48ON */ /** * @} */ @@ -1490,15 +1788,16 @@ typedef struct * @{ */ - /** * @brief Macro to configure the system clock source. * @param __SYSCLKSOURCE__ specifies the system clock source. * This parameter can be one of the following values: * @arg @ref RCC_SYSCLKSOURCE_HSI HSI oscillator is used as system clock source. * @arg @ref RCC_SYSCLKSOURCE_HSE HSE oscillator is used as system clock source. + * @arg @ref RCC_SYSCLKSOURCE_HSIUSB48 HSIUSB48 oscillator is used as system clock source.(*) * @arg @ref RCC_SYSCLKSOURCE_LSI LSI oscillator is used as system clock source. * @arg @ref RCC_SYSCLKSOURCE_LSE LSE oscillator is used as system clock source. + * @note (*) peripheral not available on all devices * @retval None */ #define __HAL_RCC_SYSCLK_CONFIG(__SYSCLKSOURCE__) \ @@ -1509,8 +1808,10 @@ typedef struct * of the following: * @arg @ref RCC_SYSCLKSOURCE_STATUS_HSI HSI used as system clock. * @arg @ref RCC_SYSCLKSOURCE_STATUS_HSE HSE used as system clock. + * @arg @ref RCC_SYSCLKSOURCE_STATUS_HSIUSB48 HSIUSB48 used as system clock.(*) * @arg @ref RCC_SYSCLKSOURCE_STATUS_LSI LSI used as system clock source. * @arg @ref RCC_SYSCLKSOURCE_STATUS_LSE LSE used as system clock source. + * @note (*) peripheral not available on all devices */ #define __HAL_RCC_GET_SYSCLK_SOURCE() (RCC->CFGR & RCC_CFGR_SWS) @@ -1536,6 +1837,7 @@ typedef struct * @arg @ref RCC_MCO1SOURCE_HSE HSE clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_LSI LSI clock selected as MCO source * @arg @ref RCC_MCO1SOURCE_LSE LSE clock selected as MCO source + * @arg @ref RCC_MCO1SOURCE_HSI48 HSI48 clock selected as MCO source for devices with HSI48 (*) * @param __MCODIV__ specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg @ref RCC_MCODIV_1 MCO clock source is divided by 1 @@ -1546,11 +1848,15 @@ typedef struct * @arg @ref RCC_MCODIV_32 MCO clock source is divided by 32 * @arg @ref RCC_MCODIV_64 MCO clock source is divided by 64 * @arg @ref RCC_MCODIV_128 MCO clock source is divided by 128 + * @arg @ref RCC_MCODIV_256 MCO clock source is divided by 256 (*) + * @arg @ref RCC_MCODIV_512 MCO clock source is divided by 512 (*) + * @arg @ref RCC_MCODIV_1024 MCO clock source is divided by 1024 (*) + * @note (*) not available on all devices + * @retval None */ #define __HAL_RCC_MCO1_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCOSEL | RCC_CFGR_MCOPRE), ((__MCOCLKSOURCE__) | (__MCODIV__))) - /** @brief Macro to configure the MCO clock. * @param __MCOCLKSOURCE__ specifies the MCO clock source. * This parameter can be one of the following values: @@ -1560,6 +1866,7 @@ typedef struct * @arg @ref RCC_MCO2SOURCE_HSE HSE clock selected as MCO source * @arg @ref RCC_MCO2SOURCE_LSI LSI clock selected as MCO source * @arg @ref RCC_MCO2SOURCE_LSE LSE clock selected as MCO source + * @arg @ref RCC_MCO2SOURCE_HSI48 HSI48 clock selected as MCO2 source for devices with HSI48 (*) * @param __MCODIV__ specifies the MCO clock prescaler. * This parameter can be one of the following values: * @arg @ref RCC_MCO2DIV_1 MCO clock source is divided by 1 @@ -1570,6 +1877,11 @@ typedef struct * @arg @ref RCC_MCO2DIV_32 MCO clock source is divided by 32 * @arg @ref RCC_MCO2DIV_64 MCO clock source is divided by 64 * @arg @ref RCC_MCO2DIV_128 MCO clock source is divided by 128 + * @arg @ref RCC_MCO2DIV_256 MCO clock source is divided by 256 (*) + * @arg @ref RCC_MCO2DIV_512 MCO clock source is divided by 512 (*) + * @arg @ref RCC_MCO2DIV_1024 MCO clock source is divided by 1024 (*) + * @note (*) not available on all devices + * @retval None */ #define __HAL_RCC_MCO2_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCOSEL | RCC_CFGR_MCOPRE), ((__MCOCLKSOURCE__) | (__MCODIV__))) @@ -1588,6 +1900,8 @@ typedef struct * @arg @ref RCC_IT_LSERDY LSE ready interrupt * @arg @ref RCC_IT_HSIRDY HSI ready interrupt * @arg @ref RCC_IT_HSERDY HSE ready interrupt + * @arg @ref RCC_IT_HSI48RDY HSI48 ready interrupt for devices with HSI48 (*) + * @note (*) peripheral not available on all devices * @retval None */ #define __HAL_RCC_ENABLE_IT(__INTERRUPT__) SET_BIT(RCC->CIER, (__INTERRUPT__)) @@ -1599,6 +1913,8 @@ typedef struct * @arg @ref RCC_IT_LSERDY LSE ready interrupt * @arg @ref RCC_IT_HSIRDY HSI ready interrupt * @arg @ref RCC_IT_HSERDY HSE ready interrupt + * @arg @ref RCC_IT_HSI48RDY HSI48 ready interrupt for devices with HSI48 (*) + * @note (*) peripheral not available on all devices * @retval None */ #define __HAL_RCC_DISABLE_IT(__INTERRUPT__) CLEAR_BIT(RCC->CIER, (__INTERRUPT__)) @@ -1612,6 +1928,7 @@ typedef struct * @arg @ref RCC_IT_HSERDY HSE ready interrupt * @arg @ref RCC_IT_CSS HSE Clock security system interrupt * @arg @ref RCC_IT_LSECSS LSE Clock security system interrupt + * @arg @ref RCC_IT_HSI48RDY HSI48 ready interrupt for devices with HSI48 (*) * @retval None */ #define __HAL_RCC_CLEAR_IT(__INTERRUPT__) (RCC->CICR = (__INTERRUPT__)) @@ -1625,6 +1942,8 @@ typedef struct * @arg @ref RCC_IT_HSERDY HSE ready interrupt * @arg @ref RCC_IT_CSS HSE Clock security system interrupt * @arg @ref RCC_IT_LSECSS LSE Clock security system interrupt + * @arg @ref RCC_IT_HSI48RDY HSI48 ready interrupt for devices with HSI48 (*) + * @note (*) peripheral not available on all devices * @retval The new state of __INTERRUPT__ (TRUE or FALSE). */ #define __HAL_RCC_GET_IT(__INTERRUPT__) ((RCC->CIFR & (__INTERRUPT__)) == (__INTERRUPT__)) @@ -1644,6 +1963,7 @@ typedef struct * @arg @ref RCC_FLAG_LSERDY LSE oscillator clock ready * @arg @ref RCC_FLAG_LSECSSD Clock security system failure on LSE oscillator detection * @arg @ref RCC_FLAG_LSIRDY LSI oscillator clock ready + * @arg @ref RCC_IT_HSI48RDY HSI48 ready interrupt for devices with HSI48 (*) * @arg @ref RCC_FLAG_PWRRST BOR or POR/PDR reset * @arg @ref RCC_FLAG_OBLRST OBLRST reset * @arg @ref RCC_FLAG_PINRST Pin reset @@ -1651,6 +1971,7 @@ typedef struct * @arg @ref RCC_FLAG_IWDGRST Independent Watchdog reset * @arg @ref RCC_FLAG_WWDGRST Window Watchdog reset * @arg @ref RCC_FLAG_LPWRRST Low Power reset + * @note (*) peripheral not available on all devices * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_RCC_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5U) == RCC_CR_REG_INDEX) ? RCC->CR : \ @@ -1694,20 +2015,20 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *RCC_ClkInitStruc */ /* Peripheral Control functions ************************************************/ -void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); -void HAL_RCC_EnableCSS(void); -void HAL_RCC_EnableLSECSS(void); -void HAL_RCC_DisableLSECSS(void); -uint32_t HAL_RCC_GetSysClockFreq(void); -uint32_t HAL_RCC_GetHCLKFreq(void); -uint32_t HAL_RCC_GetPCLK1Freq(void); -void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); -void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); +void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); +void HAL_RCC_EnableCSS(void); +void HAL_RCC_EnableLSECSS(void); +void HAL_RCC_DisableLSECSS(void); +uint32_t HAL_RCC_GetSysClockFreq(void); +uint32_t HAL_RCC_GetHCLKFreq(void); +uint32_t HAL_RCC_GetPCLK1Freq(void); +void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); +void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, + uint32_t *pFLatency); /* LSE & HSE CSS NMI IRQ handler */ -void HAL_RCC_NMI_IRQHandler(void); -/* User Callbacks in non blocking mode (IT mode) */ -void HAL_RCC_CSSCallback(void); -void HAL_RCC_LSECSSCallback(void); +void HAL_RCC_NMI_IRQHandler(void); /* User Callbacks in non blocking mode (IT mode) */ +void HAL_RCC_CSSCallback(void); +void HAL_RCC_LSECSSCallback(void); /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc_ex.h index 7780e6e74..8e4b55820 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rcc_ex.h @@ -61,6 +61,11 @@ typedef struct uint32_t I2s1ClockSelection; /*!< Specifies I2S1 clock source This parameter can be a value of @ref RCCEx_I2S1_Clock_Source */ +#if defined(USB_DRD_FS) + uint32_t UsbClockSelection; /*!< Specifies USB clock source. + This parameter can be a value of @ref RCCEx_USB_Clock_Source */ +#endif /* USB_DRD_FS */ + uint32_t AdcClockSelection; /*!< Specifies ADC interface clock source This parameter can be a value of @ref RCCEx_ADC_Clock_Source */ @@ -68,6 +73,60 @@ typedef struct This parameter can be a value of @ref RCC_RTC_Clock_Source */ } RCC_PeriphCLKInitTypeDef; +#if defined (CRS) +/** + * @brief RCC_CRS Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the division factor of the SYNC signal. + This parameter can be a value of @ref RCCEx_CRS_SynchroDivider */ + + uint32_t Source; /*!< Specifies the SYNC signal source. + This parameter can be a value of @ref RCCEx_CRS_SynchroSource */ + + uint32_t Polarity; /*!< Specifies the input polarity for the SYNC signal source. + This parameter can be a value of @ref RCCEx_CRS_SynchroPolarity */ + + uint32_t ReloadValue; /*!< Specifies the value to be loaded in the frequency error counter with each SYNC + event. It can be calculated in using macro + @ref __HAL_RCC_CRS_RELOADVALUE_CALCULATE(__FTARGET__, __FSYNC__) + This parameter must be a number between 0 and 0xFFFF or a value of + @ref RCCEx_CRS_ReloadValueDefault .*/ + + uint32_t ErrorLimitValue; /*!< Specifies the value to be used to evaluate the captured frequency error value. + This parameter must be a number between 0 and 0xFF or a value of + @ref RCCEx_CRS_ErrorLimitDefault */ + + uint32_t HSI48CalibrationValue; /*!< Specifies a user-programmable trimming value to the HSI48 oscillator. + This parameter must be a number between 0 and 0x3F or a value of + @ref RCCEx_CRS_HSI48CalibrationDefault */ + +} RCC_CRSInitTypeDef; + +/** + * @brief RCC_CRS Synchronization structure definition + */ +typedef struct +{ + uint32_t ReloadValue; /*!< Specifies the value loaded in the Counter reload value. + This parameter must be a number between 0 and 0xFFFF */ + + uint32_t HSI48CalibrationValue; /*!< Specifies value loaded in RC48 oscillator smooth trimming. + This parameter must be a number between 0 and 0x3F */ + + uint32_t FreqErrorCapture; /*!< Specifies the value loaded in the .FECAP, the frequency error counter + value latched in the time of the last SYNC event. + This parameter must be a number between 0 and 0xFFFF */ + + uint32_t FreqErrorDirection; /*!< Specifies the value loaded in the .FEDIR, the counting direction of the + frequency error counter latched in the time of the last SYNC event. + It shows whether the actual frequency is below or above the target. + This parameter must be a value of @ref RCCEx_CRS_FreqErrorDirection*/ + +} RCC_CRSSynchroInfoTypeDef; + +#endif /* CRS */ /** * @} */ @@ -90,11 +149,14 @@ typedef struct * @{ */ #define RCC_PERIPHCLK_USART1 0x00000001U -#define RCC_PERIPHCLK_I2C1 0x00000040U -#define RCC_PERIPHCLK_I2S1 0x00000800U -#define RCC_PERIPHCLK_ADC 0x00004000U -#define RCC_PERIPHCLK_RTC 0x00020000U -#define RCC_PERIPHCLK_HSIKER 0x80000000U +#define RCC_PERIPHCLK_I2C1 0x00000002U +#define RCC_PERIPHCLK_I2S1 0x00000004U +#if defined(USB_DRD_FS) +#define RCC_PERIPHCLK_USB 0x00000008U +#endif /* USB_DRD_FS */ +#define RCC_PERIPHCLK_ADC 0x00000020U +#define RCC_PERIPHCLK_RTC 0x00000040U +#define RCC_PERIPHCLK_HSIKER 0x00000080U /** * @} @@ -116,9 +178,9 @@ typedef struct /** @defgroup RCCEx_I2C1_Clock_Source RCC I2C1 Clock Source * @{ */ -#define RCC_I2C1CLKSOURCE_PCLK1 0x00000000U /*!< APB clock selected as I2C1 clock */ -#define RCC_I2C1CLKSOURCE_SYSCLK RCC_CCIPR_I2C1SEL_0 /*!< SYSCLK clock selected as I2C1 clock */ -#define RCC_I2C1CLKSOURCE_HSIKER RCC_CCIPR_I2C1SEL_1 /*!< HSI Kernel clock selected as I2C1 clock */ +#define RCC_I2C1CLKSOURCE_PCLK1 0x00000000U /*!< APB clock selected as I2C1 clock */ +#define RCC_I2C1CLKSOURCE_SYSCLK RCC_CCIPR_I2C1SEL_0 /*!< SYSCLK clock selected as I2C1 clock */ +#define RCC_I2C1CLKSOURCE_HSIKER RCC_CCIPR_I2C1SEL_1 /*!< HSI Kernel clock selected as I2C1 clock */ /** * @} */ @@ -126,14 +188,23 @@ typedef struct /** @defgroup RCCEx_I2S1_Clock_Source RCC I2S1 Clock Source * @{ */ -#define RCC_I2S1CLKSOURCE_SYSCLK 0x00000000U /*!< SYSCLK clock selected as I2S1 clock */ -#define RCC_I2S1CLKSOURCE_HSIKER RCC_CCIPR_I2S1SEL_1 /*!< HSI Kernel clock selected as I2S1 clock */ -#define RCC_I2S1CLKSOURCE_EXT RCC_CCIPR_I2S1SEL /*!< External I2S clock source selected as I2S1 clock */ +#define RCC_I2S1CLKSOURCE_SYSCLK 0x00000000U /*!< SYSCLK clock selected as I2S1 clock */ +#define RCC_I2S1CLKSOURCE_HSIKER RCC_CCIPR_I2S1SEL_1 /*!< HSI Kernel clock selected as I2S1 clock */ +#define RCC_I2S1CLKSOURCE_EXT RCC_CCIPR_I2S1SEL /*!< External I2S clock source selected as I2S1 clock */ /** * @} */ - +#if defined(USB_DRD_FS) +/** @defgroup RCCEx_USB_Clock_Source USB Clock Source + * @{ + */ +#define RCC_USBCLKSOURCE_HSI48 0x00000000U +#define RCC_USBCLKSOURCE_HSE RCC_CCIPR2_USBSEL +/** + * @} + */ +#endif /* USB_DRD_FS */ /** @defgroup RCCEx_ADC_Clock_Source RCC ADC Clock Source * @{ @@ -160,6 +231,124 @@ typedef struct * @} */ +#if defined(CRS) + +/** @defgroup RCCEx_CRS_Status RCCEx CRS Status + * @{ + */ +#define RCC_CRS_NONE 0x00000000U +#define RCC_CRS_TIMEOUT 0x00000001U +#define RCC_CRS_SYNCOK 0x00000002U +#define RCC_CRS_SYNCWARN 0x00000004U +#define RCC_CRS_SYNCERR 0x00000008U +#define RCC_CRS_SYNCMISS 0x00000010U +#define RCC_CRS_TRIMOVF 0x00000020U +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroSource RCCEx CRS SynchroSource + * @{ + */ +#define RCC_CRS_SYNC_SOURCE_GPIO 0U /*!< Synchro Signal source GPIO */ +#define RCC_CRS_SYNC_SOURCE_LSE CRS_CFGR_SYNCSRC_0 /*!< Synchro Signal source LSE */ +#define RCC_CRS_SYNC_SOURCE_USB CRS_CFGR_SYNCSRC_1 /*!< Synchro Signal source USB SOF (default)*/ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroDivider RCCEx CRS SynchroDivider + * @{ + */ +#define RCC_CRS_SYNC_DIV1 0U /*!< Synchro Signal not divided (default) */ +#define RCC_CRS_SYNC_DIV2 CRS_CFGR_SYNCDIV_0 /*!< Synchro Signal divided by 2 */ +#define RCC_CRS_SYNC_DIV4 CRS_CFGR_SYNCDIV_1 /*!< Synchro Signal divided by 4 */ +#define RCC_CRS_SYNC_DIV8 (CRS_CFGR_SYNCDIV_1 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 8 */ +#define RCC_CRS_SYNC_DIV16 CRS_CFGR_SYNCDIV_2 /*!< Synchro Signal divided by 16 */ +#define RCC_CRS_SYNC_DIV32 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 32 */ +#define RCC_CRS_SYNC_DIV64 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_1) /*!< Synchro Signal divided by 64 */ +#define RCC_CRS_SYNC_DIV128 CRS_CFGR_SYNCDIV /*!< Synchro Signal divided by 128 */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroPolarity RCCEx CRS SynchroPolarity + * @{ + */ +#define RCC_CRS_SYNC_POLARITY_RISING 0U /*!< Synchro Active on rising edge (default) */ +#define RCC_CRS_SYNC_POLARITY_FALLING CRS_CFGR_SYNCPOL /*!< Synchro Active on falling edge */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_ReloadValueDefault RCCEx CRS ReloadValueDefault + * @{ + */ +#define RCC_CRS_RELOADVALUE_DEFAULT 0x0000BB7FU /*!< The reset value of the RELOAD field corresponds + to a target frequency of 48 MHz and a synchronization + signal frequency of 1 kHz (SOF signal from USB). */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_ErrorLimitDefault RCCEx CRS ErrorLimitDefault + * @{ + */ +#define RCC_CRS_ERRORLIMIT_DEFAULT 0x00000022U /*!< Default Frequency error limit */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_HSI48CalibrationDefault RCCEx CRS HSI48CalibrationDefault + * @{ + */ +#define RCC_CRS_HSI48CALIBRATION_DEFAULT 0x00000040U /*!< The default value is 64, which corresponds to the middle + of the trimming interval. The trimming step is specified in + the product datasheet. A higher TRIM value corresponds + to a higher output frequency */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_FreqErrorDirection RCCEx CRS FreqErrorDirection + * @{ + */ +#define RCC_CRS_FREQERRORDIR_UP 0U /*!< Upcounting direction, the actual frequency is above the target */ +#define RCC_CRS_FREQERRORDIR_DOWN CRS_ISR_FEDIR /*!< Downcounting direction, the actual frequency is below the target */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_Interrupt_Sources RCCEx CRS Interrupt Sources + * @{ + */ +#define RCC_CRS_IT_SYNCOK CRS_CR_SYNCOKIE /*!< SYNC event OK */ +#define RCC_CRS_IT_SYNCWARN CRS_CR_SYNCWARNIE /*!< SYNC warning */ +#define RCC_CRS_IT_ERR CRS_CR_ERRIE /*!< Error */ +#define RCC_CRS_IT_ESYNC CRS_CR_ESYNCIE /*!< Expected SYNC */ +#define RCC_CRS_IT_SYNCERR CRS_CR_ERRIE /*!< SYNC error */ +#define RCC_CRS_IT_SYNCMISS CRS_CR_ERRIE /*!< SYNC missed */ +#define RCC_CRS_IT_TRIMOVF CRS_CR_ERRIE /*!< Trimming overflow or underflow */ +/** + * @} + */ + +/** @defgroup RCCEx_CRS_Flags RCCEx CRS Flags + * @{ + */ +#define RCC_CRS_FLAG_SYNCOK CRS_ISR_SYNCOKF /*!< SYNC event OK flag */ +#define RCC_CRS_FLAG_SYNCWARN CRS_ISR_SYNCWARNF /*!< SYNC warning flag */ +#define RCC_CRS_FLAG_ERR CRS_ISR_ERRF /*!< Error flag */ +#define RCC_CRS_FLAG_ESYNC CRS_ISR_ESYNCF /*!< Expected SYNC flag */ +#define RCC_CRS_FLAG_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ +#define RCC_CRS_FLAG_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ +#define RCC_CRS_FLAG_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ +/** + * @} + */ + +#endif /* CRS */ + /** * @} */ @@ -228,6 +417,25 @@ typedef struct */ #define __HAL_RCC_GET_USART1_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_USART1SEL))) +#if defined(USB_DRD_FS) +/** @brief Macro to configure the CLK48 source (CLK48CLK). + * + * @param __USB_SOURCE__: specifies the CLK48 clock source. + * This parameter can be one of the following values: + * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB source + * @arg RCC_USBCLKSOURCE_HSE : HSE selected as USB source + */ +#define __HAL_RCC_USB_CONFIG(__USB_SOURCE__) \ + MODIFY_REG(RCC->CCIPR2, RCC_CCIPR2_USBSEL, (uint32_t)(__USB_SOURCE__)) + +/** @brief macro to get the USB source. + * @retval The clock source can be one of the following values: + * @arg RCC_USBCLKSOURCE_HSI48: HSI48 used as USB source + * @arg RCC_USBCLKSOURCE_HSE : HSE used as USB source + */ +#define __HAL_RCC_GET_USB_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR2, RCC_CCIPR2_USBSEL))) +#endif /* USB_DRD_FS */ + /** @brief Macro to configure the ADC interface clock * @param __ADC_CLKSOURCE__ specifies the ADC digital interface clock source. * This parameter can be one of the following values: @@ -279,16 +487,172 @@ typedef struct */ +/** + * @} + */ + +#if defined(CRS) + +/** + * @brief Enable the specified CRS interrupts. + * @param __INTERRUPT__ specifies the CRS interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg @ref RCC_CRS_IT_SYNCOK SYNC event OK interrupt + * @arg @ref RCC_CRS_IT_SYNCWARN SYNC warning interrupt + * @arg @ref RCC_CRS_IT_ERR Synchronization or trimming error interrupt + * @arg @ref RCC_CRS_IT_ESYNC Expected SYNC interrupt + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_IT(__INTERRUPT__) SET_BIT(CRS->CR, (__INTERRUPT__)) + +/** + * @brief Disable the specified CRS interrupts. + * @param __INTERRUPT__ specifies the CRS interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg @ref RCC_CRS_IT_SYNCOK SYNC event OK interrupt + * @arg @ref RCC_CRS_IT_SYNCWARN SYNC warning interrupt + * @arg @ref RCC_CRS_IT_ERR Synchronization or trimming error interrupt + * @arg @ref RCC_CRS_IT_ESYNC Expected SYNC interrupt + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_IT(__INTERRUPT__) CLEAR_BIT(CRS->CR, (__INTERRUPT__)) + +/** @brief Check whether the CRS interrupt has occurred or not. + * @param __INTERRUPT__ specifies the CRS interrupt source to check. + * This parameter can be one of the following values: + * @arg @ref RCC_CRS_IT_SYNCOK SYNC event OK interrupt + * @arg @ref RCC_CRS_IT_SYNCWARN SYNC warning interrupt + * @arg @ref RCC_CRS_IT_ERR Synchronization or trimming error interrupt + * @arg @ref RCC_CRS_IT_ESYNC Expected SYNC interrupt + * @retval The new state of __INTERRUPT__ (SET or RESET). + */ +#define __HAL_RCC_CRS_GET_IT_SOURCE(__INTERRUPT__) ((READ_BIT(CRS->CR, (__INTERRUPT__)) != 0U) ? SET : RESET) + +/** @brief Clear the CRS interrupt pending bits + * @param __INTERRUPT__ specifies the interrupt pending bit to clear. + * This parameter can be any combination of the following values: + * @arg @ref RCC_CRS_IT_SYNCOK SYNC event OK interrupt + * @arg @ref RCC_CRS_IT_SYNCWARN SYNC warning interrupt + * @arg @ref RCC_CRS_IT_ERR Synchronization or trimming error interrupt + * @arg @ref RCC_CRS_IT_ESYNC Expected SYNC interrupt + * @arg @ref RCC_CRS_IT_TRIMOVF Trimming overflow or underflow interrupt + * @arg @ref RCC_CRS_IT_SYNCERR SYNC error interrupt + * @arg @ref RCC_CRS_IT_SYNCMISS SYNC missed interrupt + */ +/* CRS IT Error Mask */ +#define RCC_CRS_IT_ERROR_MASK (RCC_CRS_IT_TRIMOVF | RCC_CRS_IT_SYNCERR | RCC_CRS_IT_SYNCMISS) + +#define __HAL_RCC_CRS_CLEAR_IT(__INTERRUPT__) do { \ + if(((__INTERRUPT__) & RCC_CRS_IT_ERROR_MASK) != 0U) \ + { \ + WRITE_REG(CRS->ICR, CRS_ICR_ERRC | \ + ((__INTERRUPT__) & ~RCC_CRS_IT_ERROR_MASK)); \ + } \ + else \ + { \ + WRITE_REG(CRS->ICR, (__INTERRUPT__)); \ + } \ + } while(0) + +/** + * @brief Check whether the specified CRS flag is set or not. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of the following values: + * @arg @ref RCC_CRS_FLAG_SYNCOK SYNC event OK + * @arg @ref RCC_CRS_FLAG_SYNCWARN SYNC warning + * @arg @ref RCC_CRS_FLAG_ERR Error + * @arg @ref RCC_CRS_FLAG_ESYNC Expected SYNC + * @arg @ref RCC_CRS_FLAG_TRIMOVF Trimming overflow or underflow + * @arg @ref RCC_CRS_FLAG_SYNCERR SYNC error + * @arg @ref RCC_CRS_FLAG_SYNCMISS SYNC missed + * @retval The new state of _FLAG_ (TRUE or FALSE). + */ +#define __HAL_RCC_CRS_GET_FLAG(__FLAG__) (READ_BIT(CRS->ISR, (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clear the CRS specified FLAG. + * @param __FLAG__ specifies the flag to clear. + * This parameter can be one of the following values: + * @arg @ref RCC_CRS_FLAG_SYNCOK SYNC event OK + * @arg @ref RCC_CRS_FLAG_SYNCWARN SYNC warning + * @arg @ref RCC_CRS_FLAG_ERR Error + * @arg @ref RCC_CRS_FLAG_ESYNC Expected SYNC + * @arg @ref RCC_CRS_FLAG_TRIMOVF Trimming overflow or underflow + * @arg @ref RCC_CRS_FLAG_SYNCERR SYNC error + * @arg @ref RCC_CRS_FLAG_SYNCMISS SYNC missed + * @note RCC_CRS_FLAG_ERR clears RCC_CRS_FLAG_TRIMOVF, RCC_CRS_FLAG_SYNCERR, RCC_CRS_FLAG_SYNCMISS and + * consequently RCC_CRS_FLAG_ERR + * @retval None + */ + +/* CRS Flag Error Mask */ +#define RCC_CRS_FLAG_ERROR_MASK (RCC_CRS_FLAG_TRIMOVF | RCC_CRS_FLAG_SYNCERR | RCC_CRS_FLAG_SYNCMISS) + +#define __HAL_RCC_CRS_CLEAR_FLAG(__FLAG__) do { \ + if(((__FLAG__) & RCC_CRS_FLAG_ERROR_MASK) != 0U) \ + { \ + WRITE_REG(CRS->ICR, CRS_ICR_ERRC | \ + ((__FLAG__) & ~RCC_CRS_FLAG_ERROR_MASK)); \ + } \ + else \ + { \ + WRITE_REG(CRS->ICR, (__FLAG__)); \ + } \ + } while(0) + /** * @} */ +/** @defgroup RCCEx_CRS_Extended_Features RCCEx CRS Extended Features + * @{ + */ +/** + * @brief Enable the oscillator clock for frequency error counter. + * @note when the CEN bit is set the CRS_CFGR register becomes write-protected. + * @retval None + */ +#define __HAL_RCC_CRS_FREQ_ERROR_COUNTER_ENABLE() SET_BIT(CRS->CR, CRS_CR_CEN) + +/** + * @brief Disable the oscillator clock for frequency error counter. + * @retval None + */ +#define __HAL_RCC_CRS_FREQ_ERROR_COUNTER_DISABLE() CLEAR_BIT(CRS->CR, CRS_CR_CEN) + +/** + * @brief Enable the automatic hardware adjustment of TRIM bits. + * @note When the AUTOTRIMEN bit is set the CRS_CFGR register becomes write-protected. + * @retval None + */ +#define __HAL_RCC_CRS_AUTOMATIC_CALIB_ENABLE() SET_BIT(CRS->CR, CRS_CR_AUTOTRIMEN) + +/** + * @brief Enable or disable the automatic hardware adjustment of TRIM bits. + * @retval None + */ +#define __HAL_RCC_CRS_AUTOMATIC_CALIB_DISABLE() CLEAR_BIT(CRS->CR, CRS_CR_AUTOTRIMEN) + +/** + * @brief Macro to calculate reload value to be set in CRS register according to target and sync frequencies + * @note The RELOAD value should be selected according to the ratio between the target frequency and the frequency + * of the synchronization source after prescaling. It is then decreased by one in order to + * reach the expected synchronization on the zero value. The formula is the following: + * RELOAD = (fTARGET / fSYNC) -1 + * @param __FTARGET__ Target frequency (value in Hz) + * @param __FSYNC__ Synchronization signal frequency (value in Hz) + * @retval None + */ +#define __HAL_RCC_CRS_RELOADVALUE_CALCULATE(__FTARGET__, __FSYNC__) (((__FTARGET__) / (__FSYNC__)) - 1U) + /** * @} */ +#endif /* CRS */ + /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCCEx_Exported_Functions * @{ @@ -317,6 +681,27 @@ void HAL_RCCEx_DisableLSCO(void); * @} */ +#if defined(CRS) + +/** @addtogroup RCCEx_Exported_Functions_Group3 + * @{ + */ + +void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit); +void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void); +void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo); +uint32_t HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout); +void HAL_RCCEx_CRS_IRQHandler(void); +void HAL_RCCEx_CRS_SyncOkCallback(void); +void HAL_RCCEx_CRS_SyncWarnCallback(void); +void HAL_RCCEx_CRS_ExpectedSyncCallback(void); +void HAL_RCCEx_CRS_ErrorCallback(uint32_t Error); + +/** + * @} + */ + +#endif /* CRS */ /** * @} @@ -330,15 +715,24 @@ void HAL_RCCEx_DisableLSCO(void); #define IS_RCC_LSCOSOURCE(__SOURCE__) (((__SOURCE__) == RCC_LSCOSOURCE_LSI) || \ ((__SOURCE__) == RCC_LSCOSOURCE_LSE)) - +#if defined (USB_DRD_FS) #define IS_RCC_PERIPHCLOCK(__SELECTION__) \ ((((__SELECTION__) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) || \ (((__SELECTION__) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1) || \ (((__SELECTION__) & RCC_PERIPHCLK_I2S1) == RCC_PERIPHCLK_I2S1) || \ (((__SELECTION__) & RCC_PERIPHCLK_ADC) == RCC_PERIPHCLK_ADC) || \ + (((__SELECTION__) & RCC_PERIPHCLK_USB) == RCC_PERIPHCLK_USB) || \ (((__SELECTION__) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC) || \ (((__SELECTION__) & RCC_PERIPHCLK_HSIKER) == RCC_PERIPHCLK_HSIKER)) - +#else +#define IS_RCC_PERIPHCLOCK(__SELECTION__) \ + ((((__SELECTION__) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_I2S1) == RCC_PERIPHCLK_I2S1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_ADC) == RCC_PERIPHCLK_ADC) || \ + (((__SELECTION__) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC) || \ + (((__SELECTION__) & RCC_PERIPHCLK_HSIKER) == RCC_PERIPHCLK_HSIKER)) +#endif /* USB_DRD_FS */ #define IS_RCC_USART1CLKSOURCE(__SOURCE__) \ (((__SOURCE__) == RCC_USART1CLKSOURCE_PCLK1) || \ @@ -356,6 +750,11 @@ void HAL_RCCEx_DisableLSCO(void); ((__SOURCE__) == RCC_I2S1CLKSOURCE_HSIKER) || \ ((__SOURCE__) == RCC_I2S1CLKSOURCE_EXT)) +#if defined (USB_DRD_FS) +#define IS_RCC_USBCLKSOURCE(__SOURCE__) \ + (((__SOURCE__) == RCC_USBCLKSOURCE_HSE) || \ + ((__SOURCE__) == RCC_USBCLKSOURCE_HSI48)) +#endif /* USB_DRD_FS */ #define IS_RCC_ADCCLKSOURCE(__SOURCE__) \ (((__SOURCE__) == RCC_ADCCLKSOURCE_SYSCLK) || \ @@ -365,6 +764,35 @@ void HAL_RCCEx_DisableLSCO(void); ((__DIV__) == RCC_HSIKER_DIV3) || ((__DIV__) == RCC_HSIKER_DIV4) || \ ((__DIV__) == RCC_HSIKER_DIV5) || ((__DIV__) == RCC_HSIKER_DIV6) || \ ((__DIV__) == RCC_HSIKER_DIV7) || ((__DIV__) == RCC_HSIKER_DIV8)) + +#if defined(CRS) + +#define IS_RCC_CRS_SYNC_SOURCE(__SOURCE__) (((__SOURCE__) == RCC_CRS_SYNC_SOURCE_GPIO) || \ + ((__SOURCE__) == RCC_CRS_SYNC_SOURCE_LSE) || \ + ((__SOURCE__) == RCC_CRS_SYNC_SOURCE_USB)) + +#define IS_RCC_CRS_SYNC_DIV(__DIV__) (((__DIV__) == RCC_CRS_SYNC_DIV1) || ((__DIV__) == RCC_CRS_SYNC_DIV2) || \ + ((__DIV__) == RCC_CRS_SYNC_DIV4) || ((__DIV__) == RCC_CRS_SYNC_DIV8) || \ + ((__DIV__) == RCC_CRS_SYNC_DIV16) || ((__DIV__) == RCC_CRS_SYNC_DIV32) || \ + ((__DIV__) == RCC_CRS_SYNC_DIV64) || ((__DIV__) == RCC_CRS_SYNC_DIV128)) + +#define IS_RCC_CRS_SYNC_POLARITY(__POLARITY__) (((__POLARITY__) == RCC_CRS_SYNC_POLARITY_RISING) || \ + ((__POLARITY__) == RCC_CRS_SYNC_POLARITY_FALLING)) + +#define IS_RCC_CRS_RELOADVALUE(__VALUE__) (((__VALUE__) <= 0xFFFFU)) + +#define IS_RCC_CRS_ERRORLIMIT(__VALUE__) (((__VALUE__) <= 0xFFU)) + +#define IS_RCC_CRS_HSI48CALIBRATION(__VALUE__) (((__VALUE__) <= 0x7FU)) + +#define IS_RCC_CRS_FREQERRORDIR(__DIR__) (((__DIR__) == RCC_CRS_FREQERRORDIR_UP) || \ + ((__DIR__) == RCC_CRS_FREQERRORDIR_DOWN)) + +#endif /* CRS */ +/** + * @} + */ + /** * @} */ @@ -382,4 +810,3 @@ void HAL_RCCEx_DisableLSCO(void); #endif #endif /* STM32C0xx_HAL_RCC_EX_H */ - diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc.h index ece33186d..522754443 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc.h @@ -89,8 +89,10 @@ typedef struct typedef struct { uint8_t Hours; /*!< Specifies the RTC Time Hour. - This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HOURFORMAT_12 is selected. - This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HOURFORMAT_24 is selected */ + This parameter must be a number between Min_Data = 0 and Max_Data = 12 + if the RTC_HOURFORMAT_12 is selected. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 + if the RTC_HOURFORMAT_24 is selected */ uint8_t Minutes; /*!< Specifies the RTC Time Minutes. This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ @@ -155,8 +157,10 @@ typedef struct This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. - If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. - If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ + If the Alarm Date is selected, this parameter must be set to a value + in the 1-31 range. + If the Alarm WeekDay is selected, this parameter can be a value of + @ref RTC_WeekDay_Definitions */ uint32_t Alarm; /*!< Specifies the alarm . This parameter can be a value of @ref RTC_Alarms_Definitions */ @@ -169,7 +173,7 @@ typedef struct typedef struct __RTC_HandleTypeDef #else typedef struct -#endif +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ { RTC_TypeDef *Instance; /*!< Register base address */ @@ -389,39 +393,56 @@ typedef void (*pRTC_CallbackTypeDef)(RTC_HandleTypeDef *hrtc); /*!< pointer to /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions RTC Alarm Sub Seconds Masks Definitions * @{ */ -#define RTC_ALARMSUBSECONDMASK_ALL 0U /*!< All Alarm SS fields are masked. - There is no comparison on sub seconds - for Alarm */ -#define RTC_ALARMSUBSECONDMASK_SS14_1 RTC_ALRMASSR_MASKSS_0 /*!< SS[14:1] not used in Alarm - comparison. Only SS[0] is compared. */ -#define RTC_ALARMSUBSECONDMASK_SS14_2 RTC_ALRMASSR_MASKSS_1 /*!< SS[14:2] not used in Alarm - comparison. Only SS[1:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_3 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_1) /*!< SS[14:3] not used in Alarm - comparison. Only SS[2:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_4 RTC_ALRMASSR_MASKSS_2 /*!< SS[14:4] not used in Alarm - comparison. Only SS[3:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_5 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_2) /*!< SS[14:5] not used in Alarm - comparison. Only SS[4:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_6 (RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_2) /*!< SS[14:6] not used in Alarm - comparison. Only SS[5:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_7 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_2) /*!< SS[14:7] not used in Alarm - comparison. Only SS[6:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_8 RTC_ALRMASSR_MASKSS_3 /*!< SS[14:8] not used in Alarm - comparison. Only SS[7:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_9 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:9] not used in Alarm - comparison. Only SS[8:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_10 (RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:10] not used in Alarm - comparison. Only SS[9:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_11 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:11] not used in Alarm - comparison. Only SS[10:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_12 (RTC_ALRMASSR_MASKSS_2 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:12] not used in Alarm - comparison.Only SS[11:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14_13 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_2 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:13] not used in Alarm - comparison. Only SS[12:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_SS14 (RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_2 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14] not used in Alarm - comparison.Only SS[13:0] are compared */ -#define RTC_ALARMSUBSECONDMASK_NONE RTC_ALRMASSR_MASKSS /*!< SS[14:0] are compared and must match - to activate alarm. */ +#define RTC_ALARMSUBSECONDMASK_ALL 0x00000000U /*!< All Alarm SS fields are masked. + There is no comparison on sub seconds + for Alarm */ +#define RTC_ALARMSUBSECONDMASK_SS14_1 RTC_ALRMASSR_MASKSS_0 /*!< SS[14:1] not used in Alarm + comparison. Only SS[0] is compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_2 RTC_ALRMASSR_MASKSS_1 /*!< SS[14:2] not used in Alarm + comparison. Only SS[1:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_3 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_1) /*!< SS[14:3] not used in Alarm + comparison. Only SS[2:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_4 RTC_ALRMASSR_MASKSS_2 /*!< SS[14:4] not used in Alarm + comparison. Only SS[3:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_5 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_2) /*!< SS[14:5] not used in Alarm + comparison. Only SS[4:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_6 (RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_2) /*!< SS[14:6] not used in Alarm + comparison.Only SS[5:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_7 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_1 | \ + RTC_ALRMASSR_MASKSS_2) /*!< SS[14:7] not used in Alarm + comparison. Only SS[6:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_8 RTC_ALRMASSR_MASKSS_3 /*!< SS[14:8] not used in Alarm + comparison. Only SS[7:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_9 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:9] not used in Alarm + comparison. Only SS[8:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_10 (RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:10] not used in + Alarm comparison. Only + SS[9:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_11 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_1 | \ + RTC_ALRMASSR_MASKSS_3) /*!< SS[14:11] not used in + Alarm comparison. Only + SS[10:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_12 (RTC_ALRMASSR_MASKSS_2 | RTC_ALRMASSR_MASKSS_3) /*!< SS[14:12] not used in + Alarm comparison. Only + SS[11:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_13 (RTC_ALRMASSR_MASKSS_0 | RTC_ALRMASSR_MASKSS_2 | \ + RTC_ALRMASSR_MASKSS_3) /*!< SS[14:13] not used in + Alarm comparison. Only + SS[12:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14 (RTC_ALRMASSR_MASKSS_1 | RTC_ALRMASSR_MASKSS_2 | \ + RTC_ALRMASSR_MASKSS_3) /*!< SS[14] not used in Alarm + comparison. Only SS[13:0] + are compared */ +#define RTC_ALARMSUBSECONDMASK_NONE RTC_ALRMASSR_MASKSS /*!< SS[14:0] are compared and + must match to activate + alarm. */ /** * @} */ @@ -458,7 +479,6 @@ typedef void (*pRTC_CallbackTypeDef)(RTC_HandleTypeDef *hrtc); /*!< pointer to #define RTC_FLAG_INITS (0x00000100U | RTC_ICSR_INITS_Pos) /*!< Initialization status flag */ #define RTC_FLAG_SHPF (0x00000100U | RTC_ICSR_SHPF_Pos) /*!< Shift operation pending flag */ #define RTC_FLAG_ALRAWF (0x00000100U | RTC_ICSR_ALRAWF_Pos) /*!< Alarm A write flag */ -#define RTC_FLAG_ITSF (0x00000200U | RTC_SR_ITSF_Pos) /*!< Internal Time-stamp flag */ #define RTC_FLAG_TSOVF (0x00000200U | RTC_SR_TSOVF_Pos) /*!< Time-stamp overflow flag */ #define RTC_FLAG_TSF (0x00000200U | RTC_SR_TSF_Pos) /*!< Time-stamp flag */ #define RTC_FLAG_ALRAF (0x00000200U | RTC_SR_ALRAF_Pos) /*!< Alarm A flag */ @@ -469,7 +489,6 @@ typedef void (*pRTC_CallbackTypeDef)(RTC_HandleTypeDef *hrtc); /*!< pointer to /** @defgroup RTC_Clear_Flags_Definitions RTC Clear Flags Definitions * @{ */ -#define RTC_CLEAR_ITSF RTC_SCR_CITSF /*!< Clear Internal Time-stamp flag */ #define RTC_CLEAR_TSOVF RTC_SCR_CTSOVF /*!< Clear Time-stamp overflow flag */ #define RTC_CLEAR_TSF RTC_SCR_CTSF /*!< Clear Time-stamp flag */ #define RTC_CLEAR_ALRAF RTC_SCR_CALRAF /*!< Clear Alarm A flag */ @@ -526,7 +545,8 @@ typedef void (*pRTC_CallbackTypeDef)(RTC_HandleTypeDef *hrtc); /*!< pointer to * @param __HANDLE__ specifies the RTC handle. * @retval None */ -#define __HAL_RTC_IS_CALENDAR_INITIALIZED(__HANDLE__) (((((__HANDLE__)->Instance->ICSR) & (RTC_ICSR_INITS)) == RTC_ICSR_INITS) ? 1U : 0U) +#define __HAL_RTC_IS_CALENDAR_INITIALIZED(__HANDLE__) (((((__HANDLE__)->Instance->ICSR) &\ + (RTC_ICSR_INITS)) == RTC_ICSR_INITS) ? 1U : 0U) /** * @brief Add 1 hour (summer time change). @@ -703,7 +723,7 @@ HAL_StatusTypeDef HAL_RTC_UnRegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_Ca HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); -HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_GetDate(const RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); /** * @} */ @@ -715,7 +735,8 @@ HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDat HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); -HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_GetAlarm(const RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, + uint32_t Format); void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); @@ -736,7 +757,7 @@ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef *hrtc); * @{ */ /* Peripheral State functions *************************************************/ -HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); +HAL_RTCStateTypeDef HAL_RTC_GetState(const RTC_HandleTypeDef *hrtc); /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc_ex.h index 4c94535d3..5aaabf23a 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_rtc_ex.h @@ -128,13 +128,12 @@ extern "C" { * @param __HANDLE__ specifies the RTC Handle. * @param __FLAG__ specifies the flag to check. * This parameter can be any combination of the following values: - * @arg @ref RTC_CLEAR_ITSF Clear Internal Time-stamp flag * @arg @ref RTC_CLEAR_TSOVF Clear Time-stamp overflow flag * @arg @ref RTC_CLEAR_TSF Clear Time-stamp flag * @arg @ref RTC_CLEAR_ALRAF Clear Alarm A flag * @retval None */ -#define __HAL_RTC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SCR |= (__FLAG__)) +#define __HAL_RTC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SCR = (__FLAG__)) /** @brief Check whether the specified RTC flag is set or not. * @param __HANDLE__ specifies the RTC Handle. @@ -146,15 +145,16 @@ extern "C" { * @arg @ref RTC_FLAG_INITS Initialization status flag * @arg @ref RTC_FLAG_SHPF Shift operation pending flag * @arg @ref RTC_FLAG_ALRAWF Alarm A write flag - * @arg @ref RTC_FLAG_ITSF Internal Time-stamp flag * @arg @ref RTC_FLAG_TSOVF Time-stamp overflow flag * @arg @ref RTC_FLAG_TSF Time-stamp flag * @arg @ref RTC_FLAG_ALRAF Alarm A flag * @retval None */ -#define __HAL_RTC_GET_FLAG(__HANDLE__, __FLAG__) (((((__FLAG__)) >> 8U) == 1U) ? ((((__HANDLE__)->Instance->ICSR & (1U << (((uint16_t)(__FLAG__)) & RTC_FLAG_MASK))) != 0U) ? 1U : 0U) :\ - ((((__HANDLE__)->Instance->SR & (1U << (((uint16_t)(__FLAG__)) & RTC_FLAG_MASK))) != 0U) ? 1U : 0U)) - +#define __HAL_RTC_GET_FLAG(__HANDLE__, __FLAG__) \ + (((((__FLAG__)) >> 8U) == 1U) ? ((((__HANDLE__)->Instance->ICSR & (1U << (((uint16_t)(__FLAG__)) & RTC_FLAG_MASK))) \ + != 0U) ? 1U : 0U) : \ + ((((__HANDLE__)->Instance->SR & (1U << (((uint16_t)(__FLAG__)) & RTC_FLAG_MASK))) \ + != 0U) ? 1U : 0U)) /* ---------------------------------TIMESTAMP---------------------------------*/ /** @defgroup RTCEx_Timestamp RTC Timestamp @@ -236,7 +236,10 @@ extern "C" { * @arg @ref RTC_FLAG_TSOVF * @retval None */ -#define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) (__HAL_RTC_CLEAR_FLAG((__HANDLE__), (__FLAG__))) +#define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) \ + (((__FLAG__) == RTC_FLAG_TSF) ? \ + (__HAL_RTC_CLEAR_FLAG((__HANDLE__), RTC_CLEAR_TSF)) : \ + (__HAL_RTC_CLEAR_FLAG((__HANDLE__), RTC_CLEAR_TSOVF))) /** * @brief Enable interrupt on the RTC Timestamp associated Exti line. @@ -262,40 +265,6 @@ extern "C" { */ #define __HAL_RTC_TIMESTAMP_EXTI_DISABLE_EVENT() (EXTI->EMR1 &= ~(RTC_EXTI_LINE_TIMESTAMP_EVENT)) -/** - * @brief Enable the RTC internal TimeStamp peripheral. - * @param __HANDLE__ specifies the RTC handle. - * @retval None - */ -#define __HAL_RTC_INTERNAL_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ITSE)) - -/** - * @brief Disable the RTC internal TimeStamp peripheral. - * @param __HANDLE__ specifies the RTC handle. - * @retval None - */ -#define __HAL_RTC_INTERNAL_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ITSE)) - -/** - * @brief Get the selected RTC Internal Time Stamps flag status. - * @param __HANDLE__ specifies the RTC handle. - * @param __FLAG__ specifies the RTC Internal Time Stamp Flag is pending or not. - * This parameter can be: - * @arg @ref RTC_FLAG_ITSF - * @retval None - */ -#define __HAL_RTC_INTERNAL_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (__HAL_RTC_GET_FLAG((__HANDLE__),(__FLAG__))) - -/** - * @brief Clear the RTC Internal Time Stamps pending flags. - * @param __HANDLE__ specifies the RTC handle. - * @param __FLAG__ specifies the RTC Internal Time Stamp Flag source to clear. - * This parameter can be: - * @arg @ref RTC_FLAG_ITSF - * @retval None - */ -#define __HAL_RTC_INTERNAL_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) (__HAL_RTC_CLEAR_FLAG((__HANDLE__), RTC_CLEAR_ITSF)) - /** * @} */ @@ -367,8 +336,6 @@ extern "C" { HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); -HAL_StatusTypeDef HAL_RTCEx_SetInternalTimeStamp(RTC_HandleTypeDef *hrtc); -HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTimeStamp(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc); @@ -413,7 +380,7 @@ HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); /** @defgroup RTCEx_Private_Constants RTCEx Private Constants * @{ */ -#define RTC_EXTI_LINE_TIMESTAMP_EVENT EXTI_IMR1_IM21 /*!< External interrupt line 19 Connected to the RTC Time Stamp events */ +#define RTC_EXTI_LINE_TIMESTAMP_EVENT EXTI_IMR1_IM19 /*!< External interrupt line 19 Connected to the RTC Time Stamp events */ /** * @} @@ -454,7 +421,6 @@ HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); ((SEL) == RTC_SHIFTADD1S_SET)) - /** @defgroup RTCEx_Subtract_Fraction_Of_Second_Value RTCEx SubtractFraction Of Second Value * @{ */ @@ -474,7 +440,6 @@ HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); */ - /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus.h index 189f8c0cd..288309ab3 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus.h @@ -100,8 +100,6 @@ typedef struct #define HAL_SMBUS_STATE_MASTER_BUSY_RX (0x00000022U) /*!< Master Data Reception process is ongoing */ #define HAL_SMBUS_STATE_SLAVE_BUSY_TX (0x00000032U) /*!< Slave Data Transmission process is ongoing */ #define HAL_SMBUS_STATE_SLAVE_BUSY_RX (0x00000042U) /*!< Slave Data Reception process is ongoing */ -#define HAL_SMBUS_STATE_TIMEOUT (0x00000003U) /*!< Timeout state */ -#define HAL_SMBUS_STATE_ERROR (0x00000004U) /*!< Reception process is ongoing */ #define HAL_SMBUS_STATE_LISTEN (0x00000008U) /*!< Address Listen Mode is ongoing */ /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus_ex.h index 84e2e5ed7..539d10902 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_smbus_ex.h @@ -57,6 +57,11 @@ extern "C" { #define SMBUS_FASTMODEPLUS_PB9 (uint32_t)(0x00000012U | SMBUS_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus PB9 not supported */ #endif /* SYSCFG_CFGR1_I2C_PB8_FMP */ #define SMBUS_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C1_FMP /*!< Enable Fast Mode Plus on I2C1 pins */ +#if defined(SYSCFG_CFGR1_I2C2_FMP) +#define SMBUS_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C2_FMP /*!< Enable Fast Mode Plus on I2C2 pins */ +#else +#define SMBUS_FASTMODEPLUS_I2C2 (uint32_t)(0x00000200U | SMBUS_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus I2C2 not supported */ +#endif /* SYSCFG_CFGR1_I2C2_FMP */ /** * @} */ @@ -83,8 +88,10 @@ extern "C" { * @{ */ /* Peripheral Control functions ************************************************/ +#if defined(I2C_CR1_WUPEN) HAL_StatusTypeDef HAL_SMBUSEx_EnableWakeUp(SMBUS_HandleTypeDef *hsmbus); HAL_StatusTypeDef HAL_SMBUSEx_DisableWakeUp(SMBUS_HandleTypeDef *hsmbus); +#endif /* I2C_CR1_WUPEN */ /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi.h index 9bf12408f..04dcb148e 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi.h @@ -118,7 +118,7 @@ typedef struct __SPI_HandleTypeDef SPI_InitTypeDef Init; /*!< SPI communication parameters */ - uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ + const uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /*!< SPI Tx Transfer size */ @@ -778,7 +778,7 @@ void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); /* Callbacks Register/UnRegister functions ***********************************/ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) HAL_StatusTypeDef HAL_SPI_RegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_CallbackIDTypeDef CallbackID, -pSPI_CallbackTypeDef pCallback); + pSPI_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_CallbackIDTypeDef CallbackID); #endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ /** @@ -789,18 +789,18 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @{ */ /* I/O operation functions ***************************************************/ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, -uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, -uint16_t Size); -HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, -uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); @@ -825,8 +825,8 @@ void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi); * @{ */ /* Peripheral State and Error functions ***************************************/ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi); +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi); /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi_ex.h index 9981cede3..de3f282aa 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_spi_ex.h @@ -48,7 +48,7 @@ extern "C" { /** @addtogroup SPIEx_Exported_Functions_Group1 * @{ */ -HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(SPI_HandleTypeDef *hspi); +HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(const SPI_HandleTypeDef *hspi); /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_tim.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_tim.h index 3a2ab02e7..d4a7d38d1 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_tim.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_tim.h @@ -402,29 +402,28 @@ typedef struct */ typedef enum { - HAL_TIM_BASE_MSPINIT_CB_ID = 0x00U /*!< TIM Base MspInit Callback ID */ - , HAL_TIM_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TIM Base MspDeInit Callback ID */ - , HAL_TIM_IC_MSPINIT_CB_ID = 0x02U /*!< TIM IC MspInit Callback ID */ - , HAL_TIM_IC_MSPDEINIT_CB_ID = 0x03U /*!< TIM IC MspDeInit Callback ID */ - , HAL_TIM_OC_MSPINIT_CB_ID = 0x04U /*!< TIM OC MspInit Callback ID */ - , HAL_TIM_OC_MSPDEINIT_CB_ID = 0x05U /*!< TIM OC MspDeInit Callback ID */ - , HAL_TIM_PWM_MSPINIT_CB_ID = 0x06U /*!< TIM PWM MspInit Callback ID */ - , HAL_TIM_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TIM PWM MspDeInit Callback ID */ - , HAL_TIM_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TIM One Pulse MspInit Callback ID */ - , HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TIM One Pulse MspDeInit Callback ID */ - , HAL_TIM_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TIM Encoder MspInit Callback ID */ - , HAL_TIM_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TIM Encoder MspDeInit Callback ID */ - , HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TIM Hall Sensor MspDeInit Callback ID */ - , HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TIM Hall Sensor MspDeInit Callback ID */ + HAL_TIM_BASE_MSPINIT_CB_ID = 0x00U /*!< TIM Base MspInit Callback ID */ + , HAL_TIM_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TIM Base MspDeInit Callback ID */ + , HAL_TIM_IC_MSPINIT_CB_ID = 0x02U /*!< TIM IC MspInit Callback ID */ + , HAL_TIM_IC_MSPDEINIT_CB_ID = 0x03U /*!< TIM IC MspDeInit Callback ID */ + , HAL_TIM_OC_MSPINIT_CB_ID = 0x04U /*!< TIM OC MspInit Callback ID */ + , HAL_TIM_OC_MSPDEINIT_CB_ID = 0x05U /*!< TIM OC MspDeInit Callback ID */ + , HAL_TIM_PWM_MSPINIT_CB_ID = 0x06U /*!< TIM PWM MspInit Callback ID */ + , HAL_TIM_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TIM PWM MspDeInit Callback ID */ + , HAL_TIM_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TIM One Pulse MspInit Callback ID */ + , HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TIM One Pulse MspDeInit Callback ID */ + , HAL_TIM_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TIM Encoder MspInit Callback ID */ + , HAL_TIM_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TIM Encoder MspDeInit Callback ID */ + , HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TIM Hall Sensor MspDeInit Callback ID */ + , HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TIM Hall Sensor MspDeInit Callback ID */ , HAL_TIM_PERIOD_ELAPSED_CB_ID = 0x0EU /*!< TIM Period Elapsed Callback ID */ , HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID = 0x0FU /*!< TIM Period Elapsed half complete Callback ID */ , HAL_TIM_TRIGGER_CB_ID = 0x10U /*!< TIM Trigger Callback ID */ , HAL_TIM_TRIGGER_HALF_CB_ID = 0x11U /*!< TIM Trigger half complete Callback ID */ - , HAL_TIM_IC_CAPTURE_CB_ID = 0x12U /*!< TIM Input Capture Callback ID */ , HAL_TIM_IC_CAPTURE_HALF_CB_ID = 0x13U /*!< TIM Input Capture half complete Callback ID */ , HAL_TIM_OC_DELAY_ELAPSED_CB_ID = 0x14U /*!< TIM Output Compare Delay Elapsed Callback ID */ - , HAL_TIM_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TIM PWM Pulse Finished Callback ID */ + , HAL_TIM_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TIM PWM Pulse Finished Callback ID */ , HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID = 0x16U /*!< TIM PWM Pulse Finished half complete Callback ID */ , HAL_TIM_ERROR_CB_ID = 0x17U /*!< TIM Error Callback ID */ , HAL_TIM_COMMUTATION_CB_ID = 0x18U /*!< TIM Commutation Callback ID */ @@ -1025,8 +1024,8 @@ typedef void (*pTIM_CallbackTypeDef)(TIM_HandleTypeDef *htim); /*!< pointer to #define TIM_OCMODE_RETRIGERRABLE_OPM2 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_0) /*!< Retrigerrable OPM mode 2 */ #define TIM_OCMODE_COMBINED_PWM1 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_2) /*!< Combined PWM mode 1 */ #define TIM_OCMODE_COMBINED_PWM2 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) /*!< Combined PWM mode 2 */ -#define TIM_OCMODE_ASSYMETRIC_PWM1 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) /*!< Asymmetric PWM mode 1 */ -#define TIM_OCMODE_ASSYMETRIC_PWM2 TIM_CCMR1_OC1M /*!< Asymmetric PWM mode 2 */ +#define TIM_OCMODE_ASYMMETRIC_PWM1 (TIM_CCMR1_OC1M_3 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) /*!< Asymmetric PWM mode 1 */ +#define TIM_OCMODE_ASYMMETRIC_PWM2 TIM_CCMR1_OC1M /*!< Asymmetric PWM mode 2 */ /** * @} */ @@ -1135,10 +1134,7 @@ typedef void (*pTIM_CallbackTypeDef)(TIM_HandleTypeDef *htim); /*!< pointer to /** @defgroup TIM_Break_System TIM Break System * @{ */ -#define TIM_BREAK_SYSTEM_ECC SYSCFG_CFGR2_ECCL /*!< Enables and locks the ECC error signal with Break Input of TIM1/15/16/17 */ -#define TIM_BREAK_SYSTEM_PVD SYSCFG_CFGR2_PVDL /*!< Enables and locks the PVD connection with TIM1/15/16/17 Break Input and also the PVDE and PLS bits of the Power Control Interface */ -#define TIM_BREAK_SYSTEM_SRAM_PARITY_ERROR SYSCFG_CFGR2_SPL /*!< Enables and locks the SRAM_PARITY error signal with Break Input of TIM1/15/16/17 */ -#define TIM_BREAK_SYSTEM_LOCKUP SYSCFG_CFGR2_CLL /*!< Enables and locks the LOCKUP output of CortexM4 with Break Input of TIM1/15/16/17 */ +#define TIM_BREAK_SYSTEM_LOCKUP SYSCFG_CFGR2_CLL /*!< Enables and locks the LOCKUP (Hardfault) output of CortexM0 with Break Input of TIM1/16/17 */ /** * @} */ @@ -1868,8 +1864,9 @@ mode. #define IS_TIM_OPM_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TIM_CHANNEL_1) || \ ((__CHANNEL__) == TIM_CHANNEL_2)) -#define IS_TIM_PERIOD(__HANDLE__, __PERIOD__) \ - ((IS_TIM_32B_COUNTER_INSTANCE(((__HANDLE__)->Instance)) == 0U) ? (((__PERIOD__) > 0U) && ((__PERIOD__) <= 0x0000FFFFU)) : ((__PERIOD__) > 0U)) +#define IS_TIM_PERIOD(__HANDLE__, __PERIOD__) ((IS_TIM_32B_COUNTER_INSTANCE(((__HANDLE__)->Instance)) == 0U) ? \ + (((__PERIOD__) > 0U) && ((__PERIOD__) <= 0x0000FFFFU)) : \ + ((__PERIOD__) > 0U)) #define IS_TIM_COMPLEMENTARY_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TIM_CHANNEL_1) || \ ((__CHANNEL__) == TIM_CHANNEL_2) || \ @@ -1936,7 +1933,6 @@ mode. #define IS_TIM_BREAK_FILTER(__BRKFILTER__) ((__BRKFILTER__) <= 0xFUL) - #define IS_TIM_BREAK_STATE(__STATE__) (((__STATE__) == TIM_BREAK_ENABLE) || \ ((__STATE__) == TIM_BREAK_DISABLE)) @@ -2003,8 +1999,8 @@ mode. ((__MODE__) == TIM_OCMODE_PWM2) || \ ((__MODE__) == TIM_OCMODE_COMBINED_PWM1) || \ ((__MODE__) == TIM_OCMODE_COMBINED_PWM2) || \ - ((__MODE__) == TIM_OCMODE_ASSYMETRIC_PWM1) || \ - ((__MODE__) == TIM_OCMODE_ASSYMETRIC_PWM2)) + ((__MODE__) == TIM_OCMODE_ASYMMETRIC_PWM1) || \ + ((__MODE__) == TIM_OCMODE_ASYMMETRIC_PWM2)) #define IS_TIM_OC_MODE(__MODE__) (((__MODE__) == TIM_OCMODE_TIMING) || \ ((__MODE__) == TIM_OCMODE_ACTIVE) || \ @@ -2083,10 +2079,7 @@ mode. #define IS_TIM_DEADTIME(__DEADTIME__) ((__DEADTIME__) <= 0xFFU) -#define IS_TIM_BREAK_SYSTEM(__CONFIG__) (((__CONFIG__) == TIM_BREAK_SYSTEM_ECC) || \ - ((__CONFIG__) == TIM_BREAK_SYSTEM_PVD) || \ - ((__CONFIG__) == TIM_BREAK_SYSTEM_SRAM_PARITY_ERROR) || \ - ((__CONFIG__) == TIM_BREAK_SYSTEM_LOCKUP)) +#define IS_TIM_BREAK_SYSTEM(__CONFIG__) ((__CONFIG__) == TIM_BREAK_SYSTEM_LOCKUP) #define IS_TIM_SLAVEMODE_TRIGGER_ENABLED(__TRIGGER__) (((__TRIGGER__) == TIM_SLAVEMODE_TRIGGER) || \ ((__TRIGGER__) == TIM_SLAVEMODE_COMBINED_RESETTRIGGER)) @@ -2345,7 +2338,8 @@ HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_S HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro_IT(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength); + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_MultiWriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength, uint32_t DataLength); diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_uart.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_uart.h index cfdfb79a9..dd3f1ce5e 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_uart.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_uart.h @@ -1235,7 +1235,7 @@ typedef void (*pUART_RxEventCallbackTypeDef) /** @defgroup UART_Private_Macros UART Private Macros * @{ */ -/** @brief Get UART clok division factor from clock prescaler value. +/** @brief Get UART clock division factor from clock prescaler value. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval UART clock division factor */ @@ -1250,8 +1250,7 @@ typedef void (*pUART_RxEventCallbackTypeDef) ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV16) ? 16U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV32) ? 32U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV64) ? 64U : \ - ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : \ - ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV256) ? 256U : 1U) + ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : 256U) /** @brief BRR division operation to set BRR register in 8-bit oversampling mode. diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart.h index e5a9fbd8e..9fd349c57 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart.h @@ -141,7 +141,7 @@ typedef struct __USART_HandleTypeDef uint16_t NbTxDataToProcess; /*!< Number of data to process during TX ISR execution */ - uint32_t SlaveMode; /*!< Enable/Disable UART SPI Slave Mode. This parameter can be a value + uint32_t SlaveMode; /*!< Enable/Disable USART SPI Slave Mode. This parameter can be a value of @ref USARTEx_Slave_Mode */ uint32_t FifoMode; /*!< Specifies if the FIFO mode will be used. This parameter can be a value @@ -707,8 +707,7 @@ typedef void (*pUSART_CallbackTypeDef)(USART_HandleTypeDef *husart); /*!< poin ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV16) ? 16U : \ ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV32) ? 32U : \ ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV64) ? 64U : \ - ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV128) ? 128U : \ - ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV256) ? 256U : 1U) + ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV128) ? 128U : 256U) /** @brief BRR division operation to set BRR register in 8-bit oversampling mode. * @param __PCLK__ USART clock. diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart_ex.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart_ex.h index 5a7f0dfd9..2545e422d 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart_ex.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_hal_usart_ex.h @@ -45,7 +45,7 @@ extern "C" { * @{ */ #define USART_WORDLENGTH_7B (USART_CR1_M1) /*!< 7-bit long USART frame */ -#define USART_WORDLENGTH_8B (0x00000000U) /*!< 8-bit long USART frame */ +#define USART_WORDLENGTH_8B (0x00000000U) /*!< 8-bit long USART frame */ #define USART_WORDLENGTH_9B (USART_CR1_M0) /*!< 9-bit long USART frame */ /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_adc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_adc.h index aa3d2c205..9fec4d9eb 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_adc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_adc.h @@ -6,7 +6,7 @@ ****************************************************************************** * @attention * - * Copyright (c) 2022 STMicroelectronics.g + * Copyright (c) 2022 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file @@ -53,43 +53,43 @@ extern "C" { /* Definition of ADC group regular sequencer bits information to be inserted */ /* into ADC group regular sequencer ranks literals definition. */ -#define ADC_REG_RANK_1_SQRX_BITOFFSET_POS ( 0UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ1" position in register */ -#define ADC_REG_RANK_2_SQRX_BITOFFSET_POS ( 4UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ2" position in register */ -#define ADC_REG_RANK_3_SQRX_BITOFFSET_POS ( 8UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ3" position in register */ -#define ADC_REG_RANK_4_SQRX_BITOFFSET_POS (12UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ4" position in register */ -#define ADC_REG_RANK_5_SQRX_BITOFFSET_POS (16UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ5" position in register */ -#define ADC_REG_RANK_6_SQRX_BITOFFSET_POS (20UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ6" position in register */ -#define ADC_REG_RANK_7_SQRX_BITOFFSET_POS (24UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ7" position in register */ -#define ADC_REG_RANK_8_SQRX_BITOFFSET_POS (28UL) /* Value equivalent to bitfield "ADC_CHSELR_SQ8" position in register */ - +#define ADC_REG_RANK_1_SQRX_BITOFFSET_POS ( 0UL) /* Equivalent to bitfield "ADC_CHSELR_SQ1" position in register */ +#define ADC_REG_RANK_2_SQRX_BITOFFSET_POS ( 4UL) /* Equivalent to bitfield "ADC_CHSELR_SQ2" position in register */ +#define ADC_REG_RANK_3_SQRX_BITOFFSET_POS ( 8UL) /* Equivalent to bitfield "ADC_CHSELR_SQ3" position in register */ +#define ADC_REG_RANK_4_SQRX_BITOFFSET_POS (12UL) /* Equivalent to bitfield "ADC_CHSELR_SQ4" position in register */ +#define ADC_REG_RANK_5_SQRX_BITOFFSET_POS (16UL) /* Equivalent to bitfield "ADC_CHSELR_SQ5" position in register */ +#define ADC_REG_RANK_6_SQRX_BITOFFSET_POS (20UL) /* Equivalent to bitfield "ADC_CHSELR_SQ6" position in register */ +#define ADC_REG_RANK_7_SQRX_BITOFFSET_POS (24UL) /* Equivalent to bitfield "ADC_CHSELR_SQ7" position in register */ +#define ADC_REG_RANK_8_SQRX_BITOFFSET_POS (28UL) /* Equivalent to bitfield "ADC_CHSELR_SQ8" position in register */ /* Internal mask for ADC group regular trigger: */ /* To select into literal LL_ADC_REG_TRIG_x the relevant bits for: */ /* - regular trigger source */ /* - regular trigger edge */ -#define ADC_REG_TRIG_EXT_EDGE_DEFAULT (ADC_CFGR1_EXTEN_0) /* Trigger edge set to rising edge (default setting for compatibility with some ADC on other STM32 families having this setting set by HW default value) */ +#define ADC_REG_TRIG_EXT_EDGE_DEFAULT (ADC_CFGR1_EXTEN_0) /* Trigger edge set to rising edge (default setting for + compatibility with some ADC on other STM32 series + having this setting set by HW default value) */ /* Mask containing trigger source masks for each of possible */ /* trigger edge selection duplicated with shifts [0; 4; 8; 12] */ /* corresponding to {SW start; ext trigger; ext trigger; ext trigger}. */ -#define ADC_REG_TRIG_SOURCE_MASK (((LL_ADC_REG_TRIG_SOFTWARE & ADC_CFGR1_EXTSEL) << (4U * 0UL)) | \ - ((ADC_CFGR1_EXTSEL) << (4U * 1UL)) | \ - ((ADC_CFGR1_EXTSEL) << (4U * 2UL)) | \ - ((ADC_CFGR1_EXTSEL) << (4U * 3UL)) ) +#define ADC_REG_TRIG_SOURCE_MASK (((LL_ADC_REG_TRIG_SOFTWARE & ADC_CFGR1_EXTSEL) << (4U * 0UL)) | \ + ((ADC_CFGR1_EXTSEL) << (4U * 1UL)) | \ + ((ADC_CFGR1_EXTSEL) << (4U * 2UL)) | \ + ((ADC_CFGR1_EXTSEL) << (4U * 3UL)) ) /* Mask containing trigger edge masks for each of possible */ /* trigger edge selection duplicated with shifts [0; 4; 8; 12] */ /* corresponding to {SW start; ext trigger; ext trigger; ext trigger}. */ -#define ADC_REG_TRIG_EDGE_MASK (((LL_ADC_REG_TRIG_SOFTWARE & ADC_CFGR1_EXTEN) << (4U * 0UL)) | \ - ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) << (4U * 1UL)) | \ - ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) << (4U * 2UL)) | \ - ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) << (4U * 3UL)) ) +#define ADC_REG_TRIG_EDGE_MASK (((LL_ADC_REG_TRIG_SOFTWARE & ADC_CFGR1_EXTEN) << (4U * 0UL)) | \ + ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) << (4U * 1UL)) | \ + ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) << (4U * 2UL)) | \ + ((ADC_REG_TRIG_EXT_EDGE_DEFAULT) << (4U * 3UL)) ) /* Definition of ADC group regular trigger bits information. */ -#define ADC_REG_TRIG_EXTSEL_BITOFFSET_POS ( 6UL) /* Value equivalent to bitfield "ADC_CFGR1_EXTSEL" position in register */ -#define ADC_REG_TRIG_EXTEN_BITOFFSET_POS (10UL) /* Value equivalent to bitfield "ADC_CFGR1_EXTEN" position in register */ - +#define ADC_REG_TRIG_EXTSEL_BITOFFSET_POS ( 6UL) /* Equivalent to bitfield "ADC_CFGR1_EXTSEL" position in register */ +#define ADC_REG_TRIG_EXTEN_BITOFFSET_POS (10UL) /* Equivalent to bitfield "ADC_CFGR1_EXTEN" position in register */ /* Internal mask for ADC channel: */ @@ -100,12 +100,17 @@ extern "C" { /* GPIO pins) and internal channels (connected to internal paths) */ #define ADC_CHANNEL_ID_NUMBER_MASK (ADC_CFGR1_AWD1CH) #define ADC_CHANNEL_ID_BITFIELD_MASK (ADC_CHSELR_CHSEL) -#define ADC_CHANNEL_ID_NUMBER_MASK_SEQ (ADC_CHSELR_SQ1 << ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) /* Value equivalent to ADC_CHANNEL_ID_NUMBER_MASK with reduced range: on this STM32 series, ADC group regular sequencer, if set to mode "fully configurable", can contain channels with a restricted channel number. Refer to function @ref LL_ADC_REG_SetSequencerConfigurable(). */ -#define ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS (26UL)/* Value equivalent to bitfield "ADC_CHANNEL_ID_NUMBER_MASK" position in register */ +#define ADC_CHANNEL_ID_NUMBER_MASK_SEQ (ADC_CHSELR_SQ1 << ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) /* Equivalent to + ADC_CHANNEL_ID_NUMBER_MASK with reduced range: on this STM32 series, ADC group regular sequencer, + if set to mode "fully configurable", can contain channels with a restricted channel number. + Refer to function @ref LL_ADC_REG_SetSequencerConfigurable(). */ +#define ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS (26UL) /* Equivalent to bitfield "ADC_CHANNEL_ID_NUMBER_MASK" + position in register */ #define ADC_CHANNEL_ID_MASK (ADC_CHANNEL_ID_NUMBER_MASK | ADC_CHANNEL_ID_BITFIELD_MASK | \ ADC_CHANNEL_ID_INTERNAL_CH_MASK) /* Equivalent mask of ADC_CHANNEL_NUMBER_MASK aligned on register LSB (bit 0) */ -#define ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0 (0x0000001FUL) /* Equivalent to shift: (ADC_CHANNEL_NUMBER_MASK >> [Position of bitfield "ADC_CHANNEL_NUMBER_MASK" in register]) */ +#define ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0 (0x0000001FUL) /* Equivalent to shift: (ADC_CHANNEL_NUMBER_MASK + >> [Position of bitfield "ADC_CHANNEL_NUMBER_MASK" in register]) */ /* Channel differentiation between external and internal channels */ #define ADC_CHANNEL_ID_INTERNAL_CH (0x80000000UL) /* Marker of internal channel */ @@ -180,7 +185,7 @@ extern "C" { /* Internal mask for ADC analog watchdog: */ /* To select into literals LL_ADC_AWD_CHANNELx_xxx the relevant bits for: */ /* (concatenation of multiple bits used in different analog watchdogs, */ -/* (feature of several watchdogs not available on all STM32 families)). */ +/* (feature of several watchdogs not available on all STM32 series)). */ /* - analog watchdog 1: monitored channel defined by number, */ /* selection of ADC group (ADC group regular). */ /* - analog watchdog 2 and 3: monitored channel defined by bitfield, no */ @@ -203,71 +208,90 @@ extern "C" { #define ADC_AWD_CR23_CHANNEL_MASK (ADC_AWD2CR_AWD2CH) #define ADC_AWD_CR_ALL_CHANNEL_MASK (ADC_AWD_CR1_CHANNEL_MASK | ADC_AWD_CR23_CHANNEL_MASK) -#define ADC_AWD_CRX_REGOFFSET_POS (20UL) /* Position of bits ADC_AWD_CRx_REGOFFSET in ADC_AWD_CRX_REGOFFSET_MASK */ +#define ADC_AWD_CRX_REGOFFSET_POS (20UL) /* Position of bits ADC_AWD_CRx_REGOFFSET + in ADC_AWD_CRX_REGOFFSET_MASK */ /* Internal register offset for ADC analog watchdog threshold configuration */ #define ADC_AWD_TR1_REGOFFSET (ADC_AWD_CR1_REGOFFSET) #define ADC_AWD_TR2_REGOFFSET (ADC_AWD_CR2_REGOFFSET) #define ADC_AWD_TR3_REGOFFSET (ADC_AWD_CR3_REGOFFSET + (1UL << ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS)) #define ADC_AWD_TRX_REGOFFSET_MASK (ADC_AWD_TR1_REGOFFSET | ADC_AWD_TR2_REGOFFSET | ADC_AWD_TR3_REGOFFSET) -#define ADC_AWD_TRX_REGOFFSET_POS (ADC_AWD_CRX_REGOFFSET_POS) /* Position of bits ADC_SQRx_REGOFFSET in ADC_AWD_TRX_REGOFFSET_MASK */ -#define ADC_AWD_TRX_BIT_HIGH_MASK (0x00010000UL) /* Selection of 1 bit to discriminate threshold high: mask of bit */ -#define ADC_AWD_TRX_BIT_HIGH_POS (16UL) /* Selection of 1 bit to discriminate threshold high: position of bit */ -#define ADC_AWD_TRX_BIT_HIGH_SHIFT4 (ADC_AWD_TRX_BIT_HIGH_POS - 4UL) /* Shift of bit ADC_AWD_TRX_BIT_HIGH to position to perform a shift of 4 ranks */ +#define ADC_AWD_TRX_REGOFFSET_POS (ADC_AWD_CRX_REGOFFSET_POS) /* Position of bits ADC_SQRx_REGOFFSET + in ADC_AWD_TRX_REGOFFSET_MASK */ +#define ADC_AWD_TRX_BIT_HIGH_MASK (0x00010000UL) /* Selection of 1 bit to discriminate + threshold high: mask of bit */ +#define ADC_AWD_TRX_BIT_HIGH_POS (16UL) /* Selection of 1 bit to discriminate + threshold high: position of bit */ +#define ADC_AWD_TRX_BIT_HIGH_SHIFT4 (ADC_AWD_TRX_BIT_HIGH_POS - 4UL) /* Shift of bit ADC_AWD_TRX_BIT_HIGH to + position to perform a shift of 4 ranks */ #define ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS (20UL) - /* ADC registers bits positions */ -#define ADC_CFGR1_RES_BITOFFSET_POS ( 3UL) /* Value equivalent to bitfield "ADC_CFGR1_RES" position in register */ -#define ADC_CFGR1_AWDSGL_BITOFFSET_POS (22UL) /* Value equivalent to bitfield "ADC_CFGR1_AWDSGL" position in register */ -#define ADC_TR1_HT1_BITOFFSET_POS (16UL) /* Value equivalent to bitfield "ADC_TR1_HT1" position in register */ -#define ADC_CHSELR_CHSEL0_BITOFFSET_POS ( 0UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL0" position in register */ -#define ADC_CHSELR_CHSEL1_BITOFFSET_POS ( 1UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL1" position in register */ -#define ADC_CHSELR_CHSEL2_BITOFFSET_POS ( 2UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL2" position in register */ -#define ADC_CHSELR_CHSEL3_BITOFFSET_POS ( 3UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL3" position in register */ -#define ADC_CHSELR_CHSEL4_BITOFFSET_POS ( 4UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL4" position in register */ -#define ADC_CHSELR_CHSEL5_BITOFFSET_POS ( 5UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL5" position in register */ -#define ADC_CHSELR_CHSEL6_BITOFFSET_POS ( 6UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL6" position in register */ -#define ADC_CHSELR_CHSEL7_BITOFFSET_POS ( 7UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL7" position in register */ -#define ADC_CHSELR_CHSEL8_BITOFFSET_POS ( 8UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL8" position in register */ -#define ADC_CHSELR_CHSEL9_BITOFFSET_POS ( 9UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL9" position in register */ -#define ADC_CHSELR_CHSEL10_BITOFFSET_POS (10UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL10" position in register */ -#define ADC_CHSELR_CHSEL11_BITOFFSET_POS (11UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL11" position in register */ -#define ADC_CHSELR_CHSEL12_BITOFFSET_POS (12UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL12" position in register */ -#define ADC_CHSELR_CHSEL13_BITOFFSET_POS (13UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL13" position in register */ -#define ADC_CHSELR_CHSEL14_BITOFFSET_POS (14UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL14" position in register */ -#define ADC_CHSELR_CHSEL15_BITOFFSET_POS (15UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL15" position in register */ -#define ADC_CHSELR_CHSEL16_BITOFFSET_POS (16UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL16" position in register */ -#define ADC_CHSELR_CHSEL17_BITOFFSET_POS (17UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL17" position in register */ -#define ADC_CHSELR_CHSEL18_BITOFFSET_POS (18UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL18" position in register */ -#define ADC_CHSELR_CHSEL19_BITOFFSET_POS (19UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL19" position in register */ -#define ADC_CHSELR_CHSEL20_BITOFFSET_POS (20UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL20" position in register */ -#define ADC_CHSELR_CHSEL21_BITOFFSET_POS (21UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL21" position in register */ -#define ADC_CHSELR_CHSEL22_BITOFFSET_POS (22UL) /* Value equivalent to bitfield "ADC_CHSELR_CHSEL22" position in register */ -#define ADC_SMPR_SMP1_BITOFFSET_POS ( 0UL) /* Value equivalent to bitfield "ADC_SMPR_SMP1" position in register */ -#define ADC_SMPR_SMP2_BITOFFSET_POS ( 4UL) /* Value equivalent to bitfield "ADC_SMPR_SMP2" position in register */ -#define ADC_SMPR_SMPSEL0_BITOFFSET_POS ( 8UL) /* Value equivalent to bitfield "ADC_SMPR_SMPSEL0" position in register */ +#define ADC_CFGR1_RES_BITOFFSET_POS ( 3UL) /* Equivalent to bitfield "ADC_CFGR1_RES" position in register */ +#define ADC_CFGR1_AWDSGL_BITOFFSET_POS (22UL) /* Equivalent to bitfield "ADC_CFGR1_AWDSGL" position in register */ +#define ADC_TR1_HT1_BITOFFSET_POS (16UL) /* Equivalent to bitfield "ADC_TR1_HT1" position in register */ +#define ADC_CHSELR_CHSEL0_BITOFFSET_POS ( 0UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL0" position in register */ +#define ADC_CHSELR_CHSEL1_BITOFFSET_POS ( 1UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL1" position in register */ +#define ADC_CHSELR_CHSEL2_BITOFFSET_POS ( 2UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL2" position in register */ +#define ADC_CHSELR_CHSEL3_BITOFFSET_POS ( 3UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL3" position in register */ +#define ADC_CHSELR_CHSEL4_BITOFFSET_POS ( 4UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL4" position in register */ +#define ADC_CHSELR_CHSEL5_BITOFFSET_POS ( 5UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL5" position in register */ +#define ADC_CHSELR_CHSEL6_BITOFFSET_POS ( 6UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL6" position in register */ +#define ADC_CHSELR_CHSEL7_BITOFFSET_POS ( 7UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL7" position in register */ +#define ADC_CHSELR_CHSEL8_BITOFFSET_POS ( 8UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL8" position in register */ +#define ADC_CHSELR_CHSEL9_BITOFFSET_POS ( 9UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL9" position in register */ +#define ADC_CHSELR_CHSEL10_BITOFFSET_POS (10UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL10" position in register */ +#define ADC_CHSELR_CHSEL11_BITOFFSET_POS (11UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL11" position in register */ +#define ADC_CHSELR_CHSEL12_BITOFFSET_POS (12UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL12" position in register */ +#define ADC_CHSELR_CHSEL13_BITOFFSET_POS (13UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL13" position in register */ +#define ADC_CHSELR_CHSEL14_BITOFFSET_POS (14UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL14" position in register */ +#define ADC_CHSELR_CHSEL15_BITOFFSET_POS (15UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL15" position in register */ +#define ADC_CHSELR_CHSEL16_BITOFFSET_POS (16UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL16" position in register */ +#define ADC_CHSELR_CHSEL17_BITOFFSET_POS (17UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL17" position in register */ +#define ADC_CHSELR_CHSEL18_BITOFFSET_POS (18UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL18" position in register */ +#define ADC_CHSELR_CHSEL19_BITOFFSET_POS (19UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL19" position in register */ +#define ADC_CHSELR_CHSEL20_BITOFFSET_POS (20UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL20" position in register */ +#define ADC_CHSELR_CHSEL21_BITOFFSET_POS (21UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL21" position in register */ +#define ADC_CHSELR_CHSEL22_BITOFFSET_POS (22UL) /* Equivalent to bitfield "ADC_CHSELR_CHSEL22" position in register */ +#define ADC_SMPR_SMP1_BITOFFSET_POS ( 0UL) /* Equivalent to bitfield "ADC_SMPR_SMP1" position in register */ +#define ADC_SMPR_SMP2_BITOFFSET_POS ( 4UL) /* Equivalent to bitfield "ADC_SMPR_SMP2" position in register */ +#define ADC_SMPR_SMPSEL0_BITOFFSET_POS ( 8UL) /* Equivalent to bitfield "ADC_SMPR_SMPSEL0" position in register */ /* ADC registers bits groups */ -#define ADC_CR_BITS_PROPERTY_RS (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN) /* ADC register CR bits with HW property "rs": Software can read as well as set this bit. Writing '0' has no effect on the bit value. */ +#define ADC_CR_BITS_PROPERTY_RS (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART \ + | ADC_CR_ADDIS | ADC_CR_ADEN) /* ADC register CR bits with HW property + "rs": Software can read as well as set this bit. Writing '0' has no effect + on the bit value. */ /* ADC internal channels related definitions */ /* Internal voltage reference VrefInt */ -#define VREFINT_CAL_ADDR ((uint16_t*) (0x1FFF756AUL)) /* Internal voltage reference, address of parameter VREFINT_CAL: VrefInt ADC raw data acquired at temperature 30 DegC (tolerance: +-5 DegC), Vref+ = 3.0 V (tolerance: +-10 mV). */ -#define VREFINT_CAL_VREF ( 3000UL) /* Analog voltage reference (Vref+) voltage with which VrefInt has been calibrated in production (tolerance: +-10 mV) (unit: mV). */ +#define VREFINT_CAL_ADDR ((uint16_t*) (0x1FFF756AUL)) /* Internal voltage reference, address of + parameter VREFINT_CAL: VrefInt ADC raw data acquired at temperature 30 DegC + (tolerance: +-5 DegC), Vref+ = 3.0 V (tolerance: +-10 mV). */ +#define VREFINT_CAL_VREF ( 3000UL) /* Analog voltage reference (Vref+) + voltage with which VrefInt has been calibrated in production + (tolerance: +-10 mV) (unit: mV). */ /* Temperature sensor */ /* Note: On all devices of series STM32C0, calibration parameter TS_CAL2 is not available. Therefore, macro "__LL_ADC_CALC_TEMPERATURE()" is not available, - macro "__LL_ADC_CALC_TEMPERATURE_TYP_PARAMS()" must be used and parameter TS_CAL1 can improve accuracy: replace - datasheet parameter of temperature offset (macro argument __TEMPSENSOR_TYP_CALX_V__) by TEMPSENSOR_CAL1_ADDR + macro "__LL_ADC_CALC_TEMPERATURE_TYP_PARAMS()" must be used and parameter TS_CAL1 can improve accuracy: + replace datasheet parameter of temperature offset (macro argument __TEMPSENSOR_TYP_CALX_V__) + by TEMPSENSOR_CAL1_ADDR (with taking into account conversion from digital value resolution 12 bit, analog voltage reference ratio between calibration and application environments) */ -#define TEMPSENSOR_CAL1_ADDR ((uint16_t*) (0x1FFF7568UL)) /* Internal temperature sensor, address of parameter TS_CAL1: On STM32C0, temperature sensor ADC raw data acquired at temperature 30 DegC (tolerance: +-5 DegC), Vref+ = 3.0 V (tolerance: +-10 mV). */ -#define TEMPSENSOR_CAL1_TEMP (( int32_t) 30) /* Internal temperature sensor, temperature at which temperature sensor has been calibrated in production for data into TEMPSENSOR_CAL1_ADDR (tolerance: +-5 DegC) (unit: DegC). */ -#define TEMPSENSOR_CAL_VREFANALOG ( 3000UL) /* Analog voltage reference (Vref+) voltage with which temperature sensor has been calibrated in production (tolerance: +-10 mV) (unit: mV). */ +#define TEMPSENSOR_CAL1_ADDR ((uint16_t*) (0x1FFF7568UL)) /* Internal temperature sensor, address of + parameter TS_CAL1: On STM32C0, temperature sensor ADC raw data acquired at + temperature 30 DegC (tolerance: +-5 DegC), Vref+ = 3.0 V + (tolerance: +-10 mV). */ +#define TEMPSENSOR_CAL1_TEMP (( int32_t) 30) /* Internal temperature sensor, temperature at + which temperature sensor has been calibrated in production for data into + TEMPSENSOR_CAL1_ADDR (tolerance: +-5 DegC) (unit: DegC). */ +#define TEMPSENSOR_CAL_VREFANALOG ( 3000UL) /* Analog voltage reference (Vref+) voltage + with which temperature sensor has been calibrated in production + (tolerance: +-10 mV) (unit: mV). */ /** * @} @@ -315,8 +339,8 @@ typedef struct { uint32_t CommonClock; /*!< Set parameter common to several ADC: Clock source and prescaler. This parameter can be a value of @ref ADC_LL_EC_COMMON_CLOCK_SOURCE - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetCommonClock(). */ + This feature can be modified afterwards using unitary function + @ref LL_ADC_SetCommonClock(). */ } LL_ADC_CommonInitTypeDef; @@ -329,7 +353,7 @@ typedef struct * is conditioned to ADC state: * ADC instance must be disabled. * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different + * and compatibility over all STM32 series. However, the different * features can be set under different ADC state conditions * (setting possible with ADC enabled without conversion on going, * ADC enabled with conversion on going, ...) @@ -342,27 +366,29 @@ typedef struct { uint32_t Clock; /*!< Set ADC instance clock source and prescaler. This parameter can be a value of @ref ADC_LL_EC_CLOCK_SOURCE - @note On this STM32 series, this parameter has some clock ratio constraints: - ADC clock synchronous (from PCLK) with prescaler 1 must be enabled only if PCLK has a 50% duty clock cycle - (APB prescaler configured inside the RCC must be bypassed and the system clock must by 50% duty cycle). - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetClock(). + @note On this STM32 series, this parameter has some clock ratio constraints: + ADC clock synchronous (from PCLK) with prescaler 1 must be enabled + only if PCLK has a 50% duty clock cycle (APB prescaler configured + inside the RCC must be bypassed and the system clock must by 50% duty + cycle). + This feature can be modified afterwards using unitary function + @ref LL_ADC_SetClock(). For more details, refer to description of this function. */ uint32_t Resolution; /*!< Set ADC resolution. This parameter can be a value of @ref ADC_LL_EC_RESOLUTION - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetResolution(). */ + This feature can be modified afterwards using unitary function + @ref LL_ADC_SetResolution(). */ uint32_t DataAlignment; /*!< Set ADC conversion data alignment. This parameter can be a value of @ref ADC_LL_EC_DATA_ALIGN - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetDataAlignment(). */ + This feature can be modified afterwards using unitary function + @ref LL_ADC_SetDataAlignment(). */ uint32_t LowPowerMode; /*!< Set ADC low power mode. This parameter can be a value of @ref ADC_LL_EC_LP_MODE - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetLowPowerMode(). */ + This feature can be modified afterwards using unitary function + @ref LL_ADC_SetLowPowerMode(). */ } LL_ADC_InitTypeDef; @@ -376,7 +402,7 @@ typedef struct * is conditioned to ADC state: * ADC instance must be disabled. * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different + * and compatibility over all STM32 series. However, the different * features can be set under different ADC state conditions * (setting possible with ADC enabled without conversion on going, * ADC enabled with conversion on going, ...) @@ -387,43 +413,57 @@ typedef struct */ typedef struct { - uint32_t TriggerSource; /*!< Set ADC group regular conversion trigger source: internal (SW start) or from external peripheral (timer event, external interrupt line). + uint32_t TriggerSource; /*!< Set ADC group regular conversion trigger source: internal (SW start) or + from external peripheral (timer event, external interrupt line). This parameter can be a value of @ref ADC_LL_EC_REG_TRIGGER_SOURCE - @note On this STM32 series, setting trigger source to external trigger also set trigger polarity to rising edge - (default setting for compatibility with some ADC on other STM32 families having this setting set by HW default value). - In case of need to modify trigger edge, use function @ref LL_ADC_REG_SetTriggerEdge(). - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetTriggerSource(). */ + @note On this STM32 series, setting trigger source to external trigger also + set trigger polarity to rising edge(default setting for compatibility + with some ADC on other STM32 series having this setting set by HW + default value). + In case of need to modify trigger edge, use function + @ref LL_ADC_REG_SetTriggerEdge(). + This feature can be modified afterwards using unitary function + @ref LL_ADC_REG_SetTriggerSource(). */ uint32_t SequencerLength; /*!< Set ADC group regular sequencer length. - @note This parameter has an effect only if group regular sequencer is set to mode "fully configurable". Refer to function @ref LL_ADC_REG_SetSequencerConfigurable(). + @note This parameter has an effect only if group regular sequencer is set + to mode "fully configurable". Refer to function + @ref LL_ADC_REG_SetSequencerConfigurable(). This parameter can be a value of @ref ADC_LL_EC_REG_SEQ_SCAN_LENGTH + This feature can be modified afterwards using unitary function + @ref LL_ADC_REG_SetSequencerLength(). */ - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetSequencerLength(). */ - - uint32_t SequencerDiscont; /*!< Set ADC group regular sequencer discontinuous mode: sequence subdivided and scan conversions interrupted every selected number of ranks. + uint32_t SequencerDiscont; /*!< Set ADC group regular sequencer discontinuous mode: sequence subdivided + and scan conversions interrupted every selected number of ranks. This parameter can be a value of @ref ADC_LL_EC_REG_SEQ_DISCONT_MODE - @note This parameter has an effect only if group regular sequencer is enabled - (depending on the sequencer mode: scan length of 2 ranks or more, or several ADC channels enabled in group regular sequencer. Refer to function @ref LL_ADC_REG_SetSequencerConfigurable() ). - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetSequencerDiscont(). */ - - uint32_t ContinuousMode; /*!< Set ADC continuous conversion mode on ADC group regular, whether ADC conversions are performed in single mode (one conversion per trigger) or in continuous mode (after the first trigger, following conversions launched successively automatically). + @note This parameter has an effect only if group regular sequencer is + enabled (depending on the sequencer mode: scan length of 2 ranks or + more, or several ADC channels enabled in group regular sequencer. + Refer to function @ref LL_ADC_REG_SetSequencerConfigurable() ). + This feature can be modified afterwards using unitary function + @ref LL_ADC_REG_SetSequencerDiscont(). */ + + uint32_t ContinuousMode; /*!< Set ADC continuous conversion mode on ADC group regular, whether ADC + conversions are performed in single mode (one conversion per trigger) or in + continuous mode (after the first trigger, following conversions launched + successively automatically). This parameter can be a value of @ref ADC_LL_EC_REG_CONTINUOUS_MODE - Note: It is not possible to enable both ADC group regular continuous mode and discontinuous mode. + Note: It is not possible to enable both ADC group regular continuous mode + and discontinuous mode. + This feature can be modified afterwards using unitary function + @ref LL_ADC_REG_SetContinuousMode(). */ - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetContinuousMode(). */ - - uint32_t DMATransfer; /*!< Set ADC group regular conversion data transfer: no transfer or transfer by DMA, and DMA requests mode. + uint32_t DMATransfer; /*!< Set ADC group regular conversion data transfer: no transfer or transfer + by DMA, and DMA requests mode. This parameter can be a value of @ref ADC_LL_EC_REG_DMA_TRANSFER - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetDMATransfer(). */ + This feature can be modified afterwards using unitary function + @ref LL_ADC_REG_SetDMATransfer(). */ uint32_t Overrun; /*!< Set ADC group regular behavior in case of overrun: data preserved or overwritten. This parameter can be a value of @ref ADC_LL_EC_REG_OVR_DATA_BEHAVIOR - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetOverrun(). */ + This feature can be modified afterwards using unitary function + @ref LL_ADC_REG_SetOverrun(). */ } LL_ADC_REG_InitTypeDef; @@ -443,8 +483,10 @@ typedef struct */ #define LL_ADC_FLAG_ADRDY ADC_ISR_ADRDY /*!< ADC flag ADC instance ready */ #define LL_ADC_FLAG_CCRDY ADC_ISR_CCRDY /*!< ADC flag ADC channel configuration ready */ -#define LL_ADC_FLAG_EOC ADC_ISR_EOC /*!< ADC flag ADC group regular end of unitary conversion */ -#define LL_ADC_FLAG_EOS ADC_ISR_EOS /*!< ADC flag ADC group regular end of sequence conversions */ +#define LL_ADC_FLAG_EOC ADC_ISR_EOC /*!< ADC flag ADC group regular end of unitary + conversion */ +#define LL_ADC_FLAG_EOS ADC_ISR_EOS /*!< ADC flag ADC group regular end of sequence + conversions */ #define LL_ADC_FLAG_OVR ADC_ISR_OVR /*!< ADC flag ADC group regular overrun */ #define LL_ADC_FLAG_EOSMP ADC_ISR_EOSMP /*!< ADC flag ADC group regular end of sampling phase */ #define LL_ADC_FLAG_AWD1 ADC_ISR_AWD1 /*!< ADC flag ADC analog watchdog 1 */ @@ -461,10 +503,13 @@ typedef struct */ #define LL_ADC_IT_ADRDY ADC_IER_ADRDYIE /*!< ADC interruption ADC instance ready */ #define LL_ADC_IT_CCRDY ADC_IER_CCRDYIE /*!< ADC interruption channel configuration ready */ -#define LL_ADC_IT_EOC ADC_IER_EOCIE /*!< ADC interruption ADC group regular end of unitary conversion */ -#define LL_ADC_IT_EOS ADC_IER_EOSIE /*!< ADC interruption ADC group regular end of sequence conversions */ +#define LL_ADC_IT_EOC ADC_IER_EOCIE /*!< ADC interruption ADC group regular end of unitary + conversion */ +#define LL_ADC_IT_EOS ADC_IER_EOSIE /*!< ADC interruption ADC group regular end of sequence + conversions */ #define LL_ADC_IT_OVR ADC_IER_OVRIE /*!< ADC interruption ADC group regular overrun */ -#define LL_ADC_IT_EOSMP ADC_IER_EOSMPIE /*!< ADC interruption ADC group regular end of sampling phase */ +#define LL_ADC_IT_EOSMP ADC_IER_EOSMPIE /*!< ADC interruption ADC group regular end of sampling + phase */ #define LL_ADC_IT_AWD1 ADC_IER_AWD1IE /*!< ADC interruption ADC analog watchdog 1 */ #define LL_ADC_IT_AWD2 ADC_IER_AWD2IE /*!< ADC interruption ADC analog watchdog 2 */ #define LL_ADC_IT_AWD3 ADC_IER_AWD3IE /*!< ADC interruption ADC analog watchdog 3 */ @@ -479,7 +524,11 @@ typedef struct /* List of ADC registers intended to be used (most commonly) with */ /* DMA transfer. */ /* Refer to function @ref LL_ADC_DMA_GetRegAddr(). */ -#define LL_ADC_DMA_REG_REGULAR_DATA (0x00000000UL) /* ADC group regular conversion data register (corresponding to register DR) to be used with ADC configured in independent mode. Without DMA transfer, register accessed by LL function @ref LL_ADC_REG_ReadConversionData32() and other functions @ref LL_ADC_REG_ReadConversionDatax() */ +#define LL_ADC_DMA_REG_REGULAR_DATA (0x00000000UL) /* ADC group regular conversion data register + (corresponding to register DR) to be used with ADC configured in independent + mode. Without DMA transfer, register accessed by LL function + @ref LL_ADC_REG_ReadConversionData32() and other + functions @ref LL_ADC_REG_ReadConversionDatax() */ /** * @} */ @@ -487,27 +536,54 @@ typedef struct /** @defgroup ADC_LL_EC_COMMON_CLOCK_SOURCE ADC common - Clock source * @{ */ -#define LL_ADC_CLOCK_ASYNC_DIV1 (0x00000000UL) /*!< ADC asynchronous clock without prescaler */ -#define LL_ADC_CLOCK_ASYNC_DIV2 (ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with prescaler division by 2. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV4 (ADC_CCR_PRESC_1 ) /*!< ADC asynchronous clock with prescaler division by 4. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV6 (ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with prescaler division by 6. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV8 (ADC_CCR_PRESC_2 ) /*!< ADC asynchronous clock with prescaler division by 8. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV10 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with prescaler division by 10. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV12 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1 ) /*!< ADC asynchronous clock with prescaler division by 12. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV16 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with prescaler division by 16. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV32 (ADC_CCR_PRESC_3) /*!< ADC asynchronous clock with prescaler division by 32. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV64 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with prescaler division by 64. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV128 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1) /*!< ADC asynchronous clock with prescaler division by 128. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -#define LL_ADC_CLOCK_ASYNC_DIV256 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with prescaler division by 256. ADC common clock asynchronous prescaler is applied to each ADC instance if the corresponding ADC instance clock is set to clock source asynchronous (refer to function @ref LL_ADC_SetClock() ). */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_COMMON_CLOCK_FREQ_MODE ADC common - Clock frequency mode - * @{ - */ -#define LL_ADC_CLOCK_FREQ_MODE_HIGH (0x00000000UL) /*!< ADC clock mode to high frequency. On STM32C0, ADC clock frequency above 3.5MHz. */ -#define LL_ADC_CLOCK_FREQ_MODE_LOW (ADC_CCR_LFMEN) /*!< ADC clock mode to low frequency. On STM32C0, ADC clock frequency below 3.5MHz. */ +#define LL_ADC_CLOCK_ASYNC_DIV1 (0x00000000UL) /*!< ADC asynchronous clock without + prescaler */ +#define LL_ADC_CLOCK_ASYNC_DIV2 (ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with + prescaler division by 2. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV4 (ADC_CCR_PRESC_1) /*!< ADC asynchronous clock with + prescaler division by 4. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV6 (ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with + prescaler division by 6. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV8 (ADC_CCR_PRESC_2) /*!< ADC asynchronous clock with + prescaler division by 8. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV10 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with + prescaler division by 10. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV12 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1) /*!< ADC asynchronous clock with + prescaler division by 12. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV16 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1 \ + | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with + prescaler division by 16. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV32 (ADC_CCR_PRESC_3) /*!< ADC asynchronous clock with + prescaler division by 32. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV64 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with + prescaler division by 64. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV128 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1) /*!< ADC asynchronous clock with + prescaler division by 128. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ +#define LL_ADC_CLOCK_ASYNC_DIV256 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1 \ + | ADC_CCR_PRESC_0) /*!< ADC asynchronous clock with + prescaler division by 256. Setting common to ADC instances of ADC common + group, applied ADC instance wise to each instance clock set to clock source + asynchronous (refer to function @ref LL_ADC_SetClock() ). */ /** * @} */ @@ -520,9 +596,10 @@ typedef struct /* If they are not listed below, they do not require any specific */ /* path enable. In this case, Access to measurement path is done */ /* only by selecting the corresponding ADC internal channel. */ -#define LL_ADC_PATH_INTERNAL_NONE (0x00000000UL) /*!< ADC measurement paths all disabled */ -#define LL_ADC_PATH_INTERNAL_VREFINT (ADC_CCR_VREFEN) /*!< ADC measurement path to internal channel VrefInt */ -#define LL_ADC_PATH_INTERNAL_TEMPSENSOR (ADC_CCR_TSEN) /*!< ADC measurement path to internal channel temperature sensor */ +#define LL_ADC_PATH_INTERNAL_NONE (0x00000000UL) /*!< ADC measurement paths all disabled */ +#define LL_ADC_PATH_INTERNAL_VREFINT (ADC_CCR_VREFEN) /*!< ADC measurement path to internal channel VrefInt */ +#define LL_ADC_PATH_INTERNAL_TEMPSENSOR (ADC_CCR_TSEN) /*!< ADC measurement path to internal channel + temperature sensor */ /** * @} */ @@ -530,10 +607,15 @@ typedef struct /** @defgroup ADC_LL_EC_CLOCK_SOURCE ADC instance - Clock source * @{ */ -#define LL_ADC_CLOCK_SYNC_PCLK_DIV4 (ADC_CFGR2_CKMODE_1) /*!< ADC synchronous clock derived from AHB clock divided by 4 */ -#define LL_ADC_CLOCK_SYNC_PCLK_DIV2 (ADC_CFGR2_CKMODE_0) /*!< ADC synchronous clock derived from AHB clock divided by 2 */ -#define LL_ADC_CLOCK_SYNC_PCLK_DIV1 (ADC_CFGR2_CKMODE_1 | ADC_CFGR2_CKMODE_0) /*!< ADC synchronous clock derived from AHB clock not divided */ -#define LL_ADC_CLOCK_ASYNC (0x00000000UL) /*!< ADC asynchronous clock. Asynchronous clock prescaler can be configured using function @ref LL_ADC_SetCommonClock(). */ +#define LL_ADC_CLOCK_SYNC_PCLK_DIV4 (ADC_CFGR2_CKMODE_1) /*!< ADC synchronous clock derived from AHB clock + divided by 4 */ +#define LL_ADC_CLOCK_SYNC_PCLK_DIV2 (ADC_CFGR2_CKMODE_0) /*!< ADC synchronous clock derived from AHB clock + divided by 2 */ +#define LL_ADC_CLOCK_SYNC_PCLK_DIV1 (ADC_CFGR2_CKMODE_1 \ + | ADC_CFGR2_CKMODE_0) /*!< ADC synchronous clock derived from AHB clock + not divided */ +#define LL_ADC_CLOCK_ASYNC (0x00000000UL) /*!< ADC asynchronous clock. Asynchronous clock + prescaler can be configured using function @ref LL_ADC_SetCommonClock(). */ /** * @} */ @@ -552,8 +634,10 @@ typedef struct /** @defgroup ADC_LL_EC_DATA_ALIGN ADC instance - Data alignment * @{ */ -#define LL_ADC_DATA_ALIGN_RIGHT (0x00000000UL) /*!< ADC conversion data alignment: right aligned (alignment on data register LSB bit 0)*/ -#define LL_ADC_DATA_ALIGN_LEFT (ADC_CFGR1_ALIGN) /*!< ADC conversion data alignment: left aligned (alignment on data register MSB bit 15)*/ +#define LL_ADC_DATA_ALIGN_RIGHT (0x00000000UL) /*!< ADC conversion data alignment: right aligned + (alignment on data register LSB bit 0)*/ +#define LL_ADC_DATA_ALIGN_LEFT (ADC_CFGR1_ALIGN) /*!< ADC conversion data alignment: left aligned + (alignment on data register MSB bit 15)*/ /** * @} */ @@ -561,10 +645,18 @@ typedef struct /** @defgroup ADC_LL_EC_LP_MODE ADC instance - Low power mode * @{ */ -#define LL_ADC_LP_MODE_NONE (0x00000000UL) /*!< No ADC low power mode activated */ -#define LL_ADC_LP_AUTOWAIT (ADC_CFGR1_WAIT) /*!< ADC low power mode auto delay: Dynamic low power mode, ADC conversions are performed only when necessary (when previous ADC conversion data is read). See description with function @ref LL_ADC_SetLowPowerMode(). */ -#define LL_ADC_LP_AUTOPOWEROFF (ADC_CFGR1_AUTOFF) /*!< ADC low power mode auto power-off: the ADC automatically powers-off after a ADC conversion and automatically wakes up when a new ADC conversion is triggered (with startup time between trigger and start of sampling). See description with function @ref LL_ADC_SetLowPowerMode(). */ -#define LL_ADC_LP_AUTOWAIT_AUTOPOWEROFF (ADC_CFGR1_WAIT | ADC_CFGR1_AUTOFF) /*!< ADC low power modes auto wait and auto power-off combined. See description with function @ref LL_ADC_SetLowPowerMode(). */ +#define LL_ADC_LP_MODE_NONE (0x00000000UL) /*!< No ADC low power mode activated */ +#define LL_ADC_LP_AUTOWAIT (ADC_CFGR1_WAIT) /*!< ADC low power mode auto delay: Dynamic low power + mode, ADC conversions are performed only when necessary + (when previous ADC conversion data is read). + See description with function @ref LL_ADC_SetLowPowerMode(). */ +#define LL_ADC_LP_AUTOPOWEROFF (ADC_CFGR1_AUTOFF) /*!< ADC low power mode auto power-off: the ADC + automatically powers-off after a ADC conversion and automatically wakes up + when a new ADC conversion is triggered (with startup time between trigger + and start of sampling). See description with function + @ref LL_ADC_SetLowPowerMode(). */ +#define LL_ADC_LP_AUTOWAIT_AUTOPOWEROFF (ADC_CFGR1_WAIT | ADC_CFGR1_AUTOFF) /*!< ADC low power modes auto wait +and auto power-off combined. See description with function @ref LL_ADC_SetLowPowerMode(). */ /** * @} */ @@ -572,8 +664,27 @@ typedef struct /** @defgroup ADC_LL_EC_REG_TRIGGER_FREQ ADC group regular - Trigger frequency mode * @{ */ -#define LL_ADC_TRIGGER_FREQ_HIGH (0x00000000UL) /*!< ADC trigger frequency mode set to high frequency. Note: ADC trigger frequency mode must be set to low frequency when a duration is exceeded before ADC conversion start trigger event (between ADC enable and ADC conversion start trigger event or between two ADC conversion start trigger event). Duration value: Refer to device datasheet, parameter "tIdle". */ -#define LL_ADC_TRIGGER_FREQ_LOW (ADC_CFGR2_LFTRIG) /*!< ADC trigger frequency mode set to low frequency. Note: ADC trigger frequency mode must be set to low frequency when a duration is exceeded before ADC conversion start trigger event (between ADC enable and ADC conversion start trigger event or between two ADC conversion start trigger event). Duration value: Refer to device datasheet, parameter "tIdle". */ +#define LL_ADC_TRIGGER_FREQ_HIGH (0x00000000UL) /*!< ADC trigger frequency mode set to high frequency. + Note: ADC trigger frequency mode must be set to low frequency when a duration + is exceeded before ADC conversion start trigger event (between ADC enable + and ADC conversion start trigger event or between two ADC conversion start + trigger event). + Duration value: Refer to device datasheet, parameter "tIdle". */ +#define LL_ADC_TRIGGER_FREQ_LOW (ADC_CFGR2_LFTRIG) /*!< ADC trigger frequency mode set to low frequency. + Note: ADC trigger frequency mode must be set to low frequency when a duration + is exceeded before ADC conversion start trigger event (between ADC enable + and ADC conversion start trigger event or between two ADC conversion start + trigger event). + Duration value: Refer to device datasheet, parameter "tIdle". */ +/** + * @} + */ + +/** @defgroup ADC_LL_EC_COMMON_CLOCK_FREQ_MODE ADC common - Clock frequency mode + * @{ + */ +#define LL_ADC_CLOCK_FREQ_MODE_HIGH LL_ADC_TRIGGER_FREQ_HIGH /*!< LL ADC define maintained for legacy purpose */ +#define LL_ADC_CLOCK_FREQ_MODE_LOW LL_ADC_TRIGGER_FREQ_LOW /*!< LL ADC define maintained for legacy purpose */ /** * @} */ @@ -581,8 +692,11 @@ typedef struct /** @defgroup ADC_LL_EC_SAMPLINGTIME_COMMON ADC instance - Sampling time common to a group of channels * @{ */ -#define LL_ADC_SAMPLINGTIME_COMMON_1 (ADC_SMPR_SMP1_BITOFFSET_POS) /*!< Set sampling time common to a group of channels: sampling time nb 1 */ -#define LL_ADC_SAMPLINGTIME_COMMON_2 (ADC_SMPR_SMP2_BITOFFSET_POS | ADC_SAMPLING_TIME_CH_MASK) /*!< Set sampling time common to a group of channels: sampling time nb 2 */ +#define LL_ADC_SAMPLINGTIME_COMMON_1 (ADC_SMPR_SMP1_BITOFFSET_POS) /*!< Set sampling time common to a group + of channels: sampling time nb 1 */ +#define LL_ADC_SAMPLINGTIME_COMMON_2 (ADC_SMPR_SMP2_BITOFFSET_POS \ + | ADC_SAMPLING_TIME_CH_MASK) /*!< Set sampling time common to a group + of channels: sampling time nb 2 */ /** * @} */ @@ -598,33 +712,60 @@ typedef struct /** @defgroup ADC_LL_EC_CHANNEL ADC instance - Channel number * @{ */ -#define LL_ADC_CHANNEL_0 (ADC_CHANNEL_0_NUMBER | ADC_CHANNEL_0_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN0 */ -#define LL_ADC_CHANNEL_1 (ADC_CHANNEL_1_NUMBER | ADC_CHANNEL_1_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN1 */ -#define LL_ADC_CHANNEL_2 (ADC_CHANNEL_2_NUMBER | ADC_CHANNEL_2_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN2 */ -#define LL_ADC_CHANNEL_3 (ADC_CHANNEL_3_NUMBER | ADC_CHANNEL_3_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN3 */ -#define LL_ADC_CHANNEL_4 (ADC_CHANNEL_4_NUMBER | ADC_CHANNEL_4_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN4 */ -#define LL_ADC_CHANNEL_5 (ADC_CHANNEL_5_NUMBER | ADC_CHANNEL_5_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN5 */ -#define LL_ADC_CHANNEL_6 (ADC_CHANNEL_6_NUMBER | ADC_CHANNEL_6_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN6 */ -#define LL_ADC_CHANNEL_7 (ADC_CHANNEL_7_NUMBER | ADC_CHANNEL_7_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN7 */ -#define LL_ADC_CHANNEL_8 (ADC_CHANNEL_8_NUMBER | ADC_CHANNEL_8_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN8 */ -#define LL_ADC_CHANNEL_9 (ADC_CHANNEL_9_NUMBER | ADC_CHANNEL_9_BITFIELD ) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN9 */ -#define LL_ADC_CHANNEL_10 (ADC_CHANNEL_10_NUMBER | ADC_CHANNEL_10_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN10 */ -#define LL_ADC_CHANNEL_11 (ADC_CHANNEL_11_NUMBER | ADC_CHANNEL_11_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN11 */ -#define LL_ADC_CHANNEL_12 (ADC_CHANNEL_12_NUMBER | ADC_CHANNEL_12_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN12 */ -#define LL_ADC_CHANNEL_13 (ADC_CHANNEL_13_NUMBER | ADC_CHANNEL_13_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN13 */ -#define LL_ADC_CHANNEL_14 (ADC_CHANNEL_14_NUMBER | ADC_CHANNEL_14_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN14 */ -#define LL_ADC_CHANNEL_15 (ADC_CHANNEL_15_NUMBER | ADC_CHANNEL_15_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN15 */ -#define LL_ADC_CHANNEL_16 (ADC_CHANNEL_16_NUMBER | ADC_CHANNEL_16_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN16 */ -#define LL_ADC_CHANNEL_17 (ADC_CHANNEL_17_NUMBER | ADC_CHANNEL_17_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN17 */ -#define LL_ADC_CHANNEL_18 (ADC_CHANNEL_18_NUMBER | ADC_CHANNEL_18_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN18 */ -#define LL_ADC_CHANNEL_19 (ADC_CHANNEL_19_NUMBER | ADC_CHANNEL_19_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN19 */ -#define LL_ADC_CHANNEL_20 (ADC_CHANNEL_20_NUMBER | ADC_CHANNEL_20_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN20 */ -#define LL_ADC_CHANNEL_21 (ADC_CHANNEL_21_NUMBER | ADC_CHANNEL_21_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN21 */ -#define LL_ADC_CHANNEL_22 (ADC_CHANNEL_22_NUMBER | ADC_CHANNEL_22_BITFIELD) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN22 */ -#define LL_ADC_CHANNEL_VREFINT (LL_ADC_CHANNEL_10 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to VrefInt: Internal voltage reference. */ -#define LL_ADC_CHANNEL_TEMPSENSOR (LL_ADC_CHANNEL_9 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to Temperature sensor. */ -#define LL_ADC_CHANNEL_VDDA (LL_ADC_CHANNEL_15 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to VDDA. */ -#define LL_ADC_CHANNEL_VSSA (LL_ADC_CHANNEL_16 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to VSSA. */ +#define LL_ADC_CHANNEL_0 (ADC_CHANNEL_0_NUMBER \ + | ADC_CHANNEL_0_BITFIELD ) /*!< ADC channel ADCx_IN0 */ +#define LL_ADC_CHANNEL_1 (ADC_CHANNEL_1_NUMBER \ + | ADC_CHANNEL_1_BITFIELD ) /*!< ADC channel ADCx_IN1 */ +#define LL_ADC_CHANNEL_2 (ADC_CHANNEL_2_NUMBER \ + | ADC_CHANNEL_2_BITFIELD ) /*!< ADC channel ADCx_IN2 */ +#define LL_ADC_CHANNEL_3 (ADC_CHANNEL_3_NUMBER \ + | ADC_CHANNEL_3_BITFIELD ) /*!< ADC channel ADCx_IN3 */ +#define LL_ADC_CHANNEL_4 (ADC_CHANNEL_4_NUMBER \ + | ADC_CHANNEL_4_BITFIELD ) /*!< ADC channel ADCx_IN4 */ +#define LL_ADC_CHANNEL_5 (ADC_CHANNEL_5_NUMBER \ + | ADC_CHANNEL_5_BITFIELD ) /*!< ADC channel ADCx_IN5 */ +#define LL_ADC_CHANNEL_6 (ADC_CHANNEL_6_NUMBER \ + | ADC_CHANNEL_6_BITFIELD ) /*!< ADC channel ADCx_IN6 */ +#define LL_ADC_CHANNEL_7 (ADC_CHANNEL_7_NUMBER \ + | ADC_CHANNEL_7_BITFIELD ) /*!< ADC channel ADCx_IN7 */ +#define LL_ADC_CHANNEL_8 (ADC_CHANNEL_8_NUMBER \ + | ADC_CHANNEL_8_BITFIELD ) /*!< ADC channel ADCx_IN8 */ +#define LL_ADC_CHANNEL_9 (ADC_CHANNEL_9_NUMBER \ + | ADC_CHANNEL_9_BITFIELD ) /*!< ADC channel ADCx_IN9 */ +#define LL_ADC_CHANNEL_10 (ADC_CHANNEL_10_NUMBER \ + | ADC_CHANNEL_10_BITFIELD) /*!< ADC channel ADCx_IN10 */ +#define LL_ADC_CHANNEL_11 (ADC_CHANNEL_11_NUMBER \ + | ADC_CHANNEL_11_BITFIELD) /*!< ADC channel ADCx_IN11 */ +#define LL_ADC_CHANNEL_12 (ADC_CHANNEL_12_NUMBER \ + | ADC_CHANNEL_12_BITFIELD) /*!< ADC channel ADCx_IN12 */ +#define LL_ADC_CHANNEL_13 (ADC_CHANNEL_13_NUMBER \ + | ADC_CHANNEL_13_BITFIELD) /*!< ADC channel ADCx_IN13 */ +#define LL_ADC_CHANNEL_14 (ADC_CHANNEL_14_NUMBER \ + | ADC_CHANNEL_14_BITFIELD) /*!< ADC channel ADCx_IN14 */ +#define LL_ADC_CHANNEL_15 (ADC_CHANNEL_15_NUMBER \ + | ADC_CHANNEL_15_BITFIELD) /*!< ADC channel ADCx_IN15 */ +#define LL_ADC_CHANNEL_16 (ADC_CHANNEL_16_NUMBER \ + | ADC_CHANNEL_16_BITFIELD) /*!< ADC channel ADCx_IN16 */ +#define LL_ADC_CHANNEL_17 (ADC_CHANNEL_17_NUMBER \ + | ADC_CHANNEL_17_BITFIELD) /*!< ADC channel ADCx_IN17 */ +#define LL_ADC_CHANNEL_18 (ADC_CHANNEL_18_NUMBER \ + | ADC_CHANNEL_18_BITFIELD) /*!< ADC channel ADCx_IN18 */ +#define LL_ADC_CHANNEL_19 (ADC_CHANNEL_19_NUMBER \ + | ADC_CHANNEL_19_BITFIELD) /*!< ADC channel ADCx_IN19 */ +#define LL_ADC_CHANNEL_20 (ADC_CHANNEL_20_NUMBER \ + | ADC_CHANNEL_20_BITFIELD) /*!< ADC channel ADCx_IN20 */ +#define LL_ADC_CHANNEL_21 (ADC_CHANNEL_21_NUMBER \ + | ADC_CHANNEL_21_BITFIELD) /*!< ADC channel ADCx_IN21 */ +#define LL_ADC_CHANNEL_22 (ADC_CHANNEL_22_NUMBER \ + | ADC_CHANNEL_22_BITFIELD) /*!< ADC channel ADCx_IN22 */ +#define LL_ADC_CHANNEL_VREFINT (LL_ADC_CHANNEL_10 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel + connected to VrefInt: Internal voltage reference. */ +#define LL_ADC_CHANNEL_TEMPSENSOR (LL_ADC_CHANNEL_9 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel + connected to Temperature sensor. */ +#define LL_ADC_CHANNEL_VDDA (LL_ADC_CHANNEL_15 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel + connected to VDDA. */ +#define LL_ADC_CHANNEL_VSSA (LL_ADC_CHANNEL_16 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel + connected to VSSA. */ /** * @} */ @@ -632,11 +773,27 @@ typedef struct /** @defgroup ADC_LL_EC_REG_TRIGGER_SOURCE ADC group regular - Trigger source * @{ */ -#define LL_ADC_REG_TRIG_SOFTWARE (0x00000000UL) /*!< ADC group regular conversion trigger internal: SW start. */ -#define LL_ADC_REG_TRIG_EXT_TIM1_TRGO2 ( ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external peripheral: TIM1 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM1_CH4 ( ADC_CFGR1_EXTSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external peripheral: TIM1 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM3_TRGO ( ADC_CFGR1_EXTSEL_1 | ADC_CFGR1_EXTSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external peripheral: TIM3 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_EXTI_LINE11 (ADC_CFGR1_EXTSEL_2 | ADC_CFGR1_EXTSEL_1 | ADC_CFGR1_EXTSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger from external peripheral: external interrupt line 11. Trigger edge set to rising edge (default setting). */ +#define LL_ADC_REG_TRIG_SOFTWARE (0x00000000UL) /*!< ADC group regular conversion trigger internal: SW start */ +#define LL_ADC_REG_TRIG_EXT_TIM1_TRGO2 (ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger + from external peripheral: TIM1 TRGO. + Trigger edge set to rising edge (default setting). */ +#define LL_ADC_REG_TRIG_EXT_TIM1_CH4 (ADC_CFGR1_EXTSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular + conversion trigger from external peripheral: + TIM1 channel 4 event (capture compare: input capture or output capture). + Trigger edge set to rising edge (default setting). */ +#if defined(TIM2) +#define LL_ADC_REG_TRIG_EXT_TIM2_TRGO (ADC_CFGR1_EXTSEL_1 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular + conversion trigger from external peripheral: TIM2 TRGO. + Trigger edge set to rising edge (default setting). */ +#endif /* TIM2 */ +#define LL_ADC_REG_TRIG_EXT_TIM3_TRGO (ADC_CFGR1_EXTSEL_1 | ADC_CFGR1_EXTSEL_0 \ + | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular conversion trigger + from external peripheral: TIM3 TRGO. + Trigger edge set to rising edge (default setting). */ +#define LL_ADC_REG_TRIG_EXT_EXTI_LINE11 (ADC_CFGR1_EXTSEL_2 | ADC_CFGR1_EXTSEL_1 \ + | ADC_CFGR1_EXTSEL_0 | ADC_REG_TRIG_EXT_EDGE_DEFAULT) /*!< ADC group regular + conversion trigger from external peripheral: external interrupt line 11. + Trigger edge set to rising edge (default setting). */ /** * @} */ @@ -644,9 +801,12 @@ typedef struct /** @defgroup ADC_LL_EC_REG_TRIGGER_EDGE ADC group regular - Trigger edge * @{ */ -#define LL_ADC_REG_TRIG_EXT_RISING ( ADC_CFGR1_EXTEN_0) /*!< ADC group regular conversion trigger polarity set to rising edge */ -#define LL_ADC_REG_TRIG_EXT_FALLING (ADC_CFGR1_EXTEN_1 ) /*!< ADC group regular conversion trigger polarity set to falling edge */ -#define LL_ADC_REG_TRIG_EXT_RISINGFALLING (ADC_CFGR1_EXTEN_1 | ADC_CFGR1_EXTEN_0) /*!< ADC group regular conversion trigger polarity set to both rising and falling edges */ +#define LL_ADC_REG_TRIG_EXT_RISING (ADC_CFGR1_EXTEN_0) /*!< ADC group regular conversion + trigger polarity set to rising edge */ +#define LL_ADC_REG_TRIG_EXT_FALLING (ADC_CFGR1_EXTEN_1) /*!< ADC group regular conversion + trigger polarity set to falling edge */ +#define LL_ADC_REG_TRIG_EXT_RISINGFALLING (ADC_CFGR1_EXTEN_1 | ADC_CFGR1_EXTEN_0) /*!< ADC group regular conversion + trigger polarity set to both rising and falling edges */ /** * @} */ @@ -654,8 +814,11 @@ typedef struct /** @defgroup ADC_LL_EC_REG_CONTINUOUS_MODE ADC group regular - Continuous mode * @{ */ -#define LL_ADC_REG_CONV_SINGLE (0x00000000UL) /*!< ADC conversions are performed in single mode: one conversion per trigger */ -#define LL_ADC_REG_CONV_CONTINUOUS (ADC_CFGR1_CONT) /*!< ADC conversions are performed in continuous mode: after the first trigger, following conversions launched successively automatically */ +#define LL_ADC_REG_CONV_SINGLE (0x00000000UL) /*!< ADC conversions performed in single mode: + one conversion per trigger */ +#define LL_ADC_REG_CONV_CONTINUOUS (ADC_CFGR1_CONT) /*!< ADC conversions performed in continuous mode: + after the first trigger, following conversions launched successively + automatically */ /** * @} */ @@ -663,9 +826,15 @@ typedef struct /** @defgroup ADC_LL_EC_REG_DMA_TRANSFER ADC group regular - DMA transfer of ADC conversion data * @{ */ -#define LL_ADC_REG_DMA_TRANSFER_NONE (0x00000000UL) /*!< ADC conversions are not transferred by DMA */ -#define LL_ADC_REG_DMA_TRANSFER_LIMITED ( ADC_CFGR1_DMAEN) /*!< ADC conversion data are transferred by DMA, in limited mode (one shot mode): DMA transfer requests are stopped when number of DMA data transfers (number of ADC conversions) is reached. This ADC mode is intended to be used with DMA mode non-circular. */ -#define LL_ADC_REG_DMA_TRANSFER_UNLIMITED (ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN) /*!< ADC conversion data are transferred by DMA, in unlimited mode: DMA transfer requests are unlimited, whatever number of DMA data transferred (number of ADC conversions). This ADC mode is intended to be used with DMA mode circular. */ +#define LL_ADC_REG_DMA_TRANSFER_NONE (0x00000000UL) /*!< ADC conversions are not transferred by DMA */ +#define LL_ADC_REG_DMA_TRANSFER_LIMITED (ADC_CFGR1_DMAEN) /*!< ADC conversion data are transferred by DMA, + in limited mode (one shot mode): DMA transfer requests are stopped when + number of DMA data transfers (number of ADC conversions) is reached. + This ADC mode is intended to be used with DMA mode non-circular. */ +#define LL_ADC_REG_DMA_TRANSFER_UNLIMITED (ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN) /*!< ADC conversion data are + transferred by DMA, in unlimited mode: DMA transfer requests are unlimited, + whatever number of DMA data transferred (number of ADC conversions). + This ADC mode is intended to be used with DMA mode circular. */ /** * @} */ @@ -673,8 +842,10 @@ typedef struct /** @defgroup ADC_LL_EC_REG_OVR_DATA_BEHAVIOR ADC group regular - Overrun behavior on conversion data * @{ */ -#define LL_ADC_REG_OVR_DATA_PRESERVED (0x00000000UL) /*!< ADC group regular behavior in case of overrun: data preserved */ -#define LL_ADC_REG_OVR_DATA_OVERWRITTEN (ADC_CFGR1_OVRMOD) /*!< ADC group regular behavior in case of overrun: data overwritten */ +#define LL_ADC_REG_OVR_DATA_PRESERVED (0x00000000UL) /*!< ADC group regular behavior in case of overrun: + data preserved */ +#define LL_ADC_REG_OVR_DATA_OVERWRITTEN (ADC_CFGR1_OVRMOD) /*!< ADC group regular behavior in case of overrun: + data overwritten */ /** * @} */ @@ -682,8 +853,13 @@ typedef struct /** @defgroup ADC_LL_EC_REG_SEQ_MODE ADC group regular - Sequencer configuration flexibility * @{ */ -#define LL_ADC_REG_SEQ_FIXED (0x00000000UL) /*!< Sequencer configured to not fully configurable: sequencer length and each rank affectation to a channel are fixed by channel HW number. Refer to description of function @ref LL_ADC_REG_SetSequencerChannels(). */ -#define LL_ADC_REG_SEQ_CONFIGURABLE (ADC_CFGR1_CHSELRMOD) /*!< Sequencer configured to fully configurable: sequencer length and each rank affectation to a channel are configurable. Refer to description of function @ref LL_ADC_REG_SetSequencerLength(). */ +#define LL_ADC_REG_SEQ_FIXED (0x00000000UL) /*!< Sequencer configured to not fully configurable: + sequencer length and each rank affectation to a channel are fixed + by channel HW number. Refer to description of function + @ref LL_ADC_REG_SetSequencerChannels(). */ +#define LL_ADC_REG_SEQ_CONFIGURABLE (ADC_CFGR1_CHSELRMOD) /*!< Sequencer configured to fully configurable: + sequencer length and each rank affectation to a channel are configurable. + Refer to description of function @ref LL_ADC_REG_SetSequencerLength(). */ /** * @} */ @@ -691,14 +867,22 @@ typedef struct /** @defgroup ADC_LL_EC_REG_SEQ_SCAN_LENGTH ADC group regular - Sequencer scan length * @{ */ -#define LL_ADC_REG_SEQ_SCAN_DISABLE (ADC_CHSELR_SQ2) /*!< ADC group regular sequencer disable (equivalent to sequencer of 1 rank: ADC conversion on only 1 channel) */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS (ADC_CHSELR_SQ3) /*!< ADC group regular sequencer enable with 2 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS (ADC_CHSELR_SQ4) /*!< ADC group regular sequencer enable with 3 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS (ADC_CHSELR_SQ5) /*!< ADC group regular sequencer enable with 4 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS (ADC_CHSELR_SQ6) /*!< ADC group regular sequencer enable with 5 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS (ADC_CHSELR_SQ7) /*!< ADC group regular sequencer enable with 6 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS (ADC_CHSELR_SQ8) /*!< ADC group regular sequencer enable with 7 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS (0x00000000UL) /*!< ADC group regular sequencer enable with 8 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_DISABLE (ADC_CHSELR_SQ2) /*!< ADC group regular sequencer disable + (equivalent to sequencer of 1 rank: ADC conversion on only 1 channel) */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS (ADC_CHSELR_SQ3) /*!< ADC group regular sequencer enable + with 2 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS (ADC_CHSELR_SQ4) /*!< ADC group regular sequencer enable + with 3 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS (ADC_CHSELR_SQ5) /*!< ADC group regular sequencer enable + with 4 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS (ADC_CHSELR_SQ6) /*!< ADC group regular sequencer enable + with 5 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS (ADC_CHSELR_SQ7) /*!< ADC group regular sequencer enable + with 6 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS (ADC_CHSELR_SQ8) /*!< ADC group regular sequencer enable + with 7 ranks in the sequence */ +#define LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS (0x00000000UL) /*!< ADC group regular sequencer enable + with 8 ranks in the sequence */ /** * @} */ @@ -706,8 +890,19 @@ typedef struct /** @defgroup ADC_LL_EC_REG_SEQ_SCAN_DIRECTION ADC group regular - Sequencer scan direction * @{ */ -#define LL_ADC_REG_SEQ_SCAN_DIR_FORWARD (0x00000000UL) /*!< On this STM32 series, parameter relevant only is sequencer set to mode not fully configurable, refer to function @ref LL_ADC_REG_SetSequencerConfigurable(). ADC group regular sequencer scan direction forward: from lowest channel number to highest channel number (scan of all ranks, ADC conversion of ranks with channels enabled in sequencer). On some other STM32 families, this setting is not available and the default scan direction is forward. */ -#define LL_ADC_REG_SEQ_SCAN_DIR_BACKWARD (ADC_CFGR1_SCANDIR) /*!< On this STM32 series, parameter relevant only is sequencer set to mode not fully configurable, refer to function @ref LL_ADC_REG_SetSequencerConfigurable(). ADC group regular sequencer scan direction backward: from highest channel number to lowest channel number (scan of all ranks, ADC conversion of ranks with channels enabled in sequencer) */ +#define LL_ADC_REG_SEQ_SCAN_DIR_FORWARD (0x00000000UL) /*!< On this STM32 series, parameter relevant only if + sequencer set to mode not fully configurable, refer to function + @ref LL_ADC_REG_SetSequencerConfigurable(). ADC group regular sequencer scan + direction forward: from lowest channel number to highest channel number + (scan of all ranks, ADC conversion of ranks with channels enabled in + sequencer). On some other STM32 series, this setting is not available + and the default scan direction is forward. */ +#define LL_ADC_REG_SEQ_SCAN_DIR_BACKWARD (ADC_CFGR1_SCANDIR) /*!< On this STM32 series, parameter relevant only if + sequencer set to mode not fully configurable, refer to function + @ref LL_ADC_REG_SetSequencerConfigurable(). ADC group regular sequencer scan + direction backward: from highest channel number to lowest channel number + (scan of all ranks, ADC conversion of ranks with channels enabled in + sequencer) */ /** * @} */ @@ -715,8 +910,10 @@ typedef struct /** @defgroup ADC_LL_EC_REG_SEQ_DISCONT_MODE ADC group regular - Sequencer discontinuous mode * @{ */ -#define LL_ADC_REG_SEQ_DISCONT_DISABLE (0x00000000UL) /*!< ADC group regular sequencer discontinuous mode disable */ -#define LL_ADC_REG_SEQ_DISCONT_1RANK (ADC_CFGR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every rank */ +#define LL_ADC_REG_SEQ_DISCONT_DISABLE (0x00000000UL) /*!< ADC group regular sequencer + discontinuous mode disable */ +#define LL_ADC_REG_SEQ_DISCONT_1RANK (ADC_CFGR1_DISCEN) /*!< ADC group regular sequencer + discontinuous mode enable with sequence interruption every rank */ /** * @} */ @@ -724,14 +921,14 @@ typedef struct /** @defgroup ADC_LL_EC_REG_SEQ_RANKS ADC group regular - Sequencer ranks * @{ */ -#define LL_ADC_REG_RANK_1 (ADC_REG_RANK_1_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 1 */ -#define LL_ADC_REG_RANK_2 (ADC_REG_RANK_2_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 2 */ -#define LL_ADC_REG_RANK_3 (ADC_REG_RANK_3_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 3 */ -#define LL_ADC_REG_RANK_4 (ADC_REG_RANK_4_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 4 */ -#define LL_ADC_REG_RANK_5 (ADC_REG_RANK_5_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 5 */ -#define LL_ADC_REG_RANK_6 (ADC_REG_RANK_6_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 6 */ -#define LL_ADC_REG_RANK_7 (ADC_REG_RANK_7_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 7 */ -#define LL_ADC_REG_RANK_8 (ADC_REG_RANK_8_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 8 */ +#define LL_ADC_REG_RANK_1 (ADC_REG_RANK_1_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 1 */ +#define LL_ADC_REG_RANK_2 (ADC_REG_RANK_2_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 2 */ +#define LL_ADC_REG_RANK_3 (ADC_REG_RANK_3_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 3 */ +#define LL_ADC_REG_RANK_4 (ADC_REG_RANK_4_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 4 */ +#define LL_ADC_REG_RANK_5 (ADC_REG_RANK_5_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 5 */ +#define LL_ADC_REG_RANK_6 (ADC_REG_RANK_6_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 6 */ +#define LL_ADC_REG_RANK_7 (ADC_REG_RANK_7_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 7 */ +#define LL_ADC_REG_RANK_8 (ADC_REG_RANK_8_SQRX_BITOFFSET_POS) /*!< ADC group regular seq. rank 8 */ /** * @} */ @@ -739,14 +936,19 @@ typedef struct /** @defgroup ADC_LL_EC_CHANNEL_SAMPLINGTIME Channel - Sampling time * @{ */ -#define LL_ADC_SAMPLINGTIME_1CYCLE_5 (0x00000000UL) /*!< Sampling time 1.5 ADC clock cycle */ -#define LL_ADC_SAMPLINGTIME_3CYCLES_5 (ADC_SMPR_SMP1_0) /*!< Sampling time 3.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_7CYCLES_5 (ADC_SMPR_SMP1_1) /*!< Sampling time 7.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_12CYCLES_5 (ADC_SMPR_SMP1_1 | ADC_SMPR_SMP1_0) /*!< Sampling time 12.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_19CYCLES_5 (ADC_SMPR_SMP1_2) /*!< Sampling time 19.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_39CYCLES_5 (ADC_SMPR_SMP1_2 | ADC_SMPR_SMP1_0) /*!< Sampling time 39.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_79CYCLES_5 (ADC_SMPR_SMP1_2 | ADC_SMPR_SMP1_1) /*!< Sampling time 79.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_160CYCLES_5 (ADC_SMPR_SMP1_2 | ADC_SMPR_SMP1_1 | ADC_SMPR_SMP1_0) /*!< Sampling time 160.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_1CYCLE_5 (0x00000000UL) /*!< Sampling time 1.5 ADC clock cycle */ +#define LL_ADC_SAMPLINGTIME_3CYCLES_5 (ADC_SMPR_SMP1_0) /*!< Sampling time 3.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_7CYCLES_5 (ADC_SMPR_SMP1_1) /*!< Sampling time 7.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_12CYCLES_5 (ADC_SMPR_SMP1_1 \ + | ADC_SMPR_SMP1_0) /*!< Sampling time 12.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_19CYCLES_5 (ADC_SMPR_SMP1_2) /*!< Sampling time 19.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_39CYCLES_5 (ADC_SMPR_SMP1_2 \ + | ADC_SMPR_SMP1_0) /*!< Sampling time 39.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_79CYCLES_5 (ADC_SMPR_SMP1_2 \ + | ADC_SMPR_SMP1_1) /*!< Sampling time 79.5 ADC clock cycles */ +#define LL_ADC_SAMPLINGTIME_160CYCLES_5 (ADC_SMPR_SMP1_2 \ + | ADC_SMPR_SMP1_1 \ + | ADC_SMPR_SMP1_0) /*!< Sampling time 160.5 ADC clock cycles */ /** * @} */ @@ -754,9 +956,12 @@ typedef struct /** @defgroup ADC_LL_EC_AWD_NUMBER Analog watchdog - Analog watchdog number * @{ */ -#define LL_ADC_AWD1 (ADC_AWD_CR1_CHANNEL_MASK | ADC_AWD_CR1_REGOFFSET) /*!< ADC analog watchdog number 1 */ -#define LL_ADC_AWD2 (ADC_AWD_CR23_CHANNEL_MASK | ADC_AWD_CR2_REGOFFSET) /*!< ADC analog watchdog number 2 */ -#define LL_ADC_AWD3 (ADC_AWD_CR23_CHANNEL_MASK | ADC_AWD_CR3_REGOFFSET) /*!< ADC analog watchdog number 3 */ +#define LL_ADC_AWD1 (ADC_AWD_CR1_CHANNEL_MASK \ + | ADC_AWD_CR1_REGOFFSET) /*!< ADC analog watchdog number 1 */ +#define LL_ADC_AWD2 (ADC_AWD_CR23_CHANNEL_MASK \ + | ADC_AWD_CR2_REGOFFSET) /*!< ADC analog watchdog number 2 */ +#define LL_ADC_AWD3 (ADC_AWD_CR23_CHANNEL_MASK \ + | ADC_AWD_CR3_REGOFFSET) /*!< ADC analog watchdog number 3 */ /** * @} */ @@ -764,35 +969,96 @@ typedef struct /** @defgroup ADC_LL_EC_AWD_CHANNELS Analog watchdog - Monitored channels * @{ */ -#define LL_ADC_AWD_DISABLE (0x00000000UL) /*!< ADC analog watchdog monitoring disabled */ -#define LL_ADC_AWD_ALL_CHANNELS_REG (ADC_AWD_CR23_CHANNEL_MASK | ADC_CFGR1_AWD1EN ) /*!< ADC analog watchdog monitoring of all channels, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_0_REG ((LL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_1_REG ((LL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_2_REG ((LL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_3_REG ((LL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_4_REG ((LL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_5_REG ((LL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_6_REG ((LL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_7_REG ((LL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_8_REG ((LL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_9_REG ((LL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_10_REG ((LL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_11_REG ((LL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_12_REG ((LL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_13_REG ((LL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_14_REG ((LL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_15_REG ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_16_REG ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_17_REG ((LL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_18_REG ((LL_ADC_CHANNEL_18 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN18, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_19_REG ((LL_ADC_CHANNEL_19 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_20_REG ((LL_ADC_CHANNEL_20 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_21_REG ((LL_ADC_CHANNEL_21 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN18, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_22_REG ((LL_ADC_CHANNEL_22 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN18, converted by group regular only */ -#define LL_ADC_AWD_CH_VREFINT_REG ((LL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by group regular only */ -#define LL_ADC_AWD_CH_TEMPSENSOR_REG ((LL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group regular only */ -#define LL_ADC_AWD_CH_VSSA_REG ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VSSA : internal analog supply ground, converted by group regular only */ -#define LL_ADC_AWD_CH_VDDA_REG ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VDDA : internal analog power supply, converted by group regular only */ +#define LL_ADC_AWD_DISABLE (0x00000000UL) /*!< ADC analog watchdog monitoring + disabled */ +#define LL_ADC_AWD_ALL_CHANNELS_REG (ADC_AWD_CR23_CHANNEL_MASK \ + | ADC_CFGR1_AWD1EN) /*!< ADC analog watchdog monitoring + of all channels, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_0_REG ((LL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN0, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_1_REG ((LL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN1, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_2_REG ((LL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN2, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_3_REG ((LL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN3, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_4_REG ((LL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN4, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_5_REG ((LL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN5, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_6_REG ((LL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN6, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_7_REG ((LL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN7, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_8_REG ((LL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN8, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_9_REG ((LL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN9, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_10_REG ((LL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN10, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_11_REG ((LL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN11, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_12_REG ((LL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN12, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_13_REG ((LL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN13, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_14_REG ((LL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN14, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_15_REG ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN15, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_16_REG ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN16, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_17_REG ((LL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN17, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_18_REG ((LL_ADC_CHANNEL_18 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN18, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_19_REG ((LL_ADC_CHANNEL_19 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN19, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_20_REG ((LL_ADC_CHANNEL_20 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN20, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_21_REG ((LL_ADC_CHANNEL_21 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN21, converted by group regular only */ +#define LL_ADC_AWD_CHANNEL_22_REG ((LL_ADC_CHANNEL_22 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC channel ADCx_IN22, converted by group regular only */ +#define LL_ADC_AWD_CH_VREFINT_REG ((LL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC internal channel connected to VrefInt: Internal voltage reference, + converted by group regular only */ +#define LL_ADC_AWD_CH_TEMPSENSOR_REG ((LL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC internal channel connected to Temperature sensor, + converted by group regular only */ +#define LL_ADC_AWD_CH_VSSA_REG ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC internal channel connected to VSSA : internal analog supply ground, + converted by group regular only */ +#define LL_ADC_AWD_CH_VDDA_REG ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) \ + | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL) /*!< ADC analog watchdog monitoring + of ADC internal channel connected to VDDA : internal analog power supply, + converted by group regular only */ /** * @} */ @@ -800,9 +1066,11 @@ typedef struct /** @defgroup ADC_LL_EC_AWD_THRESHOLDS Analog watchdog - Thresholds * @{ */ -#define LL_ADC_AWD_THRESHOLD_HIGH (ADC_AWD1TR_HT1 ) /*!< ADC analog watchdog threshold high */ -#define LL_ADC_AWD_THRESHOLD_LOW ( ADC_AWD1TR_LT1) /*!< ADC analog watchdog threshold low */ -#define LL_ADC_AWD_THRESHOLDS_HIGH_LOW (ADC_AWD1TR_HT1 | ADC_AWD1TR_LT1) /*!< ADC analog watchdog both thresholds high and low concatenated into the same data */ +#define LL_ADC_AWD_THRESHOLD_HIGH (ADC_AWD1TR_HT1) /*!< ADC analog watchdog threshold high */ +#define LL_ADC_AWD_THRESHOLD_LOW (ADC_AWD1TR_LT1) /*!< ADC analog watchdog threshold low */ +#define LL_ADC_AWD_THRESHOLDS_HIGH_LOW (ADC_AWD1TR_HT1 \ + | ADC_AWD1TR_LT1) /*!< ADC analog watchdog both thresholds high and low + concatenated into the same data */ /** * @} */ @@ -810,8 +1078,11 @@ typedef struct /** @defgroup ADC_LL_EC_OVS_SCOPE Oversampling - Oversampling scope * @{ */ -#define LL_ADC_OVS_DISABLE (0x00000000UL) /*!< ADC oversampling disabled. */ -#define LL_ADC_OVS_GRP_REGULAR_CONTINUED ( ADC_CFGR2_OVSE) /*!< ADC oversampling on conversions of ADC group regular. Literal suffix "continued" is kept for compatibility with other STM32 devices featuring ADC group injected, in this case other oversampling scope parameters are available. */ +#define LL_ADC_OVS_DISABLE (0x00000000UL) /*!< ADC oversampling disabled. */ +#define LL_ADC_OVS_GRP_REGULAR_CONTINUED (ADC_CFGR2_OVSE) /*!< ADC oversampling on conversions of + ADC group regular. Literal suffix "continued" is kept for compatibility + with other STM32 devices featuring ADC group injected, in this case other + oversampling scope parameters are available. */ /** * @} */ @@ -819,8 +1090,10 @@ typedef struct /** @defgroup ADC_LL_EC_OVS_DISCONT_MODE Oversampling - Discontinuous mode * @{ */ -#define LL_ADC_OVS_REG_CONT (0x00000000UL) /*!< ADC oversampling discontinuous mode: continuous mode (all conversions of oversampling ratio are done from 1 trigger) */ -#define LL_ADC_OVS_REG_DISCONT (ADC_CFGR2_TOVS) /*!< ADC oversampling discontinuous mode: discontinuous mode (each conversion of oversampling ratio needs a trigger) */ +#define LL_ADC_OVS_REG_CONT (0x00000000UL) /*!< ADC oversampling discontinuous mode: continuous mode +(all conversions of oversampling ratio are done from 1 trigger) */ +#define LL_ADC_OVS_REG_DISCONT (ADC_CFGR2_TOVS) /*!< ADC oversampling discontinuous mode: discontinuous + mode (each conversion of oversampling ratio needs a trigger) */ /** * @} */ @@ -828,30 +1101,66 @@ typedef struct /** @defgroup ADC_LL_EC_OVS_RATIO Oversampling - Ratio * @{ */ -#define LL_ADC_OVS_RATIO_2 (0x00000000UL) /*!< ADC oversampling ratio of 2 (2 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_4 ( ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 4 (4 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_8 ( ADC_CFGR2_OVSR_1 ) /*!< ADC oversampling ratio of 8 (8 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_16 ( ADC_CFGR2_OVSR_1 | ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 16 (16 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_32 (ADC_CFGR2_OVSR_2 ) /*!< ADC oversampling ratio of 32 (32 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_64 (ADC_CFGR2_OVSR_2 | ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 64 (64 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_128 (ADC_CFGR2_OVSR_2 | ADC_CFGR2_OVSR_1 ) /*!< ADC oversampling ratio of 128 (128 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ -#define LL_ADC_OVS_RATIO_256 (ADC_CFGR2_OVSR_2 | ADC_CFGR2_OVSR_1 | ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 256 (256 ADC conversions are performed, sum of these conversions data is computed to result as the ADC oversampling conversion data (before potential shift) */ +#define LL_ADC_OVS_RATIO_2 (0x00000000UL) /*!< ADC oversampling ratio of 2 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_4 (ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 4 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_8 (ADC_CFGR2_OVSR_1) /*!< ADC oversampling ratio of 8 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_16 (ADC_CFGR2_OVSR_1 | ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 16 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_32 (ADC_CFGR2_OVSR_2) /*!< ADC oversampling ratio of 32 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_64 (ADC_CFGR2_OVSR_2 | ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 64 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_128 (ADC_CFGR2_OVSR_2 | ADC_CFGR2_OVSR_1) /*!< ADC oversampling ratio of 128 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ +#define LL_ADC_OVS_RATIO_256 (ADC_CFGR2_OVSR_2 | ADC_CFGR2_OVSR_1 \ + | ADC_CFGR2_OVSR_0) /*!< ADC oversampling ratio of 256 + (sum of conversions data computed to result as oversampling conversion data + (before potential shift) */ /** * @} */ -/** @defgroup ADC_LL_EC_OVS_SHIFT Oversampling - Data shift +/** @defgroup ADC_LL_EC_OVS_SHIFT Oversampling - Data right shift * @{ */ -#define LL_ADC_OVS_SHIFT_NONE (0x00000000UL) /*!< ADC oversampling no shift (sum of the ADC conversions data is not divided to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_1 ( ADC_CFGR2_OVSS_0) /*!< ADC oversampling shift of 1 (sum of the ADC conversions data is divided by 2 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_2 ( ADC_CFGR2_OVSS_1 ) /*!< ADC oversampling shift of 2 (sum of the ADC conversions data is divided by 4 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_3 ( ADC_CFGR2_OVSS_1 | ADC_CFGR2_OVSS_0) /*!< ADC oversampling shift of 3 (sum of the ADC conversions data is divided by 8 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_4 ( ADC_CFGR2_OVSS_2 ) /*!< ADC oversampling shift of 4 (sum of the ADC conversions data is divided by 16 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_5 ( ADC_CFGR2_OVSS_2 | ADC_CFGR2_OVSS_0) /*!< ADC oversampling shift of 5 (sum of the ADC conversions data is divided by 32 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_6 ( ADC_CFGR2_OVSS_2 | ADC_CFGR2_OVSS_1 ) /*!< ADC oversampling shift of 6 (sum of the ADC conversions data is divided by 64 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_7 ( ADC_CFGR2_OVSS_2 | ADC_CFGR2_OVSS_1 | ADC_CFGR2_OVSS_0) /*!< ADC oversampling shift of 7 (sum of the ADC conversions data is divided by 128 to result as the ADC oversampling conversion data) */ -#define LL_ADC_OVS_SHIFT_RIGHT_8 (ADC_CFGR2_OVSS_3 ) /*!< ADC oversampling shift of 8 (sum of the ADC conversions data is divided by 256 to result as the ADC oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_NONE (0x00000000UL) /*!< ADC oversampling no shift + (sum of the ADC conversions data is not divided to result as oversampling + conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_1 (ADC_CFGR2_OVSS_0) /*!< ADC oversampling right shift of 1 + (sum of the ADC conversions data (after OVS ratio) is divided by 2 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_2 (ADC_CFGR2_OVSS_1) /*!< ADC oversampling right shift of 2 + (sum of the ADC conversions data (after OVS ratio) is divided by 4 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_3 (ADC_CFGR2_OVSS_1 | ADC_CFGR2_OVSS_0) /*!< ADC oversampling right shift of 3 + (sum of the ADC conversions data (after OVS ratio) is divided by 8 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_4 (ADC_CFGR2_OVSS_2) /*!< ADC oversampling right shift of 4 + (sum of the ADC conversions data (after OVS ratio) is divided by 16 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_5 (ADC_CFGR2_OVSS_2 | ADC_CFGR2_OVSS_0) /*!< ADC oversampling right shift of 5 + (sum of the ADC conversions data (after OVS ratio) is divided by 32 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_6 (ADC_CFGR2_OVSS_2 | ADC_CFGR2_OVSS_1) /*!< ADC oversampling right shift of 6 + (sum of the ADC conversions data (after OVS ratio) is divided by 64 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_7 (ADC_CFGR2_OVSS_2 | ADC_CFGR2_OVSS_1 \ + | ADC_CFGR2_OVSS_0) /*!< ADC oversampling right shift of 7 + (sum of the ADC conversions data (after OVS ratio) is divided by 128 + to result as oversampling conversion data) */ +#define LL_ADC_OVS_SHIFT_RIGHT_8 (ADC_CFGR2_OVSS_3) /*!< ADC oversampling right shift of 8 + (sum of the ADC conversions data (after OVS ratio) is divided by 256 + to result as oversampling conversion data) */ /** * @} */ @@ -859,7 +1168,11 @@ typedef struct /** @defgroup ADC_LL_EC_HELPER_MACRO Definitions of constants used by helper macro * @{ */ -#define LL_ADC_TEMPERATURE_CALC_ERROR ((int16_t)0x7FFF) /* Temperature calculation error using helper macro @ref __LL_ADC_CALC_TEMPERATURE_TYP_PARAMS(), due to issue on calibration parameters. This value is coded on 16 bits (to fit on signed word or double word) and corresponds to an inconsistent temperature value. */ +#define LL_ADC_TEMPERATURE_CALC_ERROR ((int16_t)0x7FFF) /* Temperature calculation error using helper macro + @ref __LL_ADC_CALC_TEMPERATURE(), due to issue on + calibration parameters. This value is coded on 16 bits + (to fit on signed word or double word) and corresponds + to an inconsistent temperature value. */ /** * @} */ @@ -894,20 +1207,26 @@ typedef struct /* Delay set to maximum value (refer to device datasheet, */ /* parameter "tADCVREG_STUP"). */ /* Unit: us */ -#define LL_ADC_DELAY_INTERNAL_REGUL_STAB_US ( 20UL) /*!< Delay for ADC stabilization time (ADC voltage regulator start-up time) */ +#define LL_ADC_DELAY_INTERNAL_REGUL_STAB_US ( 20UL) /*!< Delay for ADC stabilization time (ADC voltage + regulator start-up time) */ /* Delay for internal voltage reference stabilization time. */ /* Delay set to maximum value (refer to device datasheet, */ /* parameter "tstart_vrefint"). */ /* Unit: us */ -#define LL_ADC_DELAY_VREFINT_STAB_US ( 12UL) /*!< Delay for internal voltage reference stabilization time */ +#define LL_ADC_DELAY_VREFINT_STAB_US ( 12UL) /*!< Delay for internal voltage reference stabilization + time */ /* Delay for temperature sensor stabilization time. */ /* Literal set to maximum value (refer to device datasheet, */ /* parameter "tSTART"). */ /* Unit: us */ -#define LL_ADC_DELAY_TEMPSENSOR_STAB_US (120UL) /*!< Delay for temperature sensor stabilization time (starting from temperature sensor enable, refer to @ref LL_ADC_SetCommonPathInternalCh()) */ -#define LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US ( 15UL) /*!< Delay for temperature sensor buffer stabilization time (starting from ADC enable, refer to @ref LL_ADC_Enable()) */ +#define LL_ADC_DELAY_TEMPSENSOR_STAB_US (120UL) /*!< Delay for temperature sensor stabilization time + (starting from temperature sensor enable, refer to + @ref LL_ADC_SetCommonPathInternalCh()) */ +#define LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US ( 15UL) /*!< Delay for temperature sensor buffer stabilization + time (starting from ADC enable, refer to + @ref LL_ADC_Enable()) */ /* Delay required between ADC end of calibration and ADC enable. */ /* Note: On this STM32 series, a minimum number of ADC clock cycles */ @@ -916,7 +1235,8 @@ typedef struct /* equivalent number of CPU cycles, by taking into account */ /* ratio of CPU clock versus ADC clock prescalers. */ /* Unit: ADC clock cycles. */ -#define LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES ( 2UL) /*!< Delay required between ADC end of calibration and ADC enable */ +#define LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES ( 2UL) /*!< Delay required between ADC end of calibration + and ADC enable */ /** * @} @@ -1139,7 +1459,8 @@ typedef struct * comparison with internal channel parameter to be done * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). * (3) ADC channels available on STM32C031xx device only. - * @retval Value "0" if the channel corresponds to a parameter definition of a ADC external channel (channel connected to a GPIO pin). + * @retval Value "0" if the channel corresponds to a parameter definition of a ADC external channel + * (channel connected to a GPIO pin). * Value "1" if the channel corresponds to a parameter definition of a ADC internal channel. */ #define __LL_ADC_IS_CHANNEL_INTERNAL(__CHANNEL__) \ @@ -1389,8 +1710,9 @@ typedef struct * @param __AWD_THRESHOLDS__ Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF * @retval Value between Min_Data=0x000 and Max_Data=0xFFF */ -#define __LL_ADC_ANALOGWD_THRESHOLDS_HIGH_LOW(__AWD_THRESHOLD_TYPE__, __AWD_THRESHOLDS__) \ - (((__AWD_THRESHOLDS__) >> (((__AWD_THRESHOLD_TYPE__) & ADC_AWD_TRX_BIT_HIGH_MASK) >> ADC_AWD_TRX_BIT_HIGH_SHIFT4)) & LL_ADC_AWD_THRESHOLD_LOW) +#define __LL_ADC_ANALOGWD_THRESHOLDS_HIGH_LOW(__AWD_THRESHOLD_TYPE__, __AWD_THRESHOLDS__) \ + (((__AWD_THRESHOLDS__) >> (((__AWD_THRESHOLD_TYPE__) & ADC_AWD_TRX_BIT_HIGH_MASK) >> ADC_AWD_TRX_BIT_HIGH_SHIFT4)) \ + & LL_ADC_AWD_THRESHOLD_LOW) /** * @brief Helper macro to select the ADC common instance @@ -1551,12 +1873,16 @@ typedef struct * @note ADC measurement data must correspond to a resolution of 12 bits * (full scale digital value 4095). If not the case, the data must be * preliminarily rescaled to an equivalent resolution of 12 bits. - * @param __TEMPSENSOR_TYP_AVGSLOPE__ Device datasheet data: Temperature sensor slope typical value (unit: uV/DegCelsius). - * On STM32C0, refer to device datasheet parameter "Avg_Slope". - * @param __TEMPSENSOR_TYP_CALX_V__ Device datasheet data: Temperature sensor voltage typical value (at temperature and Vref+ defined in parameters below) (unit: mV). - * On STM32C0, refer to device datasheet parameter "V30" (corresponding to TS_CAL1). - * @param __TEMPSENSOR_CALX_TEMP__ Device datasheet data: Temperature at which temperature sensor voltage (see parameter above) is corresponding (unit: mV) - * @param __VREFANALOG_VOLTAGE__ Analog voltage reference (Vref+) voltage (unit: mV) + * @param __TEMPSENSOR_TYP_AVGSLOPE__ Device datasheet data: Temperature sensor slope typical value + (unit: uV/DegCelsius). + * On this STM32 series, refer to device datasheet parameter "Avg_Slope". + * @param __TEMPSENSOR_TYP_CALX_V__ Device datasheet data: Temperature sensor voltage typical value + (at temperature and Vref+ defined in parameters below) (unit: mV). + * On this STM32 series, refer to datasheet parameter "V30" (corresponding + * to TS_CAL1). + * @param __TEMPSENSOR_CALX_TEMP__ Device datasheet data: Temperature at which temperature sensor voltage + (see parameter above) is corresponding (unit: mV) + * @param __VREFANALOG_VOLTAGE__ Analog voltage reference (Vref+) value (unit: mV) * @param __TEMPSENSOR_ADC_DATA__ ADC conversion data of internal temperature sensor (unit: digital value). * @param __ADC_RESOLUTION__ ADC resolution at which internal temperature sensor voltage has been measured. * This parameter can be one of the following values: @@ -1642,7 +1968,8 @@ __STATIC_INLINE uint32_t LL_ADC_DMA_GetRegAddr(ADC_TypeDef *ADCx, uint32_t Regis * @} */ -/** @defgroup ADC_LL_EF_Configuration_ADC_Common Configuration of ADC hierarchical scope: common to several ADC instances +/** @defgroup ADC_LL_EF_Configuration_ADC_Common Configuration of ADC hierarchical scope: common to several + * ADC instances * @{ */ @@ -2280,8 +2607,10 @@ __STATIC_INLINE uint32_t LL_ADC_GetSamplingTimeCommonChannels(ADC_TypeDef *ADCx, * @arg @ref LL_ADC_REG_TRIG_SOFTWARE * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_TRGO2 * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH4 + * @arg @ref LL_ADC_REG_TRIG_EXT_TIM2_TRGO (1) * @arg @ref LL_ADC_REG_TRIG_EXT_TIM3_TRGO * @arg @ref LL_ADC_REG_TRIG_EXT_EXTI_LINE11 + * (1) ADC external trigger available on STM32C071xx device only. * @retval None */ __STATIC_INLINE void LL_ADC_REG_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t TriggerSource) @@ -2308,8 +2637,10 @@ __STATIC_INLINE void LL_ADC_REG_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t Tri * @arg @ref LL_ADC_REG_TRIG_SOFTWARE * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_TRGO2 * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH4 + * @arg @ref LL_ADC_REG_TRIG_EXT_TIM2_TRGO (1) * @arg @ref LL_ADC_REG_TRIG_EXT_TIM3_TRGO * @arg @ref LL_ADC_REG_TRIG_EXT_EXTI_LINE11 + * (1) ADC external trigger available on STM32C071xx device only. */ __STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerSource(ADC_TypeDef *ADCx) { @@ -2762,7 +3093,8 @@ __STATIC_INLINE void LL_ADC_REG_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Ra /* other bits reserved for other purpose. */ MODIFY_REG(ADCx->CHSELR, ADC_CHSELR_SQ1 << (Rank & ADC_REG_RANK_ID_SQRX_MASK), - ((Channel & ADC_CHANNEL_ID_NUMBER_MASK_SEQ) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) << (Rank & ADC_REG_RANK_ID_SQRX_MASK)); + ((Channel & ADC_CHANNEL_ID_NUMBER_MASK_SEQ) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) + << (Rank & ADC_REG_RANK_ID_SQRX_MASK)); } /** @@ -3590,8 +3922,9 @@ __STATIC_INLINE uint32_t LL_ADC_GetChannelSamplingTime(ADC_TypeDef *ADCx, uint32 /* Retrieve sampling time bit corresponding to the selected channel */ /* and shift it to position 0. */ uint32_t smp_channel_posbit0 = ((smpr & ADC_SAMPLING_TIME_CH_MASK) - >> ((((Channel & ADC_CHANNEL_ID_NUMBER_MASK) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) + ADC_SMPR_SMPSEL0_BITOFFSET_POS) & - 0x1FUL)); + >> ((((Channel & ADC_CHANNEL_ID_NUMBER_MASK) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) + + ADC_SMPR_SMPSEL0_BITOFFSET_POS) + & 0x1FUL)); /* Select sampling time bitfield depending on sampling time bit value 0 or 1. */ return ((~(smp_channel_posbit0) * LL_ADC_SAMPLINGTIME_COMMON_1) @@ -3682,7 +4015,8 @@ __STATIC_INLINE void LL_ADC_SetAnalogWDMonitChannels(ADC_TypeDef *ADCx, uint32_t } else { - preg = __ADC_PTR_REG_OFFSET(ADCx->AWD2CR, ((AWDy & ADC_AWD_CRX_REGOFFSET_MASK)) >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL)); + preg = __ADC_PTR_REG_OFFSET(ADCx->AWD2CR, + ((AWDy & ADC_AWD_CRX_REGOFFSET_MASK)) >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL)); } MODIFY_REG(*preg, @@ -3778,8 +4112,10 @@ __STATIC_INLINE void LL_ADC_SetAnalogWDMonitChannels(ADC_TypeDef *ADCx, uint32_t * (1) On STM32C0, parameter not available on all devices: only on STM32C031xx. */__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDMonitChannels(ADC_TypeDef *ADCx, uint32_t AWDy) { - register __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->CFGR1, ((AWDy & ADC_AWD_CRX_REGOFFSET_MASK) >> ADC_AWD_CRX_REGOFFSET_POS) - + ((AWDy & ADC_AWD_CR12_REGOFFSETGAP_MASK) * ADC_AWD_CR12_REGOFFSETGAP_VAL)); + register __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->CFGR1, + ((AWDy & ADC_AWD_CRX_REGOFFSET_MASK) >> ADC_AWD_CRX_REGOFFSET_POS) + + ((AWDy & ADC_AWD_CR12_REGOFFSETGAP_MASK) + * ADC_AWD_CR12_REGOFFSETGAP_VAL)); register uint32_t AnalogWDMonitChannels = (READ_BIT(*preg, AWDy) & AWDy & ADC_AWD_CR_ALL_CHANNEL_MASK); @@ -3900,7 +4236,12 @@ __STATIC_INLINE void LL_ADC_ConfigAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t /* "AWDy". */ /* Parameters "AWDy" and "AWDThresholdxxxValue" are used with masks because */ /* containing other bits reserved for other purpose. */ - register __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWD1TR, (((AWDy & ADC_AWD_TRX_REGOFFSET_MASK)) >> (ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS)) + ((ADC_AWD_CR3_REGOFFSET & AWDy) >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL))); + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWD1TR, + (((AWDy & ADC_AWD_TRX_REGOFFSET_MASK)) + >> (ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS)) + + ((ADC_AWD_CR3_REGOFFSET & AWDy) + >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL)) + ); MODIFY_REG(*preg, ADC_AWD1TR_HT1 | ADC_AWD1TR_LT1, @@ -3977,7 +4318,11 @@ __STATIC_INLINE void LL_ADC_SetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AW /* "AWDThresholdsHighLow" and "AWDy". */ /* Parameters "AWDy" and "AWDThresholdValue" are used with masks because */ /* containing other bits reserved for other purpose. */ - register __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWD1TR, (((AWDy & ADC_AWD_TRX_REGOFFSET_MASK)) >> (ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS)) + ((ADC_AWD_CR3_REGOFFSET & AWDy) >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL))); + __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWD1TR, + (((AWDy & ADC_AWD_TRX_REGOFFSET_MASK)) + >> (ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS)) + + ((ADC_AWD_CR3_REGOFFSET & AWDy) + >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL))); MODIFY_REG(*preg, AWDThresholdsHighLow, @@ -4019,7 +4364,11 @@ __STATIC_INLINE uint32_t LL_ADC_GetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_ /* "AWDThresholdsHighLow" and "AWDy". */ /* Parameters "AWDy" and "AWDThresholdValue" are used with masks because */ /* containing other bits reserved for other purpose. */ - register const __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWD1TR, (((AWDy & ADC_AWD_TRX_REGOFFSET_MASK)) >> (ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS)) + ((ADC_AWD_CR3_REGOFFSET & AWDy) >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL))); + const __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->AWD1TR, + (((AWDy & ADC_AWD_TRX_REGOFFSET_MASK)) + >> (ADC_AWD_TRX_REGOFFSET_BITOFFSET_POS)) + + ((ADC_AWD_CR3_REGOFFSET & AWDy) + >> (ADC_AWD_CRX_REGOFFSET_BITOFFSET_POS + 1UL))); return (uint32_t)(READ_BIT(*preg, (AWDThresholdsHighLow | ADC_AWD1TR_LT1)) @@ -4901,7 +5250,7 @@ __STATIC_INLINE void LL_ADC_DisableIT_ADRDY(ADC_TypeDef *ADCx) /** * @brief Disable interruption ADC channel configuration ready. - * @rmtoll IER ADRDYIE LL_ADC_DisableIT_CCRDY + * @rmtoll IER CCRDYIE LL_ADC_DisableIT_CCRDY * @param ADCx ADC instance * @retval State of bit (1 or 0). */ @@ -5012,7 +5361,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_ADRDY(ADC_TypeDef *ADCx) /** * @brief Get state of interruption ADC channel configuration ready. - * @rmtoll IER ADRDYIE LL_ADC_IsEnabledIT_CCRDY + * @rmtoll IER CCRDYIE LL_ADC_IsEnabledIT_CCRDY * @param ADCx ADC instance * @retval State of bit (1 or 0). */ @@ -5127,13 +5476,12 @@ __STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_EOCAL(ADC_TypeDef *ADCx) */ /* Initialization of some features of ADC common parameters and multimode */ -ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON); +ErrorStatus LL_ADC_CommonDeInit(const ADC_Common_TypeDef *ADCxy_COMMON); ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct); void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct); /* De-initialization of ADC instance */ ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx); - /* Initialization of some features of ADC instance */ ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, LL_ADC_InitTypeDef *ADC_InitStruct); void LL_ADC_StructInit(LL_ADC_InitTypeDef *ADC_InitStruct); diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_bus.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_bus.h index 10add40f1..32a9d8cb1 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_bus.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_bus.h @@ -85,11 +85,26 @@ extern "C" { * @{ */ #define LL_APB1_GRP1_PERIPH_ALL 0xFFFFFFFFU +#if defined(TIM2) +#define LL_APB1_GRP1_PERIPH_TIM2 RCC_APBENR1_TIM2EN +#endif /* TIM2 */ #define LL_APB1_GRP1_PERIPH_TIM3 RCC_APBENR1_TIM3EN #define LL_APB1_GRP1_PERIPH_RTC RCC_APBENR1_RTCAPBEN #define LL_APB1_GRP1_PERIPH_WWDG RCC_APBENR1_WWDGEN +#if defined (USB_DRD_FS) +#define LL_APB1_GRP1_PERIPH_USB RCC_APBENR1_USBEN +#endif /* USB_DRD_FS */ +#if defined(SPI2) +#define LL_APB1_GRP1_PERIPH_SPI2 RCC_APBENR1_SPI2EN +#endif /* SPI2 */ +#if defined(CRS) +#define LL_APB1_GRP1_PERIPH_CRS RCC_APBENR1_CRSEN +#endif /* CRS */ #define LL_APB1_GRP1_PERIPH_USART2 RCC_APBENR1_USART2EN #define LL_APB1_GRP1_PERIPH_I2C1 RCC_APBENR1_I2C1EN +#if defined(I2C2) +#define LL_APB1_GRP1_PERIPH_I2C2 RCC_APBENR1_I2C2EN +#endif /* I2C2 */ #define LL_APB1_GRP1_PERIPH_DBGMCU RCC_APBENR1_DBGEN #define LL_APB1_GRP1_PERIPH_PWR RCC_APBENR1_PWREN @@ -97,18 +112,28 @@ extern "C" { * @} */ -/** @defgroup BUS_LL_EC_APB2_GRP1_PERIPH APB2 GRP1 PERIPH +/** @defgroup BUS_LL_EC_APB1_GRP2_PERIPH APB1 GRP2 PERIPH * @{ */ -#define LL_APB2_GRP1_PERIPH_ALL 0xFFFFFFFFU -#define LL_APB2_GRP1_PERIPH_SYSCFG RCC_APBENR2_SYSCFGEN -#define LL_APB2_GRP1_PERIPH_TIM1 RCC_APBENR2_TIM1EN -#define LL_APB2_GRP1_PERIPH_SPI1 RCC_APBENR2_SPI1EN -#define LL_APB2_GRP1_PERIPH_USART1 RCC_APBENR2_USART1EN -#define LL_APB2_GRP1_PERIPH_TIM14 RCC_APBENR2_TIM14EN -#define LL_APB2_GRP1_PERIPH_TIM16 RCC_APBENR2_TIM16EN -#define LL_APB2_GRP1_PERIPH_TIM17 RCC_APBENR2_TIM17EN -#define LL_APB2_GRP1_PERIPH_ADC RCC_APBENR2_ADCEN +#define LL_APB1_GRP2_PERIPH_ALL 0xFFFFFFFFU +#define LL_APB1_GRP2_PERIPH_SYSCFG RCC_APBENR2_SYSCFGEN +#define LL_APB1_GRP2_PERIPH_TIM1 RCC_APBENR2_TIM1EN +#define LL_APB1_GRP2_PERIPH_SPI1 RCC_APBENR2_SPI1EN +#define LL_APB1_GRP2_PERIPH_USART1 RCC_APBENR2_USART1EN +#define LL_APB1_GRP2_PERIPH_TIM14 RCC_APBENR2_TIM14EN +#define LL_APB1_GRP2_PERIPH_TIM16 RCC_APBENR2_TIM16EN +#define LL_APB1_GRP2_PERIPH_TIM17 RCC_APBENR2_TIM17EN +#define LL_APB1_GRP2_PERIPH_ADC RCC_APBENR2_ADCEN +/* defines for legacy purpose */ +#define LL_APB2_GRP2_PERIPH_ALL LL_APB1_GRP2_PERIPH_ALL +#define LL_APB2_GRP1_PERIPH_SYSCFG LL_APB1_GRP2_PERIPH_SYSCFG +#define LL_APB2_GRP1_PERIPH_TIM1 LL_APB1_GRP2_PERIPH_TIM1 +#define LL_APB2_GRP1_PERIPH_SPI1 LL_APB1_GRP2_PERIPH_SPI1 +#define LL_APB2_GRP1_PERIPH_USART1 LL_APB1_GRP2_PERIPH_USART1 +#define LL_APB2_GRP1_PERIPH_TIM14 LL_APB1_GRP2_PERIPH_TIM14 +#define LL_APB2_GRP1_PERIPH_TIM16 LL_APB1_GRP2_PERIPH_TIM16 +#define LL_APB2_GRP1_PERIPH_TIM17 LL_APB1_GRP2_PERIPH_TIM17 +#define LL_APB2_GRP1_PERIPH_ADC LL_APB1_GRP2_PERIPH_ADC /** * @} @@ -121,9 +146,9 @@ extern "C" { #define LL_IOP_GRP1_PERIPH_GPIOA RCC_IOPENR_GPIOAEN #define LL_IOP_GRP1_PERIPH_GPIOB RCC_IOPENR_GPIOBEN #define LL_IOP_GRP1_PERIPH_GPIOC RCC_IOPENR_GPIOCEN -#if defined(STM32C031xx) +#if defined(GPIOD) #define LL_IOP_GRP1_PERIPH_GPIOD RCC_IOPENR_GPIODEN -#endif +#endif /* GPIOD */ #define LL_IOP_GRP1_PERIPH_GPIOF RCC_IOPENR_GPIOFEN /** @@ -148,7 +173,7 @@ extern "C" { * @brief Enable AHB1 peripherals clock. * @rmtoll AHBENR DMA1EN LL_AHB1_GRP1_EnableClock\n * AHBENR FLASHEN LL_AHB1_GRP1_EnableClock\n - * AHBENR CRCEN LL_AHB1_GRP1_EnableClock\n + * AHBENR CRCEN LL_AHB1_GRP1_EnableClock * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 * @arg @ref LL_AHB1_GRP1_PERIPH_FLASH @@ -168,7 +193,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_EnableClock(uint32_t Periphs) * @brief Check if AHB1 peripheral clock is enabled or not * @rmtoll AHBENR DMA1EN LL_AHB1_GRP1_IsEnabledClock\n * AHBENR FLASHEN LL_AHB1_GRP1_IsEnabledClock\n - * AHBENR CRCEN LL_AHB1_GRP1_IsEnabledClock\n + * AHBENR CRCEN LL_AHB1_GRP1_IsEnabledClock * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 * @arg @ref LL_AHB1_GRP1_PERIPH_FLASH @@ -184,7 +209,7 @@ __STATIC_INLINE uint32_t LL_AHB1_GRP1_IsEnabledClock(uint32_t Periphs) * @brief Disable AHB1 peripherals clock. * @rmtoll AHBENR DMA1EN LL_AHB1_GRP1_DisableClock\n * AHBENR FLASHEN LL_AHB1_GRP1_DisableClock\n - * AHBENR CRCEN LL_AHB1_GRP1_DisableClock\n + * AHBENR CRCEN LL_AHB1_GRP1_DisableClock * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 * @arg @ref LL_AHB1_GRP1_PERIPH_FLASH @@ -200,7 +225,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_DisableClock(uint32_t Periphs) * @brief Force AHB1 peripherals reset. * @rmtoll AHBRSTR DMA1RST LL_AHB1_GRP1_ForceReset\n * AHBRSTR FLASHRST LL_AHB1_GRP1_ForceReset\n - * AHBRSTR CRCRST LL_AHB1_GRP1_ForceReset\n + * AHBRSTR CRCRST LL_AHB1_GRP1_ForceReset * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_ALL * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 @@ -217,7 +242,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_ForceReset(uint32_t Periphs) * @brief Release AHB1 peripherals reset. * @rmtoll AHBRSTR DMA1RST LL_AHB1_GRP1_ReleaseReset\n * AHBRSTR FLASHRST LL_AHB1_GRP1_ReleaseReset\n - * AHBRSTR CRCRST LL_AHB1_GRP1_ReleaseReset\n + * AHBRSTR CRCRST LL_AHB1_GRP1_ReleaseReset * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_ALL * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 @@ -235,7 +260,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_ReleaseReset(uint32_t Periphs) * @rmtoll AHBSMENR DMA1SMEN LL_AHB1_GRP1_EnableClockStopSleep\n * AHBSMENR FLASHSMEN LL_AHB1_GRP1_EnableClockStopSleep\n * AHBSMENR SRAMSMEN LL_AHB1_GRP1_EnableClockStopSleep\n - * AHBSMENR CRCSMEN LL_AHB1_GRP1_EnableClockStopSleep\n + * AHBSMENR CRCSMEN LL_AHB1_GRP1_EnableClockStopSleep * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 * @arg @ref LL_AHB1_GRP1_PERIPH_FLASH @@ -257,7 +282,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_EnableClockStopSleep(uint32_t Periphs) * @rmtoll AHBSMENR DMA1SMEN LL_AHB1_GRP1_DisableClockStopSleep\n * AHBSMENR FLASHSMEN LL_AHB1_GRP1_DisableClockStopSleep\n * AHBSMENR SRAMSMEN LL_AHB1_GRP1_DisableClockStopSleep\n - * AHBSMENR CRCSMEN LL_AHB1_GRP1_DisableClockStopSleep\n + * AHBSMENR CRCSMEN LL_AHB1_GRP1_DisableClockStopSleep * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_AHB1_GRP1_PERIPH_DMA1 * @arg @ref LL_AHB1_GRP1_PERIPH_FLASH @@ -274,7 +299,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_DisableClockStopSleep(uint32_t Periphs) * @} */ -/** @defgroup BUS_LL_EF_APB1 APB1 +/** @defgroup BUS_LL_EF_APB1_GRP1 APB1_GRP1 * @{ */ @@ -286,6 +311,10 @@ __STATIC_INLINE void LL_AHB1_GRP1_DisableClockStopSleep(uint32_t Periphs) * APBENR1 I2C1EN LL_APB1_GRP1_EnableClock\n * APBENR1 DBGEN LL_APB1_GRP1_EnableClock\n * APBENR1 PWREN LL_APB1_GRP1_EnableClock\n + * APBENR1 TIM2EN LL_APB1_GRP1_EnableClock\n (*) + * APBENR1 SPI2EN LL_APB1_GRP1_EnableClock\n (*) + * APBENR1 I2C2EN LL_APB1_GRP1_EnableClock\n (*) + * APBENR1 USBEN LL_APB1_GRP1_EnableClock\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 * @arg @ref LL_APB1_GRP1_PERIPH_RTC @@ -293,6 +322,11 @@ __STATIC_INLINE void LL_AHB1_GRP1_DisableClockStopSleep(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_APB1_GRP1_EnableClock(uint32_t Periphs) @@ -305,14 +339,18 @@ __STATIC_INLINE void LL_APB1_GRP1_EnableClock(uint32_t Periphs) } /** - * @brief Check if APB1 peripheral clock is enabled or not + * @brief Check if APB1 GRP1 peripheral clock is enabled or not * @rmtoll APBENR1 TIM3EN LL_APB1_GRP1_IsEnabledClock\n * APBENR1 RTCAPBEN LL_APB1_GRP1_IsEnabledClock\n * APBENR1 WWDGEN LL_APB1_GRP1_IsEnabledClock\n - * APBENR1 USART2EN LL_APB1_GRP1_IsEnabledClock\n + * APBENR1 USART2EN LL_APB1_GRP1_IsEnabledClock\n * APBENR1 I2C1EN LL_APB1_GRP1_IsEnabledClock\n * APBENR1 DBGEN LL_APB1_GRP1_IsEnabledClock\n * APBENR1 PWREN LL_APB1_GRP1_IsEnabledClock\n + * APBENR1 TIM2EN LL_APB1_GRP1_IsEnabledClock\n (*) + * APBENR1 SPI2EN LL_APB1_GRP1_IsEnabledClock\n (*) + * APBENR1 I2C2EN LL_APB1_GRP1_IsEnabledClock\n (*) + * APBENR1 USBEN LL_APB1_GRP1_IsEnabledClock\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 * @arg @ref LL_APB1_GRP1_PERIPH_RTC @@ -321,6 +359,11 @@ __STATIC_INLINE void LL_APB1_GRP1_EnableClock(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval State of Periphs (1 or 0). */ __STATIC_INLINE uint32_t LL_APB1_GRP1_IsEnabledClock(uint32_t Periphs) @@ -329,14 +372,18 @@ __STATIC_INLINE uint32_t LL_APB1_GRP1_IsEnabledClock(uint32_t Periphs) } /** - * @brief Disable APB1 peripherals clock. + * @brief Disable APB1 GRP1 peripherals clock. * @rmtoll APBENR1 TIM3EN LL_APB1_GRP1_DisableClock\n * APBENR1 RTCAPBEN LL_APB1_GRP1_DisableClock\n * APBENR1 WWDGEN LL_APB1_GRP1_DisableClock\n - * APBENR1 USART2EN LL_APB1_GRP1_IsEnabledClock\n + * APBENR1 USART2EN LL_APB1_GRP1_DisableClock\n * APBENR1 I2C1EN LL_APB1_GRP1_DisableClock\n * APBENR1 DBGEN LL_APB1_GRP1_DisableClock\n * APBENR1 PWREN LL_APB1_GRP1_DisableClock\n + * APBENR1 TIM2EN LL_APB1_GRP1_DisableClock\n (*) + * APBENR1 SPI2EN LL_APB1_GRP1_DisableClock\n (*) + * APBENR1 I2C2EN LL_APB1_GRP1_DisableClock\n (*) + * APBENR1 USBEN LL_APB1_GRP1_DisableClock\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 * @arg @ref LL_APB1_GRP1_PERIPH_RTC @@ -345,6 +392,11 @@ __STATIC_INLINE uint32_t LL_APB1_GRP1_IsEnabledClock(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_APB1_GRP1_DisableClock(uint32_t Periphs) @@ -353,13 +405,17 @@ __STATIC_INLINE void LL_APB1_GRP1_DisableClock(uint32_t Periphs) } /** - * @brief Force APB1 peripherals reset. + * @brief Force APB1 GRP1 peripherals reset. * @rmtoll APBRSTR1 TIM3RST LL_APB1_GRP1_ForceReset\n * APBRSTR1 RTCRST LL_APB1_GRP1_ForceReset\n * APBRSTR1 WWDGRST LL_APB1_GRP1_ForceReset\n * APBRSTR1 I2C1RST LL_APB1_GRP1_ForceReset\n * APBRSTR1 DBGRST LL_APB1_GRP1_ForceReset\n * APBRSTR1 PWRRST LL_APB1_GRP1_ForceReset\n + * APBRSTR1 TIM2RST LL_APB1_GRP1_ForceReset\n (*) + * APBRSTR1 SPI2RST LL_APB1_GRP1_ForceReset\n (*) + * APBRSTR1 I2C2RST LL_APB1_GRP1_ForceReset\n (*) + * APBRSTR1 USBRST LL_APB1_GRP1_ForceReset\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_ALL * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 @@ -368,6 +424,11 @@ __STATIC_INLINE void LL_APB1_GRP1_DisableClock(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_APB1_GRP1_ForceReset(uint32_t Periphs) @@ -376,13 +437,17 @@ __STATIC_INLINE void LL_APB1_GRP1_ForceReset(uint32_t Periphs) } /** - * @brief Release APB1 peripherals reset. + * @brief Release APB1 GRP1 peripherals reset. * @rmtoll APBRSTR1 TIM3RST LL_APB1_GRP1_ReleaseReset\n * APBRSTR1 RTCRST LL_APB1_GRP1_ReleaseReset\n * APBRSTR1 WWDGRST LL_APB1_GRP1_ReleaseReset\n * APBRSTR1 I2C1RST LL_APB1_GRP1_ReleaseReset\n * APBRSTR1 DBGRST LL_APB1_GRP1_ReleaseReset\n * APBRSTR1 PWRRST LL_APB1_GRP1_ReleaseReset\n + * APBRSTR1 TIM2RST LL_APB1_GRP1_ReleaseReset\n (*) + * APBRSTR1 SPI2RST LL_APB1_GRP1_ReleaseReset\n (*) + * APBRSTR1 I2C2RST LL_APB1_GRP1_ReleaseReset\n (*) + * APBRSTR1 USBRST LL_APB1_GRP1_ReleaseReset\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_ALL * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 @@ -391,6 +456,11 @@ __STATIC_INLINE void LL_APB1_GRP1_ForceReset(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_APB1_GRP1_ReleaseReset(uint32_t Periphs) @@ -399,13 +469,17 @@ __STATIC_INLINE void LL_APB1_GRP1_ReleaseReset(uint32_t Periphs) } /** - * @brief Enable APB1 peripheral clocks in Sleep and Stop modes + * @brief Enable APB1 GRP1 peripheral clocks in Sleep and Stop modes * @rmtoll APBSMENR1 TIM3SMEN LL_APB1_GRP1_EnableClockStopSleep\n * APBSMENR1 RTCAPBSMEN LL_APB1_GRP1_EnableClockStopSleep\n * APBSMENR1 WWDGSMEN LL_APB1_GRP1_EnableClockStopSleep\n * APBSMENR1 I2C1SMEN LL_APB1_GRP1_EnableClockStopSleep\n * APBSMENR1 DBGSMEN LL_APB1_GRP1_EnableClockStopSleep\n * APBSMENR1 PWRSMEN LL_APB1_GRP1_EnableClockStopSleep\n + * APBSMENR1 TIM2SMEN LL_APB1_GRP1_EnableClockStopSleep\n (*) + * APBSMENR1 SPI2SMEN LL_APB1_GRP1_EnableClockStopSleep\n (*) + * APBSMENR1 I2C2SMEN LL_APB1_GRP1_EnableClockStopSleep\n (*) + * APBSMENR1 USBSMEN LL_APB1_GRP1_EnableClockStopSleep\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 * @arg @ref LL_APB1_GRP1_PERIPH_RTC @@ -413,6 +487,11 @@ __STATIC_INLINE void LL_APB1_GRP1_ReleaseReset(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_APB1_GRP1_EnableClockStopSleep(uint32_t Periphs) @@ -425,13 +504,17 @@ __STATIC_INLINE void LL_APB1_GRP1_EnableClockStopSleep(uint32_t Periphs) } /** - * @brief Disable APB1 peripheral clocks in Sleep and Stop modes + * @brief Disable APB1 GRP1 peripheral clocks in Sleep and Stop modes * @rmtoll APBSMENR1 TIM3SMEN LL_APB1_GRP1_DisableClockStopSleep\n * APBSMENR1 RTCAPBSMEN LL_APB1_GRP1_DisableClockStopSleep\n * APBSMENR1 WWDGSMEN LL_APB1_GRP1_DisableClockStopSleep\n * APBSMENR1 I2C1SMEN LL_APB1_GRP1_DisableClockStopSleep\n * APBSMENR1 DBGSMEN LL_APB1_GRP1_DisableClockStopSleep\n * APBSMENR1 PWRSMEN LL_APB1_GRP1_DisableClockStopSleep\n + * APBSMENR1 TIM2SMEN LL_APB1_GRP1_DisableClockStopSleep\n (*) + * APBSMENR1 SPI2SMEN LL_APB1_GRP1_DisableClockStopSleep\n (*) + * APBSMENR1 I2C2SMEN LL_APB1_GRP1_DisableClockStopSleep\n (*) + * APBSMENR1 USBSMEN LL_APB1_GRP1_DisableClockStopSleep\n (*) * @param Periphs This parameter can be a combination of the following values: * @arg @ref LL_APB1_GRP1_PERIPH_TIM3 * @arg @ref LL_APB1_GRP1_PERIPH_RTC @@ -439,6 +522,11 @@ __STATIC_INLINE void LL_APB1_GRP1_EnableClockStopSleep(uint32_t Periphs) * @arg @ref LL_APB1_GRP1_PERIPH_I2C1 * @arg @ref LL_APB1_GRP1_PERIPH_DBGMCU * @arg @ref LL_APB1_GRP1_PERIPH_PWR + * @arg @ref LL_APB1_GRP1_PERIPH_TIM2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_SPI2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_I2C2 (*) + * @arg @ref LL_APB1_GRP1_PERIPH_USB (*) + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_APB1_GRP1_DisableClockStopSleep(uint32_t Periphs) @@ -450,32 +538,32 @@ __STATIC_INLINE void LL_APB1_GRP1_DisableClockStopSleep(uint32_t Periphs) * @} */ -/** @defgroup BUS_LL_EF_APB2 APB2 +/** @defgroup BUS_LL_EF_APB1_GRP2 APB1_GRP2 * @{ */ /** - * @brief Enable APB2 peripherals clock. - * @rmtoll APBENR2 SYSCFGEN LL_APB2_GRP1_EnableClock\n - * APBENR2 TIM1EN LL_APB2_GRP1_EnableClock\n - * APBENR2 SPI1EN LL_APB2_GRP1_EnableClock\n - * APBENR2 USART1EN LL_APB2_GRP1_EnableClock\n - * APBENR2 TIM14EN LL_APB2_GRP1_EnableClock\n - * APBENR2 TIM16EN LL_APB2_GRP1_EnableClock\n - * APBENR2 TIM17EN LL_APB2_GRP1_EnableClock\n - * APBENR2 ADCEN LL_APB2_GRP1_EnableClock + * @brief Enable APB1 GRP2 peripherals clock. + * @rmtoll APBENR2 SYSCFGEN LL_APB1_GRP2_EnableClock\n + * APBENR2 TIM1EN LL_APB1_GRP2_EnableClock\n + * APBENR2 SPI1EN LL_APB1_GRP2_EnableClock\n + * APBENR2 USART1EN LL_APB1_GRP2_EnableClock\n + * APBENR2 TIM14EN LL_APB1_GRP2_EnableClock\n + * APBENR2 TIM16EN LL_APB1_GRP2_EnableClock\n + * APBENR2 TIM17EN LL_APB1_GRP2_EnableClock\n + * APBENR2 ADCEN LL_APB1_GRP2_EnableClock * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval None */ -__STATIC_INLINE void LL_APB2_GRP1_EnableClock(uint32_t Periphs) +__STATIC_INLINE void LL_APB1_GRP2_EnableClock(uint32_t Periphs) { __IO uint32_t tmpreg; SET_BIT(RCC->APBENR2, Periphs); @@ -483,135 +571,140 @@ __STATIC_INLINE void LL_APB2_GRP1_EnableClock(uint32_t Periphs) tmpreg = READ_BIT(RCC->APBENR2, Periphs); (void)tmpreg; } - -/** - * @brief Check if APB2 peripheral clock is enabled or not - * @rmtoll APBENR2 SYSCFGEN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 TIM1EN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 SPI1EN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 USART1EN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 TIM14EN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 TIM16EN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 TIM17EN LL_APB2_GRP1_IsEnabledClock\n - * APBENR2 ADCEN LL_APB2_GRP1_IsEnabledClock +#define LL_APB2_GRP1_EnableClock LL_APB1_GRP2_EnableClock + +/** + * @brief Check if APB1 GRP2 peripheral clock is enabled or not + * @rmtoll APBENR2 SYSCFGEN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 TIM1EN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 SPI1EN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 USART1EN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 TIM14EN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 TIM16EN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 TIM17EN LL_APB1_GRP2_IsEnabledClock\n + * APBENR2 ADCEN LL_APB1_GRP2_IsEnabledClock * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval State of Periphs (1 or 0). */ -__STATIC_INLINE uint32_t LL_APB2_GRP1_IsEnabledClock(uint32_t Periphs) +__STATIC_INLINE uint32_t LL_APB1_GRP2_IsEnabledClock(uint32_t Periphs) { return ((READ_BIT(RCC->APBENR2, Periphs) == (Periphs)) ? 1UL : 0UL); } - -/** - * @brief Disable APB2 peripherals clock. - * @rmtoll APBENR2 SYSCFGEN LL_APB2_GRP1_DisableClock\n - * APBENR2 TIM1EN LL_APB2_GRP1_DisableClock\n - * APBENR2 SPI1EN LL_APB2_GRP1_DisableClock\n - * APBENR2 USART1EN LL_APB2_GRP1_DisableClock\n - * APBENR2 TIM14EN LL_APB2_GRP1_DisableClock\n - * APBENR2 TIM16EN LL_APB2_GRP1_DisableClock\n - * APBENR2 TIM17EN LL_APB2_GRP1_DisableClock\n - * APBENR2 ADCEN LL_APB2_GRP1_DisableClock +#define LL_APB2_GRP1_IsEnabledClock LL_APB1_GRP2_IsEnabledClock + +/** + * @brief Disable APB1 GRP2 peripherals clock. + * @rmtoll APBENR2 SYSCFGEN LL_APB1_GRP2_DisableClock\n + * APBENR2 TIM1EN LL_APB1_GRP2_DisableClock\n + * APBENR2 SPI1EN LL_APB1_GRP2_DisableClock\n + * APBENR2 USART1EN LL_APB1_GRP2_DisableClock\n + * APBENR2 TIM14EN LL_APB1_GRP2_DisableClock\n + * APBENR2 TIM16EN LL_APB1_GRP2_DisableClock\n + * APBENR2 TIM17EN LL_APB1_GRP2_DisableClock\n + * APBENR2 ADCEN LL_APB1_GRP2_DisableClock * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval None */ -__STATIC_INLINE void LL_APB2_GRP1_DisableClock(uint32_t Periphs) +__STATIC_INLINE void LL_APB1_GRP2_DisableClock(uint32_t Periphs) { CLEAR_BIT(RCC->APBENR2, Periphs); } - -/** - * @brief Force APB2 peripherals reset. - * @rmtoll APBRSTR2 SYSCFGRST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 TIM1RST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 SPI1RST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 USART1RST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 TIM14RST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 TIM16RST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 TIM17RST LL_APB2_GRP1_ForceReset\n - * APBRSTR2 ADCRST LL_APB2_GRP1_ForceReset +#define LL_APB2_GRP1_DisableClock LL_APB1_GRP2_DisableClock + +/** + * @brief Force APB1 GRP2 peripherals reset. + * @rmtoll APBRSTR2 SYSCFGRST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 TIM1RST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 SPI1RST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 USART1RST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 TIM14RST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 TIM16RST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 TIM17RST LL_APB1_GRP2_ForceReset\n + * APBRSTR2 ADCRST LL_APB1_GRP2_ForceReset * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_ALL - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_ALL + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval None */ -__STATIC_INLINE void LL_APB2_GRP1_ForceReset(uint32_t Periphs) +__STATIC_INLINE void LL_APB1_GRP2_ForceReset(uint32_t Periphs) { SET_BIT(RCC->APBRSTR2, Periphs); } - -/** - * @brief Release APB2 peripherals reset. - * @rmtoll APBRSTR2 SYSCFGRST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 TIM1RST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 SPI1RST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 USART1RST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 TIM14RST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 TIM16RST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 TIM17RST LL_APB2_GRP1_ReleaseReset\n - * APBRSTR2 ADCRST LL_APB2_GRP1_ReleaseReset +#define LL_APB2_GRP1_ForceReset LL_APB1_GRP2_ForceReset + +/** + * @brief Release APB1 GRP2 peripherals reset. + * @rmtoll APBRSTR2 SYSCFGRST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 TIM1RST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 SPI1RST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 USART1RST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 TIM14RST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 TIM16RST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 TIM17RST LL_APB1_GRP2_ReleaseReset\n + * APBRSTR2 ADCRST LL_APB1_GRP2_ReleaseReset * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_ALL - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_ALL + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval None */ -__STATIC_INLINE void LL_APB2_GRP1_ReleaseReset(uint32_t Periphs) +__STATIC_INLINE void LL_APB1_GRP2_ReleaseReset(uint32_t Periphs) { CLEAR_BIT(RCC->APBRSTR2, Periphs); } - -/** - * @brief Enable APB2 peripheral clocks in Sleep and Stop modes - * @rmtoll APBSMENR2 SYSCFGSMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 TIM1SMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 SPI1SMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 USART1SMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 TIM14SMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 TIM16SMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 TIM17SMEN LL_APB2_GRP1_EnableClockStopSleep\n - * APBSMENR2 ADCSMEN LL_APB2_GRP1_EnableClockStopSleep +#define LL_APB2_GRP1_ReleaseReset LL_APB1_GRP2_ReleaseReset + +/** + * @brief Enable APB1 GRP2 peripheral clocks in Sleep and Stop modes + * @rmtoll APBSMENR2 SYSCFGSMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 TIM1SMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 SPI1SMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 USART1SMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 TIM14SMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 TIM16SMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 TIM17SMEN LL_APB1_GRP2_EnableClockStopSleep\n + * APBSMENR2 ADCSMEN LL_APB1_GRP2_EnableClockStopSleep * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval None */ -__STATIC_INLINE void LL_APB2_GRP1_EnableClockStopSleep(uint32_t Periphs) +__STATIC_INLINE void LL_APB1_GRP2_EnableClockStopSleep(uint32_t Periphs) { __IO uint32_t tmpreg; SET_BIT(RCC->APBSMENR2, Periphs); @@ -619,32 +712,34 @@ __STATIC_INLINE void LL_APB2_GRP1_EnableClockStopSleep(uint32_t Periphs) tmpreg = READ_BIT(RCC->APBSMENR2, Periphs); (void)tmpreg; } - -/** - * @brief Disable APB2 peripheral clocks in Sleep and Stop modes - * @rmtoll APBSMENR2 SYSCFGSMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 TIM1SMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 SPI1SMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 USART1SMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 TIM14SMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 TIM16SMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 TIM17SMEN LL_APB2_GRP1_DisableClockStopSleep\n - * APBSMENR2 ADCSMEN LL_APB2_GRP1_DisableClockStopSleep +#define LL_APB2_GRP1_EnableClockStopSleep LL_APB1_GRP2_EnableClockStopSleep + +/** + * @brief Disable APB1 GRP2 peripheral clocks in Sleep and Stop modes + * @rmtoll APBSMENR2 SYSCFGSMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 TIM1SMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 SPI1SMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 USART1SMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 TIM14SMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 TIM16SMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 TIM17SMEN LL_APB1_GRP2_DisableClockStopSleep\n + * APBSMENR2 ADCSMEN LL_APB1_GRP2_DisableClockStopSleep * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_APB2_GRP1_PERIPH_SYSCFG - * @arg @ref LL_APB2_GRP1_PERIPH_TIM1 - * @arg @ref LL_APB2_GRP1_PERIPH_SPI1 - * @arg @ref LL_APB2_GRP1_PERIPH_USART1 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM14 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM16 - * @arg @ref LL_APB2_GRP1_PERIPH_TIM17 - * @arg @ref LL_APB2_GRP1_PERIPH_ADC + * @arg @ref LL_APB1_GRP2_PERIPH_SYSCFG + * @arg @ref LL_APB1_GRP2_PERIPH_TIM1 + * @arg @ref LL_APB1_GRP2_PERIPH_SPI1 + * @arg @ref LL_APB1_GRP2_PERIPH_USART1 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM14 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM16 + * @arg @ref LL_APB1_GRP2_PERIPH_TIM17 + * @arg @ref LL_APB1_GRP2_PERIPH_ADC * @retval None */ -__STATIC_INLINE void LL_APB2_GRP1_DisableClockStopSleep(uint32_t Periphs) +__STATIC_INLINE void LL_APB1_GRP2_DisableClockStopSleep(uint32_t Periphs) { CLEAR_BIT(RCC->APBSMENR2, Periphs); } +#define LL_APB2_GRP1_DisableClockStopSleep LL_APB1_GRP2_DisableClockStopSleep /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crc.h index 6664982b6..2da3d8d9e 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crc.h @@ -184,7 +184,7 @@ __STATIC_INLINE void LL_CRC_SetPolynomialSize(CRC_TypeDef *CRCx, uint32_t PolySi * @arg @ref LL_CRC_POLYLENGTH_8B * @arg @ref LL_CRC_POLYLENGTH_7B */ -__STATIC_INLINE uint32_t LL_CRC_GetPolynomialSize(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_GetPolynomialSize(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_BIT(CRCx->CR, CRC_CR_POLYSIZE)); } @@ -215,7 +215,7 @@ __STATIC_INLINE void LL_CRC_SetInputDataReverseMode(CRC_TypeDef *CRCx, uint32_t * @arg @ref LL_CRC_INDATA_REVERSE_HALFWORD * @arg @ref LL_CRC_INDATA_REVERSE_WORD */ -__STATIC_INLINE uint32_t LL_CRC_GetInputDataReverseMode(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_GetInputDataReverseMode(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_BIT(CRCx->CR, CRC_CR_REV_IN)); } @@ -242,7 +242,7 @@ __STATIC_INLINE void LL_CRC_SetOutputDataReverseMode(CRC_TypeDef *CRCx, uint32_t * @arg @ref LL_CRC_OUTDATA_REVERSE_NONE * @arg @ref LL_CRC_OUTDATA_REVERSE_BIT */ -__STATIC_INLINE uint32_t LL_CRC_GetOutputDataReverseMode(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_GetOutputDataReverseMode(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_BIT(CRCx->CR, CRC_CR_REV_OUT)); } @@ -270,7 +270,7 @@ __STATIC_INLINE void LL_CRC_SetInitialData(CRC_TypeDef *CRCx, uint32_t InitCrc) * @param CRCx CRC Instance * @retval Value programmed in Programmable initial CRC value register */ -__STATIC_INLINE uint32_t LL_CRC_GetInitialData(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_GetInitialData(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_REG(CRCx->INIT)); } @@ -301,7 +301,7 @@ __STATIC_INLINE void LL_CRC_SetPolynomialCoef(CRC_TypeDef *CRCx, uint32_t Polyno * @param CRCx CRC Instance * @retval Value programmed in Programmable Polynomial value register */ -__STATIC_INLINE uint32_t LL_CRC_GetPolynomialCoef(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_GetPolynomialCoef(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_REG(CRCx->POL)); } @@ -359,7 +359,7 @@ __STATIC_INLINE void LL_CRC_FeedData8(CRC_TypeDef *CRCx, uint8_t InData) * @param CRCx CRC Instance * @retval Current CRC calculation result as stored in CRC_DR register (32 bits). */ -__STATIC_INLINE uint32_t LL_CRC_ReadData32(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_ReadData32(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_REG(CRCx->DR)); } @@ -371,7 +371,7 @@ __STATIC_INLINE uint32_t LL_CRC_ReadData32(CRC_TypeDef *CRCx) * @param CRCx CRC Instance * @retval Current CRC calculation result as stored in CRC_DR register (16 bits). */ -__STATIC_INLINE uint16_t LL_CRC_ReadData16(CRC_TypeDef *CRCx) +__STATIC_INLINE uint16_t LL_CRC_ReadData16(const CRC_TypeDef *CRCx) { return (uint16_t)READ_REG(CRCx->DR); } @@ -383,7 +383,7 @@ __STATIC_INLINE uint16_t LL_CRC_ReadData16(CRC_TypeDef *CRCx) * @param CRCx CRC Instance * @retval Current CRC calculation result as stored in CRC_DR register (8 bits). */ -__STATIC_INLINE uint8_t LL_CRC_ReadData8(CRC_TypeDef *CRCx) +__STATIC_INLINE uint8_t LL_CRC_ReadData8(const CRC_TypeDef *CRCx) { return (uint8_t)READ_REG(CRCx->DR); } @@ -395,7 +395,7 @@ __STATIC_INLINE uint8_t LL_CRC_ReadData8(CRC_TypeDef *CRCx) * @param CRCx CRC Instance * @retval Current CRC calculation result as stored in CRC_DR register (7 bits). */ -__STATIC_INLINE uint8_t LL_CRC_ReadData7(CRC_TypeDef *CRCx) +__STATIC_INLINE uint8_t LL_CRC_ReadData7(const CRC_TypeDef *CRCx) { return (uint8_t)(READ_REG(CRCx->DR) & 0x7FU); } @@ -407,7 +407,7 @@ __STATIC_INLINE uint8_t LL_CRC_ReadData7(CRC_TypeDef *CRCx) * @param CRCx CRC Instance * @retval Value stored in CRC_IDR register (General-purpose 32-bit data register). */ -__STATIC_INLINE uint32_t LL_CRC_Read_IDR(CRC_TypeDef *CRCx) +__STATIC_INLINE uint32_t LL_CRC_Read_IDR(const CRC_TypeDef *CRCx) { return (uint32_t)(READ_REG(CRCx->IDR)); } @@ -433,7 +433,7 @@ __STATIC_INLINE void LL_CRC_Write_IDR(CRC_TypeDef *CRCx, uint32_t InData) * @{ */ -ErrorStatus LL_CRC_DeInit(CRC_TypeDef *CRCx); +ErrorStatus LL_CRC_DeInit(const CRC_TypeDef *CRCx); /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crs.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crs.h new file mode 100644 index 000000000..c20681e0e --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_crs.h @@ -0,0 +1,810 @@ +/** + ****************************************************************************** + * @file stm32c0xx_ll_crs.h + * @author MCD Application Team + * @brief Header file of CRS LL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32C0xx_LL_CRS_H +#define STM32C0xx_LL_CRS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx.h" + +/** @addtogroup STM32C0xx_LL_Driver + * @{ + */ + +#if defined(CRS) + +/** @defgroup CRS_LL CRS + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup CRS_LL_Private_Constants CRS Private Constants + * @{ + */ + + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CRS_LL_Exported_Constants CRS Exported Constants + * @{ + */ + +/** @defgroup CRS_LL_EC_GET_FLAG Get Flags Defines + * @brief Flags defines which can be used with LL_CRS_ReadReg function + * @{ + */ +#define LL_CRS_ISR_SYNCOKF CRS_ISR_SYNCOKF +#define LL_CRS_ISR_SYNCWARNF CRS_ISR_SYNCWARNF +#define LL_CRS_ISR_ERRF CRS_ISR_ERRF +#define LL_CRS_ISR_ESYNCF CRS_ISR_ESYNCF +#define LL_CRS_ISR_SYNCERR CRS_ISR_SYNCERR +#define LL_CRS_ISR_SYNCMISS CRS_ISR_SYNCMISS +#define LL_CRS_ISR_TRIMOVF CRS_ISR_TRIMOVF +/** + * @} + */ + +/** @defgroup CRS_LL_EC_IT IT Defines + * @brief IT defines which can be used with LL_CRS_ReadReg and LL_CRS_WriteReg functions + * @{ + */ +#define LL_CRS_CR_SYNCOKIE CRS_CR_SYNCOKIE +#define LL_CRS_CR_SYNCWARNIE CRS_CR_SYNCWARNIE +#define LL_CRS_CR_ERRIE CRS_CR_ERRIE +#define LL_CRS_CR_ESYNCIE CRS_CR_ESYNCIE +/** + * @} + */ + +/** @defgroup CRS_LL_EC_SYNC_DIV Synchronization Signal Divider + * @{ + */ +#define LL_CRS_SYNC_DIV_1 ((uint32_t)0x00U) /*!< Synchro Signal not divided (default) */ +#define LL_CRS_SYNC_DIV_2 CRS_CFGR_SYNCDIV_0 /*!< Synchro Signal divided by 2 */ +#define LL_CRS_SYNC_DIV_4 CRS_CFGR_SYNCDIV_1 /*!< Synchro Signal divided by 4 */ +#define LL_CRS_SYNC_DIV_8 (CRS_CFGR_SYNCDIV_1 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 8 */ +#define LL_CRS_SYNC_DIV_16 CRS_CFGR_SYNCDIV_2 /*!< Synchro Signal divided by 16 */ +#define LL_CRS_SYNC_DIV_32 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 32 */ +#define LL_CRS_SYNC_DIV_64 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_1) /*!< Synchro Signal divided by 64 */ +#define LL_CRS_SYNC_DIV_128 CRS_CFGR_SYNCDIV /*!< Synchro Signal divided by 128 */ +/** + * @} + */ + +/** @defgroup CRS_LL_EC_SYNC_SOURCE Synchronization Signal Source + * @{ + */ +#define LL_CRS_SYNC_SOURCE_GPIO ((uint32_t)0x00U) /*!< Synchro Signal source GPIO */ +#define LL_CRS_SYNC_SOURCE_LSE CRS_CFGR_SYNCSRC_0 /*!< Synchro Signal source LSE */ +#define LL_CRS_SYNC_SOURCE_USB CRS_CFGR_SYNCSRC_1 /*!< Synchro Signal source USB SOF (default)*/ +/** + * @} + */ + +/** @defgroup CRS_LL_EC_SYNC_POLARITY Synchronization Signal Polarity + * @{ + */ +#define LL_CRS_SYNC_POLARITY_RISING ((uint32_t)0x00U) /*!< Synchro Active on rising edge (default) */ +#define LL_CRS_SYNC_POLARITY_FALLING CRS_CFGR_SYNCPOL /*!< Synchro Active on falling edge */ +/** + * @} + */ + +/** @defgroup CRS_LL_EC_FREQERRORDIR Frequency Error Direction + * @{ + */ +#define LL_CRS_FREQ_ERROR_DIR_UP ((uint32_t)0x00U) /*!< Upcounting direction, the actual frequency is above the target */ +#define LL_CRS_FREQ_ERROR_DIR_DOWN ((uint32_t)CRS_ISR_FEDIR) /*!< Downcounting direction, the actual frequency is below the target */ +/** + * @} + */ + +/** @defgroup CRS_LL_EC_DEFAULTVALUES Default Values + * @{ + */ +/** + * @brief Reset value of the RELOAD field + * @note The reset value of the RELOAD field corresponds to a target frequency of 48 MHz + * and a synchronization signal frequency of 1 kHz (SOF signal from USB) + */ +#define LL_CRS_RELOADVALUE_DEFAULT ((uint32_t)0xBB7FU) + +/** + * @brief Reset value of Frequency error limit. + */ +#define LL_CRS_ERRORLIMIT_DEFAULT ((uint32_t)0x22U) + +/** + * @brief Reset value of the HSI48 Calibration field + * @note The default value is 64, which corresponds to the middle of the trimming interval. + * The trimming step is around 67 kHz between two consecutive TRIM steps. + * A higher TRIM value corresponds to a higher output frequency + */ +#define LL_CRS_HSI48CALIBRATION_DEFAULT ((uint32_t)0x40U) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup CRS_LL_Exported_Macros CRS Exported Macros + * @{ + */ + +/** @defgroup CRS_LL_EM_WRITE_READ Common Write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in CRS register + * @param __INSTANCE__ CRS Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define LL_CRS_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) + +/** + * @brief Read a value in CRS register + * @param __INSTANCE__ CRS Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define LL_CRS_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) +/** + * @} + */ + +/** @defgroup CRS_LL_EM_Exported_Macros_Calculate_Reload Exported_Macros_Calculate_Reload + * @{ + */ + +/** + * @brief Macro to calculate reload value to be set in CRS register according to target and sync frequencies + * @note The RELOAD value should be selected according to the ratio between + * the target frequency and the frequency of the synchronization source after + * prescaling. It is then decreased by one in order to reach the expected + * synchronization on the zero value. The formula is the following: + * RELOAD = (fTARGET / fSYNC) -1 + * @param __FTARGET__ Target frequency (value in Hz) + * @param __FSYNC__ Synchronization signal frequency (value in Hz) + * @retval Reload value (in Hz) + */ +#define __LL_CRS_CALC_CALCULATE_RELOADVALUE(__FTARGET__, __FSYNC__) (((__FTARGET__) / (__FSYNC__)) - 1U) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup CRS_LL_Exported_Functions CRS Exported Functions + * @{ + */ + +/** @defgroup CRS_LL_EF_Configuration Configuration + * @{ + */ + +/** + * @brief Enable Frequency error counter + * @note When this bit is set, the CRS_CFGR register is write-protected and cannot be modified + * @rmtoll CR CEN LL_CRS_EnableFreqErrorCounter + * @retval None + */ +__STATIC_INLINE void LL_CRS_EnableFreqErrorCounter(void) +{ + SET_BIT(CRS->CR, CRS_CR_CEN); +} + +/** + * @brief Disable Frequency error counter + * @rmtoll CR CEN LL_CRS_DisableFreqErrorCounter + * @retval None + */ +__STATIC_INLINE void LL_CRS_DisableFreqErrorCounter(void) +{ + CLEAR_BIT(CRS->CR, CRS_CR_CEN); +} + +/** + * @brief Check if Frequency error counter is enabled or not + * @rmtoll CR CEN LL_CRS_IsEnabledFreqErrorCounter + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsEnabledFreqErrorCounter(void) +{ + return (READ_BIT(CRS->CR, CRS_CR_CEN) == (CRS_CR_CEN)); +} + +/** + * @brief Enable Automatic trimming counter + * @rmtoll CR AUTOTRIMEN LL_CRS_EnableAutoTrimming + * @retval None + */ +__STATIC_INLINE void LL_CRS_EnableAutoTrimming(void) +{ + SET_BIT(CRS->CR, CRS_CR_AUTOTRIMEN); +} + +/** + * @brief Disable Automatic trimming counter + * @rmtoll CR AUTOTRIMEN LL_CRS_DisableAutoTrimming + * @retval None + */ +__STATIC_INLINE void LL_CRS_DisableAutoTrimming(void) +{ + CLEAR_BIT(CRS->CR, CRS_CR_AUTOTRIMEN); +} + +/** + * @brief Check if Automatic trimming is enabled or not + * @rmtoll CR AUTOTRIMEN LL_CRS_IsEnabledAutoTrimming + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsEnabledAutoTrimming(void) +{ + return (READ_BIT(CRS->CR, CRS_CR_AUTOTRIMEN) == (CRS_CR_AUTOTRIMEN)); +} + +/** + * @brief Set HSI48 oscillator smooth trimming + * @note When the AUTOTRIMEN bit is set, this field is controlled by hardware and is read-only + * @rmtoll CR TRIM LL_CRS_SetHSI48SmoothTrimming + * @param Value a number between Min_Data = 0 and Max_Data = 63 + * @note Default value can be set thanks to @ref LL_CRS_HSI48CALIBRATION_DEFAULT + * @retval None + */ +__STATIC_INLINE void LL_CRS_SetHSI48SmoothTrimming(uint32_t Value) +{ + MODIFY_REG(CRS->CR, CRS_CR_TRIM, Value << CRS_CR_TRIM_Pos); +} + +/** + * @brief Get HSI48 oscillator smooth trimming + * @rmtoll CR TRIM LL_CRS_GetHSI48SmoothTrimming + * @retval a number between Min_Data = 0 and Max_Data = 63 + */ +__STATIC_INLINE uint32_t LL_CRS_GetHSI48SmoothTrimming(void) +{ + return (uint32_t)(READ_BIT(CRS->CR, CRS_CR_TRIM) >> CRS_CR_TRIM_Pos); +} + +/** + * @brief Set counter reload value + * @rmtoll CFGR RELOAD LL_CRS_SetReloadCounter + * @param Value a number between Min_Data = 0 and Max_Data = 0xFFFF + * @note Default value can be set thanks to @ref LL_CRS_RELOADVALUE_DEFAULT + * Otherwise it can be calculated in using macro @ref __LL_CRS_CALC_CALCULATE_RELOADVALUE (_FTARGET_, _FSYNC_) + * @retval None + */ +__STATIC_INLINE void LL_CRS_SetReloadCounter(uint32_t Value) +{ + MODIFY_REG(CRS->CFGR, CRS_CFGR_RELOAD, Value); +} + +/** + * @brief Get counter reload value + * @rmtoll CFGR RELOAD LL_CRS_GetReloadCounter + * @retval a number between Min_Data = 0 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t LL_CRS_GetReloadCounter(void) +{ + return (uint32_t)(READ_BIT(CRS->CFGR, CRS_CFGR_RELOAD)); +} + +/** + * @brief Set frequency error limit + * @rmtoll CFGR FELIM LL_CRS_SetFreqErrorLimit + * @param Value a number between Min_Data = 0 and Max_Data = 255 + * @note Default value can be set thanks to @ref LL_CRS_ERRORLIMIT_DEFAULT + * @retval None + */ +__STATIC_INLINE void LL_CRS_SetFreqErrorLimit(uint32_t Value) +{ + MODIFY_REG(CRS->CFGR, CRS_CFGR_FELIM, Value << CRS_CFGR_FELIM_Pos); +} + +/** + * @brief Get frequency error limit + * @rmtoll CFGR FELIM LL_CRS_GetFreqErrorLimit + * @retval A number between Min_Data = 0 and Max_Data = 255 + */ +__STATIC_INLINE uint32_t LL_CRS_GetFreqErrorLimit(void) +{ + return (uint32_t)(READ_BIT(CRS->CFGR, CRS_CFGR_FELIM) >> CRS_CFGR_FELIM_Pos); +} + +/** + * @brief Set division factor for SYNC signal + * @rmtoll CFGR SYNCDIV LL_CRS_SetSyncDivider + * @param Divider This parameter can be one of the following values: + * @arg @ref LL_CRS_SYNC_DIV_1 + * @arg @ref LL_CRS_SYNC_DIV_2 + * @arg @ref LL_CRS_SYNC_DIV_4 + * @arg @ref LL_CRS_SYNC_DIV_8 + * @arg @ref LL_CRS_SYNC_DIV_16 + * @arg @ref LL_CRS_SYNC_DIV_32 + * @arg @ref LL_CRS_SYNC_DIV_64 + * @arg @ref LL_CRS_SYNC_DIV_128 + * @retval None + */ +__STATIC_INLINE void LL_CRS_SetSyncDivider(uint32_t Divider) +{ + MODIFY_REG(CRS->CFGR, CRS_CFGR_SYNCDIV, Divider); +} + +/** + * @brief Get division factor for SYNC signal + * @rmtoll CFGR SYNCDIV LL_CRS_GetSyncDivider + * @retval Returned value can be one of the following values: + * @arg @ref LL_CRS_SYNC_DIV_1 + * @arg @ref LL_CRS_SYNC_DIV_2 + * @arg @ref LL_CRS_SYNC_DIV_4 + * @arg @ref LL_CRS_SYNC_DIV_8 + * @arg @ref LL_CRS_SYNC_DIV_16 + * @arg @ref LL_CRS_SYNC_DIV_32 + * @arg @ref LL_CRS_SYNC_DIV_64 + * @arg @ref LL_CRS_SYNC_DIV_128 + */ +__STATIC_INLINE uint32_t LL_CRS_GetSyncDivider(void) +{ + return (uint32_t)(READ_BIT(CRS->CFGR, CRS_CFGR_SYNCDIV)); +} + +/** + * @brief Set SYNC signal source + * @rmtoll CFGR SYNCSRC LL_CRS_SetSyncSignalSource + * @param Source This parameter can be one of the following values: + * @arg @ref LL_CRS_SYNC_SOURCE_GPIO + * @arg @ref LL_CRS_SYNC_SOURCE_LSE + * @arg @ref LL_CRS_SYNC_SOURCE_USB + * @retval None + */ +__STATIC_INLINE void LL_CRS_SetSyncSignalSource(uint32_t Source) +{ + MODIFY_REG(CRS->CFGR, CRS_CFGR_SYNCSRC, Source); +} + +/** + * @brief Get SYNC signal source + * @rmtoll CFGR SYNCSRC LL_CRS_GetSyncSignalSource + * @retval Returned value can be one of the following values: + * @arg @ref LL_CRS_SYNC_SOURCE_GPIO + * @arg @ref LL_CRS_SYNC_SOURCE_LSE + * @arg @ref LL_CRS_SYNC_SOURCE_USB + */ +__STATIC_INLINE uint32_t LL_CRS_GetSyncSignalSource(void) +{ + return (uint32_t)(READ_BIT(CRS->CFGR, CRS_CFGR_SYNCSRC)); +} + +/** + * @brief Set input polarity for the SYNC signal source + * @rmtoll CFGR SYNCPOL LL_CRS_SetSyncPolarity + * @param Polarity This parameter can be one of the following values: + * @arg @ref LL_CRS_SYNC_POLARITY_RISING + * @arg @ref LL_CRS_SYNC_POLARITY_FALLING + * @retval None + */ +__STATIC_INLINE void LL_CRS_SetSyncPolarity(uint32_t Polarity) +{ + MODIFY_REG(CRS->CFGR, CRS_CFGR_SYNCPOL, Polarity); +} + +/** + * @brief Get input polarity for the SYNC signal source + * @rmtoll CFGR SYNCPOL LL_CRS_GetSyncPolarity + * @retval Returned value can be one of the following values: + * @arg @ref LL_CRS_SYNC_POLARITY_RISING + * @arg @ref LL_CRS_SYNC_POLARITY_FALLING + */ +__STATIC_INLINE uint32_t LL_CRS_GetSyncPolarity(void) +{ + return (uint32_t)(READ_BIT(CRS->CFGR, CRS_CFGR_SYNCPOL)); +} + +/** + * @brief Configure CRS for the synchronization + * @rmtoll CR TRIM LL_CRS_ConfigSynchronization\n + * CFGR RELOAD LL_CRS_ConfigSynchronization\n + * CFGR FELIM LL_CRS_ConfigSynchronization\n + * CFGR SYNCDIV LL_CRS_ConfigSynchronization\n + * CFGR SYNCSRC LL_CRS_ConfigSynchronization\n + * CFGR SYNCPOL LL_CRS_ConfigSynchronization + * @param HSI48CalibrationValue a number between Min_Data = 0 and Max_Data = 63 + * @param ErrorLimitValue a number between Min_Data = 0 and Max_Data = 0xFFFF + * @param ReloadValue a number between Min_Data = 0 and Max_Data = 255 + * @param Settings This parameter can be a combination of the following values: + * @arg @ref LL_CRS_SYNC_DIV_1 or @ref LL_CRS_SYNC_DIV_2 or @ref LL_CRS_SYNC_DIV_4 or @ref LL_CRS_SYNC_DIV_8 + * or @ref LL_CRS_SYNC_DIV_16 or @ref LL_CRS_SYNC_DIV_32 or @ref LL_CRS_SYNC_DIV_64 or @ref LL_CRS_SYNC_DIV_128 + * @arg @ref LL_CRS_SYNC_SOURCE_GPIO or @ref LL_CRS_SYNC_SOURCE_LSE or @ref LL_CRS_SYNC_SOURCE_USB + * @arg @ref LL_CRS_SYNC_POLARITY_RISING or @ref LL_CRS_SYNC_POLARITY_FALLING + * @retval None + */ +__STATIC_INLINE void LL_CRS_ConfigSynchronization(uint32_t HSI48CalibrationValue, uint32_t ErrorLimitValue, + uint32_t ReloadValue, uint32_t Settings) +{ + MODIFY_REG(CRS->CR, CRS_CR_TRIM, HSI48CalibrationValue); + MODIFY_REG(CRS->CFGR, + CRS_CFGR_RELOAD | CRS_CFGR_FELIM | CRS_CFGR_SYNCDIV | CRS_CFGR_SYNCSRC | CRS_CFGR_SYNCPOL, + ReloadValue | (ErrorLimitValue << CRS_CFGR_FELIM_Pos) | Settings); +} + +/** + * @} + */ + +/** @defgroup CRS_LL_EF_CRS_Management CRS_Management + * @{ + */ + +/** + * @brief Generate software SYNC event + * @rmtoll CR SWSYNC LL_CRS_GenerateEvent_SWSYNC + * @retval None + */ +__STATIC_INLINE void LL_CRS_GenerateEvent_SWSYNC(void) +{ + SET_BIT(CRS->CR, CRS_CR_SWSYNC); +} + +/** + * @brief Get the frequency error direction latched in the time of the last + * SYNC event + * @rmtoll ISR FEDIR LL_CRS_GetFreqErrorDirection + * @retval Returned value can be one of the following values: + * @arg @ref LL_CRS_FREQ_ERROR_DIR_UP + * @arg @ref LL_CRS_FREQ_ERROR_DIR_DOWN + */ +__STATIC_INLINE uint32_t LL_CRS_GetFreqErrorDirection(void) +{ + return (uint32_t)(READ_BIT(CRS->ISR, CRS_ISR_FEDIR)); +} + +/** + * @brief Get the frequency error counter value latched in the time of the last SYNC event + * @rmtoll ISR FECAP LL_CRS_GetFreqErrorCapture + * @retval A number between Min_Data = 0x0000 and Max_Data = 0xFFFF + */ +__STATIC_INLINE uint32_t LL_CRS_GetFreqErrorCapture(void) +{ + return (uint32_t)(READ_BIT(CRS->ISR, CRS_ISR_FECAP) >> CRS_ISR_FECAP_Pos); +} + +/** + * @} + */ + +/** @defgroup CRS_LL_EF_FLAG_Management FLAG_Management + * @{ + */ + +/** + * @brief Check if SYNC event OK signal occurred or not + * @rmtoll ISR SYNCOKF LL_CRS_IsActiveFlag_SYNCOK + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_SYNCOK(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_SYNCOKF) == (CRS_ISR_SYNCOKF)); +} + +/** + * @brief Check if SYNC warning signal occurred or not + * @rmtoll ISR SYNCWARNF LL_CRS_IsActiveFlag_SYNCWARN + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_SYNCWARN(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_SYNCWARNF) == (CRS_ISR_SYNCWARNF)); +} + +/** + * @brief Check if Synchronization or trimming error signal occurred or not + * @rmtoll ISR ERRF LL_CRS_IsActiveFlag_ERR + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_ERR(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_ERRF) == (CRS_ISR_ERRF)); +} + +/** + * @brief Check if Expected SYNC signal occurred or not + * @rmtoll ISR ESYNCF LL_CRS_IsActiveFlag_ESYNC + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_ESYNC(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_ESYNCF) == (CRS_ISR_ESYNCF)); +} + +/** + * @brief Check if SYNC error signal occurred or not + * @rmtoll ISR SYNCERR LL_CRS_IsActiveFlag_SYNCERR + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_SYNCERR(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_SYNCERR) == (CRS_ISR_SYNCERR)); +} + +/** + * @brief Check if SYNC missed error signal occurred or not + * @rmtoll ISR SYNCMISS LL_CRS_IsActiveFlag_SYNCMISS + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_SYNCMISS(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_SYNCMISS) == (CRS_ISR_SYNCMISS)); +} + +/** + * @brief Check if Trimming overflow or underflow occurred or not + * @rmtoll ISR TRIMOVF LL_CRS_IsActiveFlag_TRIMOVF + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsActiveFlag_TRIMOVF(void) +{ + return (READ_BIT(CRS->ISR, CRS_ISR_TRIMOVF) == (CRS_ISR_TRIMOVF)); +} + +/** + * @brief Clear the SYNC event OK flag + * @rmtoll ICR SYNCOKC LL_CRS_ClearFlag_SYNCOK + * @retval None + */ +__STATIC_INLINE void LL_CRS_ClearFlag_SYNCOK(void) +{ + WRITE_REG(CRS->ICR, CRS_ICR_SYNCOKC); +} + +/** + * @brief Clear the SYNC warning flag + * @rmtoll ICR SYNCWARNC LL_CRS_ClearFlag_SYNCWARN + * @retval None + */ +__STATIC_INLINE void LL_CRS_ClearFlag_SYNCWARN(void) +{ + WRITE_REG(CRS->ICR, CRS_ICR_SYNCWARNC); +} + +/** + * @brief Clear TRIMOVF, SYNCMISS and SYNCERR bits and consequently also + * the ERR flag + * @rmtoll ICR ERRC LL_CRS_ClearFlag_ERR + * @retval None + */ +__STATIC_INLINE void LL_CRS_ClearFlag_ERR(void) +{ + WRITE_REG(CRS->ICR, CRS_ICR_ERRC); +} + +/** + * @brief Clear Expected SYNC flag + * @rmtoll ICR ESYNCC LL_CRS_ClearFlag_ESYNC + * @retval None + */ +__STATIC_INLINE void LL_CRS_ClearFlag_ESYNC(void) +{ + WRITE_REG(CRS->ICR, CRS_ICR_ESYNCC); +} + +/** + * @} + */ + +/** @defgroup CRS_LL_EF_IT_Management IT_Management + * @{ + */ + +/** + * @brief Enable SYNC event OK interrupt + * @rmtoll CR SYNCOKIE LL_CRS_EnableIT_SYNCOK + * @retval None + */ +__STATIC_INLINE void LL_CRS_EnableIT_SYNCOK(void) +{ + SET_BIT(CRS->CR, CRS_CR_SYNCOKIE); +} + +/** + * @brief Disable SYNC event OK interrupt + * @rmtoll CR SYNCOKIE LL_CRS_DisableIT_SYNCOK + * @retval None + */ +__STATIC_INLINE void LL_CRS_DisableIT_SYNCOK(void) +{ + CLEAR_BIT(CRS->CR, CRS_CR_SYNCOKIE); +} + +/** + * @brief Check if SYNC event OK interrupt is enabled or not + * @rmtoll CR SYNCOKIE LL_CRS_IsEnabledIT_SYNCOK + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsEnabledIT_SYNCOK(void) +{ + return (READ_BIT(CRS->CR, CRS_CR_SYNCOKIE) == (CRS_CR_SYNCOKIE)); +} + +/** + * @brief Enable SYNC warning interrupt + * @rmtoll CR SYNCWARNIE LL_CRS_EnableIT_SYNCWARN + * @retval None + */ +__STATIC_INLINE void LL_CRS_EnableIT_SYNCWARN(void) +{ + SET_BIT(CRS->CR, CRS_CR_SYNCWARNIE); +} + +/** + * @brief Disable SYNC warning interrupt + * @rmtoll CR SYNCWARNIE LL_CRS_DisableIT_SYNCWARN + * @retval None + */ +__STATIC_INLINE void LL_CRS_DisableIT_SYNCWARN(void) +{ + CLEAR_BIT(CRS->CR, CRS_CR_SYNCWARNIE); +} + +/** + * @brief Check if SYNC warning interrupt is enabled or not + * @rmtoll CR SYNCWARNIE LL_CRS_IsEnabledIT_SYNCWARN + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsEnabledIT_SYNCWARN(void) +{ + return (READ_BIT(CRS->CR, CRS_CR_SYNCWARNIE) == (CRS_CR_SYNCWARNIE)); +} + +/** + * @brief Enable Synchronization or trimming error interrupt + * @rmtoll CR ERRIE LL_CRS_EnableIT_ERR + * @retval None + */ +__STATIC_INLINE void LL_CRS_EnableIT_ERR(void) +{ + SET_BIT(CRS->CR, CRS_CR_ERRIE); +} + +/** + * @brief Disable Synchronization or trimming error interrupt + * @rmtoll CR ERRIE LL_CRS_DisableIT_ERR + * @retval None + */ +__STATIC_INLINE void LL_CRS_DisableIT_ERR(void) +{ + CLEAR_BIT(CRS->CR, CRS_CR_ERRIE); +} + +/** + * @brief Check if Synchronization or trimming error interrupt is enabled or not + * @rmtoll CR ERRIE LL_CRS_IsEnabledIT_ERR + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsEnabledIT_ERR(void) +{ + return (READ_BIT(CRS->CR, CRS_CR_ERRIE) == (CRS_CR_ERRIE)); +} + +/** + * @brief Enable Expected SYNC interrupt + * @rmtoll CR ESYNCIE LL_CRS_EnableIT_ESYNC + * @retval None + */ +__STATIC_INLINE void LL_CRS_EnableIT_ESYNC(void) +{ + SET_BIT(CRS->CR, CRS_CR_ESYNCIE); +} + +/** + * @brief Disable Expected SYNC interrupt + * @rmtoll CR ESYNCIE LL_CRS_DisableIT_ESYNC + * @retval None + */ +__STATIC_INLINE void LL_CRS_DisableIT_ESYNC(void) +{ + CLEAR_BIT(CRS->CR, CRS_CR_ESYNCIE); +} + +/** + * @brief Check if Expected SYNC interrupt is enabled or not + * @rmtoll CR ESYNCIE LL_CRS_IsEnabledIT_ESYNC + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_CRS_IsEnabledIT_ESYNC(void) +{ + return (READ_BIT(CRS->CR, CRS_CR_ESYNCIE) == (CRS_CR_ESYNCIE)); +} + +/** + * @} + */ + +#if defined(USE_FULL_LL_DRIVER) +/** @defgroup CRS_LL_EF_Init Initialization and de-initialization functions + * @{ + */ + +ErrorStatus LL_CRS_DeInit(void); + +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(CRS) */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32C0xx_LL_CRS_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dma.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dma.h index ce8b0b53a..afc16dd05 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dma.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dma.h @@ -48,7 +48,13 @@ static const uint8_t CHANNEL_OFFSET_TAB[] = { (uint8_t)(DMA1_Channel1_BASE - DMA1_BASE), (uint8_t)(DMA1_Channel2_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel3_BASE - DMA1_BASE) + (uint8_t)(DMA1_Channel3_BASE - DMA1_BASE), +#if defined(DMA1_Channel4_BASE) + (uint8_t)(DMA1_Channel4_BASE - DMA1_BASE), +#endif /* DMA1_Channel4_BASE */ +#if defined(DMA1_Channel5_BASE) + (uint8_t)(DMA1_Channel5_BASE - DMA1_BASE), +#endif /* DMA1_Channel5_BASE */ }; /** * @} @@ -169,6 +175,19 @@ typedef struct #define LL_DMA_IFCR_CTCIF3 DMA_IFCR_CTCIF3 /*!< Channel 3 transfer complete flag */ #define LL_DMA_IFCR_CHTIF3 DMA_IFCR_CHTIF3 /*!< Channel 3 half transfer flag */ #define LL_DMA_IFCR_CTEIF3 DMA_IFCR_CTEIF3 /*!< Channel 3 transfer error flag */ +#if defined(DMA1_Channel4) +#define LL_DMA_IFCR_CGIF4 DMA_IFCR_CGIF4 /*!< Channel 4 global flag */ +#define LL_DMA_IFCR_CTCIF4 DMA_IFCR_CTCIF4 /*!< Channel 4 transfer complete flag */ +#define LL_DMA_IFCR_CHTIF4 DMA_IFCR_CHTIF4 /*!< Channel 4 half transfer flag */ +#define LL_DMA_IFCR_CTEIF4 DMA_IFCR_CTEIF4 /*!< Channel 4 transfer error flag */ +#endif /* DMA1_Channel4 */ +#if defined(DMA1_Channel5) +#define LL_DMA_IFCR_CGIF5 DMA_IFCR_CGIF5 /*!< Channel 5 global flag */ +#define LL_DMA_IFCR_CTCIF5 DMA_IFCR_CTCIF5 /*!< Channel 5 transfer complete flag */ +#define LL_DMA_IFCR_CHTIF5 DMA_IFCR_CHTIF5 /*!< Channel 5 half transfer flag */ +#define LL_DMA_IFCR_CTEIF5 DMA_IFCR_CTEIF5 /*!< Channel 5 transfer error flag */ +#endif /* DMA1_Channel5 */ + /** * @} */ @@ -189,6 +208,18 @@ typedef struct #define LL_DMA_ISR_TCIF3 DMA_ISR_TCIF3 /*!< Channel 3 transfer complete flag */ #define LL_DMA_ISR_HTIF3 DMA_ISR_HTIF3 /*!< Channel 3 half transfer flag */ #define LL_DMA_ISR_TEIF3 DMA_ISR_TEIF3 /*!< Channel 3 transfer error flag */ +#if defined(DMA1_Channel4) +#define LL_DMA_ISR_GIF4 DMA_ISR_GIF4 /*!< Channel 4 global flag */ +#define LL_DMA_ISR_TCIF4 DMA_ISR_TCIF4 /*!< Channel 4 transfer complete flag */ +#define LL_DMA_ISR_HTIF4 DMA_ISR_HTIF4 /*!< Channel 4 half transfer flag */ +#define LL_DMA_ISR_TEIF4 DMA_ISR_TEIF4 /*!< Channel 4 transfer error flag */ +#endif /* DMA1_Channel4 */ +#if defined(DMA1_Channel5) +#define LL_DMA_ISR_GIF5 DMA_ISR_GIF5 /*!< Channel 5 global flag */ +#define LL_DMA_ISR_TCIF5 DMA_ISR_TCIF5 /*!< Channel 5 transfer complete flag */ +#define LL_DMA_ISR_HTIF5 DMA_ISR_HTIF5 /*!< Channel 5 half transfer flag */ +#define LL_DMA_ISR_TEIF5 DMA_ISR_TEIF5 /*!< Channel 5 transfer error flag */ +#endif /* DMA1_Channel5 */ /** * @} */ @@ -210,6 +241,12 @@ typedef struct #define LL_DMA_CHANNEL_1 0x00000001U /*!< DMA Channel 1 */ #define LL_DMA_CHANNEL_2 0x00000002U /*!< DMA Channel 2 */ #define LL_DMA_CHANNEL_3 0x00000003U /*!< DMA Channel 3 */ +#if defined(DMA1_Channel4) +#define LL_DMA_CHANNEL_4 0x00000004U /*!< DMA Channel 4 */ +#endif /* DMA1_Channel4 */ +#if defined(DMA1_Channel5) +#define LL_DMA_CHANNEL_5 0x00000005U /*!< DMA Channel 5 */ +#endif /* DMA1_Channel5 */ #if defined(USE_FULL_LL_DRIVER) #define LL_DMA_CHANNEL_ALL 0xFFFF0000U /*!< DMA Channel all (used only for function @ref LL_DMA_DeInit(). */ @@ -333,10 +370,19 @@ typedef struct * @param __CHANNEL_INSTANCE__ DMAx_Channely * @retval LL_DMA_CHANNEL_y */ +#if defined(LL_DMA_CHANNEL_5) +#define __LL_DMA_GET_CHANNEL(__CHANNEL_INSTANCE__) \ + (((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel1)) ? LL_DMA_CHANNEL_1 : \ + ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel2)) ? LL_DMA_CHANNEL_2 : \ + ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel3)) ? LL_DMA_CHANNEL_3 : \ + ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel4)) ? LL_DMA_CHANNEL_4 : \ + LL_DMA_CHANNEL_5) +#else #define __LL_DMA_GET_CHANNEL(__CHANNEL_INSTANCE__) \ (((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel1)) ? LL_DMA_CHANNEL_1 : \ ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel2)) ? LL_DMA_CHANNEL_2 : \ LL_DMA_CHANNEL_3) +#endif /* LL_DMA_CHANNEL_5 */ /** * @brief Convert DMA Instance DMAx and LL_DMA_CHANNEL_y into DMAx_Channely @@ -344,14 +390,19 @@ typedef struct * @param __CHANNEL__ LL_DMA_CHANNEL_y * @retval DMAx_Channely */ - +#if defined(LL_DMA_CHANNEL_5) +#define __LL_DMA_GET_CHANNEL_INSTANCE(__DMA_INSTANCE__, __CHANNEL__) \ + ((((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_1))) ? DMA1_Channel1 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_2))) ? DMA1_Channel2 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_3))) ? DMA1_Channel3 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_4))) ? DMA1_Channel4 : \ + DMA1_Channel5) +#else #define __LL_DMA_GET_CHANNEL_INSTANCE(__DMA_INSTANCE__, __CHANNEL__) \ - ((((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == \ - ((uint32_t)LL_DMA_CHANNEL_1))) ? DMA1_Channel1 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == \ - ((uint32_t)LL_DMA_CHANNEL_2))) ? DMA1_Channel2 : \ + ((((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_1))) ? DMA1_Channel1 : \ + (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_2))) ? DMA1_Channel2 : \ DMA1_Channel3) - +#endif /* LL_DMA_CHANNEL_5 */ /** * @} @@ -377,6 +428,9 @@ typedef struct * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_EnableChannel(DMA_TypeDef *DMAx, uint32_t Channel) @@ -393,6 +447,9 @@ __STATIC_INLINE void LL_DMA_EnableChannel(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_DisableChannel(DMA_TypeDef *DMAx, uint32_t Channel) @@ -409,6 +466,9 @@ __STATIC_INLINE void LL_DMA_DisableChannel(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_DMA_IsEnabledChannel(DMA_TypeDef *DMAx, uint32_t Channel) @@ -433,16 +493,19 @@ __STATIC_INLINE uint32_t LL_DMA_IsEnabledChannel(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param Configuration This parameter must be a combination of all the following values: * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY or @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH or - @ref LL_DMA_DIRECTION_MEMORY_TO_MEMORY + * @ref LL_DMA_DIRECTION_MEMORY_TO_MEMORY * @arg @ref LL_DMA_MODE_NORMAL or @ref LL_DMA_MODE_CIRCULAR * @arg @ref LL_DMA_PERIPH_INCREMENT or @ref LL_DMA_PERIPH_NOINCREMENT * @arg @ref LL_DMA_MEMORY_INCREMENT or @ref LL_DMA_MEMORY_NOINCREMENT * @arg @ref LL_DMA_PDATAALIGN_BYTE or @ref LL_DMA_PDATAALIGN_HALFWORD or @ref LL_DMA_PDATAALIGN_WORD * @arg @ref LL_DMA_MDATAALIGN_BYTE or @ref LL_DMA_MDATAALIGN_HALFWORD or @ref LL_DMA_MDATAALIGN_WORD * @arg @ref LL_DMA_PRIORITY_LOW or @ref LL_DMA_PRIORITY_MEDIUM or @ref LL_DMA_PRIORITY_HIGH or - @ref LL_DMA_PRIORITY_VERYHIGH + * @ref LL_DMA_PRIORITY_VERYHIGH * @retval None */ __STATIC_INLINE void LL_DMA_ConfigTransfer(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t Configuration) @@ -462,6 +525,9 @@ __STATIC_INLINE void LL_DMA_ConfigTransfer(DMA_TypeDef *DMAx, uint32_t Channel, * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param Direction This parameter can be one of the following values: * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH @@ -484,6 +550,9 @@ __STATIC_INLINE void LL_DMA_SetDataTransferDirection(DMA_TypeDef *DMAx, uint32_t * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH @@ -506,6 +575,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetDataTransferDirection(DMA_TypeDef *DMAx, uint * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param Mode This parameter can be one of the following values: * @arg @ref LL_DMA_MODE_NORMAL * @arg @ref LL_DMA_MODE_CIRCULAR @@ -526,6 +598,9 @@ __STATIC_INLINE void LL_DMA_SetMode(DMA_TypeDef *DMAx, uint32_t Channel, uint32_ * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_MODE_NORMAL * @arg @ref LL_DMA_MODE_CIRCULAR @@ -545,6 +620,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetMode(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param PeriphOrM2MSrcIncMode This parameter can be one of the following values: * @arg @ref LL_DMA_PERIPH_INCREMENT * @arg @ref LL_DMA_PERIPH_NOINCREMENT @@ -565,6 +643,9 @@ __STATIC_INLINE void LL_DMA_SetPeriphIncMode(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_PERIPH_INCREMENT * @arg @ref LL_DMA_PERIPH_NOINCREMENT @@ -584,6 +665,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetPeriphIncMode(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param MemoryOrM2MDstIncMode This parameter can be one of the following values: * @arg @ref LL_DMA_MEMORY_INCREMENT * @arg @ref LL_DMA_MEMORY_NOINCREMENT @@ -604,6 +688,9 @@ __STATIC_INLINE void LL_DMA_SetMemoryIncMode(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_MEMORY_INCREMENT * @arg @ref LL_DMA_MEMORY_NOINCREMENT @@ -623,6 +710,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetMemoryIncMode(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param PeriphOrM2MSrcDataSize This parameter can be one of the following values: * @arg @ref LL_DMA_PDATAALIGN_BYTE * @arg @ref LL_DMA_PDATAALIGN_HALFWORD @@ -644,6 +734,9 @@ __STATIC_INLINE void LL_DMA_SetPeriphSize(DMA_TypeDef *DMAx, uint32_t Channel, u * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_PDATAALIGN_BYTE * @arg @ref LL_DMA_PDATAALIGN_HALFWORD @@ -664,6 +757,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetPeriphSize(DMA_TypeDef *DMAx, uint32_t Channe * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param MemoryOrM2MDstDataSize This parameter can be one of the following values: * @arg @ref LL_DMA_MDATAALIGN_BYTE * @arg @ref LL_DMA_MDATAALIGN_HALFWORD @@ -685,6 +781,9 @@ __STATIC_INLINE void LL_DMA_SetMemorySize(DMA_TypeDef *DMAx, uint32_t Channel, u * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_MDATAALIGN_BYTE * @arg @ref LL_DMA_MDATAALIGN_HALFWORD @@ -705,6 +804,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetMemorySize(DMA_TypeDef *DMAx, uint32_t Channe * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param Priority This parameter can be one of the following values: * @arg @ref LL_DMA_PRIORITY_LOW * @arg @ref LL_DMA_PRIORITY_MEDIUM @@ -727,6 +829,9 @@ __STATIC_INLINE void LL_DMA_SetChannelPriorityLevel(DMA_TypeDef *DMAx, uint32_t * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMA_PRIORITY_LOW * @arg @ref LL_DMA_PRIORITY_MEDIUM @@ -750,6 +855,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetChannelPriorityLevel(DMA_TypeDef *DMAx, uint3 * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param NbData Between Min_Data = 0 and Max_Data = 0x0000FFFF * @retval None */ @@ -770,6 +878,9 @@ __STATIC_INLINE void LL_DMA_SetDataLength(DMA_TypeDef *DMAx, uint32_t Channel, u * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF */ __STATIC_INLINE uint32_t LL_DMA_GetDataLength(DMA_TypeDef *DMAx, uint32_t Channel) @@ -790,6 +901,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetDataLength(DMA_TypeDef *DMAx, uint32_t Channe * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param SrcAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF * @param DstAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF * @param Direction This parameter can be one of the following values: @@ -826,6 +940,9 @@ __STATIC_INLINE void LL_DMA_ConfigAddresses(DMA_TypeDef *DMAx, uint32_t Channel, * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param MemoryAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF * @retval None */ @@ -845,6 +962,9 @@ __STATIC_INLINE void LL_DMA_SetMemoryAddress(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param PeriphAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF * @retval None */ @@ -863,6 +983,9 @@ __STATIC_INLINE void LL_DMA_SetPeriphAddress(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF */ __STATIC_INLINE uint32_t LL_DMA_GetMemoryAddress(DMA_TypeDef *DMAx, uint32_t Channel) @@ -880,6 +1003,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetMemoryAddress(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF */ __STATIC_INLINE uint32_t LL_DMA_GetPeriphAddress(DMA_TypeDef *DMAx, uint32_t Channel) @@ -898,6 +1024,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetPeriphAddress(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param MemoryAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF * @retval None */ @@ -917,6 +1046,9 @@ __STATIC_INLINE void LL_DMA_SetM2MSrcAddress(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param MemoryAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF * @retval None */ @@ -935,6 +1067,9 @@ __STATIC_INLINE void LL_DMA_SetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF */ __STATIC_INLINE uint32_t LL_DMA_GetM2MSrcAddress(DMA_TypeDef *DMAx, uint32_t Channel) @@ -952,6 +1087,9 @@ __STATIC_INLINE uint32_t LL_DMA_GetM2MSrcAddress(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF */ __STATIC_INLINE uint32_t LL_DMA_GetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Channel) @@ -962,13 +1100,15 @@ __STATIC_INLINE uint32_t LL_DMA_GetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Cha /** * @brief Set DMA request for DMA Channels on DMAMUX Channel x. - * @note DMAMUX channel 0 to 2 are mapped to DMA1 channel 1 to 3. + * @note DMAMUX channel 0 to 4 are mapped to DMA1 channel 1 to 5. * @rmtoll CxCR DMAREQ_ID LL_DMA_SetPeriphRequest * @param DMAx DMAx Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) * @param Request This parameter can be one of the following values: * @arg @ref LL_DMAMUX_REQ_MEM2MEM * @arg @ref LL_DMAMUX_REQ_GENERATOR0 @@ -978,14 +1118,24 @@ __STATIC_INLINE uint32_t LL_DMA_GetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMAMUX_REQ_ADC1 * @arg @ref LL_DMAMUX_REQ_I2C1_RX * @arg @ref LL_DMAMUX_REQ_I2C1_TX + * @arg @ref LL_DMAMUX_REQ_I2C2_RX (*) + * @arg @ref LL_DMAMUX_REQ_I2C2_TX (*) * @arg @ref LL_DMAMUX_REQ_SPI1_RX * @arg @ref LL_DMAMUX_REQ_SPI1_TX + * @arg @ref LL_DMAMUX_REQ_SPI2_RX (*) + * @arg @ref LL_DMAMUX_REQ_SPI2_TX (*) * @arg @ref LL_DMAMUX_REQ_TIM1_CH1 * @arg @ref LL_DMAMUX_REQ_TIM1_CH2 * @arg @ref LL_DMAMUX_REQ_TIM1_CH3 * @arg @ref LL_DMAMUX_REQ_TIM1_CH4 * @arg @ref LL_DMAMUX_REQ_TIM1_TRIG_COM * @arg @ref LL_DMAMUX_REQ_TIM1_UP + * @arg @ref LL_DMAMUX_REQ_TIM2_CH1 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH2 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH3 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH4 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_TRIG_COM (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_UP (*) * @arg @ref LL_DMAMUX_REQ_TIM3_CH1 * @arg @ref LL_DMAMUX_REQ_TIM3_CH2 * @arg @ref LL_DMAMUX_REQ_TIM3_CH3 @@ -1002,6 +1152,7 @@ __STATIC_INLINE uint32_t LL_DMA_GetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Cha * @arg @ref LL_DMAMUX_REQ_USART1_TX * @arg @ref LL_DMAMUX_REQ_USART2_RX * @arg @ref LL_DMAMUX_REQ_USART2_TX + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_SetPeriphRequest(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t Request) @@ -1013,13 +1164,15 @@ __STATIC_INLINE void LL_DMA_SetPeriphRequest(DMA_TypeDef *DMAx, uint32_t Channel /** * @brief Get DMA request for DMA Channels on DMAMUX Channel x. - * @note DMAMUX channel 0 to 2 are mapped to DMA1 channel 1 to 3. + * @note DMAMUX channel 0 to 4 are mapped to DMA1 channel 1 to 5. * @rmtoll CxCR DMAREQ_ID LL_DMA_GetPeriphRequest * @param DMAx DMAx Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) * @retval Returned value can be one of the following values: * @arg @ref LL_DMAMUX_REQ_MEM2MEM * @arg @ref LL_DMAMUX_REQ_GENERATOR0 @@ -1029,14 +1182,24 @@ __STATIC_INLINE void LL_DMA_SetPeriphRequest(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMAMUX_REQ_ADC1 * @arg @ref LL_DMAMUX_REQ_I2C1_RX * @arg @ref LL_DMAMUX_REQ_I2C1_TX + * @arg @ref LL_DMAMUX_REQ_I2C2_RX (*) + * @arg @ref LL_DMAMUX_REQ_I2C2_TX (*) * @arg @ref LL_DMAMUX_REQ_SPI1_RX * @arg @ref LL_DMAMUX_REQ_SPI1_TX + * @arg @ref LL_DMAMUX_REQ_SPI2_RX (*) + * @arg @ref LL_DMAMUX_REQ_SPI2_TX (*) * @arg @ref LL_DMAMUX_REQ_TIM1_CH1 * @arg @ref LL_DMAMUX_REQ_TIM1_CH2 * @arg @ref LL_DMAMUX_REQ_TIM1_CH3 * @arg @ref LL_DMAMUX_REQ_TIM1_CH4 * @arg @ref LL_DMAMUX_REQ_TIM1_TRIG_COM * @arg @ref LL_DMAMUX_REQ_TIM1_UP + * @arg @ref LL_DMAMUX_REQ_TIM2_CH1 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH2 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH3 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH4 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_TRIG_COM (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_UP (*) * @arg @ref LL_DMAMUX_REQ_TIM3_CH1 * @arg @ref LL_DMAMUX_REQ_TIM3_CH2 * @arg @ref LL_DMAMUX_REQ_TIM3_CH3 @@ -1053,6 +1216,7 @@ __STATIC_INLINE void LL_DMA_SetPeriphRequest(DMA_TypeDef *DMAx, uint32_t Channel * @arg @ref LL_DMAMUX_REQ_USART1_TX * @arg @ref LL_DMAMUX_REQ_USART2_RX * @arg @ref LL_DMAMUX_REQ_USART2_TX + * @note (*) Availability depends on devices */ __STATIC_INLINE uint32_t LL_DMA_GetPeriphRequest(DMA_TypeDef *DMAx, uint32_t Channel) { @@ -1103,6 +1267,32 @@ __STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI3(DMA_TypeDef *DMAx) return ((READ_BIT(DMAx->ISR, DMA_ISR_GIF3) == (DMA_ISR_GIF3)) ? 1UL : 0UL); } +#if defined(DMA_ISR_GIF4) +/** + * @brief Get Channel 4 global interrupt flag. + * @rmtoll ISR GIF4 LL_DMA_IsActiveFlag_GI4 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI4(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_GIF4) == (DMA_ISR_GIF4)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_GIF4 */ + +#if defined(DMA_ISR_GIF5) +/** + * @brief Get Channel 5 global interrupt flag. + * @rmtoll ISR GIF5 LL_DMA_IsActiveFlag_GI5 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI5(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_GIF5) == (DMA_ISR_GIF5)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_GIF5 */ + /** * @brief Get Channel 1 transfer complete flag. * @rmtoll ISR TCIF1 LL_DMA_IsActiveFlag_TC1 @@ -1136,6 +1326,31 @@ __STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC3(DMA_TypeDef *DMAx) return ((READ_BIT(DMAx->ISR, DMA_ISR_TCIF3) == (DMA_ISR_TCIF3)) ? 1UL : 0UL); } +#if defined(DMA_ISR_TCIF4) +/** + * @brief Get Channel 4 transfer complete flag. + * @rmtoll ISR TCIF4 LL_DMA_IsActiveFlag_TC4 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC4(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_TCIF4) == (DMA_ISR_TCIF4)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_TCIF4 */ + +#if defined(DMA_ISR_TCIF5) +/** + * @brief Get Channel 5 transfer complete flag. + * @rmtoll ISR TCIF5 LL_DMA_IsActiveFlag_TC5 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC5(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_TCIF5) == (DMA_ISR_TCIF5)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_TCIF5 */ /** * @brief Get Channel 1 half transfer flag. @@ -1170,6 +1385,32 @@ __STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT3(DMA_TypeDef *DMAx) return ((READ_BIT(DMAx->ISR, DMA_ISR_HTIF3) == (DMA_ISR_HTIF3)) ? 1UL : 0UL); } +#if defined(DMA_ISR_HTIF4) +/** + * @brief Get Channel 4 half transfer flag. + * @rmtoll ISR HTIF4 LL_DMA_IsActiveFlag_HT4 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT4(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_HTIF4) == (DMA_ISR_HTIF4)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_HTIF4 */ + +#if defined(DMA_ISR_HTIF5) +/** + * @brief Get Channel 5 half transfer flag. + * @rmtoll ISR HTIF5 LL_DMA_IsActiveFlag_HT5 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT5(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_HTIF5) == (DMA_ISR_HTIF5)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_HTIF5 */ + /** * @brief Get Channel 1 transfer error flag. * @rmtoll ISR TEIF1 LL_DMA_IsActiveFlag_TE1 @@ -1203,8 +1444,38 @@ __STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE3(DMA_TypeDef *DMAx) return ((READ_BIT(DMAx->ISR, DMA_ISR_TEIF3) == (DMA_ISR_TEIF3)) ? 1UL : 0UL); } +#if defined(DMA_ISR_TEIF4) +/** + * @brief Get Channel 4 transfer error flag. + * @rmtoll ISR TEIF4 LL_DMA_IsActiveFlag_TE4 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE4(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_TEIF4) == (DMA_ISR_TEIF4)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_TEIF4 */ + +#if defined(DMA_ISR_TEIF5) +/** + * @brief Get Channel 5 transfer error flag. + * @rmtoll ISR TEIF5 LL_DMA_IsActiveFlag_TE5 + * @param DMAx DMAx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE5(DMA_TypeDef *DMAx) +{ + return ((READ_BIT(DMAx->ISR, DMA_ISR_TEIF5) == (DMA_ISR_TEIF5)) ? 1UL : 0UL); +} +#endif /* DMA_ISR_TEIF5 */ + /** * @brief Clear Channel 1 global interrupt flag. + * @note Do not Clear Channel 1 global interrupt flag when the channel in ON. + Instead clear specific flags transfer complete, half transfer & transfer + error flag with LL_DMA_ClearFlag_TC1, LL_DMA_ClearFlag_HT1, + LL_DMA_ClearFlag_TE1. bug id 2.4.1 in Product Errata Sheet. * @rmtoll IFCR CGIF1 LL_DMA_ClearFlag_GI1 * @param DMAx DMAx Instance * @retval None @@ -1216,6 +1487,10 @@ __STATIC_INLINE void LL_DMA_ClearFlag_GI1(DMA_TypeDef *DMAx) /** * @brief Clear Channel 2 global interrupt flag. + * @note Do not Clear Channel 2 global interrupt flag when the channel in ON. + Instead clear specific flags transfer complete, half transfer & transfer + error flag with LL_DMA_ClearFlag_TC2, LL_DMA_ClearFlag_HT2, + LL_DMA_ClearFlag_TE2. bug id 2.4.1 in Product Errata Sheet. * @rmtoll IFCR CGIF2 LL_DMA_ClearFlag_GI2 * @param DMAx DMAx Instance * @retval None @@ -1227,6 +1502,10 @@ __STATIC_INLINE void LL_DMA_ClearFlag_GI2(DMA_TypeDef *DMAx) /** * @brief Clear Channel 3 global interrupt flag. + * @note Do not Clear Channel 3 global interrupt flag when the channel in ON. + Instead clear specific flags transfer complete, half transfer & transfer + error flag with LL_DMA_ClearFlag_TC3, LL_DMA_ClearFlag_HT3, + LL_DMA_ClearFlag_TE3. bug id 2.4.1 in Product Errata Sheet. * @rmtoll IFCR CGIF3 LL_DMA_ClearFlag_GI3 * @param DMAx DMAx Instance * @retval None @@ -1236,6 +1515,40 @@ __STATIC_INLINE void LL_DMA_ClearFlag_GI3(DMA_TypeDef *DMAx) WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF3); } +#if defined(DMA_IFCR_CGIF4) +/** + * @brief Clear Channel 4 global interrupt flag. + * @note Do not Clear Channel 4 global interrupt flag when the channel in ON. + Instead clear specific flags transfer complete, half transfer & transfer + error flag with LL_DMA_ClearFlag_TC4, LL_DMA_ClearFlag_HT4, + LL_DMA_ClearFlag_TE4. bug id 2.4.1 in Product Errata Sheet. + * @rmtoll IFCR CGIF4 LL_DMA_ClearFlag_GI4 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_GI4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF4); +} +#endif /* DMA_IFCR_CGIF4 */ + +#if defined(DMA_IFCR_CGIF5) +/** + * @brief Clear Channel 5 global interrupt flag. + * @note Do not Clear Channel 5 global interrupt flag when the channel in ON. + Instead clear specific flags transfer complete, half transfer & transfer + error flag with LL_DMA_ClearFlag_TC5, LL_DMA_ClearFlag_HT5, + LL_DMA_ClearFlag_TE5. bug id 2.4.1 in Product Errata Sheet. + * @rmtoll IFCR CGIF5 LL_DMA_ClearFlag_GI5 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_GI5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF5); +} +#endif /* DMA_IFCR_CGIF5 */ + /** * @brief Clear Channel 1 transfer complete flag. * @rmtoll IFCR CTCIF1 LL_DMA_ClearFlag_TC1 @@ -1269,8 +1582,34 @@ __STATIC_INLINE void LL_DMA_ClearFlag_TC3(DMA_TypeDef *DMAx) WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF3); } +#if defined(DMA_IFCR_CTCIF4) +/** + * @brief Clear Channel 4 transfer complete flag. + * @rmtoll IFCR CTCIF4 LL_DMA_ClearFlag_TC4 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_TC4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF4); +} +#endif /* DMA_IFCR_CTCIF4 */ + +#if defined(DMA_IFCR_CTCIF5) +/** + * @brief Clear Channel 5 transfer complete flag. + * @rmtoll IFCR CTCIF5 LL_DMA_ClearFlag_TC5 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_TC5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF5); +} +#endif /* DMA_IFCR_CTCIF5 */ + /** - * @brief Clear Channel 1 half transfer flag. + * @brief Clear Channel 1 half transfer flag. * @rmtoll IFCR CHTIF1 LL_DMA_ClearFlag_HT1 * @param DMAx DMAx Instance * @retval None @@ -1281,7 +1620,7 @@ __STATIC_INLINE void LL_DMA_ClearFlag_HT1(DMA_TypeDef *DMAx) } /** - * @brief Clear Channel 2 half transfer flag. + * @brief Clear Channel 2 half transfer flag. * @rmtoll IFCR CHTIF2 LL_DMA_ClearFlag_HT2 * @param DMAx DMAx Instance * @retval None @@ -1292,7 +1631,7 @@ __STATIC_INLINE void LL_DMA_ClearFlag_HT2(DMA_TypeDef *DMAx) } /** - * @brief Clear Channel 3 half transfer flag. + * @brief Clear Channel 3 half transfer flag. * @rmtoll IFCR CHTIF3 LL_DMA_ClearFlag_HT3 * @param DMAx DMAx Instance * @retval None @@ -1302,6 +1641,32 @@ __STATIC_INLINE void LL_DMA_ClearFlag_HT3(DMA_TypeDef *DMAx) WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF3); } +#if defined(DMA_IFCR_CHTIF4) +/** + * @brief Clear Channel 4 half transfer flag. + * @rmtoll IFCR CHTIF4 LL_DMA_ClearFlag_HT4 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_HT4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF4); +} +#endif /* DMA_IFCR_CHTIF4 */ + +#if defined(DMA_IFCR_CHTIF5) +/** + * @brief Clear Channel 5 half transfer flag. + * @rmtoll IFCR CHTIF5 LL_DMA_ClearFlag_HT5 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_HT5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF5); +} +#endif /* DMA_IFCR_CHTIF5 */ + /** * @brief Clear Channel 1 transfer error flag. * @rmtoll IFCR CTEIF1 LL_DMA_ClearFlag_TE1 @@ -1335,6 +1700,32 @@ __STATIC_INLINE void LL_DMA_ClearFlag_TE3(DMA_TypeDef *DMAx) WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF3); } +#if defined(DMA_IFCR_CTEIF4) +/** + * @brief Clear Channel 4 transfer error flag. + * @rmtoll IFCR CTEIF4 LL_DMA_ClearFlag_TE4 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_TE4(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF4); +} +#endif /* DMA_IFCR_CTEIF4 */ + +#if defined(DMA_IFCR_CTEIF5) +/** + * @brief Clear Channel 5 transfer error flag. + * @rmtoll IFCR CTEIF5 LL_DMA_ClearFlag_TE5 + * @param DMAx DMAx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMA_ClearFlag_TE5(DMA_TypeDef *DMAx) +{ + WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF5); +} +#endif /* DMA_IFCR_CTEIF5 */ + /** * @} */ @@ -1350,6 +1741,9 @@ __STATIC_INLINE void LL_DMA_ClearFlag_TE3(DMA_TypeDef *DMAx) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_EnableIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1366,6 +1760,9 @@ __STATIC_INLINE void LL_DMA_EnableIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_EnableIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1382,6 +1779,9 @@ __STATIC_INLINE void LL_DMA_EnableIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_EnableIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1398,6 +1798,9 @@ __STATIC_INLINE void LL_DMA_EnableIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_DisableIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1414,6 +1817,9 @@ __STATIC_INLINE void LL_DMA_DisableIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_DisableIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1430,6 +1836,9 @@ __STATIC_INLINE void LL_DMA_DisableIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_DMA_DisableIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1446,6 +1855,9 @@ __STATIC_INLINE void LL_DMA_DisableIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1463,6 +1875,9 @@ __STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_TC(DMA_TypeDef *DMAx, uint32_t Chann * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1480,6 +1895,9 @@ __STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_HT(DMA_TypeDef *DMAx, uint32_t Chann * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) @@ -1497,11 +1915,9 @@ __STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_TE(DMA_TypeDef *DMAx, uint32_t Chann /** @defgroup DMA_LL_EF_Init Initialization and de-initialization functions * @{ */ - ErrorStatus LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitTypeDef *DMA_InitStruct); ErrorStatus LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel); void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct); - /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dmamux.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dmamux.h index 36a0f39c8..5ce9d60ea 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dmamux.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_dmamux.h @@ -62,13 +62,22 @@ extern "C" { * @brief Flags defines which can be used with LL_DMAMUX_WriteReg function * @{ */ -#define LL_DMAMUX_CFR_CSOF0 DMAMUX_CFR_CSOF0 /*!< Synchronization Event Overrun Flag Channel 0 */ -#define LL_DMAMUX_CFR_CSOF1 DMAMUX_CFR_CSOF1 /*!< Synchronization Event Overrun Flag Channel 1 */ -#define LL_DMAMUX_CFR_CSOF2 DMAMUX_CFR_CSOF2 /*!< Synchronization Event Overrun Flag Channel 2 */ +#define LL_DMAMUX_CFR_CSOF0 DMAMUX_CFR_CSOF0 /*!< Synchronization Event Overrun Flag Channel 0 */ +#define LL_DMAMUX_CFR_CSOF1 DMAMUX_CFR_CSOF1 /*!< Synchronization Event Overrun Flag Channel 1 */ +#define LL_DMAMUX_CFR_CSOF2 DMAMUX_CFR_CSOF2 /*!< Synchronization Event Overrun Flag Channel 2 */ +#if defined(DMAMUX1_Channel3) +#define LL_DMAMUX_CFR_CSOF3 DMAMUX_CFR_CSOF3 /*!< Synchronization Event Overrun Flag Channel 3 */ +#endif /* DMAMUX1_Channel3 */ +#if defined(DMAMUX1_Channel4) +#define LL_DMAMUX_CFR_CSOF4 DMAMUX_CFR_CSOF4 /*!< Synchronization Event Overrun Flag Channel 4 */ +#endif /* DMAMUX1_Channel4 */ #define LL_DMAMUX_RGCFR_RGCOF0 DMAMUX_RGCFR_COF0 /*!< Request Generator 0 Trigger Event Overrun Flag */ #define LL_DMAMUX_RGCFR_RGCOF1 DMAMUX_RGCFR_COF1 /*!< Request Generator 1 Trigger Event Overrun Flag */ #define LL_DMAMUX_RGCFR_RGCOF2 DMAMUX_RGCFR_COF2 /*!< Request Generator 2 Trigger Event Overrun Flag */ +#if defined(DMAMUX1_Channel3) +#define LL_DMAMUX_RGCFR_RGCOF3 DMAMUX_RGCFR_COF3 /*!< Request Generator 3 Trigger Event Overrun Flag */ +#endif /* DMAMUX1_Channel3 */ /** * @} @@ -81,10 +90,20 @@ extern "C" { #define LL_DMAMUX_CSR_SOF0 DMAMUX_CSR_SOF0 /*!< Synchronization Event Overrun Flag Channel 0 */ #define LL_DMAMUX_CSR_SOF1 DMAMUX_CSR_SOF1 /*!< Synchronization Event Overrun Flag Channel 1 */ #define LL_DMAMUX_CSR_SOF2 DMAMUX_CSR_SOF2 /*!< Synchronization Event Overrun Flag Channel 2 */ +#if defined(DMAMUX1_Channel3) +#define LL_DMAMUX_CSR_SOF3 DMAMUX_CSR_SOF3 /*!< Synchronization Event Overrun Flag Channel 3 */ +#endif /* DMAMUX1_Channel3 */ +#if defined(DMAMUX1_Channel4) +#define LL_DMAMUX_CSR_SOF4 DMAMUX_CSR_SOF4 /*!< Synchronization Event Overrun Flag Channel 4 */ +#endif /* DMAMUX1_Channel4 */ #define LL_DMAMUX_RGSR_RGOF0 DMAMUX_RGSR_OF0 /*!< Request Generator 0 Trigger Event Overrun Flag */ #define LL_DMAMUX_RGSR_RGOF1 DMAMUX_RGSR_OF1 /*!< Request Generator 1 Trigger Event Overrun Flag */ #define LL_DMAMUX_RGSR_RGOF2 DMAMUX_RGSR_OF2 /*!< Request Generator 2 Trigger Event Overrun Flag */ +#if defined(DMAMUX1_Channel3) +#define LL_DMAMUX_RGSR_RGOF3 DMAMUX_RGSR_OF3 /*!< Request Generator 3 Trigger Event Overrun Flag */ +#endif /* DMAMUX1_Channel3 */ + /** * @} */ @@ -102,39 +121,54 @@ extern "C" { /** @defgroup DMAMUX_LL_EC_REQUEST Transfer request * @{ */ -#define LL_DMAMUX_REQ_MEM2MEM 0x00000000U /*!< memory to memory transfer */ -#define LL_DMAMUX_REQ_GENERATOR0 0x00000001U /*!< DMAMUX request generator 0 */ -#define LL_DMAMUX_REQ_GENERATOR1 0x00000002U /*!< DMAMUX request generator 1 */ -#define LL_DMAMUX_REQ_GENERATOR2 0x00000003U /*!< DMAMUX request generator 2 */ -#define LL_DMAMUX_REQ_GENERATOR3 0x00000004U /*!< DMAMUX request generator 3 */ -#define LL_DMAMUX_REQ_ADC1 0x00000005U /*!< DMAMUX ADC1 request */ -#define LL_DMAMUX_REQ_I2C1_RX 0x0000000AU /*!< DMAMUX I2C1 RX request */ -#define LL_DMAMUX_REQ_I2C1_TX 0x0000000BU /*!< DMAMUX I2C1 TX request */ -#define LL_DMAMUX_REQ_SPI1_RX 0x00000010U /*!< DMAMUX SPI1 RX request */ -#define LL_DMAMUX_REQ_SPI1_TX 0x00000011U /*!< DMAMUX SPI1 TX request */ -#define LL_DMAMUX_REQ_TIM1_CH1 0x00000014U /*!< DMAMUX TIM1 CH1 request */ -#define LL_DMAMUX_REQ_TIM1_CH2 0x00000015U /*!< DMAMUX TIM1 CH2 request */ -#define LL_DMAMUX_REQ_TIM1_CH3 0x00000016U /*!< DMAMUX TIM1 CH3 request */ -#define LL_DMAMUX_REQ_TIM1_CH4 0x00000017U /*!< DMAMUX TIM1 CH4 request */ -#define LL_DMAMUX_REQ_TIM1_TRIG_COM 0x00000018U /*!< DMAMUX TIM1 TRIG COM request */ -#define LL_DMAMUX_REQ_TIM1_UP 0x00000019U /*!< DMAMUX TIM1 UP request */ -#define LL_DMAMUX_REQ_TIM3_CH1 0x00000020U /*!< DMAMUX TIM3 CH1 request */ -#define LL_DMAMUX_REQ_TIM3_CH2 0x00000021U /*!< DMAMUX TIM3 CH2 request */ -#define LL_DMAMUX_REQ_TIM3_CH3 0x00000022U /*!< DMAMUX TIM3 CH3 request */ -#define LL_DMAMUX_REQ_TIM3_CH4 0x00000023U /*!< DMAMUX TIM3 CH4 request */ -#define LL_DMAMUX_REQ_TIM3_TRIG 0x00000024U /*!< DMAMUX TIM3 TRIG request */ -#define LL_DMAMUX_REQ_TIM3_UP 0x00000025U /*!< DMAMUX TIM3 UP request */ -#define LL_DMAMUX_REQ_TIM16_CH1 0x0000002CU /*!< DMAMUX TIM16 CH1 request */ +#define LL_DMAMUX_REQ_MEM2MEM 0x00000000U /*!< memory to memory transfer */ +#define LL_DMAMUX_REQ_GENERATOR0 0x00000001U /*!< DMAMUX request generator 0 */ +#define LL_DMAMUX_REQ_GENERATOR1 0x00000002U /*!< DMAMUX request generator 1 */ +#define LL_DMAMUX_REQ_GENERATOR2 0x00000003U /*!< DMAMUX request generator 2 */ +#define LL_DMAMUX_REQ_GENERATOR3 0x00000004U /*!< DMAMUX request generator 3 */ +#define LL_DMAMUX_REQ_ADC1 0x00000005U /*!< DMAMUX ADC1 request */ +#define LL_DMAMUX_REQ_I2C1_RX 0x0000000AU /*!< DMAMUX I2C1 RX request */ +#define LL_DMAMUX_REQ_I2C1_TX 0x0000000BU /*!< DMAMUX I2C1 TX request */ +#if defined(I2C2) +#define LL_DMAMUX_REQ_I2C2_RX 0x0000000CU /*!< DMAMUX I2C2 RX request */ +#define LL_DMAMUX_REQ_I2C2_TX 0x0000000DU /*!< DMAMUX I2C2 TX request */ +#endif /* I2C2 */ +#define LL_DMAMUX_REQ_SPI1_RX 0x00000010U /*!< DMAMUX SPI1 RX request */ +#define LL_DMAMUX_REQ_SPI1_TX 0x00000011U /*!< DMAMUX SPI1 TX request */ +#if defined(SPI2) +#define LL_DMAMUX_REQ_SPI2_RX 0x00000012U /*!< DMAMUX SPI2 RX request */ +#define LL_DMAMUX_REQ_SPI2_TX 0x00000013U /*!< DMAMUX SPI2 TX request */ +#endif /* SPI2 */ +#define LL_DMAMUX_REQ_TIM1_CH1 0x00000014U /*!< DMAMUX TIM1 CH1 request */ +#define LL_DMAMUX_REQ_TIM1_CH2 0x00000015U /*!< DMAMUX TIM1 CH2 request */ +#define LL_DMAMUX_REQ_TIM1_CH3 0x00000016U /*!< DMAMUX TIM1 CH3 request */ +#define LL_DMAMUX_REQ_TIM1_CH4 0x00000017U /*!< DMAMUX TIM1 CH4 request */ +#define LL_DMAMUX_REQ_TIM1_TRIG_COM 0x00000018U /*!< DMAMUX TIM1 TRIG COM request */ +#define LL_DMAMUX_REQ_TIM1_UP 0x00000019U /*!< DMAMUX TIM1 UP request */ +#if defined(TIM2) +#define LL_DMAMUX_REQ_TIM2_CH1 0x0000001AU /*!< DMAMUX TIM2 CH1 request */ +#define LL_DMAMUX_REQ_TIM2_CH2 0x0000001BU /*!< DMAMUX TIM2 CH2 request */ +#define LL_DMAMUX_REQ_TIM2_CH3 0x0000001CU /*!< DMAMUX TIM2 CH3 request */ +#define LL_DMAMUX_REQ_TIM2_CH4 0x0000001DU /*!< DMAMUX TIM2 CH4 request */ +#define LL_DMAMUX_REQ_TIM2_TRIG 0x0000001EU /*!< DMAMUX TIM2 TRIG request */ +#define LL_DMAMUX_REQ_TIM2_UP 0x0000001FU /*!< DMAMUX TIM2 UP request */ +#endif /* TIM2 */ +#define LL_DMAMUX_REQ_TIM3_CH1 0x00000020U /*!< DMAMUX TIM3 CH1 request */ +#define LL_DMAMUX_REQ_TIM3_CH2 0x00000021U /*!< DMAMUX TIM3 CH2 request */ +#define LL_DMAMUX_REQ_TIM3_CH3 0x00000022U /*!< DMAMUX TIM3 CH3 request */ +#define LL_DMAMUX_REQ_TIM3_CH4 0x00000023U /*!< DMAMUX TIM3 CH4 request */ +#define LL_DMAMUX_REQ_TIM3_TRIG 0x00000024U /*!< DMAMUX TIM3 TRIG request */ +#define LL_DMAMUX_REQ_TIM3_UP 0x00000025U /*!< DMAMUX TIM3 UP request */ +#define LL_DMAMUX_REQ_TIM16_CH1 0x0000002CU /*!< DMAMUX TIM16 CH1 request */ #define LL_DMAMUX_REQ_TIM16_TRIG_COM 0x0000002DU /*!< DMAMUX TIM16 TRIG COM request */ -#define LL_DMAMUX_REQ_TIM16_UP 0x0000002EU /*!< DMAMUX TIM16 UP request */ -#define LL_DMAMUX_REQ_TIM17_CH1 0x0000002FU /*!< DMAMUX TIM17 CH1 request */ +#define LL_DMAMUX_REQ_TIM16_UP 0x0000002EU /*!< DMAMUX TIM16 UP request */ +#define LL_DMAMUX_REQ_TIM17_CH1 0x0000002FU /*!< DMAMUX TIM17 CH1 request */ #define LL_DMAMUX_REQ_TIM17_TRIG_COM 0x00000030U /*!< DMAMUX TIM17 TRIG COM request */ -#define LL_DMAMUX_REQ_TIM17_UP 0x00000031U /*!< DMAMUX TIM17 UP request */ -#define LL_DMAMUX_REQ_USART1_RX 0x00000032U /*!< DMAMUX USART1 RX request */ -#define LL_DMAMUX_REQ_USART1_TX 0x00000033U /*!< DMAMUX USART1 TX request */ -#define LL_DMAMUX_REQ_USART2_RX 0x00000034U /*!< DMAMUX USART2 RX request */ -#define LL_DMAMUX_REQ_USART2_TX 0x00000035U /*!< DMAMUX USART2 TX request */ - +#define LL_DMAMUX_REQ_TIM17_UP 0x00000031U /*!< DMAMUX TIM17 UP request */ +#define LL_DMAMUX_REQ_USART1_RX 0x00000032U /*!< DMAMUX USART1 RX request */ +#define LL_DMAMUX_REQ_USART1_TX 0x00000033U /*!< DMAMUX USART1 TX request */ +#define LL_DMAMUX_REQ_USART2_RX 0x00000034U /*!< DMAMUX USART2 RX request */ +#define LL_DMAMUX_REQ_USART2_TX 0x00000035U /*!< DMAMUX USART2 TX request */ /** * @} */ @@ -145,6 +179,12 @@ extern "C" { #define LL_DMAMUX_CHANNEL_0 0x00000000U /*!< DMAMUX Channel 0 connected to DMA1 Channel 1 */ #define LL_DMAMUX_CHANNEL_1 0x00000001U /*!< DMAMUX Channel 1 connected to DMA1 Channel 2 */ #define LL_DMAMUX_CHANNEL_2 0x00000002U /*!< DMAMUX Channel 2 connected to DMA1 Channel 3 */ +#if defined(DMAMUX1_Channel3) +#define LL_DMAMUX_CHANNEL_3 0x00000003U /*!< DMAMUX Channel 3 connected to DMA1 Channel 4 */ +#endif /* DMAMUX1_Channel3 */ +#if defined(DMAMUX1_Channel4) +#define LL_DMAMUX_CHANNEL_4 0x00000004U /*!< DMAMUX Channel 4 connected to DMA1 Channel 5 */ +#endif /* DMAMUX1_Channel4 */ /** * @} */ @@ -152,13 +192,13 @@ extern "C" { /** @defgroup DMAMUX_LL_EC_SYNC_NO Synchronization Signal Polarity * @{ */ -#define LL_DMAMUX_SYNC_NO_EVENT 0x00000000U /*!< All requests are blocked */ +#define LL_DMAMUX_SYNC_NO_EVENT 0x00000000U /*!< All requests are blocked */ #define LL_DMAMUX_SYNC_POL_RISING DMAMUX_CxCR_SPOL_0 /*!< Synchronization on event - on rising edge */ + on rising edge */ #define LL_DMAMUX_SYNC_POL_FALLING DMAMUX_CxCR_SPOL_1 /*!< Synchronization on event - on falling edge */ + on falling edge */ #define LL_DMAMUX_SYNC_POL_RISING_FALLING (DMAMUX_CxCR_SPOL_0 | DMAMUX_CxCR_SPOL_1) /*!< Synchronization on event on - rising and falling edge */ + rising and falling edge */ /** * @} */ @@ -185,7 +225,8 @@ extern "C" { #define LL_DMAMUX_SYNC_DMAMUX_CH0 DMAMUX_CxCR_SYNC_ID_4 /*!< Synchronization signal from DMAMUX channel0 Event */ #define LL_DMAMUX_SYNC_DMAMUX_CH1 (DMAMUX_CxCR_SYNC_ID_4 | DMAMUX_CxCR_SYNC_ID_0) /*!< Synchronization signal from DMAMUX channel1 Event */ #define LL_DMAMUX_SYNC_DMAMUX_CH2 (DMAMUX_CxCR_SYNC_ID_4 | DMAMUX_CxCR_SYNC_ID_1) /*!< Synchronization signal from DMAMUX channel2 Event */ -#define LL_DMAMUX_SYNC_TIM14_OC (DMAMUX_CxCR_SYNC_ID_4 | DMAMUX_CxCR_SYNC_ID_2 | DMAMUX_CxCR_SYNC_ID_1) /*!< Synchronization signal from TIM14 OC */ +#define LL_DMAMUX_SYNC_DMAMUX_CH3 (DMAMUX_CxCR_SYNC_ID_4 | DMAMUX_CxCR_SYNC_ID_1 | DMAMUX_CxCR_SYNC_ID_0) /*!< Synchronization signal from DMAMUX channel3 Event */ +#define LL_DMAMUX_SYNC_TIM14_OC (DMAMUX_CxCR_SYNC_ID_4 | DMAMUX_CxCR_SYNC_ID_2 | DMAMUX_CxCR_SYNC_ID_0) /*!< Synchronization signal from TIM14 OC */ /** * @} */ @@ -241,6 +282,7 @@ extern "C" { #define LL_DMAMUX_REQ_GEN_DMAMUX_CH0 DMAMUX_RGxCR_SIG_ID_4 /*!< Request signal generation from DMAMUX channel0 Event */ #define LL_DMAMUX_REQ_GEN_DMAMUX_CH1 (DMAMUX_RGxCR_SIG_ID_4 | DMAMUX_RGxCR_SIG_ID_0) /*!< Request signal generation from DMAMUX channel1 Event */ #define LL_DMAMUX_REQ_GEN_DMAMUX_CH2 (DMAMUX_RGxCR_SIG_ID_4 | DMAMUX_RGxCR_SIG_ID_1) /*!< Request signal generation from DMAMUX channel2 Event */ +#define LL_DMAMUX_REQ_GEN_DMAMUX_CH3 (DMAMUX_RGxCR_SIG_ID_4 | DMAMUX_RGxCR_SIG_ID_1 | DMAMUX_RGxCR_SIG_ID_0) /*!< Request signal generation from DMAMUX channel3 Event */ #define LL_DMAMUX_REQ_GEN_TIM14_OC (DMAMUX_RGxCR_SIG_ID_4 | DMAMUX_RGxCR_SIG_ID_2 | DMAMUX_RGxCR_SIG_ID_1) /*!< Request signal generation from TIM14 OC */ /** * @} @@ -292,13 +334,15 @@ extern "C" { */ /** * @brief Set DMAMUX request ID for DMAMUX Channel x. - * @note DMAMUX channel 0 to 2 are mapped to DMA1 channel 1 to 3. + * @note DMAMUX channel 0 to 4 are mapped to DMA1 channel 1 to 5. * @rmtoll CxCR DMAREQ_ID LL_DMAMUX_SetRequestID * @param DMAMUXx DMAMUXx Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) * @param Request This parameter can be one of the following values: * @arg @ref LL_DMAMUX_REQ_MEM2MEM * @arg @ref LL_DMAMUX_REQ_GENERATOR0 @@ -308,14 +352,24 @@ extern "C" { * @arg @ref LL_DMAMUX_REQ_ADC1 * @arg @ref LL_DMAMUX_REQ_I2C1_RX * @arg @ref LL_DMAMUX_REQ_I2C1_TX + * @arg @ref LL_DMAMUX_REQ_I2C2_RX (*) + * @arg @ref LL_DMAMUX_REQ_I2C2_TX (*) * @arg @ref LL_DMAMUX_REQ_SPI1_RX * @arg @ref LL_DMAMUX_REQ_SPI1_TX + * @arg @ref LL_DMAMUX_REQ_SPI2_RX (*) + * @arg @ref LL_DMAMUX_REQ_SPI2_TX (*) * @arg @ref LL_DMAMUX_REQ_TIM1_CH1 * @arg @ref LL_DMAMUX_REQ_TIM1_CH2 * @arg @ref LL_DMAMUX_REQ_TIM1_CH3 * @arg @ref LL_DMAMUX_REQ_TIM1_CH4 * @arg @ref LL_DMAMUX_REQ_TIM1_TRIG_COM * @arg @ref LL_DMAMUX_REQ_TIM1_UP + * @arg @ref LL_DMAMUX_REQ_TIM2_CH1 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH2 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH3 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH4 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_TRIG_COM (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_UP (*) * @arg @ref LL_DMAMUX_REQ_TIM3_CH1 * @arg @ref LL_DMAMUX_REQ_TIM3_CH2 * @arg @ref LL_DMAMUX_REQ_TIM3_CH3 @@ -332,9 +386,10 @@ extern "C" { * @arg @ref LL_DMAMUX_REQ_USART1_TX * @arg @ref LL_DMAMUX_REQ_USART2_RX * @arg @ref LL_DMAMUX_REQ_USART2_TX + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetRequestID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, uint32_t Request) +__STATIC_INLINE void LL_DMAMUX_SetRequestID(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, uint32_t Request) { (void)(DMAMUXx); MODIFY_REG((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_DMAREQ_ID, Request); @@ -342,13 +397,15 @@ __STATIC_INLINE void LL_DMAMUX_SetRequestID(DMAMUX_Channel_TypeDef *DMAMUXx, uin /** * @brief Get DMAMUX request ID for DMAMUX Channel x. - * @note DMAMUX channel 0 to 2 are mapped to DMA1 channel 1 to 3. + * @note DMAMUX channel 0 to 4 are mapped to DMA1 channel 1 to 5. * @rmtoll CxCR DMAREQ_ID LL_DMAMUX_GetRequestID * @param DMAMUXx DMAMUXx Instance * @param Channel This parameter can be one of the following values: * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) * @retval Returned value can be one of the following values: * @arg @ref LL_DMAMUX_REQ_MEM2MEM * @arg @ref LL_DMAMUX_REQ_GENERATOR0 @@ -358,14 +415,24 @@ __STATIC_INLINE void LL_DMAMUX_SetRequestID(DMAMUX_Channel_TypeDef *DMAMUXx, uin * @arg @ref LL_DMAMUX_REQ_ADC1 * @arg @ref LL_DMAMUX_REQ_I2C1_RX * @arg @ref LL_DMAMUX_REQ_I2C1_TX + * @arg @ref LL_DMAMUX_REQ_I2C2_RX (*) + * @arg @ref LL_DMAMUX_REQ_I2C2_TX (*) * @arg @ref LL_DMAMUX_REQ_SPI1_RX * @arg @ref LL_DMAMUX_REQ_SPI1_TX + * @arg @ref LL_DMAMUX_REQ_SPI2_RX (*) + * @arg @ref LL_DMAMUX_REQ_SPI2_TX (*) * @arg @ref LL_DMAMUX_REQ_TIM1_CH1 * @arg @ref LL_DMAMUX_REQ_TIM1_CH2 * @arg @ref LL_DMAMUX_REQ_TIM1_CH3 * @arg @ref LL_DMAMUX_REQ_TIM1_CH4 * @arg @ref LL_DMAMUX_REQ_TIM1_TRIG_COM * @arg @ref LL_DMAMUX_REQ_TIM1_UP + * @arg @ref LL_DMAMUX_REQ_TIM2_CH1 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH2 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH3 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_CH4 (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_TRIG_COM (*) + * @arg @ref LL_DMAMUX_REQ_TIM2_UP (*) * @arg @ref LL_DMAMUX_REQ_TIM3_CH1 * @arg @ref LL_DMAMUX_REQ_TIM3_CH2 * @arg @ref LL_DMAMUX_REQ_TIM3_CH3 @@ -382,8 +449,9 @@ __STATIC_INLINE void LL_DMAMUX_SetRequestID(DMAMUX_Channel_TypeDef *DMAMUXx, uin * @arg @ref LL_DMAMUX_REQ_USART1_TX * @arg @ref LL_DMAMUX_REQ_USART2_RX * @arg @ref LL_DMAMUX_REQ_USART2_TX + * @note (*) Availability depends on devices */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetRequestID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetRequestID(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return (uint32_t)(READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_DMAREQ_ID)); @@ -398,10 +466,14 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetRequestID(DMAMUX_Channel_TypeDef *DMAMUXx, * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @param RequestNb This parameter must be a value between Min_Data = 1 and Max_Data = 32. * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetSyncRequestNb(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, uint32_t RequestNb) +__STATIC_INLINE void LL_DMAMUX_SetSyncRequestNb(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, + uint32_t RequestNb) { (void)(DMAMUXx); MODIFY_REG((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_NBREQ, ((RequestNb - 1U) << DMAMUX_CxCR_NBREQ_Pos)); @@ -416,9 +488,12 @@ __STATIC_INLINE void LL_DMAMUX_SetSyncRequestNb(DMAMUX_Channel_TypeDef *DMAMUXx, * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval Between Min_Data = 1 and Max_Data = 32 */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetSyncRequestNb(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetSyncRequestNb(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return (uint32_t)(((READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_NBREQ)) >> DMAMUX_CxCR_NBREQ_Pos) + 1U); @@ -432,6 +507,9 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetSyncRequestNb(DMAMUX_Channel_TypeDef *DMAM * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @param Polarity This parameter can be one of the following values: * @arg @ref LL_DMAMUX_SYNC_NO_EVENT * @arg @ref LL_DMAMUX_SYNC_POL_RISING @@ -439,7 +517,8 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetSyncRequestNb(DMAMUX_Channel_TypeDef *DMAM * @arg @ref LL_DMAMUX_SYNC_POL_RISING_FALLING * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetSyncPolarity(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, uint32_t Polarity) +__STATIC_INLINE void LL_DMAMUX_SetSyncPolarity(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, + uint32_t Polarity) { (void)(DMAMUXx); MODIFY_REG((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SPOL, Polarity); @@ -453,13 +532,16 @@ __STATIC_INLINE void LL_DMAMUX_SetSyncPolarity(DMAMUX_Channel_TypeDef *DMAMUXx, * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval Returned value can be one of the following values: * @arg @ref LL_DMAMUX_SYNC_NO_EVENT * @arg @ref LL_DMAMUX_SYNC_POL_RISING * @arg @ref LL_DMAMUX_SYNC_POL_FALLING * @arg @ref LL_DMAMUX_SYNC_POL_RISING_FALLING */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetSyncPolarity(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetSyncPolarity(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return (uint32_t)(READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SPOL)); @@ -473,9 +555,12 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetSyncPolarity(DMAMUX_Channel_TypeDef *DMAMU * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_EnableEventGeneration(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE void LL_DMAMUX_EnableEventGeneration(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); SET_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_EGE); @@ -489,9 +574,12 @@ __STATIC_INLINE void LL_DMAMUX_EnableEventGeneration(DMAMUX_Channel_TypeDef *DMA * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_DisableEventGeneration(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE void LL_DMAMUX_DisableEventGeneration(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); CLEAR_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_EGE); @@ -505,9 +593,12 @@ __STATIC_INLINE void LL_DMAMUX_DisableEventGeneration(DMAMUX_Channel_TypeDef *DM * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledEventGeneration(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledEventGeneration(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return ((READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_EGE) == (DMAMUX_CxCR_EGE)) ? 1UL : 0UL); @@ -521,9 +612,12 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledEventGeneration(DMAMUX_Channel_TypeD * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_EnableSync(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE void LL_DMAMUX_EnableSync(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); SET_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SE); @@ -537,9 +631,12 @@ __STATIC_INLINE void LL_DMAMUX_EnableSync(DMAMUX_Channel_TypeDef *DMAMUXx, uint3 * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_DisableSync(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE void LL_DMAMUX_DisableSync(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); CLEAR_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SE); @@ -553,9 +650,12 @@ __STATIC_INLINE void LL_DMAMUX_DisableSync(DMAMUX_Channel_TypeDef *DMAMUXx, uint * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledSync(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledSync(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return ((READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SE) == (DMAMUX_CxCR_SE)) ? 1UL : 0UL); @@ -569,6 +669,8 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledSync(DMAMUX_Channel_TypeDef *DMAMUXx * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) * @param SyncID This parameter can be one of the following values: * @arg @ref LL_DMAMUX_SYNC_EXTI_LINE0 * @arg @ref LL_DMAMUX_SYNC_EXTI_LINE1 @@ -589,10 +691,12 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledSync(DMAMUX_Channel_TypeDef *DMAMUXx * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH0 * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH1 * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH2 + * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH3 (*) * @arg @ref LL_DMAMUX_SYNC_TIM14_OC + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetSyncID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, uint32_t SyncID) +__STATIC_INLINE void LL_DMAMUX_SetSyncID(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel, uint32_t SyncID) { (void)(DMAMUXx); MODIFY_REG((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SYNC_ID, SyncID); @@ -606,6 +710,8 @@ __STATIC_INLINE void LL_DMAMUX_SetSyncID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32 * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) * @retval Returned value can be one of the following values: * @arg @ref LL_DMAMUX_SYNC_EXTI_LINE0 * @arg @ref LL_DMAMUX_SYNC_EXTI_LINE1 @@ -626,9 +732,11 @@ __STATIC_INLINE void LL_DMAMUX_SetSyncID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32 * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH0 * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH1 * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH2 + * @arg @ref LL_DMAMUX_SYNC_DMAMUX_CH3 (*) * @arg @ref LL_DMAMUX_SYNC_TIM14_OC + * @note (*) Availability depends on devices */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetSyncID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetSyncID(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return (uint32_t)(READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SYNC_ID)); @@ -645,7 +753,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetSyncID(DMAMUX_Channel_TypeDef *DMAMUXx, ui * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval None */ -__STATIC_INLINE void LL_DMAMUX_EnableRequestGen(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE void LL_DMAMUX_EnableRequestGen(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); SET_BIT(((DMAMUX_RequestGen_TypeDef *)((uint32_t)((uint32_t)DMAMUX1_RequestGenerator0 + (DMAMUX_RGCR_SIZE * @@ -663,7 +771,7 @@ __STATIC_INLINE void LL_DMAMUX_EnableRequestGen(DMAMUX_Channel_TypeDef *DMAMUXx, * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval None */ -__STATIC_INLINE void LL_DMAMUX_DisableRequestGen(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE void LL_DMAMUX_DisableRequestGen(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); CLEAR_BIT(((DMAMUX_RequestGen_TypeDef *)((uint32_t)((uint32_t)DMAMUX1_RequestGenerator0 + (DMAMUX_RGCR_SIZE * @@ -681,7 +789,8 @@ __STATIC_INLINE void LL_DMAMUX_DisableRequestGen(DMAMUX_Channel_TypeDef *DMAMUXx * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledRequestGen(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledRequestGen(const DMAMUX_Channel_TypeDef *DMAMUXx, + uint32_t RequestGenChannel) { (void)(DMAMUXx); return ((READ_BIT(((DMAMUX_RequestGen_TypeDef *)((uint32_t)((uint32_t)DMAMUX1_RequestGenerator0 + (DMAMUX_RGCR_SIZE * @@ -705,7 +814,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledRequestGen(DMAMUX_Channel_TypeDef *D * @arg @ref LL_DMAMUX_REQ_GEN_POL_RISING_FALLING * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetRequestGenPolarity(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel, +__STATIC_INLINE void LL_DMAMUX_SetRequestGenPolarity(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel, uint32_t Polarity) { (void)(DMAMUXx); @@ -728,7 +837,8 @@ __STATIC_INLINE void LL_DMAMUX_SetRequestGenPolarity(DMAMUX_Channel_TypeDef *DMA * @arg @ref LL_DMAMUX_REQ_GEN_POL_FALLING * @arg @ref LL_DMAMUX_REQ_GEN_POL_RISING_FALLING */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetRequestGenPolarity(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetRequestGenPolarity(const DMAMUX_Channel_TypeDef *DMAMUXx, + uint32_t RequestGenChannel) { (void)(DMAMUXx); return (uint32_t)(READ_BIT(((DMAMUX_RequestGen_TypeDef *)((uint32_t)((uint32_t)DMAMUX1_RequestGenerator0 + @@ -750,7 +860,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetRequestGenPolarity(DMAMUX_Channel_TypeDef * @param RequestNb This parameter must be a value between Min_Data = 1 and Max_Data = 32. * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetGenRequestNb(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel, +__STATIC_INLINE void LL_DMAMUX_SetGenRequestNb(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel, uint32_t RequestNb) { (void)(DMAMUXx); @@ -770,7 +880,7 @@ __STATIC_INLINE void LL_DMAMUX_SetGenRequestNb(DMAMUX_Channel_TypeDef *DMAMUXx, * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval Between Min_Data = 1 and Max_Data = 32 */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetGenRequestNb(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetGenRequestNb(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); return (uint32_t)((READ_BIT(((DMAMUX_RequestGen_TypeDef *)((uint32_t)((uint32_t)DMAMUX1_RequestGenerator0 + @@ -808,10 +918,12 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetGenRequestNb(DMAMUX_Channel_TypeDef *DMAMU * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH0 * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH1 * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH2 + * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH3 (*) * @arg @ref LL_DMAMUX_REQ_GEN_TIM14_OC + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_SetRequestSignalID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel, +__STATIC_INLINE void LL_DMAMUX_SetRequestSignalID(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel, uint32_t RequestSignalID) { (void)(DMAMUXx); @@ -849,9 +961,11 @@ __STATIC_INLINE void LL_DMAMUX_SetRequestSignalID(DMAMUX_Channel_TypeDef *DMAMUX * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH0 * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH1 * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH2 + * @arg @ref LL_DMAMUX_REQ_GEN_DMAMUX_CH3 (*) * @arg @ref LL_DMAMUX_REQ_GEN_TIM14_OC + * @note (*) Availability depends on devices */ -__STATIC_INLINE uint32_t LL_DMAMUX_GetRequestSignalID(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE uint32_t LL_DMAMUX_GetRequestSignalID(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); return (uint32_t)(READ_BIT(((DMAMUX_RequestGen_TypeDef *)((uint32_t)((uint32_t)DMAMUX1_RequestGenerator0 + @@ -874,7 +988,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_GetRequestSignalID(DMAMUX_Channel_TypeDef *DM * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO0(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO0(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_ChannelStatus->CSR, DMAMUX_CSR_SOF0) == (DMAMUX_CSR_SOF0)) ? 1UL : 0UL); @@ -886,7 +1000,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO0(DMAMUX_Channel_TypeDef *DMAM * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO1(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO1(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_ChannelStatus->CSR, DMAMUX_CSR_SOF1) == (DMAMUX_CSR_SOF1)) ? 1UL : 0UL);; @@ -898,12 +1012,39 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO1(DMAMUX_Channel_TypeDef *DMAM * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO2(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO2(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_ChannelStatus->CSR, DMAMUX_CSR_SOF2) == (DMAMUX_CSR_SOF2)) ? 1UL : 0UL);; } +#if defined(DMAMUX_CSR_SOF3) +/** + * @brief Get Synchronization Event Overrun Flag Channel 3. + * @rmtoll CSR SOF3 LL_DMAMUX_IsActiveFlag_SO3 + * @param DMAMUXx DMAMUXx DMAMUXx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO3(const DMAMUX_Channel_TypeDef *DMAMUXx) +{ + (void)(DMAMUXx); + return ((READ_BIT(DMAMUX1_ChannelStatus->CSR, DMAMUX_CSR_SOF3) == (DMAMUX_CSR_SOF3)) ? 1UL : 0UL);; +} +#endif /* DMAMUX_CSR_SOF3 */ + +#if defined(DMAMUX_CSR_SOF4) +/** + * @brief Get Synchronization Event Overrun Flag Channel 4. + * @rmtoll CSR SOF4 LL_DMAMUX_IsActiveFlag_SO4 + * @param DMAMUXx DMAMUXx DMAMUXx Instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO4(const DMAMUX_Channel_TypeDef *DMAMUXx) +{ + (void)(DMAMUXx); + return ((READ_BIT(DMAMUX1_ChannelStatus->CSR, DMAMUX_CSR_SOF4) == (DMAMUX_CSR_SOF4)) ? 1UL : 0UL);; +} +#endif /* DMAMUX_CSR_SOF4 */ /** * @brief Get Request Generator 0 Trigger Event Overrun Flag. @@ -911,7 +1052,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_SO2(DMAMUX_Channel_TypeDef *DMAM * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO0(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO0(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_RequestGenStatus->RGSR, DMAMUX_RGSR_OF0) == (DMAMUX_RGSR_OF0)) ? 1UL : 0UL);; @@ -923,7 +1064,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO0(DMAMUX_Channel_TypeDef *DMA * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO1(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO1(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_RequestGenStatus->RGSR, DMAMUX_RGSR_OF1) == (DMAMUX_RGSR_OF1)) ? 1UL : 0UL);; @@ -935,7 +1076,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO1(DMAMUX_Channel_TypeDef *DMA * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO2(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO2(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_RequestGenStatus->RGSR, DMAMUX_RGSR_OF2) == (DMAMUX_RGSR_OF2)) ? 1UL : 0UL);; @@ -947,7 +1088,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO2(DMAMUX_Channel_TypeDef *DMA * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO3(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO3(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); return ((READ_BIT(DMAMUX1_RequestGenStatus->RGSR, DMAMUX_RGSR_OF3) == (DMAMUX_RGSR_OF3)) ? 1UL : 0UL);; @@ -959,7 +1100,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsActiveFlag_RGO3(DMAMUX_Channel_TypeDef *DMA * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO0(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO0(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_ChannelStatus->CFR, DMAMUX_CFR_CSOF0); @@ -971,7 +1112,7 @@ __STATIC_INLINE void LL_DMAMUX_ClearFlag_SO0(DMAMUX_Channel_TypeDef *DMAMUXx) * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO1(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO1(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_ChannelStatus->CFR, DMAMUX_CFR_CSOF1); @@ -983,19 +1124,47 @@ __STATIC_INLINE void LL_DMAMUX_ClearFlag_SO1(DMAMUX_Channel_TypeDef *DMAMUXx) * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO2(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO2(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_ChannelStatus->CFR, DMAMUX_CFR_CSOF2); } +#if defined(DMAMUX_CFR_CSOF3) +/** + * @brief Clear Synchronization Event Overrun Flag Channel 3. + * @rmtoll CFR CSOF3 LL_DMAMUX_ClearFlag_SO3 + * @param DMAMUXx DMAMUXx DMAMUXx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO3(const DMAMUX_Channel_TypeDef *DMAMUXx) +{ + (void)(DMAMUXx); + SET_BIT(DMAMUX1_ChannelStatus->CFR, DMAMUX_CFR_CSOF3); +} +#endif /* DMAMUX_CFR_CSOF3 */ + +#if defined(DMAMUX_CFR_CSOF4) +/** + * @brief Clear Synchronization Event Overrun Flag Channel 4. + * @rmtoll CFR CSOF4 LL_DMAMUX_ClearFlag_SO4 + * @param DMAMUXx DMAMUXx DMAMUXx Instance + * @retval None + */ +__STATIC_INLINE void LL_DMAMUX_ClearFlag_SO4(const DMAMUX_Channel_TypeDef *DMAMUXx) +{ + (void)(DMAMUXx); + SET_BIT(DMAMUX1_ChannelStatus->CFR, DMAMUX_CFR_CSOF4); +} +#endif /* DMAMUX_CFR_CSOF4 */ + /** * @brief Clear Request Generator 0 Trigger Event Overrun Flag. * @rmtoll RGCFR COF0 LL_DMAMUX_ClearFlag_RGO0 * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO0(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO0(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_RequestGenStatus->RGCFR, DMAMUX_RGCFR_COF0); @@ -1007,7 +1176,7 @@ __STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO0(DMAMUX_Channel_TypeDef *DMAMUXx) * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO1(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO1(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_RequestGenStatus->RGCFR, DMAMUX_RGCFR_COF1); @@ -1019,7 +1188,7 @@ __STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO1(DMAMUX_Channel_TypeDef *DMAMUXx) * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO2(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO2(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_RequestGenStatus->RGCFR, DMAMUX_RGCFR_COF2); @@ -1031,7 +1200,7 @@ __STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO2(DMAMUX_Channel_TypeDef *DMAMUXx) * @param DMAMUXx DMAMUXx DMAMUXx Instance * @retval None */ -__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO3(DMAMUX_Channel_TypeDef *DMAMUXx) +__STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO3(const DMAMUX_Channel_TypeDef *DMAMUXx) { (void)(DMAMUXx); SET_BIT(DMAMUX1_RequestGenStatus->RGCFR, DMAMUX_RGCFR_COF3); @@ -1053,9 +1222,12 @@ __STATIC_INLINE void LL_DMAMUX_ClearFlag_RGO3(DMAMUX_Channel_TypeDef *DMAMUXx) * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_EnableIT_SO(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE void LL_DMAMUX_EnableIT_SO(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); SET_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SOIE); @@ -1069,9 +1241,12 @@ __STATIC_INLINE void LL_DMAMUX_EnableIT_SO(DMAMUX_Channel_TypeDef *DMAMUXx, uint * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval None */ -__STATIC_INLINE void LL_DMAMUX_DisableIT_SO(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE void LL_DMAMUX_DisableIT_SO(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); CLEAR_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SOIE); @@ -1085,9 +1260,12 @@ __STATIC_INLINE void LL_DMAMUX_DisableIT_SO(DMAMUX_Channel_TypeDef *DMAMUXx, uin * @arg @ref LL_DMAMUX_CHANNEL_0 * @arg @ref LL_DMAMUX_CHANNEL_1 * @arg @ref LL_DMAMUX_CHANNEL_2 + * @arg @ref LL_DMAMUX_CHANNEL_3 (*) + * @arg @ref LL_DMAMUX_CHANNEL_4 (*) + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledIT_SO(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledIT_SO(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t Channel) { (void)(DMAMUXx); return (((READ_BIT((DMAMUX1_Channel0 + Channel)->CCR, DMAMUX_CxCR_SOIE)) == (DMAMUX_CxCR_SOIE)) ? 1UL : 0UL); @@ -1104,7 +1282,7 @@ __STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledIT_SO(DMAMUX_Channel_TypeDef *DMAMUX * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval None */ -__STATIC_INLINE void LL_DMAMUX_EnableIT_RGO(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE void LL_DMAMUX_EnableIT_RGO(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); SET_BIT((DMAMUX1_RequestGenerator0 + RequestGenChannel)->RGCR, DMAMUX_RGxCR_OIE); @@ -1121,7 +1299,7 @@ __STATIC_INLINE void LL_DMAMUX_EnableIT_RGO(DMAMUX_Channel_TypeDef *DMAMUXx, uin * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval None */ -__STATIC_INLINE void LL_DMAMUX_DisableIT_RGO(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE void LL_DMAMUX_DisableIT_RGO(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); CLEAR_BIT((DMAMUX1_RequestGenerator0 + RequestGenChannel)->RGCR, DMAMUX_RGxCR_OIE); @@ -1138,7 +1316,7 @@ __STATIC_INLINE void LL_DMAMUX_DisableIT_RGO(DMAMUX_Channel_TypeDef *DMAMUXx, ui * @arg @ref LL_DMAMUX_REQ_GEN_3 * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledIT_RGO(DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) +__STATIC_INLINE uint32_t LL_DMAMUX_IsEnabledIT_RGO(const DMAMUX_Channel_TypeDef *DMAMUXx, uint32_t RequestGenChannel) { (void)(DMAMUXx); return ((READ_BIT((DMAMUX1_RequestGenerator0 + RequestGenChannel)->RGCR, DMAMUX_RGxCR_OIE) == (DMAMUX_RGxCR_OIE)) ? \ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_exti.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_exti.h index 10c26857b..05c469113 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_exti.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_exti.h @@ -61,7 +61,10 @@ typedef struct uint32_t Line_0_31; /*!< Specifies the EXTI lines to be enabled or disabled for Lines in range 0 to 31 This parameter can be any combination of @ref EXTI_LL_EC_LINE */ - +#if defined(EXTI_IMR2_IM36) + uint32_t Line_32_63; /*!< Specifies the EXTI lines to be enabled or disabled for Lines in range 32 to 63 + This parameter can be any combination of @ref EXTI_LL_EC_LINE */ +#endif /* LL_EXTI_LINE_36 */ FunctionalState LineCommand; /*!< Specifies the new state of the selected EXTI lines. This parameter can be set either to ENABLE or DISABLE */ @@ -106,7 +109,13 @@ typedef struct #define LL_EXTI_LINE_25 EXTI_IMR1_IM25 /*!< Extended line 25 */ #define LL_EXTI_LINE_31 EXTI_IMR1_IM31 /*!< Extended line 31 */ #define LL_EXTI_LINE_ALL_0_31 0xFFFFFFFFU /*!< All Extended line */ - +#if defined(EXTI_IMR2_IM34) +#define LL_EXTI_LINE_34 EXTI_IMR2_IM34 /*!< Extended line 34 */ +#endif /* EXTI_IMR2_IM34 */ +#if defined(EXTI_IMR2_IM36) +#define LL_EXTI_LINE_36 EXTI_IMR2_IM36 /*!< Extended line 36 */ +#endif /* EXTI_IMR2_IM36 */ +#define LL_EXTI_LINE_ALL_32_63 0x00000014U /*!< only line 34 & line 36 */ #if defined(USE_FULL_LL_DRIVER) #define LL_EXTI_LINE_NONE 0x00000000U /*!< None Extended line */ #endif /*USE_FULL_LL_DRIVER*/ @@ -128,22 +137,22 @@ typedef struct /** @defgroup EXTI_LL_EC_CONFIG_LINE EXTI CONFIG LINE * @{ */ -#define LL_EXTI_CONFIG_LINE0 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_0 | EXTICR[0] */ -#define LL_EXTI_CONFIG_LINE1 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_8 | EXTICR[0] */ -#define LL_EXTI_CONFIG_LINE2 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_16 | EXTICR[0] */ -#define LL_EXTI_CONFIG_LINE3 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_24 | EXTICR[0] */ -#define LL_EXTI_CONFIG_LINE4 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_0 | EXTICR[1] */ -#define LL_EXTI_CONFIG_LINE5 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_8 | EXTICR[1] */ -#define LL_EXTI_CONFIG_LINE6 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_16 | EXTICR[1] */ -#define LL_EXTI_CONFIG_LINE7 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_24 | EXTICR[1] */ -#define LL_EXTI_CONFIG_LINE8 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_0 | EXTICR[2] */ -#define LL_EXTI_CONFIG_LINE9 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_8 | EXTICR[2] */ -#define LL_EXTI_CONFIG_LINE10 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_16 | EXTICR[2] */ -#define LL_EXTI_CONFIG_LINE11 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_24 | EXTICR[2] */ -#define LL_EXTI_CONFIG_LINE12 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_0 | EXTICR[3] */ -#define LL_EXTI_CONFIG_LINE13 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_8 | EXTICR[3] */ -#define LL_EXTI_CONFIG_LINE14 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_16 | EXTICR[3] */ -#define LL_EXTI_CONFIG_LINE15 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_24 | EXTICR[3] */ +#define LL_EXTI_CONFIG_LINE0 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_0 | EXTICR[0] */ +#define LL_EXTI_CONFIG_LINE1 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_8 | EXTICR[0] */ +#define LL_EXTI_CONFIG_LINE2 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_16 | EXTICR[0] */ +#define LL_EXTI_CONFIG_LINE3 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 0U) /*!< EXTI_POSITION_24 | EXTICR[0] */ +#define LL_EXTI_CONFIG_LINE4 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_0 | EXTICR[1] */ +#define LL_EXTI_CONFIG_LINE5 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_8 | EXTICR[1] */ +#define LL_EXTI_CONFIG_LINE6 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_16 | EXTICR[1] */ +#define LL_EXTI_CONFIG_LINE7 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 1U) /*!< EXTI_POSITION_24 | EXTICR[1] */ +#define LL_EXTI_CONFIG_LINE8 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_0 | EXTICR[2] */ +#define LL_EXTI_CONFIG_LINE9 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_8 | EXTICR[2] */ +#define LL_EXTI_CONFIG_LINE10 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_16 | EXTICR[2] */ +#define LL_EXTI_CONFIG_LINE11 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 2U) /*!< EXTI_POSITION_24 | EXTICR[2] */ +#define LL_EXTI_CONFIG_LINE12 ((0uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_0 | EXTICR[3] */ +#define LL_EXTI_CONFIG_LINE13 ((8uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_8 | EXTICR[3] */ +#define LL_EXTI_CONFIG_LINE14 ((16uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_16 | EXTICR[3] */ +#define LL_EXTI_CONFIG_LINE15 ((24uL << LL_EXTI_REGISTER_PINPOS_SHFT) | 3U) /*!< EXTI_POSITION_24 | EXTICR[3] */ /** * @} */ @@ -215,7 +224,6 @@ typedef struct */ - /* Exported functions --------------------------------------------------------*/ /** @defgroup EXTI_LL_Exported_Functions EXTI Exported Functions * @{ @@ -259,6 +267,25 @@ __STATIC_INLINE void LL_EXTI_EnableIT_0_31(uint32_t ExtiLine) SET_BIT(EXTI->IMR1, ExtiLine); } +#if defined(LL_EXTI_LINE_36) +/** + * @brief Enable ExtiLine Interrupt request for Lines in range 32 to 63 + * @note The reset value for the direct lines (lines from 32 to 34, line + * 39) is set to 1 in order to enable the interrupt by default. + * Bits are set automatically at Power on. + * @rmtoll IMR2 IMx LL_EXTI_EnableIT_32_63 + * @param ExtiLine This parameter can be one of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @arg @ref LL_EXTI_LINE_36 + * @arg @ref LL_EXTI_LINE_ALL_32_63 + * @retval None + */ +__STATIC_INLINE void LL_EXTI_EnableIT_32_63(uint32_t ExtiLine) +{ + SET_BIT(EXTI->IMR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_36 */ + /** * @brief Disable ExtiLine Interrupt request for Lines in range 0 to 31 * @note The reset value for the direct or internal lines (see RM) @@ -294,6 +321,25 @@ __STATIC_INLINE void LL_EXTI_DisableIT_0_31(uint32_t ExtiLine) CLEAR_BIT(EXTI->IMR1, ExtiLine); } +#if defined(LL_EXTI_LINE_36) +/** + * @brief Disable ExtiLine Interrupt request for Lines in range 32 to 63 + * @note The reset value for the direct lines (lines from 32 to 34, line + * 39) is set to 1 in order to enable the interrupt by default. + * Bits are set automatically at Power on. + * @rmtoll IMR2 IMx LL_EXTI_DisableIT_32_63 + * @param ExtiLine This parameter can be one of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @arg @ref LL_EXTI_LINE_36 + * @arg @ref LL_EXTI_LINE_ALL_32_63 + * @retval None + */ +__STATIC_INLINE void LL_EXTI_DisableIT_32_63(uint32_t ExtiLine) +{ + CLEAR_BIT(EXTI->IMR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_36 */ + /** * @brief Disable ExtiLine Interrupt request for Lines in range 0 to 31 * @note The reset value for the direct or internal lines (see RM) @@ -329,6 +375,24 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledIT_0_31(uint32_t ExtiLine) return ((READ_BIT(EXTI->IMR1, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); } +#if defined(LL_EXTI_LINE_36) +/** + * @brief Indicate if ExtiLine Interrupt request is enabled for Lines in range 32 to 63 + * @note The reset value for the direct lines (lines from 32 to 34, line + * 39) is set to 1 in order to enable the interrupt by default. + * Bits are set automatically at Power on. + * @rmtoll IMR2 IMx LL_EXTI_IsEnabledIT_32_63 + * @param ExtiLine This parameter can be one of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @arg @ref LL_EXTI_LINE_36 + * @arg @ref LL_EXTI_LINE_ALL_32_63 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_EXTI_IsEnabledIT_32_63(uint32_t ExtiLine) +{ + return ((READ_BIT(EXTI->IMR2, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); +} +#endif /* LL_EXTI_LINE_36 */ /** * @} */ @@ -370,6 +434,22 @@ __STATIC_INLINE void LL_EXTI_EnableEvent_0_31(uint32_t ExtiLine) } +#if defined(LL_EXTI_LINE_36) +/** + * @brief Enable ExtiLine Event request for Lines in range 32 to 63 + * @rmtoll EMR2 EMx LL_EXTI_EnableEvent_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @arg @ref LL_EXTI_LINE_36 + * @arg @ref LL_EXTI_LINE_ALL_32_63 + * @retval None + */ +__STATIC_INLINE void LL_EXTI_EnableEvent_32_63(uint32_t ExtiLine) +{ + SET_BIT(EXTI->EMR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_36 */ + /** * @brief Disable ExtiLine Event request for Lines in range 0 to 31 * @rmtoll EMR1 EMx LL_EXTI_DisableEvent_0_31 @@ -402,6 +482,22 @@ __STATIC_INLINE void LL_EXTI_DisableEvent_0_31(uint32_t ExtiLine) CLEAR_BIT(EXTI->EMR1, ExtiLine); } +#if defined(LL_EXTI_LINE_36) +/** + * @brief Disable ExtiLine Event request for Lines in range 32 to 63 + * @rmtoll EMR2 EMx LL_EXTI_DisableEvent_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @arg @ref LL_EXTI_LINE_36 + * @arg @ref LL_EXTI_LINE_ALL_32_63 + * @retval None + */ +__STATIC_INLINE void LL_EXTI_DisableEvent_32_63(uint32_t ExtiLine) +{ + CLEAR_BIT(EXTI->EMR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_36 */ + /** * @brief Indicate if ExtiLine Event request is enabled for Lines in range 0 to 31 * @rmtoll EMR1 EMx LL_EXTI_IsEnabledEvent_0_31 @@ -434,6 +530,21 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledEvent_0_31(uint32_t ExtiLine) return ((READ_BIT(EXTI->EMR1, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); } +#if defined(LL_EXTI_LINE_36) +/** + * @brief Indicate if ExtiLine Event request is enabled for Lines in range 32 to 63 + * @rmtoll EMR2 EMx LL_EXTI_IsEnabledEvent_32_63 + * @param ExtiLine This parameter can be a combination of the following values + * @arg @ref LL_EXTI_LINE_34 + * @arg @ref LL_EXTI_LINE_36 + * @arg @ref LL_EXTI_LINE_ALL_32_63 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_EXTI_IsEnabledEvent_32_63(uint32_t ExtiLine) +{ + return ((READ_BIT(EXTI->EMR2, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); +} +#endif /* LL_EXTI_LINE_36 */ /** * @} @@ -470,10 +581,6 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledEvent_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -482,6 +589,28 @@ __STATIC_INLINE void LL_EXTI_EnableRisingTrig_0_31(uint32_t ExtiLine) SET_BIT(EXTI->RTSR1, ExtiLine); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Enable ExtiLine Rising Edge Trigger for Lines in range 32 to 63 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a rising edge on a configurable interrupt + * line occurs during a write operation in the EXTI_RTSR register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for + * the same interrupt line. In this case, both generate a trigger + * condition. + * @rmtoll RTSR2 RTx LL_EXTI_EnableRisingTrig_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_EnableRisingTrig_32_63(uint32_t ExtiLine) +{ + SET_BIT(EXTI->RTSR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Disable ExtiLine Rising Edge Trigger for Lines in range 0 to 31 * @note The configurable wakeup lines are edge-triggered. No glitch must be @@ -509,10 +638,6 @@ __STATIC_INLINE void LL_EXTI_EnableRisingTrig_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -522,6 +647,28 @@ __STATIC_INLINE void LL_EXTI_DisableRisingTrig_0_31(uint32_t ExtiLine) } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Disable ExtiLine Rising Edge Trigger for Lines in range 32 to 63 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a rising edge on a configurable interrupt + * line occurs during a write operation in the EXTI_RTSR register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for + * the same interrupt line. In this case, both generate a trigger + * condition. + * @rmtoll RTSR2 RTx LL_EXTI_DisableRisingTrig_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_DisableRisingTrig_32_63(uint32_t ExtiLine) +{ + CLEAR_BIT(EXTI->RTSR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Check if rising edge trigger is enabled for Lines in range 0 to 31 * @rmtoll RTSR1 RTx LL_EXTI_IsEnabledRisingTrig_0_31 @@ -542,10 +689,6 @@ __STATIC_INLINE void LL_EXTI_DisableRisingTrig_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval State of bit (1 or 0). */ @@ -554,6 +697,21 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledRisingTrig_0_31(uint32_t ExtiLine) return ((READ_BIT(EXTI->RTSR1, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Check if rising edge trigger is enabled for Lines in range 32 to 63 + * @rmtoll RTSR2 RTx LL_EXTI_IsEnabledRisingTrig_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_EXTI_IsEnabledRisingTrig_32_63(uint32_t ExtiLine) +{ + return ((READ_BIT(EXTI->RTSR2, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @} */ @@ -589,10 +747,6 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledRisingTrig_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -601,6 +755,28 @@ __STATIC_INLINE void LL_EXTI_EnableFallingTrig_0_31(uint32_t ExtiLine) SET_BIT(EXTI->FTSR1, ExtiLine); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Enable ExtiLine Falling Edge Trigger for Lines in range 32 to 63 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a falling edge on a configurable interrupt + * line occurs during a write operation in the EXTI_FTSR register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for + * the same interrupt line. In this case, both generate a trigger + * condition. + * @rmtoll FTSR2 FTx LL_EXTI_EnableFallingTrig_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_EnableFallingTrig_32_63(uint32_t ExtiLine) +{ + SET_BIT(EXTI->FTSR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Disable ExtiLine Falling Edge Trigger for Lines in range 0 to 31 * @note The configurable wakeup lines are edge-triggered. No glitch must be @@ -627,10 +803,6 @@ __STATIC_INLINE void LL_EXTI_EnableFallingTrig_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -639,6 +811,27 @@ __STATIC_INLINE void LL_EXTI_DisableFallingTrig_0_31(uint32_t ExtiLine) CLEAR_BIT(EXTI->FTSR1, ExtiLine); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Disable ExtiLine Falling Edge Trigger for Lines in range 32 to 63 + * @note The configurable wakeup lines are edge-triggered. No glitch must be + * generated on these lines. If a Falling edge on a configurable interrupt + * line occurs during a write operation in the EXTI_FTSR register, the + * pending bit is not set. + * Rising and falling edge triggers can be set for the same interrupt line. + * In this case, both generate a trigger condition. + * @rmtoll FTSR2 FTx LL_EXTI_DisableFallingTrig_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_DisableFallingTrig_32_63(uint32_t ExtiLine) +{ + CLEAR_BIT(EXTI->FTSR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Check if falling edge trigger is enabled for Lines in range 0 to 31 * @rmtoll FTSR1 FTx LL_EXTI_IsEnabledFallingTrig_0_31 @@ -659,10 +852,6 @@ __STATIC_INLINE void LL_EXTI_DisableFallingTrig_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval State of bit (1 or 0). */ @@ -671,6 +860,21 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledFallingTrig_0_31(uint32_t ExtiLine) return ((READ_BIT(EXTI->FTSR1, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Check if falling edge trigger is enabled for Lines in range 32 to 63 + * @rmtoll FTSR2 FTx LL_EXTI_IsEnabledFallingTrig_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_EXTI_IsEnabledFallingTrig_32_63(uint32_t ExtiLine) +{ + return ((READ_BIT(EXTI->FTSR2, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @} */ @@ -704,10 +908,6 @@ __STATIC_INLINE uint32_t LL_EXTI_IsEnabledFallingTrig_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -716,6 +916,26 @@ __STATIC_INLINE void LL_EXTI_GenerateSWI_0_31(uint32_t ExtiLine) SET_BIT(EXTI->SWIER1, ExtiLine); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Generate a software Interrupt Event for Lines in range 32 to 63 + * @note If the interrupt is enabled on this line in the EXTI_IMR, writing a 1 to + * this bit when it is at '0' sets the corresponding pending bit in EXTI_PR + * resulting in an interrupt request generation. + * This bit is cleared by clearing the corresponding bit in the EXTI_PR + * register (by writing a 1 into the bit) + * @rmtoll SWIER2 SWIx LL_EXTI_GenerateSWI_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_GenerateSWI_32_63(uint32_t ExtiLine) +{ + SET_BIT(EXTI->SWIER2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @} */ @@ -758,6 +978,23 @@ __STATIC_INLINE uint32_t LL_EXTI_IsActiveFallingFlag_0_31(uint32_t ExtiLine) return ((READ_BIT(EXTI->FPR1, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Check if the ExtLine Falling Flag is set or not for Lines in range 32 to 63 + * @note This bit is set when the falling edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @rmtoll FPR2 FPIFx LL_EXTI_IsActiveFallingFlag_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_EXTI_IsActiveFallingFlag_32_63(uint32_t ExtiLine) +{ + return ((READ_BIT(EXTI->FPR2, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Read ExtLine Combination Falling Flag for Lines in range 0 to 31 * @note This bit is set when the falling edge event arrives on the interrupt @@ -792,6 +1029,23 @@ __STATIC_INLINE uint32_t LL_EXTI_ReadFallingFlag_0_31(uint32_t ExtiLine) return (READ_BIT(EXTI->FPR1, ExtiLine)); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Read ExtLine Combination Falling Flag for Lines in range 32 to 63 + * @note This bit is set when the falling edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @rmtoll FPR2 FPIFx LL_EXTI_ReadFallingFlag_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval @note This bit is set when the selected edge event arrives on the interrupt + */ +__STATIC_INLINE uint32_t LL_EXTI_ReadFallingFlag_32_63(uint32_t ExtiLine) +{ + return (uint32_t)(READ_BIT(EXTI->FPR2, ExtiLine)); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Clear ExtLine Falling Flags for Lines in range 0 to 31 * @note This bit is set when the falling edge event arrives on the interrupt @@ -814,10 +1068,6 @@ __STATIC_INLINE uint32_t LL_EXTI_ReadFallingFlag_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -826,6 +1076,23 @@ __STATIC_INLINE void LL_EXTI_ClearFallingFlag_0_31(uint32_t ExtiLine) WRITE_REG(EXTI->FPR1, ExtiLine); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Clear ExtLine Falling Flags for Lines in range 32 to 63 + * @note This bit is set when the falling edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @rmtoll FPR2 FPIFx LL_EXTI_ClearFallingFlag_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_ClearFallingFlag_32_63(uint32_t ExtiLine) +{ + WRITE_REG(EXTI->FPR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Check if the ExtLine Rising Flag is set or not for Lines in range 0 to 31 * @note This bit is set when the Rising edge event arrives on the interrupt @@ -848,10 +1115,6 @@ __STATIC_INLINE void LL_EXTI_ClearFallingFlag_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval State of bit (1 or 0). */ @@ -860,6 +1123,23 @@ __STATIC_INLINE uint32_t LL_EXTI_IsActiveRisingFlag_0_31(uint32_t ExtiLine) return ((READ_BIT(EXTI->RPR1, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Check if the ExtLine Rising Flag is set or not for Lines in range 32 to 63 + * @note This bit is set when the Rising edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @rmtoll RPR2 RPIFx LL_EXTI_IsActiveRisingFlag_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_EXTI_IsActiveRisingFlag_32_63(uint32_t ExtiLine) +{ + return ((READ_BIT(EXTI->RPR2, ExtiLine) == (ExtiLine)) ? 1UL : 0UL); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Read ExtLine Combination Rising Flag for Lines in range 0 to 31 * @note This bit is set when the Rising edge event arrives on the interrupt @@ -882,10 +1162,6 @@ __STATIC_INLINE uint32_t LL_EXTI_IsActiveRisingFlag_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval @note This bit is set when the selected edge event arrives on the interrupt */ @@ -894,6 +1170,23 @@ __STATIC_INLINE uint32_t LL_EXTI_ReadRisingFlag_0_31(uint32_t ExtiLine) return (READ_BIT(EXTI->RPR1, ExtiLine)); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Read ExtLine Combination Rising Flag for Lines in range 32 to 63 + * @note This bit is set when the Rising edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @rmtoll RPR2 RPIFx LL_EXTI_ReadRisingFlag_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval @note This bit is set when the selected edge event arrives on the interrupt + */ +__STATIC_INLINE uint32_t LL_EXTI_ReadRisingFlag_32_63(uint32_t ExtiLine) +{ + return (READ_BIT(EXTI->RPR2, ExtiLine)); +} +#endif /* LL_EXTI_LINE_34 */ + /** * @brief Clear ExtLine Rising Flags for Lines in range 0 to 31 * @note This bit is set when the Rising edge event arrives on the interrupt @@ -916,10 +1209,6 @@ __STATIC_INLINE uint32_t LL_EXTI_ReadRisingFlag_0_31(uint32_t ExtiLine) * @arg @ref LL_EXTI_LINE_13 * @arg @ref LL_EXTI_LINE_14 * @arg @ref LL_EXTI_LINE_15 - * @arg @ref LL_EXTI_LINE_19 - * @arg @ref LL_EXTI_LINE_23 - * @arg @ref LL_EXTI_LINE_25 - * @arg @ref LL_EXTI_LINE_31 * @note Please check each device line mapping for EXTI Line availability * @retval None */ @@ -928,6 +1217,22 @@ __STATIC_INLINE void LL_EXTI_ClearRisingFlag_0_31(uint32_t ExtiLine) WRITE_REG(EXTI->RPR1, ExtiLine); } +#if defined(LL_EXTI_LINE_34) +/** + * @brief Clear ExtLine Rising Flags for Lines in range 32 to 63 + * @note This bit is set when the Rising edge event arrives on the interrupt + * line. This bit is cleared by writing a 1 to the bit. + * @rmtoll RPR2 RPIFx LL_EXTI_ClearRisingFlag_32_63 + * @param ExtiLine This parameter can be a combination of the following values: + * @arg @ref LL_EXTI_LINE_34 + * @note Please check each device line mapping for EXTI Line availability + * @retval None + */ +__STATIC_INLINE void LL_EXTI_ClearRisingFlag_32_63(uint32_t ExtiLine) +{ + WRITE_REG(EXTI->RPR2, ExtiLine); +} +#endif /* LL_EXTI_LINE_34 */ /** * @} */ @@ -956,7 +1261,6 @@ __STATIC_INLINE void LL_EXTI_ClearRisingFlag_0_31(uint32_t ExtiLine) * @param Port This parameter can be one of the following values: * @arg @ref EXTI_LL_EC_CONFIG_PORT * - * (*) value not defined in all devices * @param Line This parameter can be one of the following values: * @arg @ref LL_EXTI_CONFIG_LINE0 * @arg @ref LL_EXTI_CONFIG_LINE1 @@ -1020,7 +1324,6 @@ __STATIC_INLINE void LL_EXTI_SetEXTISource(uint32_t Port, uint32_t Line) * @retval Returned value can be one of the following values: * @arg @ref EXTI_LL_EC_CONFIG_PORT * - * (*) value not defined in all devices */ __STATIC_INLINE uint32_t LL_EXTI_GetEXTISource(uint32_t Line) { @@ -1064,4 +1367,4 @@ void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct); } #endif -#endif /* STM32U5xx_LL_EXTI_H */ +#endif /* STM32C0xx_LL_EXTI_H */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_gpio.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_gpio.h index 921d8f5e4..f7764e498 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_gpio.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_gpio.h @@ -281,7 +281,7 @@ typedef struct */ __STATIC_INLINE void LL_GPIO_SetPinMode(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Mode) { - MODIFY_REG(GPIOx->MODER, (GPIO_MODER_MODE0 << (POSITION_VAL(Pin) * 2U)), (Mode << (POSITION_VAL(Pin) * 2U))); + MODIFY_REG(GPIOx->MODER, ((Pin * Pin) * GPIO_MODER_MODE0), ((Pin * Pin) * Mode)); } /** @@ -313,10 +313,9 @@ __STATIC_INLINE void LL_GPIO_SetPinMode(GPIO_TypeDef *GPIOx, uint32_t Pin, uint3 * @arg @ref LL_GPIO_MODE_ALTERNATE * @arg @ref LL_GPIO_MODE_ANALOG */ -__STATIC_INLINE uint32_t LL_GPIO_GetPinMode(GPIO_TypeDef *GPIOx, uint32_t Pin) +__STATIC_INLINE uint32_t LL_GPIO_GetPinMode(const GPIO_TypeDef *GPIOx, uint32_t Pin) { - return (uint32_t)(READ_BIT(GPIOx->MODER, - (GPIO_MODER_MODE0 << (POSITION_VAL(Pin) * 2U))) >> (POSITION_VAL(Pin) * 2U)); + return (uint32_t)(READ_BIT(GPIOx->MODER, ((Pin * Pin) * GPIO_MODER_MODE0)) / (Pin * Pin)); } /** @@ -382,9 +381,9 @@ __STATIC_INLINE void LL_GPIO_SetPinOutputType(GPIO_TypeDef *GPIOx, uint32_t PinM * @arg @ref LL_GPIO_OUTPUT_PUSHPULL * @arg @ref LL_GPIO_OUTPUT_OPENDRAIN */ -__STATIC_INLINE uint32_t LL_GPIO_GetPinOutputType(GPIO_TypeDef *GPIOx, uint32_t Pin) +__STATIC_INLINE uint32_t LL_GPIO_GetPinOutputType(const GPIO_TypeDef *GPIOx, uint32_t Pin) { - return (uint32_t)(READ_BIT(GPIOx->OTYPER, Pin) >> POSITION_VAL(Pin)); + return (uint32_t)(READ_BIT(GPIOx->OTYPER, Pin) / Pin); } /** @@ -421,8 +420,7 @@ __STATIC_INLINE uint32_t LL_GPIO_GetPinOutputType(GPIO_TypeDef *GPIOx, uint32_t */ __STATIC_INLINE void LL_GPIO_SetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Speed) { - MODIFY_REG(GPIOx->OSPEEDR, (GPIO_OSPEEDR_OSPEED0 << (POSITION_VAL(Pin) * 2U)), - (Speed << (POSITION_VAL(Pin) * 2U))); + MODIFY_REG(GPIOx->OSPEEDR, ((Pin * Pin) * GPIO_OSPEEDR_OSPEED0), ((Pin * Pin) * Speed)); } /** @@ -456,10 +454,9 @@ __STATIC_INLINE void LL_GPIO_SetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin, uint * @arg @ref LL_GPIO_SPEED_FREQ_HIGH * @arg @ref LL_GPIO_SPEED_FREQ_VERY_HIGH */ -__STATIC_INLINE uint32_t LL_GPIO_GetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin) +__STATIC_INLINE uint32_t LL_GPIO_GetPinSpeed(const GPIO_TypeDef *GPIOx, uint32_t Pin) { - return (uint32_t)(READ_BIT(GPIOx->OSPEEDR, - (GPIO_OSPEEDR_OSPEED0 << (POSITION_VAL(Pin) * 2U))) >> (POSITION_VAL(Pin) * 2U)); + return (uint32_t)(READ_BIT(GPIOx->OSPEEDR, ((Pin * Pin) * GPIO_OSPEEDR_OSPEED0)) / (Pin * Pin)); } /** @@ -492,7 +489,7 @@ __STATIC_INLINE uint32_t LL_GPIO_GetPinSpeed(GPIO_TypeDef *GPIOx, uint32_t Pin) */ __STATIC_INLINE void LL_GPIO_SetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Pull) { - MODIFY_REG(GPIOx->PUPDR, (GPIO_PUPDR_PUPD0 << (POSITION_VAL(Pin) * 2U)), (Pull << (POSITION_VAL(Pin) * 2U))); + MODIFY_REG(GPIOx->PUPDR, ((Pin * Pin) * GPIO_PUPDR_PUPD0), ((Pin * Pin) * Pull)); } /** @@ -522,10 +519,9 @@ __STATIC_INLINE void LL_GPIO_SetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin, uint3 * @arg @ref LL_GPIO_PULL_UP * @arg @ref LL_GPIO_PULL_DOWN */ -__STATIC_INLINE uint32_t LL_GPIO_GetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin) +__STATIC_INLINE uint32_t LL_GPIO_GetPinPull(const GPIO_TypeDef *GPIOx, uint32_t Pin) { - return (uint32_t)(READ_BIT(GPIOx->PUPDR, - (GPIO_PUPDR_PUPD0 << (POSITION_VAL(Pin) * 2U))) >> (POSITION_VAL(Pin) * 2U)); + return (uint32_t)(READ_BIT(GPIOx->PUPDR, ((Pin * Pin) * GPIO_PUPDR_PUPD0)) / (Pin * Pin)); } /** @@ -564,8 +560,8 @@ __STATIC_INLINE uint32_t LL_GPIO_GetPinPull(GPIO_TypeDef *GPIOx, uint32_t Pin) */ __STATIC_INLINE void LL_GPIO_SetAFPin_0_7(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Alternate) { - MODIFY_REG(GPIOx->AFR[0], (GPIO_AFRL_AFSEL0 << (POSITION_VAL(Pin) * 4U)), - (Alternate << (POSITION_VAL(Pin) * 4U))); + MODIFY_REG(GPIOx->AFR[0], ((((Pin * Pin) * Pin) * Pin) * GPIO_AFRL_AFSEL0), + ((((Pin * Pin) * Pin) * Pin) * Alternate)); } /** @@ -599,10 +595,10 @@ __STATIC_INLINE void LL_GPIO_SetAFPin_0_7(GPIO_TypeDef *GPIOx, uint32_t Pin, uin * @arg @ref LL_GPIO_AF_14 * @arg @ref LL_GPIO_AF_15 */ -__STATIC_INLINE uint32_t LL_GPIO_GetAFPin_0_7(GPIO_TypeDef *GPIOx, uint32_t Pin) +__STATIC_INLINE uint32_t LL_GPIO_GetAFPin_0_7(const GPIO_TypeDef *GPIOx, uint32_t Pin) { return (uint32_t)(READ_BIT(GPIOx->AFR[0], - (GPIO_AFRL_AFSEL0 << (POSITION_VAL(Pin) * 4U))) >> (POSITION_VAL(Pin) * 4U)); + ((((Pin * Pin) * Pin) * Pin) * GPIO_AFRL_AFSEL0)) / (((Pin * Pin) * Pin) * Pin)); } /** @@ -641,8 +637,8 @@ __STATIC_INLINE uint32_t LL_GPIO_GetAFPin_0_7(GPIO_TypeDef *GPIOx, uint32_t Pin) */ __STATIC_INLINE void LL_GPIO_SetAFPin_8_15(GPIO_TypeDef *GPIOx, uint32_t Pin, uint32_t Alternate) { - MODIFY_REG(GPIOx->AFR[1], (GPIO_AFRH_AFSEL8 << (POSITION_VAL(Pin >> 8U) * 4U)), - (Alternate << (POSITION_VAL(Pin >> 8U) * 4U))); + MODIFY_REG(GPIOx->AFR[1], (((((Pin >> 8U) * (Pin >> 8U)) * (Pin >> 8U)) * (Pin >> 8U)) * GPIO_AFRH_AFSEL8), + (((((Pin >> 8U) * (Pin >> 8U)) * (Pin >> 8U)) * (Pin >> 8U)) * Alternate)); } /** @@ -677,10 +673,11 @@ __STATIC_INLINE void LL_GPIO_SetAFPin_8_15(GPIO_TypeDef *GPIOx, uint32_t Pin, ui * @arg @ref LL_GPIO_AF_14 * @arg @ref LL_GPIO_AF_15 */ -__STATIC_INLINE uint32_t LL_GPIO_GetAFPin_8_15(GPIO_TypeDef *GPIOx, uint32_t Pin) +__STATIC_INLINE uint32_t LL_GPIO_GetAFPin_8_15(const GPIO_TypeDef *GPIOx, uint32_t Pin) { return (uint32_t)(READ_BIT(GPIOx->AFR[1], - (GPIO_AFRH_AFSEL8 << (POSITION_VAL(Pin >> 8U) * 4U))) >> (POSITION_VAL(Pin >> 8U) * 4U)); + (((((Pin >> 8U) * (Pin >> 8U)) * (Pin >> 8U)) * (Pin >> 8U)) * GPIO_AFRH_AFSEL8)) / + ((((Pin >> 8U) * (Pin >> 8U)) * (Pin >> 8U)) * (Pin >> 8U))); } /** @@ -747,7 +744,7 @@ __STATIC_INLINE void LL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint32_t PinMask) * @arg @ref LL_GPIO_PIN_ALL * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_GPIO_IsPinLocked(GPIO_TypeDef *GPIOx, uint32_t PinMask) +__STATIC_INLINE uint32_t LL_GPIO_IsPinLocked(const GPIO_TypeDef *GPIOx, uint32_t PinMask) { return ((READ_BIT(GPIOx->LCKR, PinMask) == (PinMask)) ? 1UL : 0UL); } @@ -758,7 +755,7 @@ __STATIC_INLINE uint32_t LL_GPIO_IsPinLocked(GPIO_TypeDef *GPIOx, uint32_t PinMa * @param GPIOx GPIO Port * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_GPIO_IsAnyPinLocked(GPIO_TypeDef *GPIOx) +__STATIC_INLINE uint32_t LL_GPIO_IsAnyPinLocked(const GPIO_TypeDef *GPIOx) { return ((READ_BIT(GPIOx->LCKR, GPIO_LCKR_LCKK) == (GPIO_LCKR_LCKK)) ? 1UL : 0UL); } @@ -777,7 +774,7 @@ __STATIC_INLINE uint32_t LL_GPIO_IsAnyPinLocked(GPIO_TypeDef *GPIOx) * @param GPIOx GPIO Port * @retval Input data register value of port */ -__STATIC_INLINE uint32_t LL_GPIO_ReadInputPort(GPIO_TypeDef *GPIOx) +__STATIC_INLINE uint32_t LL_GPIO_ReadInputPort(const GPIO_TypeDef *GPIOx) { return (uint32_t)(READ_REG(GPIOx->IDR)); } @@ -806,7 +803,7 @@ __STATIC_INLINE uint32_t LL_GPIO_ReadInputPort(GPIO_TypeDef *GPIOx) * @arg @ref LL_GPIO_PIN_ALL * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_GPIO_IsInputPinSet(GPIO_TypeDef *GPIOx, uint32_t PinMask) +__STATIC_INLINE uint32_t LL_GPIO_IsInputPinSet(const GPIO_TypeDef *GPIOx, uint32_t PinMask) { return ((READ_BIT(GPIOx->IDR, PinMask) == (PinMask)) ? 1UL : 0UL); } @@ -829,7 +826,7 @@ __STATIC_INLINE void LL_GPIO_WriteOutputPort(GPIO_TypeDef *GPIOx, uint32_t PortV * @param GPIOx GPIO Port * @retval Output data register value of port */ -__STATIC_INLINE uint32_t LL_GPIO_ReadOutputPort(GPIO_TypeDef *GPIOx) +__STATIC_INLINE uint32_t LL_GPIO_ReadOutputPort(const GPIO_TypeDef *GPIOx) { return (uint32_t)(READ_REG(GPIOx->ODR)); } @@ -858,7 +855,7 @@ __STATIC_INLINE uint32_t LL_GPIO_ReadOutputPort(GPIO_TypeDef *GPIOx) * @arg @ref LL_GPIO_PIN_ALL * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_GPIO_IsOutputPinSet(GPIO_TypeDef *GPIOx, uint32_t PinMask) +__STATIC_INLINE uint32_t LL_GPIO_IsOutputPinSet(const GPIO_TypeDef *GPIOx, uint32_t PinMask) { return ((READ_BIT(GPIOx->ODR, PinMask) == (PinMask)) ? 1UL : 0UL); } @@ -960,7 +957,7 @@ __STATIC_INLINE void LL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint32_t PinMask) * @{ */ -ErrorStatus LL_GPIO_DeInit(GPIO_TypeDef *GPIOx); +ErrorStatus LL_GPIO_DeInit(const GPIO_TypeDef *GPIOx); ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, LL_GPIO_InitTypeDef *GPIO_InitStruct); void LL_GPIO_StructInit(LL_GPIO_InitTypeDef *GPIO_InitStruct); diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_i2c.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_i2c.h index 2290c32c1..7cf2881bc 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_i2c.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_i2c.h @@ -31,7 +31,7 @@ extern "C" { * @{ */ -#if defined (I2C1) +#if defined (I2C1) || defined(I2C2) /** @defgroup I2C_LL I2C * @{ @@ -702,6 +702,7 @@ __STATIC_INLINE uint32_t LL_I2C_IsEnabledSlaveByteControl(const I2C_TypeDef *I2C return ((READ_BIT(I2Cx->CR1, I2C_CR1_SBC) == (I2C_CR1_SBC)) ? 1UL : 0UL); } +#if defined(I2C_CR1_WUPEN) /** * @brief Enable Wakeup from STOP. * @note The macro IS_I2C_WAKEUP_FROMSTOP_INSTANCE(I2Cx) can be used to check whether or not @@ -742,6 +743,7 @@ __STATIC_INLINE uint32_t LL_I2C_IsEnabledWakeUpFromStop(const I2C_TypeDef *I2Cx) return ((READ_BIT(I2Cx->CR1, I2C_CR1_WUPEN) == (I2C_CR1_WUPEN)) ? 1UL : 0UL); } +#endif /* I2C_CR1_WUPEN */ /** * @brief Enable General Call. * @note When enabled the Address 0x00 is ACKed. @@ -2133,11 +2135,18 @@ __STATIC_INLINE uint32_t LL_I2C_GetSlaveAddr(const I2C_TypeDef *I2Cx) __STATIC_INLINE void LL_I2C_HandleTransfer(I2C_TypeDef *I2Cx, uint32_t SlaveAddr, uint32_t SlaveAddrSize, uint32_t TransferSize, uint32_t EndMode, uint32_t Request) { + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + uint32_t tmp = ((uint32_t)(((uint32_t)SlaveAddr & I2C_CR2_SADD) | \ + ((uint32_t)SlaveAddrSize & I2C_CR2_ADD10) | \ + (((uint32_t)TransferSize << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \ + (uint32_t)EndMode | (uint32_t)Request) & (~0x80000000U)); + + /* update CR2 register */ MODIFY_REG(I2Cx->CR2, I2C_CR2_SADD | I2C_CR2_ADD10 | (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31U - I2C_CR2_RD_WRN_Pos))) | I2C_CR2_START | I2C_CR2_STOP | I2C_CR2_RELOAD | I2C_CR2_NBYTES | I2C_CR2_AUTOEND | I2C_CR2_HEAD10R, - SlaveAddr | SlaveAddrSize | (TransferSize << I2C_CR2_NBYTES_Pos) | EndMode | Request); + tmp); } /** @@ -2259,7 +2268,7 @@ void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct); * @} */ -#endif /* I2C1 */ +#endif /* I2C1 || I2C2 */ /** * @} diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_iwdg.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_iwdg.h index e8161679e..95d90d1ce 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_iwdg.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_iwdg.h @@ -208,7 +208,7 @@ __STATIC_INLINE void LL_IWDG_SetPrescaler(IWDG_TypeDef *IWDGx, uint32_t Prescale * @arg @ref LL_IWDG_PRESCALER_128 * @arg @ref LL_IWDG_PRESCALER_256 */ -__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->PR)); } @@ -231,7 +231,7 @@ __STATIC_INLINE void LL_IWDG_SetReloadCounter(IWDG_TypeDef *IWDGx, uint32_t Coun * @param IWDGx IWDG Instance * @retval Value between Min_Data=0 and Max_Data=0x0FFF */ -__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->RLR)); } @@ -254,7 +254,7 @@ __STATIC_INLINE void LL_IWDG_SetWindow(IWDG_TypeDef *IWDGx, uint32_t Window) * @param IWDGx IWDG Instance * @retval Value between Min_Data=0 and Max_Data=0x0FFF */ -__STATIC_INLINE uint32_t LL_IWDG_GetWindow(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetWindow(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->WINR)); } @@ -273,7 +273,7 @@ __STATIC_INLINE uint32_t LL_IWDG_GetWindow(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_PVU) == (IWDG_SR_PVU)) ? 1UL : 0UL); } @@ -284,7 +284,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_RVU) == (IWDG_SR_RVU)) ? 1UL : 0UL); } @@ -295,7 +295,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_WVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_WVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_WVU) == (IWDG_SR_WVU)) ? 1UL : 0UL); } @@ -308,7 +308,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_WVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bits (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsReady(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsReady(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_PVU | IWDG_SR_RVU | IWDG_SR_WVU) == 0U) ? 1UL : 0UL); } @@ -336,4 +336,3 @@ __STATIC_INLINE uint32_t LL_IWDG_IsReady(IWDG_TypeDef *IWDGx) #endif #endif /* STM32C0xx_LL_IWDG_H */ - diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_pwr.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_pwr.h index e2552fc62..7b51731af 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_pwr.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_pwr.h @@ -57,6 +57,9 @@ extern "C" { #define LL_PWR_SCR_CSBF PWR_SCR_CSBF #define LL_PWR_SCR_CWUF PWR_SCR_CWUF #define LL_PWR_SCR_CWUF6 PWR_SCR_CWUF6 +#if defined(PWR_SCR_CWUF5) +#define LL_PWR_SCR_CWUF5 PWR_SCR_CWUF5 +#endif /* PWR_SCR_CWUF5 */ #define LL_PWR_SCR_CWUF4 PWR_SCR_CWUF4 #define LL_PWR_SCR_CWUF3 PWR_SCR_CWUF3 #define LL_PWR_SCR_CWUF2 PWR_SCR_CWUF2 @@ -72,6 +75,9 @@ extern "C" { #define LL_PWR_SR1_WUFI PWR_SR1_WUFI #define LL_PWR_SR1_SBF PWR_SR1_SBF #define LL_PWR_SR1_WUF6 PWR_SR1_WUF6 +#if defined(PWR_SR1_WUF5) +#define LL_PWR_SR1_WUF5 PWR_SR1_WUF5 +#endif /* PWR_SR1_WUF5 */ #define LL_PWR_SR1_WUF4 PWR_SR1_WUF4 #define LL_PWR_SR1_WUF3 PWR_SR1_WUF3 #define LL_PWR_SR1_WUF2 PWR_SR1_WUF2 @@ -85,12 +91,23 @@ extern "C" { * @{ */ #define LL_PWR_MODE_STOP0 (0x00000000UL) -#define LL_PWR_MODE_STANDBY (PWR_CR1_LPMS_1|PWR_CR1_LPMS_0) +#define LL_PWR_MODE_STANDBY (PWR_CR1_LPMS_1 | PWR_CR1_LPMS_0) #define LL_PWR_MODE_SHUTDOWN (PWR_CR1_LPMS_2) /** * @} */ +#if defined(PWR_PVM_SUPPORT) +/** @defgroup PWR_LL_EC_PVM_IP PVM_IP + * @{ + */ +#define LL_PWR_PVM_USB PWR_CR2_PVMEN_USB /*!< Peripheral Voltage Monitoring enable for USB peripheral: + Enable to keep the USB peripheral voltage monitoring + under control (power domain Vddio2) */ +/** + * @} + */ +#endif /* PWR_PVM_SUPPORT */ /** @defgroup PWR_LL_EC_WAKEUP WAKEUP * @{ @@ -99,21 +116,23 @@ extern "C" { #define LL_PWR_WAKEUP_PIN2 (PWR_CR3_EWUP2) #define LL_PWR_WAKEUP_PIN3 (PWR_CR3_EWUP3) #define LL_PWR_WAKEUP_PIN4 (PWR_CR3_EWUP4) +#if defined(PWR_CR3_EWUP5) +#define LL_PWR_WAKEUP_PIN5 (PWR_CR3_EWUP5) +#endif /* PWR_CR3_EWUP5 */ #define LL_PWR_WAKEUP_PIN6 (PWR_CR3_EWUP6) /** * @} */ - /** @defgroup PWR_LL_EC_GPIO GPIO * @{ */ #define LL_PWR_GPIO_A ((uint32_t)(&(PWR->PUCRA))) #define LL_PWR_GPIO_B ((uint32_t)(&(PWR->PUCRB))) #define LL_PWR_GPIO_C ((uint32_t)(&(PWR->PUCRC))) -#if defined(STM32C031xx) +#if defined(GPIOD) #define LL_PWR_GPIO_D ((uint32_t)(&(PWR->PUCRD))) -#endif /* STM32C031xx */ +#endif /* GPIOD */ #define LL_PWR_GPIO_F ((uint32_t)(&(PWR->PUCRF))) /** * @} @@ -122,27 +141,27 @@ extern "C" { /** @defgroup PWR_LL_EC_GPIO_BIT GPIO BIT * @{ */ -#define LL_PWR_GPIO_BIT_0 0x00000001u -#define LL_PWR_GPIO_BIT_1 0x00000002u -#define LL_PWR_GPIO_BIT_2 0x00000004u -#define LL_PWR_GPIO_BIT_3 0x00000008u -#define LL_PWR_GPIO_BIT_4 0x00000010u -#define LL_PWR_GPIO_BIT_5 0x00000020u -#define LL_PWR_GPIO_BIT_6 0x00000040u -#define LL_PWR_GPIO_BIT_7 0x00000080u -#define LL_PWR_GPIO_BIT_8 0x00000100u -#define LL_PWR_GPIO_BIT_9 0x00000200u -#define LL_PWR_GPIO_BIT_10 0x00000400u -#define LL_PWR_GPIO_BIT_11 0x00000800u -#define LL_PWR_GPIO_BIT_12 0x00001000u -#define LL_PWR_GPIO_BIT_13 0x00002000u -#define LL_PWR_GPIO_BIT_14 0x00004000u -#define LL_PWR_GPIO_BIT_15 0x00008000u +#define LL_PWR_GPIO_BIT_0 0x00000001U +#define LL_PWR_GPIO_BIT_1 0x00000002U +#define LL_PWR_GPIO_BIT_2 0x00000004U +#define LL_PWR_GPIO_BIT_3 0x00000008U +#define LL_PWR_GPIO_BIT_4 0x00000010U +#define LL_PWR_GPIO_BIT_5 0x00000020U +#define LL_PWR_GPIO_BIT_6 0x00000040U +#define LL_PWR_GPIO_BIT_7 0x00000080U +#define LL_PWR_GPIO_BIT_8 0x00000100U +#define LL_PWR_GPIO_BIT_9 0x00000200U +#define LL_PWR_GPIO_BIT_10 0x00000400U +#define LL_PWR_GPIO_BIT_11 0x00000800U +#define LL_PWR_GPIO_BIT_12 0x00001000U +#define LL_PWR_GPIO_BIT_13 0x00002000U +#define LL_PWR_GPIO_BIT_14 0x00004000U +#define LL_PWR_GPIO_BIT_15 0x00008000U /** * @} */ -/** @defgroup PWR_LL_EC_BKP BACKUP +/** @defgroup PWR_LL_EC_BKP BACKUP * @{ */ #define LL_PWR_BKP_NUMBER 4U @@ -202,7 +221,7 @@ extern "C" { /** * @brief Enable Flash Power-down mode during sleep mode - * @rmtoll CR1 CFIPD_SLP LL_PWR_EnableFlashPowerDownInSleep + * @rmtoll CR1 FPD_SLP LL_PWR_EnableFlashPowerDownInSleep * @retval None */ __STATIC_INLINE void LL_PWR_EnableFlashPowerDownInSleep(void) @@ -212,7 +231,7 @@ __STATIC_INLINE void LL_PWR_EnableFlashPowerDownInSleep(void) /** * @brief Disable Flash Power-down mode during sleep mode - * @rmtoll CR1 CFIPD_SLP LL_PWR_DisableFlashPowerDownInSleep + * @rmtoll CR1 FPD_SLP LL_PWR_DisableFlashPowerDownInSleep * @retval None */ __STATIC_INLINE void LL_PWR_DisableFlashPowerDownInSleep(void) @@ -222,7 +241,7 @@ __STATIC_INLINE void LL_PWR_DisableFlashPowerDownInSleep(void) /** * @brief Check if flash power-down mode during sleep mode domain is enabled - * @rmtoll CR1 CFIPD_SLP LL_PWR_IsEnableFlashPowerDownInSleep + * @rmtoll CR1 FPD_SLP LL_PWR_IsEnableFlashPowerDownInSleep * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnableFlashPowerDownInSleep(void) @@ -232,7 +251,7 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnableFlashPowerDownInSleep(void) /** * @brief Enable Flash Power-down mode during stop mode - * @rmtoll CR1 CFIPD_STOP LL_PWR_EnableFlashPowerDownInStop + * @rmtoll CR1 FPD_STOP LL_PWR_EnableFlashPowerDownInStop * @retval None */ __STATIC_INLINE void LL_PWR_EnableFlashPowerDownInStop(void) @@ -242,7 +261,7 @@ __STATIC_INLINE void LL_PWR_EnableFlashPowerDownInStop(void) /** * @brief Disable Flash Power-down mode during stop mode - * @rmtoll CR1 CFIPD_STOP LL_PWR_DisableFlashPowerDownInStop + * @rmtoll CR1 FPD_STOP LL_PWR_DisableFlashPowerDownInStop * @retval None */ __STATIC_INLINE void LL_PWR_DisableFlashPowerDownInStop(void) @@ -252,7 +271,7 @@ __STATIC_INLINE void LL_PWR_DisableFlashPowerDownInStop(void) /** * @brief Check if flash power-down mode during stop mode domain is enabled - * @rmtoll CR1 CFIPD_STOP LL_PWR_IsEnableFlashPowerDownInStop + * @rmtoll CR1 FPD_STOP LL_PWR_IsEnableFlashPowerDownInStop * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnableFlashPowerDownInStop(void) @@ -260,6 +279,80 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnableFlashPowerDownInStop(void) return ((READ_BIT(PWR->CR1, PWR_CR1_FPD_STOP) == (PWR_CR1_FPD_STOP)) ? 1UL : 0UL); } +#if defined(PWR_PVM_SUPPORT) +/** + * @brief Enable VDDIO2 supply + * @rmtoll CR2 PVM_VDDIO2 LL_PWR_EnableVddIO2 + * @retval None + */ +__STATIC_INLINE void LL_PWR_EnableVddIO2(void) +{ + SET_BIT(PWR->CR2, PWR_CR2_PVM_VDDIO2_1); +} + +/** + * @brief Disable VDDIO2 supply + * @rmtoll CR2 PVM_VDDIO2 LL_PWR_DisableVddIO2 + * @retval None + */ +__STATIC_INLINE void LL_PWR_DisableVddIO2(void) +{ + CLEAR_BIT(PWR->CR2, PWR_CR2_PVM_VDDIO2_1); +} + +/** + * @brief Check if VDDIO2 supply is enabled + * @rmtoll CR2 PVM_VDDIO2 LL_PWR_IsEnabledVddIO2 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_PWR_IsEnabledVddIO2(void) +{ + return ((READ_BIT(PWR->CR2, PWR_CR2_PVM_VDDIO2_1) == (PWR_CR2_PVM_VDDIO2_1)) ? 1UL : 0UL); +} + +/** + * @brief Enable the Power Voltage Monitoring on a peripheral + * @rmtoll CR2 PVMUSB LL_PWR_EnablePVM + * @param PeriphVoltage This parameter can be one of the following values: + * @arg @ref LL_PWR_PVM_USB (*) + * + * @note (*) Availability depends on devices + * @retval None + */ +__STATIC_INLINE void LL_PWR_EnablePVM(uint32_t PeriphVoltage) +{ + SET_BIT(PWR->CR2, PeriphVoltage); +} + +/** + * @brief Disable the Power Voltage Monitoring on a peripheral + * @rmtoll CR2 PVMUSB LL_PWR_DisablePVM + * @param PeriphVoltage This parameter can be one of the following values: + * @arg @ref LL_PWR_PVM_USB (*) + * + * @note (*) Availability depends on devices + * @retval None + */ +__STATIC_INLINE void LL_PWR_DisablePVM(uint32_t PeriphVoltage) +{ + CLEAR_BIT(PWR->CR2, PeriphVoltage); +} + +/** + * @brief Check if Power Voltage Monitoring is enabled on a peripheral + * @rmtoll CR2 PVMUSB LL_PWR_IsEnabledPVM + * @param PeriphVoltage This parameter can be one of the following values: + * @arg @ref LL_PWR_PVM_USB (*) + + * @note (*) Availability depends on devices + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_PWR_IsEnabledPVM(uint32_t PeriphVoltage) +{ + return ((READ_BIT(PWR->CR2, PeriphVoltage) == (PeriphVoltage)) ? 1UL : 0UL); +} +#endif /* PWR_PVM_SUPPORT */ + /** * @brief Set Low-Power mode * @rmtoll CR1 LPMS LL_PWR_SetPowerMode @@ -353,13 +446,16 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnabledPUPDCfg(void) * CR3 EWUP2 LL_PWR_EnableWakeUpPin\n * CR3 EWUP3 LL_PWR_EnableWakeUpPin\n * CR3 EWUP4 LL_PWR_EnableWakeUpPin\n + * CR3 EWUP5 LL_PWR_EnableWakeUpPin (*)\n * CR3 EWUP6 LL_PWR_EnableWakeUpPin * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 * @arg @ref LL_PWR_WAKEUP_PIN4 + * @arg @ref LL_PWR_WAKEUP_PIN5 (*) * @arg @ref LL_PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_PWR_EnableWakeUpPin(uint32_t WakeUpPin) @@ -373,13 +469,16 @@ __STATIC_INLINE void LL_PWR_EnableWakeUpPin(uint32_t WakeUpPin) * CR3 EWUP2 LL_PWR_DisableWakeUpPin\n * CR3 EWUP3 LL_PWR_DisableWakeUpPin\n * CR3 EWUP4 LL_PWR_DisableWakeUpPin\n + * CR3 EWUP5 LL_PWR_DisableWakeUpPin (*)\n * CR3 EWUP6 LL_PWR_DisableWakeUpPin * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 * @arg @ref LL_PWR_WAKEUP_PIN4 + * @arg @ref LL_PWR_WAKEUP_PIN5 (*) * @arg @ref LL_PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_PWR_DisableWakeUpPin(uint32_t WakeUpPin) @@ -393,13 +492,16 @@ __STATIC_INLINE void LL_PWR_DisableWakeUpPin(uint32_t WakeUpPin) * CR3 EWUP2 LL_PWR_IsEnabledWakeUpPin\n * CR3 EWUP3 LL_PWR_IsEnabledWakeUpPin\n * CR3 EWUP4 LL_PWR_IsEnabledWakeUpPin\n + * CR3 EWUP5 LL_PWR_IsEnabledWakeUpPin (*)\n * CR3 EWUP6 LL_PWR_IsEnabledWakeUpPin * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 * @arg @ref LL_PWR_WAKEUP_PIN4 + * @arg @ref LL_PWR_WAKEUP_PIN5 (*) * @arg @ref LL_PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledWakeUpPin(uint32_t WakeUpPin) @@ -407,20 +509,22 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnabledWakeUpPin(uint32_t WakeUpPin) return ((READ_BIT(PWR->CR3, WakeUpPin) == (WakeUpPin)) ? 1UL : 0UL); } - /** * @brief Set the Wake-Up pin polarity low for the event detection * @rmtoll CR4 WP1 LL_PWR_SetWakeUpPinPolarityLow\n * CR4 WP2 LL_PWR_SetWakeUpPinPolarityLow\n * CR4 WP3 LL_PWR_SetWakeUpPinPolarityLow\n * CR4 WP4 LL_PWR_SetWakeUpPinPolarityLow\n + * CR4 WP5 LL_PWR_SetWakeUpPinPolarityLow (*)\n * CR4 WP6 LL_PWR_SetWakeUpPinPolarityLow\n * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 * @arg @ref LL_PWR_WAKEUP_PIN4 + * @arg @ref LL_PWR_WAKEUP_PIN5 (*) * @arg @ref LL_PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_PWR_SetWakeUpPinPolarityLow(uint32_t WakeUpPin) @@ -434,13 +538,16 @@ __STATIC_INLINE void LL_PWR_SetWakeUpPinPolarityLow(uint32_t WakeUpPin) * CR4 WP2 LL_PWR_SetWakeUpPinPolarityHigh\n * CR4 WP3 LL_PWR_SetWakeUpPinPolarityHigh\n * CR4 WP4 LL_PWR_SetWakeUpPinPolarityHigh\n + * CR4 WP5 LL_PWR_SetWakeUpPinPolarityHigh (*)\n * CR4 WP6 LL_PWR_SetWakeUpPinPolarityHigh * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 * @arg @ref LL_PWR_WAKEUP_PIN4 + * @arg @ref LL_PWR_WAKEUP_PIN5 (*) * @arg @ref LL_PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval None */ __STATIC_INLINE void LL_PWR_SetWakeUpPinPolarityHigh(uint32_t WakeUpPin) @@ -454,13 +561,16 @@ __STATIC_INLINE void LL_PWR_SetWakeUpPinPolarityHigh(uint32_t WakeUpPin) * CR4 WP2 LL_PWR_IsWakeUpPinPolarityLow\n * CR4 WP3 LL_PWR_IsWakeUpPinPolarityLow\n * CR4 WP4 LL_PWR_IsWakeUpPinPolarityLow\n + * CR4 WP5 LL_PWR_IsWakeUpPinPolarityLow (*)\n * CR4 WP6 LL_PWR_IsWakeUpPinPolarityLow * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 * @arg @ref LL_PWR_WAKEUP_PIN4 + * @arg @ref LL_PWR_WAKEUP_PIN5 (*) * @arg @ref LL_PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsWakeUpPinPolarityLow(uint32_t WakeUpPin) @@ -473,16 +583,16 @@ __STATIC_INLINE uint32_t LL_PWR_IsWakeUpPinPolarityLow(uint32_t WakeUpPin) * @rmtoll PUCRA PU0-15 LL_PWR_EnableGPIOPullUp\n * PUCRB PU0-15 LL_PWR_EnableGPIOPullUp\n * PUCRC PU0-15 LL_PWR_EnableGPIOPullUp\n - * PUCRD PU0-15 LL_PWR_EnableGPIOPullUp\n - * (+) Port D is available only for STM32C031xx devices. + * PUCRD PU0-15 LL_PWR_EnableGPIOPullUp (*)\n * PUCRF PU0-15 LL_PWR_EnableGPIOPullUp + * @note (*) Port D availability depends on devices * @param GPIO This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_A * @arg @ref LL_PWR_GPIO_B * @arg @ref LL_PWR_GPIO_C - * @arg @ref LL_PWR_GPIO_D - * (+) Port D is available only for STM32C031xx devices. + * @arg @ref LL_PWR_GPIO_D (*) * @arg @ref LL_PWR_GPIO_F + * @note (*) Port D availability depends on devices * @param GPIONumber This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_BIT_0 * @arg @ref LL_PWR_GPIO_BIT_1 @@ -512,15 +622,14 @@ __STATIC_INLINE void LL_PWR_EnableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber) * @rmtoll PUCRA PU0-15 LL_PWR_DisableGPIOPullUp\n * PUCRB PU0-15 LL_PWR_DisableGPIOPullUp\n * PUCRC PU0-15 LL_PWR_DisableGPIOPullUp\n - * PUCRD PU0-15 LL_PWR_DisableGPIOPullUp\n - * (+) Port D is available only for STM32C031xx devices. + * PUCRD PU0-15 LL_PWR_DisableGPIOPullUp (*)\n * PUCRF PU0-15 LL_PWR_DisableGPIOPullUp + * @note (*) Port D availability depends on devices * @param GPIO This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_A * @arg @ref LL_PWR_GPIO_B * @arg @ref LL_PWR_GPIO_C - * @arg @ref LL_PWR_GPIO_D - * (+) Port D is available only for STM32C031xx devices. + * @arg @ref LL_PWR_GPIO_D (*) * @arg @ref LL_PWR_GPIO_F * @param GPIONumber This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_BIT_0 @@ -551,16 +660,16 @@ __STATIC_INLINE void LL_PWR_DisableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber * @rmtoll PUCRA PU0-15 LL_PWR_IsEnabledGPIOPullUp\n * PUCRB PU0-15 LL_PWR_IsEnabledGPIOPullUp\n * PUCRC PU0-15 LL_PWR_IsEnabledGPIOPullUp\n - * PUCRD PU0-15 LL_PWR_IsEnabledGPIOPullUp\n - * (+) Port D is available only for STM32C031xx devices. + * PUCRD PU0-15 LL_PWR_IsEnabledGPIOPullUp (*)\n * PUCRF PU0-15 LL_PWR_IsEnabledGPIOPullUp + * @note (*) Port D availability depends on devices * @param GPIO This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_A * @arg @ref LL_PWR_GPIO_B * @arg @ref LL_PWR_GPIO_C - * @arg @ref LL_PWR_GPIO_D - * (+) Port D is available only for STM32C031xx devices. + * @arg @ref LL_PWR_GPIO_D (*) * @arg @ref LL_PWR_GPIO_F + * @note (*) Port D availability depends on devices * @param GPIONumber This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_BIT_0 * @arg @ref LL_PWR_GPIO_BIT_1 @@ -590,15 +699,14 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnabledGPIOPullUp(uint32_t GPIO, uint32_t GPIO * @rmtoll PDCRA PD0-15 LL_PWR_EnableGPIOPullDown\n * PDCRB PD0-15 LL_PWR_EnableGPIOPullDown\n * PDCRC PD0-15 LL_PWR_EnableGPIOPullDown\n - * PDCRD PD0-15 LL_PWR_EnableGPIOPullDown\n - * (+) Port D is available only for STM32C031xx devices. + * PDCRD PD0-15 LL_PWR_EnableGPIOPullDown (*)\n * PDCRF PD0-15 LL_PWR_EnableGPIOPullDown + * @note (*) Port D availability depends on devices * @param GPIO This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_A * @arg @ref LL_PWR_GPIO_B * @arg @ref LL_PWR_GPIO_C - * @arg @ref LL_PWR_GPIO_D - * (+) Port D is available only for STM32C031xx devices. + * @arg @ref LL_PWR_GPIO_D (*) * @arg @ref LL_PWR_GPIO_F * @param GPIONumber This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_BIT_0 @@ -629,15 +737,15 @@ __STATIC_INLINE void LL_PWR_EnableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumbe * @rmtoll PDCRA PD0-15 LL_PWR_DisableGPIOPullDown\n * PDCRB PD0-15 LL_PWR_DisableGPIOPullDown\n * PDCRC PD0-15 LL_PWR_DisableGPIOPullDown\n - * PDCRD PD0-15 LL_PWR_DisableGPIOPullDown\n - * (+) Port D is available only for STM32C031xx devices. + * PDCRD PD0-15 LL_PWR_DisableGPIOPullDown (*)\n * PDCRF PD0-15 LL_PWR_DisableGPIOPullDown + * @note (*) Port D availability depends on devices * @param GPIO This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_A * @arg @ref LL_PWR_GPIO_B * @arg @ref LL_PWR_GPIO_C - * @arg @ref LL_PWR_GPIO_D - * (+) Port D is available only for STM32C031xx devices. + * @arg @ref LL_PWR_GPIO_D (*) + * @note (*) Port D availability depends on devices * @arg @ref LL_PWR_GPIO_F * @param GPIONumber This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_BIT_0 @@ -668,16 +776,16 @@ __STATIC_INLINE void LL_PWR_DisableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumb * @rmtoll PDCRA PD0-15 LL_PWR_IsEnabledGPIOPullDown\n * PDCRB PD0-15 LL_PWR_IsEnabledGPIOPullDown\n * PDCRC PD0-15 LL_PWR_IsEnabledGPIOPullDown\n - * PDCRD PD0-15 LL_PWR_IsEnabledGPIOPullDown\n - * (+) Port D is available only for STM32C031xx devices. + * PDCRD PD0-15 LL_PWR_IsEnabledGPIOPullDown (*)\n + * @note (*) Port D availability depends on devices * PDCRF PD0-15 LL_PWR_IsEnabledGPIOPullDown * @param GPIO This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_A * @arg @ref LL_PWR_GPIO_B * @arg @ref LL_PWR_GPIO_C - * @arg @ref LL_PWR_GPIO_D - * (+) Port D is available only for STM32C031xx devices. + * @arg @ref LL_PWR_GPIO_D (*) * @arg @ref LL_PWR_GPIO_F + * @note (*) Port D availability depends on devices * @param GPIONumber This parameter can be one of the following values: * @arg @ref LL_PWR_GPIO_BIT_0 * @arg @ref LL_PWR_GPIO_BIT_1 @@ -772,7 +880,7 @@ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_InternWU(void) } /** - * @brief Get Stand-By Flag + * @brief Get Standby Flag * @rmtoll SR1 SBF LL_PWR_IsActiveFlag_SB * @retval State of bit (1 or 0). */ @@ -791,6 +899,17 @@ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_WU6(void) return ((READ_BIT(PWR->SR1, PWR_SR1_WUF6) == (PWR_SR1_WUF6)) ? 1UL : 0UL); } +#if defined(PWR_CR3_EWUP5) +/** + * @brief Get Wake-up Flag 5 + * @rmtoll SR1 WUF5 LL_PWR_IsActiveFlag_WU5 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_WU5(void) +{ + return ((READ_BIT(PWR->SR1, PWR_SR1_WUF5) == (PWR_SR1_WUF5)) ? 1UL : 0UL); +} +#endif /* PWR_CR3_EWUP5 */ /** * @brief Get Wake-up Flag 4 @@ -812,7 +931,6 @@ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_WU3(void) return ((READ_BIT(PWR->SR1, PWR_SR1_WUF3) == (PWR_SR1_WUF3)) ? 1UL : 0UL); } - /** * @brief Get Wake-up Flag 2 * @rmtoll SR1 WUF2 LL_PWR_IsActiveFlag_WU2 @@ -834,7 +952,7 @@ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_WU1(void) } /** - * @brief Clear Stand-By Flag + * @brief Clear Standby Flag * @rmtoll SCR CSBF LL_PWR_ClearFlag_SB * @retval None */ @@ -863,6 +981,18 @@ __STATIC_INLINE void LL_PWR_ClearFlag_WU6(void) WRITE_REG(PWR->SCR, PWR_SCR_CWUF6); } +#if defined(PWR_CR3_EWUP5) +/** + * @brief Clear Wake-up Flag 5 + * @rmtoll SCR CWUF5 LL_PWR_ClearFlag_WU5 + * @retval None + */ +__STATIC_INLINE void LL_PWR_ClearFlag_WU5(void) +{ + WRITE_REG(PWR->SCR, PWR_SCR_CWUF5); +} +#endif /* PWR_CR3_EWUP5 */ + /** * @brief Clear Wake-up Flag 4 * @rmtoll SCR CWUF4 LL_PWR_ClearFlag_WU4 @@ -903,6 +1033,19 @@ __STATIC_INLINE void LL_PWR_ClearFlag_WU1(void) WRITE_REG(PWR->SCR, PWR_SCR_CWUF1); } +#if defined (PWR_PVM_SUPPORT) +/** + * @brief Indicate whether VDD voltage is below or above the selected PVD + * threshold + * @rmtoll SR2 PVDMO_USB LL_PWR_IsActiveFlag_PVMOUSB + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_PVMOUSB(void) +{ + return ((READ_BIT(PWR->SR2, PWR_SR2_PVMO_VDDIO2) == (PWR_SR2_PVMO_VDDIO2)) ? 1UL : 0UL); +} +#endif /* PWR_PVM_SUPPORT */ + /** * @brief Indicate whether or not the flash is ready to be accessed * @rmtoll SR2 FLASH_RDY LL_PWR_IsActiveFlag_FLASH_RDY @@ -912,8 +1055,6 @@ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_FLASH_RDY(void) { return ((READ_BIT(PWR->SR2, PWR_SR2_FLASH_RDY) == (PWR_SR2_FLASH_RDY)) ? 1UL : 0UL); } - - /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rcc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rcc.h index 2342753a1..29ea98b71 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rcc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rcc.h @@ -42,8 +42,6 @@ extern "C" { /** @defgroup RCC_LL_Private_Variables RCC Private Variables * @{ */ - - /** * @} */ @@ -117,6 +115,12 @@ typedef struct #if !defined (EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE 48000000U /*!< Value of the I2S_CKIN external oscillator in Hz */ #endif /* EXTERNAL_CLOCK_VALUE */ + +#if defined(RCC_HSI48_SUPPORT) +#if !defined (HSI48_VALUE) +#define HSI48_VALUE 48000000U /*!< Value of the HSI48 oscillator in Hz */ +#endif /* HSI48_VALUE */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ @@ -131,6 +135,9 @@ typedef struct #define LL_RCC_CICR_HSERDYC RCC_CICR_HSERDYC /*!< HSE Ready Interrupt Clear */ #define LL_RCC_CICR_LSECSSC RCC_CICR_LSECSSC /*!< LSE Clock Security System Interrupt Clear */ #define LL_RCC_CICR_CSSC RCC_CICR_CSSC /*!< Clock Security System Interrupt Clear */ +#if defined(RCC_HSI48_SUPPORT) +#define LL_RCC_CICR_HSI48CSSC RCC_CICR_HSIUSB48RDYC /*!< HSI48 Ready Interrupt Clear */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ @@ -145,13 +152,16 @@ typedef struct #define LL_RCC_CIFR_HSERDYF RCC_CIFR_HSERDYF /*!< HSE Ready Interrupt flag */ #define LL_RCC_CIFR_LSECSSF RCC_CIFR_LSECSSF /*!< LSE Clock Security System Interrupt flag */ #define LL_RCC_CIFR_CSSF RCC_CIFR_CSSF /*!< Clock Security System Interrupt flag */ -#define LL_RCC_CSR_LPWRRSTF RCC_CSR_LPWRRSTF /*!< Low-Power reset flag */ -#define LL_RCC_CSR_OBLRSTF RCC_CSR_OBLRSTF /*!< OBL reset flag */ -#define LL_RCC_CSR_PINRSTF RCC_CSR_PINRSTF /*!< PIN reset flag */ -#define LL_RCC_CSR_SFTRSTF RCC_CSR_SFTRSTF /*!< Software Reset flag */ -#define LL_RCC_CSR_IWDGRSTF RCC_CSR_IWDGRSTF /*!< Independent Watchdog reset flag */ -#define LL_RCC_CSR_WWDGRSTF RCC_CSR_WWDGRSTF /*!< Window watchdog reset flag */ -#define LL_RCC_CSR_PWRRSTF RCC_CSR_PWRRSTF /*!< BOR or POR/PDR reset flag */ +#if defined(RCC_HSI48_SUPPORT) +#define LL_RCC_CIFR_HSI48RDYF RCC_CIFR_HSIUSB48RDYF /*!< HSI48 Ready Interrupt flag */ +#endif /* RCC_HSI48_SUPPORT */ +#define LL_RCC_CSR_LPWRRSTF RCC_CSR2_LPWRRSTF /*!< Low-Power reset flag */ +#define LL_RCC_CSR_OBLRSTF RCC_CSR2_OBLRSTF /*!< OBL reset flag */ +#define LL_RCC_CSR_PINRSTF RCC_CSR2_PINRSTF /*!< PIN reset flag */ +#define LL_RCC_CSR_SFTRSTF RCC_CSR2_SFTRSTF /*!< Software Reset flag */ +#define LL_RCC_CSR_IWDGRSTF RCC_CSR2_IWDGRSTF /*!< Independent Watchdog reset flag */ +#define LL_RCC_CSR_WWDGRSTF RCC_CSR2_WWDGRSTF /*!< Window watchdog reset flag */ +#define LL_RCC_CSR_PWRRSTF RCC_CSR2_PWRRSTF /*!< BOR or POR/PDR reset flag */ /** * @} */ @@ -193,6 +203,9 @@ typedef struct */ #define LL_RCC_SYS_CLKSOURCE_HSI 0x00000000U /*!< HSI selection as system clock */ #define LL_RCC_SYS_CLKSOURCE_HSE RCC_CFGR_SW_0 /*!< HSE selection as system clock */ +#if defined(RCC_HSI48_SUPPORT) +#define LL_RCC_SYS_CLKSOURCE_HSIUSB48 RCC_CFGR_SW_1 /*!< HSIUSB48 selection used as system clock */ +#endif /* RCC_HSI48_SUPPORT */ #define LL_RCC_SYS_CLKSOURCE_LSI (RCC_CFGR_SW_1 | RCC_CFGR_SW_0) /*!< LSI selection used as system clock */ #define LL_RCC_SYS_CLKSOURCE_LSE RCC_CFGR_SW_2 /*!< LSE selection used as system clock */ /** @@ -202,10 +215,32 @@ typedef struct /** @defgroup RCC_LL_EC_SYS_CLKSOURCE_STATUS System clock switch status * @{ */ -#define LL_RCC_SYS_CLKSOURCE_STATUS_HSI 0x00000000U /*!< HSI used as system clock */ -#define LL_RCC_SYS_CLKSOURCE_STATUS_HSE RCC_CFGR_SWS_0 /*!< HSE used as system clock */ -#define LL_RCC_SYS_CLKSOURCE_STATUS_LSI (RCC_CFGR_SWS_1 | RCC_CFGR_SWS_0) /*!< LSI used as system clock */ -#define LL_RCC_SYS_CLKSOURCE_STATUS_LSE RCC_CFGR_SWS_2 /*!< LSE used as system clock */ +#define LL_RCC_SYS_CLKSOURCE_STATUS_HSI 0x00000000U /*!< HSI used as system clock */ +#define LL_RCC_SYS_CLKSOURCE_STATUS_HSE RCC_CFGR_SWS_0 /*!< HSE used as system clock */ +#if defined(RCC_HSI48_SUPPORT) +#define LL_RCC_SYS_CLKSOURCE_STATUS_HSIUSB48 RCC_CFGR_SWS_1 /*!< HSIUSB48 used as system clock */ +#endif /* RCC_HSI48_SUPPORT */ +#define LL_RCC_SYS_CLKSOURCE_STATUS_LSI (RCC_CFGR_SWS_1 | RCC_CFGR_SWS_0) /*!< LSI used as system clock */ +#define LL_RCC_SYS_CLKSOURCE_STATUS_LSE RCC_CFGR_SWS_2 /*!< LSE used as system clock */ +/** + * @} + */ + +/** @defgroup RCC_LL_EC_SYSCLK_DIV AHB prescaler + * @{ + */ +#if defined(RCC_CR_SYSDIV) +#define LL_RCC_SYSCLK_DIV_1 0x00000000U /*!< SYSCLK not divided */ +#define LL_RCC_SYSCLK_DIV_2 RCC_CR_SYSDIV_0 /*!< SYSCLK divided by 2 */ +#define LL_RCC_SYSCLK_DIV_3 RCC_CR_SYSDIV_1 /*!< SYSCLK divided by 3 */ +#define LL_RCC_SYSCLK_DIV_4 (RCC_CR_SYSDIV_1 | RCC_CR_SYSDIV_0) /*!< SYSCLK divided by 4 */ +#define LL_RCC_SYSCLK_DIV_5 RCC_CR_SYSDIV_2 /*!< SYSCLK divided by 5 */ +#define LL_RCC_SYSCLK_DIV_6 (RCC_CR_SYSDIV_2 | RCC_CR_SYSDIV_0) /*!< SYSCLK divided by 6 */ +#define LL_RCC_SYSCLK_DIV_7 (RCC_CR_SYSDIV_2 | RCC_CR_SYSDIV_1) /*!< SYSCLK divided by 7 */ +#define LL_RCC_SYSCLK_DIV_8 (RCC_CR_SYSDIV_2 | RCC_CR_SYSDIV_1 | RCC_CR_SYSDIV_0) /*!< SYSCLK divided by 8 */ +#else +#define LL_RCC_SYSCLK_DIV_1 0x00000000U /*!< SYSCLK not divided */ +#endif /* RCC_CR_SYSDIV */ /** * @} */ @@ -213,15 +248,15 @@ typedef struct /** @defgroup RCC_HCLK_Clock_Source RCC HCLK Clock Source * @{ */ -#define LL_RCC_SYSCLK_DIV_1 0x00000000U /*!< HCLK not divided */ -#define LL_RCC_SYSCLK_DIV_2 RCC_CFGR_HPRE_3 /*!< HCLK divided by 2 */ -#define LL_RCC_SYSCLK_DIV_4 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 4 */ -#define LL_RCC_SYSCLK_DIV_8 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 8 */ -#define LL_RCC_SYSCLK_DIV_16 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 16 */ -#define LL_RCC_SYSCLK_DIV_64 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2) /*!< HCLK divided by 64 */ -#define LL_RCC_SYSCLK_DIV_128 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 128 */ -#define LL_RCC_SYSCLK_DIV_256 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 256 */ -#define LL_RCC_SYSCLK_DIV_512 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 512 */ +#define LL_RCC_HCLK_DIV_1 0x00000000U /*!< HCLK not divided */ +#define LL_RCC_HCLK_DIV_2 RCC_CFGR_HPRE_3 /*!< HCLK divided by 2 */ +#define LL_RCC_HCLK_DIV_4 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 4 */ +#define LL_RCC_HCLK_DIV_8 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 8 */ +#define LL_RCC_HCLK_DIV_16 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 16 */ +#define LL_RCC_HCLK_DIV_64 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2) /*!< HCLK divided by 64 */ +#define LL_RCC_HCLK_DIV_128 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 128 */ +#define LL_RCC_HCLK_DIV_256 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1) /*!< HCLK divided by 256 */ +#define LL_RCC_HCLK_DIV_512 (RCC_CFGR_HPRE_3 | RCC_CFGR_HPRE_2 | RCC_CFGR_HPRE_1 | RCC_CFGR_HPRE_0) /*!< HCLK divided by 512 */ /** * @} */ @@ -229,11 +264,11 @@ typedef struct /** @defgroup RCC_LL_EC_APB1_DIV APB low-speed prescaler (APB1) * @{ */ -#define LL_RCC_APB1_DIV_1 0x00000000U /*!< HCLK not divided */ -#define LL_RCC_APB1_DIV_2 RCC_CFGR_PPRE_2 /*!< HCLK divided by 2 */ -#define LL_RCC_APB1_DIV_4 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_0) /*!< HCLK divided by 4 */ -#define LL_RCC_APB1_DIV_8 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1) /*!< HCLK divided by 8 */ -#define LL_RCC_APB1_DIV_16 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1 | RCC_CFGR_PPRE_0) /*!< HCLK divided by 16 */ +#define LL_RCC_APB1_DIV_1 0x00000000U /*!< HCLK not divided */ +#define LL_RCC_APB1_DIV_2 RCC_CFGR_PPRE_2 /*!< HCLK divided by 2 */ +#define LL_RCC_APB1_DIV_4 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_0) /*!< HCLK divided by 4 */ +#define LL_RCC_APB1_DIV_8 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1) /*!< HCLK divided by 8 */ +#define LL_RCC_APB1_DIV_16 (RCC_CFGR_PPRE_2 | RCC_CFGR_PPRE_1 | RCC_CFGR_PPRE_0) /*!< HCLK divided by 16 */ /** * @} */ @@ -277,6 +312,9 @@ typedef struct #define LL_RCC_MCO1SOURCE_HSE RCC_CFGR_MCOSEL_2 /*!< HSE selection as MCO1 source */ #define LL_RCC_MCO1SOURCE_LSI (RCC_CFGR_MCOSEL_1|RCC_CFGR_MCOSEL_2) /*!< LSI selection as MCO1 source */ #define LL_RCC_MCO1SOURCE_LSE (RCC_CFGR_MCOSEL_0|RCC_CFGR_MCOSEL_1|RCC_CFGR_MCOSEL_2) /*!< LSE selection as MCO1 source */ +#if defined(RCC_HSI48_SUPPORT) +#define LL_RCC_MCO1SOURCE_HSIUSB48 RCC_CFGR_MCOSEL_3 /*!< HSIUSB48 selection as MCO1 source */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ @@ -284,14 +322,19 @@ typedef struct /** @defgroup RCC_LL_EC_MCO1_DIV MCO1 prescaler * @{ */ -#define LL_RCC_MCO1_DIV_1 0x00000000U /*!< MCO1 not divided */ -#define LL_RCC_MCO1_DIV_2 RCC_CFGR_MCOPRE_0 /*!< MCO1 divided by 2 */ -#define LL_RCC_MCO1_DIV_4 RCC_CFGR_MCOPRE_1 /*!< MCO1 divided by 4 */ -#define LL_RCC_MCO1_DIV_8 (RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 8 */ -#define LL_RCC_MCO1_DIV_16 RCC_CFGR_MCOPRE_2 /*!< MCO1 divided by 16 */ -#define LL_RCC_MCO1_DIV_32 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 32 */ -#define LL_RCC_MCO1_DIV_64 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1) /*!< MCO1 divided by 64 */ -#define LL_RCC_MCO1_DIV_128 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 128 */ +#define LL_RCC_MCO1_DIV_1 0x00000000U /*!< MCO1 not divided */ +#define LL_RCC_MCO1_DIV_2 RCC_CFGR_MCOPRE_0 /*!< MCO1 divided by 2 */ +#define LL_RCC_MCO1_DIV_4 RCC_CFGR_MCOPRE_1 /*!< MCO1 divided by 4 */ +#define LL_RCC_MCO1_DIV_8 (RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 8 */ +#define LL_RCC_MCO1_DIV_16 RCC_CFGR_MCOPRE_2 /*!< MCO1 divided by 16 */ +#define LL_RCC_MCO1_DIV_32 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 32 */ +#define LL_RCC_MCO1_DIV_64 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1) /*!< MCO1 divided by 64 */ +#define LL_RCC_MCO1_DIV_128 (RCC_CFGR_MCOPRE_2 | RCC_CFGR_MCOPRE_1 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 128 */ +#if defined(RCC_CFGR_MCOPRE_3) +#define LL_RCC_MCO1_DIV_256 RCC_CFGR_MCOPRE_3 /*!< MCO1 divided by 256 */ +#define LL_RCC_MCO1_DIV_512 (RCC_CFGR_MCOPRE_3 | RCC_CFGR_MCOPRE_0) /*!< MCO1 divided by 512 */ +#define LL_RCC_MCO1_DIV_1024 (RCC_CFGR_MCOPRE_3 | RCC_CFGR_MCOPRE_1) /*!< MCO1 divided by 1024 */ +#endif /* RCC_CFGR_MCOPRE_3 */ /** * @} */ @@ -305,6 +348,9 @@ typedef struct #define LL_RCC_MCO2SOURCE_HSE RCC_CFGR_MCO2SEL_2 /*!< HSE selection as MCO2 source */ #define LL_RCC_MCO2SOURCE_LSI (RCC_CFGR_MCO2SEL_1|RCC_CFGR_MCO2SEL_2) /*!< LSI selection as MCO2 source */ #define LL_RCC_MCO2SOURCE_LSE (RCC_CFGR_MCO2SEL_0|RCC_CFGR_MCO2SEL_1|RCC_CFGR_MCO2SEL_2) /*!< LSE selection as MCO2 source */ +#if defined(RCC_HSI48_SUPPORT) +#define LL_RCC_MCO2SOURCE_HSIUSB48 RCC_CFGR_MCO2SEL_3 /*!< HSIUSB48 selection as MCO2 source */ +#endif /* RCC_HSI48_SUPPORT */ /** * @} */ @@ -312,14 +358,19 @@ typedef struct /** @defgroup RCC_LL_EC_MCO2_DIV MCO2 prescaler * @{ */ -#define LL_RCC_MCO2_DIV_1 0x00000000U /*!< MCO2 not divided */ -#define LL_RCC_MCO2_DIV_2 RCC_CFGR_MCO2PRE_0 /*!< MCO2 divided by 2 */ -#define LL_RCC_MCO2_DIV_4 RCC_CFGR_MCO2PRE_1 /*!< MCO2 divided by 4 */ -#define LL_RCC_MCO2_DIV_8 (RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO2 divided by 8 */ -#define LL_RCC_MCO2_DIV_16 RCC_CFGR_MCO2PRE_2 /*!< MCO2 divided by 16 */ -#define LL_RCC_MCO2_DIV_32 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_0) /*!< MCO2 divided by 32 */ -#define LL_RCC_MCO2_DIV_64 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1) /*!< MCO2 divided by 64 */ -#define LL_RCC_MCO2_DIV_128 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO2 divided by 128 */ +#define LL_RCC_MCO2_DIV_1 0x00000000U /*!< MCO2 not divided */ +#define LL_RCC_MCO2_DIV_2 RCC_CFGR_MCO2PRE_0 /*!< MCO2 divided by 2 */ +#define LL_RCC_MCO2_DIV_4 RCC_CFGR_MCO2PRE_1 /*!< MCO2 divided by 4 */ +#define LL_RCC_MCO2_DIV_8 (RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO2 divided by 8 */ +#define LL_RCC_MCO2_DIV_16 RCC_CFGR_MCO2PRE_2 /*!< MCO2 divided by 16 */ +#define LL_RCC_MCO2_DIV_32 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_0) /*!< MCO2 divided by 32 */ +#define LL_RCC_MCO2_DIV_64 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1) /*!< MCO2 divided by 64 */ +#define LL_RCC_MCO2_DIV_128 (RCC_CFGR_MCO2PRE_2 | RCC_CFGR_MCO2PRE_1 | RCC_CFGR_MCO2PRE_0) /*!< MCO2 divided by 128 */ +#if defined(RCC_CFGR_MCO2PRE_3) +#define LL_RCC_MCO2_DIV_256 RCC_CFGR_MCO2PRE_3 /*!< MCO1 divided by 256 */ +#define LL_RCC_MCO2_DIV_512 (RCC_CFGR_MCO2PRE_3 | RCC_CFGR_MCO2PRE_0) /*!< MCO1 divided by 512 */ +#define LL_RCC_MCO2_DIV_1024 (RCC_CFGR_MCO2PRE_3 | RCC_CFGR_MCO2PRE_1) /*!< MCO1 divided by 1024 */ +#endif /* RCC_CFGR_MCO2PRE_3 */ /** * @} */ @@ -327,8 +378,8 @@ typedef struct /** @defgroup RCC_LL_EC_PERIPH_FREQUENCY Peripheral clock frequency * @{ */ -#define LL_RCC_PERIPH_FREQUENCY_NO 0x00000000U /*!< No clock enabled for the peripheral */ -#define LL_RCC_PERIPH_FREQUENCY_NA 0xFFFFFFFFU /*!< Frequency cannot be provided as external clock */ +#define LL_RCC_PERIPH_FREQUENCY_NO 0x00000000U /*!< No clock enabled for the peripheral */ +#define LL_RCC_PERIPH_FREQUENCY_NA 0xFFFFFFFFU /*!< Frequency cannot be provided as external clock */ /** * @} */ @@ -347,12 +398,17 @@ typedef struct */ -/** @defgroup RCC_LL_EC_I2C1_CLKSOURCE Peripheral I2C clock source selection +/** @defgroup RCC_LL_EC_I2Cx_CLKSOURCE Peripheral I2C clock source selection * @{ */ #define LL_RCC_I2C1_CLKSOURCE_PCLK1 0x00000000U /*!< PCLK1 clock used as I2C1 clock source */ #define LL_RCC_I2C1_CLKSOURCE_SYSCLK RCC_CCIPR_I2C1SEL_0 /*!< SYSCLK clock used as I2C1 clock source */ #define LL_RCC_I2C1_CLKSOURCE_HSIKER RCC_CCIPR_I2C1SEL_1 /*!< HSIKER clock used as I2C1 clock source */ +#if defined(I2C2) +#define LL_RCC_I2C2_CLKSOURCE_PCLK1 0x00000000U /*!< PCLK1 clock used as I2C2 clock source */ +#define LL_RCC_I2C2_CLKSOURCE_SYSCLK RCC_CCIPR_I2C1SEL_0 /*!< SYSCLK clock used as I2C2 clock source */ +#define LL_RCC_I2C2_CLKSOURCE_HSIKER RCC_CCIPR_I2C1SEL_1 /*!< HSIKER clock used as I2C2 clock source */ +#endif /* I2C2 */ /** * @} */ @@ -388,6 +444,9 @@ typedef struct * @{ */ #define LL_RCC_I2C1_CLKSOURCE RCC_CCIPR_I2C1SEL /*!< I2C1 Clock source selection */ +#if defined(I2C2) +#define LL_RCC_I2C2_CLKSOURCE RCC_CCIPR_I2C1SEL /*!< I2C2 Clock source selection */ +#endif /* I2C2 */ /** * @} */ @@ -415,10 +474,27 @@ typedef struct #define LL_RCC_RTC_CLKSOURCE_LSE RCC_CSR1_RTCSEL_0 /*!< LSE oscillator clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_LSI RCC_CSR1_RTCSEL_1 /*!< LSI oscillator clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_HSE_DIV32 RCC_CSR1_RTCSEL /*!< HSE oscillator clock divided by 32 used as RTC clock */ +/** + * @} + */ +#if defined(USB_DRD_FS) +/** @defgroup RCC_LL_EC_USB_CLKSOURCE Peripheral USB clock source selection + * @{ + */ +#define LL_RCC_USB_CLKSOURCE_HSI48 0x00000000U /*!< HSI48 clock used as USB clock source */ +#define LL_RCC_USB_CLKSOURCE_HSE RCC_CCIPR2_USBSEL /*!< HSE clock used as USB clock source */ +/** @defgroup RCC_LL_EC_USB Peripheral USB get clock source + * @{ + */ +#define LL_RCC_USB_CLKSOURCE RCC_CCIPR2_USBSEL /*!< USB Clock source selection */ /** * @} */ +/** + * @} + */ +#endif /* USB_DRD_FS */ /** * @} */ @@ -452,24 +528,25 @@ typedef struct /** * @brief Helper macro to calculate the HCLK frequency - * @param __SYSCLKFREQ__ SYSCLK frequency (based on HSE/HSI/PLLCLK) + * @param __SYSCLKFREQ__ SYSCLK frequency (based on HSE/HSI/LSE/LSI) * @param __AHBPRESCALER__ This parameter can be one of the following values: - * @arg @ref LL_RCC_SYSCLK_DIV_1 - * @arg @ref LL_RCC_SYSCLK_DIV_2 - * @arg @ref LL_RCC_SYSCLK_DIV_4 - * @arg @ref LL_RCC_SYSCLK_DIV_8 - * @arg @ref LL_RCC_SYSCLK_DIV_16 - * @arg @ref LL_RCC_SYSCLK_DIV_64 - * @arg @ref LL_RCC_SYSCLK_DIV_128 - * @arg @ref LL_RCC_SYSCLK_DIV_256 - * @arg @ref LL_RCC_SYSCLK_DIV_512 + * @arg @ref LL_RCC_HCLK_DIV_1 + * @arg @ref LL_RCC_HCLK_DIV_2 + * @arg @ref LL_RCC_HCLK_DIV_4 + * @arg @ref LL_RCC_HCLK_DIV_8 + * @arg @ref LL_RCC_HCLK_DIV_16 + * @arg @ref LL_RCC_HCLK_DIV_64 + * @arg @ref LL_RCC_HCLK_DIV_128 + * @arg @ref LL_RCC_HCLK_DIV_256 + * @arg @ref LL_RCC_HCLK_DIV_512 * @retval HCLK clock frequency (in Hz) */ -#define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__,__AHBPRESCALER__) ((__SYSCLKFREQ__) >> (AHBPrescTable[((__AHBPRESCALER__)\ - & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos] & 0x1FU)) +#define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__,__AHBPRESCALER__) \ + ((__SYSCLKFREQ__) >> (AHBPrescTable[((__AHBPRESCALER__)\ + & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos] & 0x1FU)) /** - * @brief Helper macro to calculate the PCLK1 frequency (ABP1) + * @brief Helper macro to calculate the PCLK1 frequency (APB1) * @param __HCLKFREQ__ HCLK frequency * @param __APB1PRESCALER__ This parameter can be one of the following values: * @arg @ref LL_RCC_APB1_DIV_1 @@ -479,8 +556,9 @@ typedef struct * @arg @ref LL_RCC_APB1_DIV_16 * @retval PCLK1 clock frequency (in Hz) */ -#define __LL_RCC_CALC_PCLK1_FREQ(__HCLKFREQ__, __APB1PRESCALER__) ((__HCLKFREQ__) >> (APBPrescTable[(__APB1PRESCALER__) >> RCC_CFGR_PPRE_Pos]\ - & 0x1FU)) +#define __LL_RCC_CALC_PCLK1_FREQ(__HCLKFREQ__, __APB1PRESCALER__) \ + ((__HCLKFREQ__) >> (APBPrescTable[(__APB1PRESCALER__) >> RCC_CFGR_PPRE_Pos]\ + & 0x1FU)) /** * @brief Helper macro to calculate the HSISYS frequency @@ -769,6 +847,46 @@ __STATIC_INLINE uint32_t LL_RCC_HSI_GetCalibTrimming(void) * @} */ +#if defined(RCC_HSI48_SUPPORT) +/** @defgroup RCC_LL_EF_HSI48 HSI48 + * @{ + */ + +/** + * @brief Enable HSI48 + * @rmtoll CR HSI48ON LL_RCC_HSI48_Enable + * @retval None + */ +__STATIC_INLINE void LL_RCC_HSI48_Enable(void) +{ + SET_BIT(RCC->CR, RCC_CR_HSIUSB48ON); +} + +/** + * @brief Disable HSI48 + * @rmtoll CR HSI48ON LL_RCC_HSI48_Disable + * @retval None + */ +__STATIC_INLINE void LL_RCC_HSI48_Disable(void) +{ + CLEAR_BIT(RCC->CR, RCC_CR_HSIUSB48ON); +} + +/** + * @brief Check if HSI48 oscillator Ready + * @rmtoll CR HSI48RDY LL_RCC_HSI48_IsReady + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_RCC_HSI48_IsReady(void) +{ + return ((READ_BIT(RCC->CR, RCC_CR_HSIUSB48RDY) == RCC_CR_HSIUSB48RDY) ? 1UL : 0UL); +} + +/** + * @} + */ +#endif /* RCC_HSI48_SUPPORT */ + /** @defgroup RCC_LL_EF_LSE LSE * @{ */ @@ -990,8 +1108,10 @@ __STATIC_INLINE uint32_t LL_RCC_LSCO_GetSource(void) * @param Source This parameter can be one of the following values: * @arg @ref LL_RCC_SYS_CLKSOURCE_HSI * @arg @ref LL_RCC_SYS_CLKSOURCE_HSE + * @arg @ref LL_RCC_SYS_CLKSOURCE_HSIUSB48 (*) * @arg @ref LL_RCC_SYS_CLKSOURCE_LSI * @arg @ref LL_RCC_SYS_CLKSOURCE_LSE + * @note (*) peripheral not available on all devices * @retval None */ __STATIC_INLINE void LL_RCC_SetSysClkSource(uint32_t Source) @@ -1005,14 +1125,37 @@ __STATIC_INLINE void LL_RCC_SetSysClkSource(uint32_t Source) * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_HSI * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_HSE + * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_HSIUSB48 (*) * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_LSI * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_LSE + * @note (*) peripheral not available on all devices */ __STATIC_INLINE uint32_t LL_RCC_GetSysClkSource(void) { return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_SWS)); } +#if defined(RCC_CR_SYSDIV) +/** + * @brief Set SYS DIV + * @rmtoll CR SYSDIV LL_RCC_SetSYSDivider + * @param Divider This parameter can be one of the following values: + * @arg @ref LL_RCC_SYSCLK_DIV_1 + * @arg @ref LL_RCC_SYSCLK_DIV_2 + * @arg @ref LL_RCC_SYSCLK_DIV_3 + * @arg @ref LL_RCC_SYSCLK_DIV_4 + * @arg @ref LL_RCC_SYSCLK_DIV_5 + * @arg @ref LL_RCC_SYSCLK_DIV_6 + * @arg @ref LL_RCC_SYSCLK_DIV_7 + * @arg @ref LL_RCC_SYSCLK_DIV_8 + * @retval None + */ +__STATIC_INLINE void LL_RCC_SetSYSDivider(uint32_t Divider) +{ + MODIFY_REG(RCC->CR, RCC_CR_SYSDIV, Divider); +} +#endif /* RCC_CR_SYSDIV */ + /** * @brief Set AHB prescaler * @rmtoll CFGR HPRE LL_RCC_SetAHBPrescaler @@ -1088,6 +1231,27 @@ __STATIC_INLINE void LL_RCC_SetHSIKERDiv(uint32_t HSIKERDiv) { MODIFY_REG(RCC->CR, RCC_CR_HSIKERDIV, HSIKERDiv); } + +#if defined(RCC_CR_SYSDIV) +/** + * @brief Get SYS divider + * @rmtoll CR SYSDIV LL_RCC_GetSYSDivider + * @retval Returned value can be one of the following values: + * @arg @ref LL_RCC_SYSCLK_DIV_1 + * @arg @ref LL_RCC_SYSCLK_DIV_2 + * @arg @ref LL_RCC_SYSCLK_DIV_3 + * @arg @ref LL_RCC_SYSCLK_DIV_4 + * @arg @ref LL_RCC_SYSCLK_DIV_5 + * @arg @ref LL_RCC_SYSCLK_DIV_6 + * @arg @ref LL_RCC_SYSCLK_DIV_7 + * @arg @ref LL_RCC_SYSCLK_DIV_8 + */ +__STATIC_INLINE uint32_t LL_RCC_GetSYSDivider(void) +{ + return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_SYSDIV)); +} +#endif /* RCC_CR_SYSDIV */ + /** * @brief Get AHB prescaler * @rmtoll CFGR HPRE LL_RCC_GetAHBPrescaler @@ -1159,6 +1323,7 @@ __STATIC_INLINE uint32_t LL_RCC_GetHSIDiv(void) * @arg @ref LL_RCC_MCO1SOURCE_NOCLOCK * @arg @ref LL_RCC_MCO1SOURCE_SYSCLK * @arg @ref LL_RCC_MCO1SOURCE_HSI + * @arg @ref LL_RCC_MCO1SOURCE_HSIUSB48 (*) * @arg @ref LL_RCC_MCO1SOURCE_HSE * @arg @ref LL_RCC_MCO1SOURCE_LSI * @arg @ref LL_RCC_MCO1SOURCE_LSE @@ -1171,6 +1336,10 @@ __STATIC_INLINE uint32_t LL_RCC_GetHSIDiv(void) * @arg @ref LL_RCC_MCO1_DIV_32 * @arg @ref LL_RCC_MCO1_DIV_64 * @arg @ref LL_RCC_MCO1_DIV_128 + * @arg @ref LL_RCC_MCO1_DIV_256 (*) + * @arg @ref LL_RCC_MCO1_DIV_512 (*) + * @arg @ref LL_RCC_MCO1_DIV_1024 (*) + * @note (*) not available on all devices * @retval None */ __STATIC_INLINE void LL_RCC_ConfigMCO(uint32_t MCOxSource, uint32_t MCOxPrescaler) @@ -1195,6 +1364,7 @@ __STATIC_INLINE void LL_RCC_ConfigMCO(uint32_t MCOxSource, uint32_t MCOxPrescale * @arg @ref LL_RCC_MCO2SOURCE_NOCLOCK * @arg @ref LL_RCC_MCO2SOURCE_SYSCLK * @arg @ref LL_RCC_MCO2SOURCE_HSI + * @arg @ref LL_RCC_MCO2SOURCE_HSIUSB48 (*) * @arg @ref LL_RCC_MCO2SOURCE_HSE * @arg @ref LL_RCC_MCO2SOURCE_LSI * @arg @ref LL_RCC_MCO2SOURCE_LSE @@ -1207,6 +1377,10 @@ __STATIC_INLINE void LL_RCC_ConfigMCO(uint32_t MCOxSource, uint32_t MCOxPrescale * @arg @ref LL_RCC_MCO2_DIV_32 * @arg @ref LL_RCC_MCO2_DIV_64 * @arg @ref LL_RCC_MCO2_DIV_128 + * @arg @ref LL_RCC_MCO2_DIV_256 (*) + * @arg @ref LL_RCC_MCO2_DIV_512 (*) + * @arg @ref LL_RCC_MCO2_DIV_1024 (*) + * @note (*) not available on all devices * @retval None */ __STATIC_INLINE void LL_RCC_ConfigMCO2(uint32_t MCOxSource, uint32_t MCOxPrescaler) @@ -1236,7 +1410,6 @@ __STATIC_INLINE void LL_RCC_SetUSARTClockSource(uint32_t USARTxSource) MODIFY_REG(RCC->CCIPR, (USARTxSource >> 16U), (USARTxSource & 0x0000FFFFU)); } - /** * @brief Configure I2Cx clock source * @rmtoll CCIPR I2C1SEL LL_RCC_SetI2CClockSource @@ -1251,7 +1424,6 @@ __STATIC_INLINE void LL_RCC_SetI2CClockSource(uint32_t I2CxSource) MODIFY_REG(RCC->CCIPR, RCC_CCIPR_I2C1SEL, I2CxSource); } - /** * @brief Configure ADC clock source * @rmtoll CCIPR ADCSEL LL_RCC_SetADCClockSource @@ -1279,6 +1451,23 @@ __STATIC_INLINE void LL_RCC_SetI2SClockSource(uint32_t I2SxSource) MODIFY_REG(RCC->CCIPR, RCC_CCIPR_I2S1SEL, I2SxSource); } +#if defined (USB_DRD_FS) +/** + * @brief Configure USB clock source + * @rmtoll CCIPR2 CK48MSEL LL_RCC_SetUSBClockSource + * @param USBxSource This parameter can be one of the following values: + * @arg @ref LL_RCC_USB_CLKSOURCE_HSI48 + * @arg @ref LL_RCC_USB_CLKSOURCE_HSE + * + * (*) value not defined in all devices. + * @retval None + */ +__STATIC_INLINE void LL_RCC_SetUSBClockSource(uint32_t USBxSource) +{ + MODIFY_REG(RCC->CCIPR2, RCC_CCIPR2_USBSEL, USBxSource); +} +#endif /* USB_DRD_FS */ + /** * @brief Get USARTx clock source * @rmtoll CCIPR USART1SEL LL_RCC_GetUSARTClockSource @@ -1295,7 +1484,6 @@ __STATIC_INLINE uint32_t LL_RCC_GetUSARTClockSource(uint32_t USARTx) return (uint32_t)(READ_BIT(RCC->CCIPR, USARTx) | (USARTx << 16U)); } - /** * @brief Get I2Cx clock source * @rmtoll CCIPR I2C1SEL LL_RCC_GetI2CClockSource @@ -1339,6 +1527,22 @@ __STATIC_INLINE uint32_t LL_RCC_GetI2SClockSource(uint32_t I2Sx) { return (uint32_t)(READ_BIT(RCC->CCIPR, I2Sx)); } + +#if defined (USB_DRD_FS) +/** + * @brief Get USBx clock source + * @rmtoll CCIPR2 CK48MSEL LL_RCC_GetUSBClockSource + * @param USBx This parameter can be one of the following values: + * @arg @ref LL_RCC_USB_CLKSOURCE + * @retval Returned value can be one of the following values: + * @arg @ref LL_RCC_USB_CLKSOURCE_HSI48 + */ +__STATIC_INLINE uint32_t LL_RCC_GetUSBClockSource(uint32_t USBx) +{ + return (uint32_t)(READ_BIT(RCC->CCIPR2, USBx)); +} +#endif /* USB_DRD_FS */ + /** * @} */ @@ -1457,6 +1661,18 @@ __STATIC_INLINE void LL_RCC_ClearFlag_LSERDY(void) SET_BIT(RCC->CICR, RCC_CICR_LSERDYC); } +#if defined(RCC_HSI48_SUPPORT) +/** + * @brief Clear HSI48 ready interrupt flag + * @rmtoll CICR HSI48RDYC LL_RCC_ClearFlag_HSI48RDY + * @retval None + */ +__STATIC_INLINE void LL_RCC_ClearFlag_HSI48RDY(void) +{ + SET_BIT(RCC->CICR, RCC_CICR_HSIUSB48RDYC); +} +#endif /* RCC_HSI48_SUPPORT */ + /** * @brief Clear HSI ready interrupt flag * @rmtoll CICR HSIRDYC LL_RCC_ClearFlag_HSIRDY @@ -1517,6 +1733,18 @@ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_LSERDY(void) return ((READ_BIT(RCC->CIFR, RCC_CIFR_LSERDYF) == (RCC_CIFR_LSERDYF)) ? 1UL : 0UL); } +#if defined(RCC_HSI48_SUPPORT) +/** + * @brief Check if HSI48 ready interrupt occurred or not + * @rmtoll CIR HSI48RDYF LL_RCC_IsActiveFlag_HSI48RDY + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_HSI48RDY(void) +{ + return ((READ_BIT(RCC->CIFR, RCC_CIFR_HSIUSB48RDYF) == (RCC_CIFR_HSIUSB48RDYF)) ? 1UL : 0UL); +} +#endif /* RCC_HSI48_SUPPORT */ + /** * @brief Check if HSI ready interrupt occurred or not * @rmtoll CIFR HSIRDYF LL_RCC_IsActiveFlag_HSIRDY @@ -1665,6 +1893,18 @@ __STATIC_INLINE void LL_RCC_EnableIT_LSERDY(void) SET_BIT(RCC->CIER, RCC_CIER_LSERDYIE); } +#if defined(RCC_HSI48_SUPPORT) +/** + * @brief Enable HSI48 ready interrupt + * @rmtoll CIER HSI48RDYIE LL_RCC_EnableIT_HSI48RDY + * @retval None + */ +__STATIC_INLINE void LL_RCC_EnableIT_HSI48RDY(void) +{ + SET_BIT(RCC->CIER, RCC_CIER_HSIUSB48RDYIE); +} +#endif /* RCC_HSI48_SUPPORT */ + /** * @brief Enable HSI ready interrupt * @rmtoll CIER HSIRDYIE LL_RCC_EnableIT_HSIRDY @@ -1705,6 +1945,18 @@ __STATIC_INLINE void LL_RCC_DisableIT_LSERDY(void) CLEAR_BIT(RCC->CIER, RCC_CIER_LSERDYIE); } +#if defined(RCC_HSI48_SUPPORT) +/** + * @brief Disable HSI48 ready interrupt + * @rmtoll CIER HSI48RDYIE LL_RCC_DisableIT_HSI48RDY + * @retval None + */ +__STATIC_INLINE void LL_RCC_DisableIT_HSI48RDY(void) +{ + CLEAR_BIT(RCC->CIER, RCC_CIER_HSIUSB48RDYIE); +} +#endif /* RCC_HSI48_SUPPORT */ + /** * @brief Disable HSI ready interrupt * @rmtoll CIER HSIRDYIE LL_RCC_DisableIT_HSIRDY @@ -1746,6 +1998,18 @@ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_LSERDY(void) return ((READ_BIT(RCC->CIER, RCC_CIER_LSERDYIE) == (RCC_CIER_LSERDYIE)) ? 1UL : 0UL); } +#if defined(RCC_HSI48_SUPPORT) +/** + * @brief Checks if HSI48 ready interrupt source is enabled or disabled. + * @rmtoll CIER HSI48RDYIE LL_RCC_IsEnabledIT_HSI48RDY + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_HSI48RDY(void) +{ + return ((READ_BIT(RCC->CIER, RCC_CIER_HSIUSB48RDYIE) == (RCC_CIER_HSIUSB48RDYIE)) ? 1UL : 0UL); +} +#endif /* RCC_HSI48_SUPPORT */ + /** * @brief Checks if HSI ready interrupt source is enabled or disabled. * @rmtoll CIER HSIRDYIE LL_RCC_IsEnabledIT_HSIRDY @@ -1788,6 +2052,9 @@ uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource); uint32_t LL_RCC_GetADCClockFreq(uint32_t ADCxSource); uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource); uint32_t LL_RCC_GetRTCClockFreq(void); +#if defined(USB_DRD_FS) +uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource); +#endif /* USB_DRD_FS */ /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rtc.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rtc.h index f229236e3..487aa54b5 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rtc.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_rtc.h @@ -111,23 +111,28 @@ typedef struct uint32_t TimeFormat; /*!< Specifies the RTC AM/PM Time. This parameter can be a value of @ref RTC_LL_EC_TIME_FORMAT - This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetFormat(). */ + This feature can be modified afterwards using unitary function + @ref LL_RTC_TIME_SetFormat(). */ uint8_t Hours; /*!< Specifies the RTC Time Hours. - This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the @ref LL_RTC_TIME_FORMAT_PM is selected. - This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the @ref LL_RTC_TIME_FORMAT_AM_OR_24 is selected. + This parameter must be a number between Min_Data = 0 and Max_Data = 12 + if the @ref LL_RTC_TIME_FORMAT_PM is selected. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 + if the @ref LL_RTC_TIME_FORMAT_AM_OR_24 is selected. - This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetHour(). */ + This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetHour().*/ uint8_t Minutes; /*!< Specifies the RTC Time Minutes. This parameter must be a number between Min_Data = 0 and Max_Data = 59 - This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetMinute(). */ + This feature can be modified afterwards using unitary function + @ref LL_RTC_TIME_SetMinute(). */ uint8_t Seconds; /*!< Specifies the RTC Time Seconds. This parameter must be a number between Min_Data = 0 and Max_Data = 59 - This feature can be modified afterwards using unitary function @ref LL_RTC_TIME_SetSecond(). */ + This feature can be modified afterwards using unitary function + @ref LL_RTC_TIME_SetSecond(). */ } LL_RTC_TimeTypeDef; /** @@ -138,7 +143,7 @@ typedef struct uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. This parameter can be a value of @ref RTC_LL_EC_WEEKDAY - This feature can be modified afterwards using unitary function @ref LL_RTC_DATE_SetWeekDay(). */ + This feature can be modified afterwards using unitary function @ref LL_RTC_DATE_SetWeekDay() */ uint8_t Month; /*!< Specifies the RTC Date Month. This parameter can be a value of @ref RTC_LL_EC_MONTH @@ -166,26 +171,29 @@ typedef struct uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. This parameter can be a value of @ref RTC_LL_EC_ALMA_MASK for ALARM A. - This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_SetMask() for ALARM A. + This feature can be modified afterwards using unitary function + @ref LL_RTC_ALMA_SetMask() for ALARM A. */ uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on day or WeekDay. This parameter can be a value of @ref RTC_LL_EC_ALMA_WEEKDAY_SELECTION for ALARM A - This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_EnableWeekday() or @ref LL_RTC_ALMA_DisableWeekday() - for ALARM A + This feature can be modified afterwards using unitary function + @ref LL_RTC_ALMA_EnableWeekday() or @ref LL_RTC_ALMA_DisableWeekday() for ALARM A */ uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Day/WeekDay. - If AlarmDateWeekDaySel set to day, this parameter must be a number between Min_Data = 1 and Max_Data = 31. + If AlarmDateWeekDaySel set to day, this parameter must be a number + between Min_Data = 1 and Max_Data = 31. - This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_SetDay() - for ALARM A. + This feature can be modified afterwards using unitary function + @ref LL_RTC_ALMA_SetDay() for ALARM A. - If AlarmDateWeekDaySel set to Weekday, this parameter can be a value of @ref RTC_LL_EC_WEEKDAY. + If AlarmDateWeekDaySel set to Weekday, this parameter can be a value of + @ref RTC_LL_EC_WEEKDAY. - This feature can be modified afterwards using unitary function @ref LL_RTC_ALMA_SetWeekDay() - for ALARM A. + This feature can be modified afterwards using unitary function + @ref LL_RTC_ALMA_SetWeekDay() for ALARM A. */ } LL_RTC_AlarmTypeDef; @@ -312,8 +320,8 @@ typedef struct /** @defgroup RTC_LL_EC_OUTPUTPOLARITY_PIN OUTPUT POLARITY PIN * @{ */ -#define LL_RTC_OUTPUTPOLARITY_PIN_HIGH 0U /*!< Pin is high when ALRAF is asserted (depending on OSEL)*/ -#define LL_RTC_OUTPUTPOLARITY_PIN_LOW RTC_CR_POL /*!< Pin is low when ALRAF is asserted (depending on OSEL) */ +#define LL_RTC_OUTPUTPOLARITY_PIN_HIGH 0U /*!< Pin is high when ALRAF is asserted (depending on OSEL)*/ +#define LL_RTC_OUTPUTPOLARITY_PIN_LOW RTC_CR_POL /*!< Pin is low when ALRAF is asserted (depending on OSEL) */ /** * @} */ @@ -330,8 +338,8 @@ typedef struct /** @defgroup RTC_LL_EC_SHIFT_SECOND SHIFT SECOND * @{ */ -#define LL_RTC_SHIFT_SECOND_DELAY 0U /*!< Delay (seconds) = SUBFS / (PREDIV_S + 1) */ -#define LL_RTC_SHIFT_SECOND_ADVANCE RTC_SHIFTR_ADD1S /*!< Advance (seconds) = (1 - (SUBFS / (PREDIV_S + 1))) */ +#define LL_RTC_SHIFT_SECOND_DELAY 0U /*!< Delay (seconds) = SUBFS / (PREDIV_S + 1) */ +#define LL_RTC_SHIFT_SECOND_ADVANCE RTC_SHIFTR_ADD1S /*!< Advance (seconds) = (1 - (SUBFS / (PREDIV_S + 1))) */ /** * @} */ @@ -361,8 +369,8 @@ typedef struct /** @defgroup RTC_LL_EC_TIMESTAMP_EDGE TIMESTAMP EDGE * @{ */ -#define LL_RTC_TIMESTAMP_EDGE_RISING 0U /*!< RTC_TS input rising edge generates a time-stamp event */ -#define LL_RTC_TIMESTAMP_EDGE_FALLING RTC_CR_TSEDGE /*!< RTC_TS input falling edge generates a time-stamp even */ +#define LL_RTC_TIMESTAMP_EDGE_RISING 0U /*!< RTC_TS input rising edge generates a time-stamp event */ +#define LL_RTC_TIMESTAMP_EDGE_FALLING RTC_CR_TSEDGE /*!< RTC_TS input falling edge generates a time-stamp even */ /** * @} */ @@ -454,8 +462,8 @@ typedef struct * @param __VALUE__ BCD value to be converted * @retval Converted byte */ -#define __LL_RTC_CONVERT_BCD2BIN(__VALUE__) (uint8_t)((((uint8_t)((__VALUE__)\ - & (uint8_t)0xF0U) >> (uint8_t)0x4U) * 10U ) + ((__VALUE__) & (uint8_t)0x0FU)) +#define __LL_RTC_CONVERT_BCD2BIN(__VALUE__) \ + (uint8_t)((((uint8_t)((__VALUE__) & (uint8_t)0xF0U) >> (uint8_t)0x4U) * 10U ) + ((__VALUE__) & (uint8_t)0x0FU)) /** * @} @@ -582,7 +590,7 @@ __STATIC_INLINE void LL_RTC_SetHourFormat(RTC_TypeDef *RTCx, uint32_t HourFormat * @arg @ref LL_RTC_HOURFORMAT_24HOUR * @arg @ref LL_RTC_HOURFORMAT_AMPM */ -__STATIC_INLINE uint32_t LL_RTC_GetHourFormat(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_GetHourFormat(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_FMT)); } @@ -610,7 +618,7 @@ __STATIC_INLINE void LL_RTC_SetAlarmOutEvent(RTC_TypeDef *RTCx, uint32_t AlarmOu * @arg @ref LL_RTC_ALARMOUT_DISABLE * @arg @ref LL_RTC_ALARMOUT_ALMA */ -__STATIC_INLINE uint32_t LL_RTC_GetAlarmOutEvent(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_GetAlarmOutEvent(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_OSEL)); } @@ -637,7 +645,7 @@ __STATIC_INLINE void LL_RTC_SetAlarmOutputType(RTC_TypeDef *RTCx, uint32_t Outpu * @arg @ref LL_RTC_ALARM_OUTPUTTYPE_OPENDRAIN * @arg @ref LL_RTC_ALARM_OUTPUTTYPE_PUSHPULL */ -__STATIC_INLINE uint32_t LL_RTC_GetAlarmOutputType(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_GetAlarmOutputType(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_TAMPALRM_TYPE)); } @@ -692,7 +700,7 @@ __STATIC_INLINE void LL_RTC_SetOutputPolarity(RTC_TypeDef *RTCx, uint32_t Polari * @arg @ref LL_RTC_OUTPUTPOLARITY_PIN_HIGH * @arg @ref LL_RTC_OUTPUTPOLARITY_PIN_LOW */ -__STATIC_INLINE uint32_t LL_RTC_GetOutputPolarity(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_GetOutputPolarity(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_POL)); } @@ -726,7 +734,7 @@ __STATIC_INLINE void LL_RTC_DisableShadowRegBypass(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsShadowRegBypassEnabled(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsShadowRegBypassEnabled(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CR, RTC_CR_BYPSHAD) == (RTC_CR_BYPSHAD)) ? 1UL : 0UL); } @@ -787,7 +795,7 @@ __STATIC_INLINE void LL_RTC_SetSynchPrescaler(RTC_TypeDef *RTCx, uint32_t SynchP * @param RTCx RTC Instance * @retval Value between Min_Data = 0 and Max_Data = 0x7F */ -__STATIC_INLINE uint32_t LL_RTC_GetAsynchPrescaler(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_GetAsynchPrescaler(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->PRER, RTC_PRER_PREDIV_A) >> RTC_PRER_PREDIV_A_Pos); } @@ -798,7 +806,7 @@ __STATIC_INLINE uint32_t LL_RTC_GetAsynchPrescaler(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Value between Min_Data = 0 and Max_Data = 0x7FFF */ -__STATIC_INLINE uint32_t LL_RTC_GetSynchPrescaler(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_GetSynchPrescaler(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->PRER, RTC_PRER_PREDIV_S)); } @@ -855,7 +863,7 @@ __STATIC_INLINE void LL_RTC_DisableAlarmPullUp(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsAlarmPullUpEnabled(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsAlarmPullUpEnabled(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CR, RTC_CR_TAMPALRM_PU) == (RTC_CR_TAMPALRM_PU)) ? 1UL : 0UL); } @@ -891,7 +899,7 @@ __STATIC_INLINE void LL_RTC_DisableOutput2(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsOutput2Enabled(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsOutput2Enabled(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CR, RTC_CR_OUT2EN) == (RTC_CR_OUT2EN)) ? 1UL : 0UL); } @@ -922,7 +930,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetFormat(RTC_TypeDef *RTCx, uint32_t TimeForma /** * @brief Get time format (AM or PM notation) - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -932,7 +940,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetFormat(RTC_TypeDef *RTCx, uint32_t TimeForma * @arg @ref LL_RTC_TIME_FORMAT_AM_OR_24 * @arg @ref LL_RTC_TIME_FORMAT_PM */ -__STATIC_INLINE uint32_t LL_RTC_TIME_GetFormat(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_GetFormat(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TR, RTC_TR_PM)); } @@ -956,7 +964,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) /** * @brief Get Hours in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -967,7 +975,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) * @param RTCx RTC Instance * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 */ -__STATIC_INLINE uint32_t LL_RTC_TIME_GetHour(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_GetHour(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->TR, (RTC_TR_HT | RTC_TR_HU))) >> RTC_TR_HU_Pos); } @@ -991,7 +999,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) /** * @brief Get Minutes in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1002,7 +1010,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x59 */ -__STATIC_INLINE uint32_t LL_RTC_TIME_GetMinute(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_GetMinute(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->TR, (RTC_TR_MNT | RTC_TR_MNU))) >> RTC_TR_MNU_Pos); } @@ -1026,7 +1034,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) /** * @brief Get Seconds in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1037,7 +1045,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x59 */ -__STATIC_INLINE uint32_t LL_RTC_TIME_GetSecond(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_GetSecond(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->TR, (RTC_TR_ST | RTC_TR_SU))) >> RTC_TR_SU_Pos); } @@ -1077,7 +1085,7 @@ __STATIC_INLINE void LL_RTC_TIME_Config(RTC_TypeDef *RTCx, uint32_t Format12_24, /** * @brief Get time (hour, minute and second) in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1092,13 +1100,15 @@ __STATIC_INLINE void LL_RTC_TIME_Config(RTC_TypeDef *RTCx, uint32_t Format12_24, * @param RTCx RTC Instance * @retval Combination of hours, minutes and seconds (Format: 0x00HHMMSS). */ -__STATIC_INLINE uint32_t LL_RTC_TIME_Get(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_Get(const RTC_TypeDef *RTCx) { register uint32_t temp; temp = READ_BIT(RTCx->TR, (RTC_TR_HT | RTC_TR_HU | RTC_TR_MNT | RTC_TR_MNU | RTC_TR_ST | RTC_TR_SU)); - return (uint32_t)((((((temp & RTC_TR_HT) >> RTC_TR_HT_Pos) << 4U) | ((temp & RTC_TR_HU) >> RTC_TR_HU_Pos)) << RTC_OFFSET_HOUR) | \ - (((((temp & RTC_TR_MNT) >> RTC_TR_MNT_Pos) << 4U) | ((temp & RTC_TR_MNU) >> RTC_TR_MNU_Pos)) << RTC_OFFSET_MINUTE) | \ + return (uint32_t)((((((temp & RTC_TR_HT) >> RTC_TR_HT_Pos) << 4U) | \ + ((temp & RTC_TR_HU) >> RTC_TR_HU_Pos)) << RTC_OFFSET_HOUR) | \ + (((((temp & RTC_TR_MNT) >> RTC_TR_MNT_Pos) << 4U) | \ + ((temp & RTC_TR_MNU) >> RTC_TR_MNU_Pos)) << RTC_OFFSET_MINUTE) | \ ((((temp & RTC_TR_ST) >> RTC_TR_ST_Pos) << 4U) | ((temp & RTC_TR_SU) >> RTC_TR_SU_Pos))); } @@ -1132,7 +1142,7 @@ __STATIC_INLINE void LL_RTC_TIME_DisableDayLightStore(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_TIME_IsDayLightStoreEnabled(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_IsDayLightStoreEnabled(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CR, RTC_CR_BKP) == (RTC_CR_BKP)) ? 1UL : 0UL); } @@ -1174,7 +1184,7 @@ __STATIC_INLINE void LL_RTC_TIME_IncHour(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Sub second value (number between 0 and 65535) */ -__STATIC_INLINE uint32_t LL_RTC_TIME_GetSubSecond(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TIME_GetSubSecond(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->SSR, RTC_SSR_SS)); } @@ -1223,7 +1233,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetYear(RTC_TypeDef *RTCx, uint32_t Year) /** * @brief Get Year in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Year from BCD to Binary format * @rmtoll RTC_DR YT LL_RTC_DATE_GetYear\n @@ -1231,7 +1241,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetYear(RTC_TypeDef *RTCx, uint32_t Year) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x99 */ -__STATIC_INLINE uint32_t LL_RTC_DATE_GetYear(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_DATE_GetYear(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->DR, (RTC_DR_YT | RTC_DR_YU))) >> RTC_DR_YU_Pos); } @@ -1257,7 +1267,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) /** * @brief Get Week day - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @rmtoll RTC_DR WDU LL_RTC_DATE_GetWeekDay * @param RTCx RTC Instance @@ -1270,7 +1280,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) * @arg @ref LL_RTC_WEEKDAY_SATURDAY * @arg @ref LL_RTC_WEEKDAY_SUNDAY */ -__STATIC_INLINE uint32_t LL_RTC_DATE_GetWeekDay(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_DATE_GetWeekDay(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->DR, RTC_DR_WDU) >> RTC_DR_WDU_Pos); } @@ -1304,7 +1314,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetMonth(RTC_TypeDef *RTCx, uint32_t Month) /** * @brief Get Month in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Month from BCD to Binary format * @rmtoll RTC_DR MT LL_RTC_DATE_GetMonth\n @@ -1324,7 +1334,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetMonth(RTC_TypeDef *RTCx, uint32_t Month) * @arg @ref LL_RTC_MONTH_NOVEMBER * @arg @ref LL_RTC_MONTH_DECEMBER */ -__STATIC_INLINE uint32_t LL_RTC_DATE_GetMonth(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_DATE_GetMonth(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->DR, (RTC_DR_MT | RTC_DR_MU))) >> RTC_DR_MU_Pos); } @@ -1346,7 +1356,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetDay(RTC_TypeDef *RTCx, uint32_t Day) /** * @brief Get Day in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format * @rmtoll RTC_DR DT LL_RTC_DATE_GetDay\n @@ -1354,7 +1364,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetDay(RTC_TypeDef *RTCx, uint32_t Day) * @param RTCx RTC Instance * @retval Value between Min_Data=0x01 and Max_Data=0x31 */ -__STATIC_INLINE uint32_t LL_RTC_DATE_GetDay(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_DATE_GetDay(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->DR, (RTC_DR_DT | RTC_DR_DU))) >> RTC_DR_DU_Pos); } @@ -1409,7 +1419,7 @@ __STATIC_INLINE void LL_RTC_DATE_Config(RTC_TypeDef *RTCx, uint32_t WeekDay, uin /** * @brief Get date (WeekDay, Day, Month and Year) in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macros __LL_RTC_GET_WEEKDAY, __LL_RTC_GET_YEAR, __LL_RTC_GET_MONTH, * and __LL_RTC_GET_DAY are available to get independently each parameter. @@ -1423,14 +1433,16 @@ __STATIC_INLINE void LL_RTC_DATE_Config(RTC_TypeDef *RTCx, uint32_t WeekDay, uin * @param RTCx RTC Instance * @retval Combination of WeekDay, Day, Month and Year (Format: 0xWWDDMMYY). */ -__STATIC_INLINE uint32_t LL_RTC_DATE_Get(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_DATE_Get(const RTC_TypeDef *RTCx) { register uint32_t temp; temp = READ_BIT(RTCx->DR, (RTC_DR_WDU | RTC_DR_MT | RTC_DR_MU | RTC_DR_DT | RTC_DR_DU | RTC_DR_YT | RTC_DR_YU)); return (uint32_t)((((temp & RTC_DR_WDU) >> RTC_DR_WDU_Pos) << RTC_OFFSET_WEEKDAY) | \ - (((((temp & RTC_DR_DT) >> RTC_DR_DT_Pos) << 4U) | ((temp & RTC_DR_DU) >> RTC_DR_DU_Pos)) << RTC_OFFSET_DAY) | \ - (((((temp & RTC_DR_MT) >> RTC_DR_MT_Pos) << 4U) | ((temp & RTC_DR_MU) >> RTC_DR_MU_Pos)) << RTC_OFFSET_MONTH) | \ + (((((temp & RTC_DR_DT) >> RTC_DR_DT_Pos) << 4U) | \ + ((temp & RTC_DR_DU) >> RTC_DR_DU_Pos)) << RTC_OFFSET_DAY) | \ + (((((temp & RTC_DR_MT) >> RTC_DR_MT_Pos) << 4U) | \ + ((temp & RTC_DR_MU) >> RTC_DR_MU_Pos)) << RTC_OFFSET_MONTH) | \ ((((temp & RTC_DR_YT) >> RTC_DR_YT_Pos) << 4U) | ((temp & RTC_DR_YU) >> RTC_DR_YU_Pos))); } @@ -1502,7 +1514,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetMask(RTC_TypeDef *RTCx, uint32_t Mask) * @arg @ref LL_RTC_ALMA_MASK_SECONDS * @arg @ref LL_RTC_ALMA_MASK_ALL */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetMask(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetMask(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->ALRMAR, RTC_ALRMAR_MSK4 | RTC_ALRMAR_MSK3 | RTC_ALRMAR_MSK2 | RTC_ALRMAR_MSK1)); } @@ -1552,7 +1564,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetDay(RTC_TypeDef *RTCx, uint32_t Day) * @param RTCx RTC Instance * @retval Value between Min_Data=0x01 and Max_Data=0x31 */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetDay(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetDay(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_DT | RTC_ALRMAR_DU))) >> RTC_ALRMAR_DU_Pos); } @@ -1589,7 +1601,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) * @arg @ref LL_RTC_WEEKDAY_SATURDAY * @arg @ref LL_RTC_WEEKDAY_SUNDAY */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetWeekDay(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetWeekDay(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->ALRMAR, RTC_ALRMAR_DU) >> RTC_ALRMAR_DU_Pos); } @@ -1616,7 +1628,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetTimeFormat(RTC_TypeDef *RTCx, uint32_t TimeF * @arg @ref LL_RTC_ALMA_TIME_FORMAT_AM * @arg @ref LL_RTC_ALMA_TIME_FORMAT_PM */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetTimeFormat(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetTimeFormat(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->ALRMAR, RTC_ALRMAR_PM)); } @@ -1644,7 +1656,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) * @param RTCx RTC Instance * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetHour(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetHour(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_HT | RTC_ALRMAR_HU))) >> RTC_ALRMAR_HU_Pos); } @@ -1672,7 +1684,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x59 */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetMinute(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetMinute(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU))) >> RTC_ALRMAR_MNU_Pos); } @@ -1700,7 +1712,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x59 */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSecond(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSecond(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ALRMAR, (RTC_ALRMAR_ST | RTC_ALRMAR_SU))) >> RTC_ALRMAR_SU_Pos); } @@ -1728,12 +1740,12 @@ __STATIC_INLINE void LL_RTC_ALMA_ConfigTime(RTC_TypeDef *RTCx, uint32_t Format12 { register uint32_t temp; - temp = Format12_24 | (((Hours & 0xF0U) << (RTC_ALRMAR_HT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMAR_HU_Pos)) | \ + temp = Format12_24 | (((Hours & 0xF0U) << (RTC_ALRMAR_HT_Pos - 4U)) | ((Hours & 0x0FU) << RTC_ALRMAR_HU_Pos)) | \ (((Minutes & 0xF0U) << (RTC_ALRMAR_MNT_Pos - 4U)) | ((Minutes & 0x0FU) << RTC_ALRMAR_MNU_Pos)) | \ (((Seconds & 0xF0U) << (RTC_ALRMAR_ST_Pos - 4U)) | ((Seconds & 0x0FU) << RTC_ALRMAR_SU_Pos)); - MODIFY_REG(RTCx->ALRMAR, RTC_ALRMAR_PM | RTC_ALRMAR_HT | RTC_ALRMAR_HU | RTC_ALRMAR_MNT | RTC_ALRMAR_MNU | RTC_ALRMAR_ST - | RTC_ALRMAR_SU, temp); + MODIFY_REG(RTCx->ALRMAR, RTC_ALRMAR_PM | RTC_ALRMAR_HT | RTC_ALRMAR_HU | RTC_ALRMAR_MNT | RTC_ALRMAR_MNU | \ + RTC_ALRMAR_ST | RTC_ALRMAR_SU, temp); } /** @@ -1751,7 +1763,8 @@ __STATIC_INLINE void LL_RTC_ALMA_ConfigTime(RTC_TypeDef *RTCx, uint32_t Format12 */ __STATIC_INLINE uint32_t LL_RTC_ALMA_GetTime(RTC_TypeDef *RTCx) { - return (uint32_t)((LL_RTC_ALMA_GetHour(RTCx) << RTC_OFFSET_HOUR) | (LL_RTC_ALMA_GetMinute(RTCx) << RTC_OFFSET_MINUTE) | LL_RTC_ALMA_GetSecond(RTCx)); + return (uint32_t)((LL_RTC_ALMA_GetHour(RTCx) << RTC_OFFSET_HOUR) | \ + (LL_RTC_ALMA_GetMinute(RTCx) << RTC_OFFSET_MINUTE) | LL_RTC_ALMA_GetSecond(RTCx)); } /** @@ -1774,7 +1787,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetSubSecondMask(RTC_TypeDef *RTCx, uint32_t Ma * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0xF */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSubSecondMask(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSubSecondMask(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->ALRMASSR, RTC_ALRMASSR_MASKSS) >> RTC_ALRMASSR_MASKSS_Pos); } @@ -1797,7 +1810,7 @@ __STATIC_INLINE void LL_RTC_ALMA_SetSubSecond(RTC_TypeDef *RTCx, uint32_t Subsec * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x7FFF */ -__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSubSecond(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_ALMA_GetSubSecond(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->ALRMASSR, RTC_ALRMASSR_SS)); } @@ -1859,7 +1872,7 @@ __STATIC_INLINE void LL_RTC_TS_SetActiveEdge(RTC_TypeDef *RTCx, uint32_t Edge) * @arg @ref LL_RTC_TIMESTAMP_EDGE_RISING * @arg @ref LL_RTC_TIMESTAMP_EDGE_FALLING */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetActiveEdge(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetActiveEdge(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_TSEDGE)); } @@ -1872,7 +1885,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetActiveEdge(RTC_TypeDef *RTCx) * @arg @ref LL_RTC_TS_TIME_FORMAT_AM * @arg @ref LL_RTC_TS_TIME_FORMAT_PM */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetTimeFormat(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetTimeFormat(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_PM)); } @@ -1885,7 +1898,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetTimeFormat(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Value between Min_Data=0x01 and Max_Data=0x12 or between Min_Data=0x00 and Max_Data=0x23 */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetHour(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetHour(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_HT | RTC_TSTR_HU) >> RTC_TSTR_HU_Pos); } @@ -1898,7 +1911,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetHour(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x59 */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetMinute(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetMinute(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_MNT | RTC_TSTR_MNU) >> RTC_TSTR_MNU_Pos); } @@ -1911,7 +1924,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetMinute(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0x59 */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetSecond(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetSecond(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_ST | RTC_TSTR_SU)); } @@ -1929,7 +1942,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetSecond(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Combination of hours, minutes and seconds. */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetTime(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetTime(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSTR, RTC_TSTR_HT | RTC_TSTR_HU | RTC_TSTR_MNT | RTC_TSTR_MNU | RTC_TSTR_ST | RTC_TSTR_SU)); @@ -1948,7 +1961,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetTime(RTC_TypeDef *RTCx) * @arg @ref LL_RTC_WEEKDAY_SATURDAY * @arg @ref LL_RTC_WEEKDAY_SUNDAY */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetWeekDay(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetWeekDay(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_WDU) >> RTC_TSDR_WDU_Pos); } @@ -1973,7 +1986,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetWeekDay(RTC_TypeDef *RTCx) * @arg @ref LL_RTC_MONTH_NOVEMBER * @arg @ref LL_RTC_MONTH_DECEMBER */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetMonth(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetMonth(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_MT | RTC_TSDR_MU) >> RTC_TSDR_MU_Pos); } @@ -1986,7 +1999,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetMonth(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Value between Min_Data=0x01 and Max_Data=0x31 */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetDay(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetDay(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_DT | RTC_TSDR_DU)); } @@ -2003,7 +2016,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetDay(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Combination of Weekday, Day and Month */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetDate(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetDate(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSDR, RTC_TSDR_WDU | RTC_TSDR_MT | RTC_TSDR_MU | RTC_TSDR_DT | RTC_TSDR_DU)); } @@ -2014,7 +2027,7 @@ __STATIC_INLINE uint32_t LL_RTC_TS_GetDate(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data=0xFFFF */ -__STATIC_INLINE uint32_t LL_RTC_TS_GetSubSecond(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_TS_GetSubSecond(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->TSSSR, RTC_TSSSR_SS)); } @@ -2054,7 +2067,7 @@ __STATIC_INLINE void LL_RTC_CAL_SetOutputFreq(RTC_TypeDef *RTCx, uint32_t Freque * @arg @ref LL_RTC_CALIB_OUTPUT_1HZ * @arg @ref LL_RTC_CALIB_OUTPUT_512HZ */ -__STATIC_INLINE uint32_t LL_RTC_CAL_GetOutputFreq(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_CAL_GetOutputFreq(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CR, RTC_CR_COE | RTC_CR_COSEL)); } @@ -2081,7 +2094,7 @@ __STATIC_INLINE void LL_RTC_CAL_SetPulse(RTC_TypeDef *RTCx, uint32_t Pulse) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_CAL_IsPulseInserted(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_CAL_IsPulseInserted(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CALR, RTC_CALR_CALP) == (RTC_CALR_CALP)) ? 1UL : 0UL); } @@ -2114,7 +2127,7 @@ __STATIC_INLINE void LL_RTC_CAL_SetPeriod(RTC_TypeDef *RTCx, uint32_t Period) * @arg @ref LL_RTC_CALIB_PERIOD_16SEC * @arg @ref LL_RTC_CALIB_PERIOD_8SEC */ -__STATIC_INLINE uint32_t LL_RTC_CAL_GetPeriod(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_CAL_GetPeriod(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CALR, RTC_CALR_CALW8 | RTC_CALR_CALW16)); } @@ -2139,7 +2152,7 @@ __STATIC_INLINE void LL_RTC_CAL_SetMinus(RTC_TypeDef *RTCx, uint32_t CalibMinus) * @param RTCx RTC Instance * @retval Value between Min_Data=0x00 and Max_Data= 0x1FF */ -__STATIC_INLINE uint32_t LL_RTC_CAL_GetMinus(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_CAL_GetMinus(const RTC_TypeDef *RTCx) { return (uint32_t)(READ_BIT(RTCx->CALR, RTC_CALR_CALM)); } @@ -2158,7 +2171,7 @@ __STATIC_INLINE uint32_t LL_RTC_CAL_GetMinus(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RECALP(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RECALP(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ICSR, RTC_ICSR_RECALPF) == (RTC_ICSR_RECALPF)) ? 1UL : 0UL); } @@ -2169,7 +2182,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RECALP(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSOV(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSOV(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->SR, RTC_SR_TSOVF) == (RTC_SR_TSOVF)) ? 1UL : 0UL); } @@ -2180,7 +2193,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSOV(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TS(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TS(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->SR, RTC_SR_TSF) == (RTC_SR_TSF)) ? 1UL : 0UL); } @@ -2192,7 +2205,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TS(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRA(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRA(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->SR, RTC_SR_ALRAF) == (RTC_SR_ALRAF)) ? 1UL : 0UL); } @@ -2237,7 +2250,7 @@ __STATIC_INLINE void LL_RTC_ClearFlag_ALRA(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INIT(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INIT(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ICSR, RTC_ICSR_INITF) == (RTC_ICSR_INITF)) ? 1UL : 0UL); } @@ -2248,7 +2261,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INIT(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RS(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RS(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ICSR, RTC_ICSR_RSF) == (RTC_ICSR_RSF)) ? 1UL : 0UL); } @@ -2270,7 +2283,7 @@ __STATIC_INLINE void LL_RTC_ClearFlag_RS(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INITS(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INITS(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ICSR, RTC_ICSR_INITS) == (RTC_ICSR_INITS)) ? 1UL : 0UL); } @@ -2281,7 +2294,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_INITS(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_SHP(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_SHP(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ICSR, RTC_ICSR_SHPF) == (RTC_ICSR_SHPF)) ? 1UL : 0UL); } @@ -2293,7 +2306,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_SHP(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAW(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAW(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->ICSR, RTC_ICSR_ALRAWF) == (RTC_ICSR_ALRAWF)) ? 1UL : 0UL); } @@ -2304,7 +2317,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAW(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAM(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAM(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->MISR, RTC_MISR_ALRAMF) == (RTC_MISR_ALRAMF)) ? 1UL : 0UL); } @@ -2315,7 +2328,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALRAM(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSM(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSM(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->MISR, RTC_MISR_TSMF) == (RTC_MISR_TSMF)) ? 1UL : 0UL); } @@ -2326,7 +2339,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSM(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSOVM(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TSOVM(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->MISR, RTC_MISR_TSOVMF) == (RTC_MISR_TSOVMF)) ? 1UL : 0UL); } @@ -2393,7 +2406,7 @@ __STATIC_INLINE void LL_RTC_DisableIT_ALRA(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_TS(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_TS(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CR, RTC_CR_TSIE) == (RTC_CR_TSIE)) ? 1UL : 0UL); } @@ -2404,7 +2417,7 @@ __STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_TS(RTC_TypeDef *RTCx) * @param RTCx RTC Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_ALRA(RTC_TypeDef *RTCx) +__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_ALRA(const RTC_TypeDef *RTCx) { return ((READ_BIT(RTCx->CR, RTC_CR_ALRAIE) == (RTC_CR_ALRAIE)) ? 1UL : 0UL); } diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_spi.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_spi.h index 05f4626a9..6b7189fce 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_spi.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_spi.h @@ -378,7 +378,7 @@ __STATIC_INLINE void LL_SPI_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_SPE) == (SPI_CR1_SPE)) ? 1UL : 0UL); } @@ -408,7 +408,7 @@ __STATIC_INLINE void LL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_SPI_MODE_MASTER * @arg @ref LL_SPI_MODE_SLAVE */ -__STATIC_INLINE uint32_t LL_SPI_GetMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI)); } @@ -436,7 +436,7 @@ __STATIC_INLINE void LL_SPI_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_SPI_PROTOCOL_MOTOROLA * @arg @ref LL_SPI_PROTOCOL_TI */ -__STATIC_INLINE uint32_t LL_SPI_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_FRF)); } @@ -465,7 +465,7 @@ __STATIC_INLINE void LL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase * @arg @ref LL_SPI_PHASE_1EDGE * @arg @ref LL_SPI_PHASE_2EDGE */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPHA)); } @@ -494,7 +494,7 @@ __STATIC_INLINE void LL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_SPI_POLARITY_LOW * @arg @ref LL_SPI_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPOL)); } @@ -534,7 +534,7 @@ __STATIC_INLINE void LL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t Bau * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 */ -__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_BR)); } @@ -562,7 +562,7 @@ __STATIC_INLINE void LL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitO * @arg @ref LL_SPI_LSB_FIRST * @arg @ref LL_SPI_MSB_FIRST */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_LSBFIRST)); } @@ -599,7 +599,7 @@ __STATIC_INLINE void LL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t Tra * @arg @ref LL_SPI_HALF_DUPLEX_RX * @arg @ref LL_SPI_HALF_DUPLEX_TX */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE)); } @@ -648,7 +648,7 @@ __STATIC_INLINE void LL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) * @arg @ref LL_SPI_DATAWIDTH_15BIT * @arg @ref LL_SPI_DATAWIDTH_16BIT */ -__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_DS)); } @@ -675,7 +675,7 @@ __STATIC_INLINE void LL_SPI_SetRxFIFOThreshold(SPI_TypeDef *SPIx, uint32_t Thres * @arg @ref LL_SPI_RX_FIFO_TH_HALF * @arg @ref LL_SPI_RX_FIFO_TH_QUARTER */ -__STATIC_INLINE uint32_t LL_SPI_GetRxFIFOThreshold(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetRxFIFOThreshold(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_FRXTH)); } @@ -719,7 +719,7 @@ __STATIC_INLINE void LL_SPI_DisableCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_CRCEN) == (SPI_CR1_CRCEN)) ? 1UL : 0UL); } @@ -747,7 +747,7 @@ __STATIC_INLINE void LL_SPI_SetCRCWidth(SPI_TypeDef *SPIx, uint32_t CRCLength) * @arg @ref LL_SPI_CRC_8BIT * @arg @ref LL_SPI_CRC_16BIT */ -__STATIC_INLINE uint32_t LL_SPI_GetCRCWidth(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetCRCWidth(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CRCL)); } @@ -782,7 +782,7 @@ __STATIC_INLINE void LL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->CRCPR)); } @@ -793,7 +793,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->RXCRCR)); } @@ -804,7 +804,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->TXCRCR)); } @@ -845,7 +845,7 @@ __STATIC_INLINE void LL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) * @arg @ref LL_SPI_NSS_HARD_INPUT * @arg @ref LL_SPI_NSS_HARD_OUTPUT */ -__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(const SPI_TypeDef *SPIx) { uint32_t Ssm = (READ_BIT(SPIx->CR1, SPI_CR1_SSM)); uint32_t Ssoe = (READ_BIT(SPIx->CR2, SPI_CR2_SSOE) << 16U); @@ -883,7 +883,7 @@ __STATIC_INLINE void LL_SPI_DisableNSSPulseMgt(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledNSSPulse(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledNSSPulse(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_NSSP) == (SPI_CR2_NSSP)) ? 1UL : 0UL); } @@ -902,7 +902,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledNSSPulse(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_RXNE) == (SPI_SR_RXNE)) ? 1UL : 0UL); } @@ -913,7 +913,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_TXE) == (SPI_SR_TXE)) ? 1UL : 0UL); } @@ -924,7 +924,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CRCERR) == (SPI_SR_CRCERR)) ? 1UL : 0UL); } @@ -935,7 +935,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_MODF) == (SPI_SR_MODF)) ? 1UL : 0UL); } @@ -946,7 +946,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_OVR) == (SPI_SR_OVR)) ? 1UL : 0UL); } @@ -964,7 +964,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_BSY) == (SPI_SR_BSY)) ? 1UL : 0UL); } @@ -975,7 +975,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_FRE) == (SPI_SR_FRE)) ? 1UL : 0UL); } @@ -990,7 +990,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(SPI_TypeDef *SPIx) * @arg @ref LL_SPI_RX_FIFO_HALF_FULL * @arg @ref LL_SPI_RX_FIFO_FULL */ -__STATIC_INLINE uint32_t LL_SPI_GetRxFIFOLevel(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetRxFIFOLevel(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->SR, SPI_SR_FRLVL)); } @@ -1005,7 +1005,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetRxFIFOLevel(SPI_TypeDef *SPIx) * @arg @ref LL_SPI_TX_FIFO_HALF_FULL * @arg @ref LL_SPI_TX_FIFO_FULL */ -__STATIC_INLINE uint32_t LL_SPI_GetTxFIFOLevel(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTxFIFOLevel(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->SR, SPI_SR_FTLVL)); } @@ -1150,7 +1150,7 @@ __STATIC_INLINE void LL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_ERRIE) == (SPI_CR2_ERRIE)) ? 1UL : 0UL); } @@ -1161,7 +1161,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXNEIE) == (SPI_CR2_RXNEIE)) ? 1UL : 0UL); } @@ -1172,7 +1172,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXEIE) == (SPI_CR2_TXEIE)) ? 1UL : 0UL); } @@ -1213,7 +1213,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXDMAEN) == (SPI_CR2_RXDMAEN)) ? 1UL : 0UL); } @@ -1246,7 +1246,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXDMAEN) == (SPI_CR2_TXDMAEN)) ? 1UL : 0UL); } @@ -1273,7 +1273,7 @@ __STATIC_INLINE void LL_SPI_SetDMAParity_RX(SPI_TypeDef *SPIx, uint32_t Parity) * @arg @ref LL_SPI_DMA_PARITY_ODD * @arg @ref LL_SPI_DMA_PARITY_EVEN */ -__STATIC_INLINE uint32_t LL_SPI_GetDMAParity_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetDMAParity_RX(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_LDMARX) >> SPI_CR2_LDMARX_Pos); } @@ -1300,7 +1300,7 @@ __STATIC_INLINE void LL_SPI_SetDMAParity_TX(SPI_TypeDef *SPIx, uint32_t Parity) * @arg @ref LL_SPI_DMA_PARITY_ODD * @arg @ref LL_SPI_DMA_PARITY_EVEN */ -__STATIC_INLINE uint32_t LL_SPI_GetDMAParity_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetDMAParity_TX(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_LDMATX) >> SPI_CR2_LDMATX_Pos); } @@ -1311,7 +1311,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetDMAParity_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Address of data register */ -__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(const SPI_TypeDef *SPIx) { return (uint32_t) &(SPIx->DR); } @@ -1388,7 +1388,7 @@ __STATIC_INLINE void LL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct); void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct); @@ -1656,7 +1656,7 @@ __STATIC_INLINE void LL_I2S_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SE) == (SPI_I2SCFGR_I2SE)) ? 1UL : 0UL); } @@ -1689,7 +1689,7 @@ __STATIC_INLINE void LL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat * @arg @ref LL_I2S_DATAFORMAT_24B * @arg @ref LL_I2S_DATAFORMAT_32B */ -__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)); } @@ -1716,7 +1716,7 @@ __STATIC_INLINE void LL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_I2S_POLARITY_LOW * @arg @ref LL_I2S_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_CKPOL)); } @@ -1751,7 +1751,7 @@ __STATIC_INLINE void LL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_I2S_STANDARD_PCM_SHORT * @arg @ref LL_I2S_STANDARD_PCM_LONG */ -__STATIC_INLINE uint32_t LL_I2S_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC)); } @@ -1782,7 +1782,7 @@ __STATIC_INLINE void LL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_I2S_MODE_MASTER_TX * @arg @ref LL_I2S_MODE_MASTER_RX */ -__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG)); } @@ -1805,7 +1805,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t Presca * @param SPIx SPI Instance * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_I2SDIV)); } @@ -1832,7 +1832,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t Presc * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN * @arg @ref LL_I2S_PRESCALER_PARITY_ODD */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_ODD) >> 8U); } @@ -1865,7 +1865,7 @@ __STATIC_INLINE void LL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE) == (SPI_I2SPR_MCKOE)) ? 1UL : 0UL); } @@ -1899,7 +1899,7 @@ __STATIC_INLINE void LL_I2S_DisableAsyncStart(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_ASTRTEN) == (SPI_I2SCFGR_ASTRTEN)) ? 1UL : 0UL); } @@ -1919,7 +1919,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_RXNE(SPIx); } @@ -1930,7 +1930,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_TXE(SPIx); } @@ -1941,7 +1941,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_BSY(SPIx); } @@ -1952,7 +1952,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_OVR(SPIx); } @@ -1963,7 +1963,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_UDR) == (SPI_SR_UDR)) ? 1UL : 0UL); } @@ -1974,7 +1974,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_FRE(SPIx); } @@ -1988,7 +1988,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CHSIDE) == (SPI_SR_CHSIDE)) ? 1UL : 0UL); } @@ -2110,7 +2110,7 @@ __STATIC_INLINE void LL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_ERR(SPIx); } @@ -2121,7 +2121,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_RXNE(SPIx); } @@ -2132,7 +2132,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_TXE(SPIx); } @@ -2173,7 +2173,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_RX(SPIx); } @@ -2206,7 +2206,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_TX(SPIx); } @@ -2251,7 +2251,7 @@ __STATIC_INLINE void LL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_system.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_system.h index 4d0ef0a96..79154cf1e 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_system.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_system.h @@ -123,6 +123,9 @@ extern "C" { #define LL_SYSCFG_I2C_FASTMODEPLUS_PB8 SYSCFG_CFGR1_I2C_PB8_FMP /*!< I2C PB8 Fast mode plus */ #define LL_SYSCFG_I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_PB9_FMP /*!< I2C PB9 Fast mode plus */ #define LL_SYSCFG_I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C1_FMP /*!< Enable I2C1 Fast mode Plus */ +#if defined(I2C2) +#define LL_SYSCFG_I2C_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C2_FMP /*!< Enable I2C2 Fast mode Plus */ +#endif /* I2C2 */ #define LL_SYSCFG_I2C_FASTMODEPLUS_PA9 SYSCFG_CFGR1_I2C_PA9_FMP /*!< Enable Fast Mode Plus on PA9 */ #define LL_SYSCFG_I2C_FASTMODEPLUS_PA10 SYSCFG_CFGR1_I2C_PA10_FMP /*!< Enable Fast Mode Plus on PA10 */ #define LL_SYSCFG_I2C_FASTMODEPLUS_PC14 SYSCFG_CFGR1_I2C_PC14_FMP /*!< Enable Fast Mode Plus on PC14 */ @@ -142,6 +145,9 @@ extern "C" { /** @defgroup SYSTEM_LL_EC_APB1_GRP1_STOP_IP DBGMCU APB1 GRP1 STOP IP * @{ */ +#if defined(TIM2) +#define LL_DBGMCU_APB1_GRP1_TIM2_STOP DBG_APB_FZ1_DBG_TIM2_STOP /*!< TIM2 counter stopped when core is halted */ +#endif /* TIM2 */ #define LL_DBGMCU_APB1_GRP1_TIM3_STOP DBG_APB_FZ1_DBG_TIM3_STOP /*!< TIM3 counter stopped when core is halted */ #define LL_DBGMCU_APB1_GRP1_RTC_STOP DBG_APB_FZ1_DBG_RTC_STOP /*!< RTC Calendar frozen when core is halted */ #define LL_DBGMCU_APB1_GRP1_WWDG_STOP DBG_APB_FZ1_DBG_WWDG_STOP /*!< Debug Window Watchdog stopped when Core is halted */ @@ -152,15 +158,21 @@ extern "C" { * @} */ -/** @defgroup SYSTEM_LL_EC_APB2_GRP1_STOP_IP DBGMCU APB2 GRP1 STOP IP +/** @defgroup SYSTEM_LL_EC_APB1_GRP2_STOP_IP DBGMCU APB1 GRP2 STOP IP * @{ */ -#define LL_DBGMCU_APB2_GRP1_TIM1_STOP DBG_APB_FZ2_DBG_TIM1_STOP /*!< TIM1 counter stopped when core is halted */ +#define LL_DBGMCU_APB1_GRP2_TIM1_STOP DBG_APB_FZ2_DBG_TIM1_STOP /*!< TIM1 counter stopped when core is halted */ #if defined(DBG_APB_FZ2_DBG_TIM14_STOP) -#define LL_DBGMCU_APB2_GRP1_TIM14_STOP DBG_APB_FZ2_DBG_TIM14_STOP /*!< TIM14 counter stopped when core is halted */ +#define LL_DBGMCU_APB1_GRP2_TIM14_STOP DBG_APB_FZ2_DBG_TIM14_STOP /*!< TIM14 counter stopped when core is halted */ #endif /* DBG_APB_FZ2_DBG_TIM14_STOP */ -#define LL_DBGMCU_APB2_GRP1_TIM16_STOP DBG_APB_FZ2_DBG_TIM16_STOP /*!< TIM16 counter stopped when core is halted */ -#define LL_DBGMCU_APB2_GRP1_TIM17_STOP DBG_APB_FZ2_DBG_TIM17_STOP /*!< TIM17 counter stopped when core is halted */ +#define LL_DBGMCU_APB1_GRP2_TIM16_STOP DBG_APB_FZ2_DBG_TIM16_STOP /*!< TIM16 counter stopped when core is halted */ +#define LL_DBGMCU_APB1_GRP2_TIM17_STOP DBG_APB_FZ2_DBG_TIM17_STOP /*!< TIM17 counter stopped when core is halted */ + +/* defines for legacy purpose */ +#define LL_DBGMCU_APB2_GRP1_TIM1_STOP LL_DBGMCU_APB1_GRP2_TIM1_STOP +#define LL_DBGMCU_APB2_GRP1_TIM14_STOP LL_DBGMCU_APB1_GRP2_TIM14_STOP +#define LL_DBGMCU_APB2_GRP1_TIM16_STOP LL_DBGMCU_APB1_GRP2_TIM16_STOP +#define LL_DBGMCU_APB2_GRP1_TIM17_STOP LL_DBGMCU_APB1_GRP2_TIM17_STOP /** * @} */ @@ -179,37 +191,76 @@ extern "C" { * @{ */ #if (DEV_ID == 0x443UL) -#define LL_PINMUX_SO8_PIN1_PB7 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin1 assigned to GPIO PB7 */ -#define LL_PINMUX_SO8_PIN1_PC14 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | SYSCFG_CFGR3_PINMUX0_0) /*!< STM32C011 SO8 package, Pin1 assigned to GPIO PC14 */ -#define LL_PINMUX_SO8_PIN4_PF2 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PF2 */ -#define LL_PINMUX_SO8_PIN4_PA0 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | SYSCFG_CFGR3_PINMUX1_0) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PA0 */ -#define LL_PINMUX_SO8_PIN4_PA1 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | SYSCFG_CFGR3_PINMUX1_1) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PA1 */ -#define LL_PINMUX_SO8_PIN4_PA2 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PA2 */ -#define LL_PINMUX_SO8_PIN5_PA8 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin5 assigned to GPIO PA8 */ -#define LL_PINMUX_SO8_PIN5_PA11 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | SYSCFG_CFGR3_PINMUX2_0) /*!< STM32C011 SO8 package, Pin5 assigned to GPIO PA11 */ -#define LL_PINMUX_SO8_PIN8_PA14 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin8 assigned to GPIO PA14 */ -#define LL_PINMUX_SO8_PIN8_PB6 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | SYSCFG_CFGR3_PINMUX3_0) /*!< STM32C011 SO8 package, Pin8 assigned to GPIO PB6 */ -#define LL_PINMUX_SO8_PIN8_PC15 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | SYSCFG_CFGR3_PINMUX3_1) /*!< STM32C011 SO8 package, Pin8 assigned to GPIO PC15 */ -#define LL_PINMUX_WLCSP12_PINE2_PA7 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | 0x00000000U) /*!< STM32C011 WLCSP12 package, PinE2 assigned to GPIO PA7 */ -#define LL_PINMUX_WLCSP12_PINE2_PA12 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | SYSCFG_CFGR3_PINMUX4_0) /*!< STM32C011 WLCSP12 package, PinE2 assigned to GPIO PA12 */ -#define LL_PINMUX_WLCSP12_PINF1_PA3 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | 0x00000000U) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA3*/ -#define LL_PINMUX_WLCSP12_PINF1_PA4 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | SYSCFG_CFGR3_PINMUX5_0) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA4 */ -#define LL_PINMUX_WLCSP12_PINF1_PA5 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | SYSCFG_CFGR3_PINMUX5_1) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA5 */ -#define LL_PINMUX_WLCSP12_PINF1_PA6 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA6 */ +#define LL_PINMUX_SO8_PIN1_PB7 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin1 assigned to GPIO PB7 */ +#define LL_PINMUX_SO8_PIN1_PC14 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX0_0) /*!< STM32C011 SO8 package, Pin1 assigned to GPIO PC14 */ +#define LL_PINMUX_SO8_PIN4_PF2 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PF2 */ +#define LL_PINMUX_SO8_PIN4_PA0 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX1_0) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PA0 */ +#define LL_PINMUX_SO8_PIN4_PA1 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX1_1) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PA1 */ +#define LL_PINMUX_SO8_PIN4_PA2 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) /*!< STM32C011 SO8 package, Pin4 assigned to GPIO PA2 */ +#define LL_PINMUX_SO8_PIN5_PA8 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin5 assigned to GPIO PA8 */ +#define LL_PINMUX_SO8_PIN5_PA11 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX2_0) /*!< STM32C011 SO8 package, Pin5 assigned to GPIO PA11 */ +#define LL_PINMUX_SO8_PIN8_PA14 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | 0x00000000U) /*!< STM32C011 SO8 package, Pin8 assigned to GPIO PA14 */ +#define LL_PINMUX_SO8_PIN8_PB6 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX3_0) /*!< STM32C011 SO8 package, Pin8 assigned to GPIO PB6 */ +#define LL_PINMUX_SO8_PIN8_PC15 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX3_1) /*!< STM32C011 SO8 package, Pin8 assigned to GPIO PC15 */ +#define LL_PINMUX_WLCSP12_PINE2_PA7 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | 0x00000000U) /*!< STM32C011 WLCSP12 package, PinE2 assigned to GPIO PA7 */ +#define LL_PINMUX_WLCSP12_PINE2_PA12 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX4_0) /*!< STM32C011 WLCSP12 package, PinE2 assigned to GPIO PA12 */ +#define LL_PINMUX_WLCSP12_PINF1_PA3 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | 0x00000000U) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA3*/ +#define LL_PINMUX_WLCSP12_PINF1_PA4 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX5_0) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA4 */ +#define LL_PINMUX_WLCSP12_PINF1_PA5 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX5_1) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA5 */ +#define LL_PINMUX_WLCSP12_PINF1_PA6 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) /*!< STM32C011 WLCSP12 package, PinF1 assigned to GPIO PA6 */ #elif (DEV_ID == 0x453UL) -#define LL_PINMUX_WLCSP14_PINF2_PA1 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinF2 assigned to GPIO PA1 */ -#define LL_PINMUX_WLCSP14_PINF2_PA2 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | SYSCFG_CFGR3_PINMUX0_0) /*!< STM32C031 WLCSP14 package, PinF2 assigned to GPIO PA2 */ -#define LL_PINMUX_WLCSP14_PING3_PF2 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinG3 assigned to GPIO PF2 */ -#define LL_PINMUX_WLCSP14_PING3_PA0 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | SYSCFG_CFGR3_PINMUX1_0) /*!< STM32C031 WLCSP14 package, PinG3 assigned to GPIO PA0 */ -#define LL_PINMUX_WLCSP14_PINJ1_PA8 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinJ1 assigned to GPIO PA8 */ -#define LL_PINMUX_WLCSP14_PINJ1_PA11 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | SYSCFG_CFGR3_PINMUX2_0) /*!< STM32C031 WLCSP14 package, PinJ1 assigned to GPIO PA11 */ +#define LL_PINMUX_WLCSP14_PINF2_PA1 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinF2 assigned to GPIO PA1 */ +#define LL_PINMUX_WLCSP14_PINF2_PA2 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX0_0) /*!< STM32C031 WLCSP14 package, PinF2 assigned to GPIO PA2 */ +#define LL_PINMUX_WLCSP14_PING3_PF2 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinG3 assigned to GPIO PF2 */ +#define LL_PINMUX_WLCSP14_PING3_PA0 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX1_0) /*!< STM32C031 WLCSP14 package, PinG3 assigned to GPIO PA0 */ +#define LL_PINMUX_WLCSP14_PINJ1_PA8 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinJ1 assigned to GPIO PA8 */ +#define LL_PINMUX_WLCSP14_PINJ1_PA11 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX2_0) /*!< STM32C031 WLCSP14 package, PinJ1 assigned to GPIO PA11 */ #define LL_PINMUX_WLCSP14_PINH2_PA5 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinH2 assigned to GPIO PA5 */ -#define LL_PINMUX_WLCSP14_PINH2_PA6 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | SYSCFG_CFGR3_PINMUX3_0) /*!< STM32C031 WLCSP14 package, PinH2 assigned to GPIO PA6 */ -#define LL_PINMUX_WLCSP14_PING1_PA7 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA7 */ -#define LL_PINMUX_WLCSP14_PING1_PA12 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | SYSCFG_CFGR3_PINMUX4_0) /*!< STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA12 */ +#define LL_PINMUX_WLCSP14_PINH2_PA6 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX3_0) /*!< STM32C031 WLCSP14 package, PinH2 assigned to GPIO PA6 */ +#define LL_PINMUX_WLCSP14_PING1_PA7 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA7 */ +#define LL_PINMUX_WLCSP14_PING1_PA12 (((SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX4_0) /*!< STM32C031 WLCSP14 package, PinG1 assigned to GPIO PA12 */ #define LL_PINMUX_WLCSP14_PINJ3_PA3 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | 0x00000000U) /*!< STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA3 */ -#define LL_PINMUX_WLCSP14_PINJ3_PA4 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | SYSCFG_CFGR3_PINMUX5_0) /*!< STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA4 */ +#define LL_PINMUX_WLCSP14_PINJ3_PA4 (((SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX5_0) /*!< STM32C031 WLCSP14 package, PinJ3 assigned to GPIO PA4 */ + +#elif (DEV_ID == 0x493UL) +#define LL_PINMUX_WLCSP19_PINH3_PF2 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | 0x00000000U) /*!< STM32C071 WLCSP19 package, PinH3 assigned to GPIO PF2 */ +#define LL_PINMUX_WLCSP19_PINH3_PA0 (((SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX0_0) /*!< STM32C071 WLCSP19 package, PinH3 assigned to GPIO PA0 */ +#define LL_PINMUX_WLCSP19_PINB1_PA14 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | 0x00000000U) /*!< STM32C071 WLCSP19 package, PinB1 assigned to GPIO PA14 */ +#define LL_PINMUX_WLCSP19_PINB1_PA15 (((SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX1_0) /*!< STM32C071 WLCSP19 package, PinB1 assigned to GPIO PA15 */ +#define LL_PINMUX_TSSOP20_PIN19_PA14 LL_PINMUX_WLCSP19_PINB1_PA14 +#define LL_PINMUX_TSSOP20_PIN19_PA15 LL_PINMUX_WLCSP19_PINB1_PA15 +#define LL_PINMUX_TSSOP20_PIN20_PB6 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | 0x00000000U) /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB6 */ +#define LL_PINMUX_TSSOP20_PIN20_PB3 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX2_0) /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB3 */ +#define LL_PINMUX_TSSOP20_PIN20_PB4 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX2_1) /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB4 */ +#define LL_PINMUX_TSSOP20_PIN20_PB5 (((SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) /*!< STM32C071 TSSOP20 package, Pin20 assigned to GPIO PB5 */ +#define LL_PINMUX_WLCSP19_PINB3_PB7 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | 0x00000000U) /*!< STM32C071 WLCSP19 package, PinH2 assigned to GPIO PB7 */ +#define LL_PINMUX_WLCSP19_PINB3_PB8 (((SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) << 16U) | \ + SYSCFG_CFGR3_PINMUX3_0) /*!< STM32C071 WLCSP19 package, PinH2 assigned to GPIO PB8 */ +#define LL_PINMUX_TSSOP20_PIN1_PB7 LL_PINMUX_WLCSP19_PINB3_PB7 +#define LL_PINMUX_TSSOP20_PIN1_PB8 LL_PINMUX_WLCSP19_PINB3_PB8 #endif /* DEV_ID == 0x443UL */ /** * @} @@ -232,10 +283,17 @@ extern "C" { #define LL_PINMUX_WLCSP14_PINH2 (SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) /*!< STM32C031 WLCSP14 package, GPIO PinH2 multiplexer */ #define LL_PINMUX_WLCSP14_PING1 (SYSCFG_CFGR3_PINMUX4_0 | SYSCFG_CFGR3_PINMUX4_1) /*!< STM32C031 WLCSP14 package, GPIO PinG1 multiplexer */ #define LL_PINMUX_WLCSP14_PINJ3 (SYSCFG_CFGR3_PINMUX5_0 | SYSCFG_CFGR3_PINMUX5_1) /*!< STM32C031 WLCSP14 package, GPIO PinJ3 multiplexer */ +#elif (DEV_ID == 0x493UL) +#define LL_PINMUX_WLCSP19_PINH3 (SYSCFG_CFGR3_PINMUX0_0 | SYSCFG_CFGR3_PINMUX0_1) /*!< STM32C071 WLCSP19 package, GPIO PinH3 multiplexer */ +#define LL_PINMUX_WLCSP19_PINB1 (SYSCFG_CFGR3_PINMUX1_0 | SYSCFG_CFGR3_PINMUX1_1) /*!< STM32C071 WLCSP19 package, GPIO PinB1 multiplexer */ +#define LL_PINMUX_TSSOP20_PIN19 LL_PINMUX_WLCSP19_PINB1 /*!< STM32C071 TSSOP20 package, GPIO Pin19 multiplexer */ +#define LL_PINMUX_TSSOP20_PIN20 (SYSCFG_CFGR3_PINMUX2_0 | SYSCFG_CFGR3_PINMUX2_1) /*!< STM32C071 TSSOP20 package, GPIO Pin20 multiplexer */ +#define LL_PINMUX_WLCSP19_PINB3 (SYSCFG_CFGR3_PINMUX3_0 | SYSCFG_CFGR3_PINMUX3_1) /*!< STM32C071 WLCSP19 package, GPIO PinB3 multiplexer */ +#define LL_PINMUX_TSSOP20_PIN1 LL_PINMUX_WLCSP19_PINB3 /*!< STM32C071 TSSOP20 package, GPIO Pin1 multiplexer */ #endif /* DEV_ID == 0x443UL */ - /** +/** * @} - */ + */ /** * @} @@ -367,6 +425,7 @@ __STATIC_INLINE uint32_t LL_SYSCFG_GetIRPolarity(void) * SYSCFG_CFGR1 I2C_FMP_PB8 LL_SYSCFG_EnableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_PB9 LL_SYSCFG_EnableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_I2C1 LL_SYSCFG_EnableFastModePlus\n + * SYSCFG_CFGR1 I2C_FMP_I2C2 LL_SYSCFG_EnableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_PA9 LL_SYSCFG_EnableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_PA10 LL_SYSCFG_EnableFastModePlus * SYSCFG_CFGR1 I2C_FMP_PC14 LL_SYSCFG_EnableFastModePlus @@ -376,6 +435,7 @@ __STATIC_INLINE uint32_t LL_SYSCFG_GetIRPolarity(void) * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PB8 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PB9 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_I2C1 + * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_I2C2 (*) * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PA9 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PA10 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PC14 @@ -394,6 +454,7 @@ __STATIC_INLINE void LL_SYSCFG_EnableFastModePlus(uint32_t ConfigFastModePlus) * SYSCFG_CFGR1 I2C_FMP_PB8 LL_SYSCFG_DisableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_PB9 LL_SYSCFG_DisableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_I2C1 LL_SYSCFG_DisableFastModePlus\n + * SYSCFG_CFGR1 I2C_FMP_I2C2 LL_SYSCFG_DisableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_PA9 LL_SYSCFG_DisableFastModePlus\n * SYSCFG_CFGR1 I2C_FMP_PA10 LL_SYSCFG_DisableFastModePlus * SYSCFG_CFGR1 I2C_FMP_PC14 LL_SYSCFG_EnableFastModePlus @@ -403,6 +464,7 @@ __STATIC_INLINE void LL_SYSCFG_EnableFastModePlus(uint32_t ConfigFastModePlus) * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PB8 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PB9 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_I2C1 + * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_I2C2 (*) * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PA9 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PA10 * @arg @ref LL_SYSCFG_I2C_FASTMODEPLUS_PC14 @@ -459,7 +521,7 @@ __STATIC_INLINE uint32_t LL_SYSCFG_GetConfigPinMux(uint32_t LL_PINMUX_PACKx_PINy return (uint32_t)(READ_BIT(SYSCFG->CFGR3, LL_PINMUX_PACKx_PINy) | (LL_PINMUX_PACKx_PINy << 16U)); } -#if defined(SYSCFG_ITLINE0_SR_EWDG) +#if defined(SYSCFG_ITLINE0_SR_WWDG) /** * @brief Check if Window watchdog interrupt occurred or not. * @rmtoll SYSCFG_ITLINE0 SR_EWDG LL_SYSCFG_IsActiveFlag_WWDG @@ -467,9 +529,22 @@ __STATIC_INLINE uint32_t LL_SYSCFG_GetConfigPinMux(uint32_t LL_PINMUX_PACKx_PINy */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_WWDG(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[0], SYSCFG_ITLINE0_SR_EWDG) == (SYSCFG_ITLINE0_SR_EWDG)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[0], SYSCFG_ITLINE0_SR_WWDG) == (SYSCFG_ITLINE0_SR_WWDG)) ? 1UL : 0UL); } -#endif /* SYSCFG_ITLINE0_SR_EWDG */ +#endif /* SYSCFG_ITLINE0_SR_WWDG */ + +#if defined(SYSCFG_ITLINE1_SR_PVM_VDDIO2_OUT) +/** + * @brief Check if VDDIO2 supply monitoring interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE1_SR_PVM_VDDIO2_OUT LL_SYSCFG_IsActiveFlag_PVM_VDDIO2_OUT + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_PVM_VDDIO2_OUT(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[1], + SYSCFG_ITLINE1_SR_PVM_VDDIO2_OUT) == (SYSCFG_ITLINE1_SR_PVM_VDDIO2_OUT)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE1_SR_PVM_VDDIO2_OUT */ #if defined(SYSCFG_ITLINE2_SR_RTC) /** @@ -495,18 +570,29 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_FLASH_ITF(void) } #endif /* SYSCFG_ITLINE3_SR_FLASH_ITF */ - -#if defined(SYSCFG_ITLINE4_SR_CLK_CTRL) +#if defined(SYSCFG_ITLINE4_SR_RCC) /** * @brief Check if Reset and clock control interrupt occurred or not. - * @rmtoll SYSCFG_ITLINE4 SR_CLK_CTRL LL_SYSCFG_IsActiveFlag_CLK_CTRL + * @rmtoll SYSCFG_ITLINE4_SR_RCC LL_SYSCFG_IsActiveFlag_CLK_CTRL * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_CLK_CTRL(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[4], SYSCFG_ITLINE4_SR_CLK_CTRL) == (SYSCFG_ITLINE4_SR_CLK_CTRL)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[4], SYSCFG_ITLINE4_SR_RCC) == (SYSCFG_ITLINE4_SR_RCC)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE4_SR_RCC */ + +#if defined(SYSCFG_ITLINE4_SR_CRS) +/** + * @brief Check if CRS interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE4 SR_CRS LL_SYSCFG_IsActiveFlag_CRS + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_CRS(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[4], SYSCFG_ITLINE4_SR_CRS) == (SYSCFG_ITLINE4_SR_CRS)) ? 1UL : 0UL); } -#endif /* SYSCFG_ITLINE4_SR_CLK_CTRL */ +#endif /* SYSCFG_ITLINE4_SR_CRS */ #if defined(SYSCFG_ITLINE5_SR_EXTI0) /** @@ -700,6 +786,17 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_EXTI15(void) } #endif /* SYSCFG_ITLINE7_SR_EXTI15 */ +#if defined(SYSCFG_ITLINE8_SR_USB) +/** + * @brief Check if USB interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE8_SR_USB LL_SYSCFG_IsActiveFlag_USB + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_USB(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[8], SYSCFG_ITLINE8_SR_USB) == (SYSCFG_ITLINE8_SR_USB)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE8_SR_USB */ #if defined(SYSCFG_ITLINE9_SR_DMA1_CH1) /** @@ -737,7 +834,6 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_DMA1_CH3(void) } #endif /* SYSCFG_ITLINE10_SR_DMA1_CH3 */ - #if defined(SYSCFG_ITLINE11_SR_DMAMUX1) /** * @brief Check if DMAMUX interrupt occurred or not. @@ -750,6 +846,30 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_DMAMUX(void) } #endif /* SYSCFG_ITLINE11_SR_DMAMUX */ +#if defined(SYSCFG_ITLINE11_SR_DMA1_CH4) +/** + * @brief Check if DMA1_CH4 interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE11 SR_DMA1_CH4 LL_SYSCFG_IsActiveFlag_DMA1_CH4 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_DMA1_CH4(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[11], SYSCFG_ITLINE11_SR_DMA1_CH4) == (SYSCFG_ITLINE11_SR_DMA1_CH4)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE11_SR_DMA1_CH4 */ + +#if defined(SYSCFG_ITLINE11_SR_DMA1_CH5) +/** + * @brief Check if DMA1_CH5 interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE11 SR_DMA1_CH5 LL_SYSCFG_IsActiveFlag_DMA1_CH5 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_DMA1_CH5(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[11], SYSCFG_ITLINE11_SR_DMA1_CH5) == (SYSCFG_ITLINE11_SR_DMA1_CH5)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE11_SR_DMA1_CH5 */ + #if defined(SYSCFG_ITLINE12_SR_ADC) /** * @brief Check if ADC interrupt occurred or not. @@ -822,6 +942,17 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM1_CC(void) } #endif /* SYSCFG_ITLINE14_SR_TIM1_CC */ +#if defined(SYSCFG_ITLINE15_SR_TIM2) +/** + * @brief Check if Timer 2 interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE15 SR_TIM2_GLB LL_SYSCFG_IsActiveFlag_TIM2 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM2(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[15], SYSCFG_ITLINE15_SR_TIM2) == (SYSCFG_ITLINE15_SR_TIM2)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE15_SR_TIM2 */ #if defined(SYSCFG_ITLINE16_SR_TIM3_GLB) /** @@ -843,7 +974,8 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM3(void) */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM14(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[19], SYSCFG_ITLINE19_SR_TIM14_GLB) == (SYSCFG_ITLINE19_SR_TIM14_GLB)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[19], SYSCFG_ITLINE19_SR_TIM14_GLB) == \ + (SYSCFG_ITLINE19_SR_TIM14_GLB)) ? 1UL : 0UL); } #endif /* SYSCFG_ITLINE19_SR_TIM14_GLB */ @@ -855,7 +987,8 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM14(void) */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM16(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[21], SYSCFG_ITLINE21_SR_TIM16_GLB) == (SYSCFG_ITLINE21_SR_TIM16_GLB)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[21], SYSCFG_ITLINE21_SR_TIM16_GLB) == \ + (SYSCFG_ITLINE21_SR_TIM16_GLB)) ? 1UL : 0UL); } #endif /* SYSCFG_ITLINE21_SR_TIM16_GLB */ @@ -867,7 +1000,8 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM16(void) */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_TIM17(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[22], SYSCFG_ITLINE22_SR_TIM17_GLB) == (SYSCFG_ITLINE22_SR_TIM17_GLB)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[22], SYSCFG_ITLINE22_SR_TIM17_GLB) == \ + (SYSCFG_ITLINE22_SR_TIM17_GLB)) ? 1UL : 0UL); } #endif /* SYSCFG_ITLINE22_SR_TIM17_GLB */ @@ -883,6 +1017,18 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_I2C1(void) } #endif /* SYSCFG_ITLINE23_SR_I2C1_GLB */ +#if defined(SYSCFG_ITLINE24_SR_I2C2_GLB) +/** + * @brief Check if I2C2 interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE24 SR_I2C2_GLB LL_SYSCFG_IsActiveFlag_I2C2 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_I2C2(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[24], SYSCFG_ITLINE24_SR_I2C2_GLB) == (SYSCFG_ITLINE24_SR_I2C2_GLB)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE24_SR_I2C2_GLB */ + #if defined(SYSCFG_ITLINE25_SR_SPI1) /** * @brief Check if SPI1 interrupt occurred or not. @@ -895,6 +1041,17 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_SPI1(void) } #endif /* SYSCFG_ITLINE25_SR_SPI1 */ +#if defined(SYSCFG_ITLINE26_SR_SPI2) +/** + * @brief Check if SPI2 interrupt occurred or not. + * @rmtoll SYSCFG_ITLINE26_SR_SPI2 LL_SYSCFG_IsActiveFlag_SPI2 + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_SPI2(void) +{ + return ((READ_BIT(SYSCFG->IT_LINE_SR[26], SYSCFG_ITLINE26_SR_SPI2) == (SYSCFG_ITLINE26_SR_SPI2)) ? 1UL : 0UL); +} +#endif /* SYSCFG_ITLINE26_SR_SPI2 */ #if defined(SYSCFG_ITLINE27_SR_USART1_GLB) /** @@ -904,7 +1061,8 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_SPI1(void) */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_USART1(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[27], SYSCFG_ITLINE27_SR_USART1_GLB) == (SYSCFG_ITLINE27_SR_USART1_GLB)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[27], SYSCFG_ITLINE27_SR_USART1_GLB) == \ + (SYSCFG_ITLINE27_SR_USART1_GLB)) ? 1UL : 0UL); } #endif /* SYSCFG_ITLINE27_SR_USART1_GLB */ @@ -916,7 +1074,8 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_USART1(void) */ __STATIC_INLINE uint32_t LL_SYSCFG_IsActiveFlag_USART2(void) { - return ((READ_BIT(SYSCFG->IT_LINE_SR[28], SYSCFG_ITLINE28_SR_USART2_GLB) == (SYSCFG_ITLINE28_SR_USART2_GLB)) ? 1UL : 0UL); + return ((READ_BIT(SYSCFG->IT_LINE_SR[28], SYSCFG_ITLINE28_SR_USART2_GLB) == \ + (SYSCFG_ITLINE28_SR_USART2_GLB)) ? 1UL : 0UL); } #endif /* SYSCFG_ITLINE28_SR_USART2_GLB */ @@ -997,6 +1156,7 @@ __STATIC_INLINE void LL_DBGMCU_DisableDBGStandbyMode(void) * DBG_APB_FZ1 DBG_IWDG_STOP LL_DBGMCU_APB1_GRP1_FreezePeriph\n * DBG_APB_FZ1 DBG_I2C1_STOP LL_DBGMCU_APB1_GRP1_FreezePeriph\n * @param Periphs This parameter can be a combination of the following values: + * @arg @ref LL_DBGMCU_APB1_GRP1_TIM2_STOP (*) * @arg @ref LL_DBGMCU_APB1_GRP1_TIM3_STOP * @arg @ref LL_DBGMCU_APB1_GRP1_RTC_STOP * @arg @ref LL_DBGMCU_APB1_GRP1_WWDG_STOP @@ -1013,11 +1173,13 @@ __STATIC_INLINE void LL_DBGMCU_APB1_GRP1_FreezePeriph(uint32_t Periphs) /** * @brief Unfreeze APB1 peripherals (group1 peripherals) * @rmtoll DBG_APB_FZ1 DBG_TIM3_STOP LL_DBGMCU_APB1_GRP1_UnFreezePeriph\n + * DBG_APB_FZ1 DBG_TIM2_STOP LL_DBGMCU_APB1_GRP1_UnFreezePeriph\n * DBG_APB_FZ1 DBG_RTC_STOP LL_DBGMCU_APB1_GRP1_UnFreezePeriph\n * DBG_APB_FZ1 DBG_WWDG_STOP LL_DBGMCU_APB1_GRP1_UnFreezePeriph\n * DBG_APB_FZ1 DBG_IWDG_STOP LL_DBGMCU_APB1_GRP1_UnFreezePeriph\n * DBG_APB_FZ1 DBG_I2C1_SMBUS_TIMEOUT LL_DBGMCU_APB1_GRP1_UnFreezePeriph\n * @param Periphs This parameter can be a combination of the following values: + * @arg @ref LL_DBGMCU_APB1_GRP1_TIM2_STOP (*) * @arg @ref LL_DBGMCU_APB1_GRP1_TIM3_STOP * @arg @ref LL_DBGMCU_APB1_GRP1_RTC_STOP * @arg @ref LL_DBGMCU_APB1_GRP1_WWDG_STOP @@ -1033,42 +1195,45 @@ __STATIC_INLINE void LL_DBGMCU_APB1_GRP1_UnFreezePeriph(uint32_t Periphs) } /** - * @brief Freeze APB2 peripherals - * @rmtoll DBG_APB_FZ2 DBG_TIM1_STOP LL_DBGMCU_APB2_GRP1_FreezePeriph\n - * DBG_APB_FZ2 DBG_TIM14_STOP LL_DBGMCU_APB2_GRP1_FreezePeriph\n - * DBG_APB_FZ2 DBG_TIM16_STOP LL_DBGMCU_APB2_GRP1_FreezePeriph\n - * DBG_APB_FZ2 DBG_TIM17_STOP LL_DBGMCU_APB2_GRP1_FreezePeriph + * @brief Freeze APB1 peripherals (group2 peripherals) + * @rmtoll DBG_APB_FZ2 DBG_TIM1_STOP LL_DBGMCU_APB1_GRP2_FreezePeriph\n + * DBG_APB_FZ2 DBG_TIM14_STOP LL_DBGMCU_APB1_GRP2_FreezePeriph\n + * DBG_APB_FZ2 DBG_TIM16_STOP LL_DBGMCU_APB1_GRP2_FreezePeriph\n + * DBG_APB_FZ2 DBG_TIM17_STOP LL_DBGMCU_APB1_GRP2_FreezePeriph * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM1_STOP - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM14_STOP - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM16_STOP - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM17_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM1_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM14_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM16_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM17_STOP * * @retval None */ -__STATIC_INLINE void LL_DBGMCU_APB2_GRP1_FreezePeriph(uint32_t Periphs) +__STATIC_INLINE void LL_DBGMCU_APB1_GRP2_FreezePeriph(uint32_t Periphs) { SET_BIT(DBG->APBFZ2, Periphs); } +#define LL_DBGMCU_APB2_GRP1_FreezePeriph LL_DBGMCU_APB1_GRP2_FreezePeriph /* define for legacy purpose */ /** * @brief Unfreeze APB2 peripherals - * @rmtoll DBG_APB_FZ2 DBG_TIM1_STOP LL_DBGMCU_APB2_GRP1_UnFreezePeriph\n - * DBG_APB_FZ2 DBG_TIM14_STOP LL_DBGMCU_APB2_GRP1_UnFreezePeriph\n - * DBG_APB_FZ2 DBG_TIM16_STOP LL_DBGMCU_APB2_GRP1_UnFreezePeriph\n - * DBG_APB_FZ2 DBG_TIM17_STOP LL_DBGMCU_APB2_GRP1_UnFreezePeriph + * @rmtoll DBG_APB_FZ2 DBG_TIM1_STOP LL_DBGMCU_APB1_GRP2_UnFreezePeriph\n + * DBG_APB_FZ2 DBG_TIM14_STOP LL_DBGMCU_APB1_GRP2_UnFreezePeriph\n + * DBG_APB_FZ2 DBG_TIM16_STOP LL_DBGMCU_APB1_GRP2_UnFreezePeriph\n + * DBG_APB_FZ2 DBG_TIM17_STOP LL_DBGMCU_APB1_GRP2_UnFreezePeriph * @param Periphs This parameter can be a combination of the following values: - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM1_STOP - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM14_STOP - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM16_STOP - * @arg @ref LL_DBGMCU_APB2_GRP1_TIM17_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM1_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM14_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM16_STOP + * @arg @ref LL_DBGMCU_APB1_GRP2_TIM17_STOP * * @retval None */ -__STATIC_INLINE void LL_DBGMCU_APB2_GRP1_UnFreezePeriph(uint32_t Periphs) +__STATIC_INLINE void LL_DBGMCU_APB1_GRP2_UnFreezePeriph(uint32_t Periphs) { CLEAR_BIT(DBG->APBFZ2, Periphs); } + +#define LL_DBGMCU_APB2_GRP1_UnFreezePeriph LL_DBGMCU_APB1_GRP2_UnFreezePeriph /* define for legacy purpose */ /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_tim.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_tim.h index 4baef1bfc..dcfd894e5 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_tim.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_tim.h @@ -655,10 +655,10 @@ typedef struct /** @defgroup TIM_LL_EC_COUNTERMODE Counter Mode * @{ */ -#define LL_TIM_COUNTERMODE_UP 0x00000000U /*!CR2, TIM_CR2_CCPC); } +/** + * @brief Indicates whether the capture/compare control bits (CCxE, CCxNE and OCxM) preload is enabled. + * @rmtoll CR2 CCPC LL_TIM_CC_IsEnabledPreload + * @param TIMx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_TIM_CC_IsEnabledPreload(const TIM_TypeDef *TIMx) +{ + return ((READ_BIT(TIMx->CR2, TIM_CR2_CCPC) == (TIM_CR2_CCPC)) ? 1UL : 0UL); +} + /** * @brief Set the updated source of the capture/compare control bits (CCxE, CCxNE and OCxM). * @note Macro IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check @@ -2035,8 +2064,8 @@ __STATIC_INLINE void LL_TIM_OC_ConfigOutput(TIM_TypeDef *TIMx, uint32_t Channel, * @arg @ref LL_TIM_OCMODE_RETRIG_OPM2 * @arg @ref LL_TIM_OCMODE_COMBINED_PWM1 * @arg @ref LL_TIM_OCMODE_COMBINED_PWM2 - * @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM1 - * @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM2 + * @arg @ref LL_TIM_OCMODE_ASYMMETRIC_PWM1 + * @arg @ref LL_TIM_OCMODE_ASYMMETRIC_PWM2 * @retval None */ __STATIC_INLINE void LL_TIM_OC_SetMode(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Mode) @@ -2075,8 +2104,8 @@ __STATIC_INLINE void LL_TIM_OC_SetMode(TIM_TypeDef *TIMx, uint32_t Channel, uint * @arg @ref LL_TIM_OCMODE_RETRIG_OPM2 * @arg @ref LL_TIM_OCMODE_COMBINED_PWM1 * @arg @ref LL_TIM_OCMODE_COMBINED_PWM2 - * @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM1 - * @arg @ref LL_TIM_OCMODE_ASSYMETRIC_PWM2 + * @arg @ref LL_TIM_OCMODE_ASYMMETRIC_PWM1 + * @arg @ref LL_TIM_OCMODE_ASYMMETRIC_PWM2 */ __STATIC_INLINE uint32_t LL_TIM_OC_GetMode(const TIM_TypeDef *TIMx, uint32_t Channel) { @@ -3465,18 +3494,6 @@ __STATIC_INLINE void LL_TIM_DisarmBRK(TIM_TypeDef *TIMx) SET_BIT(TIMx->BDTR, TIM_BDTR_BKDSRM); } -/** - * @brief Re-arm the break input (when it operates in bidirectional mode). - * @note The Break input is automatically armed as soon as MOE bit is set. - * @rmtoll BDTR BKDSRM LL_TIM_ReArmBRK - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ReArmBRK(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->BDTR, TIM_BDTR_BKDSRM); -} - /** * @brief Enable the break 2 function. * @note Macro IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not @@ -3566,18 +3583,6 @@ __STATIC_INLINE void LL_TIM_DisarmBRK2(TIM_TypeDef *TIMx) SET_BIT(TIMx->BDTR, TIM_BDTR_BK2DSRM); } -/** - * @brief Re-arm the break 2 input (when it operates in bidirectional mode). - * @note The Break 2 input is automatically armed as soon as MOE bit is set. - * @rmtoll BDTR BK2DSRM LL_TIM_ReArmBRK2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ReArmBRK2(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->BDTR, TIM_BDTR_BK2DSRM); -} - /** * @brief Select the outputs off state (enabled v.s. disabled) in Idle and Run modes. * @note Macro IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_usb.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_usb.h new file mode 100644 index 000000000..2cf6f309c --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_usb.h @@ -0,0 +1,911 @@ +/** + ****************************************************************************** + * @file stm32c0xx_ll_usb.h + * @author MCD Application Team + * @brief Header file of USB Low Layer HAL module. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32C0xx_LL_USB_H +#define STM32C0xx_LL_USB_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_hal_def.h" + +#if defined (USB_DRD_FS) +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +/** @addtogroup USB_LL + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +#ifndef HAL_USB_TIMEOUT +#define HAL_USB_TIMEOUT 0xF000000U +#endif /* define HAL_USB_TIMEOUT */ + +/** + * @brief USB Mode definition + */ + +typedef enum +{ + USB_DEVICE_MODE = 0, + USB_HOST_MODE = 1 +} USB_ModeTypeDef; + +/** + * @brief URB States definition + */ +typedef enum +{ + URB_IDLE = 0, + URB_DONE, + URB_NOTREADY, + URB_NYET, + URB_ERROR, + URB_STALL +} USB_URBStateTypeDef; + +/** + * @brief Host channel States definition + */ +typedef enum +{ + HC_IDLE = 0, + HC_XFRC, + HC_HALTED, + HC_ACK, + HC_NAK, + HC_NYET, + HC_STALL, + HC_XACTERR, + HC_BBLERR, + HC_DATATGLERR +} USB_HCStateTypeDef; + + +/** + * @brief USB Instance Initialization Structure definition + */ +typedef struct +{ + uint8_t dev_endpoints; /*!< Device Endpoints number. + This parameter depends on the used USB core. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t Host_channels; /*!< Host Channels number. + This parameter Depends on the used USB core. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t dma_enable; /*!< USB DMA state. + If DMA is not supported this parameter shall be set by default to zero */ + + uint8_t speed; /*!< USB Core speed. + This parameter can be any value of @ref PCD_Speed/HCD_Speed + (HCD_SPEED_xxx, HCD_SPEED_xxx) */ + + uint8_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */ + + uint8_t phy_itface; /*!< Select the used PHY interface. + This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */ + + uint8_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ + + uint8_t low_power_enable; /*!< Enable or disable the low Power Mode. */ + + uint8_t lpm_enable; /*!< Enable or disable Link Power Management. */ + + uint8_t battery_charging_enable; /*!< Enable or disable Battery charging. */ + + uint8_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ + + uint8_t bulk_doublebuffer_enable; /*!< Enable or disable the double buffer mode on bulk EP */ + + uint8_t iso_singlebuffer_enable; /*!< Enable or disable the Single buffer mode on Isochronous EP */ +} USB_CfgTypeDef; + +typedef struct +{ + uint8_t num; /*!< Endpoint number + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t is_in; /*!< Endpoint direction + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t is_stall; /*!< Endpoint stall condition + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t type; /*!< Endpoint type + This parameter can be any value of @ref USB_LL_EP_Type */ + + uint8_t data_pid_start; /*!< Initial data PID + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + + uint16_t pmaadress; /*!< PMA Address + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + uint16_t pmaaddr0; /*!< PMA Address0 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + uint16_t pmaaddr1; /*!< PMA Address1 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + uint8_t doublebuffer; /*!< Double buffer enable + This parameter can be 0 or 1 */ + + + uint32_t maxpacket; /*!< Endpoint Max packet size + This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ + + uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ + + uint32_t xfer_len; /*!< Current transfer length */ + + uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ + + uint32_t xfer_len_db; /*!< double buffer transfer length used with bulk double buffer in */ + + uint8_t xfer_fill_db; /*!< double buffer Need to Fill new buffer used with bulk_in */ +} USB_EPTypeDef; + +typedef struct +{ + uint8_t dev_addr; /*!< USB device address. + This parameter must be a number between Min_Data = 1 and Max_Data = 255 */ + + uint8_t phy_ch_num; /*!< Host channel number. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t ep_num; /*!< Endpoint number. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t ch_dir; /*!< channel direction + This parameter store the physical channel direction IN/OUT/BIDIR */ + + uint8_t speed; /*!< USB Host Channel speed. + This parameter can be any value of @ref HCD_Device_Speed: + (HCD_DEVICE_SPEED_xxx) */ + + uint8_t hub_port_nbr; /*!< USB HUB port number */ + uint8_t hub_addr; /*!< USB HUB address */ + + uint8_t ep_type; /*!< Endpoint Type. + This parameter can be any value of @ref USB_LL_EP_Type */ + + uint16_t max_packet; /*!< Endpoint Max packet size. + This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ + + uint8_t data_pid; /*!< Initial data PID. + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t *xfer_buff; /*!< Pointer to transfer buffer. */ + + uint32_t xfer_len; /*!< Current transfer length. */ + + uint32_t xfer_len_db; /*!< Current transfer length used in double buffer mode. */ + + + uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer. */ + + uint8_t toggle_in; /*!< IN transfer current toggle flag. + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t toggle_out; /*!< OUT transfer current toggle flag + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint32_t ErrCnt; /*!< Host channel error count. */ + + uint16_t pmaadress; /*!< PMA Address + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + uint16_t pmaaddr0; /*!< PMA Address0 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + uint16_t pmaaddr1; /*!< PMA Address1 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + uint8_t doublebuffer; /*!< Double buffer enable + This parameter can be 0 or 1 */ + + USB_URBStateTypeDef urb_state; /*!< URB state. + This parameter can be any value of @ref USB_URBStateTypeDef */ + + USB_HCStateTypeDef state; /*!< Host Channel state. + This parameter can be any value of @ref USB_HCStateTypeDef */ +} USB_HCTypeDef; + +typedef USB_ModeTypeDef USB_DRD_ModeTypeDef; +typedef USB_CfgTypeDef USB_DRD_CfgTypeDef; +typedef USB_EPTypeDef USB_DRD_EPTypeDef; +typedef USB_URBStateTypeDef USB_DRD_URBStateTypeDef; +typedef USB_HCStateTypeDef USB_DRD_HCStateTypeDef; +typedef USB_HCTypeDef USB_DRD_HCTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup PCD_Exported_Constants PCD Exported Constants + * @{ + */ +/** @defgroup USB_LL_EP0_MPS USB Low Layer EP0 MPS + * @{ + */ +#define EP_MPS_64 0U +#define EP_MPS_32 1U +#define EP_MPS_16 2U +#define EP_MPS_8 3U +/** + * @} + */ + +/** @defgroup USB_LL_EP_Type USB Low Layer EP Type + * @{ + */ +#define EP_TYPE_CTRL 0U +#define EP_TYPE_ISOC 1U +#define EP_TYPE_BULK 2U +#define EP_TYPE_INTR 3U +#define EP_TYPE_MSK 3U +/** + * @} + */ + +/** @defgroup USB_LL_EP_Speed USB Low Layer EP Speed + * @{ + */ +#define EP_SPEED_LOW 0U +#define EP_SPEED_FULL 1U +#define EP_SPEED_HIGH 2U +/** + * @} + */ + +/** @defgroup USB_LL_CH_PID_Type USB Low Layer Channel PID Type + * @{ + */ +#define HC_PID_DATA0 0U +#define HC_PID_DATA2 1U +#define HC_PID_DATA1 2U +#define HC_PID_SETUP 3U +/** + * @} + */ + +/** @defgroup USB_LL Device Speed + * @{ + */ +#define USBD_FS_SPEED 2U +#define USBH_FSLS_SPEED 1U +/** + * @} + */ + +#define EP_ADDR_MSK 0x7U + +#ifndef USE_USB_DOUBLE_BUFFER +#define USE_USB_DOUBLE_BUFFER 1U +#endif /* USE_USB_DOUBLE_BUFFER */ + +#define USB_EMBEDDED_PHY 2U + +/*!< USB Speed */ +#define USB_DRD_SPEED_FS 1U +#define USB_DRD_SPEED_LS 2U +#define USB_DRD_SPEED_LSFS 3U + +/*!< Channel Direction */ +#define CH_IN_DIR 1U +#define CH_OUT_DIR 0U + +/*!< Number of used channels in the Application */ +#ifndef USB_DRD_USED_CHANNELS +#define USB_DRD_USED_CHANNELS 8U +#endif /* USB_DRD_USED_CHANNELS */ + +/** + * used for USB_HC_DoubleBuffer API + */ +#define USB_DRD_BULK_DBUFF_ENBALE 1U +#define USB_DRD_BULK_DBUFF_DISABLE 2U +#define USB_DRD_ISOC_DBUFF_ENBALE 3U +#define USB_DRD_ISOC_DBUFF_DISABLE 4U + +/* First available address in PMA */ +#define PMA_START_ADDR (0x10U + (8U *(USB_DRD_USED_CHANNELS - 2U))) +#define PMA_END_ADDR USB_DRD_PMA_SIZE + +/* Exported macro ------------------------------------------------------------*/ +/** + * @} + */ +/******************** Bit definition for USB_COUNTn_RX register *************/ +#define USB_CNTRX_NBLK_MSK (0x1FU << 26) +#define USB_CNTRX_BLSIZE (0x1U << 31) + + +/*Set Channel/Endpoint to the USB Register */ +#define USB_DRD_SET_CHEP(USBx, bEpChNum, wRegValue) (*(__IO uint32_t *)\ + (&(USBx)->CHEP0R + (bEpChNum)) = (uint32_t)(wRegValue)) + +/*Get Channel/Endpoint from the USB Register */ +#define USB_DRD_GET_CHEP(USBx, bEpChNum) (*(__IO uint32_t *)(&(USBx)->CHEP0R + (bEpChNum))) + + +/** + * @brief free buffer used from the application realizing it to the line + * toggles bit SW_BUF in the double buffered endpoint register + * @param USBx USB device. + * @param bEpChNum, bDir + * @retval None + */ +#define USB_DRD_FREE_USER_BUFFER(USBx, bEpChNum, bDir) \ + do { \ + if ((bDir) == 0U) \ + { \ + /* OUT double buffered endpoint */ \ + USB_DRD_TX_DTOG((USBx), (bEpChNum)); \ + } \ + else if ((bDir) == 1U) \ + { \ + /* IN double buffered endpoint */ \ + USB_DRD_RX_DTOG((USBx), (bEpChNum)); \ + } \ + } while(0) + + +/** + * @brief Set the Setup bit in the corresponding channel, when a Setup + transaction is needed. + * @param USBx USB device. + * @param bEpChNum + * @retval None + */ +#define USB_DRD_CHEP_TX_SETUP(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) ; \ + \ + /* Set Setup bit */ \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_SETUP)); \ + } while(0) + + +/** + * @brief Clears bit ERR_RX in the Channel register + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_CLEAR_CHEP_RX_ERR(USBx, bChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bChNum)); \ + _wRegVal = (_wRegVal & USB_CHEP_REG_MASK & (~USB_CHEP_ERRRX) & (~USB_CHEP_VTRX)) | \ + (USB_CHEP_VTTX | USB_CHEP_ERRTX); \ + \ + USB_DRD_SET_CHEP((USBx), (bChNum), _wRegVal); \ + } while(0) /* USB_DRD_CLEAR_CHEP_RX_ERR */ + + +/** + * @brief Clears bit ERR_TX in the Channel register + * @param USBx USB peripheral instance register address. + * @param bChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_CLEAR_CHEP_TX_ERR(USBx, bChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bChNum)); \ + _wRegVal = (_wRegVal & USB_CHEP_REG_MASK & (~USB_CHEP_ERRTX) & (~USB_CHEP_VTTX)) | \ + (USB_CHEP_VTRX|USB_CHEP_ERRRX); \ + \ + USB_DRD_SET_CHEP((USBx), (bChNum), _wRegVal); \ + } while(0) /* USB_DRD_CLEAR_CHEP_TX_ERR */ + + +/** + * @brief sets the status for tx transfer (bits STAT_TX[1:0]). + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param wState new state + * @retval None + */ +#define USB_DRD_SET_CHEP_TX_STATUS(USBx, bEpChNum, wState) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_CHEP_TX_DTOGMASK; \ + /* toggle first bit ? */ \ + if ((USB_CHEP_TX_DTOG1 & (wState)) != 0U) \ + { \ + _wRegVal ^= USB_CHEP_TX_DTOG1; \ + } \ + /* toggle second bit ? */ \ + if ((USB_CHEP_TX_DTOG2 & (wState)) != 0U) \ + { \ + _wRegVal ^= USB_CHEP_TX_DTOG2; \ + } \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTRX| USB_CHEP_VTTX)); \ + } while(0) /* USB_DRD_SET_CHEP_TX_STATUS */ + + +/** + * @brief sets the status for rx transfer (bits STAT_TX[1:0]) + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param wState new state + * @retval None + */ +#define USB_DRD_SET_CHEP_RX_STATUS(USBx, bEpChNum, wState) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_CHEP_RX_DTOGMASK; \ + /* toggle first bit ? */ \ + if ((USB_CHEP_RX_DTOG1 & (wState)) != 0U) \ + { \ + _wRegVal ^= USB_CHEP_RX_DTOG1; \ + } \ + /* toggle second bit ? */ \ + if ((USB_CHEP_RX_DTOG2 & (wState)) != 0U) \ + { \ + _wRegVal ^= USB_CHEP_RX_DTOG2; \ + } \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTRX | USB_CHEP_VTTX)); \ + } while(0) /* USB_DRD_SET_CHEP_RX_STATUS */ + + +/** + * @brief gets the status for tx/rx transfer (bits STAT_TX[1:0] + * /STAT_RX[1:0]) + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval status + */ +#define USB_DRD_GET_CHEP_TX_STATUS(USBx, bEpChNum) \ + ((uint16_t)USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_DRD_CHEP_TX_STTX) + +#define USB_DRD_GET_CHEP_RX_STATUS(USBx, bEpChNum) \ + ((uint16_t)USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_DRD_CHEP_RX_STRX) + + +/** + * @brief set EP_KIND bit. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_SET_CHEP_KIND(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_CHEP_REG_MASK; \ + \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTRX | USB_CHEP_VTTX | USB_CHEP_KIND)); \ + } while(0) /* USB_DRD_SET_CHEP_KIND */ + + +/** + * @brief clear EP_KIND bit. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_CLEAR_CHEP_KIND(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_EP_KIND_MASK; \ + \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTRX | USB_CHEP_VTTX)); \ + } while(0) /* USB_DRD_CLEAR_CHEP_KIND */ + + +/** + * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_CLEAR_RX_CHEP_CTR(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & (0xFFFF7FFFU & USB_CHEP_REG_MASK); \ + \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTTX)); \ + } while(0) /* USB_CLEAR_RX_CHEP_CTR */ + +#define USB_DRD_CLEAR_TX_CHEP_CTR(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & (0xFFFFFF7FU & USB_CHEP_REG_MASK); \ + \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTRX)); \ + } while(0) /* USB_CLEAR_TX_CHEP_CTR */ + + +/** + * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_RX_DTOG(USBx, bEpChNum) \ + do { \ + uint32_t _wEPVal; \ + \ + _wEPVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_CHEP_REG_MASK; \ + \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wEPVal | USB_CHEP_VTRX | USB_CHEP_VTTX | USB_CHEP_DTOG_RX)); \ + } while(0) /* USB_DRD_RX_DTOG */ + +#define USB_DRD_TX_DTOG(USBx, bEpChNum) \ + do { \ + uint32_t _wEPVal; \ + \ + _wEPVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_CHEP_REG_MASK; \ + \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wEPVal | USB_CHEP_VTRX | USB_CHEP_VTTX | USB_CHEP_DTOG_TX)); \ + } while(0) /* USB_TX_DTOG */ + + +/** + * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_CLEAR_RX_DTOG(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)); \ + \ + if ((_wRegVal & USB_CHEP_DTOG_RX) != 0U) \ + { \ + USB_DRD_RX_DTOG((USBx), (bEpChNum)); \ + } \ + } while(0) /* USB_DRD_CLEAR_RX_DTOG */ + +#define USB_DRD_CLEAR_TX_DTOG(USBx, bEpChNum) \ + do { \ + uint32_t _wRegVal; \ + \ + _wRegVal = USB_DRD_GET_CHEP((USBx), (bEpChNum)); \ + \ + if ((_wRegVal & USB_CHEP_DTOG_TX) != 0U) \ + { \ + USB_DRD_TX_DTOG((USBx), (bEpChNum)); \ + } \ + } while(0) /* USB_DRD_CLEAR_TX_DTOG */ + + +/** + * @brief Sets address in an endpoint register. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param bAddr Address. + * @retval None + */ +#define USB_DRD_SET_CHEP_ADDRESS(USBx, bEpChNum, bAddr) \ + do { \ + uint32_t _wRegVal; \ + \ + /*Read the USB->CHEPx into _wRegVal, Reset(DTOGRX/STRX/DTOGTX/STTX) and set the EpAddress*/ \ + _wRegVal = (USB_DRD_GET_CHEP((USBx), (bEpChNum)) & USB_CHEP_REG_MASK) | (bAddr); \ + \ + /*Set _wRegVal in USB->CHEPx and set Transmit/Receive Valid Transfer (x=bEpChNum)*/ \ + USB_DRD_SET_CHEP((USBx), (bEpChNum), (_wRegVal | USB_CHEP_VTRX | USB_CHEP_VTTX)); \ + } while(0) /* USB_DRD_SET_CHEP_ADDRESS */ + + +/* PMA API Buffer Descriptor Management ------------------------------------------------------------*/ +/* Buffer Descriptor Table TXBD0/RXBD0 --- > TXBD7/RXBD7 8 possible descriptor +* The buffer descriptor is located inside the packet buffer memory (USB_PMA_BUFF) +* TXBD [Reserve |Countx| Address_Tx] +* RXBD [BLSIEZ|NUM_Block |CounRx| Address_Rx] */ + +/* Set TX Buffer Descriptor Address Field */ +#define USB_DRD_SET_CHEP_TX_ADDRESS(USBx, bEpChNum, wAddr) \ + do { \ + /* Reset old Address */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->TXBD &= USB_PMA_TXBD_ADDMSK; \ + \ + /* Bit0 & Bit1 should be =0 PMA must be Word aligned */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->TXBD |= (uint32_t)(((uint32_t)(wAddr) >> 2U) << 2U); \ + } while(0) /* USB_DRD_SET_CHEP_TX_ADDRESS */ + +/* Set RX Buffer Descriptor Address Field */ +#define USB_DRD_SET_CHEP_RX_ADDRESS(USBx, bEpChNum, wAddr) \ + do { \ + /* Reset old Address */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->RXBD &= USB_PMA_RXBD_ADDMSK; \ + \ + /* Bit0 & Bit1 should be =0 PMA must be Word aligned */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->RXBD |= (uint32_t)(((uint32_t)(wAddr) >> 2U) << 2U); \ + } while(0) /* USB_SET_CHEP_RX_ADDRESS */ + + +/** + * @brief Sets counter of rx buffer with no. of blocks. + * @param pdwReg Register pointer + * @param wCount Counter. + * @param wNBlocks no. of Blocks. + * @retval None + */ +#define USB_DRD_CALC_BLK32(pdwReg, wCount, wNBlocks) \ + do { \ + /* Divide PacketSize by 32 to calculate the Nb of Block32 */ \ + (wNBlocks) =((uint32_t)(wCount) >> 5U); \ + if (((uint32_t)(wCount) % 32U) == 0U) \ + { \ + (wNBlocks)--; \ + } \ + \ + (pdwReg)|= (uint32_t)((((wNBlocks) << 26U)) | USB_CNTRX_BLSIZE); \ + } while(0) /* USB_DRD_CALC_BLK32 */ + +#define USB_DRD_CALC_BLK2(pdwReg, wCount, wNBlocks) \ + do { \ + /* Divide PacketSize by 32 to calculate the Nb of Block32 */ \ + (wNBlocks) = (uint32_t)((uint32_t)(wCount) >> 1U); \ + if (((wCount) & 0x1U) != 0U) \ + { \ + (wNBlocks)++; \ + } \ + (pdwReg) |= (uint32_t)((wNBlocks) << 26U); \ + } while(0) /* USB_DRD_CALC_BLK2 */ + +#define USB_DRD_SET_CHEP_CNT_RX_REG(pdwReg, wCount) \ + do { \ + uint32_t wNBlocks; \ + \ + (pdwReg) &= ~(USB_CNTRX_BLSIZE | USB_CNTRX_NBLK_MSK); \ + \ + if ((wCount) == 0U) \ + { \ + (pdwReg) |= USB_CNTRX_BLSIZE; \ + } \ + else if ((wCount) <= 62U) \ + { \ + USB_DRD_CALC_BLK2((pdwReg), (wCount), wNBlocks); \ + } \ + else \ + { \ + USB_DRD_CALC_BLK32((pdwReg), (wCount), wNBlocks); \ + } \ + } while(0) /* USB_DRD_SET_CHEP_CNT_RX_REG */ + + +/** + * @brief sets counter for the tx/rx buffer. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param wCount Counter value. + * @retval None + */ +#define USB_DRD_SET_CHEP_TX_CNT(USBx,bEpChNum, wCount) \ + do { \ + /* Reset old TX_Count value */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->TXBD &= USB_PMA_TXBD_COUNTMSK; \ + \ + /* Set the wCount in the dedicated EP_TXBuffer */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->TXBD |= (uint32_t)((uint32_t)(wCount) << 16U); \ + } while(0) + +#define USB_DRD_SET_CHEP_RX_DBUF0_CNT(USBx, bEpChNum, wCount) \ + USB_DRD_SET_CHEP_CNT_RX_REG(((USB_DRD_PMA_BUFF + (bEpChNum))->TXBD), (wCount)) + +#define USB_DRD_SET_CHEP_RX_CNT(USBx, bEpChNum, wCount) \ + USB_DRD_SET_CHEP_CNT_RX_REG(((USB_DRD_PMA_BUFF + (bEpChNum))->RXBD), (wCount)) + +/** + * @brief gets counter of the tx buffer. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval Counter value + */ +#define USB_DRD_GET_CHEP_TX_CNT(USBx, bEpChNum) (((USB_DRD_PMA_BUFF + (bEpChNum))->TXBD & 0x03FF0000U) >> 16U) +#define USB_DRD_GET_CHEP_RX_CNT(USBx, bEpChNum) (((USB_DRD_PMA_BUFF + (bEpChNum))->RXBD & 0x03FF0000U) >> 16U) + +#define USB_DRD_GET_EP_TX_CNT USB_GET_CHEP_TX_CNT +#define USB_DRD_GET_CH_TX_CNT USB_GET_CHEP_TX_CNT + +#define USB_DRD_GET_EP_RX_CNT USB_DRD_GET_CHEP_RX_CNT +#define USB_DRD_GET_CH_RX_CNT USB_DRD_GET_CHEP_RX_CNT +/** + * @brief Sets buffer 0/1 address in a double buffer endpoint. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param wBuf0Addr buffer 0 address. + * @retval Counter value + */ +#define USB_DRD_SET_CHEP_DBUF0_ADDR(USBx, bEpChNum, wBuf0Addr) \ + USB_DRD_SET_CHEP_TX_ADDRESS((USBx), (bEpChNum), (wBuf0Addr)) + +#define USB_DRD_SET_CHEP_DBUF1_ADDR(USBx, bEpChNum, wBuf1Addr) \ + USB_DRD_SET_CHEP_RX_ADDRESS((USBx), (bEpChNum), (wBuf1Addr)) + + +/** + * @brief Sets addresses in a double buffer endpoint. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param wBuf0Addr: buffer 0 address. + * @param wBuf1Addr = buffer 1 address. + * @retval None + */ +#define USB_DRD_SET_CHEP_DBUF_ADDR(USBx, bEpChNum, wBuf0Addr, wBuf1Addr) \ + do { \ + USB_DRD_SET_CHEP_DBUF0_ADDR((USBx), (bEpChNum), (wBuf0Addr)); \ + USB_DRD_SET_CHEP_DBUF1_ADDR((USBx), (bEpChNum), (wBuf1Addr)); \ + } while(0) /* USB_DRD_SET_CHEP_DBUF_ADDR */ + + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @param bDir endpoint dir EP_DBUF_OUT = OUT + * EP_DBUF_IN = IN + * @param wCount: Counter value + * @retval None + */ +#define USB_DRD_SET_CHEP_DBUF0_CNT(USBx, bEpChNum, bDir, wCount) \ + do { \ + if ((bDir) == 0U) \ + { \ + /* OUT endpoint */ \ + USB_DRD_SET_CHEP_RX_DBUF0_CNT((USBx), (bEpChNum), (wCount)); \ + } \ + else \ + { \ + if ((bDir) == 1U) \ + { \ + /* IN endpoint */ \ + USB_DRD_SET_CHEP_TX_CNT((USBx), (bEpChNum), (wCount)); \ + } \ + } \ + } while(0) /* USB_DRD_SET_CHEP_DBUF0_CNT */ + +#define USB_DRD_SET_CHEP_DBUF1_CNT(USBx, bEpChNum, bDir, wCount) \ + do { \ + if ((bDir) == 0U) \ + { \ + /* OUT endpoint */ \ + USB_DRD_SET_CHEP_RX_CNT((USBx), (bEpChNum), (wCount)); \ + } \ + else \ + { \ + if ((bDir) == 1U) \ + { \ + /* IN endpoint */ \ + (USB_DRD_PMA_BUFF + (bEpChNum))->RXBD &= USB_PMA_TXBD_COUNTMSK; \ + (USB_DRD_PMA_BUFF + (bEpChNum))->RXBD |= (uint32_t)((uint32_t)(wCount) << 16U); \ + } \ + } \ + } while(0) /* USB_DRD_SET_CHEP_DBUF1_CNT */ + +#define USB_DRD_SET_CHEP_DBUF_CNT(USBx, bEpChNum, bDir, wCount) \ + do { \ + USB_DRD_SET_CHEP_DBUF0_CNT((USBx), (bEpChNum), (bDir), (wCount)); \ + USB_DRD_SET_CHEP_DBUF1_CNT((USBx), (bEpChNum), (bDir), (wCount)); \ + } while(0) /* USB_DRD_SET_EPCH_DBUF_CNT */ + +/** + * @brief Gets buffer 0/1 rx/tx counter for double buffering. + * @param USBx USB peripheral instance register address. + * @param bEpChNum Endpoint Number. + * @retval None + */ +#define USB_DRD_GET_CHEP_DBUF0_CNT(USBx, bEpChNum) (USB_DRD_GET_CHEP_TX_CNT((USBx), (bEpChNum))) +#define USB_DRD_GET_CHEP_DBUF1_CNT(USBx, bEpChNum) (USB_DRD_GET_CHEP_RX_CNT((USBx), (bEpChNum))) + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup USB_LL_Exported_Functions USB Low Layer Exported Functions + * @{ + */ + + +HAL_StatusTypeDef USB_CoreInit(USB_DRD_TypeDef *USBx, USB_DRD_CfgTypeDef cfg); +HAL_StatusTypeDef USB_DevInit(USB_DRD_TypeDef *USBx, USB_DRD_CfgTypeDef cfg); +HAL_StatusTypeDef USB_EnableGlobalInt(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_DisableGlobalInt(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_SetCurrentMode(USB_DRD_TypeDef *USBx, USB_DRD_ModeTypeDef mode); + +HAL_StatusTypeDef USB_FlushRxFifo(USB_DRD_TypeDef const *USBx); +HAL_StatusTypeDef USB_FlushTxFifo(USB_DRD_TypeDef const *USBx, uint32_t num); + +#if defined (HAL_PCD_MODULE_ENABLED) +HAL_StatusTypeDef USB_ActivateEndpoint(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep); +HAL_StatusTypeDef USB_DeactivateEndpoint(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPStartXfer(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPSetStall(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPClearStall(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPStopXfer(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep); +#endif /* defined (HAL_PCD_MODULE_ENABLED) */ + +HAL_StatusTypeDef USB_SetDevAddress(USB_DRD_TypeDef *USBx, uint8_t address); +HAL_StatusTypeDef USB_DevConnect(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_DevDisconnect(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_StopDevice(USB_DRD_TypeDef *USBx); +uint32_t USB_ReadInterrupts(USB_DRD_TypeDef const *USBx); + +HAL_StatusTypeDef USB_ResetPort(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_HostInit(USB_DRD_TypeDef *USBx, USB_DRD_CfgTypeDef cfg); +HAL_StatusTypeDef USB_HC_IN_Halt(USB_DRD_TypeDef *USBx, uint8_t phy_ch); +HAL_StatusTypeDef USB_HC_OUT_Halt(USB_DRD_TypeDef *USBx, uint8_t phy_ch); +HAL_StatusTypeDef USB_HC_StartXfer(USB_DRD_TypeDef *USBx, USB_DRD_HCTypeDef *hc); + +uint32_t USB_GetHostSpeed(USB_DRD_TypeDef const *USBx); +uint32_t USB_GetCurrentFrame(USB_DRD_TypeDef const *USBx); +HAL_StatusTypeDef USB_StopHost(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_HC_DoubleBuffer(USB_DRD_TypeDef *USBx, uint8_t phy_ch_num, uint8_t db_state); +HAL_StatusTypeDef USB_HC_Init(USB_DRD_TypeDef *USBx, uint8_t phy_ch_num, uint8_t epnum, + uint8_t dev_address, uint8_t speed, uint8_t ep_type, uint16_t mps); + +HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_DRD_TypeDef *USBx); +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_DRD_TypeDef *USBx); + +void USB_WritePMA(USB_DRD_TypeDef const *USBx, uint8_t *pbUsrBuf, + uint16_t wPMABufAddr, uint16_t wNBytes); + +void USB_ReadPMA(USB_DRD_TypeDef const *USBx, uint8_t *pbUsrBuf, + uint16_t wPMABufAddr, uint16_t wNBytes); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +#endif /* STM32C0xx_LL_USB_H */ diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_utils.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_utils.h index 8484d31f3..60a4839b1 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_utils.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_utils.h @@ -84,55 +84,40 @@ extern "C" { * @} */ /* Exported types ------------------------------------------------------------*/ -/** @defgroup UTILS_LL_ES_INIT UTILS Exported structures - * @{ - */ - -/** - * @brief UTILS System, AHB and APB buses clock configuration structure definition - */ -typedef struct -{ - uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). - This parameter can be a value of @ref RCC_HCLK_Clock_Source - - This feature can be modified afterwards using unitary function - @ref LL_RCC_SetAHBPrescaler(). */ - - uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). - This parameter can be a value of @ref RCC_LL_EC_APB1_DIV - - This feature can be modified afterwards using unitary function - @ref LL_RCC_SetAPB1Prescaler(). */ -} LL_UTILS_ClkInitTypeDef; - -/** - * @} - */ - /* Exported constants --------------------------------------------------------*/ /** @defgroup UTILS_LL_Exported_Constants UTILS Exported Constants * @{ */ -/** @defgroup UTILS_EC_HSE_BYPASS HSE Bypass activation - * @{ - */ -#define LL_UTILS_HSEBYPASS_OFF 0x00000000U /*!< HSE Bypass is not enabled */ -#define LL_UTILS_HSEBYPASS_ON 0x00000001U /*!< HSE Bypass is enabled */ -/** - * @} - */ - /** @defgroup UTILS_EC_PACKAGETYPE PACKAGE TYPE * @{ */ -#define LL_UTILS_PACKAGETYPE_QFN28_GP 0x00000000U /*!< UFQFPN28 general purpose (GP) package type */ -#define LL_UTILS_PACKAGETYPE_QFN28_PD 0x00000001U /*!< UFQFPN28 Power Delivery (PD) */ -#define LL_UTILS_PACKAGETYPE_QFN32_GP 0x00000004U /*!< UFQFPN32 / LQFP32 general purpose (GP) package type */ -#define LL_UTILS_PACKAGETYPE_QFN32_PD 0x00000005U /*!< UFQFPN32 / LQFP32 Power Delivery (PD) package type */ -#define LL_UTILS_PACKAGETYPE_QFN48 0x00000008U /*!< UFQFPN48 / LQFP488 package type */ -#define LL_UTILS_PACKAGETYPE_QFP48 0x0000000CU /*!< LQPF48 package type */ +#if defined(STM32C011xx) +#define LL_UTILS_PACKAGETYPE_SO8 0x0001U /*!< SO8 package type */ +#define LL_UTILS_PACKAGETYPE_WLCSP12 0x0002U /*!< WLCSP12 package type */ +#define LL_UTILS_PACKAGETYPE_UFQFPN20 0x0003U /*!< UFQFPN20 package type */ +#define LL_UTILS_PACKAGETYPE_TSSOP20 0x0004U /*!< TSSOP20 package type */ +#elif defined(STM32C031xx) +#define LL_UTILS_PACKAGETYPE_TSSOP20 0x0002U /*!< TSSOP20 package type */ +#define LL_UTILS_PACKAGETYPE_UFQFPN28 0x0003U /*!< UFQFPN28 package type */ +#define LL_UTILS_PACKAGETYPE_QFN32 0x0004U /*!< UFQFPN32 / LQFP32 package type */ +#define LL_UTILS_PACKAGETYPE_QFN48 0x0005U /*!< UFQFPN48 / LQFP48 package type */ +#elif defined(STM32C071xx) +#define LL_UTILS_PACKAGETYPE_WLCSP19_GP 0x0001U /*!< WLCSP19 (GP) package type */ +#define LL_UTILS_PACKAGETYPE_WLCSP19_N 0x0002U /*!< WLCSP19 (N) package type */ +#define LL_UTILS_PACKAGETYPE_TSSOP20_GP 0x0003U /*!< TSSOP20 (GP) package type */ +#define LL_UTILS_PACKAGETYPE_TSSOP20_N 0x0004U /*!< TSSOP20 (N) package type */ +#define LL_UTILS_PACKAGETYPE_UFQFPN28_GP 0x0005U /*!< UFQFPN28 (GP) package type */ +#define LL_UTILS_PACKAGETYPE_UFQFPN28_N 0x0006U /*!< UFQFPN28 (GP) package type */ +#define LL_UTILS_PACKAGETYPE_QFN32_GP 0x0007U /*!< UFQFPN32 / LQFP32 general purpose (GP) package type */ +#define LL_UTILS_PACKAGETYPE_QFN32_N 0x0008U /*!< UFQFPN32 / LQFP32 general purpose (N) package type */ +#define LL_UTILS_PACKAGETYPE_QFN48_GP 0x0009U /*!< UFQFPN48 / LQFP48 general purpose (GP) package type */ +#define LL_UTILS_PACKAGETYPE_QFN48_N 0x000AU /*!< UFQFPN32 / LQFP48 general purpose (N) package type */ +#define LL_UTILS_PACKAGETYPE_LQFP64_GP 0x000BU /*!< UFQFPN64 / LQFP64 general purpose (GP) package type */ +#define LL_UTILS_PACKAGETYPE_LQFP64_N 0x0008U /*!< UFQFPN64 / LQFP64 general purpose (N) package type */ +#define LL_UTILS_PACKAGETYPE_UFBGA64_GP 0x000DU /*!< UFBGA64 (GP) package type */ +#define LL_UTILS_PACKAGETYPE_UFBGA64_N 0x000EU /*!< UFBGA64 (N) package type */ +#endif /* STM32C0xx */ /** * @} */ @@ -193,12 +178,20 @@ __STATIC_INLINE uint32_t LL_GetFlashSize(void) /** * @brief Get Package type * @retval Returned value can be one of the following values: - * @arg @ref LL_UTILS_PACKAGETYPE_QFN28_GP - * @arg @ref LL_UTILS_PACKAGETYPE_QFN28_PD - * @arg @ref LL_UTILS_PACKAGETYPE_QFN32_GP - * @arg @ref LL_UTILS_PACKAGETYPE_QFN32_PD - * @arg @ref LL_UTILS_PACKAGETYPE_QFN48 - * @arg @ref LL_UTILS_PACKAGETYPE_QFP48 + * @arg @ref LL_UTILS_PACKAGETYPE_SO8 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_WLCSP12 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_UFQFPN20 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_TSSOP20 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_UFQFPN28 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_QFN32 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_QFN48 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_WLCSP19 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_WLCSP15 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_UFBGA64 (*) + * @arg @ref LL_UTILS_PACKAGETYPE_LQFP64 (*) + * + * @note (*) Availability depends on devices. + * */ __STATIC_INLINE uint32_t LL_GetPackageType(void) { diff --git a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_wwdg.h b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_wwdg.h index f23c34fb0..f76746731 100644 --- a/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_wwdg.h +++ b/stm32cube/stm32c0xx/drivers/include/stm32c0xx_ll_wwdg.h @@ -135,7 +135,7 @@ __STATIC_INLINE void LL_WWDG_Enable(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->CR, WWDG_CR_WDGA) == (WWDG_CR_WDGA)) ? 1UL : 0UL); } @@ -162,7 +162,7 @@ __STATIC_INLINE void LL_WWDG_SetCounter(WWDG_TypeDef *WWDGx, uint32_t Counter) * @param WWDGx WWDG Instance * @retval 7 bit Watchdog Counter value */ -__STATIC_INLINE uint32_t LL_WWDG_GetCounter(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetCounter(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CR, WWDG_CR_T)); } @@ -203,7 +203,7 @@ __STATIC_INLINE void LL_WWDG_SetPrescaler(WWDG_TypeDef *WWDGx, uint32_t Prescale * @arg @ref LL_WWDG_PRESCALER_64 * @arg @ref LL_WWDG_PRESCALER_128 */ -__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CFR, WWDG_CFR_WDGTB)); } @@ -235,7 +235,7 @@ __STATIC_INLINE void LL_WWDG_SetWindow(WWDG_TypeDef *WWDGx, uint32_t Window) * @param WWDGx WWDG Instance * @retval 7 bit Watchdog Window value */ -__STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetWindow(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CFR, WWDG_CFR_W)); } @@ -256,7 +256,7 @@ __STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->SR, WWDG_SR_EWIF) == (WWDG_SR_EWIF)) ? 1UL : 0UL); } @@ -298,7 +298,7 @@ __STATIC_INLINE void LL_WWDG_EnableIT_EWKUP(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->CFR, WWDG_CFR_EWI) == (WWDG_CFR_EWI)) ? 1UL : 0UL); } @@ -326,4 +326,3 @@ __STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(WWDG_TypeDef *WWDGx) #endif #endif /* STM32C0xx_LL_WWDG_H */ - diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal.c index bfa2d7d56..d25d2e418 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal.c @@ -56,7 +56,7 @@ * @brief STM32C0xx HAL Driver version number */ #define __STM32C0xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ -#define __STM32C0xx_HAL_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */ +#define __STM32C0xx_HAL_VERSION_SUB1 (0x02U) /*!< [23:16] sub1 version */ #define __STM32C0xx_HAL_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */ #define __STM32C0xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32C0xx_HAL_VERSION ((__STM32C0xx_HAL_VERSION_MAIN << 24U)\ @@ -176,11 +176,11 @@ HAL_StatusTypeDef HAL_Init(void) HAL_StatusTypeDef HAL_DeInit(void) { /* Reset of all peripherals */ - __HAL_RCC_APB1_FORCE_RESET(); - __HAL_RCC_APB1_RELEASE_RESET(); + __HAL_RCC_APB1_GRP1_FORCE_RESET(); + __HAL_RCC_APB1_GRP1_RELEASE_RESET(); - __HAL_RCC_APB2_FORCE_RESET(); - __HAL_RCC_APB2_RELEASE_RESET(); + __HAL_RCC_APB1_GRP2_FORCE_RESET(); + __HAL_RCC_APB1_GRP2_RELEASE_RESET(); __HAL_RCC_AHB_FORCE_RESET(); __HAL_RCC_AHB_RELEASE_RESET(); @@ -540,30 +540,9 @@ void HAL_DBGMCU_DisableDBGStandbyMode(void) =============================================================================== [..] This section provides functions allowing to: (+) Enable/Disable Pin remap - (+) Enable/Disable the I/O analog switch voltage booster @endverbatim * @{ */ - - -/** - * @brief Enable the I/O analog switch voltage booster - * @retval None - */ -void HAL_SYSCFG_EnableIOAnalogSwitchBooster(void) -{ - SET_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_BOOSTEN); -} - -/** - * @brief Disable the I/O analog switch voltage booster - * @retval None - */ -void HAL_SYSCFG_DisableIOAnalogSwitchBooster(void) -{ - CLEAR_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_BOOSTEN); -} - /** * @brief Enable the remap on PA11_PA12 * @param PinRemap specifies which pins have to be remapped diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc.c index 142cceee9..ca18c3c21 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc.c @@ -445,6 +445,9 @@ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc) hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback; /* Legacy weak callback */ hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback; /* Legacy weak callback */ hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback; /* Legacy weak callback */ + hadc->CalibrationCpltCallback = HAL_ADC_CalibrationCpltCallback; /* Legacy weak callback */ + hadc->ADCReadyCallback = HAL_ADC_ADCReadyCallback; /* Legacy weak callback */ + hadc->ChannelConfigReadyCallback = HAL_ADCEx_ChannelConfigReadyCallback; /* Legacy weak callback */ if (hadc->MspInitCallback == NULL) { @@ -670,11 +673,15 @@ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc) /* - Set sequencer scan length by clearing ranks above maximum rank */ /* and do not modify other ranks value. */ MODIFY_REG(hadc->Instance->CHSELR, - ADC_CHSELR_SQ_ALL, - (ADC_CHSELR_SQ2_TO_SQ8 << (((hadc->Init.NbrOfConversion - 1UL) * ADC_REGULAR_RANK_2) & 0x1FUL)) | (hadc->ADCGroupRegularSequencerRanks) + ADC_CHSELR_SQ_ALL, + (ADC_CHSELR_SQ2_TO_SQ8 << (((hadc->Init.NbrOfConversion - 1UL) * ADC_REGULAR_RANK_2) & 0x1FUL)) + | (hadc->ADCGroupRegularSequencerRanks) ); } - + else + { + /* Nothing to do */ + } /* Check back that ADC registers have effectively been configured to */ /* ensure of no potential problem of ADC core peripheral clocking. */ if (LL_ADC_GetSamplingTimeCommonChannels(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_1) @@ -780,13 +787,13 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD3 | ADC_IT_AWD2 | ADC_IT_AWD1 | ADC_IT_OVR | ADC_IT_EOS | ADC_IT_EOC | - ADC_IT_EOSMP | ADC_IT_RDY)); + ADC_IT_EOCAL | ADC_IT_EOSMP | ADC_IT_RDY)); /* Reset register ISR */ __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD3 | ADC_FLAG_AWD2 | ADC_FLAG_AWD1 | ADC_FLAG_OVR | ADC_FLAG_EOS | ADC_FLAG_EOC | - ADC_FLAG_EOSMP | ADC_FLAG_RDY)); + ADC_FLAG_EOCAL | ADC_FLAG_EOSMP | ADC_FLAG_RDY)); /* Reset register CR */ /* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode */ @@ -1386,9 +1393,12 @@ HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Ti * @param EventType the ADC event type. * This parameter can be one of the following values: * @arg @ref ADC_EOSMP_EVENT ADC End of Sampling event - * @arg @ref ADC_AWD1_EVENT ADC Analog watchdog 1 event (main analog watchdog, present on all STM32 devices) - * @arg @ref ADC_AWD2_EVENT ADC Analog watchdog 2 event (additional analog watchdog, not present on all STM32 families) - * @arg @ref ADC_AWD3_EVENT ADC Analog watchdog 3 event (additional analog watchdog, not present on all STM32 families) + * @arg @ref ADC_AWD1_EVENT ADC Analog watchdog 1 event (main analog watchdog, present on + * all STM32 devices) + * @arg @ref ADC_AWD2_EVENT ADC Analog watchdog 2 event (additional analog watchdog, not present on + * all STM32 families) + * @arg @ref ADC_AWD3_EVENT ADC Analog watchdog 3 event (additional analog watchdog, not present on + * all STM32 families) * @arg @ref ADC_OVR_EVENT ADC Overrun event * @param Timeout Timeout value in millisecond. * @note The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR. @@ -2062,11 +2072,50 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); } + /* ========== Check ADC Ready flag ========== */ + if (((tmp_isr & ADC_FLAG_RDY) == ADC_FLAG_RDY) && ((tmp_ier & ADC_IT_RDY) == ADC_IT_RDY)) + { + /* Update state machine on end of sampling status if not in error state */ + if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL) + { + /* Set ADC state */ + SET_BIT(hadc->State, HAL_ADC_STATE_READY); + } + + /* ADC Ready callback */ +#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ADCReadyCallback(hadc); +#else + HAL_ADC_ADCReadyCallback(hadc); +#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */ + + /* Leave ADRDY flag up (used by HAL), disable interrupt source instead */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_RDY); + } + + /* ========== Check End of Calibration flag ========== */ + if (((tmp_isr & ADC_FLAG_EOCAL) == ADC_FLAG_EOCAL) && ((tmp_ier & ADC_IT_EOCAL) == ADC_IT_EOCAL)) + { + /* End Of Calibration callback */ +#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1) + hadc->CalibrationCpltCallback(hadc); +#else + HAL_ADC_CalibrationCpltCallback(hadc); +#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */ + + /* Clear end of calibration flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOCAL); + } + /* ========== Check channel configuration ready flag ========== */ if (((tmp_isr & ADC_FLAG_CCRDY) == ADC_FLAG_CCRDY) && ((tmp_ier & ADC_IT_CCRDY) == ADC_IT_CCRDY)) { - /* Level out of window 1 callback */ + /* Channel configuration ready callback */ +#if (USE_HAL_ADC_REGISTER_CALLBACKS == 1) + hadc->ChannelConfigReadyCallback(hadc); +#else HAL_ADCEx_ChannelConfigReadyCallback(hadc); +#endif /* USE_HAL_ADC_REGISTER_CALLBACKS */ /* Clear ADC analog watchdog flag */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_CCRDY); @@ -2140,6 +2189,36 @@ __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc) */ } +/** + * @brief Calibration complete callback in non-blocking mode. + * @param hadc ADC handle + * @retval None + */ +__weak void HAL_ADC_CalibrationCpltCallback(ADC_HandleTypeDef *hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_CalibrationCpltCallback must be implemented in the user file. + */ +} + +/** + * @brief ADC Ready callback in non-blocking mode. + * @param hadc ADC handle + * @retval None + */ +__weak void HAL_ADC_ADCReadyCallback(ADC_HandleTypeDef *hadc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_ADCReadyCallback must be implemented in the user file. + */ +} + /** * @} */ @@ -2428,14 +2507,14 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG { backup_setting_adc_enable_state = 1UL; tmp_hal_status = ADC_Disable(hadc); - + /* Check if ADC is effectively disabled */ if (tmp_hal_status == HAL_OK) { - /* Set ADC state */ - ADC_STATE_CLR_SET(hadc->State, - HAL_ADC_STATE_REG_BUSY, - HAL_ADC_STATE_READY); + /* Set ADC state */ + ADC_STATE_CLR_SET(hadc->State, + HAL_ADC_STATE_REG_BUSY, + HAL_ADC_STATE_READY); } } @@ -2446,7 +2525,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG { case ADC_ANALOGWATCHDOG_SINGLE_REG: LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, - __LL_ADC_ANALOGWD_CHANNEL_GROUP(AnalogWDGConfig->Channel, LL_ADC_GROUP_REGULAR)); + __LL_ADC_ANALOGWD_CHANNEL_GROUP(AnalogWDGConfig->Channel, + LL_ADC_GROUP_REGULAR)); break; case ADC_ANALOGWATCHDOG_ALL_REG: @@ -2735,14 +2815,16 @@ HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc) /* Enable the ADC peripheral */ LL_ADC_Enable(hadc->Instance); - if ((LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) & LL_ADC_PATH_INTERNAL_TEMPSENSOR) != 0UL) + if ((LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) & LL_ADC_PATH_INTERNAL_TEMPSENSOR) + != 0UL) { /* Delay for temperature sensor buffer stabilization time */ /* Wait loop initialization and execution */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ - wait_loop_index = (((LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))) + 1UL); + wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US / 10UL) + * ((SystemCoreClock / (100000UL * 2UL)) + 1UL)); while (wait_loop_index != 0UL) { wait_loop_index--; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc_ex.c index 13683cd28..018a4072e 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_adc_ex.c @@ -175,19 +175,19 @@ HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef *hadc) LL_ADC_Enable(hadc->Instance); /* Case of ADC clocked at low frequency: Delay required between ADC enable and disable actions */ - if(LL_ADC_GetClock(hadc->Instance) == LL_ADC_CLOCK_ASYNC) + if (LL_ADC_GetClock(hadc->Instance) == LL_ADC_CLOCK_ASYNC) { adc_clk_async_presc = LL_ADC_GetCommonClock(__LL_ADC_COMMON_INSTANCE(hadc->Instance)); - if(adc_clk_async_presc >= LL_ADC_CLOCK_ASYNC_DIV16) + if (adc_clk_async_presc >= LL_ADC_CLOCK_ASYNC_DIV16) { /* Delay loop initialization and execution */ /* Delay depends on ADC clock prescaler: Compute ADC clock asynchronous prescaler to decimal format */ - delay_cpu_cycles = (1U << ((adc_clk_async_presc >> ADC_CCR_PRESC_Pos) - 3U)); + delay_cpu_cycles = (1UL << ((adc_clk_async_presc >> ADC_CCR_PRESC_Pos) - 3UL)); /* Divide variable by 2 to compensate partially CPU processing cycles */ - delay_cpu_cycles >>= 1U; + delay_cpu_cycles >>= 1UL; - while(delay_cpu_cycles != 0) + while (delay_cpu_cycles != 0UL) { delay_cpu_cycles--; } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_cortex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_cortex.c index 093366716..f8de58f91 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_cortex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_cortex.c @@ -344,7 +344,6 @@ void HAL_MPU_Enable(uint32_t MPU_Control) __ISB(); } - /** * @brief Disable the MPU. * @retval None @@ -358,6 +357,37 @@ void HAL_MPU_Disable(void) MPU->CTRL = 0; } +/** + * @brief Enable the MPU Region. + * @retval None + */ +void HAL_MPU_EnableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Enable the Region */ + SET_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @brief Disable the MPU Region. + * @retval None + */ +void HAL_MPU_DisableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} /** * @brief Initialize and configure the Region and the memory to be protected. @@ -370,38 +400,32 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); + assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); + assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); + assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); + assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); + assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); + assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); + assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); + assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; - if ((MPU_Init->Enable) != 0U) - { - /* Check the parameters */ - assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); - assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); - assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); - assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); - assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); - assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); - assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); - assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); - - MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | - ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | - ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | - ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | - ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | - ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | - ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | - ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | - ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); - } - else - { - MPU->RBAR = 0x00U; - MPU->RASR = 0x00U; - } + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); + + /* Apply configuration */ + MPU->RBAR = MPU_Init->BaseAddress; + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | + ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | + ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | + ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | + ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | + ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | + ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } #endif /* __MPU_PRESENT */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc.c index 716a0eb60..a7adc216a 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc.c @@ -200,7 +200,7 @@ HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) __HAL_CRC_DR_RESET(hcrc); /* Reset IDR register content */ - CLEAR_BIT(hcrc->Instance->IDR, CRC_IDR_IDR); + CLEAR_REG(hcrc->Instance->IDR); /* DeInit the low level hardware */ HAL_CRC_MspDeInit(hcrc); @@ -403,7 +403,7 @@ uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t * @param hcrc CRC handle * @retval HAL state */ -HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc) +HAL_CRC_StateTypeDef HAL_CRC_GetState(const CRC_HandleTypeDef *hcrc) { /* Return CRC handle state */ return hcrc->State; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc_ex.c index c8c8f7011..af566b9c1 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_crc_ex.c @@ -210,8 +210,6 @@ HAL_StatusTypeDef HAL_CRCEx_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_ } - - /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma.c index 17731b491..28f886967 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma.c @@ -169,7 +169,6 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) /* calculation of the channel index */ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - \ (uint32_t)DMA1_Channel1)) << 2U; - /* Change DMA peripheral state */ hdma->State = HAL_DMA_STATE_BUSY; @@ -201,7 +200,7 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) /* Clear the DMAMUX synchro overrun flag */ hdma->DMAmuxChannelStatus->CFR = hdma->DMAmuxChannelStatusMask; - if (((hdma->Init.Request > 0UL) && (hdma->Init.Request <= DMA_REQUEST_GENERATOR3))) + if (((hdma->Init.Request > 0UL) && (hdma->Init.Request <= DMA_REQUEST_GENERATOR3))) { /* Initialize parameters for DMAMUX request generator : DMAmuxRequestGen, DMAmuxRequestGenStatus and DMAmuxRequestGenStatusMask @@ -922,8 +921,6 @@ HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_Ca * @} */ - - /** @defgroup DMA_Exported_Functions_Group3 Peripheral State and Errors functions * @brief Peripheral State and Errors functions * diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma_ex.c index 1df7b617e..de921d159 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_dma_ex.c @@ -95,9 +95,7 @@ HAL_StatusTypeDef HAL_DMAEx_ConfigMuxSync(DMA_HandleTypeDef *hdma, HAL_DMA_MuxSy { /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); - assert_param(IS_DMAMUX_SYNC_SIGNAL_ID(pSyncConfig->SyncSignalID)); - assert_param(IS_DMAMUX_SYNC_POLARITY(pSyncConfig-> SyncPolarity)); assert_param(IS_DMAMUX_SYNC_STATE(pSyncConfig->SyncEnable)); assert_param(IS_DMAMUX_SYNC_EVENT(pSyncConfig->EventEnable)); @@ -190,7 +188,6 @@ HAL_StatusTypeDef HAL_DMAEx_EnableMuxRequestGenerator(DMA_HandleTypeDef *hdma) */ if ((hdma->State != HAL_DMA_STATE_RESET) && (hdma->DMAmuxRequestGen != 0)) { - /* Enable the request generator*/ hdma->DMAmuxRequestGen->RGCR |= DMAMUX_RGxCR_GE; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_exti.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_exti.c index 96f857e3d..e8b7dee5c 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_exti.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_exti.c @@ -248,7 +248,6 @@ HAL_StatusTypeDef HAL_EXTI_SetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigT return HAL_OK; } - /** * @brief Get configuration of a dedicated Exti line. * @param hexti Exti handle. @@ -257,7 +256,7 @@ HAL_StatusTypeDef HAL_EXTI_SetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigT */ HAL_StatusTypeDef HAL_EXTI_GetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) { - __IO uint32_t *regaddr; + const __IO uint32_t *regaddr; uint32_t regval; uint32_t linepos; uint32_t maskline; @@ -343,7 +342,6 @@ HAL_StatusTypeDef HAL_EXTI_GetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigT return HAL_OK; } - /** * @brief Clear whole configuration of a dedicated Exti line. * @param hexti Exti handle. @@ -406,7 +404,6 @@ HAL_StatusTypeDef HAL_EXTI_ClearConfigLine(const EXTI_HandleTypeDef *hexti) return HAL_OK; } - /** * @brief Register callback for a dedicaated Exti line. * @param hexti Exti handle. @@ -443,7 +440,6 @@ HAL_StatusTypeDef HAL_EXTI_RegisterCallback(EXTI_HandleTypeDef *hexti, EXTI_Call return status; } - /** * @brief Store line number as handle private field. * @param hexti Exti handle. @@ -470,7 +466,6 @@ HAL_StatusTypeDef HAL_EXTI_GetHandle(EXTI_HandleTypeDef *hexti, uint32_t ExtiLin } } - /** * @} */ @@ -548,7 +543,7 @@ void HAL_EXTI_IRQHandler(const EXTI_HandleTypeDef *hexti) */ uint32_t HAL_EXTI_GetPending(const EXTI_HandleTypeDef *hexti, uint32_t Edge) { - __IO uint32_t *regaddr; + const __IO uint32_t *regaddr; uint32_t regval; uint32_t linepos; uint32_t maskline; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_flash_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_flash_ex.c index 1923fbd96..47877a557 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_flash_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_flash_ex.c @@ -136,7 +136,7 @@ static void FLASH_OB_GetSecMem(uint32_t *BootEntry, uint32_t *SecSize * the pages have been correctly erased) * @retval HAL Status */ -HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError) +HAL_StatusTypeDef HAL_FLASHEx_Erase(const FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError) { HAL_StatusTypeDef status; uint32_t index; @@ -566,26 +566,30 @@ static void FLASH_OB_WRPConfig(uint32_t WRPArea, uint32_t WRPStartOffset, uint32 * This parameter can be a combination of @ref FLASH_OB_USER_Type * @param UserConfig The FLASH User Option Bytes values. * This parameter can be a combination of: - * @arg @ref FLASH_OB_USER_BOR_ENABLE, - * @arg @ref FLASH_OB_USER_BOR_LEVEL, - * @arg @ref FLASH_OB_USER_nRST_STOP, - * @arg @ref FLASH_OB_USER_nRST_STANDBY, - * @arg @ref FLASH_OB_USER_nRST_SHUTDOWN, - * @arg @ref FLASH_OB_USER_IWDG_SW, - * @arg @ref FLASH_OB_USER_IWDG_STOP, - * @arg @ref FLASH_OB_USER_IWDG_STANDBY, - * @arg @ref FLASH_OB_USER_WWDG_SW, - * @arg @ref FLASH_OB_USER_SRAM_PARITY, - * @arg @ref FLASH_OB_USER_nBOOT_SEL, - * @arg @ref FLASH_OB_USER_nBOOT1, - * @arg @ref FLASH_OB_USER_nBOOT0, - * @arg @ref FLASH_OB_USER_INPUT_RESET_HOLDER + * @arg @ref OB_USER_BOR_ENABLE, + * @arg @ref OB_USER_BOR_LEVEL, + * @arg @ref OB_USER_nRST_STOP, + * @arg @ref OB_USER_nRST_STANDBY, + * @arg @ref OB_USER_nRST_SHUTDOWN, + * @arg @ref OB_USER_IWDG_SW, + * @arg @ref OB_USER_IWDG_STOP, + * @arg @ref OB_USER_IWDG_STANDBY, + * @arg @ref OB_USER_WWDG_SW, + * @arg @ref OB_USER_SRAM_PARITY, + * @arg @ref OB_USER_nBOOT_SEL, + * @arg @ref OB_USER_nBOOT1, + * @arg @ref OB_USER_nBOOT0, + * @arg @ref OB_USER_INPUT_RESET_HOLDER + * @arg @ref OB_USER_SECURE_MUXING_EN + * @arg @ref OB_USER_HSE_NOT_REMAPPED (*) * @param RDPLevel specifies the read protection level. * This parameter can be one of the following values: * @arg @ref OB_RDP_LEVEL_0 No protection * @arg @ref OB_RDP_LEVEL_1 Memory Read protection * @arg @ref OB_RDP_LEVEL_2 Full chip protection * @retval None + * + * @note (*) available only on STM32C071xx devices. */ static void FLASH_OB_OptrConfig(uint32_t UserType, uint32_t UserConfig, uint32_t RDPLevel) { @@ -766,20 +770,24 @@ static uint32_t FLASH_OB_GetRDP(void) /** * @brief Return the FLASH User Option Byte value. * @retval The FLASH User Option Bytes values. It will be a combination of all the following values: - * @arg @ref FLASH_OB_USER_BOR_ENABLE, - * @ref FLASH_OB_USER_BOR_LEVEL, - * @ref FLASH_OB_USER_nRST_STOP, - * @ref FLASH_OB_USER_nRST_STANDBY, - * @ref FLASH_OB_USER_nRST_SHUTDOWN, - * @ref FLASH_OB_USER_IWDG_SW, - * @ref FLASH_OB_USER_IWDG_STOP, - * @ref FLASH_OB_USER_IWDG_STANDBY, - * @ref FLASH_OB_USER_WWDG_SW, - * @ref FLASH_OB_USER_SRAM_PARITY, - * @ref FLASH_OB_USER_nBOOT_SEL, - * @ref FLASH_OB_USER_nBOOT1, - * @ref FLASH_OB_USER_nBOOT0, - * @ref FLASH_OB_USER_INPUT_RESET_HOLDER + * @arg @ref OB_USER_BOR_ENABLE, + * @ref OB_USER_BOR_LEVEL, + * @ref OB_USER_nRST_STOP, + * @ref OB_USER_nRST_STANDBY, + * @ref OB_USER_nRST_SHUTDOWN, + * @ref OB_USER_IWDG_SW, + * @ref OB_USER_IWDG_STOP, + * @ref OB_USER_IWDG_STANDBY, + * @ref OB_USER_WWDG_SW, + * @ref OB_USER_SRAM_PARITY, + * @ref OB_USER_nBOOT_SEL, + * @ref OB_USER_nBOOT1, + * @ref OB_USER_nBOOT0, + * @ref OB_USER_INPUT_RESET_HOLDER + * @ref OB_USER_SECURE_MUXING_EN + * @ref OB_USER_HSE_NOT_REMAPPED (*) + * + * @note (*) available only on STM32C071xx devices. */ static uint32_t FLASH_OB_GetUser(void) { diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_gpio.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_gpio.c index 0ab7aada7..7529a0a21 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_gpio.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_gpio.c @@ -199,15 +199,15 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, const GPIO_InitTypeDef *pGPIO_Init) /* Configure Alternate function mapped with the current IO */ tmp = GPIOx->AFR[position >> 3U]; - tmp &= ~(0xFUL << ((position & 0x07U) * 4U)) ; - tmp |= ((pGPIO_Init->Alternate & 0x0FUL) << ((position & 0x07U) * 4U)); + tmp &= ~(0xFUL << ((position & 0x07U) * GPIO_AFRL_AFSEL1_Pos)) ; + tmp |= ((pGPIO_Init->Alternate & 0x0FUL) << ((position & 0x07U) * GPIO_AFRL_AFSEL1_Pos)); GPIOx->AFR[position >> 3U] = tmp; } /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ tmp = GPIOx->MODER; - tmp &= ~(GPIO_MODER_MODE0 << (position * 2U)); - tmp |= ((pGPIO_Init->Mode & GPIO_MODE) << (position * 2U)); + tmp &= ~(GPIO_MODER_MODE0 << (position * GPIO_MODER_MODE1_Pos)); + tmp |= ((pGPIO_Init->Mode & GPIO_MODE) << (position * GPIO_MODER_MODE1_Pos)); GPIOx->MODER = tmp; /* In case of Output or Alternate function mode selection */ @@ -219,8 +219,8 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, const GPIO_InitTypeDef *pGPIO_Init) /* Configure the IO Speed */ tmp = GPIOx->OSPEEDR; - tmp &= ~(GPIO_OSPEEDR_OSPEED0 << (position * 2U)); - tmp |= (pGPIO_Init->Speed << (position * 2U)); + tmp &= ~(GPIO_OSPEEDR_OSPEED0 << (position * GPIO_OSPEEDR_OSPEED1_Pos)); + tmp |= (pGPIO_Init->Speed << (position * GPIO_OSPEEDR_OSPEED1_Pos)); GPIOx->OSPEEDR = tmp; /* Configure the IO Output Type */ @@ -237,8 +237,8 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, const GPIO_InitTypeDef *pGPIO_Init) /* Activate the Pull-up or Pull down resistor for the current IO */ tmp = GPIOx->PUPDR; - tmp &= ~(GPIO_PUPDR_PUPD0 << (position * 2U)); - tmp |= ((pGPIO_Init->Pull) << (position * 2U)); + tmp &= ~(GPIO_PUPDR_PUPD0 << (position * GPIO_PUPDR_PUPD1_Pos)); + tmp |= ((pGPIO_Init->Pull) << (position * GPIO_PUPDR_PUPD1_Pos)); GPIOx->PUPDR = tmp; } @@ -247,8 +247,8 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, const GPIO_InitTypeDef *pGPIO_Init) if ((pGPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) { tmp = EXTI->EXTICR[position >> 2U]; - tmp &= ~((0x0FUL) << (8U * (position & 0x03U))); - tmp |= (GPIO_GET_INDEX(GPIOx) << (8U * (position & 0x03U))); + tmp &= ~((0x0FUL) << ((position & 0x03U) * EXTI_EXTICR1_EXTI1_Pos)); + tmp |= (GPIO_GET_INDEX(GPIOx) << ((position & 0x03U) * EXTI_EXTICR1_EXTI1_Pos)); EXTI->EXTICR[position >> 2U] = tmp; /* Clear EXTI line configuration */ @@ -319,8 +319,8 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) /*------------------------- EXTI Mode Configuration --------------------*/ /* Clear the External Interrupt or Event for the current IO */ tmp = EXTI->EXTICR[position >> 2U]; - tmp &= ((0x0FUL) << (8U * (position & 0x03U))); - if (tmp == (GPIO_GET_INDEX(GPIOx) << (8U * (position & 0x03U)))) + tmp &= ((0x0FUL) << ((position & 0x03U) * EXTI_EXTICR1_EXTI1_Pos)); + if (tmp == (GPIO_GET_INDEX(GPIOx) << ((position & 0x03U) * EXTI_EXTICR1_EXTI1_Pos))) { /* Clear EXTI line configuration */ EXTI->IMR1 &= ~(iocurrent); @@ -336,19 +336,19 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) /*------------------------- GPIO Mode Configuration --------------------*/ /* Configure IO in Analog Mode */ - GPIOx->MODER |= (GPIO_MODER_MODE0 << (position * 2U)); + GPIOx->MODER |= (GPIO_MODER_MODE0 << (position * GPIO_MODER_MODE1_Pos)); /* Configure the default Alternate Function in current IO */ - GPIOx->AFR[position >> 3U] &= ~(0x0FUL << ((position & 0x07U) * 4U)) ; + GPIOx->AFR[position >> 3U] &= ~(0x0FUL << ((position & 0x07U) * GPIO_AFRL_AFSEL1_Pos)) ; /* Configure the default value for IO Speed */ - GPIOx->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEED0 << (position * 2U)); + GPIOx->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEED0 << (position * GPIO_OSPEEDR_OSPEED1_Pos)); /* Configure the default value IO Output Type */ GPIOx->OTYPER &= ~(GPIO_OTYPER_OT0 << position); /* Deactivate the Pull-up and Pull-down resistor for the current IO */ - GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * 2U)); + GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * GPIO_PUPDR_PUPD1_Pos)); } position++; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_hcd.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_hcd.c new file mode 100644 index 000000000..8c392dbeb --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_hcd.c @@ -0,0 +1,2881 @@ +/** + ****************************************************************************** + * @file stm32c0xx_hal_hcd.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 the following macros + (+++) __HAL_RCC_USB_CLK_ENABLE(); + (##) 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 + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_hal.h" + +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +#ifdef HAL_HCD_MODULE_ENABLED +#if defined (USB_DRD_FS) + +/** @defgroup HCD HCD + * @brief HCD HAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function ----------------------------------------------------------*/ +/** @defgroup HCD_Private_Functions HCD Private Functions + * @{ + */ +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_Port_IRQHandler(HCD_HandleTypeDef *hhcd); +static void HAL_HCD_ClearPhyChannel(HCD_HandleTypeDef *hhcd); +static uint8_t HAL_HCD_GetLogical_Channel(HCD_HandleTypeDef const *hhcd, uint8_t phy_chnum, uint8_t dir); +static uint8_t HAL_HCD_Check_usedChannel(HCD_HandleTypeDef const *hhcd, uint8_t ch_num); +static uint8_t HAL_HCD_Get_FreePhyChannel(HCD_HandleTypeDef *hhcd, uint8_t ch_num, uint8_t epnum, uint8_t ep_type); + +#if (USE_USB_DOUBLE_BUFFER == 1U) +static void HCD_HC_IN_BulkDb(HCD_HandleTypeDef *hhcd, uint8_t ch_num, uint8_t phy_chnum, uint32_t regvalue); +static void HCD_HC_OUT_BulkDb(HCD_HandleTypeDef *hhcd, uint8_t ch_num, uint8_t phy_chnum, uint32_t regvalue); +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + +static uint16_t HAL_HCD_GetFreePMA(HCD_HandleTypeDef *hhcd, uint16_t mps); +static HAL_StatusTypeDef HAL_HCD_PMAFree(HCD_HandleTypeDef *hhcd, uint32_t pma_base, uint16_t mps); +static void inline HCD_HC_IN_ISO(HCD_HandleTypeDef *hhcd, uint8_t ch_num, uint8_t phy_chnum, uint32_t regvalue); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup HCD_Exported_Functions HCD Exported Functions + * @{ + */ + +/** @defgroup HCD_Exported_Functions_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 status + */ +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)); + + if (hhcd->State == HAL_HCD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhcd->Lock = HAL_UNLOCKED; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->SOFCallback = HAL_HCD_SOF_Callback; + hhcd->ConnectCallback = HAL_HCD_Connect_Callback; + hhcd->DisconnectCallback = HAL_HCD_Disconnect_Callback; + hhcd->PortEnabledCallback = HAL_HCD_PortEnabled_Callback; + hhcd->PortDisabledCallback = HAL_HCD_PortDisabled_Callback; + hhcd->HC_NotifyURBChangeCallback = HAL_HCD_HC_NotifyURBChange_Callback; + + if (hhcd->MspInitCallback == NULL) + { + hhcd->MspInitCallback = HAL_HCD_MspInit; + } + + /* Init the low level hardware */ + hhcd->MspInitCallback(hhcd); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_HCD_MspInit(hhcd); +#endif /* (USE_HAL_HCD_REGISTER_CALLBACKS) */ + } + hhcd->State = HAL_HCD_STATE_BUSY; + + /* Disable the Interrupts */ + (void)__HAL_HCD_DISABLE(hhcd); + + /* Dma not supported, force to zero */ + hhcd->Init.dma_enable = 0U; + + /* Init the Core (common init.) */ + (void)USB_CoreInit(hhcd->Instance, hhcd->Init); + + /* Force Host Mode */ + (void)USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE); + + /* Init Host */ + (void)USB_HostInit(hhcd->Instance, hhcd->Init); + + hhcd->State = HAL_HCD_STATE_READY; + + /* Host Port State */ + hhcd->HostState = HCD_HCD_STATE_DISCONNECTED; + + /* Init PMA Address */ + (void)HAL_HCD_PMAReset(hhcd); + + hhcd->State = HAL_HCD_STATE_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 these values: + * HCD_DEVICE_SPEED_HIGH High speed mode, + * HCD_DEVICE_SPEED_FULL Full speed mode, + * HCD_DEVICE_SPEED_LOW Low speed mode + * @param ep_type Endpoint Type. + * This parameter can be one of these values: + * USBH_EP_CONTROL Control type, + * USBH_EP_ISO Isochronous type, + * USBH_EP_BULK Bulk type, + * USBH_EP_INTERRUPT Interrupt type + * @param mps Max Packet Size. + * This parameter can be a value from 0 to32K + * @retval HAL status + */ +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; + uint8_t used_channel; + uint8_t ep0_virtual_channel; + + __HAL_LOCK(hhcd); + + if (ch_num > 16U) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + + if (((epnum & 0xFU) == 0U) && ((hhcd->ep0_PmaAllocState & 0xF000U) != 0U)) + { + hhcd->hc[ch_num & 0xFU].pmaadress = hhcd->hc[0U].pmaadress; + hhcd->hc[ch_num & 0xFU].pmaaddr0 = hhcd->hc[0U].pmaaddr0; + hhcd->hc[ch_num & 0xFU].pmaaddr1 = hhcd->hc[0U].pmaaddr1; + + hhcd->phy_chin_state[0U] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + + hhcd->phy_chout_state[0U] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + } + + /* Check if the logical channel are already allocated */ + used_channel = HAL_HCD_Check_usedChannel(hhcd, ch_num); + + /* Check if the channel is not already opened */ + if (used_channel == 0U) + { + /* Allocate New Physical channel */ + hhcd->hc[ch_num & 0xFU].phy_ch_num = HAL_HCD_Get_FreePhyChannel(hhcd, ch_num, epnum, ep_type); + + /* No free Channel available, return error */ + if (hhcd->hc[ch_num & 0xFU].phy_ch_num == HCD_FREE_CH_NOT_FOUND) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + } + /* Channel already opened */ + else + { + /* Get Physical Channel number */ + hhcd->hc[ch_num & 0xFU].phy_ch_num = (used_channel & 0xF0U) >> 4U; + } + + if ((epnum & 0x80U) != 0U) + { + hhcd->hc[ch_num & 0xFU].ch_dir = CH_IN_DIR; + } + else + { + hhcd->hc[ch_num & 0xFU].ch_dir = CH_OUT_DIR; + } + + hhcd->hc[ch_num & 0xFU].dev_addr = dev_address; + hhcd->hc[ch_num & 0xFU].max_packet = mps; + hhcd->hc[ch_num & 0xFU].ep_type = ep_type; + hhcd->hc[ch_num & 0xFU].ep_num = epnum & 0x7FU; + hhcd->hc[ch_num & 0xFU].speed = speed; + + /* Check if the channel is not already opened */ + if (used_channel == 0U) + { + if (((ep_type == EP_TYPE_ISOC) && (hhcd->Init.iso_singlebuffer_enable == 0U)) || + ((ep_type == EP_TYPE_BULK) && (hhcd->Init.bulk_doublebuffer_enable == 1U))) + { + /* PMA Dynamic Allocation */ + status = HAL_HCD_PMAlloc(hhcd, ch_num, HCD_DBL_BUF, mps); + + if (status == HAL_ERROR) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + + /* Clear Channel DTOG_TX */ + HCD_CLEAR_TX_DTOG(hhcd->Instance, hhcd->hc[ch_num & 0xFU].phy_ch_num); + + /* Clear Channel DTOG RX */ + HCD_CLEAR_RX_DTOG(hhcd->Instance, hhcd->hc[ch_num & 0xFU].phy_ch_num); + + } + else + { + if (hhcd->hc[ch_num & 0xFU].ep_num != 0U) + { + status = HAL_HCD_PMAlloc(hhcd, ch_num, HCD_SNG_BUF, mps); + + if (status == HAL_ERROR) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + } + else + { + if (ch_num == 0U) + { + ep0_virtual_channel = (uint8_t)(hhcd->ep0_PmaAllocState & 0xFU); + + if ((ep0_virtual_channel != 0U) && (((hhcd->ep0_PmaAllocState & 0xF0U) >> 4) == CH_IN_DIR)) + { + if (hhcd->hc[ch_num & 0xFU].ch_dir == CH_OUT_DIR) + { + status = HAL_HCD_PMAlloc(hhcd, ch_num, HCD_SNG_BUF, 64U); + + if (status == HAL_ERROR) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + } + else + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + } + else + { + /* This is a dual EP0 PMA allocation */ + hhcd->ep0_PmaAllocState |= (0x1U << 12); + + /* PMA Dynamic Allocation for EP0 OUT direction */ + hhcd->hc[ch_num & 0xFU].ch_dir = CH_OUT_DIR; + status = HAL_HCD_PMAlloc(hhcd, ch_num, HCD_SNG_BUF, 64U); + + if (status == HAL_ERROR) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + + /* PMA Dynamic Allocation for EP0 IN direction */ + hhcd->hc[ch_num & 0xFU].ch_dir = CH_IN_DIR; + status = HAL_HCD_PMAlloc(hhcd, ch_num, HCD_SNG_BUF, 64U); + + if (status == HAL_ERROR) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + } + } + else + { + if (((hhcd->ep0_PmaAllocState & 0xF00U) >> 8) == 1U) + { + ep0_virtual_channel = (uint8_t)(hhcd->ep0_PmaAllocState & 0xFU); + + if (((hhcd->ep0_PmaAllocState & 0xF0U) >> 4) == CH_IN_DIR) + { + hhcd->hc[ch_num & 0xFU].pmaaddr1 = hhcd->hc[ep0_virtual_channel & 0xFU].pmaaddr1; + } + else + { + hhcd->hc[ch_num & 0xFU].pmaaddr0 = hhcd->hc[ep0_virtual_channel & 0xFU].pmaaddr0; + } + } + else + { + status = HAL_HCD_PMAlloc(hhcd, ch_num, HCD_SNG_BUF, 64U); + + if (status == HAL_ERROR) + { + __HAL_UNLOCK(hhcd); + return HAL_ERROR; + } + } + } + } + } + } + + if ((epnum & 0x80U) != 0U) + { + hhcd->hc[ch_num & 0xFU].ch_dir = CH_IN_DIR; + + if (hhcd->hc[ch_num & 0xFU].ep_num == 0U) + { + hhcd->hc[ch_num & 0xFU].pmaadress = hhcd->hc[ch_num & 0xFU].pmaaddr1; + } + } + else + { + hhcd->hc[ch_num & 0xFU].ch_dir = CH_OUT_DIR; + + if (hhcd->hc[ch_num & 0xFU].ep_num == 0U) + { + hhcd->hc[ch_num & 0xFU].pmaadress = hhcd->hc[ch_num & 0xFU].pmaaddr0; + } + } + + /* Init the USB Channel CHEPRx */ + status = USB_HC_Init(hhcd->Instance, hhcd->hc[ch_num & 0xFU].phy_ch_num, + epnum, dev_address, speed, ep_type, mps); + + /* check single buffer for isochronous channel */ + if (ep_type == EP_TYPE_ISOC) + { + if (hhcd->Init.iso_singlebuffer_enable == 1U) + { + (void)USB_HC_DoubleBuffer(hhcd->Instance, hhcd->hc[ch_num & 0xFU].phy_ch_num, + USB_DRD_ISOC_DBUFF_DISABLE); + } + } + + /* Bulk double buffer check */ + if (ep_type == EP_TYPE_BULK) + { + if (hhcd->Init.bulk_doublebuffer_enable == 1U) + { + (void)USB_HC_DoubleBuffer(hhcd->Instance, hhcd->hc[ch_num & 0xFU].phy_ch_num, + USB_DRD_BULK_DBUFF_ENBALE); + } + } + + __HAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief HAL_HCD_HC_Close Pipe + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 15 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_HC_Close(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + /* Stop the channel */ + (void) HAL_HCD_HC_Halt(hhcd, ch_num); + + HAL_Delay(3U); + + if (hhcd->hc[ch_num & 0xFU].ch_dir == CH_IN_DIR) + { + /* Free Allocated Channel */ + hhcd->phy_chin_state[hhcd->hc[ch_num & 0xFU].phy_ch_num] = 0U; + } + else + { + /* Free Allocated Channel */ + hhcd->phy_chout_state[hhcd->hc[ch_num & 0xFU].phy_ch_num] = 0U; + } + + /* Reset PMA Channel_Allocation */ + (void)HAL_HCD_PMADeAlloc(hhcd, ch_num); + + return HAL_OK; +} + +/** + * @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 status + */ +HAL_StatusTypeDef HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + HAL_StatusTypeDef status = HAL_OK; + + __HAL_LOCK(hhcd); + if (hhcd->hc[ch_num & 0xFU].ch_dir == CH_IN_DIR) + { + (void)USB_HC_IN_Halt(hhcd->Instance, (uint8_t) hhcd->hc[ch_num & 0xFU].phy_ch_num); + } + else + { + (void)USB_HC_OUT_Halt(hhcd->Instance, (uint8_t) hhcd->hc[ch_num & 0xFU].phy_ch_num); + } + __HAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief DeInitialize the host driver. + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd) +{ + uint8_t idx; + + /* Check the HCD handle allocation */ + if (hhcd == NULL) + { + return HAL_ERROR; + } + + /* Host Port State */ + hhcd->HostState = HCD_HCD_STATE_DISCONNECTED; + + /* Reset PMA Address */ + (void)HAL_HCD_PMAReset(hhcd); + + for (idx = 0U; idx < hhcd->Init.Host_channels; idx++) + { + hhcd->phy_chin_state[idx] = 0U; + hhcd->phy_chout_state[idx] = 0U; + } + + /* reset Ep0 Pma allocation state */ + hhcd->ep0_PmaAllocState = 0U; + + hhcd->State = HAL_HCD_STATE_BUSY; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + if (hhcd->MspDeInitCallback == NULL) + { + hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hhcd->MspDeInitCallback(hhcd); +#else + /* DeInit the low level hardware: CLOCK, NVIC. */ + HAL_HCD_MspDeInit(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + hhcd->State = HAL_HCD_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initialize the HCD MSP. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the HCD MSP. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_MspDeInit could be implemented in the user file + */ +} + +__weak void HAL_HCD_SuspendCallback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_SuspendCallback could be implemented in the user file + */ + +} + +__weak void HAL_HCD_ResumeCallback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_ResumeCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_Group2 Input and Output 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 these values: + * 0 : Output / 1 : Input + * @param ep_type Endpoint Type. + * This parameter can be one of these values: + * USBH_EP_CONTROL : Control type/ + * USBH_EP_ISO : Isochronous type/ + * USBH_EP_BULK : Bulk type/ + * USBH_EP_INTERRUPT : Interrupt type/ + * @param token Endpoint Type. + * This parameter can be one of these values: + * 0: HC_PID_SETUP / 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 these values: + * 0 : do ping inactive / 1 : do ping active + * @retval HAL status + */ +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) +{ + UNUSED(do_ping); + + if (token == 0U) + { + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_SETUP; + } + else + { + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA1; + } + + /* Manage Data Toggle */ + switch (ep_type) + { + case EP_TYPE_CTRL: + if ((token == 1U) && (direction == 0U)) /* send data */ + { + if (length == 0U) + { + /* For Status OUT stage, Length==0, Status Out PID = 1 */ + hhcd->hc[ch_num & 0xFU].toggle_out = 1U; + } + + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num & 0xFU].toggle_out == 0U) + { + /* Put the PID 0 */ + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA0; + } + else + { + /* Put the PID 1 */ + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA1; + } + } + break; + + case EP_TYPE_BULK: + if (direction == 0U) + { + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num & 0xFU].toggle_out == 0U) + { + /* Put the PID 0 */ + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA0; + } + else + { + /* Put the PID 1 */ + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA1; + } + } + else + { + if (hhcd->hc[ch_num & 0xFU].toggle_in == 0U) + { + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA0; + } + else + { + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA1; + } + } + break; + + case EP_TYPE_INTR: + if (direction == 0U) + { + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num & 0xFU].toggle_out == 0U) + { + /* Put the PID 0 */ + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA0; + } + else + { + /* Put the PID 1 */ + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA1; + } + } + else + { + if (hhcd->hc[ch_num & 0xFU].toggle_in == 0U) + { + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA0; + } + else + { + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA1; + } + } + break; + + case EP_TYPE_ISOC: + hhcd->hc[ch_num & 0xFU].data_pid = HC_PID_DATA0; + break; + + default: + break; + } + + hhcd->hc[ch_num & 0xFU].xfer_buff = pbuff; + hhcd->hc[ch_num & 0xFU].xfer_len = length; + hhcd->hc[ch_num & 0xFU].xfer_len_db = length; + hhcd->hc[ch_num & 0xFU].urb_state = URB_IDLE; + hhcd->hc[ch_num & 0xFU].xfer_count = 0U; + hhcd->hc[ch_num & 0xFU].state = HC_IDLE; + + return USB_HC_StartXfer(hhcd->Instance, &hhcd->hc[ch_num & 0xFU]); +} +/** + * @brief Handle HCD interrupt request. + * @param hhcd HCD handle + * @retval None + */ +void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + uint8_t phy_chnum; + uint8_t ch_dir; + uint32_t wIstr = USB_ReadInterrupts(hhcd->Instance); + + /* Port Change Detected (Connection/Disconnection) */ + if ((wIstr & USB_ISTR_DCON) == USB_ISTR_DCON) + { + /* Clear Flag */ + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_DCON); + + /* Call Port IRQHandler */ + HCD_Port_IRQHandler(hhcd); + + return; + } + + /* Correct Transaction Detected -------*/ + if ((wIstr & USB_ISTR_CTR) == USB_ISTR_CTR) + { + /* Get Physical channel */ + phy_chnum = (uint8_t)__HAL_HCD_GET_CHNUM(hhcd); + + /* Get channel direction */ + ch_dir = (uint8_t)__HAL_HCD_GET_CHDIR(hhcd); + + if (ch_dir == CH_OUT_DIR) + { + /* Call Channel_OUT_IRQ() */ + HCD_HC_OUT_IRQHandler(hhcd, phy_chnum); + } + else + { + /* Call Channel_IN_IRQ() */ + HCD_HC_IN_IRQHandler(hhcd, phy_chnum); + } + + return; + } + + /* Wakeup Flag Detected */ + if ((wIstr & USB_ISTR_WKUP) == USB_ISTR_WKUP) + { + if (hhcd->HostState == HCD_HCD_STATE_SUSPEND) + { + /* Set The L2Resume bit */ + hhcd->Instance->CNTR |= USB_CNTR_L2RES; + + /* Clear the wake-up flag */ + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_WKUP); + + /* Update the USB Software state machine */ + HAL_HCD_ResumeCallback(hhcd); + hhcd->HostState = HCD_HCD_STATE_RESUME; + } + else + { + /* Clear the wake-up flag */ + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_WKUP); + } + + return; + } + + /* Global Error Flag Detected */ + if ((wIstr & USB_ISTR_ERR) == USB_ISTR_ERR) + { + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_ERR); + + return; + } + + /* PMA Overrun detected */ + if ((wIstr & USB_ISTR_PMAOVR) == USB_ISTR_PMAOVR) + { + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_PMAOVR); + + return; + } + + /* Suspend Detected */ + if ((wIstr & USB_ISTR_SUSP) == USB_ISTR_SUSP) + { + /* Set HAL State to Suspend */ + hhcd->HostState = HCD_HCD_STATE_SUSPEND; + + /* Force low-power mode in the macrocell */ + hhcd->Instance->CNTR |= USB_CNTR_SUSPEN; + + /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_SUSP); + + /* Call suspend Callback */ + HAL_HCD_SuspendCallback(hhcd); + + return; + } + + /* Start Of Frame Detected */ + if ((wIstr & USB_ISTR_SOF) == USB_ISTR_SOF) + { +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->SOFCallback(hhcd); +#else + HAL_HCD_SOF_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + __HAL_HCD_CLEAR_FLAG(hhcd, USB_ISTR_SOF); + + /* when first SOF is detected after USB_RESET is asserted */ + if (hhcd->HostState == HCD_HCD_STATE_RESETED) + { + /* HAL State */ + hhcd->HostState = HCD_HCD_STATE_RUN; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->PortEnabledCallback(hhcd); +#else + HAL_HCD_PortEnabled_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + + return; + } +} + +/** + * @brief SOF callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_SOF_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_SOF_Callback could be implemented in the user file + */ +} + +/** + * @brief Connection Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_Connect_Callback could be implemented in the user file + */ +} + +/** + * @brief Disconnection Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} +/** + * @brief Port Enabled Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} +/** + * @brief Port Disabled Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_Disconnect_Callback could be implemented 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 these values: + * URB_IDLE/ + * URB_DONE/ + * URB_NOTREADY/ + * URB_NYET/ + * URB_ERROR/ + * URB_STALL/ + * @retval None + */ +__weak void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, + uint8_t chnum, HCD_URBStateTypeDef urb_state) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + UNUSED(chnum); + UNUSED(urb_state); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_HCD_HC_NotifyURBChange_Callback could be implemented in the user file + */ +} +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User USB HCD Callback + * To be used instead of the weak predefined callback + * @param hhcd USB HCD handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_HCD_SOF_CB_ID USB HCD SOF callback ID + * @arg @ref HAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID + * @arg @ref HAL_HCD_DISCONNECT_CB_ID HCD Disconnect callback ID + * @arg @ref HAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enable callback ID + * @arg @ref HAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disable callback ID + * @arg @ref HAL_HCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_RegisterCallback(HCD_HandleTypeDef *hhcd, + HAL_HCD_CallbackIDTypeDef CallbackID, + pHCD_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hhcd); + + if (hhcd->State == HAL_HCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_HCD_SOF_CB_ID : + hhcd->SOFCallback = pCallback; + break; + + case HAL_HCD_CONNECT_CB_ID : + hhcd->ConnectCallback = pCallback; + break; + + case HAL_HCD_DISCONNECT_CB_ID : + hhcd->DisconnectCallback = pCallback; + break; + + case HAL_HCD_PORT_ENABLED_CB_ID : + hhcd->PortEnabledCallback = pCallback; + break; + + case HAL_HCD_PORT_DISABLED_CB_ID : + hhcd->PortDisabledCallback = pCallback; + break; + + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = pCallback; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hhcd->State == HAL_HCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = pCallback; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + return status; +} + +/** + * @brief Unregister an USB HCD Callback + * USB HCD callback is redirected to the weak predefined callback + * @param hhcd USB HCD handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_HCD_SOF_CB_ID USB HCD SOF callback ID + * @arg @ref HAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID + * @arg @ref HAL_HCD_DISCONNECT_CB_ID DRD HCD Disconnect callback ID + * @arg @ref HAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enabled callback ID + * @arg @ref HAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disabled callback ID + * @arg @ref HAL_HCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_UnRegisterCallback(HCD_HandleTypeDef *hhcd, + HAL_HCD_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hhcd); + + /* Setup Legacy weak Callbacks */ + if (hhcd->State == HAL_HCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_HCD_SOF_CB_ID : + hhcd->SOFCallback = HAL_HCD_SOF_Callback; + break; + + case HAL_HCD_CONNECT_CB_ID : + hhcd->ConnectCallback = HAL_HCD_Connect_Callback; + break; + + case HAL_HCD_DISCONNECT_CB_ID : + hhcd->DisconnectCallback = HAL_HCD_Disconnect_Callback; + break; + + case HAL_HCD_PORT_ENABLED_CB_ID : + hhcd->PortEnabledCallback = HAL_HCD_PortEnabled_Callback; + break; + + case HAL_HCD_PORT_DISABLED_CB_ID : + hhcd->PortDisabledCallback = HAL_HCD_PortDisabled_Callback; + break; + + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = HAL_HCD_MspInit; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hhcd->State == HAL_HCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = HAL_HCD_MspInit; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + return status; +} + +/** + * @brief Register USB HCD Host Channel Notify URB Change Callback + * To be used instead of the weak HAL_HCD_HC_NotifyURBChange_Callback() predefined callback + * @param hhcd HCD handle + * @param pCallback pointer to the USB HCD Host Channel Notify URB Change Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_RegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd, + pHCD_HC_NotifyURBChangeCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hhcd); + + if (hhcd->State == HAL_HCD_STATE_READY) + { + hhcd->HC_NotifyURBChangeCallback = pCallback; + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief Unregister the USB HCD Host Channel Notify URB Change Callback + * USB HCD Host Channel Notify URB Change Callback is redirected + * to the weak HAL_HCD_HC_NotifyURBChange_Callback() predefined callback + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_UnRegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hhcd); + + if (hhcd->State == HAL_HCD_STATE_READY) + { + hhcd->HC_NotifyURBChangeCallback = HAL_HCD_HC_NotifyURBChange_Callback; /* Legacy weak DataOutStageCallback */ + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + + return status; +} +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_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 status + */ +HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd) +{ + __IO uint32_t count = HCD_PDWN_EXIT_CNT; + + __HAL_LOCK(hhcd); + + /* Remove PowerDown */ + hhcd->Instance->CNTR &= ~USB_CNTR_PDWN; + + /* Few cycles to ensure exit from powerdown */ + while (count > 0U) + { + count--; + } + + /* Clear Reset */ + hhcd->Instance->CNTR &= ~USB_CNTR_USBRST; + + __HAL_UNLOCK(hhcd); + + return HAL_OK; +} + +/** + * @brief Stop the host driver. + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd) +{ + __HAL_LOCK(hhcd); + /*Stop the Host IP: setting powerdown */ + (void)USB_StopHost(hhcd->Instance); + + /* clear all allocated virtual channel */ + HAL_HCD_ClearPhyChannel(hhcd); + + /* Reset the PMA current pointer */ + (void)HAL_HCD_PMAReset(hhcd); + + /* reset Ep0 Pma allocation state */ + hhcd->ep0_PmaAllocState = 0U; + + __HAL_UNLOCK(hhcd); + return HAL_OK; +} + +/** + * @brief Put the Device in suspend mode + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_Suspend(HCD_HandleTypeDef *hhcd) +{ + __IO uint32_t count = 0U; + + /* Set Suspend Mode */ + hhcd->Instance->CNTR |= USB_CNTR_SUSPEN; + + /* wait for Suspend Ready */ + while ((hhcd->Instance->CNTR & USB_CNTR_SUSPRDY) == 0U) + { + if (++count > HAL_USB_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + return HAL_OK; +} + +/** + * @brief Resume host port + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_Resume(HCD_HandleTypeDef *hhcd) +{ + /* Set Resume bit */ + hhcd->Instance->CNTR |= USB_CNTR_L2RES; + + return HAL_OK; +} + +/** + * @brief Reset the host port. + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd) +{ + __HAL_LOCK(hhcd); + + /* Reset the USB Port by inserting an SE0 on the bus */ + (void)USB_ResetPort(hhcd->Instance); + + if (hhcd->HostState == HCD_HCD_STATE_CONNECTED) + { + hhcd->HostState = HCD_HCD_STATE_RESETED; + } + __HAL_UNLOCK(hhcd); + + return HAL_OK; +} + +/** + * @brief Resme the host port. + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_ResumePort(HCD_HandleTypeDef *hhcd) +{ + /* Set Resume bit */ + hhcd->Instance->CNTR |= USB_CNTR_L2RES; + HAL_Delay(30U); + + /* Clear Resume bit */ + hhcd->Instance->CNTR &= ~USB_CNTR_L2RES; + + return HAL_OK; +} + + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_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. + +@endverbatim + * @{ + */ + +/** + * @brief Return the HCD handle state. + * @param hhcd HCD handle + * @retval HAL state + */ +HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef const *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 these values: + * URB_IDLE/ + * URB_DONE/ + * URB_NOTREADY/ + * URB_NYET/ + * URB_ERROR/ + * URB_STALL + */ +HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef const *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 const *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 these values: + * HC_IDLE/ + * HC_XFRC/ + * HC_HALTED/ + * HC_NYET/ + * HC_NAK/ + * HC_STALL/ + * HC_XACTERR/ + * HC_BBLERR/ + * HC_DATATGLERR + */ +HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef const *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 speed : Device speed after Host enumeration + * This parameter can be one of these values: + * @arg HCD_DEVICE_SPEED_FULL: Full speed mode + * @arg HCD_DEVICE_SPEED_LOW: Low speed mode + */ +uint32_t HAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd) +{ + return (USB_GetHostSpeed(hhcd->Instance)); +} + +/** + * @brief Set host channel Hub Information. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 8 + * @param addr Hub address + * @param PortNbr Hub port number + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_HC_SetHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t addr, uint8_t PortNbr) +{ + hhcd->hc[ch_num].hub_addr = addr; + hhcd->hc[ch_num].hub_port_nbr = PortNbr; + + return HAL_OK; +} + + +/** + * @brief Clear host channel hub information. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_HC_ClearHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + hhcd->hc[ch_num].hub_addr = 0U; + hhcd->hc[ch_num].hub_port_nbr = 0U; + + return HAL_OK; +} + +#if (USE_USB_DOUBLE_BUFFER == 1U) +/** + * @brief Handle Host Channel OUT Double Buffer Bulk requests. + * @param hhcd HCD handle + * @param ch_num Channel number This parameter can be a value from 1 to 15 + * @param phy_chnum Physical Channel number [0..7] + * @param regvalue contain Snapshot of the EPCHn register when ISR is detected + * @retval none + */ +static void HCD_HC_OUT_BulkDb(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t phy_chnum, uint32_t regvalue) +{ + uint16_t data_xfr; + uint16_t len; + + /* Send Buffer0 */ + if ((regvalue & USB_CH_DTOG_TX) != 0U) + { + data_xfr = (uint16_t)(((USB_DRD_PMA_BUFF + phy_chnum)->TXBD & 0x03FF0000U) >> 16U); + + if (hhcd->hc[ch_num & 0xFU].xfer_len >= data_xfr) + { + hhcd->hc[ch_num & 0xFU].xfer_len -= data_xfr; + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_len = 0U; + } + + /* Transfer no yet finished only one packet of mps is transferred and ACKed from device */ + if (hhcd->hc[ch_num & 0xFU].xfer_len != 0U) + { + /* manage multiple Xfer */ + hhcd->hc[ch_num & 0xFU].xfer_count += data_xfr; + + /* check if we need to free user buffer */ + if ((regvalue & USB_CH_DTOG_RX) != 0U) + { + /* Toggle SwBuff */ + HCD_CLEAR_TX_DTOG(hhcd->Instance, phy_chnum); + HCD_CLEAR_RX_DTOG(hhcd->Instance, phy_chnum); + HCD_TX_DTOG(hhcd->Instance, phy_chnum); + } + + /* hhcd->hc[ch_num&0xFU].xfer_len_db==0 ==> when all data are written in the PMA to yet transferred */ + if (hhcd->hc[ch_num & 0xFU].xfer_len_db > 0U) /* Still data to fill in the buffer */ + { + hhcd->hc[ch_num & 0xFU].xfer_buff += data_xfr; + + /* calculate len of new buffer to fill */ + if (hhcd->hc[ch_num & 0xFU].xfer_len_db > hhcd->hc[ch_num & 0xFU].max_packet) + { + len = (uint16_t)hhcd->hc[ch_num & 0xFU].max_packet; + hhcd->hc[ch_num & 0xFU].xfer_len_db -= len; + } + else + { + len = (uint16_t)hhcd->hc[ch_num & 0xFU].xfer_len_db; + hhcd->hc[ch_num & 0xFU].xfer_len_db = 0U; /* end of fill buffer */ + } + + /* Write remaining data to Buffer0 */ + HCD_SET_CH_DBUF0_CNT(hhcd->Instance, phy_chnum, 1U, (uint16_t)len); + USB_WritePMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaaddr0, (uint16_t)len); + } + /* start a new transfer */ + HCD_SET_CH_TX_STATUS(hhcd->Instance, phy_chnum, USB_CH_TX_VALID); + } + else + { + /* Transfer complete state */ + hhcd->hc[ch_num & 0xFU].xfer_count += data_xfr; + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + hhcd->hc[ch_num & 0xFU].toggle_out ^= 1U; + /* Close the Channel */ + HCD_SET_CH_TX_STATUS(hhcd->Instance, phy_chnum, USB_CH_TX_DIS); + } + } + else + { + /* Send Buffer1 */ + data_xfr = (uint16_t)(((USB_DRD_PMA_BUFF + phy_chnum)->RXBD & 0x03FF0000U) >> 16U); + + if (hhcd->hc[ch_num & 0xFU].xfer_len >= data_xfr) /* updated */ + { + hhcd->hc[ch_num & 0xFU].xfer_len -= data_xfr; + } + + /* Transfer no yet finished only one packet of mps is transferred and ACKed from device */ + if (hhcd->hc[ch_num & 0xFU].xfer_len != 0U) + { + /* manage multiple Xfer */ + hhcd->hc[ch_num & 0xFU].xfer_count += data_xfr; + + /* check if we need to free user buffer */ + if ((regvalue & USB_CH_DTOG_RX) == 0U) + { + /* Toggle SwBuff */ + HCD_CLEAR_TX_DTOG(hhcd->Instance, phy_chnum); + HCD_CLEAR_RX_DTOG(hhcd->Instance, phy_chnum); + HCD_RX_DTOG(hhcd->Instance, phy_chnum); + } + + /* hhcd->hc[ch_num&0xFU].xfer_len_db==0 ==> when all data are written in the PMA to yet transferred */ + if (hhcd->hc[ch_num & 0xFU].xfer_len_db > 0U) /* Still data to fill in the buffer */ + { + hhcd->hc[ch_num & 0xFU].xfer_buff += data_xfr; + + /* calculate len of new buffer to fill */ + if (hhcd->hc[ch_num & 0xFU].xfer_len_db > hhcd->hc[ch_num & 0xFU].max_packet) + { + len = hhcd->hc[ch_num & 0xFU].max_packet; + hhcd->hc[ch_num & 0xFU].xfer_len_db -= len; + } + else + { + len = (uint16_t)hhcd->hc[ch_num & 0xFU].xfer_len_db; + hhcd->hc[ch_num & 0xFU].xfer_len_db = 0U; /* end of fill buffer */ + } + + /* Write remaining data to Buffer0 */ + HCD_SET_CH_DBUF1_CNT(hhcd->Instance, phy_chnum, 1U, (uint16_t)len); + + USB_WritePMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaaddr1, (uint16_t)len); + } + + /* start a new transfer */ + HCD_SET_CH_TX_STATUS(hhcd->Instance, phy_chnum, USB_CH_TX_VALID); + } + else + { + /* Transfer complete state */ + hhcd->hc[ch_num & 0xFU].xfer_count += data_xfr; + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + hhcd->hc[ch_num & 0xFU].toggle_out ^= 1U; + + /* Close the channel */ + HCD_SET_CH_TX_STATUS(hhcd->Instance, phy_chnum, USB_CH_TX_DIS); + } + } +} + + +/** + * @brief Handle Host Channel IN Double Buffer Bulk requests. + * @param hhcd HCD handle + * @param ch_num Channel number: This parameter can be a value from 1 to 15 + * @param phy_chnum Physical Channel number [0..7] + * @param regvalue contain Snapshot of the EPCHn register when ISR is detected + * @retval none + */ +static void HCD_HC_IN_BulkDb(HCD_HandleTypeDef *hhcd, + uint8_t ch_num, uint8_t phy_chnum, uint32_t regvalue) +{ + uint16_t received_bytes; + + /* Read from Buffer 0 */ + if ((regvalue & USB_CH_DTOG_RX) != 0U) + { + received_bytes = (uint16_t)HCD_GET_CH_DBUF0_CNT(hhcd->Instance, phy_chnum); + + if (hhcd->hc[ch_num & 0xFU].xfer_len <= received_bytes) + { + hhcd->hc[ch_num & 0xFU].xfer_len = 0U; + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_len -= received_bytes; + } + + /* Check if we Need to free the other buffer for the IP */ + if ((hhcd->hc[ch_num & 0xFU].xfer_len != 0U) && ((regvalue & USB_CH_DTOG_TX) != 0U)) + { + /* Toggle SwBuff to Allow the IP to submit a new IN */ + HCD_FREE_USER_BUFFER(hhcd->Instance, phy_chnum, 0U); + } + + /* Read the byte from PMA to user Buffer(System Memory) */ + USB_ReadPMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaaddr0, (uint16_t)received_bytes); + } + else + { + /* Read from Buffer 1 */ + received_bytes = (uint16_t) HCD_GET_CH_DBUF1_CNT(hhcd->Instance, phy_chnum); + + if (hhcd->hc[ch_num & 0xFU].xfer_len <= received_bytes) + { + hhcd->hc[ch_num & 0xFU].xfer_len = 0U; + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_len -= received_bytes; + } + + /* Check if we Need to free the other buffer for the IP */ + if ((hhcd->hc[ch_num & 0xFU].xfer_len != 0U) && ((regvalue & USB_CH_DTOG_TX) == 0U)) + { + /* Toggle SwBuff */ + HCD_FREE_USER_BUFFER(hhcd->Instance, phy_chnum, 0U); + } + + /* Read the byte from PMA to user Buffer(System Memory) */ + USB_ReadPMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaaddr1, (uint16_t)received_bytes); + } + + /* update the global number of all received bytes */ + hhcd->hc[ch_num & 0xFU].xfer_count += received_bytes; + + /* Transfer complete state */ + hhcd->hc[ch_num & 0xFU].state = HC_ACK; + hhcd->hc[ch_num & 0xFU].ErrCnt = 0U; + + if ((hhcd->hc[ch_num & 0xFU].xfer_len == 0U) || + ((received_bytes < hhcd->hc[ch_num & 0xFU].max_packet))) + { + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + + /* disable channel */ + HCD_SET_CH_RX_STATUS(hhcd->Instance, phy_chnum, USB_CH_RX_DIS); + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_buff += received_bytes; + + /* Reactivate the Channel Submit an other URB since the Transfer is not yet completed */ + HCD_SET_CH_RX_STATUS(hhcd->Instance, phy_chnum, USB_CH_RX_STRX); + } +} +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + +/** + * @brief Handle Host Channel IN Isochronous Transaction + * @param hhcd HCD handle + * @param ch_num Channel number: This parameter can be a value from 1 to 15 + * @param phy_chnum Physical Channel number [0..7] + * @param regvalue contain Snapshot of the EPCHn register when ISR is detected + * @retval none + */ +static void inline HCD_HC_IN_ISO(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t phy_chnum, uint32_t regvalue) +{ + /* Check if Double buffer isochronous */ + if ((regvalue & USB_CH_KIND) != 0U) + { + /* Get Data IN Packet */ + hhcd->hc[ch_num & 0xFU].xfer_count = HCD_GET_CH_RX_CNT(hhcd->Instance, phy_chnum); + if (hhcd->hc[ch_num & 0xFU].xfer_count != 0U) + { + USB_ReadPMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaadress, + (uint16_t)hhcd->hc[ch_num & 0xFU].xfer_count); + + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + } + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else /* double buffer isochronous */ + { + /* Read from Buffer0 */ + if ((regvalue & USB_CH_DTOG_RX) != 0U) + { + /* Get number of Received byte in buffer0 */ + hhcd->hc[ch_num & 0xFU].xfer_count = HCD_GET_CH_DBUF0_CNT(hhcd->Instance, phy_chnum); + + if (hhcd->hc[ch_num & 0xFU].xfer_count != 0U) + { + /* Read from Buffer0 */ + USB_ReadPMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaaddr0, + (uint16_t)hhcd->hc[ch_num & 0xFU].xfer_count); + + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + } + } + else + { + /* Get number of Received byte in buffer1 */ + hhcd->hc[ch_num & 0xFU].xfer_count = HCD_GET_CH_DBUF1_CNT(hhcd->Instance, phy_chnum); + + if (hhcd->hc[ch_num & 0xFU].xfer_count != 0U) + { + /* Read from Buffer1 */ + USB_ReadPMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaaddr1, + (uint16_t)hhcd->hc[ch_num & 0xFU].xfer_count); + + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + } + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* Transfer complete state */ + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + + /* Clear VTRX */ + HCD_CLEAR_RX_CH_CTR(hhcd->Instance, phy_chnum); +} + +/** + * @brief Handle Host Channel IN interrupt requests. + * @param hhcd HCD handle + * @param chnum Channel number + * This parameter can be a value from 1 to 8 + * @retval none + */ +static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + uint16_t received_bytes; + uint8_t phy_chnum = chnum; + uint8_t ch_num = HAL_HCD_GetLogical_Channel(hhcd, phy_chnum, 1U); + + /* Take a Flag snapshot from the CHEP register, due to STRX bits are used for both control and status */ + uint32_t ch_reg = HCD_GET_CHANNEL(hhcd->Instance, phy_chnum); + + /* Manage Correct Transaction */ + if ((ch_reg & USB_CH_ERRRX) == 0U) + { + /* Isochronous Channel */ + if ((ch_reg & USB_CH_UTYPE) == USB_EP_ISOCHRONOUS) + { + HCD_HC_IN_ISO(hhcd, ch_num, phy_chnum, ch_reg); + } + else + { + /* manage ACK response single buffer */ + if (((ch_reg) & USB_CH_RX_STRX) == USB_CH_RX_ACK_SBUF) + { + /* Get Control Data OUT Packet */ + received_bytes = (uint16_t)HCD_GET_CH_RX_CNT(hhcd->Instance, phy_chnum); + + /* Read the byte from PMA to user Buffer(System Memory) */ + USB_ReadPMA(hhcd->Instance, hhcd->hc[ch_num & 0xFU].xfer_buff, + hhcd->hc[ch_num & 0xFU].pmaadress, (uint16_t)received_bytes); + + /* update the global number of all received bytes */ + hhcd->hc[ch_num & 0xFU].xfer_count += received_bytes; + + /* Transfer complete state */ + hhcd->hc[ch_num & 0xFU].state = HC_ACK; + hhcd->hc[ch_num & 0xFU].ErrCnt = 0U; + + if (hhcd->hc[ch_num & 0xFU].xfer_len <= received_bytes) + { + hhcd->hc[ch_num & 0xFU].xfer_len = 0U; + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_len -= received_bytes; + } + + if ((hhcd->hc[ch_num & 0xFU].xfer_len == 0U) || + ((received_bytes < hhcd->hc[ch_num & 0xFU].max_packet))) + { + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_buff += received_bytes; + + /* Reactivate the Channel to Submit another URB since the Transfer is not yet completed */ + HCD_SET_CH_RX_STATUS(hhcd->Instance, phy_chnum, USB_CH_RX_STRX); + } + + if ((hhcd->hc[ch_num & 0xFU].ep_type == EP_TYPE_BULK) || + (hhcd->hc[ch_num & 0xFU].ep_type == EP_TYPE_INTR)) + { + hhcd->hc[ch_num & 0xFU].toggle_in ^= 1U; + } + } + /* Manage NACK Response */ + else if (((ch_reg & USB_CH_RX_STRX) == USB_CH_RX_NAK) + && (hhcd->hc[ch_num & 0xFU].urb_state != URB_DONE)) + { + hhcd->hc[ch_num & 0xFU].urb_state = URB_NOTREADY; + hhcd->hc[ch_num & 0xFU].ErrCnt = 0U; + hhcd->hc[ch_num & 0xFU].state = HC_NAK; + + if (hhcd->hc[ch_num & 0xFU].ep_type == EP_TYPE_INTR) + { + /* Close the channel */ + HCD_SET_CH_RX_STATUS(hhcd->Instance, phy_chnum, USB_CH_RX_DIS); + } + } + /* Manage STALL Response */ + else if ((ch_reg & USB_CH_RX_STRX) == USB_CH_RX_STALL) + { + (void)HAL_HCD_HC_Halt(hhcd, ch_num); + hhcd->hc[ch_num & 0xFU].state = HC_STALL; + hhcd->hc[ch_num & 0xFU].urb_state = URB_STALL; + + /* Close the channel */ + HCD_SET_CH_RX_STATUS(hhcd->Instance, phy_chnum, USB_CH_RX_DIS); + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + /* Double Buffer Management in case of Bulk Transaction */ + else if (((ch_reg & USB_CH_RX_STRX) == USB_CH_RX_ACK_DBUF) + && ((ch_reg & USB_CH_KIND) != 0U)) + { + /* Bulk IN Double Buffer ISR */ + HCD_HC_IN_BulkDb(hhcd, ch_num, phy_chnum, ch_reg); + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + else + { + /*....*/ + /* not defined state: STRX=11 in single buffer no iso is not defined */ + } + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + /*Clear VTRX */ + HCD_CLEAR_RX_CH_CTR(hhcd->Instance, phy_chnum); + } + } + else /* Error detected during last transaction */ + { + /* Set URB Error State */ + hhcd->hc[ch_num & 0xFU].urb_state = URB_NOTREADY; + hhcd->hc[ch_num & 0xFU].ErrCnt++; + hhcd->hc[ch_num & 0xFU].state = HC_XACTERR; + + /* Clear VTTRX & ERR_RX */ + HCD_CLEAR_RX_CH_ERR(hhcd->Instance, phy_chnum); + + /* Check Error number */ + if (hhcd->hc[ch_num & 0xFU].ErrCnt > 3U) + { + hhcd->hc[ch_num & 0xFU].urb_state = URB_ERROR; + HCD_SET_CH_RX_STATUS(hhcd->Instance, phy_chnum, USB_CH_RX_DIS); + + /* Clear pending err_tx */ + HCD_CLEAR_RX_CH_ERR(hhcd->Instance, phy_chnum); + } + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } +} + + +/** + * @brief Handle Host Channel OUT interrupt requests. + * @param hhcd HCD handle + * @param chnum Channel number + * This parameter can be a value from 1 to 8 + * @retval none + */ +static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) +{ + __IO uint32_t WregCh; + uint16_t data_xfr; + uint8_t phy_chnum = chnum; + + /* Get Virtual Channel number */ + uint8_t ch_num = HAL_HCD_GetLogical_Channel(hhcd, phy_chnum, 0U); + + /* Take a Flag snapshot from the CHEP register, due to STRX bits are used for both control &status */ + uint32_t ch_reg = *(__IO uint32_t *)(&(hhcd->Instance->CHEP0R) + phy_chnum); + + /*------ Manage Correct Transaction ------*/ + if ((ch_reg & USB_CH_ERRTX) == 0U) + { + /* Handle Isochronous channel */ + if ((ch_reg & USB_CH_UTYPE) == USB_EP_ISOCHRONOUS) + { + /* Correct transaction */ + if ((hhcd->Instance->ISTR & USB_ISTR_ERR) == 0U) + { + /* Double buffer isochronous out */ + if ((ch_reg & USB_CH_KIND) != 0U) + { + HCD_SET_CH_TX_CNT(hhcd->Instance, phy_chnum, 0U); + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else /* Double buffer isochronous out */ + { + /* Odd Transaction */ + if ((ch_reg & USB_CH_DTOG_TX) != 0U) + { + HCD_SET_CH_TX_CNT(hhcd->Instance, phy_chnum, 0U); + } + /* Even Transaction */ + else + { + HCD_SET_CH_RX_CNT(hhcd->Instance, phy_chnum, 0U); + } + + USB_DRD_SET_CHEP_TX_STATUS(hhcd->Instance, phy_chnum, USB_CH_TX_DIS); + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* Transfer complete state */ + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + } + + /*Clear Correct Transfer */ + HCD_CLEAR_TX_CH_CTR(hhcd->Instance, phy_chnum); + + /*TX COMPLETE*/ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + } + else /* Manage all Non Isochronous Transaction */ + { + /* Check ACK response */ + if ((ch_reg & USB_CH_TX_STTX) == USB_CH_TX_ACK_SBUF) + { + data_xfr = (uint16_t)(((USB_DRD_PMA_BUFF + phy_chnum)->TXBD & 0x03FF0000U) >> 16U); + + if (hhcd->hc[ch_num & 0xFU].xfer_len >= data_xfr) + { + hhcd->hc[ch_num & 0xFU].xfer_len -= data_xfr; + } + else + { + hhcd->hc[ch_num & 0xFU].xfer_len = 0U; + } + + if ((hhcd->hc[ch_num & 0xFU].ep_type == EP_TYPE_BULK) || + (hhcd->hc[ch_num & 0xFU].ep_type == EP_TYPE_INTR)) + { + hhcd->hc[ch_num & 0xFU].toggle_out ^= 1U; + } + + /* Transfer no yet finished only one packet of mps is transferred and ACKed from device */ + if (hhcd->hc[ch_num & 0xFU].xfer_len != 0U) + { + /* Manage multiple Xfer */ + hhcd->hc[ch_num & 0xFU].xfer_buff += data_xfr; + hhcd->hc[ch_num & 0xFU].xfer_count += data_xfr; + + /* Start a new transfer */ + (void) USB_HC_StartXfer(hhcd->Instance, &hhcd->hc[ch_num & 0xFU]); + } + else + { + /* Transfer complete */ + hhcd->hc[ch_num & 0xFU].xfer_count += data_xfr; + hhcd->hc[ch_num & 0xFU].state = HC_XFRC; + hhcd->hc[ch_num & 0xFU].urb_state = URB_DONE; + } + } + /* Check NACK Response */ + else if (((ch_reg & USB_CHEP_NAK) == USB_CHEP_NAK) || + ((ch_reg & USB_CH_TX_STTX) == USB_CH_TX_NAK)) + { + /* Update Channel status */ + hhcd->hc[ch_num & 0xFU].state = HC_NAK; + hhcd->hc[ch_num & 0xFU].urb_state = URB_NOTREADY; + hhcd->hc[ch_num & 0xFU].ErrCnt = 0U; + + /* Get Channel register value */ + WregCh = *(__IO uint32_t *)(&(hhcd->Instance->CHEP0R) + phy_chnum); + + /* Clear NAK status */ + WregCh &= ~USB_CHEP_NAK & USB_CHEP_REG_MASK; + + /* Update channel register Value */ + HCD_SET_CHANNEL(hhcd->Instance, phy_chnum, WregCh); + + if (hhcd->hc[ch_num & 0xFU].doublebuffer == 0U) + { +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + } + /* Check STALL Response */ + else if ((ch_reg & USB_CH_TX_STTX) == USB_CH_TX_STALL) + { + (void) HAL_HCD_HC_Halt(hhcd, (uint8_t)ch_num); + hhcd->hc[ch_num & 0xFU].state = HC_STALL; + hhcd->hc[ch_num & 0xFU].urb_state = URB_STALL; + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + /* Check double buffer ACK in case of bulk transaction */ + else if ((ch_reg & USB_CH_TX_STTX) == USB_CH_TX_ACK_DBUF) + { + /* Double buffer management Bulk Out */ + (void) HCD_HC_OUT_BulkDb(hhcd, ch_num, (uint8_t)phy_chnum, ch_reg); + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + else + { + /*...*/ + } + + if ((ch_reg & USB_CH_TX_STTX) != USB_CH_TX_NAK) + { +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + + HCD_CLEAR_TX_CH_CTR(hhcd->Instance, phy_chnum); + } /* End no isochronous */ + } + /*------ Manage Transaction Error------*/ + else + { + hhcd->hc[ch_num & 0xFU].ErrCnt++; + if (hhcd->hc[ch_num & 0xFU].ErrCnt > 3U) + { + HCD_SET_CH_TX_STATUS(hhcd->Instance, phy_chnum, USB_CH_TX_DIS); + hhcd->hc[ch_num & 0xFU].urb_state = URB_ERROR; + } + else + { + hhcd->hc[ch_num & 0xFU].urb_state = URB_NOTREADY; + } + + hhcd->hc[ch_num & 0xFU].state = HC_XACTERR; + + /* Clear ERR_TX */ + HCD_CLEAR_TX_CH_ERR(hhcd->Instance, phy_chnum); + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, (uint8_t)ch_num, hhcd->hc[ch_num & 0xFU].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } +} + + +/** + * @brief Handle Host Port interrupt requests. + * @param hhcd HCD handle + * @retval None + */ +static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + uint32_t FnrReg = hhcd->Instance->FNR; + uint32_t IstrReg = hhcd->Instance->ISTR; + + /* SE0 detected USB Disconnected state */ + if ((FnrReg & (USB_FNR_RXDP | USB_FNR_RXDM)) == 0U) + { + /* Host Port State */ + hhcd->HostState = HCD_HCD_STATE_DISCONNECTED; + + /* Clear all allocated virtual channel */ + HAL_HCD_ClearPhyChannel(hhcd); + + /* Reset the PMA current pointer */ + (void)HAL_HCD_PMAReset(hhcd); + + /* Reset Ep0 Pma allocation state */ + hhcd->ep0_PmaAllocState = 0U; + + /* Disconnection Callback */ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->DisconnectCallback(hhcd); +#else + HAL_HCD_Disconnect_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + return; + } + + if ((hhcd->HostState == HCD_HCD_STATE_DISCONNECTED) != 0U) + { + /* J-state or K-state detected & LastState=Disconnected */ + if (((FnrReg & USB_FNR_RXDP) != 0U) || ((IstrReg & USB_ISTR_LS_DCONN) != 0U)) + { + hhcd->HostState = HCD_HCD_STATE_CONNECTED; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->ConnectCallback(hhcd); +#else + HAL_HCD_Connect_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + } + else + { + /* J-state or K-state detected & lastState=Connected: a Missed disconnection is detected */ + if (((FnrReg & USB_FNR_RXDP) != 0U) || ((IstrReg & USB_ISTR_LS_DCONN) != 0U)) + { + /* Host Port State */ + hhcd->HostState = HCD_HCD_STATE_DISCONNECTED; + + /* clear all allocated virtual channel */ + HAL_HCD_ClearPhyChannel(hhcd); + + /* Reset the PMA current pointer */ + (void)HAL_HCD_PMAReset(hhcd); + + /* reset Ep0 PMA allocation state */ + hhcd->ep0_PmaAllocState = 0U; + + /* Disconnection Callback */ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->DisconnectCallback(hhcd); +#else + HAL_HCD_Disconnect_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + } +} + + +/** + * @brief Check if the ch_num are already reserved to a physical channel + * @param hhcd HCD handle + * @param ch_num Channel number + * This parameter can be a value from 1 to 15 + * @retval HAL status + */ +static uint8_t HAL_HCD_Check_usedChannel(HCD_HandleTypeDef const *hhcd, uint8_t ch_num) +{ + uint8_t idx; + + /* Check if the logical channel are already opened */ + for (idx = 0U; idx < hhcd->Init.Host_channels; idx++) + { + if ((((hhcd->phy_chin_state[idx] & 0xF0U) >> 4U) == ((uint16_t)ch_num + 1U)) && + (hhcd->phy_chin_state[idx] != 0U)) + { + return (1U | (idx << 4U)); + } + + if ((((hhcd->phy_chout_state[idx] & 0xF0U) >> 4U) == ((uint16_t)ch_num + 1U)) && + (hhcd->phy_chout_state[idx] != 0U)) + { + return (1U | (idx << 4U)); + } + } + + return 0U; +} + + +/** + * @brief Get a Logical Channel number from physical Channel + * @param hhcd HCD handle + * @param phy_chnum + * This parameter can be a value from 1 to 15 + * @param dir Channel direction + * -0 OUT_Channel + * -1 IN_Channel + * @retval HAL status + */ +static uint8_t HAL_HCD_GetLogical_Channel(HCD_HandleTypeDef const *hhcd, + uint8_t phy_chnum, uint8_t dir) +{ + /* Out Channel Direction */ + if (dir == 0U) + { + if (((hhcd->phy_chout_state[phy_chnum & 0x7U] & 0x00F0U) >> 4U) != 0U) + { + return ((uint8_t)((hhcd->phy_chout_state[phy_chnum & 0x7U] & 0x00F0U) >> 4U) - 1U); + } + else + { + /* Channel not registered Error */ + return HCD_LOGICAL_CH_NOT_OPENED; + } + } + /* IN Channel Direction */ + else + { + if (((hhcd->phy_chin_state[phy_chnum & 0x7U] & 0x00F0U) >> 4U) != 0U) + { + return ((uint8_t)((hhcd->phy_chin_state[phy_chnum & 0x7U] & 0x00F0U) >> 4U) - 1U); + } + else + { + /* Channel not registered Error */ + return HCD_LOGICAL_CH_NOT_OPENED; + } + } +} + + +/** + * @brief Get a free physical Channel number according to the direction + * @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 ep_type Endpoint Type + * This parameter can be one of these values: + * EP_TYPE_CTRL Control type, + * EP_TYPE_ISOC Isochronous type, + * EP_TYPE_BULK Bulk type, + * EP_TYPE_INTR Interrupt type + * @retval if physical channel is available return Phy_channel number + else return HCD_FREE_CH_NOT_FOUND + */ +static uint8_t HAL_HCD_Get_FreePhyChannel(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t epnum, uint8_t ep_type) +{ + uint8_t idx; + + if ((epnum & 0x7FU) == 0U) + { + idx = 0U; + + if (ch_num == 0U) + { + if (hhcd->phy_chin_state[idx] == 0U) + { + /* chin_state to store the ep_type to be used for the same channel in OUT direction + * adding + 1 to ep_type avoid starting with a 0 value. ep_type take by default (0/1/2/3) */ + hhcd->phy_chin_state[idx] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + } + + if (hhcd->phy_chout_state[idx] == 0U) + { + /* chout_state will store the ep_type to be used for the same channel in IN direction + * adding + 1 to ep_type avoid starting with a 0 value. ep_type take by default (0/1/2/3) */ + hhcd->phy_chout_state[idx] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + } + } + else + { + if ((epnum & 0x80U) != 0U) + { + if (((hhcd->phy_chin_state[idx] & 0xF0U) >> 4U) != ((uint16_t)ch_num + 1U)) + { + /* chin_state to store the ep_type to be used for the same channel in OUT direction + * adding + 1 to ep_type avoid starting with a 0 value. ep_type take by default (0/1/2/3) */ + hhcd->phy_chin_state[idx] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + } + } + else + { + if (((hhcd->phy_chout_state[idx] & 0xF0U) >> 4U) != ((uint16_t)ch_num + 1U)) + { + /* chout_state will store the ep_type to be used for the same channel in IN direction + * adding + 1 to ep_type avoid starting with a 0 value. ep_type take by default (0/1/2/3) */ + hhcd->phy_chout_state[idx] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + } + } + } + + return idx; + } + + if ((epnum & 0x80U) != 0U) + { + /* Find a new available physical in channel */ + for (idx = 1U; idx < hhcd->Init.Host_channels; idx++) + { + /* Check if the same epnum is allocated then allocate the same physical channel OUT for IN Logical Channel */ + if ((hhcd->phy_chin_state[idx] == 0U) && + ((((hhcd->phy_chout_state[idx] & 0x000FU) == ((uint16_t)ep_type + 1U)) && + (((hhcd->phy_chout_state[idx] & 0x0F00U) == ((uint16_t)epnum & 0x0FU)))) || + (hhcd->phy_chout_state[idx] == 0U))) + { + /* chin_state to store the ep_type to be used for the same channel in OUT direction + * adding + 1 to ep_type avoid starting with a 0 value. ep_type take by default (0/1/2/3) */ + hhcd->phy_chin_state[idx] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + + return idx; + } + } + } + else + { + /* Find a new available physical out channel */ + for (idx = 1U; idx < hhcd->Init.Host_channels; idx++) + { + /* Check if the same epnum is allocated then allocate the same physical channel IN for OUT Logical Channel */ + if ((hhcd->phy_chout_state[idx] == 0U) && + ((((hhcd->phy_chin_state[idx] & 0x0FU) == ((uint16_t)ep_type + 1U)) && + ((hhcd->phy_chin_state[idx] & 0x0F00U) == ((uint16_t)epnum & 0x0FU))) || + (hhcd->phy_chin_state[idx] == 0U))) + { + /* chout_state will store the ep_type to be used for the same channel in IN direction + * adding + 1 to ep_type avoid starting with a 0 value. ep_type take by default (0/1/2/3) */ + hhcd->phy_chout_state[idx] = (((uint16_t)ch_num + 1U) << 4U) | + ((uint16_t)ep_type + 1U) | + (((uint16_t)epnum & 0x0FU) << 8U); + + return idx; + } + } + } + + /* in case of Error */ + return HCD_FREE_CH_NOT_FOUND; +} + +/** + * @brief Free All Channel allocation + * @param hhcd HCD handle + * @retval HAL status + */ +static void HAL_HCD_ClearPhyChannel(HCD_HandleTypeDef *hhcd) +{ + uint8_t idx; + + for (idx = 0U; idx < hhcd->Init.Host_channels; idx++) + { + /*Reset channel allocation value */ + hhcd->phy_chout_state[idx] = 0U; + hhcd->phy_chin_state[idx] = 0U; + } +} + +/*---------------------- PMA Allocation Section --------------------- */ +/* + __col31________________col0__ Column-- > + lin0 | entry31.|....... | entry0 | Line + |---------|---------|--------| | + line1| entry63.|....... | entry32| | + |---------|---------|--------| \|/ + | entry127|....... | entry64| + |---------|---------|--------| + | entry256|...... |entry128| + ---------------------------- + an allocation space of 64byte need 8 Free contiguous Entry in the Matrix + - a Free Entry is a bit with 0 Value/ a busy entry is a bit with 1 value. */ + +/** + * @brief Fetch in the PMA_LockupTable free space of number of mps byte + * @param hhcd Host instance + * @param mps Channel Max Packet Size + * @retval PMA_Address of the first free block containing mps byte + 0xFFFF in case of no space available + */ +static uint16_t HAL_HCD_GetFreePMA(HCD_HandleTypeDef *hhcd, uint16_t mps) +{ + uint32_t Entry; + uint32_t FreeBlocks = 0U; + uint8_t FirstFreeBlock_col = 0U; + uint8_t FirstFreeBlock_line = 0U; + uint8_t ColIndex; + uint16_t NbrReqBlocks; + uint16_t mps_t = mps; + + /* since PMA buffer descriptor RXBD allocate address according to BLSIZE, BLSIZE=1==> mps>64 + allocation in PMA is done in 32Bytes each entry */ + if ((mps_t > 64U) && ((mps_t % 32U) != 0U)) + { + /* Align the mps to 32byte block to match the allocation in PMA, + check Definition of allocation buffer memory in usb user spec */ + mps_t = (uint16_t)(((mps_t / 32U) + 1U) * 32U); + } + + /* calculate the number of block(8byte) to allocate */ + NbrReqBlocks = mps_t / 8U; + + /* check if we need remaining Block */ + if ((mps_t % 8U) != 0U) + { + NbrReqBlocks++; + } + + /* Look For NbrReqBlocks * Empty Block */ + for (uint8_t i = 0U; ((i < PMA_BLOCKS) && (FreeBlocks != NbrReqBlocks)); i++) + { + Entry = hhcd->PMALookupTable[i]; + + /* when parse is in progress, check the first col to look for a contiguous block */ + if ((FreeBlocks != 0U) && ((Entry & (uint32_t)1U) != 0U)) + { + FreeBlocks = 0U; + } + uint8_t j = 0U; + while ((j <= 31U) && (FreeBlocks != NbrReqBlocks)) + { + /* check if block j is free */ + if ((Entry & ((uint32_t)1U << j)) == 0U) + { + if (FreeBlocks == 0U) + { + FirstFreeBlock_col = j; + FirstFreeBlock_line = i; + FreeBlocks++; + } + j++; + + /* Parse Column PMALockTable */ + while ((j <= 31U) && ((Entry & ((uint32_t)1U << j)) == 0U) && (FreeBlocks < NbrReqBlocks)) + { + FreeBlocks++; + j++; + } + + /* Free contiguous Blocks not found */ + if (((FreeBlocks < NbrReqBlocks) && (j < 31U)) || + ((j == 31U) && ((Entry & ((uint32_t)1U << j)) != 0U))) + { + FreeBlocks = 0U; + } + } + j++; + } /* end for j */ + } /* end for i */ + + /* Free block found */ + if (FreeBlocks >= NbrReqBlocks) + { + ColIndex = FirstFreeBlock_col; + + for (uint8_t i = FirstFreeBlock_line; ((i < PMA_BLOCKS) && (FreeBlocks > 0U)); i++) + { + for (uint8_t j = ColIndex; j <= 31U; j++) + { + hhcd->PMALookupTable[i] |= ((uint32_t)1U << j); + if (--FreeBlocks == 0U) + { + break; + } + } + ColIndex = 0U; + } + + return (uint16_t)((FirstFreeBlock_line * (uint16_t)256U) + (FirstFreeBlock_col * (uint16_t)8U)); + } + else + { + return 0xFFFFU; + } +} + +/** + * @brief Allocate PMA buffer for Channel + * This API will fetch a free space + * @param hhcd Host instance + * @param ch_num Channel number + * @param ch_kind endpoint Kind + * USB_SNG_BUF Single Buffer used + * USB_DBL_BUF Double Buffer used + * @param mps Channel Max Packet Size + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_PMAlloc(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint16_t ch_kind, uint16_t mps) +{ + uint16_t pma_addr0; +#if (USE_USB_DOUBLE_BUFFER == 1U) + uint16_t pma_addr1; /* used for double buffer mode if enabled */ +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* Host Channel */ + HCD_HCTypeDef *hc = &(hhcd->hc[ch_num]); + + /* Get a FreePMA Address */ + pma_addr0 = HAL_HCD_GetFreePMA(hhcd, mps); + + /* If there is no free space to allocate */ + if (pma_addr0 == 0xFFFFU) + { + return HAL_ERROR; + } + else + { + /* Here we check if the endpoint is single or double Buffer */ + if (ch_kind == HCD_SNG_BUF) + { + /* Single Buffer */ + hc->doublebuffer = 0U; + + if (hc->ep_num == 0U) + { + hhcd->ep0_PmaAllocState &= 0xFFF0U; + hhcd->ep0_PmaAllocState |= ch_num; + hhcd->ep0_PmaAllocState |= (1U << 8); + } + + /* Configure the PMA */ + if (hc->ch_dir == CH_IN_DIR) + { + hc->pmaaddr1 = pma_addr0; + (USB_DRD_PMA_BUFF + hc->phy_ch_num)->RXBD = hc->pmaaddr1; + + if (hc->ep_num == 0U) + { + hhcd->ep0_PmaAllocState |= (CH_IN_DIR << 4); + } + } + else + { + hc->pmaaddr0 = pma_addr0; + (USB_DRD_PMA_BUFF + hc->phy_ch_num)->TXBD = hc->pmaaddr0; + } + + /* Set the PmaAddress */ + hc->pmaadress = pma_addr0; + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else /* USB_DBL_BUF */ + { + /* Double Buffer Endpoint */ + hc->doublebuffer = 1U; + + /* Get a FreePMA Address for buffer 2 */ + pma_addr1 = HAL_HCD_GetFreePMA(hhcd, mps); + + if (pma_addr1 == 0xFFFFU) + { + /* Free the first buffer */ + (void)HAL_HCD_PMAFree(hhcd, pma_addr0, mps); + return HAL_ERROR; + } + else + { + /* Configure the PMA */ + hc->pmaaddr0 = (uint16_t)(pma_addr0); + hc->pmaaddr1 = (uint16_t)(pma_addr1); + + /* Set Buffer0 pma address */ + (USB_DRD_PMA_BUFF + hc->phy_ch_num)->TXBD = pma_addr0; + + /* Set Buffer1 pma address */ + (USB_DRD_PMA_BUFF + hc->phy_ch_num)->RXBD = pma_addr1; + + /* Used for Bulk DB MPS < 64bytes */ + if (hc->ch_dir == CH_IN_DIR) + { + hc->pmaadress = hc->pmaaddr1; + } + else + { + hc->pmaadress = hc->pmaaddr0; + } + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + } + + return HAL_OK; +} + +/** + * @brief PMA De-Allocation for Channel Free the reserved block in the PMA-LookupTable + * @param hhcd Host instance + * @param ch_num Channel number + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_PMADeAlloc(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + HAL_StatusTypeDef status; + +#if (USE_USB_DOUBLE_BUFFER == 1U) + uint8_t Err = 0U; +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* Host Channel */ + HCD_HCTypeDef *hc = &(hhcd->hc[ch_num]); + + /* Single Buffer */ + if (hc->doublebuffer == 0U) + { + status = HAL_HCD_PMAFree(hhcd, hc->pmaadress, hc->max_packet); + } + else /* Double buffer */ + { +#if (USE_USB_DOUBLE_BUFFER == 1U) + status = HAL_HCD_PMAFree(hhcd, hc->pmaaddr0, hc->max_packet); + if (status != HAL_OK) + { + Err++; + } + + status = HAL_HCD_PMAFree(hhcd, hc->pmaaddr1, hc->max_packet); + if (status != HAL_OK) + { + Err++; + } + + if (Err != 0U) + { + return HAL_ERROR; + } +#else + status = HAL_ERROR; +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + } + + return status; +} + + +/** + * @brief PMA Reset + * @param hhcd Host instance + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_PMAReset(HCD_HandleTypeDef *hhcd) +{ + /* Reset All PMA Entry */ + for (uint8_t i = 0U; i < PMA_BLOCKS; i++) + { + hhcd->PMALookupTable[i] = 0U; + } + + /* Allocate a Space for buffer descriptor table depending on the Host channel number */ + for (uint8_t i = 0U; i < hhcd->Init.Host_channels; i++) + { + hhcd->PMALookupTable[0] |= ((uint32_t)1U << i); + } + + return HAL_OK; +} + +/** + * @brief PMA Free + * @param hhcd Host instance + * @param pma_base PMA base offset stored in hhcd->hc.pmaaddr + * @param mps Max Packet Size + * @retval HAL status + */ +static HAL_StatusTypeDef HAL_HCD_PMAFree(HCD_HandleTypeDef *hhcd, uint32_t pma_base, uint16_t mps) +{ + uint32_t block_nbr; + uint8_t ColIndex; + uint8_t LineIndex; + uint16_t mps_t = mps; + + /* since PMA buffer descriptor RXBD allocate address according to BLSIZE, BLSIZE=1==> mps>64 + allocation in PMA is done in 32Bytes each entry */ + if ((mps_t > 64U) && ((mps_t % 32U) != 0U)) + { + /* Align the mps to 32byte block to match the allocation in PMA, + check Definition of allocation buffer memory in usb user spec */ + mps_t = (uint16_t)(((mps_t / 32U) + 1U) * 32U); + } + + /* Calculate the number of needed block to Free */ + if ((mps_t / 8U) != 0U) + { + block_nbr = ((uint32_t)mps_t / 8U); + + if ((mps_t % 8U) != 0U) + { + block_nbr++; + } + } + else + { + block_nbr = 1U; + } + + /* Decode Col/Line of PMA_Base position in the PMA_LookupTable */ + if (pma_base > 256U) + { + LineIndex = (uint8_t)(pma_base / 256U); + ColIndex = (uint8_t)((pma_base - ((uint32_t)LineIndex * 256U)) / 8U); + } + else + { + LineIndex = 0U; + ColIndex = (uint8_t)(pma_base / 8U); + } + + /* Reset the corresponding bit in the lookupTable */ + for (uint8_t i = LineIndex; ((i < PMA_BLOCKS) && (block_nbr > 0U)); i++) + { + for (uint8_t j = ColIndex; j <= 31U; j++) + { + /* Check if the block is not already reserved or it was already closed */ + if ((hhcd->PMALookupTable[i] & ((uint32_t)1U << j)) == 0U) + { + return HAL_ERROR; + } + /* Free the reserved block by resetting the corresponding bit */ + hhcd->PMALookupTable[i] &= ~(1U << j); + + if (--block_nbr == 0U) + { + break; + } + } + ColIndex = 0U; + } + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ +#endif /* HAL_HCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c.c index f650441a3..6816bc698 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c.c @@ -90,7 +90,7 @@ add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. @@ -156,7 +156,7 @@ HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA() (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() @@ -214,7 +214,7 @@ add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. @@ -1385,6 +1385,8 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData uint32_t Timeout) { uint32_t tickstart; + uint16_t tmpXferCount; + HAL_StatusTypeDef error; if (hi2c->State == HAL_I2C_STATE_READY) { @@ -1411,14 +1413,6 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData /* Enable Address Acknowledge */ hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - /* Preload TX data if no stretch enable */ if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) { @@ -1432,6 +1426,18 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData hi2c->XferCount--; } + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + return HAL_ERROR; + } + /* Clear ADDR flag */ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); @@ -1443,6 +1449,10 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData { /* Disable Address Acknowledge */ hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + return HAL_ERROR; } @@ -1455,6 +1465,10 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData { /* Disable Address Acknowledge */ hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + return HAL_ERROR; } @@ -1478,31 +1492,48 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData } /* Wait until AF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != HAL_OK) + error = I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart); + + if (error != HAL_OK) { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; + /* Check that I2C transfer finished */ + /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ + /* Mean XferCount == 0 */ + + tmpXferCount = hi2c->XferCount; + if ((hi2c->ErrorCode == HAL_I2C_ERROR_AF) && (tmpXferCount == 0U)) + { + /* Reset ErrorCode to NONE */ + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + } + else + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } } + else + { + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); + /* Clear AF flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + /* Wait until STOP flag is set */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; - /* Wait until STOP flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } - return HAL_ERROR; + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); } - /* Clear STOP flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - /* Wait until BUSY flag is reset */ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK) { @@ -3332,22 +3363,6 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); } - /* Check if the maximum allowed number of trials has been reached */ - if (I2C_Trials == Trials) - { - /* Generate Stop */ - hi2c->Instance->CR2 |= I2C_CR2_STOP; - - /* Wait until STOPF flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - } - /* Increment Trials */ I2C_Trials++; } while (I2C_Trials < Trials); @@ -4571,7 +4586,7 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) } /** - * @brief Abort a master I2C IT or DMA process communication with Interrupt. + * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress Target device address: The device 7 bits address value @@ -4580,7 +4595,9 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) */ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) { - if (hi2c->Mode == HAL_I2C_MODE_MASTER) + HAL_I2C_ModeTypeDef tmp_mode = hi2c->Mode; + + if ((tmp_mode == HAL_I2C_MODE_MASTER) || (tmp_mode == HAL_I2C_MODE_MEM)) { /* Process Locked */ __HAL_LOCK(hi2c); @@ -5251,9 +5268,8 @@ static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint /* Call I2C Slave complete process */ I2C_ITSlaveCplt(hi2c, tmpITFlags); } - - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) { /* Check that I2C transfer finished */ /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ @@ -5682,9 +5698,8 @@ static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uin /* Call I2C Slave complete process */ I2C_ITSlaveCplt(hi2c, ITFlags); } - - if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) { /* Check that I2C transfer finished */ /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ @@ -6286,6 +6301,7 @@ static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) { uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1); uint32_t tmpITFlags = ITFlags; + uint32_t tmpoptions = hi2c->XferOptions; HAL_I2C_StateTypeDef tmpstate = hi2c->State; /* Clear STOP Flag */ @@ -6375,6 +6391,57 @@ static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) hi2c->ErrorCode |= HAL_I2C_ERROR_AF; } + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_IT_NACKI) != RESET)) + { + /* Check that I2C transfer finished */ + /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ + /* Mean XferCount == 0*/ + /* So clear Flag NACKF only */ + if (hi2c->XferCount == 0U) + { + if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) + /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for + Warning[Pa134]: left and right operands are identical */ + { + /* Call I2C Listen complete process */ + I2C_ITListenCplt(hi2c, tmpITFlags); + } + else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Last Byte is Transmitted */ + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + else + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + } + } + else + { + /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, hi2c->ErrorCode); + } + } + } + hi2c->Mode = HAL_I2C_MODE_NONE; hi2c->XferISR = NULL; @@ -6909,6 +6976,12 @@ static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uin { while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status) { + /* Check if an error is detected */ + if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { @@ -7020,16 +7093,18 @@ static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) + HAL_StatusTypeDef status = HAL_OK; + + while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) && (status == HAL_OK)) { /* Check if an error is detected */ if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; + status = HAL_ERROR; } /* Check if a STOPF is detected */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) && (status == HAL_OK)) { /* Check if an RXNE is pending */ /* Store Last receive data if any */ @@ -7037,19 +7112,14 @@ static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, { /* Return HAL_OK */ /* The Reading of data from RXDR will be done in caller function */ - return HAL_OK; + status = HAL_OK; } - else + + /* Check a no-acknowledge have been detected */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) { - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) - { - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - hi2c->ErrorCode = HAL_I2C_ERROR_AF; - } - else - { - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - } + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + hi2c->ErrorCode = HAL_I2C_ERROR_AF; /* Clear STOP Flag */ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); @@ -7063,12 +7133,16 @@ static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, /* Process Unlocked */ __HAL_UNLOCK(hi2c); - return HAL_ERROR; + status = HAL_ERROR; + } + else + { + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; } } /* Check for the Timeout */ - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + if ((((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) && (status == HAL_OK)) { if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET)) { @@ -7078,11 +7152,11 @@ static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, /* Process Unlocked */ __HAL_UNLOCK(hi2c); - return HAL_ERROR; + status = HAL_ERROR; } } } - return HAL_OK; + return status; } /** diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c_ex.c index bc9cf4c82..e209b5b97 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2c_ex.c @@ -184,6 +184,7 @@ HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_ /** * @} */ +#if defined(I2C_CR1_WUPEN) /** @defgroup I2CEx_Exported_Functions_Group2 WakeUp Mode Functions * @brief WakeUp Mode Functions @@ -279,6 +280,7 @@ HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp(I2C_HandleTypeDef *hi2c) /** * @} */ +#endif /* I2C_CR1_WUPEN */ /** @defgroup I2CEx_Exported_Functions_Group3 Fast Mode Plus Functions * @brief Fast Mode Plus Functions @@ -303,6 +305,8 @@ HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp(I2C_HandleTypeDef *hi2c) * on each one of the following pins PB6, PB7, PB8 and PB9. * @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability * can be enabled only by using I2C_FASTMODEPLUS_I2C1 parameter. + * @note For all I2C2 pins fast mode plus driving capability can be enabled + * only by using I2C_FASTMODEPLUS_I2C2 parameter. * @retval None */ void HAL_I2CEx_EnableFastModePlus(uint32_t ConfigFastModePlus) @@ -326,6 +330,8 @@ void HAL_I2CEx_EnableFastModePlus(uint32_t ConfigFastModePlus) * on each one of the following pins PB6, PB7, PB8 and PB9. * @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability * can be disabled only by using I2C_FASTMODEPLUS_I2C1 parameter. + * @note For all I2C2 pins fast mode plus driving capability can be disabled + * only by using I2C_FASTMODEPLUS_I2C2 parameter. * @retval None */ void HAL_I2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus) diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2s.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2s.c index 86d749016..181c7fafc 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2s.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_i2s.c @@ -757,15 +757,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uin return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -876,15 +875,14 @@ HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -974,15 +972,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1001,6 +998,8 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, hi2s->TxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable TXE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); @@ -1011,7 +1010,6 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1040,15 +1038,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1067,6 +1064,8 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u hi2s->RxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable RXNE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); @@ -1077,7 +1076,6 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1104,15 +1102,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1154,12 +1151,7 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Tx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_TXDMAEN)) @@ -1168,7 +1160,13 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } @@ -1195,15 +1193,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1251,12 +1248,7 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Rx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_RXDMAEN)) @@ -1265,7 +1257,13 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_iwdg.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_iwdg.c index d784f00ad..f060734d5 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_iwdg.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_iwdg.c @@ -97,7 +97,6 @@ the reload register @endverbatim - ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ @@ -125,7 +124,7 @@ the LSI_VALUE constant. The value of this constant can be changed by the user to take into account possible LSI clock period variations. The timeout value is multiplied by 1000 to be converted in milliseconds. - LSI startup time is also considered here by adding LSI_STARTUP_TIMEOUT + LSI startup time is also considered here by adding LSI_STARTUP_TIME converted in milliseconds. */ #define HAL_IWDG_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) #define IWDG_KERNEL_UPDATE_FLAGS (IWDG_SR_WVU | IWDG_SR_RVU | IWDG_SR_PVU) @@ -281,4 +280,3 @@ HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) /** * @} */ - diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd.c new file mode 100644 index 000000000..05de1d694 --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd.c @@ -0,0 +1,2241 @@ +/** + ****************************************************************************** + * @file stm32c0xx_hal_pcd.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 PCD 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 + (+++) __HAL_RCC_USB_CLK_ENABLE(); For USB Device FS peripheral + + (##) 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 PCD transmission and reception: + (##) HAL_PCD_Start(); + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_hal.h" + +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +/** @defgroup PCD PCD + * @brief PCD HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +#if defined (USB_DRD_FS) + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PCD_Private_Macros PCD Private Macros + * @{ + */ +#define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b)) +/** + * @} + */ + +/* Private functions prototypes ----------------------------------------------*/ +/** @defgroup PCD_Private_Functions PCD Private Functions + * @{ + */ + +static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd); +#if (USE_USB_DOUBLE_BUFFER == 1U) +static HAL_StatusTypeDef HAL_PCD_EP_DB_Transmit(PCD_HandleTypeDef *hpcd, PCD_EPTypeDef *ep, uint16_t wEPVal); +static uint16_t HAL_PCD_EP_DB_Receive(PCD_HandleTypeDef *hpcd, PCD_EPTypeDef *ep, uint16_t wEPVal); +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Functions PCD Exported Functions + * @{ + */ + +/** @defgroup PCD_Exported_Functions_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 initialize the associated handle. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) +{ + uint8_t i; + + /* Check the PCD handle allocation */ + if (hpcd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); + + if (hpcd->State == HAL_PCD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hpcd->Lock = HAL_UNLOCKED; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SOFCallback = HAL_PCD_SOFCallback; + hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback; + hpcd->ResetCallback = HAL_PCD_ResetCallback; + hpcd->SuspendCallback = HAL_PCD_SuspendCallback; + hpcd->ResumeCallback = HAL_PCD_ResumeCallback; + hpcd->ConnectCallback = HAL_PCD_ConnectCallback; + hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback; + hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; + hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; + hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; + hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; + hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; + hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; + + if (hpcd->MspInitCallback == NULL) + { + hpcd->MspInitCallback = HAL_PCD_MspInit; + } + + /* Init the low level hardware */ + hpcd->MspInitCallback(hpcd); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_PCD_MspInit(hpcd); +#endif /* (USE_HAL_PCD_REGISTER_CALLBACKS) */ + } + + hpcd->State = HAL_PCD_STATE_BUSY; + + /* Disable the Interrupts */ + __HAL_PCD_DISABLE(hpcd); + + /* Init endpoints structures */ + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + /* Init ep structure */ + hpcd->IN_ep[i].is_in = 1U; + hpcd->IN_ep[i].num = i; + /* Control until ep is activated */ + hpcd->IN_ep[i].type = EP_TYPE_CTRL; + hpcd->IN_ep[i].maxpacket = 0U; + hpcd->IN_ep[i].xfer_buff = 0U; + hpcd->IN_ep[i].xfer_len = 0U; + } + + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + hpcd->OUT_ep[i].is_in = 0U; + hpcd->OUT_ep[i].num = i; + /* Control until ep is activated */ + hpcd->OUT_ep[i].type = EP_TYPE_CTRL; + hpcd->OUT_ep[i].maxpacket = 0U; + hpcd->OUT_ep[i].xfer_buff = 0U; + hpcd->OUT_ep[i].xfer_len = 0U; + } + + /* Init Device */ + (void)USB_DevInit(hpcd->Instance, hpcd->Init); + + hpcd->USB_Address = 0U; + hpcd->State = HAL_PCD_STATE_READY; + + /* Activate LPM */ + if (hpcd->Init.lpm_enable == 1U) + { + (void)HAL_PCDEx_ActivateLPM(hpcd); + } + + 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 = HAL_PCD_STATE_BUSY; + + /* Stop Device */ + if (USB_StopDevice(hpcd->Instance) != HAL_OK) + { + return HAL_ERROR; + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + if (hpcd->MspDeInitCallback == NULL) + { + hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hpcd->MspDeInitCallback(hpcd); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_PCD_MspDeInit(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + hpcd->State = HAL_PCD_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initializes the PCD MSP. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes PCD MSP. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User USB PCD Callback + * To be used instead of the weak predefined callback + * @param hpcd USB PCD handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID + * @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID + * @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID + * @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID + * @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID + * @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID + * @arg @ref HAL_PCD_DISCONNECT_CB_ID USB PCD Disconnect callback ID + * @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd, + HAL_PCD_CallbackIDTypeDef CallbackID, + pPCD_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_PCD_SOF_CB_ID : + hpcd->SOFCallback = pCallback; + break; + + case HAL_PCD_SETUPSTAGE_CB_ID : + hpcd->SetupStageCallback = pCallback; + break; + + case HAL_PCD_RESET_CB_ID : + hpcd->ResetCallback = pCallback; + break; + + case HAL_PCD_SUSPEND_CB_ID : + hpcd->SuspendCallback = pCallback; + break; + + case HAL_PCD_RESUME_CB_ID : + hpcd->ResumeCallback = pCallback; + break; + + case HAL_PCD_CONNECT_CB_ID : + hpcd->ConnectCallback = pCallback; + break; + + case HAL_PCD_DISCONNECT_CB_ID : + hpcd->DisconnectCallback = pCallback; + break; + + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = pCallback; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hpcd->State == HAL_PCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = pCallback; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + return status; +} + +/** + * @brief Unregister an USB PCD Callback + * USB PCD callback is redirected to the weak predefined callback + * @param hpcd USB PCD handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID + * @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID + * @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID + * @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID + * @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID + * @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID + * @arg @ref HAL_PCD_DISCONNECT_CB_ID USB PCD Disconnect callback ID + * @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, HAL_PCD_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + /* Setup Legacy weak Callbacks */ + if (hpcd->State == HAL_PCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_PCD_SOF_CB_ID : + hpcd->SOFCallback = HAL_PCD_SOFCallback; + break; + + case HAL_PCD_SETUPSTAGE_CB_ID : + hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback; + break; + + case HAL_PCD_RESET_CB_ID : + hpcd->ResetCallback = HAL_PCD_ResetCallback; + break; + + case HAL_PCD_SUSPEND_CB_ID : + hpcd->SuspendCallback = HAL_PCD_SuspendCallback; + break; + + case HAL_PCD_RESUME_CB_ID : + hpcd->ResumeCallback = HAL_PCD_ResumeCallback; + break; + + case HAL_PCD_CONNECT_CB_ID : + hpcd->ConnectCallback = HAL_PCD_ConnectCallback; + break; + + case HAL_PCD_DISCONNECT_CB_ID : + hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback; + break; + + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = HAL_PCD_MspInit; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hpcd->State == HAL_PCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = HAL_PCD_MspInit; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + return status; +} + +/** + * @brief Register USB PCD Data OUT Stage Callback + * To be used instead of the weak HAL_PCD_DataOutStageCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Data OUT Stage Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataOutStageCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataOutStageCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Data OUT Stage Callback + * USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataOutStageCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; /* Legacy weak DataOutStageCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Data IN Stage Callback + * To be used instead of the weak HAL_PCD_DataInStageCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Data IN Stage Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataInStageCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataInStageCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Data IN Stage Callback + * USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataInStageCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; /* Legacy weak DataInStageCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Iso OUT incomplete Callback + * To be used instead of the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Iso OUT incomplete Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoOutIncpltCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOOUTIncompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Iso OUT incomplete Callback + * USB PCD Iso OUT incomplete Callback is redirected + * to the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; /* Legacy weak ISOOUTIncompleteCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Iso IN incomplete Callback + * To be used instead of the weak HAL_PCD_ISOINIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Iso IN incomplete Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoInIncpltCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOINIncompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Iso IN incomplete Callback + * USB PCD Iso IN incomplete Callback is redirected + * to the weak HAL_PCD_ISOINIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; /* Legacy weak ISOINIncompleteCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD BCD Callback + * To be used instead of the weak HAL_PCDEx_BCD_Callback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD BCD Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->BCDCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD BCD Callback + * USB BCD Callback is redirected to the weak HAL_PCDEx_BCD_Callback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; /* Legacy weak HAL_PCDEx_BCD_Callback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD LPM Callback + * To be used instead of the weak HAL_PCDEx_LPM_Callback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD LPM Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->LPMCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD LPM Callback + * USB LPM Callback is redirected to the weak HAL_PCDEx_LPM_Callback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; /* Legacy weak HAL_PCDEx_LPM_Callback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_Group2 Input and Output 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 device + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + __HAL_PCD_ENABLE(hpcd); + (void)USB_DevConnect(hpcd->Instance); + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Stop the USB device. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + __HAL_PCD_DISABLE(hpcd); + (void)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) +{ + uint32_t wIstr = USB_ReadInterrupts(hpcd->Instance); + + if ((wIstr & USB_ISTR_CTR) == USB_ISTR_CTR) + { + /* servicing of the endpoint correct transfer interrupt */ + /* clear of the CTR flag into the sub */ + (void)PCD_EP_ISR_Handler(hpcd); + + return; + } + + if ((wIstr & USB_ISTR_RESET) == USB_ISTR_RESET) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_RESET); + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ResetCallback(hpcd); +#else + HAL_PCD_ResetCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + (void)HAL_PCD_SetAddress(hpcd, 0U); + + return; + } + + if ((wIstr & USB_ISTR_PMAOVR) == USB_ISTR_PMAOVR) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_PMAOVR); + + return; + } + + if ((wIstr & USB_ISTR_ERR) == USB_ISTR_ERR) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ERR); + + return; + } + + if ((wIstr & USB_ISTR_WKUP) == USB_ISTR_WKUP) + { + hpcd->Instance->CNTR &= ~(USB_CNTR_SUSPRDY); + hpcd->Instance->CNTR &= ~(USB_CNTR_SUSPEN); + + if (hpcd->LPM_State == LPM_L1) + { + hpcd->LPM_State = LPM_L0; +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->LPMCallback(hpcd, PCD_LPM_L0_ACTIVE); +#else + HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L0_ACTIVE); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ResumeCallback(hpcd); +#else + HAL_PCD_ResumeCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_WKUP); + + return; + } + + if ((wIstr & USB_ISTR_SUSP) == USB_ISTR_SUSP) + { + /* Force low-power mode in the macrocell */ + hpcd->Instance->CNTR |= USB_CNTR_SUSPEN; + + /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SUSP); + + hpcd->Instance->CNTR |= USB_CNTR_SUSPRDY; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SuspendCallback(hpcd); +#else + HAL_PCD_SuspendCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + return; + } + + /* Handle LPM Interrupt */ + if ((wIstr & USB_ISTR_L1REQ) == USB_ISTR_L1REQ) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_L1REQ); + if (hpcd->LPM_State == LPM_L0) + { + /* Force suspend and low-power mode before going to L1 state*/ + hpcd->Instance->CNTR |= USB_CNTR_SUSPRDY; + hpcd->Instance->CNTR |= USB_CNTR_SUSPEN; + + hpcd->LPM_State = LPM_L1; + hpcd->BESL = ((uint32_t)hpcd->Instance->LPMCSR & USB_LPMCSR_BESL) >> 2; +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->LPMCallback(hpcd, PCD_LPM_L1_ACTIVE); +#else + HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L1_ACTIVE); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SuspendCallback(hpcd); +#else + HAL_PCD_SuspendCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + + return; + } + + if ((wIstr & USB_ISTR_SOF) == USB_ISTR_SOF) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SOF); + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SOFCallback(hpcd); +#else + HAL_PCD_SOFCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + return; + } + + if ((wIstr & USB_ISTR_ESOF) == USB_ISTR_ESOF) + { + /* clear ESOF flag in ISTR */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ESOF); + + return; + } +} + + +/** + * @brief Data OUT stage callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implemented in the user file + */ +} + +/** + * @brief Data IN stage callback + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_DataInStageCallback could be implemented in the user file + */ +} +/** + * @brief Setup stage callback + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_SetupStageCallback could be implemented in the user file + */ +} + +/** + * @brief USB Start Of Frame callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_SOFCallback could be implemented in the user file + */ +} + +/** + * @brief USB Reset callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ResetCallback could be implemented in the user file + */ +} + +/** + * @brief Suspend event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_SuspendCallback could be implemented in the user file + */ +} + +/** + * @brief Resume event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ResumeCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO OUT callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO IN callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ISOINIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Connection event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ConnectCallback could be implemented in the user file + */ +} + +/** + * @brief Disconnection event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_DisconnectCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_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 Connect the USB device + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + (void)USB_DevConnect(hpcd->Instance); + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Disconnect the USB device. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + (void)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); + hpcd->USB_Address = address; + (void)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 packet 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; + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80U) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + + ep->num = ep_addr & EP_ADDR_MSK; + ep->maxpacket = (uint32_t)ep_mps & 0x7FFU; + ep->type = ep_type; + + /* Set initial data PID. */ + if (ep_type == EP_TYPE_BULK) + { + ep->data_pid_start = 0U; + } + + __HAL_LOCK(hpcd); + (void)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) +{ + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80U) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + ep->num = ep_addr & EP_ADDR_MSK; + + __HAL_LOCK(hpcd); + (void)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) +{ + PCD_EPTypeDef *ep; + + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0U; + ep->is_in = 0U; + ep->num = ep_addr & EP_ADDR_MSK; + + (void)USB_EPStartXfer(hpcd->Instance, ep); + + return HAL_OK; +} + +/** + * @brief Get Received Data Size + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval Data Size + */ +uint32_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef const *hpcd, uint8_t ep_addr) +{ + return hpcd->OUT_ep[ep_addr & EP_ADDR_MSK].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) +{ + PCD_EPTypeDef *ep; + + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_fill_db = 1U; + ep->xfer_len_db = len; + ep->xfer_count = 0U; + ep->is_in = 1U; + ep->num = ep_addr & EP_ADDR_MSK; + + (void)USB_EPStartXfer(hpcd->Instance, ep); + + 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) +{ + PCD_EPTypeDef *ep; + + if (((uint32_t)ep_addr & EP_ADDR_MSK) > hpcd->Init.dev_endpoints) + { + return HAL_ERROR; + } + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + ep->is_in = 0U; + } + + ep->is_stall = 1U; + ep->num = ep_addr & EP_ADDR_MSK; + + __HAL_LOCK(hpcd); + + (void)USB_EPSetStall(hpcd->Instance, ep); + + __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) +{ + PCD_EPTypeDef *ep; + + if (((uint32_t)ep_addr & 0x0FU) > hpcd->Init.dev_endpoints) + { + return HAL_ERROR; + } + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + + ep->is_stall = 0U; + ep->num = ep_addr & EP_ADDR_MSK; + + __HAL_LOCK(hpcd); + (void)USB_EPClearStall(hpcd->Instance, ep); + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Abort an USB EP transaction. + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + HAL_StatusTypeDef ret; + PCD_EPTypeDef *ep; + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + } + + /* Stop Xfer */ + ret = USB_EPStopXfer(hpcd->Instance, ep); + + return ret; +} + +/** + * @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 & 0x80U) == 0x80U) + { + (void)USB_FlushTxFifo(hpcd->Instance, (uint32_t)ep_addr & EP_ADDR_MSK); + } + else + { + (void)USB_FlushRxFifo(hpcd->Instance); + } + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Activate remote wakeup signalling + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + return (USB_ActivateRemoteWakeup(hpcd->Instance)); +} + +/** + * @brief De-activate remote wakeup signalling. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + return (USB_DeActivateRemoteWakeup(hpcd->Instance)); +} + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_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. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PCD handle state. + * @param hpcd PCD handle + * @retval HAL state + */ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef const *hpcd) +{ + return hpcd->State; +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup PCD_Private_Functions + * @{ + */ + + +/** + * @brief This function handles PCD Endpoint interrupt request. + * @param hpcd PCD handle + * @retval HAL status + */ +static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) +{ + PCD_EPTypeDef *ep; + uint16_t count; + uint16_t wIstr; + uint16_t wEPVal; + uint16_t TxPctSize; + uint8_t epindex; + +#if (USE_USB_DOUBLE_BUFFER != 1U) + count = 0U; +#endif /* USE_USB_DOUBLE_BUFFER */ + + /* stay in loop while pending interrupts */ + while ((hpcd->Instance->ISTR & USB_ISTR_CTR) != 0U) + { + wIstr = (uint16_t)hpcd->Instance->ISTR; + + /* extract highest priority endpoint number */ + epindex = (uint8_t)(wIstr & USB_ISTR_IDN); + + if (epindex == 0U) + { + /* Decode and service control endpoint interrupt */ + + /* DIR bit = origin of the interrupt */ + if ((wIstr & USB_ISTR_DIR) == 0U) + { + /* DIR = 0 */ + + /* DIR = 0 => IN int */ + /* DIR = 0 implies that (EP_CTR_TX = 1) always */ + PCD_CLEAR_TX_EP_CTR(hpcd->Instance, PCD_ENDP0); + ep = &hpcd->IN_ep[0]; + + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + ep->xfer_buff += ep->xfer_count; + + /* TX COMPLETE */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, 0U); +#else + HAL_PCD_DataInStageCallback(hpcd, 0U); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + if ((hpcd->USB_Address > 0U) && (ep->xfer_len == 0U)) + { + hpcd->Instance->DADDR = ((uint16_t)hpcd->USB_Address | USB_DADDR_EF); + hpcd->USB_Address = 0U; + } + } + else + { + /* DIR = 1 */ + + /* DIR = 1 & CTR_RX => SETUP or OUT int */ + /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ + ep = &hpcd->OUT_ep[0]; + wEPVal = (uint16_t)PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0); + + if ((wEPVal & USB_EP_SETUP) != 0U) + { + /* Get SETUP Packet */ + ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + + USB_ReadPMA(hpcd->Instance, (uint8_t *)hpcd->Setup, + ep->pmaadress, (uint16_t)ep->xfer_count); + + /* SETUP bit kept frozen while CTR_RX = 1 */ + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); + + /* Process SETUP Packet*/ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SetupStageCallback(hpcd); +#else + HAL_PCD_SetupStageCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else if ((wEPVal & USB_EP_VTRX) != 0U) + { + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); + + /* Get Control Data OUT Packet */ + ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + + if ((ep->xfer_count != 0U) && (ep->xfer_buff != 0U)) + { + USB_ReadPMA(hpcd->Instance, ep->xfer_buff, + ep->pmaadress, (uint16_t)ep->xfer_count); + + ep->xfer_buff += ep->xfer_count; + + /* Process Control Data OUT Packet */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, 0U); +#else + HAL_PCD_DataOutStageCallback(hpcd, 0U); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + + wEPVal = (uint16_t)PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0); + + if (((wEPVal & USB_EP_SETUP) == 0U) && ((wEPVal & USB_EP_RX_STRX) != USB_EP_RX_VALID)) + { + PCD_SET_EP_RX_CNT(hpcd->Instance, PCD_ENDP0, ep->maxpacket); + PCD_SET_EP_RX_STATUS(hpcd->Instance, PCD_ENDP0, USB_EP_RX_VALID); + } + } + } + } + else + { + /* Decode and service non control endpoints interrupt */ + /* process related endpoint register */ + wEPVal = (uint16_t)PCD_GET_ENDPOINT(hpcd->Instance, epindex); + + if ((wEPVal & USB_EP_VTRX) != 0U) + { + /* clear int flag */ + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, epindex); + ep = &hpcd->OUT_ep[epindex]; + + /* OUT Single Buffering */ + if (ep->doublebuffer == 0U) + { + count = (uint16_t)PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + + if (count != 0U) + { + USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, count); + } + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else + { + /* manage double buffer bulk out */ + if (ep->type == EP_TYPE_BULK) + { + count = HAL_PCD_EP_DB_Receive(hpcd, ep, wEPVal); + } + else /* manage double buffer iso out */ + { + /* free EP OUT Buffer */ + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 0U); + + if ((PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_RX) != 0U) + { + /* read from endpoint BUF0Addr buffer */ + count = (uint16_t)PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + + if (count != 0U) + { + USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count); + } + } + else + { + /* read from endpoint BUF1Addr buffer */ + count = (uint16_t)PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + + if (count != 0U) + { + USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count); + } + } + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* multi-packet on the NON control OUT endpoint */ + ep->xfer_count += count; + ep->xfer_buff += count; + + if ((ep->xfer_len == 0U) || (count < ep->maxpacket)) + { + /* RX COMPLETE */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, ep->num); +#else + HAL_PCD_DataOutStageCallback(hpcd, ep->num); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { + (void)USB_EPStartXfer(hpcd->Instance, ep); + } + } + + if ((wEPVal & USB_EP_VTTX) != 0U) + { + ep = &hpcd->IN_ep[epindex]; + + /* clear int flag */ + PCD_CLEAR_TX_EP_CTR(hpcd->Instance, epindex); + + if (ep->type == EP_TYPE_ISOC) + { + ep->xfer_len = 0U; + +#if (USE_USB_DOUBLE_BUFFER == 1U) + if (ep->doublebuffer != 0U) + { + if ((wEPVal & USB_EP_DTOG_TX) != 0U) + { + PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, 0U); + } + else + { + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, 0U); + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* TX COMPLETE */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, ep->num); +#else + HAL_PCD_DataInStageCallback(hpcd, ep->num); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { + /* Manage Single Buffer Transaction */ + if ((wEPVal & USB_EP_KIND) == 0U) + { + /* multi-packet on the NON control IN endpoint */ + TxPctSize = (uint16_t)PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_len > TxPctSize) + { + ep->xfer_len -= TxPctSize; + } + else + { + ep->xfer_len = 0U; + } + + /* Zero Length Packet? */ + if (ep->xfer_len == 0U) + { + /* TX COMPLETE */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, ep->num); +#else + HAL_PCD_DataInStageCallback(hpcd, ep->num); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { + /* Transfer is not yet Done */ + ep->xfer_buff += TxPctSize; + ep->xfer_count += TxPctSize; + (void)USB_EPStartXfer(hpcd->Instance, ep); + } + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + /* Double Buffer bulk IN (bulk transfer Len > Ep_Mps) */ + else + { + (void)HAL_PCD_EP_DB_Transmit(hpcd, ep, wEPVal); + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + } + } + } + } + + return HAL_OK; +} + + +#if (USE_USB_DOUBLE_BUFFER == 1U) +/** + * @brief Manage double buffer bulk out transaction from ISR + * @param hpcd PCD handle + * @param ep current endpoint handle + * @param wEPVal Last snapshot of EPRx register value taken in ISR + * @retval HAL status + */ +static uint16_t HAL_PCD_EP_DB_Receive(PCD_HandleTypeDef *hpcd, + PCD_EPTypeDef *ep, uint16_t wEPVal) +{ + uint16_t count; + + /* Manage Buffer0 OUT */ + if ((wEPVal & USB_EP_DTOG_RX) != 0U) + { + /* Get count of received Data on buffer0 */ + count = (uint16_t)PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_len >= count) + { + ep->xfer_len -= count; + } + else + { + ep->xfer_len = 0U; + } + + if (ep->xfer_len == 0U) + { + /* set NAK to OUT endpoint since double buffer is enabled */ + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_NAK); + } + + /* Check if Buffer1 is in blocked state which requires to toggle */ + if ((wEPVal & USB_EP_DTOG_TX) != 0U) + { + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 0U); + } + + if (count != 0U) + { + USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count); + } + } + /* Manage Buffer 1 DTOG_RX=0 */ + else + { + /* Get count of received data */ + count = (uint16_t)PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_len >= count) + { + ep->xfer_len -= count; + } + else + { + ep->xfer_len = 0U; + } + + if (ep->xfer_len == 0U) + { + /* set NAK on the current endpoint */ + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_NAK); + } + + /*Need to FreeUser Buffer*/ + if ((wEPVal & USB_EP_DTOG_TX) == 0U) + { + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 0U); + } + + if (count != 0U) + { + USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count); + } + } + + return count; +} + + +/** + * @brief Manage double buffer bulk IN transaction from ISR + * @param hpcd PCD handle + * @param ep current endpoint handle + * @param wEPVal Last snapshot of EPRx register value taken in ISR + * @retval HAL status + */ +static HAL_StatusTypeDef HAL_PCD_EP_DB_Transmit(PCD_HandleTypeDef *hpcd, + PCD_EPTypeDef *ep, uint16_t wEPVal) +{ + uint32_t len; + uint16_t TxPctSize; + + /* Data Buffer0 ACK received */ + if ((wEPVal & USB_EP_DTOG_TX) != 0U) + { + /* multi-packet on the NON control IN endpoint */ + TxPctSize = (uint16_t)PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_len > TxPctSize) + { + ep->xfer_len -= TxPctSize; + } + else + { + ep->xfer_len = 0U; + } + + /* Transfer is completed */ + if (ep->xfer_len == 0U) + { + PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, 0U); + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, 0U); + + /* TX COMPLETE */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, ep->num); +#else + HAL_PCD_DataInStageCallback(hpcd, ep->num); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + if ((wEPVal & USB_EP_DTOG_RX) != 0U) + { + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U); + } + } + else /* Transfer is not yet Done */ + { + /* need to Free USB Buff */ + if ((wEPVal & USB_EP_DTOG_RX) != 0U) + { + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U); + } + + /* Still there is data to Fill in the next Buffer */ + if (ep->xfer_fill_db == 1U) + { + ep->xfer_buff += TxPctSize; + ep->xfer_count += TxPctSize; + + /* Calculate the len of the new buffer to fill */ + if (ep->xfer_len_db >= ep->maxpacket) + { + len = ep->maxpacket; + ep->xfer_len_db -= len; + } + else if (ep->xfer_len_db == 0U) + { + len = TxPctSize; + ep->xfer_fill_db = 0U; + } + else + { + ep->xfer_fill_db = 0U; + len = ep->xfer_len_db; + ep->xfer_len_db = 0U; + } + + /* Write remaining Data to Buffer */ + /* Set the Double buffer counter for pma buffer1 */ + PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, len); + + /* Copy user buffer to USB PMA */ + USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, (uint16_t)len); + } + } + } + else /* Data Buffer1 ACK received */ + { + /* multi-packet on the NON control IN endpoint */ + TxPctSize = (uint16_t)PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_len >= TxPctSize) + { + ep->xfer_len -= TxPctSize; + } + else + { + ep->xfer_len = 0U; + } + + /* Transfer is completed */ + if (ep->xfer_len == 0U) + { + PCD_SET_EP_DBUF0_CNT(hpcd->Instance, ep->num, ep->is_in, 0U); + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, 0U); + + /* TX COMPLETE */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, ep->num); +#else + HAL_PCD_DataInStageCallback(hpcd, ep->num); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + /* need to Free USB Buff */ + if ((wEPVal & USB_EP_DTOG_RX) == 0U) + { + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U); + } + } + else /* Transfer is not yet Done */ + { + /* need to Free USB Buff */ + if ((wEPVal & USB_EP_DTOG_RX) == 0U) + { + PCD_FREE_USER_BUFFER(hpcd->Instance, ep->num, 1U); + } + + /* Still there is data to Fill in the next Buffer */ + if (ep->xfer_fill_db == 1U) + { + ep->xfer_buff += TxPctSize; + ep->xfer_count += TxPctSize; + + /* Calculate the len of the new buffer to fill */ + if (ep->xfer_len_db >= ep->maxpacket) + { + len = ep->maxpacket; + ep->xfer_len_db -= len; + } + else if (ep->xfer_len_db == 0U) + { + len = TxPctSize; + ep->xfer_fill_db = 0U; + } + else + { + len = ep->xfer_len_db; + ep->xfer_len_db = 0U; + ep->xfer_fill_db = 0; + } + + /* Set the Double buffer counter for pmabuffer1 */ + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, len); + + /* Copy the user buffer to USB PMA */ + USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, (uint16_t)len); + } + } + } + + /*enable endpoint IN*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_VALID); + + return HAL_OK; +} +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ +#endif /* HAL_PCD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd_ex.c new file mode 100644 index 000000000..f15a393d9 --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pcd_ex.c @@ -0,0 +1,331 @@ +/** + ****************************************************************************** + * @file stm32c0xx_hal_pcd_ex.c + * @author MCD Application Team + * @brief PCD Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Extended features functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_hal.h" + +/** @addtogroup STM32C0xx_HAL_Driver + * @{ + */ + +/** @defgroup PCDEx PCDEx + * @brief PCD Extended HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +#if defined (USB_DRD_FS) +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions + * @{ + */ + +/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions + * @brief PCDEx control functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Update FIFO configuration + +@endverbatim + * @{ + */ + +/** + * @brief Configure PMA for EP + * @param hpcd Device instance + * @param ep_addr endpoint address + * @param ep_kind endpoint Kind + * USB_SNG_BUF: Single Buffer used + * USB_DBL_BUF: Double Buffer used + * @param pmaadress: EP address in The PMA: In case of single buffer endpoint + * this parameter is 16-bit value providing the address + * in PMA allocated to endpoint. + * In case of double buffer endpoint this parameter + * is a 32-bit value providing the endpoint buffer 0 address + * in the LSB part of 32-bit value and endpoint buffer 1 address + * in the MSB part of 32-bit value. + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr, + uint16_t ep_kind, uint32_t pmaadress) +{ + PCD_EPTypeDef *ep; + + /* initialize ep structure*/ + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + /* Here we check if the endpoint is single or double Buffer*/ + if (ep_kind == PCD_SNG_BUF) + { + /* Single Buffer */ + ep->doublebuffer = 0U; + /* Configure the PMA */ + ep->pmaadress = (uint16_t)pmaadress; + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else /* USB_DBL_BUF */ + { + /* Double Buffer Endpoint */ + ep->doublebuffer = 1U; + /* Configure the PMA */ + ep->pmaaddr0 = (uint16_t)(pmaadress & 0xFFFFU); + ep->pmaaddr1 = (uint16_t)((pmaadress & 0xFFFF0000U) >> 16); + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + return HAL_OK; +} + +/** + * @brief Activate BatteryCharging feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd) +{ + USB_DRD_TypeDef *USBx = hpcd->Instance; + hpcd->battery_charging_active = 1U; + + /* Enable BCD feature */ + USBx->BCDR |= USB_BCDR_BCDEN; + + /* Enable DCD : Data Contact Detect */ + USBx->BCDR &= ~(USB_BCDR_PDEN); + USBx->BCDR &= ~(USB_BCDR_SDEN); + USBx->BCDR |= USB_BCDR_DCDEN; + + return HAL_OK; +} + +/** + * @brief Deactivate BatteryCharging feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd) +{ + USB_DRD_TypeDef *USBx = hpcd->Instance; + hpcd->battery_charging_active = 0U; + + /* Disable BCD feature */ + USBx->BCDR &= ~(USB_BCDR_BCDEN); + + return HAL_OK; +} + +/** + * @brief Handle BatteryCharging Process. + * @param hpcd PCD handle + * @retval HAL status + */ +void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd) +{ + USB_DRD_TypeDef *USBx = hpcd->Instance; + uint32_t tickstart = HAL_GetTick(); + + /* Wait for Min DCD Timeout */ + HAL_Delay(300U); + + /* Data Pin Contact ? Check Detect flag */ + if ((USBx->BCDR & USB_BCDR_DCDET) == USB_BCDR_DCDET) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_CONTACT_DETECTION); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CONTACT_DETECTION); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + /* Primary detection: checks if connected to Standard Downstream Port + (without charging capability) */ + USBx->BCDR &= ~(USB_BCDR_DCDEN); + HAL_Delay(50U); + USBx->BCDR |= (USB_BCDR_PDEN); + HAL_Delay(50U); + + /* If Charger detect ? */ + if ((USBx->BCDR & USB_BCDR_PDET) == USB_BCDR_PDET) + { + /* Start secondary detection to check connection to Charging Downstream + Port or Dedicated Charging Port */ + USBx->BCDR &= ~(USB_BCDR_PDEN); + HAL_Delay(50U); + USBx->BCDR |= (USB_BCDR_SDEN); + HAL_Delay(50U); + + /* If CDP ? */ + if ((USBx->BCDR & USB_BCDR_SDET) == USB_BCDR_SDET) + { + /* Dedicated Downstream Port DCP */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { + /* Charging Downstream Port CDP */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + else /* NO */ + { + /* Standard Downstream Port */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + + /* Battery Charging capability discovery finished Start Enumeration */ + (void)HAL_PCDEx_DeActivateBCD(hpcd); + + /* Check for the Timeout, else start USB Device */ + if ((HAL_GetTick() - tickstart) > 1000U) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_ERROR); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_ERROR); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_DISCOVERY_COMPLETED); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DISCOVERY_COMPLETED); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Activate LPM feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd) +{ + + USB_DRD_TypeDef *USBx = hpcd->Instance; + hpcd->lpm_active = 1U; + hpcd->LPM_State = LPM_L0; + + USBx->LPMCSR |= USB_LPMCSR_LMPEN; + USBx->LPMCSR |= USB_LPMCSR_LPMACK; + + return HAL_OK; +} + +/** + * @brief Deactivate LPM feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd) +{ + USB_DRD_TypeDef *USBx = hpcd->Instance; + + hpcd->lpm_active = 0U; + + USBx->LPMCSR &= ~(USB_LPMCSR_LMPEN); + USBx->LPMCSR &= ~(USB_LPMCSR_LPMACK); + + return HAL_OK; +} + + +/** + * @brief Send LPM message to user layer callback. + * @param hpcd PCD handle + * @param msg LPM message + * @retval HAL status + */ +__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(msg); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCDEx_LPM_Callback could be implemented in the user file + */ +} + +/** + * @brief Send BatteryCharging message to user layer callback. + * @param hpcd PCD handle + * @param msg LPM message + * @retval HAL status + */ +__weak void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(msg); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCDEx_BCD_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ +#endif /* HAL_PCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr.c index ed159c6df..d86ef7dd8 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr.c @@ -185,22 +185,23 @@ void HAL_PWR_DeInit(void) * @{ */ - /** * @brief Enable the WakeUp PINx functionality. * @param WakeUpPinPolarity Specifies which Wake-Up pin to enable. * This parameter can be one of the following legacy values which set * the default polarity i.e. detection on high level (rising edge): * @arg @ref PWR_WAKEUP_PIN1, PWR_WAKEUP_PIN2, PWR_WAKEUP_PIN3, - * PWR_WAKEUP_PIN4, PWR_WAKEUP_PIN6 + * PWR_WAKEUP_PIN4, PWR_WAKEUP_PIN5 (Only on STM32C071xx), PWR_WAKEUP_PIN6 * or one of the following value where the user can explicitly specify * the enabled pin and the chosen polarity: * @arg @ref PWR_WAKEUP_PIN1_HIGH or PWR_WAKEUP_PIN1_LOW * @arg @ref PWR_WAKEUP_PIN2_HIGH or PWR_WAKEUP_PIN2_LOW * @arg @ref PWR_WAKEUP_PIN3_HIGH or PWR_WAKEUP_PIN3_LOW * @arg @ref PWR_WAKEUP_PIN4_HIGH or PWR_WAKEUP_PIN4_LOW + * @arg @ref PWR_WAKEUP_PIN5_HIGH or PWR_WAKEUP_PIN5_LOW (*) * @arg @ref PWR_WAKEUP_PIN6_HIGH or PWR_WAKEUP_PIN6_LOW * @note PWR_WAKEUP_PINx and PWR_WAKEUP_PINx_HIGH are equivalent. + * @note (*) Availability depends on devices * @retval None */ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinPolarity) @@ -215,13 +216,13 @@ void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinPolarity) SET_BIT(PWR->CR3, (PWR_CR3_EWUP & WakeUpPinPolarity)); } - /** * @brief Disable the WakeUp PINx functionality. * @param WakeUpPinx Specifies the Power Wake-Up pin to disable. * This parameter can be one of the following values: - * @arg @ref PWR_WAKEUP_PIN1, PWR_WAKEUP_PIN2, PWR_WAKEUP_PIN4, - * PWR_WAKEUP_PIN6 + * @arg @ref PWR_WAKEUP_PIN1, PWR_WAKEUP_PIN2, PWR_WAKEUP_PIN3, + * PWR_WAKEUP_PIN4, PWR_WAKEUP_PIN5 (*), PWR_WAKEUP_PIN6 + * @note (*) Availability depends on devices * @retval None */ void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) @@ -231,7 +232,6 @@ void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) CLEAR_BIT(PWR->CR3, (PWR_CR3_EWUP & WakeUpPinx)); } - /** * @brief Enter Sleep mode. * @note In Sleep mode, all I/O pins keep the same state as @@ -273,7 +273,6 @@ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) } } - /** * @brief Enter Stop mode * @note This API is named HAL_PWR_EnterSTOPMode to ensure compatibility with @@ -327,7 +326,6 @@ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); } - /** * @brief Enter Standby mode. * @note In Standby mode,the HSI and the HSE oscillators are @@ -354,7 +352,6 @@ void HAL_PWR_EnterSTANDBYMode(void) __WFI(); } - /** * @brief Enable Sleep-On-Exit Cortex feature * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the @@ -370,7 +367,6 @@ void HAL_PWR_EnableSleepOnExit(void) SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); } - /** * @brief Disable Sleep-On-Exit Cortex feature * @note Clear SLEEPONEXIT bit of SCR register. When this bit is set, the @@ -384,7 +380,6 @@ void HAL_PWR_DisableSleepOnExit(void) CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk)); } - /** * @brief Enable Cortex Sev On Pending feature. * @note Set SEVONPEND bit of SCR register. When this bit is set, enabled @@ -398,7 +393,6 @@ void HAL_PWR_EnableSEVOnPend(void) SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk)); } - /** * @brief Disable Cortex Sev On Pending feature. * @note Clear SEVONPEND bit of SCR register. When this bit is clear, only diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr_ex.c index d2afef4b7..ba7e46fe3 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_pwr_ex.c @@ -73,6 +73,89 @@ * @{ */ +#if defined (PWR_PVM_SUPPORT) +/** + * @brief Enable the Power Voltage Monitoring for USB peripheral (power domain Vddio2) + * @retval None + */ +void HAL_PWREx_EnablePVMUSB(void) +{ + SET_BIT(PWR->CR2, PWR_CR2_PVM_VDDIO2_0); +} + +/** + * @brief Disable the Power Voltage Monitoring for USB peripheral (power domain Vddio2) + * @retval None + */ +void HAL_PWREx_DisablePVMUSB(void) +{ + CLEAR_BIT(PWR->CR2, PWR_CR2_PVM_VDDIO2_0); +} + +/** + * @brief Configure the Peripheral Voltage Monitoring (PVM). + * @param sConfigPVM: pointer to a PWR_PVMTypeDef structure that contains the + * PVM configuration information. + * @note The API configures a single PVM according to the information contained + * in the input structure. To configure several PVMs, the API must be singly + * called for each PVM used. + * @note Refer to the electrical characteristics of your device datasheet for + * more details about the voltage thresholds corresponding to each + * detection level and to each monitored supply. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PWREx_ConfigPVM(PWR_PVMTypeDef *sConfigPVM) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_PWR_PVM_TYPE(sConfigPVM->PVMType)); + assert_param(IS_PWR_PVM_MODE(sConfigPVM->Mode)); + + /* Configure EXTI 34 interrupts if so required: + scan through PVMType to detect which PVMx is set and + configure the corresponding EXTI line accordingly. */ + switch (sConfigPVM->PVMType) + { + case PWR_PVM_USB: + /* Clear any previous config. Keep it clear if no event or IT mode is selected */ + __HAL_PWR_PVM_EXTI_DISABLE_EVENT(); + __HAL_PWR_PVM_EXTI_DISABLE_IT(); + __HAL_PWR_PVM_EXTI_DISABLE_FALLING_EDGE(); + __HAL_PWR_PVM_EXTI_DISABLE_RISING_EDGE(); + + /* Configure interrupt mode */ + if ((sConfigPVM->Mode & PVM_MODE_IT) == PVM_MODE_IT) + { + __HAL_PWR_PVM_EXTI_ENABLE_IT(); + } + + /* Configure event mode */ + if ((sConfigPVM->Mode & PVM_MODE_EVT) == PVM_MODE_EVT) + { + __HAL_PWR_PVM_EXTI_ENABLE_EVENT(); + } + + /* Configure the edge */ + if ((sConfigPVM->Mode & PVM_RISING_EDGE) == PVM_RISING_EDGE) + { + __HAL_PWR_PVM_EXTI_ENABLE_RISING_EDGE(); + } + + if ((sConfigPVM->Mode & PVM_FALLING_EDGE) == PVM_FALLING_EDGE) + { + __HAL_PWR_PVM_EXTI_ENABLE_FALLING_EDGE(); + } + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} +#endif /* PWR_PVM_SUPPORT */ /** * @brief Enable Internal Wake-up Line. * @retval None @@ -135,12 +218,12 @@ HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber) SET_BIT(PWR->PUCRC, GPIONumber); CLEAR_BIT(PWR->PDCRC, GPIONumber); break; -#if defined (STM32C031xx) +#if defined (GPIOD) case PWR_GPIO_D: SET_BIT(PWR->PUCRD, GPIONumber); CLEAR_BIT(PWR->PDCRD, GPIONumber); break; -#endif /* STM32C031xx */ +#endif /* GPIOD */ case PWR_GPIO_F: SET_BIT(PWR->PUCRF, GPIONumber); CLEAR_BIT(PWR->PDCRF, GPIONumber); @@ -188,11 +271,11 @@ HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullUp(uint32_t GPIO, uint32_t GPIONumber case PWR_GPIO_C: CLEAR_BIT(PWR->PUCRC, GPIONumber); break; -#if defined (STM32C031xx) +#if defined (GPIOD) case PWR_GPIO_D: CLEAR_BIT(PWR->PUCRD, GPIONumber); break; -#endif /* STM32C031xx */ +#endif /* GPIOD */ case PWR_GPIO_F: CLEAR_BIT(PWR->PUCRF, GPIONumber); break; @@ -248,12 +331,12 @@ HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumbe SET_BIT(PWR->PDCRC, GPIONumber); CLEAR_BIT(PWR->PUCRC, GPIONumber); break; -#if defined (STM32C031xx) +#if defined (GPIOD) case PWR_GPIO_D: SET_BIT(PWR->PDCRD, GPIONumber); CLEAR_BIT(PWR->PUCRD, GPIONumber); break; -#endif /* STM32C031xx */ +#endif /* GPIOD */ case PWR_GPIO_F: SET_BIT(PWR->PDCRF, GPIONumber); CLEAR_BIT(PWR->PUCRF, GPIONumber); @@ -301,11 +384,11 @@ HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullDown(uint32_t GPIO, uint32_t GPIONumb case PWR_GPIO_C: CLEAR_BIT(PWR->PDCRC, GPIONumber); break; -#if defined (STM32C031xx) +#if defined (GPIOD) case PWR_GPIO_D: CLEAR_BIT(PWR->PDCRD, GPIONumber); break; -#endif /* STM32C031xx */ +#endif /* GPIOD */ case PWR_GPIO_F: CLEAR_BIT(PWR->PDCRF, GPIONumber); break; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc.c index ed063c4f2..ebfb5974c 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc.c @@ -68,6 +68,9 @@ #define RCC_HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT #define RCC_HSI_TIMEOUT_VALUE (2U) /* 2 ms (minimum Tick + 1) */ #define RCC_LSI_TIMEOUT_VALUE (2U) /* 2 ms (minimum Tick + 1) */ +#if defined(RCC_CR_HSIUSB48ON) +#define HSI48_TIMEOUT_VALUE (2U) /* 2 ms (minimum Tick + 1) */ +#endif /* RCC_CR_HSIUSB48ON */ #define RCC_CLOCKSWITCH_TIMEOUT_VALUE (5000U) /* 5 s */ /** @@ -185,7 +188,7 @@ * @note The default reset state of the clock configuration is given below: * - HSI ON and used as system clock source * - HSE OFF - * - AHB and APB prescaler set to 1. + * - SYSDIV, AHB and APB prescaler set to 1. * - CSS, MCO1, MCO2 OFF * - All interrupts disabled * @note This function does not modify the configuration of the @@ -545,6 +548,50 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(const RCC_OscInitTypeDef *RCC_OscInitStruct } } } +#if defined(RCC_CR_HSIUSB48ON) + /*------------------------------ HSI48 Configuration -----------------------*/ + if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48) + { + /* Check the parameters */ + assert_param(IS_RCC_HSI48(RCC_OscInitStruct->HSI48State)); + + /* Check the LSI State */ + if (RCC_OscInitStruct->HSI48State != RCC_HSI48_OFF) + { + /* Enable the Internal Low Speed oscillator (HSI48). */ + __HAL_RCC_HSI48_ENABLE(); + + /* Get Start Tick*/ + tickstart = HAL_GetTick(); + + /* Wait till HSI48 is ready */ + while (READ_BIT(RCC->CR, RCC_CR_HSIUSB48RDY) == 0U) + { + if ((HAL_GetTick() - tickstart) > HSI48_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal Low Speed oscillator (HSI48). */ + __HAL_RCC_HSI48_DISABLE(); + + /* Get Start Tick*/ + tickstart = HAL_GetTick(); + + /* Wait till HSI48 is disabled */ + while (READ_BIT(RCC->CR, RCC_CR_HSIUSB48RDY) != 0U) + { + if ((HAL_GetTick() - tickstart) > HSI48_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } +#endif /* RCC_CR_HSIUSB48ON */ return HAL_OK; } @@ -643,7 +690,10 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *RCC_ClkInitStru { assert_param(IS_RCC_SYSCLK(RCC_ClkInitStruct->SYSCLKDivider)); assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource)); + +#if defined(RCC_CR_SYSDIV) MODIFY_REG(RCC->CR, RCC_CR_SYSDIV, RCC_ClkInitStruct->SYSCLKDivider); +#endif /* RCC_CR_SYSDIV */ /* HSE is selected as System Clock Source */ if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) @@ -663,6 +713,17 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *RCC_ClkInitStru return HAL_ERROR; } } +#if defined(RCC_HSI48_SUPPORT) + /* HSIUSB48 is selected as System Clock Source */ + else if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSIUSB48) + { + /* Check the HSIUSB48 ready flag */ + if (READ_BIT(RCC->CR, RCC_CR_HSIUSB48RDY) == 0U) + { + return HAL_ERROR; + } + } +#endif /* RCC_HSI48_SUPPORT */ /* LSI is selected as System Clock Source */ else if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_LSI) { @@ -722,7 +783,8 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *RCC_ClkInitStru } /* Update the SystemCoreClock global variable */ - SystemCoreClock = (HAL_RCC_GetSysClockFreq() >> ((AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos]) & 0x1FU)); + SystemCoreClock = (HAL_RCC_GetSysClockFreq() >> ((AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) \ + >> RCC_CFGR_HPRE_Pos]) & 0x1FU)); /* Configure the source of time base considering new system clocks settings*/ return HAL_InitTick(uwTickPrio); @@ -761,12 +823,14 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *RCC_ClkInitStru * @arg @ref RCC_MCO1SOURCE_NOCLOCK MCO1 output disabled, no clock on MCO1 * @arg @ref RCC_MCO1SOURCE_SYSCLK system clock selected as MCO1 source * @arg @ref RCC_MCO1SOURCE_HSI HSI clock selected as MCO1 source + * @arg @ref RCC_MCO1SOURCE_HSI48 HSI48 clock selected as MCO1 source (*) * @arg @ref RCC_MCO1SOURCE_HSE HSE clock selected as MCO1 source * @arg @ref RCC_MCO1SOURCE_LSI LSI clock selected as MCO1 source * @arg @ref RCC_MCO1SOURCE_LSE LSE clock selected as MCO1 source * @arg @ref RCC_MCO2SOURCE_NOCLOCK MCO2 output disabled, no clock on MCO2 * @arg @ref RCC_MCO2SOURCE_SYSCLK system clock selected as MCO2 source * @arg @ref RCC_MCO2SOURCE_HSI HSI clock selected as MCO2 source + * @arg @ref RCC_MCO2SOURCE_HSI48 HSI48 clock selected as MCO2 source (*) * @arg @ref RCC_MCO2SOURCE_HSE HSE clock selected as MCO2 source * @arg @ref RCC_MCO2SOURCE_LSI LSI clock selected as MCO2 source * @arg @ref RCC_MCO2SOURCE_LSE LSE clock selected as MCO2 source @@ -780,6 +844,7 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(const RCC_ClkInitTypeDef *RCC_ClkInitStru * @arg @ref RCC_MCODIV_32 division by 32 applied to MCO clock * @arg @ref RCC_MCODIV_64 division by 64 applied to MCO clock * @arg @ref RCC_MCODIV_128 division by 128 applied to MCO clock + * @note (*) peripheral not available on all devices * @retval None */ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv) @@ -827,7 +892,9 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M LL_RCC_ConfigMCO2(RCC_MCOSource, RCC_MCODiv); } else - {} + { + /* unexpected case: added to resolve MISRA 15.7 rule */ + } } /** @@ -868,6 +935,9 @@ uint32_t HAL_RCC_GetSysClockFreq(void) { uint32_t hsidiv; uint32_t sysclockfreq; +#if defined(RCC_CR_SYSDIV) + uint32_t sysclockdiv = (uint32_t)(((RCC->CR & RCC_CR_SYSDIV) >> RCC_CR_SYSDIV_Pos) + 1U); +#endif /* RCC_CR_SYSDIV */ if (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI) { @@ -892,11 +962,20 @@ uint32_t HAL_RCC_GetSysClockFreq(void) /* LSI used as system clock source */ sysclockfreq = LSI_VALUE; } +#if defined(RCC_HSI48_SUPPORT) + else if (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI48) + { + /* HSI48 used as system clock source */ + sysclockfreq = HSI48_VALUE; + } +#endif /* RCC_HSI48_SUPPORT */ else { sysclockfreq = 0U; } - +#if defined(RCC_CR_SYSDIV) + sysclockfreq = sysclockfreq / sysclockdiv; +#endif /* RCC_CR_SYSDIV */ return sysclockfreq; } @@ -910,6 +989,8 @@ uint32_t HAL_RCC_GetSysClockFreq(void) */ uint32_t HAL_RCC_GetHCLKFreq(void) { + SystemCoreClock = (HAL_RCC_GetSysClockFreq() >> ((AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) \ + >> RCC_CFGR_HPRE_Pos]) & 0x1FU)); return SystemCoreClock; } @@ -940,9 +1021,13 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) assert_param(RCC_OscInitStruct != (void *)NULL); /* Set all possible values for the Oscillator type parameter ---------------*/ +#if defined(RCC_HSI48_SUPPORT) + RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | \ + RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_HSI48; +#else RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | \ RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI; - +#endif /* RCC_HSI48_SUPPORT */ /* Get Control register */ regval = RCC->CR; @@ -966,6 +1051,18 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /* Get the LSI configuration -----------------------------------------------*/ RCC_OscInitStruct->LSIState = regval & RCC_CSR2_LSION; +#if defined(RCC_HSI48_SUPPORT) + /* Get the HSI48 configuration ---------------------------------------------*/ + if (READ_BIT(RCC->CR, RCC_CR_HSIUSB48ON) == RCC_CR_HSIUSB48ON) + { + RCC_OscInitStruct->HSI48State = RCC_HSI48_ON; + } + else + { + RCC_OscInitStruct->HSI48State = RCC_HSI48_OFF; + } +#endif /* RCC_HSI48_SUPPORT */ + } /** @@ -988,6 +1085,11 @@ void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pF /* Get the SYSCLK configuration --------------------------------------------*/ RCC_ClkInitStruct->SYSCLKSource = (uint32_t)(RCC->CFGR & RCC_CFGR_SW); +#if defined(RCC_CR_SYSDIV) + /* Get the SYSCLK configuration ----------------------------------------------*/ + RCC_ClkInitStruct->SYSCLKDivider = (uint32_t)(RCC->CR & RCC_CR_SYSDIV); +#endif /* RCC_CR_SYSDIV */ + /* Get the HCLK configuration ----------------------------------------------*/ RCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_HPRE); diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc_ex.c index 5be27303a..547000a58 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rcc_ex.c @@ -84,8 +84,10 @@ * @arg @ref RCC_PERIPHCLK_I2C1 I2C1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2S1 I2S1 peripheral clock * @arg @ref RCC_PERIPHCLK_USART1 USART1 peripheral clock + * @arg @ref RCC_PERIPHCLK_USB USB peripheral clock (*) * @note Care must be taken when @ref HAL_RCCEx_PeriphCLKConfig() is used to select * the RTC clock source: in this case the access to RTC domain is enabled. + * @note (*) not available on all devices * * @retval HAL status */ @@ -195,7 +197,18 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(const RCC_PeriphCLKInitTypeDef *Per __HAL_RCC_ADC_CONFIG(PeriphClkInit->AdcClockSelection); } +#if defined (USB_DRD_FS) + /*-------------------------- USB clock source configuration ----------------*/ + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == RCC_PERIPHCLK_USB) + { + /* Check the parameters */ + assert_param(IS_RCC_USBCLKSOURCE(PeriphClkInit->UsbClockSelection)); + + /* Configure the USB clock source */ + __HAL_RCC_USB_CONFIG(PeriphClkInit->UsbClockSelection); + } +#endif /* USB_DRD_FS */ /*-------------------------- I2S1 clock source configuration ---------------------*/ if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S1) == RCC_PERIPHCLK_I2S1) { @@ -230,7 +243,9 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2S1 | \ RCC_PERIPHCLK_ADC | RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_HSIKER ; - +#if defined(USB_DRD_FS) + PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_USB; +#endif /* USB_DRD_FS */ /* Get the USART1 clock source ---------------------------------------------*/ PeriphClkInit->Usart1ClockSelection = __HAL_RCC_GET_USART1_SOURCE(); @@ -243,6 +258,11 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) /* Get the ADC clock source -----------------------------------------------*/ PeriphClkInit->AdcClockSelection = __HAL_RCC_GET_ADC_SOURCE(); +#if defined (USB_DRD_FS) + /* Get the USB clock source -------------------------------------------------*/ + PeriphClkInit->UsbClockSelection = __HAL_RCC_GET_USB_SOURCE(); +#endif /* USB_DRD_FS */ + /* Get the I2S1 clock source -----------------------------------------------*/ PeriphClkInit->I2s1ClockSelection = __HAL_RCC_GET_I2S1_SOURCE(); @@ -260,6 +280,8 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) * @arg @ref RCC_PERIPHCLK_I2C1 I2C1 peripheral clock * @arg @ref RCC_PERIPHCLK_I2S1 I2S1 peripheral clock * @arg @ref RCC_PERIPHCLK_USART1 USART1 peripheral clock + * @arg @ref RCC_PERIPHCLK_USB USB peripheral clock (*) + * @note (*) not available on all devices * @retval Frequency in Hz */ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) @@ -395,7 +417,24 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* Nothing to do as frequency already initialized to 0U */ } break; - +#if defined (USB_DRD_FS) + case RCC_PERIPHCLK_USB: + /* Get the current USB source */ + srcclk = __HAL_RCC_GET_USB_SOURCE(); + if (srcclk == RCC_USBCLKSOURCE_HSI48) + { + frequency = HSI48_VALUE; + } + else if (srcclk == RCC_USBCLKSOURCE_HSE) + { + frequency = HSE_VALUE; + } + /* Clock not enabled for USB */ + else + { + /* Nothing to do as frequency already initialized to 0U */ + } +#endif /* USB_DRD_FS */ default: break; } @@ -467,7 +506,363 @@ void HAL_RCCEx_DisableLSCO(void) * @} */ +#if defined(CRS) + +/** @defgroup RCCEx_Exported_Functions_Group3 Extended Clock Recovery System Control functions + * @brief Extended Clock Recovery System Control functions + * +@verbatim + =============================================================================== + ##### Extended Clock Recovery System Control functions ##### + =============================================================================== + [..] + For devices with Clock Recovery System feature (CRS), RCC Extension HAL driver can be used as follows: + + (#) In System clock config, HSI48 needs to be enabled + + (#) Enable CRS clock in IP MSP init which will use CRS functions + + (#) Call CRS functions as follows: + (##) Prepare synchronization configuration necessary for HSI48 calibration + (+++) Default values can be set for frequency Error Measurement (reload and error limit) + and also HSI48 oscillator smooth trimming. + (+++) Macro __HAL_RCC_CRS_RELOADVALUE_CALCULATE can be also used to calculate + directly reload value with target and synchronization frequencies values + (##) Call function HAL_RCCEx_CRSConfig which + (+++) Resets CRS registers to their default values. + (+++) Configures CRS registers with synchronization configuration + (+++) Enables automatic calibration and frequency error counter feature + Note: When using USB LPM (Link Power Management) and the device is in Sleep mode, the + periodic USB SOF will not be generated by the host. No SYNC signal will therefore be + provided to the CRS to calibrate the HSI48 on the run. To guarantee the required clock + precision after waking up from Sleep mode, the LSE or reference clock on the GPIOs + should be used as SYNC signal. + + (##) A polling function is provided to wait for complete synchronization + (+++) Call function HAL_RCCEx_CRSWaitSynchronization() + (+++) According to CRS status, user can decide to adjust again the calibration or continue + application if synchronization is OK + + (#) User can retrieve information related to synchronization in calling function + HAL_RCCEx_CRSGetSynchronizationInfo() + + (#) Regarding synchronization status and synchronization information, user can try a new calibration + in changing synchronization configuration and call again HAL_RCCEx_CRSConfig. + Note: When the SYNC event is detected during the downcounting phase (before reaching the zero value), + it means that the actual frequency is lower than the target (and so, that the TRIM value should be + incremented), while when it is detected during the upcounting phase it means that the actual frequency + is higher (and that the TRIM value should be decremented). + + (#) In interrupt mode, user can resort to the available macros (__HAL_RCC_CRS_XXX_IT). Interrupts will go + through CRS Handler (CRS_IRQn/CRS_IRQHandler) + (++) Call function HAL_RCCEx_CRSConfig() + (++) Enable CRS_IRQn (thanks to NVIC functions) + (++) Enable CRS interrupt (__HAL_RCC_CRS_ENABLE_IT) + (++) Implement CRS status management in the following user callbacks called from + HAL_RCCEx_CRS_IRQHandler(): + (+++) HAL_RCCEx_CRS_SyncOkCallback() + (+++) HAL_RCCEx_CRS_SyncWarnCallback() + (+++) HAL_RCCEx_CRS_ExpectedSyncCallback() + (+++) HAL_RCCEx_CRS_ErrorCallback() + + (#) To force a SYNC EVENT, user can use the function HAL_RCCEx_CRSSoftwareSynchronizationGenerate(). + This function can be called before calling HAL_RCCEx_CRSConfig (for instance in Systick handler) + +@endverbatim + * @{ + */ + +/** + * @brief Start automatic synchronization for polling mode + * @param pInit Pointer on RCC_CRSInitTypeDef structure + * @retval None + */ +void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit) +{ + uint32_t value; /* no init needed */ + + /* Check the parameters */ + assert_param(IS_RCC_CRS_SYNC_DIV(pInit->Prescaler)); + assert_param(IS_RCC_CRS_SYNC_SOURCE(pInit->Source)); + assert_param(IS_RCC_CRS_SYNC_POLARITY(pInit->Polarity)); + assert_param(IS_RCC_CRS_RELOADVALUE(pInit->ReloadValue)); + assert_param(IS_RCC_CRS_ERRORLIMIT(pInit->ErrorLimitValue)); + assert_param(IS_RCC_CRS_HSI48CALIBRATION(pInit->HSI48CalibrationValue)); + + /* CONFIGURATION */ + + /* Before configuration, reset CRS registers to their default values*/ + __HAL_RCC_CRS_FORCE_RESET(); + __HAL_RCC_CRS_RELEASE_RESET(); + + /* Set the SYNCDIV[2:0] bits according to Prescaler value */ + /* Set the SYNCSRC[1:0] bits according to Source value */ + /* Set the SYNCSPOL bit according to Polarity value */ + value = (pInit->Prescaler | pInit->Source | pInit->Polarity); + /* Set the RELOAD[15:0] bits according to ReloadValue value */ + value |= pInit->ReloadValue; + /* Set the FELIM[7:0] bits according to ErrorLimitValue value */ + value |= (pInit->ErrorLimitValue << CRS_CFGR_FELIM_Pos); + WRITE_REG(CRS->CFGR, value); + + /* Adjust HSI48 oscillator smooth trimming */ + /* Set the TRIM[6:0] bits according to RCC_CRS_HSI48CalibrationValue value */ + MODIFY_REG(CRS->CR, CRS_CR_TRIM, (pInit->HSI48CalibrationValue << CRS_CR_TRIM_Pos)); + + /* START AUTOMATIC SYNCHRONIZATION*/ + + /* Enable Automatic trimming & Frequency error counter */ + SET_BIT(CRS->CR, CRS_CR_AUTOTRIMEN | CRS_CR_CEN); +} + +/** + * @brief Generate the software synchronization event + * @retval None + */ +void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void) +{ + SET_BIT(CRS->CR, CRS_CR_SWSYNC); +} + +/** + * @brief Return synchronization info + * @param pSynchroInfo Pointer on RCC_CRSSynchroInfoTypeDef structure + * @retval None + */ +void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo) +{ + /* Check the parameter */ + assert_param(pSynchroInfo != (void *)NULL); + + /* Get the reload value */ + pSynchroInfo->ReloadValue = (READ_BIT(CRS->CFGR, CRS_CFGR_RELOAD)); + + /* Get HSI48 oscillator smooth trimming */ + pSynchroInfo->HSI48CalibrationValue = (READ_BIT(CRS->CR, CRS_CR_TRIM) >> CRS_CR_TRIM_Pos); + + /* Get Frequency error capture */ + pSynchroInfo->FreqErrorCapture = (READ_BIT(CRS->ISR, CRS_ISR_FECAP) >> CRS_ISR_FECAP_Pos); + + /* Get Frequency error direction */ + pSynchroInfo->FreqErrorDirection = (READ_BIT(CRS->ISR, CRS_ISR_FEDIR)); +} + +/** + * @brief Wait for CRS Synchronization status. + * @param Timeout Duration of the timeout + * @note Timeout is based on the maximum time to receive a SYNC event based on synchronization + * frequency. + * @note If Timeout set to HAL_MAX_DELAY, HAL_TIMEOUT will be never returned. + * @retval Combination of Synchronization status + * This parameter can be a combination of the following values: + * @arg @ref RCC_CRS_TIMEOUT + * @arg @ref RCC_CRS_SYNCOK + * @arg @ref RCC_CRS_SYNCWARN + * @arg @ref RCC_CRS_SYNCERR + * @arg @ref RCC_CRS_SYNCMISS + * @arg @ref RCC_CRS_TRIMOVF + */ +uint32_t HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout) +{ + uint32_t crsstatus = RCC_CRS_NONE; + uint32_t tickstart; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait for CRS flag or timeout detection */ + do + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + crsstatus = RCC_CRS_TIMEOUT; + } + } + /* Check CRS SYNCOK flag */ + if (__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCOK)) + { + /* CRS SYNC event OK */ + crsstatus |= RCC_CRS_SYNCOK; + + /* Clear CRS SYNC event OK bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCOK); + } + + /* Check CRS SYNCWARN flag */ + if (__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCWARN)) + { + /* CRS SYNC warning */ + crsstatus |= RCC_CRS_SYNCWARN; + + /* Clear CRS SYNCWARN bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCWARN); + } + + /* Check CRS TRIM overflow flag */ + if (__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_TRIMOVF)) + { + /* CRS SYNC Error */ + crsstatus |= RCC_CRS_TRIMOVF; + + /* Clear CRS Error bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_TRIMOVF); + } + + /* Check CRS Error flag */ + if (__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCERR)) + { + /* CRS SYNC Error */ + crsstatus |= RCC_CRS_SYNCERR; + + /* Clear CRS Error bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCERR); + } + + /* Check CRS SYNC Missed flag */ + if (__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCMISS)) + { + /* CRS SYNC Missed */ + crsstatus |= RCC_CRS_SYNCMISS; + + /* Clear CRS SYNC Missed bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCMISS); + } + + /* Check CRS Expected SYNC flag */ + if (__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_ESYNC)) + { + /* frequency error counter reached a zero value */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_ESYNC); + } + } while (RCC_CRS_NONE == crsstatus); + + return crsstatus; +} + +/** + * @brief Handle the Clock Recovery System interrupt request. + * @retval None + */ +void HAL_RCCEx_CRS_IRQHandler(void) +{ + uint32_t crserror = RCC_CRS_NONE; + /* Get current IT flags and IT sources values */ + uint32_t itflags = READ_REG(CRS->ISR); + uint32_t itsources = READ_REG(CRS->CR); + + /* Check CRS SYNCOK flag */ + if (((itflags & RCC_CRS_FLAG_SYNCOK) != 0U) && ((itsources & RCC_CRS_IT_SYNCOK) != 0U)) + { + /* Clear CRS SYNC event OK flag */ + WRITE_REG(CRS->ICR, CRS_ICR_SYNCOKC); + + /* user callback */ + HAL_RCCEx_CRS_SyncOkCallback(); + } + /* Check CRS SYNCWARN flag */ + else if (((itflags & RCC_CRS_FLAG_SYNCWARN) != 0U) && ((itsources & RCC_CRS_IT_SYNCWARN) != 0U)) + { + /* Clear CRS SYNCWARN flag */ + WRITE_REG(CRS->ICR, CRS_ICR_SYNCWARNC); + + /* user callback */ + HAL_RCCEx_CRS_SyncWarnCallback(); + } + /* Check CRS Expected SYNC flag */ + else if (((itflags & RCC_CRS_FLAG_ESYNC) != 0U) && ((itsources & RCC_CRS_IT_ESYNC) != 0U)) + { + /* frequency error counter reached a zero value */ + WRITE_REG(CRS->ICR, CRS_ICR_ESYNCC); + + /* user callback */ + HAL_RCCEx_CRS_ExpectedSyncCallback(); + } + /* Check CRS Error flags */ + else + { + if (((itflags & RCC_CRS_FLAG_ERR) != 0U) && ((itsources & RCC_CRS_IT_ERR) != 0U)) + { + if ((itflags & RCC_CRS_FLAG_SYNCERR) != 0U) + { + crserror |= RCC_CRS_SYNCERR; + } + if ((itflags & RCC_CRS_FLAG_SYNCMISS) != 0U) + { + crserror |= RCC_CRS_SYNCMISS; + } + if ((itflags & RCC_CRS_FLAG_TRIMOVF) != 0U) + { + crserror |= RCC_CRS_TRIMOVF; + } + + /* Clear CRS Error flags */ + WRITE_REG(CRS->ICR, CRS_ICR_ERRC); + + /* user error callback */ + HAL_RCCEx_CRS_ErrorCallback(crserror); + } + } +} + +/** + * @brief RCCEx Clock Recovery System SYNCOK interrupt callback. + * @retval none + */ +__weak void HAL_RCCEx_CRS_SyncOkCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the @ref HAL_RCCEx_CRS_SyncOkCallback should be implemented in the user file + */ +} + +/** + * @brief RCCEx Clock Recovery System SYNCWARN interrupt callback. + * @retval none + */ +__weak void HAL_RCCEx_CRS_SyncWarnCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the @ref HAL_RCCEx_CRS_SyncWarnCallback should be implemented in the user file + */ +} + +/** + * @brief RCCEx Clock Recovery System Expected SYNC interrupt callback. + * @retval none + */ +__weak void HAL_RCCEx_CRS_ExpectedSyncCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the @ref HAL_RCCEx_CRS_ExpectedSyncCallback should be implemented in the user file + */ +} + +/** + * @brief RCCEx Clock Recovery System Error interrupt callback. + * @param Error Combination of Error status. + * This parameter can be a combination of the following values: + * @arg @ref RCC_CRS_SYNCERR + * @arg @ref RCC_CRS_SYNCMISS + * @arg @ref RCC_CRS_TRIMOVF + * @retval none + */ +__weak void HAL_RCCEx_CRS_ErrorCallback(uint32_t Error) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(Error); + + /* NOTE : This function should not be modified, when the callback is needed, + the @ref HAL_RCCEx_CRS_ErrorCallback should be implemented in the user file + */ +} + +/** + * @} + */ +#endif /* CRS */ /** * @} */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc.c index 72a2a6e87..c28a31913 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc.c @@ -205,8 +205,8 @@ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) #if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; /* Legacy weak AlarmAEventCallback */ - hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; /* Legacy weak TimeStampEventCallback */ + hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; /* Legacy weak AlarmAEventCallback */ + hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; /* Legacy weak TimeStampEventCallback */ if (hrtc->MspInitCallback == NULL) { @@ -239,13 +239,13 @@ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) if (status == HAL_OK) { /* Clear RTC_CR FMT, OSEL and POL Bits */ - hrtc->Instance->CR &= ~(RTC_CR_FMT | RTC_CR_POL | RTC_CR_OSEL); + CLEAR_BIT(RTC->CR, (RTC_CR_FMT | RTC_CR_POL | RTC_CR_OSEL)); + /* Set RTC_CR register */ - hrtc->Instance->CR |= (hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity); + SET_BIT(RTC->CR, (hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity)); /* Configure the RTC PRER */ - hrtc->Instance->PRER = (hrtc->Init.SynchPrediv); - hrtc->Instance->PRER |= (hrtc->Init.AsynchPrediv << RTC_PRER_PREDIV_A_Pos); + WRITE_REG(RTC->PRER, ((hrtc->Init.SynchPrediv) | (hrtc->Init.AsynchPrediv << RTC_PRER_PREDIV_A_Pos))); /* Exit Initialization mode */ status = RTC_ExitInitMode(hrtc); @@ -253,12 +253,13 @@ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) if (status == HAL_OK) { - hrtc->Instance->CR &= ~(RTC_CR_TAMPALRM_PU | RTC_CR_TAMPALRM_TYPE | RTC_CR_OUT2EN); - hrtc->Instance->CR |= (hrtc->Init.OutPutPullUp | hrtc->Init.OutPutType | hrtc->Init.OutPutRemap); + MODIFY_REG(RTC->CR, \ + RTC_CR_TAMPALRM_PU | RTC_CR_TAMPALRM_TYPE | RTC_CR_OUT2EN, \ + hrtc->Init.OutPutPullUp | hrtc->Init.OutPutType | hrtc->Init.OutPutRemap); } - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); } else { @@ -294,21 +295,25 @@ HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - /* Enter Initialization mode */ status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { - /* Reset TR, DR and CR registers */ - hrtc->Instance->TR = 0x00000000U; - hrtc->Instance->DR = ((uint32_t)(RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); + /* Set Initialization mode */ + if (status != HAL_OK) + { + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + } + else + { /* Reset all RTC CR register bits */ - hrtc->Instance->CR &= 0x00000000U; - hrtc->Instance->PRER = ((uint32_t)(RTC_PRER_PREDIV_A | 0x000000FFU)); - hrtc->Instance->ALRMAR = 0x00000000U; - hrtc->Instance->SHIFTR = 0x00000000U; - hrtc->Instance->CALR = 0x00000000U; - hrtc->Instance->ALRMASSR = 0x00000000U; + CLEAR_REG(RTC->CR); + WRITE_REG(RTC->DR, (uint32_t)(RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); + CLEAR_REG(RTC->TR); + WRITE_REG(RTC->PRER, ((uint32_t)(RTC_PRER_PREDIV_A | 0xFFU))); + CLEAR_REG(RTC->ALRMAR); + CLEAR_REG(RTC->SHIFTR); + CLEAR_REG(RTC->CALR); + WRITE_REG(RTC->SCR, RTC_SCR_CTSOVF | RTC_SCR_CTSF | RTC_SCR_CALRAF); /* Exit initialization mode */ status = RTC_ExitInitMode(hrtc); @@ -797,7 +802,7 @@ HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDat * @arg RTC_FORMAT_BCD: BCD data format * @retval HAL status */ -HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +HAL_StatusTypeDef HAL_RTC_GetDate(const RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) { uint32_t datetmpreg; @@ -1215,7 +1220,8 @@ HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alar * @arg RTC_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) +HAL_StatusTypeDef HAL_RTC_GetAlarm(const RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, + uint32_t Format) { uint32_t tmpreg; uint32_t subsecondtmpreg; @@ -1372,17 +1378,17 @@ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef *hrtc) uint32_t tickstart; /* Clear RSF flag */ - hrtc->Instance->ICSR &= (uint32_t)RTC_RSF_MASK; + CLEAR_BIT(RTC->ICSR, RTC_ICSR_RSF); tickstart = HAL_GetTick(); /* Wait the registers to be synchronised */ - while ((hrtc->Instance->ICSR & RTC_ICSR_RSF) == 0U) + while (READ_BIT(RTC->ICSR, RTC_ICSR_RSF) == 0U) { if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) { /* New check to avoid false timeout detection in case of preemption */ - if ((hrtc->Instance->ICSR & RTC_ICSR_RSF) == 0U) + if (READ_BIT(RTC->ICSR, RTC_ICSR_RSF) == 0U) { /* Change RTC state */ hrtc->State = HAL_RTC_STATE_TIMEOUT; @@ -1421,7 +1427,7 @@ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef *hrtc) * @param hrtc RTC handle * @retval HAL state */ -HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc) +HAL_RTCStateTypeDef HAL_RTC_GetState(const RTC_HandleTypeDef *hrtc) { /* Return RTC handle state */ return hrtc->State; @@ -1450,19 +1456,19 @@ HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef *hrtc) HAL_StatusTypeDef status = HAL_OK; /* Check if the Initialization mode is set */ - if ((hrtc->Instance->ICSR & RTC_ICSR_INITF) == 0U) + if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) { /* Set the Initialization mode */ - SET_BIT(hrtc->Instance->ICSR, RTC_ICSR_INIT); + SET_BIT(RTC->ICSR, RTC_ICSR_INIT); tickstart = HAL_GetTick(); /* Wait till RTC is in INIT state and if Time out is reached exit */ - while (((hrtc->Instance->ICSR & RTC_ICSR_INITF) == 0U) && (status != HAL_TIMEOUT)) + while ((READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) && (status != HAL_TIMEOUT)) { if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) { /* New check to avoid false timeout detection in case of preemption */ - if ((hrtc->Instance->ICSR & RTC_ICSR_INITF) == 0U) + if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) { status = HAL_TIMEOUT; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc_ex.c index 62706d7a2..02353feae 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_rtc_ex.c @@ -270,7 +270,8 @@ HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format) { - uint32_t tmptime, tmpdate; + uint32_t tmptime; + uint32_t tmpdate; /* Check the parameters */ assert_param(IS_RTC_FORMAT(Format)); @@ -346,7 +347,7 @@ void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc) HAL_RTCEx_TimeStampEventCallback(hrtc); #endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - /* Clearing flags after the Callback because the content of RTC_TSTR and RTC_TSDR are cleared when TSF bit is reset.*/ + /* Clearing flags after the Callback because the RTC_TSTR and RTC_TSDR contents are cleared when TSF bit is reset.*/ WRITE_REG(RTC->SCR, RTC_SCR_CTSF); } @@ -425,7 +426,6 @@ HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint3 */ - /** * @brief Set the Smooth calibration parameters. * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses @@ -493,7 +493,8 @@ HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t Smo } /* Configure the Smooth calibration settings */ - hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | (uint32_t)SmoothCalibMinusPulsesValue); + hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | \ + (uint32_t)SmoothCalibMinusPulsesValue); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smartcard.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smartcard.c index 6325fc3e3..ed1ea4a83 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smartcard.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smartcard.c @@ -2426,7 +2426,7 @@ static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); tmpreg |= (uint32_t) hsmartcard->Init.TimeOutValue; } - MODIFY_REG(hsmartcard->Instance->RTOR, (USART_RTOR_RTO | USART_RTOR_BLEN), tmpreg); + WRITE_REG(hsmartcard->Instance->RTOR, tmpreg); /*-------------------------- USART BRR Configuration -----------------------*/ SMARTCARD_GETCLOCKSOURCE(hsmartcard, clocksource); diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus.c index 47fbf9cdb..260a3ff20 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus.c @@ -2610,8 +2610,11 @@ static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus) __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); } - /* Flush TX register */ - SMBUS_Flush_TXDR(hsmbus); + if (hsmbus->ErrorCode != HAL_SMBUS_ERROR_NONE) + { + /* Flush TX register */ + SMBUS_Flush_TXDR(hsmbus); + } /* Store current volatile hsmbus->ErrorCode, misra rule */ tmperror = hsmbus->ErrorCode; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus_ex.c index 19662b263..3bea4745f 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_smbus_ex.c @@ -6,6 +6,8 @@ * This file provides firmware functions to manage the following * functionalities of SMBUS Extended peripheral: * + Extended features functions + * + WakeUp Mode Functions + * + FastModePlus Functions * ****************************************************************************** * @attention @@ -64,6 +66,7 @@ /** @defgroup SMBUSEx_Exported_Functions SMBUS Extended Exported Functions * @{ */ +#if defined(I2C_CR1_WUPEN) /** @defgroup SMBUSEx_Exported_Functions_Group2 WakeUp Mode Functions * @brief WakeUp Mode Functions @@ -159,6 +162,7 @@ HAL_StatusTypeDef HAL_SMBUSEx_DisableWakeUp(SMBUS_HandleTypeDef *hsmbus) /** * @} */ +#endif /* SMBUS_CR1_WUPEN */ /** @defgroup SMBUSEx_Exported_Functions_Group3 Fast Mode Plus Functions * @brief Fast Mode Plus Functions @@ -183,6 +187,8 @@ HAL_StatusTypeDef HAL_SMBUSEx_DisableWakeUp(SMBUS_HandleTypeDef *hsmbus) * on each one of the following pins PB6, PB7, PB8 and PB9. * @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability * can be enabled only by using SMBUS_FASTMODEPLUS_I2C1 parameter. + * @note For all I2C2 pins fast mode plus driving capability can be enabled + * only by using SMBUS_FASTMODEPLUS_I2C2 parameter. * @retval None */ void HAL_SMBUSEx_EnableFastModePlus(uint32_t ConfigFastModePlus) @@ -206,6 +212,8 @@ void HAL_SMBUSEx_EnableFastModePlus(uint32_t ConfigFastModePlus) * on each one of the following pins PB6, PB7, PB8 and PB9. * @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability * can be disabled only by using SMBUS_FASTMODEPLUS_I2C1 parameter. + * @note For all I2C2 pins fast mode plus driving capability can be disabled + * only by using SMBUS_FASTMODEPLUS_I2C2 parameter. * @retval None */ void HAL_SMBUSEx_DisableFastModePlus(uint32_t ConfigFastModePlus) diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi.c index ab6e72791..03dfc1b0f 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi.c @@ -818,38 +818,35 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @param Timeout Timeout duration * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; uint16_t initial_TxXferCount; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); initial_TxXferCount = Size; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -888,7 +885,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -898,7 +895,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -907,8 +904,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -921,13 +919,13 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint if (hspi->TxXferCount > 1U) { /* write on the data register in packing mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount -= 2U; } else { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr ++; hspi->TxXferCount--; } @@ -940,13 +938,13 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint if (hspi->TxXferCount > 1U) { /* write on the data register in packing mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount -= 2U; } else { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; } @@ -956,8 +954,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -982,16 +981,18 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint __HAL_SPI_CLEAR_OVRFLAG(hspi); } - if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - errorcode = HAL_ERROR; - } - -error: hspi->State = HAL_SPI_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } } /** @@ -1011,7 +1012,11 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 __IO uint8_t tmpreg8 = 0; #endif /* USE_SPI_CRC */ uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; + + if (hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } if ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) { @@ -1020,24 +1025,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); } - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } - if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1108,8 +1106,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1131,8 +1130,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1149,8 +1149,8 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { /* the latest data has not been received */ - errorcode = HAL_TIMEOUT; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Receive last data in 16 Bit mode */ @@ -1168,8 +1168,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC to Flush DR and RXNE flag */ @@ -1195,8 +1196,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 { /* Error on the CRC reception */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read 8bit CRC again in case of 16bit CRC in 8bit Data mode */ tmpreg8 = *ptmpreg8; @@ -1222,15 +1224,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 } #endif /* USE_SPI_CRC */ + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; + } + else + { + return HAL_OK; } - -error : - hspi->State = HAL_SPI_STATE_READY; - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1243,8 +1247,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) { uint16_t initial_TxXferCount; uint16_t initial_RxXferCount; @@ -1261,14 +1265,10 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Variable used to alternate Rx and Tx during transfer */ uint32_t txallowed = 1U; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); @@ -1285,16 +1285,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD if (!((tmp_state == HAL_SPI_STATE_READY) || \ ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1306,7 +1307,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD hspi->pRxBuffPtr = (uint8_t *)pRxData; hspi->RxXferCount = Size; hspi->RxXferSize = Size; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferCount = Size; hspi->TxXferSize = Size; @@ -1346,16 +1347,30 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + /* Set NSS Soft to received correctly the CRC on slave mode with NSS pulse activated */ + if ((READ_BIT(spi_cr1, SPI_CR1_MSTR) == 0U) && (READ_BIT(spi_cr2, SPI_CR2_NSSP) == SPI_CR2_NSSP)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_SSM); + } + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } +#endif /* USE_SPI_CRC */ + } while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) { /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1386,8 +1401,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if (((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) { - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1398,15 +1414,28 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if (hspi->TxXferCount > 1U) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount -= 2U; } else { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + /* Set NSS Soft to received correctly the CRC on slave mode with NSS pulse activated */ + if ((READ_BIT(spi_cr1, SPI_CR1_MSTR) == 0U) && (READ_BIT(spi_cr2, SPI_CR2_NSSP) == SPI_CR2_NSSP)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_SSM); + } + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } +#endif /* USE_SPI_CRC */ } } while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) @@ -1416,13 +1445,13 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if (hspi->TxXferCount > 1U) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount -= 2U; } else { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; } @@ -1468,8 +1497,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if ((((HAL_GetTick() - tickstart) >= Timeout) && ((Timeout != HAL_MAX_DELAY))) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1483,8 +1513,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { /* Error on the CRC reception */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC */ if (hspi->Init.DataSize == SPI_DATASIZE_16BIT) @@ -1509,8 +1540,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { /* Error on the CRC reception */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read 8bit CRC again in case of 16bit CRC in 8bit Data mode */ tmpreg8 = *ptmpreg8; @@ -1526,22 +1558,32 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); /* Clear CRC Flag */ __HAL_SPI_CLEAR_CRCERRFLAG(hspi); - - errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } #endif /* USE_SPI_CRC */ /* Check the end of the transaction */ if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK) { - errorcode = HAL_ERROR; hspi->ErrorCode = HAL_SPI_ERROR_FLAG; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } -error : + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ __HAL_UNLOCK(hspi); - return errorcode; + + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } } /** @@ -1552,32 +1594,30 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1613,10 +1653,6 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u } #endif /* USE_SPI_CRC */ - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); - - /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) { @@ -1624,9 +1660,12 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } -error : + /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1639,7 +1678,11 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; + + if (hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) { @@ -1648,21 +1691,15 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1715,9 +1752,6 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui } #endif /* USE_SPI_CRC */ - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); - /* Note : The SPI must be enabled after unlocking current process to avoid the risk of SPI interrupt handle execution before current process unlock */ @@ -1729,10 +1763,12 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui __HAL_SPI_ENABLE(hspi); } -error : /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1744,18 +1780,15 @@ error : * @param Size amount of data to be sent and received * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; @@ -1763,16 +1796,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p if (!((tmp_state == HAL_SPI_STATE_READY) || \ ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1781,7 +1815,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1829,8 +1863,6 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); } - /* Enable TXE, RXNE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) @@ -1839,10 +1871,12 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p __HAL_SPI_ENABLE(hspi); } -error : /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable TXE, RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1853,9 +1887,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check tx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx)); @@ -1863,25 +1896,23 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1943,10 +1974,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - hspi->State = HAL_SPI_STATE_READY; - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1956,16 +1986,16 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1980,11 +2010,14 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - /* Check rx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); + if (hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } + if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) { hspi->State = HAL_SPI_STATE_BUSY_RX; @@ -1996,21 +2029,14 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } - if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -2088,10 +2114,9 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - hspi->State = HAL_SPI_STATE_READY; - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -2101,16 +2126,16 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Rx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -2123,12 +2148,11 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u * @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, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check rx & tx dma handles */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); @@ -2137,9 +2161,6 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; @@ -2147,16 +2168,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * if (!((tmp_state == HAL_SPI_STATE_READY) || ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -2165,7 +2187,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -2256,10 +2278,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - hspi->State = HAL_SPI_STATE_READY; - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Enable Rx DMA Request */ @@ -2278,10 +2299,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - hspi->State = HAL_SPI_STATE_READY; - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -2290,16 +2310,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Enable SPI peripheral */ __HAL_SPI_ENABLE(hspi); } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -2972,7 +2993,7 @@ __weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI state */ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi) { /* Return SPI handle state */ return hspi->State; @@ -2984,7 +3005,7 @@ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI error code in bitmap format */ -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi) { /* Return SPI ErrorCode */ return hspi->ErrorCode; @@ -3603,14 +3624,14 @@ static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) /* Transmit data in packing Bit mode */ if (hspi->TxXferCount >= 2U) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount -= 2U; } /* Transmit data in 8 Bit mode */ else { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; } @@ -3704,7 +3725,7 @@ static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3857,7 +3878,7 @@ static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) */ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3883,7 +3904,7 @@ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3985,7 +4006,7 @@ static HAL_StatusTypeDef SPI_WaitFifoStateUntilTimeout(SPI_HandleTypeDef *hspi, __IO uint32_t count; uint32_t tmp_timeout; uint32_t tmp_tickstart; - __IO uint8_t *ptmpreg8; + __IO const uint8_t *ptmpreg8; __IO uint8_t tmpreg8 = 0; /* Adjust Timeout value in case of end of transfer */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi_ex.c index 9ced2ecef..d254174c0 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_spi_ex.c @@ -76,7 +76,7 @@ * the configuration information for the specified SPI module. * @retval HAL status */ -HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(SPI_HandleTypeDef *hspi) +HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(const SPI_HandleTypeDef *hspi) { __IO uint32_t tmpreg; uint8_t count = 0U; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim.c index 47279377c..ff97814fa 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim.c @@ -3850,7 +3850,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) if ((itsource & (TIM_IT_CC1)) == (TIM_IT_CC1)) { { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC1); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; /* Input capture event */ @@ -3882,7 +3882,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { if ((itsource & (TIM_IT_CC2)) == (TIM_IT_CC2)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC2); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; /* Input capture event */ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) @@ -3912,7 +3912,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { if ((itsource & (TIM_IT_CC3)) == (TIM_IT_CC3)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC3); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) @@ -3942,7 +3942,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { if ((itsource & (TIM_IT_CC4)) == (TIM_IT_CC4)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC4); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) @@ -3972,7 +3972,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { if ((itsource & (TIM_IT_UPDATE)) == (TIM_IT_UPDATE)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_UPDATE); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PeriodElapsedCallback(htim); #else @@ -3981,11 +3981,12 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Break input event */ - if ((itflag & (TIM_FLAG_BREAK)) == (TIM_FLAG_BREAK)) + if (((itflag & (TIM_FLAG_BREAK)) == (TIM_FLAG_BREAK)) || \ + ((itflag & (TIM_FLAG_SYSTEM_BREAK)) == (TIM_FLAG_SYSTEM_BREAK))) { if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK | TIM_FLAG_SYSTEM_BREAK); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->BreakCallback(htim); #else @@ -4011,7 +4012,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { if ((itsource & (TIM_IT_TRIGGER)) == (TIM_IT_TRIGGER)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TRIGGER); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TriggerCallback(htim); #else @@ -4024,7 +4025,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { if ((itsource & (TIM_IT_COM)) == (TIM_IT_COM)) { - __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_COM); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->CommutationCallback(htim); #else @@ -4575,7 +4576,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_O * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength) + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength) { HAL_StatusTypeDef status; @@ -4583,7 +4585,6 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t ((BurstLength) >> 8U) + 1U); - return status; } @@ -6972,6 +6973,13 @@ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, const TIM_Base_InitTypeDef *Structure /* Generate an update event to reload the Prescaler and the repetition counter (only for advanced timer) value immediately */ TIMx->EGR = TIM_EGR_UG; + + /* Check if the update flag is set after the Update Generation, if so clear the UIF flag */ + if (HAL_IS_BIT_SET(TIMx->SR, TIM_FLAG_UPDATE)) + { + /* Clear the update flag */ + CLEAR_BIT(TIMx->SR, TIM_FLAG_UPDATE); + } } /** @@ -7096,7 +7104,6 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) tmpccer |= (OC_Config->OCNPolarity << 4U); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC2NE; - } if (IS_TIM_BREAK_INSTANCE(TIMx)) diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim_ex.c index d5a629050..be65d9a58 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_tim_ex.c @@ -848,7 +848,7 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channe /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; - if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == (uint32_t)RESET) + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } @@ -1094,17 +1094,6 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chann (+) 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 * @{ */ @@ -1330,7 +1319,7 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Chann /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; - if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == (uint32_t)RESET) + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } @@ -2096,6 +2085,7 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, assert_param(IS_TIM_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity)); assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->BreakFilter)); assert_param(IS_TIM_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput)); + assert_param(IS_TIM_BREAK_AFMODE(sBreakDeadTimeConfig->BreakAFMode)); /* Check input state */ __HAL_LOCK(htim); @@ -2112,15 +2102,7 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, sBreakDeadTimeConfig->BreakPolarity); MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, sBreakDeadTimeConfig->AutomaticOutput); MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, (sBreakDeadTimeConfig->BreakFilter << TIM_BDTR_BKF_Pos)); - - if (IS_TIM_ADVANCED_INSTANCE(htim->Instance)) - { - /* Check the parameters */ - assert_param(IS_TIM_BREAK_AFMODE(sBreakDeadTimeConfig->BreakAFMode)); - - /* Set BREAK AF mode */ - MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, sBreakDeadTimeConfig->BreakAFMode); - } + MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, sBreakDeadTimeConfig->BreakAFMode); if (IS_TIM_BKIN2_INSTANCE(htim->Instance)) { @@ -2128,20 +2110,13 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, assert_param(IS_TIM_BREAK2_STATE(sBreakDeadTimeConfig->Break2State)); assert_param(IS_TIM_BREAK2_POLARITY(sBreakDeadTimeConfig->Break2Polarity)); assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->Break2Filter)); + assert_param(IS_TIM_BREAK2_AFMODE(sBreakDeadTimeConfig->Break2AFMode)); /* Set the BREAK2 input related BDTR bits */ MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (sBreakDeadTimeConfig->Break2Filter << TIM_BDTR_BK2F_Pos)); MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, sBreakDeadTimeConfig->Break2State); MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, sBreakDeadTimeConfig->Break2Polarity); - - if (IS_TIM_ADVANCED_INSTANCE(htim->Instance)) - { - /* Check the parameters */ - assert_param(IS_TIM_BREAK2_AFMODE(sBreakDeadTimeConfig->Break2AFMode)); - - /* Set BREAK2 AF mode */ - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, sBreakDeadTimeConfig->Break2AFMode); - } + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, sBreakDeadTimeConfig->Break2AFMode); } /* Set TIMx_BDTR */ @@ -2165,7 +2140,6 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, HAL_StatusTypeDef HAL_TIMEx_ConfigBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput, const TIMEx_BreakInputConfigTypeDef *sBreakInputConfig) - { HAL_StatusTypeDef status = HAL_OK; uint32_t tmporx; @@ -2404,7 +2378,7 @@ HAL_StatusTypeDef HAL_TIMEx_DisarmBreakInput(TIM_HandleTypeDef *htim, uint32_t B uint32_t tmpbdtr; /* Check the parameters */ - assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance)); + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_BREAKINPUT(BreakInput)); switch (BreakInput) @@ -2421,7 +2395,6 @@ HAL_StatusTypeDef HAL_TIMEx_DisarmBreakInput(TIM_HandleTypeDef *htim, uint32_t B } break; } - case TIM_BREAKINPUT_BRK2: { /* Check initial conditions */ @@ -2459,7 +2432,7 @@ HAL_StatusTypeDef HAL_TIMEx_ReArmBreakInput(const TIM_HandleTypeDef *htim, uint3 uint32_t tickstart; /* Check the parameters */ - assert_param(IS_TIM_ADVANCED_INSTANCE(htim->Instance)); + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_BREAKINPUT(BreakInput)); switch (BreakInput) @@ -2538,7 +2511,7 @@ HAL_StatusTypeDef HAL_TIMEx_ReArmBreakInput(const TIM_HandleTypeDef *htim, uint3 */ /** - * @brief Hall commutation changed callback in non-blocking mode + * @brief Commutation callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2552,7 +2525,7 @@ __weak void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) */ } /** - * @brief Hall commutation changed half complete callback in non-blocking mode + * @brief Commutation half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2567,7 +2540,7 @@ __weak void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim) } /** - * @brief Hall Break detection callback in non-blocking mode + * @brief Break detection callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2582,7 +2555,7 @@ __weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim) } /** - * @brief Hall Break2 detection callback in non blocking mode + * @brief Break2 detection callback in non blocking mode * @param htim: TIM handle * @retval None */ @@ -2733,15 +2706,6 @@ static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - - if (hdma->Init.Mode == DMA_NORMAL) - { - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); - } - } else { /* nothing to do */ @@ -2810,13 +2774,13 @@ static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Cha { uint32_t tmp; - tmp = TIM_CCER_CC1NE << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ + tmp = TIM_CCER_CC1NE << (Channel & 0xFU); /* 0xFU = 15 bits max shift */ /* Reset the CCxNE Bit */ TIMx->CCER &= ~tmp; /* Set or reset the CCxNE Bit */ - TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ + TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0xFU)); /* 0xFU = 15 bits max shift */ } /** * @} diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_timebase_tim_template.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_timebase_tim_template.c index 65a904da4..5b4ffc9f8 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_timebase_tim_template.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_timebase_tim_template.c @@ -67,7 +67,8 @@ void TIM3_IRQHandler(void); HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { RCC_ClkInitTypeDef clkconfig; - uint32_t uwTimclock, uwAPB1Prescaler; + uint32_t uwTimclock; + uint32_t uwAPB1Prescaler; uint32_t uwPrescalerValue; uint32_t pFLatency; @@ -87,7 +88,7 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) uwAPB1Prescaler = clkconfig.APB1CLKDivider; /* Compute TIM3 clock */ - if (uwAPB1Prescaler == RCC_HCLK_DIV1) + if (uwAPB1Prescaler == RCC_APB1_DIV1) { uwTimclock = HAL_RCC_GetPCLK1Freq(); } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart.c index 4bbc90bd2..4990752b3 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart.c @@ -971,10 +971,7 @@ HAL_StatusTypeDef HAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pU return HAL_ERROR; } - /* Process locked */ - __HAL_LOCK(huart); - - if (huart->gState == HAL_UART_STATE_READY) + if (huart->RxState == HAL_UART_STATE_READY) { huart->RxEventCallback = pCallback; } @@ -985,9 +982,6 @@ HAL_StatusTypeDef HAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pU status = HAL_ERROR; } - /* Release Lock */ - __HAL_UNLOCK(huart); - return status; } @@ -1001,10 +995,7 @@ HAL_StatusTypeDef HAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart) { HAL_StatusTypeDef status = HAL_OK; - /* Process locked */ - __HAL_LOCK(huart); - - if (huart->gState == HAL_UART_STATE_READY) + if (huart->RxState == HAL_UART_STATE_READY) { huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak UART Rx Event Callback */ } @@ -1015,8 +1006,6 @@ HAL_StatusTypeDef HAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart) status = HAL_ERROR; } - /* Release Lock */ - __HAL_UNLOCK(huart); return status; } @@ -2543,6 +2532,28 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) HAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } + else + { + /* If DMA is in Circular mode, Idle event is to be reported to user + even if occurring after a Transfer Complete event from DMA */ + if (nb_remaining_rx_data == huart->RxXferSize) + { + if (HAL_IS_BIT_SET(huart->hdmarx->Instance->CCR, DMA_CCR_CIRC)) + { + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Idle Event */ + huart->RxEventType = HAL_UART_RXEVENT_IDLE; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + } + } return; } else @@ -3411,7 +3422,7 @@ HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_ return HAL_TIMEOUT; } - if (READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) + if ((READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) && (Flag != UART_FLAG_TXE) && (Flag != UART_FLAG_TC)) { if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) == SET) { @@ -4496,6 +4507,7 @@ static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } + break; } } @@ -4657,6 +4669,7 @@ static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } + break; } } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart_ex.c index 915734ca1..cecce5d84 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_uart_ex.c @@ -576,7 +576,7 @@ HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart) /* Disable UART */ __HAL_UART_DISABLE(huart); - /* Enable FIFO mode */ + /* Disable FIFO mode */ CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); huart->FifoMode = UART_FIFOMODE_DISABLE; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart.c index c8a95ffeb..1951067e3 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart.c @@ -144,7 +144,7 @@ */ /** @defgroup USART USART - * @brief HAL USART Synchronous module driver + * @brief HAL USART Synchronous SPI module driver * @{ */ @@ -227,8 +227,8 @@ static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); =============================================================================== [..] 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: + in synchronous SPI master/slave mode. + (+) For the synchronous SPI mode only these parameters can be configured: (++) Baud Rate (++) Word Length (++) Stop Bit @@ -240,7 +240,7 @@ static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); (++) Receiver/transmitter modes [..] - The HAL_USART_Init() function follows the USART synchronous configuration + The HAL_USART_Init() function follows the USART synchronous SPI configuration procedure (details for the procedure are available in reference manual). @endverbatim @@ -318,7 +318,7 @@ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) return HAL_ERROR; } - /* In Synchronous mode, the following bits must be kept cleared: + /* In Synchronous SPI 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. */ @@ -659,11 +659,10 @@ HAL_StatusTypeDef HAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, HAL_ =============================================================================== ##### IO operation functions ##### =============================================================================== - [..] This subsection provides a set of functions allowing to manage the USART synchronous + [..] This subsection provides a set of functions allowing to manage the USART synchronous SPI data transfers. - [..] The USART supports master mode only: it cannot receive or send data related to an input - clock (SCLK is always an output). + [..] The USART Synchronous SPI supports master and slave modes (SCLK as output or input). [..] @@ -3064,7 +3063,7 @@ static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart) /* Clear and configure the USART Clock, CPOL, CPHA, LBCL STOP and SLVEN bits: * 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 (used in SPI master mode only) + * set LBCL bit according to husart->Init.CLKLastBit value (used in USART Synchronous SPI master mode only) * set STOP[13:12] bits according to husart->Init.StopBits value */ tmpreg = (uint32_t)(USART_CLOCK_ENABLE); tmpreg |= (uint32_t)husart->Init.CLKLastBit; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart_ex.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart_ex.c index 5e5bd5bf1..686fd3abd 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart_ex.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_usart_ex.c @@ -364,7 +364,7 @@ HAL_StatusTypeDef HAL_USARTEx_DisableFifoMode(USART_HandleTypeDef *husart) /* Disable USART */ __HAL_USART_DISABLE(husart); - /* Enable FIFO mode */ + /* Disable FIFO mode */ CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); husart->FifoMode = USART_FIFOMODE_DISABLE; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_wwdg.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_wwdg.c index 84fb0b97b..25bbd1ac3 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_wwdg.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_hal_wwdg.c @@ -122,7 +122,6 @@ (+) __HAL_WWDG_ENABLE_IT: Enable the WWDG early wakeup interrupt @endverbatim - ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_adc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_adc.c index b49c048b8..8c0457719 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_adc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_adc.c @@ -25,7 +25,7 @@ #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) -#endif +#endif /* USE_FULL_ASSERT */ /** @addtogroup STM32C0xx_LL_Driver * @{ @@ -133,13 +133,25 @@ /* Check of parameters for configuration of ADC hierarchical scope: */ /* ADC group regular */ +#if defined(TIM2) #define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ (((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH4 ) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ ) +#else +#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ + (((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH4 ) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ + ) +#endif /* TIM1 */ + #define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \ (((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \ || ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \ @@ -204,11 +216,14 @@ * - SUCCESS: ADC common registers are de-initialized * - ERROR: not applicable */ -ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON) +ErrorStatus LL_ADC_CommonDeInit(const ADC_Common_TypeDef *ADCxy_COMMON) { /* Check the parameters */ assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); + /* Prevent unused argument(s) compilation warning if no assert_param check */ + (void)(ADCxy_COMMON); + /* Force reset of ADC clock (core clock) */ LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_ADC); diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crc.c index 3f07530cf..9477be26f 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crc.c @@ -59,7 +59,7 @@ * - SUCCESS: CRC registers are de-initialized * - ERROR: CRC registers are not de-initialized */ -ErrorStatus LL_CRC_DeInit(CRC_TypeDef *CRCx) +ErrorStatus LL_CRC_DeInit(const CRC_TypeDef *CRCx) { ErrorStatus status = SUCCESS; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crs.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crs.c new file mode 100644 index 000000000..1caf19b59 --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_crs.c @@ -0,0 +1,101 @@ +/** + ****************************************************************************** + * @file stm32c0xx_ll_crs.h + * @author MCD Application Team + * @brief CRS LL module driver. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * 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. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_ll_crs.h" +#include "stm32c0xx_ll_bus.h" + +/** @addtogroup STM32C0xx_LL_Driver + * @{ + */ + +#if defined(CRS) + +/** @defgroup CRS_LL CRS + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CRS_LL_Exported_Functions + * @{ + */ + +/** @addtogroup CRS_LL_EF_Init + * @{ + */ + +/** + * @brief De-Initializes CRS peripheral registers to their default reset values. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: CRS registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_CRS_DeInit(void) +{ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_CRS); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_CRS); + + return SUCCESS; +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(CRS) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_dma.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_dma.c index 3f0cf6f24..80d655a16 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_dma.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_dma.c @@ -74,10 +74,19 @@ ((__VALUE__) == LL_DMA_PRIORITY_HIGH) || \ ((__VALUE__) == LL_DMA_PRIORITY_VERYHIGH)) +#if defined(LL_DMA_CHANNEL_5) +#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, CHANNEL) ((((INSTANCE) == DMA1) && \ + (((CHANNEL) == LL_DMA_CHANNEL_1) || \ + ((CHANNEL) == LL_DMA_CHANNEL_2) || \ + ((CHANNEL) == LL_DMA_CHANNEL_3) || \ + ((CHANNEL) == LL_DMA_CHANNEL_4) || \ + ((CHANNEL) == LL_DMA_CHANNEL_5)))) +#else #define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, CHANNEL) ((((INSTANCE) == DMA1) && \ (((CHANNEL) == LL_DMA_CHANNEL_1) || \ ((CHANNEL) == LL_DMA_CHANNEL_2) || \ ((CHANNEL) == LL_DMA_CHANNEL_3)))) +#endif /* LL_DMA_CHANNEL_5 */ /** * @} @@ -101,7 +110,10 @@ * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) * @arg @ref LL_DMA_CHANNEL_ALL + * @note (*) Availability depends on devices * @retval An ErrorStatus enumeration value: * - SUCCESS: DMA registers are de-initialized * - ERROR: DMA registers are not de-initialized @@ -167,6 +179,18 @@ ErrorStatus LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) /* Reset interrupt pending bits for DMAx Channel3 */ LL_DMA_ClearFlag_GI3(DMAx); } +#if defined(DMA1_Channel4) + else if (Channel == LL_DMA_CHANNEL_4) + { + /* Reset interrupt pending bits for DMAx Channel4 */ + LL_DMA_ClearFlag_GI4(DMAx); + } + else if (Channel == LL_DMA_CHANNEL_5) + { + /* Reset interrupt pending bits for DMAx Channel5 */ + LL_DMA_ClearFlag_GI5(DMAx); + } +#endif /* DMA1_Channel4 */ else { status = ERROR; @@ -186,6 +210,9 @@ ErrorStatus LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) * @arg @ref LL_DMA_CHANNEL_1 * @arg @ref LL_DMA_CHANNEL_2 * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 (*) + * @arg @ref LL_DMA_CHANNEL_5 (*) + * @note (*) Availability depends on devices * @param DMA_InitStruct pointer to a @ref LL_DMA_InitTypeDef structure. * @retval An ErrorStatus enumeration value: * - SUCCESS: DMA registers are initialized diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_exti.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_exti.c index 50af5587c..4cbfabf4d 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_exti.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_exti.c @@ -44,7 +44,9 @@ */ #define IS_LL_EXTI_LINE_0_31(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_0_31) == 0x00000000U) - +#if defined(EXTI_IMR2_IM36) +#define IS_LL_EXTI_LINE_32_63(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_32_63) == 0x00000000U) +#endif /* EXTI_IMR2_IM36 */ #define IS_LL_EXTI_MODE(__VALUE__) (((__VALUE__) == LL_EXTI_MODE_IT) \ || ((__VALUE__) == LL_EXTI_MODE_EVENT) \ || ((__VALUE__) == LL_EXTI_MODE_IT_EVENT)) @@ -91,6 +93,22 @@ ErrorStatus LL_EXTI_DeInit(void) /* Pending register set to default reset values */ LL_EXTI_WriteReg(RPR1, 0x0007FFFFU); LL_EXTI_WriteReg(FPR1, 0x0007FFFFU); +#if defined(EXTI_IMR2_IM36) + /* Interrupt mask register set to default reset values */ + LL_EXTI_WriteReg(IMR2, 0x00000010U); + /* Event mask register set to default reset values */ + LL_EXTI_WriteReg(EMR2, 0x00000000U); + /* Rising Trigger selection register set to default reset values */ + LL_EXTI_WriteReg(RTSR2, 0x00000000U); + /* Falling Trigger selection register set to default reset values */ + LL_EXTI_WriteReg(FTSR2, 0x00000000U); + /* Software interrupt event register set to default reset values */ + LL_EXTI_WriteReg(SWIER2, 0x00000000U); + /* Pending register set to default reset values */ + LL_EXTI_WriteReg(RPR2, 0x00000004U); + LL_EXTI_WriteReg(FPR2, 0x00000004U); +#endif /* EXTI_IMR2_IM36*/ + return SUCCESS; } @@ -106,6 +124,9 @@ ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_LL_EXTI_LINE_0_31(EXTI_InitStruct->Line_0_31)); +#if defined(EXTI_IMR2_IM36) + assert_param(IS_LL_EXTI_LINE_32_63(EXTI_InitStruct->Line_32_63)); +#endif /* EXTI_IMR2_IM36 */ assert_param(IS_FUNCTIONAL_STATE(EXTI_InitStruct->LineCommand)); assert_param(IS_LL_EXTI_MODE(EXTI_InitStruct->Mode)); @@ -140,6 +161,7 @@ ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) status = ERROR; break; } + if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) { switch (EXTI_InitStruct->Trigger) @@ -166,7 +188,60 @@ ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) } } } - +#if defined(EXTI_IMR2_IM36) + /* Configure EXTI Lines in range from 32 to 63 */ + if (EXTI_InitStruct->Line_32_63 != LL_EXTI_LINE_NONE) + { + switch (EXTI_InitStruct->Mode) + { + case LL_EXTI_MODE_IT: + /* First Disable Event on provided Lines */ + LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable IT on provided Lines */ + LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_MODE_EVENT: + /* First Disable IT on provided Lines */ + LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable Event on provided Lines */ + LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_MODE_IT_EVENT: + /* Directly Enable IT & Event on provided Lines */ + LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63); + LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63); + break; + default: + status = ERROR; + break; + } + if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) + { + switch (EXTI_InitStruct->Trigger) + { + case LL_EXTI_TRIGGER_RISING: + /* First Disable Falling Trigger on provided Lines */ + LL_EXTI_DisableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable Rising Trigger on provided Lines */ + LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_TRIGGER_FALLING: + /* First Disable Rising Trigger on provided Lines */ + LL_EXTI_DisableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable Falling Trigger on provided Lines */ + LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_TRIGGER_RISING_FALLING: + LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); + LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); + break; + default: + status = ERROR; + break; + } + } + } +#endif /* EXTI_IMR2_IM36 */ } /* DISABLE LineCommand */ else @@ -174,9 +249,15 @@ ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) /* De-configure EXTI Lines in range from 0 to 31 */ LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31); LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31); +#if defined(EXTI_IMR2_IM36) + /* De-configure EXTI Lines in range from 32 to 63 */ + LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63); + LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63); +#endif /* EXTI_IMR2_IM36 */ } return status; } + /** * @brief Set each @ref LL_EXTI_InitTypeDef field to default value. * @param EXTI_InitStruct Pointer to a @ref LL_EXTI_InitTypeDef structure. @@ -185,7 +266,9 @@ ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct) { EXTI_InitStruct->Line_0_31 = LL_EXTI_LINE_NONE; - +#if defined(EXTI_IMR2_IM36) + EXTI_InitStruct->Line_32_63 = LL_EXTI_LINE_NONE; +#endif /* EXTI_IMR2_IM36 */ EXTI_InitStruct->LineCommand = DISABLE; EXTI_InitStruct->Mode = LL_EXTI_MODE_IT; EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING; diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_gpio.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_gpio.c index acd124ae1..9eb83e4b5 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_gpio.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_gpio.c @@ -100,7 +100,7 @@ * - SUCCESS: GPIO registers are de-initialized * - ERROR: Wrong GPIO Port */ -ErrorStatus LL_GPIO_DeInit(GPIO_TypeDef *GPIOx) +ErrorStatus LL_GPIO_DeInit(const GPIO_TypeDef *GPIOx) { ErrorStatus status = SUCCESS; @@ -165,19 +165,16 @@ ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, LL_GPIO_InitTypeDef *GPIO_InitStru /* ------------------------- Configure the port pins ---------------- */ /* Initialize pinpos on first pin set */ - pinpos = POSITION_VAL(GPIO_InitStruct->Pin); + pinpos = 0; /* Configure the port pins */ - while (((GPIO_InitStruct->Pin) >> pinpos) != 0U) + while (((GPIO_InitStruct->Pin) >> pinpos) != 0x00u) { /* Get current io position */ - currentpin = (GPIO_InitStruct->Pin) & (1UL << pinpos); + currentpin = (GPIO_InitStruct->Pin) & (0x00000001uL << pinpos); - if (currentpin != 0U) + if (currentpin != 0x00u) { - /* Pin Mode configuration */ - LL_GPIO_SetPinMode(GPIOx, currentpin, GPIO_InitStruct->Mode); - if ((GPIO_InitStruct->Mode == LL_GPIO_MODE_OUTPUT) || (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE)) { /* Check Speed mode parameters */ @@ -185,6 +182,12 @@ ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, LL_GPIO_InitTypeDef *GPIO_InitStru /* Speed mode configuration */ LL_GPIO_SetPinSpeed(GPIOx, currentpin, GPIO_InitStruct->Speed); + + /* Check Output mode parameters */ + assert_param(IS_LL_GPIO_OUTPUT_TYPE(GPIO_InitStruct->OutputType)); + + /* Output mode configuration*/ + LL_GPIO_SetPinOutputType(GPIOx, currentpin, GPIO_InitStruct->OutputType); } /* Pull-up Pull down resistor configuration*/ @@ -196,7 +199,7 @@ ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, LL_GPIO_InitTypeDef *GPIO_InitStru assert_param(IS_LL_GPIO_ALTERNATE(GPIO_InitStruct->Alternate)); /* Speed mode configuration */ - if (POSITION_VAL(currentpin) < 8U) + if (currentpin < LL_GPIO_PIN_8) { LL_GPIO_SetAFPin_0_7(GPIOx, currentpin, GPIO_InitStruct->Alternate); } @@ -205,19 +208,13 @@ ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, LL_GPIO_InitTypeDef *GPIO_InitStru LL_GPIO_SetAFPin_8_15(GPIOx, currentpin, GPIO_InitStruct->Alternate); } } + + /* Pin Mode configuration */ + LL_GPIO_SetPinMode(GPIOx, currentpin, GPIO_InitStruct->Mode); } pinpos++; } - if ((GPIO_InitStruct->Mode == LL_GPIO_MODE_OUTPUT) || (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE)) - { - /* Check Output mode parameters */ - assert_param(IS_LL_GPIO_OUTPUT_TYPE(GPIO_InitStruct->OutputType)); - - /* Output mode configuration*/ - LL_GPIO_SetPinOutputType(GPIOx, GPIO_InitStruct->Pin, GPIO_InitStruct->OutputType); - - } return (SUCCESS); } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_i2c.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_i2c.c index 50a2c7b62..1529b7ecd 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_i2c.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_i2c.c @@ -30,7 +30,7 @@ * @{ */ -#if defined (I2C1) +#if defined (I2C1) || defined(I2C2) /** @defgroup I2C_LL I2C * @{ @@ -98,6 +98,17 @@ ErrorStatus LL_I2C_DeInit(const I2C_TypeDef *I2Cx) /* Release reset of I2C clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1); } +#if defined(I2C2) + else if (I2Cx == I2C2) + { + /* Force reset of I2C clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C2); + + /* Release reset of I2C clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2); + + } +#endif /* I2C2 */ else { status = ERROR; @@ -206,7 +217,7 @@ void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct) * @} */ -#endif /* I2C1 */ +#endif /* I2C1 || I2C2 */ /** * @} diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rcc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rcc.c index c1ef0f7ca..af292db99 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rcc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rcc.c @@ -23,7 +23,7 @@ #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) -#endif +#endif /* USE_FULL_ASSERT */ /** @addtogroup STM32C0xx_LL_Driver * @{ */ @@ -43,9 +43,12 @@ */ #define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_USART1_CLKSOURCE) -#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) -#define IS_LL_RCC_ADC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADC_CLKSOURCE)) -#define IS_LL_RCC_I2S_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2S1_CLKSOURCE)) +#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) +#define IS_LL_RCC_ADC_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_ADC_CLKSOURCE) +#define IS_LL_RCC_I2S_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_I2S1_CLKSOURCE) +#if defined (USB_DRD_FS) +#define IS_LL_RCC_USB_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_USB_CLKSOURCE) +#endif /* USB_DRD_FS */ /** * @} @@ -58,9 +61,6 @@ uint32_t RCC_GetSystemClockFreq(void); uint32_t RCC_GetHCLKClockFreq(uint32_t SYSCLK_Frequency); uint32_t RCC_GetPCLK1ClockFreq(uint32_t HCLK_Frequency); -uint32_t RCC_PLL_GetFreqDomain_SYS(void); -uint32_t RCC_PLL_GetFreqDomain_ADC(void); -uint32_t RCC_PLL_GetFreqDomain_I2S1(void); /** * @} */ @@ -214,8 +214,10 @@ uint32_t LL_RCC_GetUSARTClockFreq(uint32_t USARTxSource) * @brief Return I2Cx clock frequency * @param I2CxSource This parameter can be one of the following values: * @arg @ref LL_RCC_I2C1_CLKSOURCE + * @arg @ref LL_RCC_I2C2_CLKSOURCE (*) * @retval I2C clock frequency (in Hz) * - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that HSI oscillator is not ready + * @note (*) peripheral not available on all devices */ uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource) { @@ -246,9 +248,30 @@ uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource) break; } } - else +#if defined(I2C2) + else if (I2CxSource == LL_RCC_I2C2_CLKSOURCE) { + /* I2C2 CLK clock frequency */ + switch (LL_RCC_GetI2CClockSource(I2CxSource)) + { + case LL_RCC_I2C2_CLKSOURCE_SYSCLK: /* I2C2 Clock is System Clock */ + i2c_frequency = RCC_GetSystemClockFreq(); + break; + + case LL_RCC_I2C2_CLKSOURCE_HSIKER: /* I2C2 Clock is HSI Kernel */ + if (LL_RCC_HSI_IsReady() == 1U) + { + i2c_frequency = (HSI_VALUE / ((LL_RCC_HSIKER_GetDivider() >> RCC_CR_HSIKERDIV_Pos) + 1U)); + } + break; + + case LL_RCC_I2C2_CLKSOURCE_PCLK1: /* I2C2 Clock is PCLK1 */ + default: + i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq())); + break; + } } +#endif /* I2C2 */ return i2c_frequency; } @@ -273,7 +296,10 @@ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) switch (LL_RCC_GetI2SClockSource(I2SxSource)) { case LL_RCC_I2S1_CLKSOURCE_HSIKER: /* I2S1 Clock is HSI Kernel */ - i2s_frequency = (HSI_VALUE / ((LL_RCC_HSIKER_GetDivider() >> RCC_CR_HSIKERDIV_Pos) + 1U)); + if (LL_RCC_HSI_IsReady() == 1U) + { + i2s_frequency = (HSI_VALUE / ((LL_RCC_HSIKER_GetDivider() >> RCC_CR_HSIKERDIV_Pos) + 1U)); + } break; case LL_RCC_I2S1_CLKSOURCE_PIN: /* I2S1 Clock is External clock */ @@ -312,7 +338,10 @@ uint32_t LL_RCC_GetADCClockFreq(uint32_t ADCxSource) adc_frequency = RCC_GetSystemClockFreq(); break; case LL_RCC_ADC_CLKSOURCE_HSIKER : /* HSI clock Kernel used as ADC clock source */ - adc_frequency = (HSI_VALUE / ((LL_RCC_HSIKER_GetDivider() >> RCC_CR_HSIKERDIV_Pos) + 1U)); + if (LL_RCC_HSI_IsReady() == 1U) + { + adc_frequency = (HSI_VALUE / ((LL_RCC_HSIKER_GetDivider() >> RCC_CR_HSIKERDIV_Pos) + 1U)); + } break; default: adc_frequency = LL_RCC_PERIPH_FREQUENCY_NA; @@ -362,6 +391,50 @@ uint32_t LL_RCC_GetRTCClockFreq(void) return rtc_frequency; } +#if defined(USB_DRD_FS) +/** + * @brief Return USBx clock frequency + * @param USBxSource This parameter can be one of the following values: + * @arg @ref LL_RCC_USB_CLKSOURCE + * @retval USB clock frequency (in Hz) + * - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI48) is not ready + * - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected + */ +uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource) +{ + uint32_t usb_frequency = LL_RCC_PERIPH_FREQUENCY_NO; + + /* Check parameter */ + assert_param(IS_LL_RCC_USB_CLKSOURCE(USBxSource)); + + /* USBCLK clock frequency */ + switch (LL_RCC_GetUSBClockSource(USBxSource)) + { +#if defined(RCC_HSI48_SUPPORT) + case LL_RCC_USB_CLKSOURCE_HSI48: /* HSI48 used as USB clock source */ + if (LL_RCC_HSI48_IsReady() != 0U) + { + usb_frequency = HSI48_VALUE; + } + break; +#endif /* RCC_HSI48_SUPPORT */ + + case LL_RCC_USB_CLKSOURCE_HSE: /* HSE used as USB clock source */ + if (LL_RCC_HSE_IsReady() != 0U) + { + usb_frequency = HSE_VALUE; + } + break; + + default: + usb_frequency = LL_RCC_PERIPH_FREQUENCY_NA; + break; + } + + return usb_frequency; +} +#endif /* USB_DRD_FS */ + /** * @} */ @@ -382,6 +455,9 @@ uint32_t RCC_GetSystemClockFreq(void) { uint32_t frequency; uint32_t hsidiv; +#if defined(RCC_CR_SYSDIV) + uint32_t sysdiv = (uint32_t)(((RCC->CR & RCC_CR_SYSDIV) >> RCC_CR_SYSDIV_Pos) + 1U); +#endif /* RCC_CR_SYSDIV */ /* Get SYSCLK source -------------------------------------------------------*/ switch (LL_RCC_GetSysClkSource()) @@ -389,12 +465,34 @@ uint32_t RCC_GetSystemClockFreq(void) case LL_RCC_SYS_CLKSOURCE_STATUS_HSE: /* HSE used as system clock source */ frequency = HSE_VALUE; break; + case LL_RCC_SYS_CLKSOURCE_STATUS_HSI: /* HSI used as system clock source */ + hsidiv = (1UL << ((READ_BIT(RCC->CR, RCC_CR_HSIDIV)) >> RCC_CR_HSIDIV_Pos)); + frequency = (HSI_VALUE / hsidiv); + break; + + case LL_RCC_SYS_CLKSOURCE_STATUS_LSE: /* LSE used as system clock source */ + frequency = LSE_VALUE; + break; + + case LL_RCC_SYS_CLKSOURCE_STATUS_LSI: /* LSI used as system clock source */ + frequency = LSI_VALUE; + break; + +#if defined(RCC_HSI48_SUPPORT) + case LL_RCC_SYS_CLKSOURCE_STATUS_HSIUSB48: /* HSIUSB48 used as system clock source */ + frequency = HSI48_VALUE; + break; +#endif /* RCC_HSI48_SUPPORT */ + default: hsidiv = (1UL << ((READ_BIT(RCC->CR, RCC_CR_HSIDIV)) >> RCC_CR_HSIDIV_Pos)); frequency = (HSI_VALUE / hsidiv); break; } +#if defined(RCC_CR_SYSDIV) + frequency = frequency / sysdiv; +#endif /* RCC_CR_SYSDIV */ return frequency; } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rtc.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rtc.c index 804a96d20..0b2a5e63f 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rtc.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_rtc.c @@ -24,7 +24,7 @@ #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) -#endif +#endif /* USE_FULL_ASSERT */ /** @addtogroup STM32C0xx_LL_Driver * @{ @@ -376,12 +376,14 @@ ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_Date /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { - LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year); + LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, + RTC_DateStruct->Year); } else { LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day), - __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); + __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), + __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); } /* Exit Initialization mode */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_spi.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_spi.c index cbfaa2580..065572255 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_spi.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_spi.c @@ -130,7 +130,7 @@ * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx) { ErrorStatus status = ERROR; @@ -149,6 +149,18 @@ ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) status = SUCCESS; } #endif /* SPI1 */ +#if defined(SPI2) + if (SPIx == SPI2) + { + /* Force reset of SPI clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2); + + /* Release reset of SPI clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2); + + status = SUCCESS; + } +#endif /* SPI2 */ return status; } @@ -343,7 +355,7 @@ void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx) { return LL_SPI_DeInit(SPIx); } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_tim.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_tim.c index c71b14d64..8f5ded0c4 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_tim.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_tim.c @@ -66,8 +66,8 @@ || ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM2) \ || ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM1) \ || ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM2) \ - || ((__VALUE__) == LL_TIM_OCMODE_ASSYMETRIC_PWM1) \ - || ((__VALUE__) == LL_TIM_OCMODE_ASSYMETRIC_PWM2)) + || ((__VALUE__) == LL_TIM_OCMODE_ASYMMETRIC_PWM1) \ + || ((__VALUE__) == LL_TIM_OCMODE_ASYMMETRIC_PWM2)) #define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \ || ((__VALUE__) == LL_TIM_OCSTATE_ENABLE)) @@ -706,6 +706,8 @@ ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, const LL_TIM_BDTR_InitTypeDef *T assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState)); assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity)); assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput)); + assert_param(IS_LL_TIM_BREAK_FILTER(TIM_BDTRInitStruct->BreakFilter)); + assert_param(IS_LL_TIM_BREAK_AFMODE(TIM_BDTRInitStruct->BreakAFMode)); /* 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 */ @@ -718,8 +720,6 @@ ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, const LL_TIM_BDTR_InitTypeDef *T MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState); MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity); MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput); - assert_param(IS_LL_TIM_BREAK_FILTER(TIM_BDTRInitStruct->BreakFilter)); - assert_param(IS_LL_TIM_BREAK_AFMODE(TIM_BDTRInitStruct->BreakAFMode)); MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, TIM_BDTRInitStruct->BreakFilter); MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, TIM_BDTRInitStruct->BreakAFMode); @@ -773,8 +773,6 @@ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 1: Reset the CC1E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); @@ -802,8 +800,10 @@ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); @@ -852,8 +852,6 @@ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 2: Reset the CC2E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); @@ -881,8 +879,10 @@ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); @@ -931,8 +931,6 @@ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 3: Reset the CC3E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); @@ -960,8 +958,10 @@ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); @@ -1010,8 +1010,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); /* Disable the Channel 4: Reset the CC4E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); @@ -1039,7 +1037,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the Output Idle state */ @@ -1306,7 +1303,7 @@ static ErrorStatus IC4Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); - /* Select the Polarity and set the CC2E Bit */ + /* Select the Polarity and set the CC4E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC4P | TIM_CCER_CC4NP), ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usart.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usart.c index c43ba5f2d..dc9124848 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usart.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usart.c @@ -238,7 +238,7 @@ ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, const LL_USART_InitTypeDef *USA } else if (USARTx == USART2) { - /* USART2 clock is PCLK */ + /* USART2 clock is PCLK1 */ LL_RCC_GetSystemClocksFreq(&RCC_Clocks); periphclk = RCC_Clocks.PCLK1_Frequency; } diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usb.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usb.c new file mode 100644 index 000000000..c53d95a15 --- /dev/null +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_usb.c @@ -0,0 +1,1485 @@ +/** + ****************************************************************************** + * @file stm32c0xx_ll_usb.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Fill parameters of Init structure in USB_CfgTypeDef structure. + + (#) Call USB_CoreInit() API to initialize the USB Core peripheral. + + (#) The upper HAL HCD/PCD driver will call the right routines for its internal processes. + + @endverbatim + + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32c0xx_hal.h" + +/** @addtogroup STM32C0xx_LL_USB_DRIVER + * @{ + */ + +#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) +#if defined (USB_DRD_FS) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +static HAL_StatusTypeDef USB_CoreReset(USB_DRD_TypeDef *USBx); +#if (USE_USB_DOUBLE_BUFFER == 1U) +static HAL_StatusTypeDef USB_HC_BULK_DB_StartXfer(USB_DRD_TypeDef *USBx, + USB_DRD_HCTypeDef *hc, + uint32_t ch_reg, + uint32_t *len); + +static HAL_StatusTypeDef USB_HC_ISO_DB_StartXfer(USB_DRD_TypeDef *USBx, + USB_DRD_HCTypeDef *hc, + uint32_t len); +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + +/** + * @brief Reset the USB Core (needed after USB clock settings change) + * @param USBx Selected device + * @retval HAL status + */ +static HAL_StatusTypeDef USB_CoreReset(USB_DRD_TypeDef *USBx) +{ + /* Disable Host Mode */ + USBx->CNTR &= ~USB_CNTR_HOST; + + /* Force Reset IP */ + USBx->CNTR |= USB_CNTR_USBRST; + + return HAL_OK; +} + +/** + * @brief Initializes the USB Core + * @param USBx USB Instance + * @param cfg pointer to a USB_CfgTypeDef structure that contains + * the configuration information for the specified USBx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef USB_CoreInit(USB_DRD_TypeDef *USBx, USB_DRD_CfgTypeDef cfg) +{ + HAL_StatusTypeDef ret; + UNUSED(cfg); + + if (USBx == NULL) + { + return HAL_ERROR; + } + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + + /* Clear pending interrupts */ + USBx->ISTR = 0U; + + return ret; +} + +/** + * @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_DRD_TypeDef *USBx) +{ + uint32_t winterruptmask; + + /* Clear pending interrupts */ + USBx->ISTR = 0U; + + /* Set winterruptmask variable */ + winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM | + USB_CNTR_SUSPM | USB_CNTR_ERRM | + USB_CNTR_SOFM | USB_CNTR_ESOFM | + USB_CNTR_RESETM | USB_CNTR_L1REQM; + + /* Set interrupt mask */ + USBx->CNTR = winterruptmask; + + 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_DRD_TypeDef *USBx) +{ + uint32_t winterruptmask; + + /* Set winterruptmask variable */ + winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM | + USB_CNTR_SUSPM | USB_CNTR_ERRM | + USB_CNTR_SOFM | USB_CNTR_ESOFM | + USB_CNTR_RESETM | USB_CNTR_L1REQM; + + /* Clear interrupt mask */ + USBx->CNTR &= ~winterruptmask; + + 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_DEVICE_MODE Peripheral mode + * @retval HAL status + */ +HAL_StatusTypeDef USB_SetCurrentMode(USB_DRD_TypeDef *USBx, USB_DRD_ModeTypeDef mode) +{ + if (mode == USB_DEVICE_MODE) + { + USBx->CNTR &= ~USB_CNTR_HOST; + } + else if (mode == USB_HOST_MODE) + { + USBx->CNTR |= USB_CNTR_HOST; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief USB_DevInit Initializes the USB controller registers + * for device mode + * @param USBx Selected device + * @param cfg pointer to a USB_DRD_CfgTypeDef structure that contains + * the configuration information for the specified USBx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef USB_DevInit(USB_DRD_TypeDef *USBx, USB_DRD_CfgTypeDef cfg) +{ + HAL_StatusTypeDef ret; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(cfg); + + /* Force Reset */ + USBx->CNTR = USB_CNTR_USBRST; + + /* Release Reset */ + USBx->CNTR &= ~USB_CNTR_USBRST; + + /* Set the Device Mode */ + ret = USB_SetCurrentMode(USBx, USB_DEVICE_MODE); + + /* Clear pending interrupts */ + USBx->ISTR = 0U; + + return ret; +} + +/** + * @brief USB_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_DRD_TypeDef const *USBx, uint32_t num) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(USBx); + UNUSED(num); + + /* NOTE : - This function is not required by USB Device FS peripheral, it is used + only by USB OTG FS peripheral. + - This function is added to ensure compatibility across platforms. + */ + + return HAL_OK; +} + +/** + * @brief USB_FlushRxFifo : Flush Rx FIFO + * @param USBx : Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_FlushRxFifo(USB_DRD_TypeDef const *USBx) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(USBx); + + /* NOTE : - This function is not required by USB Device FS peripheral, it is used + only by USB OTG FS peripheral. + - This function is added to ensure compatibility across platforms. + */ + + return HAL_OK; +} + + +#if defined (HAL_PCD_MODULE_ENABLED) +/** + * @brief Activate and configure an endpoint + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval HAL status + */ +HAL_StatusTypeDef USB_ActivateEndpoint(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t wEpRegVal; + + wEpRegVal = PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_T_MASK; + + /* initialize Endpoint */ + switch (ep->type) + { + case EP_TYPE_CTRL: + wEpRegVal |= USB_EP_CONTROL; + break; + + case EP_TYPE_BULK: + wEpRegVal |= USB_EP_BULK; + break; + + case EP_TYPE_INTR: + wEpRegVal |= USB_EP_INTERRUPT; + break; + + case EP_TYPE_ISOC: + wEpRegVal |= USB_EP_ISOCHRONOUS; + break; + + default: + ret = HAL_ERROR; + break; + } + + PCD_SET_ENDPOINT(USBx, ep->num, (wEpRegVal | USB_EP_VTRX | USB_EP_VTTX)); + + PCD_SET_EP_ADDRESS(USBx, ep->num, ep->num); + + if (ep->doublebuffer == 0U) + { + if (ep->is_in != 0U) + { + /*Set the endpoint Transmit buffer address */ + PCD_SET_EP_TX_ADDRESS(USBx, ep->num, ep->pmaadress); + PCD_CLEAR_TX_DTOG(USBx, ep->num); + + if (ep->type != EP_TYPE_ISOC) + { + /* Configure NAK status for the Endpoint */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK); + } + else + { + /* Configure TX Endpoint to disabled state */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + } + } + else + { + /* Set the endpoint Receive buffer address */ + PCD_SET_EP_RX_ADDRESS(USBx, ep->num, ep->pmaadress); + + /* Set the endpoint Receive buffer counter */ + PCD_SET_EP_RX_CNT(USBx, ep->num, ep->maxpacket); + PCD_CLEAR_RX_DTOG(USBx, ep->num); + + if (ep->num == 0U) + { + /* Configure VALID status for EP0 */ + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID); + } + else + { + /* Configure NAK status for OUT Endpoint */ + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_NAK); + } + } + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + /* Double Buffer */ + else + { + if (ep->type == EP_TYPE_BULK) + { + /* Set bulk endpoint as double buffered */ + PCD_SET_BULK_EP_DBUF(USBx, ep->num); + } + else + { + /* Set the ISOC endpoint in double buffer mode */ + PCD_CLEAR_EP_KIND(USBx, ep->num); + } + + /* Set buffer address for double buffered mode */ + PCD_SET_EP_DBUF_ADDR(USBx, ep->num, ep->pmaaddr0, ep->pmaaddr1); + + if (ep->is_in == 0U) + { + /* Clear the data toggle bits for the endpoint IN/OUT */ + PCD_CLEAR_RX_DTOG(USBx, ep->num); + PCD_CLEAR_TX_DTOG(USBx, ep->num); + + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID); + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + } + else + { + /* Clear the data toggle bits for the endpoint IN/OUT */ + PCD_CLEAR_RX_DTOG(USBx, ep->num); + PCD_CLEAR_TX_DTOG(USBx, ep->num); + + if (ep->type != EP_TYPE_ISOC) + { + /* Configure NAK status for the Endpoint */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK); + } + else + { + /* Configure TX Endpoint to disabled state */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + } + + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS); + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + return ret; +} + +/** + * @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_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep) +{ + if (ep->doublebuffer == 0U) + { + if (ep->is_in != 0U) + { + PCD_CLEAR_TX_DTOG(USBx, ep->num); + + /* Configure DISABLE status for the Endpoint */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + } + + else + { + PCD_CLEAR_RX_DTOG(USBx, ep->num); + + /* Configure DISABLE status for the Endpoint */ + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS); + } + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + /* Double Buffer */ + else + { + if (ep->is_in == 0U) + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(USBx, ep->num); + PCD_CLEAR_TX_DTOG(USBx, ep->num); + + /* Reset value of the data toggle bits for the endpoint out*/ + PCD_TX_DTOG(USBx, ep->num); + + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS); + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + } + else + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(USBx, ep->num); + PCD_CLEAR_TX_DTOG(USBx, ep->num); + PCD_RX_DTOG(USBx, ep->num); + + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS); + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + return HAL_OK; +} + +/** + * @brief USB_EPStartXfer setup and starts a transfer over an EP + * @param USBx Selected device + * @param ep pointer to endpoint structure + * @retval HAL status + */ +HAL_StatusTypeDef USB_EPStartXfer(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep) +{ + uint32_t len; +#if (USE_USB_DOUBLE_BUFFER == 1U) + uint16_t pmabuffer; + uint16_t wEPVal; +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* IN endpoint */ + if (ep->is_in == 1U) + { + /*Multi packet transfer*/ + if (ep->xfer_len > ep->maxpacket) + { + len = ep->maxpacket; + } + else + { + len = ep->xfer_len; + } + + /* configure and validate Tx endpoint */ + if (ep->doublebuffer == 0U) + { + USB_WritePMA(USBx, ep->xfer_buff, ep->pmaadress, (uint16_t)len); + PCD_SET_EP_TX_CNT(USBx, ep->num, len); + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else + { + /* double buffer bulk management */ + if (ep->type == EP_TYPE_BULK) + { + if (ep->xfer_len_db > ep->maxpacket) + { + /* enable double buffer */ + PCD_SET_BULK_EP_DBUF(USBx, ep->num); + + /* each Time to write in PMA xfer_len_db will */ + ep->xfer_len_db -= len; + + /* Fill the two first buffer in the Buffer0 & Buffer1 */ + if ((PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_DTOG_TX) != 0U) + { + /* Set the Double buffer counter for pmabuffer1 */ + PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len); + pmabuffer = ep->pmaaddr1; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + ep->xfer_buff += len; + + if (ep->xfer_len_db > ep->maxpacket) + { + ep->xfer_len_db -= len; + } + else + { + len = ep->xfer_len_db; + ep->xfer_len_db = 0U; + } + + /* Set the Double buffer counter for pmabuffer0 */ + PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len); + pmabuffer = ep->pmaaddr0; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + } + else + { + /* Set the Double buffer counter for pmabuffer0 */ + PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len); + pmabuffer = ep->pmaaddr0; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + ep->xfer_buff += len; + + if (ep->xfer_len_db > ep->maxpacket) + { + ep->xfer_len_db -= len; + } + else + { + len = ep->xfer_len_db; + ep->xfer_len_db = 0U; + } + + /* Set the Double buffer counter for pmabuffer1 */ + PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len); + pmabuffer = ep->pmaaddr1; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + } + } + /* auto Switch to single buffer mode when transfer xfer_len_db; + + /* disable double buffer mode for Bulk endpoint */ + PCD_CLEAR_BULK_EP_DBUF(USBx, ep->num); + + /* Set Tx count with nbre of byte to be transmitted */ + PCD_SET_EP_TX_CNT(USBx, ep->num, len); + pmabuffer = ep->pmaaddr0; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + } + } + else /* manage isochronous double buffer IN mode */ + { + /* each Time to write in PMA xfer_len_db will */ + ep->xfer_len_db -= len; + + /* Fill the data buffer */ + if ((PCD_GET_ENDPOINT(USBx, ep->num) & USB_EP_DTOG_TX) != 0U) + { + /* Set the Double buffer counter for pmabuffer1 */ + PCD_SET_EP_DBUF1_CNT(USBx, ep->num, ep->is_in, len); + pmabuffer = ep->pmaaddr1; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + } + else + { + /* Set the Double buffer counter for pmabuffer0 */ + PCD_SET_EP_DBUF0_CNT(USBx, ep->num, ep->is_in, len); + pmabuffer = ep->pmaaddr0; + + /* Write the user buffer to USB PMA */ + USB_WritePMA(USBx, ep->xfer_buff, pmabuffer, (uint16_t)len); + } + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_VALID); + } + else /* OUT endpoint */ + { + if (ep->doublebuffer == 0U) + { + /* Multi packet transfer */ + if (ep->xfer_len > ep->maxpacket) + { + len = ep->maxpacket; + ep->xfer_len -= len; + } + else + { + len = ep->xfer_len; + ep->xfer_len = 0U; + } + /* configure and validate Rx endpoint */ + PCD_SET_EP_RX_CNT(USBx, ep->num, len); + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else + { + /* First Transfer Coming From HAL_PCD_EP_Receive & From ISR */ + /* Set the Double buffer counter */ + if (ep->type == EP_TYPE_BULK) + { + PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, ep->maxpacket); + + /* Coming from ISR */ + if (ep->xfer_count != 0U) + { + /* update last value to check if there is blocking state */ + wEPVal = (uint16_t)PCD_GET_ENDPOINT(USBx, ep->num); + + /*Blocking State */ + if ((((wEPVal & USB_EP_DTOG_RX) != 0U) && ((wEPVal & USB_EP_DTOG_TX) != 0U)) || + (((wEPVal & USB_EP_DTOG_RX) == 0U) && ((wEPVal & USB_EP_DTOG_TX) == 0U))) + { + PCD_FREE_USER_BUFFER(USBx, ep->num, 0U); + } + } + } + /* iso out double */ + else if (ep->type == EP_TYPE_ISOC) + { + /* Multi packet transfer */ + if (ep->xfer_len > ep->maxpacket) + { + len = ep->maxpacket; + ep->xfer_len -= len; + } + else + { + len = ep->xfer_len; + ep->xfer_len = 0U; + } + PCD_SET_EP_DBUF_CNT(USBx, ep->num, ep->is_in, len); + } + else + { + return HAL_ERROR; + } + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID); + } + + return HAL_OK; +} + + +/** + * @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_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep) +{ + if (ep->is_in != 0U) + { + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_STALL); + } + else + { + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_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_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep) +{ + if (ep->doublebuffer == 0U) + { + if (ep->is_in != 0U) + { + PCD_CLEAR_TX_DTOG(USBx, ep->num); + + if (ep->type != EP_TYPE_ISOC) + { + /* Configure NAK status for the Endpoint */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK); + } + } + else + { + PCD_CLEAR_RX_DTOG(USBx, ep->num); + + /* Configure VALID status for the Endpoint */ + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_VALID); + } + } + + return HAL_OK; +} + +/** + * @brief USB_EPStoptXfer Stop transfer on an EP + * @param USBx usb device instance + * @param ep pointer to endpoint structure + * @retval HAL status + */ +HAL_StatusTypeDef USB_EPStopXfer(USB_DRD_TypeDef *USBx, USB_DRD_EPTypeDef *ep) +{ + /* IN endpoint */ + if (ep->is_in == 1U) + { + if (ep->doublebuffer == 0U) + { + if (ep->type != EP_TYPE_ISOC) + { + /* Configure NAK status for the Endpoint */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_NAK); + } + else + { + /* Configure TX Endpoint to disabled state */ + PCD_SET_EP_TX_STATUS(USBx, ep->num, USB_EP_TX_DIS); + } + } + } + else /* OUT endpoint */ + { + if (ep->doublebuffer == 0U) + { + if (ep->type != EP_TYPE_ISOC) + { + /* Configure NAK status for the Endpoint */ + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_NAK); + } + else + { + /* Configure RX Endpoint to disabled state */ + PCD_SET_EP_RX_STATUS(USBx, ep->num, USB_EP_RX_DIS); + } + } + } + + return HAL_OK; +} +#endif /* defined (HAL_PCD_MODULE_ENABLED) */ + +/** + * @brief USB_StopDevice Stop the usb device mode + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_StopDevice(USB_DRD_TypeDef *USBx) +{ + /* disable all interrupts and force USB reset */ + USBx->CNTR = USB_CNTR_USBRST; + + /* clear interrupt status register */ + USBx->ISTR = 0U; + + /* switch-off device */ + USBx->CNTR = (USB_CNTR_USBRST | USB_CNTR_PDWN); + + 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_DRD_TypeDef *USBx, uint8_t address) +{ + if (address == 0U) + { + /* set device address and enable function */ + USBx->DADDR = USB_DADDR_EF; + } + + 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_DRD_TypeDef *USBx) +{ + /* Enabling DP Pull-UP bit to Connect internal PU resistor on USB DP line */ + USBx->BCDR |= USB_BCDR_DPPU; + + 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_DRD_TypeDef *USBx) +{ + /* Disable DP Pull-Up bit to disconnect the Internal PU resistor on USB DP line */ + USBx->BCDR &= ~(USB_BCDR_DPPU); + + return HAL_OK; +} + +/** + * @brief USB_ReadInterrupts return the global USB interrupt status + * @param USBx Selected device + * @retval USB Global Interrupt status + */ +uint32_t USB_ReadInterrupts(USB_DRD_TypeDef const *USBx) +{ + uint32_t tmpreg; + + tmpreg = USBx->ISTR; + return tmpreg; +} + +/** + * @brief USB_ActivateRemoteWakeup : active remote wakeup signalling + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_DRD_TypeDef *USBx) +{ + USBx->CNTR |= USB_CNTR_L2RES; + + return HAL_OK; +} + +/** + * @brief USB_DeActivateRemoteWakeup de-active remote wakeup signalling + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_DRD_TypeDef *USBx) +{ + USBx->CNTR &= ~USB_CNTR_L2RES; + + return HAL_OK; +} + +/** + * @brief Copy a buffer from user memory area to packet memory area (PMA) + * @param USBx USB peripheral instance register address. + * @param pbUsrBuf pointer to user memory area. + * @param wPMABufAddr address into PMA. + * @param wNBytes no. of bytes to be copied. + * @retval None + */ +void USB_WritePMA(USB_DRD_TypeDef const *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) +{ + UNUSED(USBx); + uint32_t WrVal; + uint32_t count; + __IO uint32_t *pdwVal; + uint32_t NbWords = ((uint32_t)wNBytes + 3U) >> 2U; + /* Due to the PMA access 32bit only so the last non word data should be processed alone */ + uint16_t remaining_bytes = wNBytes % 4U; + uint8_t *pBuf = pbUsrBuf; + + /* Check if there is a remaining byte */ + if (remaining_bytes != 0U) + { + NbWords--; + } + + /* Get the PMA Buffer pointer */ + pdwVal = (__IO uint32_t *)(USB_DRD_PMAADDR + (uint32_t)wPMABufAddr); + + /* Write the Calculated Word into the PMA related Buffer */ + for (count = NbWords; count != 0U; count--) + { + *pdwVal = __UNALIGNED_UINT32_READ(pBuf); + pdwVal++; + /* Increment pBuf 4 Time as Word Increment */ + pBuf++; + pBuf++; + pBuf++; + pBuf++; + } + + /* When Number of data is not word aligned, write the remaining Byte */ + if (remaining_bytes != 0U) + { + WrVal = 0U; + + do + { + WrVal |= (uint32_t)(*(uint8_t *)pBuf) << (8U * count); + count++; + pBuf++; + remaining_bytes--; + } while (remaining_bytes != 0U); + + *pdwVal = WrVal; + } +} + +/** + * @brief Copy data from packet memory area (PMA) to user memory buffer + * @param USBx USB peripheral instance register address. + * @param pbUsrBuf pointer to user memory area. + * @param wPMABufAddr address into PMA. + * @param wNBytes no. of bytes to be copied. + * @retval None + */ +void USB_ReadPMA(USB_DRD_TypeDef const *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) +{ + UNUSED(USBx); + uint32_t count; + uint32_t RdVal; + __IO uint32_t *pdwVal; + uint32_t NbWords = ((uint32_t)wNBytes + 3U) >> 2U; + /*Due to the PMA access 32bit only so the last non word data should be processed alone */ + uint16_t remaining_bytes = wNBytes % 4U; + uint8_t *pBuf = pbUsrBuf; + + /* Get the PMA Buffer pointer */ + pdwVal = (__IO uint32_t *)(USB_DRD_PMAADDR + (uint32_t)wPMABufAddr); + + /* if nbre of byte is not word aligned decrement the nbre of word*/ + if (remaining_bytes != 0U) + { + NbWords--; + } + + /*Read the Calculated Word From the PMA related Buffer*/ + for (count = NbWords; count != 0U; count--) + { + __UNALIGNED_UINT32_WRITE(pBuf, *pdwVal); + + pdwVal++; + pBuf++; + pBuf++; + pBuf++; + pBuf++; + } + + /*When Number of data is not word aligned, read the remaining byte*/ + if (remaining_bytes != 0U) + { + RdVal = *(__IO uint32_t *)pdwVal; + + do + { + *(uint8_t *)pBuf = (uint8_t)(RdVal >> (8U * (uint8_t)(count))); + count++; + pBuf++; + remaining_bytes--; + } while (remaining_bytes != 0U); + } +} + + +/*------------------------------------------------------------------------*/ +/* HOST API */ +/*------------------------------------------------------------------------*/ + +/** + * @brief USB_HostInit Initializes the USB DRD controller registers + * for Host mode + * @param USBx Selected device + * @param cfg pointer to a USB_DRD_CfgTypeDef structure that contains + * the configuration information for the specified USBx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef USB_HostInit(USB_DRD_TypeDef *USBx, USB_DRD_CfgTypeDef cfg) +{ + UNUSED(cfg); + + /* Clear All Pending Interrupt */ + USBx->ISTR = 0U; + + /* Disable all interrupts */ + USBx->CNTR &= ~(USB_CNTR_CTRM | USB_CNTR_PMAOVRM | USB_CNTR_ERRM | + USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_DCON | + USB_CNTR_SOFM | USB_CNTR_ESOFM | USB_CNTR_L1REQM); + + /* Clear All Pending Interrupt */ + USBx->ISTR = 0U; + + /* Set the PullDown on the PHY */ + USBx->BCDR |= USB_BCDR_DPPD; + + /* Enable Global interrupt */ + USBx->CNTR |= (USB_CNTR_CTRM | USB_CNTR_PMAOVRM | USB_CNTR_ERRM | + USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_DCON | + USB_CNTR_SOFM | USB_CNTR_ESOFM | USB_CNTR_L1REQM); + + return HAL_OK; +} + + +/** + * @brief USB_DRD_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_DRD_TypeDef *USBx) +{ + /* Force USB Reset */ + USBx->CNTR |= USB_CNTR_USBRST; + HAL_Delay(100); + /* Release USB Reset */ + USBx->CNTR &= ~USB_CNTR_USBRST; + HAL_Delay(30); + + return HAL_OK; +} + +/** + * @brief Return Host Core speed + * @param USBx Selected device + * @retval speed Host speed + * This parameter can be one of these values + * @arg USB_DRD_SPEED_FS Full speed mode + * @arg USB_DRD_SPEED_LS Low speed mode + */ +uint32_t USB_GetHostSpeed(USB_DRD_TypeDef const *USBx) +{ + if ((USBx->ISTR & USB_ISTR_LS_DCONN) != 0U) + { + return USB_DRD_SPEED_LS; + } + else + { + return USB_DRD_SPEED_FS; + } +} + +/** + * @brief Return Host Current Frame number + * @param USBx Selected device + * @retval current frame number + */ +uint32_t USB_GetCurrentFrame(USB_DRD_TypeDef const *USBx) +{ + return USBx->FNR & 0x7FFU; +} + +/** + * @brief Set the channel Kind (Single/double buffer mode) + * @param USBx Selected device + * @param phy_ch_num Selected device + * @param db_state double state can be USB_DRD_XXX_DBUFF_ENBALE/USB_DRD_XXX_DBUFF_DISABLE + * @retval HAL status + */ +HAL_StatusTypeDef USB_HC_DoubleBuffer(USB_DRD_TypeDef *USBx, + uint8_t phy_ch_num, uint8_t db_state) +{ + uint32_t tmp; + + if ((db_state == USB_DRD_BULK_DBUFF_ENBALE) || (db_state == USB_DRD_ISOC_DBUFF_DISABLE)) + { + tmp = (USB_DRD_GET_CHEP(USBx, phy_ch_num) | USB_CH_KIND) & USB_CHEP_DB_MSK; + } + else + { + tmp = USB_DRD_GET_CHEP(USBx, phy_ch_num) & (~USB_CH_KIND) & USB_CHEP_DB_MSK; + } + + /* Set the device speed in case using HUB FS with device LS */ + USB_DRD_SET_CHEP(USBx, phy_ch_num, tmp); + + return HAL_OK; +} + +/** + * @brief Initialize a host channel + * @param USBx Selected device + * @param phy_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 these values: + * @arg USB_DRD_SPEED_FULL Full speed mode + * @arg USB_DRD_SPEED_LOW Low speed mode + * @param ep_type Endpoint Type + * This parameter can be one of these values: + * @arg EP_TYPE_CTRL Control type + * @arg EP_TYPE_ISOC Isochronous 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 to 32K + * @retval HAL state + */ +HAL_StatusTypeDef USB_HC_Init(USB_DRD_TypeDef *USBx, uint8_t phy_ch_num, + uint8_t epnum, uint8_t dev_address, uint8_t speed, + uint8_t ep_type, uint16_t mps) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t wChRegVal; + uint32_t HostCoreSpeed; + + UNUSED(mps); + + wChRegVal = USB_DRD_GET_CHEP(USBx, phy_ch_num) & USB_CH_T_MASK; + + /* Initialize host Channel */ + switch (ep_type) + { + case EP_TYPE_CTRL: + wChRegVal |= USB_EP_CONTROL; + break; + + case EP_TYPE_BULK: + wChRegVal |= USB_EP_BULK; + break; + + case EP_TYPE_INTR: + wChRegVal |= USB_EP_INTERRUPT; + break; + + case EP_TYPE_ISOC: + wChRegVal |= USB_EP_ISOCHRONOUS; + break; + + default: + ret = HAL_ERROR; + break; + } + + /* Clear device address, Endpoint number and Low Speed Endpoint fields */ + wChRegVal &= ~(USB_CHEP_DEVADDR | + USB_CHEP_ADDR | + USB_CHEP_LSEP | + USB_CHEP_NAK | + USB_CHEP_KIND | + USB_CHEP_ERRTX | + USB_CHEP_ERRRX | + (0xFU << 27)); + + /* Set device address and Endpoint number associated to the channel */ + wChRegVal |= (((uint32_t)dev_address << USB_CHEP_DEVADDR_Pos) | + ((uint32_t)epnum & 0x0FU)); + + /* Get Host core Speed */ + HostCoreSpeed = USB_GetHostSpeed(USBx); + + /* Set the device speed in case using HUB FS with device LS */ + if ((speed == USB_DRD_SPEED_LS) && (HostCoreSpeed == USB_DRD_SPEED_FS)) + { + wChRegVal |= USB_CHEP_LSEP; + } + + /* Update the channel register value */ + USB_DRD_SET_CHEP(USBx, phy_ch_num, (wChRegVal | USB_CH_VTRX | USB_CH_VTTX)); + + return ret; +} + +/** + * @brief Start a transfer over a host channel + * @param USBx Selected device + * @param hc pointer to host channel structure + * @retval HAL state + */ +HAL_StatusTypeDef USB_HC_StartXfer(USB_DRD_TypeDef *USBx, USB_DRD_HCTypeDef *hc) +{ + uint32_t len; + uint32_t phy_ch_num = (uint32_t)hc->phy_ch_num; +#if (USE_USB_DOUBLE_BUFFER == 1U) + uint32_t ch_reg = USB_DRD_GET_CHEP(USBx, phy_ch_num); +#endif /* USE_USB_DOUBLE_BUFFER */ + + if (hc->ch_dir == CH_IN_DIR) /* In Channel */ + { + /* Multi packet transfer */ + if (hc->xfer_len > hc->max_packet) + { + len = hc->max_packet; + } + else + { + len = hc->xfer_len; + } + + if (hc->doublebuffer == 0U) + { + if ((hc->ep_type == EP_TYPE_BULK) || + (hc->ep_type == EP_TYPE_INTR)) + { + USB_DRD_CLEAR_RX_DTOG(USBx, phy_ch_num); + + /* Set Data PID */ + if (hc->data_pid == HC_PID_DATA1) + { + USB_DRD_RX_DTOG(USBx, phy_ch_num); + } + } + + /* Set RX buffer count */ + USB_DRD_SET_CHEP_RX_CNT(USBx, phy_ch_num, len); + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else if (hc->ep_type == EP_TYPE_BULK) + { + /* Double buffer activated */ + if ((hc->xfer_len > hc->max_packet)) + { + (void)USB_HC_DoubleBuffer(USBx, (uint8_t)phy_ch_num, USB_DRD_BULK_DBUFF_ENBALE); + + /* Set the Double buffer counter */ + USB_DRD_SET_CHEP_DBUF0_CNT(USBx, phy_ch_num, 0U, len); + USB_DRD_SET_CHEP_DBUF1_CNT(USBx, phy_ch_num, 0U, len); + } + else /* Switch to single buffer mode */ + { + (void)USB_HC_DoubleBuffer(USBx, (uint8_t)phy_ch_num, USB_DRD_BULK_DBUFF_DISABLE); + + /* Set RX buffer count */ + USB_DRD_SET_CHEP_RX_CNT(USBx, phy_ch_num, len); + } + } + else /* Isochronous */ + { + /* Set the Double buffer counter */ + USB_DRD_SET_CHEP_DBUF0_CNT(USBx, phy_ch_num, 0U, len); + USB_DRD_SET_CHEP_DBUF1_CNT(USBx, phy_ch_num, 0U, len); + } +#endif /* USE_USB_DOUBLE_BUFFER */ + + /* Enable host channel */ + USB_DRD_SET_CHEP_RX_STATUS(USBx, phy_ch_num, USB_CH_RX_VALID); + } + else /* Out Channel */ + { + /* Multi packet transfer */ + if (hc->xfer_len > hc->max_packet) + { + len = hc->max_packet; + } + else + { + len = hc->xfer_len; + } + + /* Configure and validate Tx endpoint */ + if (hc->doublebuffer == 0U) + { + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaadress, (uint16_t)len); + USB_DRD_SET_CHEP_TX_CNT(USBx, phy_ch_num, (uint16_t)len); + + /* SET PID SETUP */ + if ((hc->data_pid) == HC_PID_SETUP) + { + USB_DRD_CHEP_TX_SETUP(USBx, phy_ch_num); + } + + if ((hc->ep_type == EP_TYPE_BULK) || + (hc->ep_type == EP_TYPE_INTR)) + { + USB_DRD_CLEAR_TX_DTOG(USBx, phy_ch_num); + + /* Set Data PID */ + if (hc->data_pid == HC_PID_DATA1) + { + USB_DRD_TX_DTOG(USBx, phy_ch_num); + } + } + } +#if (USE_USB_DOUBLE_BUFFER == 1U) + else if (hc->ep_type == EP_TYPE_BULK) + { + (void)USB_HC_BULK_DB_StartXfer(USBx, hc, ch_reg, &len); + } + else + { + (void)USB_HC_ISO_DB_StartXfer(USBx, hc, len); + } +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + /* Enable host channel */ + USB_DRD_SET_CHEP_TX_STATUS(USBx, hc->phy_ch_num, USB_CH_TX_VALID); + } + + return HAL_OK; +} + +#if (USE_USB_DOUBLE_BUFFER == 1U) +/** + * @brief Start Transfer of Channel isochronous out double buffer + * @param USBx Selected device + * @param hc_num Host Channel number + * This parameter can be a value from 1 to 15 + * @param len Transfer Length + * @retval HAL state + */ +static HAL_StatusTypeDef USB_HC_ISO_DB_StartXfer(USB_DRD_TypeDef *USBx, + USB_DRD_HCTypeDef *hc, + uint32_t len) +{ + uint32_t phy_ch_num = (uint32_t)hc->phy_ch_num; + + /* check the DTOG_TX to determine in which buffer we should write */ + if ((USB_DRD_GET_CHEP(USBx, phy_ch_num) & USB_CH_DTOG_TX) != 0U) + { + USB_DRD_SET_CHEP_DBUF0_CNT(USBx, phy_ch_num, 1U, len); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr0, (uint16_t)len); + } + else + { + /* DTOGTX=0 */ + /* Set the Double buffer counter for pmabuffer0 */ + USB_DRD_SET_CHEP_DBUF1_CNT(USBx, phy_ch_num, 1U, len); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr1, (uint16_t)len); + } + + return HAL_OK; +} + +/** + * @brief Start Transfer of Channel bulk out double buffer + * @param USBx Selected device + * @param hc_num Host Channel number + * This parameter can be a value from 1 to 15 + * @param ch_reg snapshot of the CHEPR register + * @param len Transfer Length + * @retval HAL state + */ +static HAL_StatusTypeDef USB_HC_BULK_DB_StartXfer(USB_DRD_TypeDef *USBx, + USB_DRD_HCTypeDef *hc, + uint32_t ch_reg, + uint32_t *len) +{ + uint32_t phy_ch_num = (uint32_t)hc->phy_ch_num; + + /* -Double Buffer Mangement- */ + if (hc->xfer_len_db > hc->max_packet) + { + /* enable double buffer mode */ + (void)USB_HC_DoubleBuffer(USBx, (uint8_t)phy_ch_num, USB_DRD_BULK_DBUFF_ENBALE); + *len = hc->max_packet; + hc->xfer_len_db -= *len; + + /* Prepare two buffer before enabling host */ + if ((ch_reg & USB_CH_DTOG_TX) == 0U) + { + /* Write Buffer0 */ + USB_DRD_SET_CHEP_DBUF0_CNT(USBx, phy_ch_num, 1U, (uint16_t)*len); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr0, (uint16_t)*len); + } + else + { + /* Write Buffer1 */ + USB_DRD_SET_CHEP_DBUF1_CNT(USBx, phy_ch_num, 1U, (uint16_t)*len); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr1, (uint16_t)*len); + } + + hc->xfer_buff += *len; + + /* Multi packet transfer */ + if (hc->xfer_len_db > hc->max_packet) + { + hc->xfer_len_db -= *len; + } + else + { + *len = hc->xfer_len_db; + hc->xfer_len_db = 0U; + } + + if ((ch_reg & USB_CH_DTOG_TX) == 0U) + { + /* Write Buffer1 */ + USB_DRD_SET_CHEP_DBUF1_CNT(USBx, phy_ch_num, 1U, (uint16_t)*len); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr1, (uint16_t)*len); + } + else + { + /* Write Buffer0 */ + USB_DRD_SET_CHEP_DBUF0_CNT(USBx, phy_ch_num, 1U, (uint16_t)*len); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr0, (uint16_t)*len); + } + } + else + { + /* Disable bulk double buffer mode */ + (void)USB_HC_DoubleBuffer(USBx, (uint8_t)phy_ch_num, USB_DRD_BULK_DBUFF_DISABLE); + USB_WritePMA(USBx, hc->xfer_buff, hc->pmaaddr0, (uint16_t)*len); + USB_DRD_SET_CHEP_TX_CNT(USBx, phy_ch_num, (uint16_t)*len); + } + + return HAL_OK; +} +#endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ + + +/** + * @brief Halt a host channel in + * @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_IN_Halt(USB_DRD_TypeDef *USBx, uint8_t phy_ch) +{ + /* Set disable to Channel */ + USB_DRD_SET_CHEP_RX_STATUS(USBx, phy_ch, USB_CH_RX_DIS); + + return HAL_OK; +} + + +/** + * @brief Halt a host channel out + * @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_OUT_Halt(USB_DRD_TypeDef *USBx, uint8_t phy_ch) +{ + /* Set disable to Channel */ + USB_DRD_SET_CHEP_TX_STATUS(USBx, phy_ch, USB_CH_TX_DIS); + + return HAL_OK; +} + +/** + * @brief Stop Host Core + * @param USBx Selected device + * @retval HAL state + */ +HAL_StatusTypeDef USB_StopHost(USB_DRD_TypeDef *USBx) +{ + USBx->ISTR &= ~(USB_ISTR_DIR | USB_ISTR_L1REQ | + USB_ISTR_ESOF | USB_ISTR_SOF | + USB_ISTR_RESET | USB_ISTR_DCON | + USB_ISTR_SUSP | USB_ISTR_WKUP | + USB_ISTR_ERR | USB_ISTR_PMAOVR | + USB_ISTR_CTR); + + /* Set PowerDown */ + USBx->CNTR |= USB_CNTR_PDWN; + + /* Force a Reset */ + USBx->CNTR |= USB_CNTR_USBRST; + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_DRD_FS) */ +#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */ + +/** + * @} + */ diff --git a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_utils.c b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_utils.c index cb3e3c54f..0a94d18e7 100644 --- a/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_utils.c +++ b/stm32cube/stm32c0xx/drivers/src/stm32c0xx_ll_utils.c @@ -42,10 +42,6 @@ */ #define UTILS_MAX_FREQUENCY 48000000U /*!< Maximum frequency for system clock, in Hz */ -/* Defines used for HSE range */ -#define UTILS_HSE_FREQUENCY_MIN 4000000U /*!< Frequency min for HSE frequency, in Hz */ -#define UTILS_HSE_FREQUENCY_MAX 48000000U /*!< Frequency max for HSE frequency, in Hz */ - /* Defines used for FLASH latency according to HCLK Frequency */ #define UTILS_SCALE1_LATENCY1_FREQ 24000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 1 */ #define UTILS_SCALE1_LATENCY2_FREQ 48000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 1 */ @@ -54,51 +50,6 @@ */ /* Private macros ------------------------------------------------------------*/ -/** @addtogroup UTILS_LL_Private_Macros - * @{ - */ -#define IS_LL_UTILS_SYSCLK_DIV(__VALUE__) (((__VALUE__) == LL_RCC_HCLK_DIV_1) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_2) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_4) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_8) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_16) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_64) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_128) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_256) \ - || ((__VALUE__) == LL_RCC_HCLK_DIV_512)) - -#define IS_LL_UTILS_APB1_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB1_DIV_1) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_2) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_4) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_8) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_16)) - -#define IS_LL_UTILS_HSI_DIV(__VALUE__) (((__VALUE__) == LL_RCC_HSI_DIV_1) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_2) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_4) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_8) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_16) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_32) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_64) \ - || ((__VALUE__) == LL_RCC_HSI_DIV_128)) - -#define IS_LL_UTILS_HSIKER_DIV(__VALUE__) (((__VALUE__) == LL_RCC_HSIKER_DIV_1) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_2) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_3) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_4) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_5) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_6) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_7) \ - || ((__VALUE__) == LL_RCC_HSIKER_DIV_8)) - -#define IS_LL_UTILS_HSE_BYPASS(__STATE__) (((__STATE__) == LL_UTILS_HSEBYPASS_ON) \ - || ((__STATE__) == LL_UTILS_HSEBYPASS_OFF)) - -#define IS_LL_UTILS_HSE_FREQUENCY(__FREQUENCY__) (((__FREQUENCY__) >= UTILS_HSE_FREQUENCY_MIN)\ - && ((__FREQUENCY__) <= UTILS_HSE_FREQUENCY_MAX)) -/** - * @} - */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup UTILS_LL_Exported_Functions @@ -205,8 +156,6 @@ void LL_SetSystemCoreClock(uint32_t HCLKFrequency) SystemCoreClock = HCLKFrequency; } - - /** * @} */ @@ -263,7 +212,7 @@ ErrorStatus LL_SetFlashLatency(uint32_t HCLK_Frequency) timeout--; } while ((getlatency != latency) && (timeout > 0U)); - if(getlatency != latency) + if (getlatency != latency) { status = ERROR; } @@ -275,7 +224,6 @@ ErrorStatus LL_SetFlashLatency(uint32_t HCLK_Frequency) return status; } - /** * @} */ diff --git a/stm32cube/stm32c0xx/release_note.html b/stm32cube/stm32c0xx/release_note.html index ecd828274..2cc9d0cb6 100644 --- a/stm32cube/stm32c0xx/release_note.html +++ b/stm32cube/stm32c0xx/release_note.html @@ -11,8 +11,11 @@ div.columns{display: flex; gap: min(4vw, 1.5em);} div.column{flex: auto; overflow-x: auto;} div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} - ul.task-list{list-style: none;} + /* The extra [class] is a hack that increases specificity enough to + override a similar rule in reveal.js */ + ul.task-list[class]{list-style: none;} ul.task-list li input[type="checkbox"] { + font-size: inherit; width: 0.8em; margin: 0 0.8em 0.2em -1.6em; vertical-align: middle; @@ -62,22 +65,315 @@

Purpose

CodeSonar® static analysis tool, and developed in compliance with MISRA C® guidelines. Reports are available on demand.

-STM32Cube +STM32Cube

The drivers provided within this package -support the STM32C031/STM32C011 +support the STM32C031/STM32C011/C071 lines.

Update History

- - + +

Main Changes

    +
  • First official release of STM32CubeC0 Firmware +Package to support STM32CubeC071xx +devices
  • +
+

Contents

+

Features

+

STM32CubeC0 gathers in one single package all the generic embedded +software components required to develop an application on STM32C0 +microcontrollers.

+
    +
  • Production–ready HAL and LL API drivers, checked with Coverity® +static analysis tool, and developed in compliance with MISRA C® +guidelines.
  • +
  • CMSIS CORE, DSP and RTOS software components.
  • +
  • Consistent set of middleware components (Azure® RTOS USBX, +FileX/LevelX, ThreadX, mcuboot, mbed-crypto, and OpenBootloader).
  • +
  • Up to 187 examples and applications for easy +understanding, compatible with STM32CubeMX to facilitate the +configuration through a graphical tool.
  • +
  • New Templates_Board project for NUCLEO-C071RB demonstrating the +STM32CubeMX “Start my project from ST Board” providing an easy access to +ST boards’ features.
  • +
+

CMSIS Device Updates

+
    +
  • Support of STM32C071xx devices
  • +
  • Update CMSIS devices to include latest corrections
  • +
+

HAL/LL Drivers Updates

+
    +
  • HAL and LL drivers Official Release for STM32C071xx
  • +
  • Add USB HAL and LL drivers for STM32C071xx devices
  • +
  • General updates to fix known defects and implementation +enhancements
  • +
+

BSP Drivers Updates

+
    +
  • Update STM32C0xx_Nucleo BSP Driver to support NUCLEO-C071RB board +for STM32UC071xx devices
  • +
  • General updates to fix known defects and implementation +enhancements
  • +
+

Midlware Updates

+
    +
  • Major update in AzureRTOS Middlewares (new version V6.4.0)
  • +
  • Add the AzureRTOS USBX middleware component
  • +
  • Add mbed-crypto and mcuboot Middleware
  • +
+

Projects

+
    +
  • Add 75 new projects on NUCLEO-C071RB board: +
      +
    • 14 Applications
    • +
    • 58 examples
    • +
    • 1 HAL Templates
    • +
    • 1 LL Templates
    • +
    • 1 Board Templates
    • +
  • +
+

The STM32CubeC0 Firmware package comes with template +running on STMicroelectronics boards, organized by board and provided +with preconfigured projects for the main supported toolchains. The +exhaustive list of projects is provided in this table STM32CubeProjectsList.html

+ + + + + + + + + + + + + + + +
NameVersionRelease note
ProjectsV1.2.0release notes
+

Components

+

The components flagged by “” have changed since the previous release. +“” are new.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Drivers
NameVersionRelease note
CMSISV5.9.0release +notes
STM32C0xx CMSIS V1.2.0release +notes
STM32C0xx HAL/LL V1.2.0release +notes
BSP STM32C0xx NUCLEO V1.1.0release +notes
BSP STM32C0316-DK V1.0.1release +notes
BSP STM32C0116-DK V1.1.1release +notes
BSP ComponentsV7.1.0release +notes
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameVersionRelease note
OpenBootloaderV6.0.0release +notes
Azure RTOS ThreadX threadx-6.4.0.240419release +notes
Azure RTOS FileX filex-6.4.0.240419release +notes
Azure RTOS LeveLX levelx-6.4.0.240419release +notes
Azure RTOS USBX usbx-6.4.0.240419release +notes
mbed-crypto mbed-tls-v2.28.8release +notes
mcuboot v1.7.2.24release +notes
+

Development Toolchains and +Compilers

+ +

Supported Devices and boards

+
    +
  • STM32C071xB and STM32C071x8 devices
  • +
  • STM32C031 and STM32C011 devices
  • +
  • NUCLEO-C071RB board rev.B
  • +
  • NUCLEO-C031C6 board rev.B
  • +
  • STM32C0116-DK board rev.B
  • +
  • STM32C0316-DK board rev.B
  • +
+

Dependencies

+
    +
  • STM32CubeMX V6.12.0 +
      +
    • Projects (Applications and Examples) are generated using STM32CubeMX +version V6.12.0.
    • +
  • +
+

Known Limitations

+
    +
  • Some projects are not generated with STM32CubeMX tool. For the +exhaustive list please refer to this table STM32CubeProjectsList.html

  • +
  • The following projects are not supported with STM32CubeIDE +toolchain (Release):

    +
      +
    • NUCLEO-C071RB/Examples_LL/SPI/SPI_OneBoard_HalfDuplex_IT_Init
    • +
  • +
  • The following projects are not supported with MDK-ARM toolchain +:

    +
      +
    • NUCLEO-C071RB/Examples_LL/I2C/I2C_OneBoard_AdvCommunication_DMAAndIT_Init
    • +
  • +
+

Backward Compatibility

+
    +
  • Not applicable
  • +
+
+
+
+ + +
+

Main Changes

+
  • Maintenance Release of STM32CubeC0 Firmware Package
@@ -166,8 +462,8 @@

Main Changes

  • Update of AzureRtos Middleware to new version V6.2.0
  • Update of OpenBootloader to new version V6.1.0
  • -

    Contents

    -

    Projects

    +

    Contents

    +

    Projects

    The STM32CubeC0 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains. The @@ -192,7 +488,7 @@

    Projects

    -

    Components

    +

    Components

    The Project categories flagged by “” have changed since the previous release. “” are new.

    @@ -305,8 +601,8 @@

    Components

    -

    Development Toolchains and -Compilers

    +

    Development Toolchains +and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patch available here: @@ -325,14 +621,15 @@

      Development Toolchains and

  • STM32CubeIDE v1.12.0 using GCC10
  • -

    Supported Devices and boards

    +

    Supported Devices and +boards

    • STM32C031 and STM32C011 devices Rev A
    • NUCLEO-C031C6 board rev.B
    • STM32C0116-DK board rev.B
    • STM32C0316-DK board rev.B
    -

    Dependencies

    +

    Dependencies

    • STM32CubeMX V6.9.0
        @@ -340,11 +637,11 @@

        Dependencies

        version V6.9.0.
    -

    Known Limitations

    +

    Known Limitations

    • Not applicable
    -

    Backward Compatibility

    +

    Backward Compatibility

    • HAL_SYSCFG_GetPinBinding() and LL_SYSCFG_GetConfigPinMux() are updated.
    • @@ -356,7 +653,7 @@

      Backward Compatibility

      -

      Main Changes

      +

      Main Changes

      • Patch Release of STM32CubeC0 Firmware Package

        @@ -369,8 +666,8 @@

        Main Changes

      • Update RCC LL driver by adding missing AHB Prescaler.

    -

    Contents

    -

    Projects

    +

    Contents

    +

    Projects

    The STM32CubeC0 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains. The @@ -396,7 +693,7 @@

    Projects

    -

    Components

    +

    Components

    The Project categories flagged by “” have changed since the previous release. “” are new.

    @@ -507,13 +804,13 @@

    Components

    -

    Main Changes

    +

    Main Changes

    • First Official Release of STM32CubeC0 Firmware Package
    -

    Contents

    -

    Projects

    +

    Contents

    +

    Projects

    The STM32CubeC0 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains. The @@ -538,7 +835,7 @@

    Projects

    -

    Components

    +

    Components

    @@ -639,7 +936,7 @@

    Components

    Drivers
    -

    Development Toolchains +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, @@ -659,7 +956,7 @@

      Development Toolchains

  • STM32CubeIDE v1.9.0 using GCC10
  • -

    Supported Devices and +

    Supported Devices and boards

    • STM32C031 and STM32C011 devices Rev A
    • @@ -667,7 +964,7 @@

      Supported Devices and
    • STM32C0116-DK board rev.B
    • STM32C0316-DK board rev.B
    -

    Dependencies

    +

    Dependencies

    • STM32CubeMX V6.5.0
        @@ -675,11 +972,11 @@

        Dependencies

        version V6.5.0.
    -

    Known Limitations

    +

    Known Limitations

    • None
    -

    Backward Compatibility

    +

    Backward Compatibility

    • Not applicable
    diff --git a/stm32cube/stm32c0xx/soc/stm32c011xx.h b/stm32cube/stm32c0xx/soc/stm32c011xx.h index 0b4813bf6..7ce9b55ca 100644 --- a/stm32cube/stm32c0xx/soc/stm32c011xx.h +++ b/stm32cube/stm32c0xx/soc/stm32c011xx.h @@ -225,7 +225,7 @@ typedef struct __IO uint32_t FPR1; /*!< EXTI Falling Pending Register 1, Address offset: 0x10 */ uint32_t RESERVED1[3]; /*!< Reserved 1, 0x14 -- 0x1C */ uint32_t RESERVED2[5]; /*!< Reserved 2, 0x20 -- 0x30 */ - uint32_t RESERVED3[11]; /*!< Reserved 3, 0x34 -- 0x5C */ + uint32_t RESERVED3[11]; /*!< Reserved 3, 0x3C -- 0x5F */ __IO uint32_t EXTICR[4]; /*!< EXTI External Interrupt Configuration Register, 0x60 -- 0x6C */ uint32_t RESERVED4[4]; /*!< Reserved 4, 0x70 -- 0x7C */ __IO uint32_t IMR1; /*!< EXTI Interrupt Mask Register 1, Address offset: 0x80 */ @@ -421,7 +421,7 @@ typedef struct __IO uint32_t CFGR2; /*!< SYSCFG configuration register 2, Address offset: 0x18 */ uint32_t RESERVED1[8]; /*!< Reserved 0x1C --0x38 */ __IO uint32_t CFGR3; /*!< SYSCFG configuration register 3, Address offset: 0x3C */ - uint32_t RESERVED2[16]; /*!< Reserved 0x40 --0x7C */ + uint32_t RESERVED2[16]; /*!< Reserved 0x40 --0x7C */ __IO uint32_t IT_LINE_SR[32]; /*!< SYSCFG configuration IT_LINE register, Address offset: 0x80 */ } SYSCFG_TypeDef; @@ -498,7 +498,14 @@ typedef struct #define PERIPH_BASE (0x40000000UL) /*!< Peripheral base address */ #define IOPORT_BASE (0x50000000UL) /*!< IOPORT base address */ -#define SRAM_SIZE_MAX (0x00001500UL) /*!< maximum SRAM size (up to 6 KBytes) */ +#define SRAM_SIZE_MAX (0x00001800UL) /*!< maximum SRAM size (up to 6 KBytes) */ + +#define FLASH_SIZE_DEFAULT 0x8000U /*!< Flash memory default size */ + +#define FLASH_SIZE ((((*((uint16_t *)FLASHSIZE_BASE)) == 0xFFFFU)) ? FLASH_SIZE_DEFAULT : \ + ((((*((uint16_t *)FLASHSIZE_BASE)) == 0x0000U)) ? FLASH_SIZE_DEFAULT : \ + (((uint32_t)(*((uint16_t *)FLASHSIZE_BASE)) & (0xFFFFU)) << 10U))) + /*!< Peripheral memory map */ #define APBPERIPH_BASE (PERIPH_BASE) #define AHBPERIPH_BASE (PERIPH_BASE + 0x00020000UL) @@ -546,6 +553,7 @@ typedef struct #define DMAMUX1_RequestGenerator0_BASE (DMAMUX1_BASE + 0x00000100UL) #define DMAMUX1_RequestGenerator1_BASE (DMAMUX1_BASE + 0x00000104UL) #define DMAMUX1_RequestGenerator2_BASE (DMAMUX1_BASE + 0x00000108UL) +#define DMAMUX1_RequestGenerator3_BASE (DMAMUX1_BASE + 0x0000010CUL) #define DMAMUX1_ChannelStatus_BASE (DMAMUX1_BASE + 0x00000080UL) #define DMAMUX1_RequestGenStatus_BASE (DMAMUX1_BASE + 0x00000140UL) @@ -606,10 +614,10 @@ typedef struct #define DMAMUX1_Channel1 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel1_BASE) #define DMAMUX1_Channel2 ((DMAMUX_Channel_TypeDef *) DMAMUX1_Channel2_BASE) - #define DMAMUX1_RequestGenerator0 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator0_BASE) #define DMAMUX1_RequestGenerator1 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator1_BASE) #define DMAMUX1_RequestGenerator2 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator2_BASE) +#define DMAMUX1_RequestGenerator3 ((DMAMUX_RequestGen_TypeDef *) DMAMUX1_RequestGenerator3_BASE) #define DMAMUX1_ChannelStatus ((DMAMUX_ChannelStatus_TypeDef *) DMAMUX1_ChannelStatus_BASE) #define DMAMUX1_RequestGenStatus ((DMAMUX_RequestGenStatus_TypeDef *) DMAMUX1_RequestGenStatus_BASE) @@ -1283,6 +1291,10 @@ typedef struct #define ADC_AWD2CR_AWD2CH_16 (0x10000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00010000 */ #define ADC_AWD2CR_AWD2CH_17 (0x20000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00020000 */ #define ADC_AWD2CR_AWD2CH_18 (0x40000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00040000 */ +#define ADC_AWD2CR_AWD2CH_19 (0x80000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00080000 */ +#define ADC_AWD2CR_AWD2CH_20 (0x100000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00100000 */ +#define ADC_AWD2CR_AWD2CH_21 (0x20000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00200000 */ +#define ADC_AWD2CR_AWD2CH_22 (0x40000UL << ADC_AWD2CR_AWD2CH_Pos) /*!< 0x00400000 */ /******************** Bit definition for ADC_AWD3CR register ****************/ #define ADC_AWD3CR_AWD3CH_Pos (0U) @@ -1307,6 +1319,10 @@ typedef struct #define ADC_AWD3CR_AWD3CH_16 (0x10000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00010000 */ #define ADC_AWD3CR_AWD3CH_17 (0x20000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00020000 */ #define ADC_AWD3CR_AWD3CH_18 (0x40000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00040000 */ +#define ADC_AWD3CR_AWD3CH_19 (0x80000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00080000 */ +#define ADC_AWD3CR_AWD3CH_20 (0x100000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00100000 */ +#define ADC_AWD3CR_AWD3CH_21 (0x200000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00200000 */ +#define ADC_AWD3CR_AWD3CH_22 (0x400000UL << ADC_AWD3CR_AWD3CH_Pos) /*!< 0x00400000 */ /******************** Bit definition for ADC_CALFACT register ***************/ #define ADC_CALFACT_CALFACT_Pos (0U) @@ -1523,18 +1539,6 @@ typedef struct #define DMA_IFCR_CTEIF3_Pos (11U) #define DMA_IFCR_CTEIF3_Msk (0x1UL << DMA_IFCR_CTEIF3_Pos) /*!< 0x00000800 */ #define DMA_IFCR_CTEIF3 DMA_IFCR_CTEIF3_Msk /*!< Channel 3 Transfer Error clear */ -#define DMA_IFCR_CGIF4_Pos (12U) -#define DMA_IFCR_CGIF4_Msk (0x1UL << DMA_IFCR_CGIF4_Pos) /*!< 0x00001000 */ -#define DMA_IFCR_CGIF4 DMA_IFCR_CGIF4_Msk /*!< Channel 4 Global interrupt clear */ -#define DMA_IFCR_CTCIF4_Pos (13U) -#define DMA_IFCR_CTCIF4_Msk (0x1UL << DMA_IFCR_CTCIF4_Pos) /*!< 0x00002000 */ -#define DMA_IFCR_CTCIF4 DMA_IFCR_CTCIF4_Msk /*!< Channel 4 Transfer Complete clear */ -#define DMA_IFCR_CHTIF4_Pos (14U) -#define DMA_IFCR_CHTIF4_Msk (0x1UL << DMA_IFCR_CHTIF4_Pos) /*!< 0x00004000 */ -#define DMA_IFCR_CHTIF4 DMA_IFCR_CHTIF4_Msk /*!< Channel 4 Half Transfer clear */ -#define DMA_IFCR_CTEIF4_Pos (15U) -#define DMA_IFCR_CTEIF4_Msk (0x1UL << DMA_IFCR_CTEIF4_Pos) /*!< 0x00008000 */ -#define DMA_IFCR_CTEIF4 DMA_IFCR_CTEIF4_Msk /*!< Channel 4 Transfer Error clear */ /******************* Bit definition for DMA_CCR register ********************/ #define DMA_CCR_EN_Pos (0U) @@ -1953,7 +1957,6 @@ typedef struct #define EXTI_RPR1_RPIF15_Msk (0x1UL << EXTI_RPR1_RPIF15_Pos) /*!< 0x00008000 */ #define EXTI_RPR1_RPIF15 EXTI_RPR1_RPIF15_Msk /*!< Rising Pending Interrupt Flag on line 15 */ - /******************* Bit definition for EXTI_FPR1 register ******************/ #define EXTI_FPR1_FPIF0_Pos (0U) #define EXTI_FPR1_FPIF0_Msk (0x1UL << EXTI_FPR1_FPIF0_Pos) /*!< 0x00000001 */ @@ -2093,8 +2096,8 @@ typedef struct #define EXTI_EXTICR4_EXTI13_Msk (0x7UL << EXTI_EXTICR4_EXTI13_Pos) /*!< 0x00000700 */ #define EXTI_EXTICR4_EXTI13 EXTI_EXTICR4_EXTI13_Msk /*!< EXTI 13 configuration */ #define EXTI_EXTICR4_EXTI13_0 (0x1UL << EXTI_EXTICR4_EXTI13_Pos) /*!< 0x00000100 */ -#define EXTI_EXTICR4_EXTI13_1 (0x2UL << EXTI_EXTICR4_EXTI13_Pos) /*!< 0x00000200 */ -#define EXTI_EXTICR4_EXTI13_2 (0x4UL << EXTI_EXTICR4_EXTI13_Pos) /*!< 0x00000400 */ +#define EXTI_EXTICR4_EXTI13_1 (0x2UL << EXTI_EXTICR4_EXTI13_Pos) /*!< 0x00000200 */ +#define EXTI_EXTICR4_EXTI13_2 (0x4UL << EXTI_EXTICR4_EXTI13_Pos) /*!< 0x00000400 */ #define EXTI_EXTICR4_EXTI14_Pos (16U) #define EXTI_EXTICR4_EXTI14_Msk (0x7UL << EXTI_EXTICR4_EXTI14_Pos) /*!< 0x00070000 */ #define EXTI_EXTICR4_EXTI14 EXTI_EXTICR4_EXTI14_Msk /*!< EXTI 14 configuration */ @@ -2157,57 +2160,21 @@ typedef struct #define EXTI_IMR1_IM15_Pos (15U) #define EXTI_IMR1_IM15_Msk (0x1UL << EXTI_IMR1_IM15_Pos) /*!< 0x00008000 */ #define EXTI_IMR1_IM15 EXTI_IMR1_IM15_Msk /*!< Interrupt Mask on line 15 */ -#define EXTI_IMR1_IM16_Pos (16U) -#define EXTI_IMR1_IM16_Msk (0x1UL << EXTI_IMR1_IM16_Pos) /*!< 0x00010000 */ -#define EXTI_IMR1_IM16 EXTI_IMR1_IM16_Msk /*!< Interrupt Mask on line 16 */ -#define EXTI_IMR1_IM17_Pos (17U) -#define EXTI_IMR1_IM17_Msk (0x1UL << EXTI_IMR1_IM17_Pos) /*!< 0x00020000 */ -#define EXTI_IMR1_IM17 EXTI_IMR1_IM17_Msk /*!< Interrupt Mask on line 17 */ -#define EXTI_IMR1_IM18_Pos (18U) -#define EXTI_IMR1_IM18_Msk (0x1UL << EXTI_IMR1_IM18_Pos) /*!< 0x00040000 */ -#define EXTI_IMR1_IM18 EXTI_IMR1_IM18_Msk /*!< Interrupt Mask on line 18 */ #define EXTI_IMR1_IM19_Pos (19U) #define EXTI_IMR1_IM19_Msk (0x1UL << EXTI_IMR1_IM19_Pos) /*!< 0x00080000 */ #define EXTI_IMR1_IM19 EXTI_IMR1_IM19_Msk /*!< Interrupt Mask on line 19 */ -#define EXTI_IMR1_IM20_Pos (20U) -#define EXTI_IMR1_IM20_Msk (0x1UL << EXTI_IMR1_IM20_Pos) /*!< 0x00100000 */ -#define EXTI_IMR1_IM20 EXTI_IMR1_IM20_Msk /*!< Interrupt Mask on line 20 */ -#define EXTI_IMR1_IM21_Pos (21U) -#define EXTI_IMR1_IM21_Msk (0x1UL << EXTI_IMR1_IM21_Pos) /*!< 0x00200000 */ -#define EXTI_IMR1_IM21 EXTI_IMR1_IM21_Msk /*!< Interrupt Mask on line 21 */ -#define EXTI_IMR1_IM22_Pos (22U) -#define EXTI_IMR1_IM22_Msk (0x1UL << EXTI_IMR1_IM22_Pos) /*!< 0x00400000 */ -#define EXTI_IMR1_IM22 EXTI_IMR1_IM22_Msk /*!< Interrupt Mask on line 22 */ #define EXTI_IMR1_IM23_Pos (23U) #define EXTI_IMR1_IM23_Msk (0x1UL << EXTI_IMR1_IM23_Pos) /*!< 0x00800000 */ #define EXTI_IMR1_IM23 EXTI_IMR1_IM23_Msk /*!< Interrupt Mask on line 23 */ -#define EXTI_IMR1_IM24_Pos (24U) -#define EXTI_IMR1_IM24_Msk (0x1UL << EXTI_IMR1_IM24_Pos) /*!< 0x01000000 */ -#define EXTI_IMR1_IM24 EXTI_IMR1_IM24_Msk /*!< Interrupt Mask on line 24 */ #define EXTI_IMR1_IM25_Pos (25U) #define EXTI_IMR1_IM25_Msk (0x1UL << EXTI_IMR1_IM25_Pos) /*!< 0x02000000 */ #define EXTI_IMR1_IM25 EXTI_IMR1_IM25_Msk /*!< Interrupt Mask on line 25 */ -#define EXTI_IMR1_IM26_Pos (26U) -#define EXTI_IMR1_IM26_Msk (0x1UL << EXTI_IMR1_IM26_Pos) /*!< 0x04000000 */ -#define EXTI_IMR1_IM26 EXTI_IMR1_IM26_Msk /*!< Interrupt Mask on line 26 */ -#define EXTI_IMR1_IM27_Pos (27U) -#define EXTI_IMR1_IM27_Msk (0x1UL << EXTI_IMR1_IM27_Pos) /*!< 0x08000000 */ -#define EXTI_IMR1_IM27 EXTI_IMR1_IM27_Msk /*!< Interrupt Mask on line 27 */ -#define EXTI_IMR1_IM28_Pos (28U) -#define EXTI_IMR1_IM28_Msk (0x1UL << EXTI_IMR1_IM28_Pos) /*!< 0x10000000 */ -#define EXTI_IMR1_IM28 EXTI_IMR1_IM28_Msk /*!< Interrupt Mask on line 28 */ -#define EXTI_IMR1_IM29_Pos (29U) -#define EXTI_IMR1_IM29_Msk (0x1UL << EXTI_IMR1_IM29_Pos) /*!< 0x20000000 */ -#define EXTI_IMR1_IM29 EXTI_IMR1_IM29_Msk /*!< Interrupt Mask on line 29 */ -#define EXTI_IMR1_IM30_Pos (30U) -#define EXTI_IMR1_IM30_Msk (0x1UL << EXTI_IMR1_IM30_Pos) /*!< 0x40000000 */ -#define EXTI_IMR1_IM30 EXTI_IMR1_IM30_Msk /*!< Interrupt Mask on line 30 */ #define EXTI_IMR1_IM31_Pos (31U) -#define EXTI_IMR1_IM31_Msk (0x1UL << EXTI_IMR1_IM31_Pos) /*!< 0x80000000 */ +#define EXTI_IMR1_IM31_Msk (0x1UL << EXTI_IMR1_IM31_Pos) /*!< 0x80000000 */ #define EXTI_IMR1_IM31 EXTI_IMR1_IM31_Msk /*!< Interrupt Mask on line 31 */ #define EXTI_IMR1_IM_Pos (0U) -#define EXTI_IMR1_IM_Msk (0xFEAFFFFFUL << EXTI_IMR1_IM_Pos) /*!< 0xFEAFFFFF */ +#define EXTI_IMR1_IM_Msk (0x0288FFFFUL << EXTI_IMR1_IM_Pos) /*!< 0x288FFFF */ #define EXTI_IMR1_IM EXTI_IMR1_IM_Msk /*!< Interrupt Mask All */ /******************* Bit definition for EXTI_EMR1 register ******************/ @@ -2272,34 +2239,17 @@ typedef struct #define EXTI_EMR1_EM19_Pos (19U) #define EXTI_EMR1_EM19_Msk (0x1UL << EXTI_EMR1_EM19_Pos) /*!< 0x00080000 */ #define EXTI_EMR1_EM19 EXTI_EMR1_EM19_Msk /*!< Event Mask on line 19 */ -#define EXTI_EMR1_EM21_Pos (21U) -#define EXTI_EMR1_EM21_Msk (0x1UL << EXTI_EMR1_EM21_Pos) /*!< 0x00200000 */ -#define EXTI_EMR1_EM21 EXTI_EMR1_EM21_Msk /*!< Event Mask on line 21 */ #define EXTI_EMR1_EM23_Pos (23U) #define EXTI_EMR1_EM23_Msk (0x1UL << EXTI_EMR1_EM23_Pos) /*!< 0x00800000 */ #define EXTI_EMR1_EM23 EXTI_EMR1_EM23_Msk /*!< Event Mask on line 23 */ #define EXTI_EMR1_EM25_Pos (25U) #define EXTI_EMR1_EM25_Msk (0x1UL << EXTI_EMR1_EM25_Pos) /*!< 0x02000000 */ #define EXTI_EMR1_EM25 EXTI_EMR1_EM25_Msk /*!< Event Mask on line 25 */ -#define EXTI_EMR1_EM26_Pos (26U) -#define EXTI_EMR1_EM26_Msk (0x1UL << EXTI_EMR1_EM26_Pos) /*!< 0x04000000 */ -#define EXTI_EMR1_EM26 EXTI_EMR1_EM26_Msk /*!< Event Mask on line 26 */ -#define EXTI_EMR1_EM27_Pos (27U) -#define EXTI_EMR1_EM27_Msk (0x1UL << EXTI_EMR1_EM27_Pos) /*!< 0x08000000 */ -#define EXTI_EMR1_EM27 EXTI_EMR1_EM27_Msk /*!< Event Mask on line 27 */ -#define EXTI_EMR1_EM28_Pos (28U) -#define EXTI_EMR1_EM28_Msk (0x1UL << EXTI_EMR1_EM28_Pos) /*!< 0x10000000 */ -#define EXTI_EMR1_EM28 EXTI_EMR1_EM28_Msk /*!< Event Mask on line 28 */ -#define EXTI_EMR1_EM29_Pos (29U) -#define EXTI_EMR1_EM29_Msk (0x1UL << EXTI_EMR1_EM29_Pos) /*!< 0x20000000 */ -#define EXTI_EMR1_EM29 EXTI_EMR1_EM29_Msk /*!< Event Mask on line 29 */ -#define EXTI_EMR1_EM30_Pos (30U) -#define EXTI_EMR1_EM30_Msk (0x1UL << EXTI_EMR1_EM30_Pos) /*!< 0x40000000 */ -#define EXTI_EMR1_EM30 EXTI_EMR1_EM30_Msk /*!< Event Mask on line 30 */ #define EXTI_EMR1_EM31_Pos (31U) #define EXTI_EMR1_EM31_Msk (0x1UL << EXTI_EMR1_EM31_Pos) /*!< 0x80000000 */ #define EXTI_EMR1_EM31 EXTI_EMR1_EM31_Msk /*!< Event Mask on line 31 */ + /******************************************************************************/ /* */ /* FLASH */ @@ -2384,7 +2334,7 @@ typedef struct #define FLASH_CR_MER1_Msk (0x1UL << FLASH_CR_MER1_Pos) /*!< 0x00000004 */ #define FLASH_CR_MER1 FLASH_CR_MER1_Msk #define FLASH_CR_PNB_Pos (3U) -#define FLASH_CR_PNB_Msk (0xFUL << FLASH_CR_PNB_Pos) /*!< 0x000001F8 */ +#define FLASH_CR_PNB_Msk (0xFUL << FLASH_CR_PNB_Pos) /*!< 0x00000078 */ #define FLASH_CR_PNB FLASH_CR_PNB_Msk #define FLASH_CR_STRT_Pos (16U) #define FLASH_CR_STRT_Msk (0x1UL << FLASH_CR_STRT_Pos) /*!< 0x00010000 */ @@ -2417,23 +2367,6 @@ typedef struct #define FLASH_CR_LOCK_Msk (0x1UL << FLASH_CR_LOCK_Pos) /*!< 0x80000000 */ #define FLASH_CR_LOCK FLASH_CR_LOCK_Msk -/******************* Bits definition for FLASH_ECCR register ****************/ -#define FLASH_ECCR_ADDR_ECC_Pos (0U) -#define FLASH_ECCR_ADDR_ECC_Msk (0x3FFFUL << FLASH_ECCR_ADDR_ECC_Pos) /*!< 0x00003FFF */ -#define FLASH_ECCR_ADDR_ECC FLASH_ECCR_ADDR_ECC_Msk -#define FLASH_ECCR_SYSF_ECC_Pos (20U) -#define FLASH_ECCR_SYSF_ECC_Msk (0x1UL << FLASH_ECCR_SYSF_ECC_Pos) /*!< 0x00100000 */ -#define FLASH_ECCR_SYSF_ECC FLASH_ECCR_SYSF_ECC_Msk -#define FLASH_ECCR_ECCCIE_Pos (24U) -#define FLASH_ECCR_ECCCIE_Msk (0x1UL << FLASH_ECCR_ECCCIE_Pos) /*!< 0x01000000 */ -#define FLASH_ECCR_ECCCIE FLASH_ECCR_ECCCIE_Msk -#define FLASH_ECCR_ECCC_Pos (30U) -#define FLASH_ECCR_ECCC_Msk (0x1UL << FLASH_ECCR_ECCC_Pos) /*!< 0x40000000 */ -#define FLASH_ECCR_ECCC FLASH_ECCR_ECCC_Msk -#define FLASH_ECCR_ECCD_Pos (31U) -#define FLASH_ECCR_ECCD_Msk (0x1UL << FLASH_ECCR_ECCD_Pos) /*!< 0x80000000 */ -#define FLASH_ECCR_ECCD FLASH_ECCR_ECCD_Msk - /******************* Bits definition for FLASH_OPTR register ****************/ #define FLASH_OPTR_RDP_Pos (0U) #define FLASH_OPTR_RDP_Msk (0xFFUL << FLASH_OPTR_RDP_Pos) /*!< 0x000000FF */ @@ -2441,16 +2374,16 @@ typedef struct #define FLASH_OPTR_BOR_EN_Pos (8U) #define FLASH_OPTR_BOR_EN_Msk (0x1UL << FLASH_OPTR_BOR_EN_Pos) /*!< 0x00000100 */ #define FLASH_OPTR_BOR_EN FLASH_OPTR_BOR_EN_Msk -#define FLASH_OPTR_BORF_LEV_Pos (9U) -#define FLASH_OPTR_BORF_LEV_Msk (0x3UL << FLASH_OPTR_BORF_LEV_Pos) /*!< 0x00000600 */ -#define FLASH_OPTR_BORF_LEV FLASH_OPTR_BORF_LEV_Msk -#define FLASH_OPTR_BORF_LEV_0 (0x1UL << FLASH_OPTR_BORF_LEV_Pos) /*!< 0x00000200 */ -#define FLASH_OPTR_BORF_LEV_1 (0x2UL << FLASH_OPTR_BORF_LEV_Pos) /*!< 0x00000400 */ -#define FLASH_OPTR_BORR_LEV_Pos (11U) -#define FLASH_OPTR_BORR_LEV_Msk (0x3UL << FLASH_OPTR_BORR_LEV_Pos) /*!< 0x00001800 */ +#define FLASH_OPTR_BORR_LEV_Pos (9U) +#define FLASH_OPTR_BORR_LEV_Msk (0x3UL << FLASH_OPTR_BORR_LEV_Pos) /*!< 0x00000600 */ #define FLASH_OPTR_BORR_LEV FLASH_OPTR_BORR_LEV_Msk -#define FLASH_OPTR_BORR_LEV_0 (0x1UL << FLASH_OPTR_BORR_LEV_Pos) /*!< 0x00000800 */ -#define FLASH_OPTR_BORR_LEV_1 (0x2UL << FLASH_OPTR_BORR_LEV_Pos) /*!< 0x00001000 */ +#define FLASH_OPTR_BORR_LEV_0 (0x1UL << FLASH_OPTR_BORR_LEV_Pos) /*!< 0x00000200 */ +#define FLASH_OPTR_BORR_LEV_1 (0x2UL << FLASH_OPTR_BORR_LEV_Pos) /*!< 0x00000400 */ +#define FLASH_OPTR_BORF_LEV_Pos (11U) +#define FLASH_OPTR_BORF_LEV_Msk (0x3UL << FLASH_OPTR_BORF_LEV_Pos) /*!< 0x00001800 */ +#define FLASH_OPTR_BORF_LEV FLASH_OPTR_BORF_LEV_Msk +#define FLASH_OPTR_BORF_LEV_0 (0x1UL << FLASH_OPTR_BORF_LEV_Pos) /*!< 0x00000800 */ +#define FLASH_OPTR_BORF_LEV_1 (0x2UL << FLASH_OPTR_BORF_LEV_Pos) /*!< 0x00001000 */ #define FLASH_OPTR_nRST_STOP_Pos (13U) #define FLASH_OPTR_nRST_STOP_Msk (0x1UL << FLASH_OPTR_nRST_STOP_Pos) /*!< 0x00002000 */ #define FLASH_OPTR_nRST_STOP FLASH_OPTR_nRST_STOP_Msk @@ -2475,6 +2408,9 @@ typedef struct #define FLASH_OPTR_RAM_PARITY_CHECK_Pos (22U) #define FLASH_OPTR_RAM_PARITY_CHECK_Msk (0x1UL << FLASH_OPTR_RAM_PARITY_CHECK_Pos) /*!< 0x00400000 */ #define FLASH_OPTR_RAM_PARITY_CHECK FLASH_OPTR_RAM_PARITY_CHECK_Msk +#define FLASH_OPTR_SECURE_MUXING_EN_Pos (23U) +#define FLASH_OPTR_SECURE_MUXING_EN_Msk (0x1UL << FLASH_OPTR_SECURE_MUXING_EN_Pos) /*!< 0x00800000 */ +#define FLASH_OPTR_SECURE_MUXING_EN FLASH_OPTR_SECURE_MUXING_EN_Msk #define FLASH_OPTR_nBOOT_SEL_Pos (24U) #define FLASH_OPTR_nBOOT_SEL_Msk (0x1UL << FLASH_OPTR_nBOOT_SEL_Pos) /*!< 0x01000000 */ #define FLASH_OPTR_nBOOT_SEL FLASH_OPTR_nBOOT_SEL_Msk @@ -2495,12 +2431,12 @@ typedef struct /****************** Bits definition for FLASH_PCROP1ASR register ************/ #define FLASH_PCROP1ASR_PCROP1A_STRT_Pos (0U) -#define FLASH_PCROP1ASR_PCROP1A_STRT_Msk (0x7FUL << FLASH_PCROP1ASR_PCROP1A_STRT_Pos) /*!< 0x0000007F */ +#define FLASH_PCROP1ASR_PCROP1A_STRT_Msk (0x3FUL << FLASH_PCROP1ASR_PCROP1A_STRT_Pos) /*!< 0x0000003F */ #define FLASH_PCROP1ASR_PCROP1A_STRT FLASH_PCROP1ASR_PCROP1A_STRT_Msk /****************** Bits definition for FLASH_PCROP1AER register ************/ #define FLASH_PCROP1AER_PCROP1A_END_Pos (0U) -#define FLASH_PCROP1AER_PCROP1A_END_Msk (0x7FUL << FLASH_PCROP1AER_PCROP1A_END_Pos) /*!< 0x0000007F */ +#define FLASH_PCROP1AER_PCROP1A_END_Msk (0x3FUL << FLASH_PCROP1AER_PCROP1A_END_Pos) /*!< 0x0000003F */ #define FLASH_PCROP1AER_PCROP1A_END FLASH_PCROP1AER_PCROP1A_END_Msk #define FLASH_PCROP1AER_PCROP_RDP_Pos (31U) #define FLASH_PCROP1AER_PCROP_RDP_Msk (0x1UL << FLASH_PCROP1AER_PCROP_RDP_Pos) /*!< 0x80000000 */ @@ -2508,34 +2444,34 @@ typedef struct /****************** Bits definition for FLASH_WRP1AR register ***************/ #define FLASH_WRP1AR_WRP1A_STRT_Pos (0U) -#define FLASH_WRP1AR_WRP1A_STRT_Msk (0x1FUL << FLASH_WRP1AR_WRP1A_STRT_Pos) /*!< 0x0000001F */ +#define FLASH_WRP1AR_WRP1A_STRT_Msk (0xFUL << FLASH_WRP1AR_WRP1A_STRT_Pos) /*!< 0x0000000F */ #define FLASH_WRP1AR_WRP1A_STRT FLASH_WRP1AR_WRP1A_STRT_Msk #define FLASH_WRP1AR_WRP1A_END_Pos (16U) -#define FLASH_WRP1AR_WRP1A_END_Msk (0x1FUL << FLASH_WRP1AR_WRP1A_END_Pos) /*!< 0x001F0000 */ +#define FLASH_WRP1AR_WRP1A_END_Msk (0xFUL << FLASH_WRP1AR_WRP1A_END_Pos) /*!< 0x000F0000 */ #define FLASH_WRP1AR_WRP1A_END FLASH_WRP1AR_WRP1A_END_Msk /****************** Bits definition for FLASH_WRP1BR register ***************/ #define FLASH_WRP1BR_WRP1B_STRT_Pos (0U) -#define FLASH_WRP1BR_WRP1B_STRT_Msk (0x1FUL << FLASH_WRP1BR_WRP1B_STRT_Pos) /*!< 0x0000001F */ +#define FLASH_WRP1BR_WRP1B_STRT_Msk (0xFUL << FLASH_WRP1BR_WRP1B_STRT_Pos) /*!< 0x0000000F */ #define FLASH_WRP1BR_WRP1B_STRT FLASH_WRP1BR_WRP1B_STRT_Msk #define FLASH_WRP1BR_WRP1B_END_Pos (16U) -#define FLASH_WRP1BR_WRP1B_END_Msk (0x1FUL << FLASH_WRP1BR_WRP1B_END_Pos) /*!< 0x001F0000 */ +#define FLASH_WRP1BR_WRP1B_END_Msk (0xFUL << FLASH_WRP1BR_WRP1B_END_Pos) /*!< 0x000F0000 */ #define FLASH_WRP1BR_WRP1B_END FLASH_WRP1BR_WRP1B_END_Msk /****************** Bits definition for FLASH_PCROP1BSR register ************/ #define FLASH_PCROP1BSR_PCROP1B_STRT_Pos (0U) -#define FLASH_PCROP1BSR_PCROP1B_STRT_Msk (0x7FUL << FLASH_PCROP1BSR_PCROP1B_STRT_Pos) /*!< 0x0000007F */ +#define FLASH_PCROP1BSR_PCROP1B_STRT_Msk (0x3FUL << FLASH_PCROP1BSR_PCROP1B_STRT_Pos) /*!< 0x0000003F */ #define FLASH_PCROP1BSR_PCROP1B_STRT FLASH_PCROP1BSR_PCROP1B_STRT_Msk /****************** Bits definition for FLASH_PCROP1BER register ************/ #define FLASH_PCROP1BER_PCROP1B_END_Pos (0U) -#define FLASH_PCROP1BER_PCROP1B_END_Msk (0x7FUL << FLASH_PCROP1BER_PCROP1B_END_Pos) /*!< 0x0000007F */ +#define FLASH_PCROP1BER_PCROP1B_END_Msk (0x3FUL << FLASH_PCROP1BER_PCROP1B_END_Pos) /*!< 0x0000003F */ #define FLASH_PCROP1BER_PCROP1B_END FLASH_PCROP1BER_PCROP1B_END_Msk /****************** Bits definition for FLASH_SECR register *****************/ #define FLASH_SECR_SEC_SIZE_Pos (0U) -#define FLASH_SECR_SEC_SIZE_Msk (0x3FUL << FLASH_SECR_SEC_SIZE_Pos) /*!< 0x0000003F */ +#define FLASH_SECR_SEC_SIZE_Msk (0x1FUL << FLASH_SECR_SEC_SIZE_Pos) /*!< 0x0000001F */ #define FLASH_SECR_SEC_SIZE FLASH_SECR_SEC_SIZE_Msk #define FLASH_SECR_BOOT_LOCK_Pos (16U) #define FLASH_SECR_BOOT_LOCK_Msk (0x1UL << FLASH_SECR_BOOT_LOCK_Pos) /*!< 0x00010000 */ @@ -3617,7 +3553,7 @@ typedef struct #define PWR_CR3_EWUP3_Msk (0x1UL << PWR_CR3_EWUP3_Pos) /*!< 0x00000004 */ #define PWR_CR3_EWUP3 PWR_CR3_EWUP3_Msk /*!< Enable external WKUP pin 3 */ #define PWR_CR3_EWUP4_Pos (3U) -#define PWR_CR3_EWUP4_Msk (0x1UL << PWR_CR3_EWUP4_Pos) /*!< 0x00000004 */ +#define PWR_CR3_EWUP4_Msk (0x1UL << PWR_CR3_EWUP4_Pos) /*!< 0x00000008 */ #define PWR_CR3_EWUP4 PWR_CR3_EWUP4_Msk /*!< Enable external WKUP pin 4 */ #define PWR_CR3_EWUP6_Pos (5U) #define PWR_CR3_EWUP6_Msk (0x1UL << PWR_CR3_EWUP6_Pos) /*!< 0x00000020 */ @@ -3679,9 +3615,6 @@ typedef struct #define PWR_SR2_FLASH_RDY_Pos (7U) #define PWR_SR2_FLASH_RDY_Msk (0x1UL << PWR_SR2_FLASH_RDY_Pos) /*!< 0x00000080 */ #define PWR_SR2_FLASH_RDY PWR_SR2_FLASH_RDY_Msk /*!< Flash Ready */ -#define PWR_SR2_REGLPF_Pos (9U) -#define PWR_SR2_REGLPF_Msk (0x1UL << PWR_SR2_REGLPF_Pos) /*!< 0x00000200 */ -#define PWR_SR2_REGLPF PWR_SR2_REGLPF_Msk /*!< Regulator Low Power flag */ /******************** Bit definition for PWR_SCR register ********************/ #define PWR_SCR_CWUF_Pos (0U) @@ -3970,40 +3903,36 @@ typedef struct #define RCC_CFGR_PPRE_2 (0x4UL << RCC_CFGR_PPRE_Pos) /*!< 0x00004000 */ /*!< MCO2SEL configuration */ -#define RCC_CFGR_MCO2SEL_Pos (16U) -#define RCC_CFGR_MCO2SEL_Msk (0xFUL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x000F0000 */ -#define RCC_CFGR_MCO2SEL RCC_CFGR_MCO2SEL_Msk /*!< MCO2SEL [3:0] bits (Clock output selection) */ -#define RCC_CFGR_MCO2SEL_0 (0x1UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00010000 */ -#define RCC_CFGR_MCO2SEL_1 (0x2UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00020000 */ -#define RCC_CFGR_MCO2SEL_2 (0x4UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00040000 */ -#define RCC_CFGR_MCO2SEL_3 (0x8UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00080000 */ +#define RCC_CFGR_MCO2SEL_Pos (16U) +#define RCC_CFGR_MCO2SEL_Msk (0x7UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00070000 */ +#define RCC_CFGR_MCO2SEL RCC_CFGR_MCO2SEL_Msk /*!< MCO2SEL [2:0] bits (Clock output selection) */ +#define RCC_CFGR_MCO2SEL_0 (0x1UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00010000 */ +#define RCC_CFGR_MCO2SEL_1 (0x2UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00020000 */ +#define RCC_CFGR_MCO2SEL_2 (0x4UL << RCC_CFGR_MCO2SEL_Pos) /*!< 0x00040000 */ /*!< MCO2 Prescaler configuration */ -#define RCC_CFGR_MCO2PRE_Pos (20U) -#define RCC_CFGR_MCO2PRE_Msk (0xFUL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00F00000 */ -#define RCC_CFGR_MCO2PRE RCC_CFGR_MCO2PRE_Msk /*!< MCO prescaler [3:0] */ -#define RCC_CFGR_MCO2PRE_0 (0x1UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00100000 */ -#define RCC_CFGR_MCO2PRE_1 (0x2UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00200000 */ -#define RCC_CFGR_MCO2PRE_2 (0x4UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00400000 */ -#define RCC_CFGR_MCO2PRE_3 (0x8UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00800000 */ +#define RCC_CFGR_MCO2PRE_Pos (20U) +#define RCC_CFGR_MCO2PRE_Msk (0x7UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00700000 */ +#define RCC_CFGR_MCO2PRE RCC_CFGR_MCO2PRE_Msk /*!< MCO prescaler [2:0] */ +#define RCC_CFGR_MCO2PRE_0 (0x1UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00100000 */ +#define RCC_CFGR_MCO2PRE_1 (0x2UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00200000 */ +#define RCC_CFGR_MCO2PRE_2 (0x4UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x00400000 */ /*!< MCOSEL configuration */ #define RCC_CFGR_MCOSEL_Pos (24U) -#define RCC_CFGR_MCOSEL_Msk (0xFUL << RCC_CFGR_MCOSEL_Pos) /*!< 0x0F000000 */ -#define RCC_CFGR_MCOSEL RCC_CFGR_MCOSEL_Msk /*!< MCOSEL [3:0] bits (Clock output selection) */ +#define RCC_CFGR_MCOSEL_Msk (0x7UL << RCC_CFGR_MCOSEL_Pos) /*!< 0x07000000 */ +#define RCC_CFGR_MCOSEL RCC_CFGR_MCOSEL_Msk /*!< MCOSEL [2:0] bits (Clock output selection) */ #define RCC_CFGR_MCOSEL_0 (0x1UL << RCC_CFGR_MCOSEL_Pos) /*!< 0x01000000 */ #define RCC_CFGR_MCOSEL_1 (0x2UL << RCC_CFGR_MCOSEL_Pos) /*!< 0x02000000 */ #define RCC_CFGR_MCOSEL_2 (0x4UL << RCC_CFGR_MCOSEL_Pos) /*!< 0x04000000 */ -#define RCC_CFGR_MCOSEL_3 (0x8UL << RCC_CFGR_MCOSEL_Pos) /*!< 0x08000000 */ /*!< MCO Prescaler configuration */ #define RCC_CFGR_MCOPRE_Pos (28U) -#define RCC_CFGR_MCOPRE_Msk (0xFUL << RCC_CFGR_MCOPRE_Pos) /*!< 0xF0000000 */ -#define RCC_CFGR_MCOPRE RCC_CFGR_MCOPRE_Msk /*!< MCO prescaler [3:0] */ +#define RCC_CFGR_MCOPRE_Msk (0x7UL << RCC_CFGR_MCOPRE_Pos) /*!< 0x70000000 */ +#define RCC_CFGR_MCOPRE RCC_CFGR_MCOPRE_Msk /*!< MCO prescaler [2:0] */ #define RCC_CFGR_MCOPRE_0 (0x1UL << RCC_CFGR_MCOPRE_Pos) /*!< 0x10000000 */ #define RCC_CFGR_MCOPRE_1 (0x2UL << RCC_CFGR_MCOPRE_Pos) /*!< 0x20000000 */ #define RCC_CFGR_MCOPRE_2 (0x4UL << RCC_CFGR_MCOPRE_Pos) /*!< 0x40000000 */ -#define RCC_CFGR_MCOPRE_3 (0x8UL << RCC_CFGR_MCOPRE_Pos) /*!< 0x80000000 */ /******************** Bit definition for RCC_CIER register ******************/ #define RCC_CIER_LSIRDYIE_Pos (0U) @@ -4089,7 +4018,7 @@ typedef struct #define RCC_APBRSTR1_TIM3RST_Msk (0x1UL << RCC_APBRSTR1_TIM3RST_Pos) /*!< 0x00000002 */ #define RCC_APBRSTR1_TIM3RST RCC_APBRSTR1_TIM3RST_Msk #define RCC_APBRSTR1_USART2RST_Pos (17U) -#define RCC_APBRSTR1_USART2RST_Msk (0x1UL << RCC_APBRSTR1_USART2RST_Pos) /*!< 0x00020000 */ +#define RCC_APBRSTR1_USART2RST_Msk (0x1UL << RCC_APBRSTR1_USART2RST_Pos) /*!< 0x00010000 */ #define RCC_APBRSTR1_USART2RST RCC_APBRSTR1_USART2RST_Msk #define RCC_APBRSTR1_I2C1RST_Pos (21U) #define RCC_APBRSTR1_I2C1RST_Msk (0x1UL << RCC_APBRSTR1_I2C1RST_Pos) /*!< 0x00200000 */ @@ -4163,7 +4092,7 @@ typedef struct #define RCC_APBENR1_WWDGEN_Msk (0x1UL << RCC_APBENR1_WWDGEN_Pos) /*!< 0x00000800 */ #define RCC_APBENR1_WWDGEN RCC_APBENR1_WWDGEN_Msk #define RCC_APBENR1_USART2EN_Pos (17U) -#define RCC_APBENR1_USART2EN_Msk (0x1UL << RCC_APBENR1_USART2EN_Pos) /*!< 0x00020000 */ +#define RCC_APBENR1_USART2EN_Msk (0x1UL << RCC_APBENR1_USART2EN_Pos) /*!< 0x00010000 */ #define RCC_APBENR1_USART2EN RCC_APBENR1_USART2EN_Msk #define RCC_APBENR1_I2C1EN_Pos (21U) #define RCC_APBENR1_I2C1EN_Msk (0x1UL << RCC_APBENR1_I2C1EN_Pos) /*!< 0x00200000 */ @@ -4240,7 +4169,7 @@ typedef struct #define RCC_APBSMENR1_WWDGSMEN_Msk (0x1UL << RCC_APBSMENR1_WWDGSMEN_Pos) /*!< 0x00000800 */ #define RCC_APBSMENR1_WWDGSMEN RCC_APBSMENR1_WWDGSMEN_Msk #define RCC_APBSMENR1_USART2SMEN_Pos (17U) -#define RCC_APBSMENR1_USART2SMEN_Msk (0x1UL << RCC_APBSMENR1_USART2SMEN_Pos) /*!< 0x00020000 */ +#define RCC_APBSMENR1_USART2SMEN_Msk (0x1UL << RCC_APBSMENR1_USART2SMEN_Pos) /*!< 0x00010000 */ #define RCC_APBSMENR1_USART2SMEN RCC_APBSMENR1_USART2SMEN_Msk #define RCC_APBSMENR1_I2C1SMEN_Pos (21U) #define RCC_APBSMENR1_I2C1SMEN_Msk (0x1UL << RCC_APBSMENR1_I2C1SMEN_Pos) /*!< 0x00200000 */ @@ -5013,9 +4942,6 @@ typedef struct #define SYSCFG_CFGR1_IR_MOD SYSCFG_CFGR1_IR_MOD_Msk /*!< IRDA Modulation Envelope signal source selection */ #define SYSCFG_CFGR1_IR_MOD_0 (0x1UL << SYSCFG_CFGR1_IR_MOD_Pos) /*!< 0x00000040 */ #define SYSCFG_CFGR1_IR_MOD_1 (0x2UL << SYSCFG_CFGR1_IR_MOD_Pos) /*!< 0x00000080 */ -#define SYSCFG_CFGR1_BOOSTEN_Pos (8U) -#define SYSCFG_CFGR1_BOOSTEN_Msk (0x1UL << SYSCFG_CFGR1_BOOSTEN_Pos) /*!< 0x00000100 */ -#define SYSCFG_CFGR1_BOOSTEN SYSCFG_CFGR1_BOOSTEN_Msk /*!< I/O analog switch voltage booster enable */ #define SYSCFG_CFGR1_I2C_PB6_FMP_Pos (16U) #define SYSCFG_CFGR1_I2C_PB6_FMP_Msk (0x1UL << SYSCFG_CFGR1_I2C_PB6_FMP_Pos) /*!< 0x00010000 */ #define SYSCFG_CFGR1_I2C_PB6_FMP SYSCFG_CFGR1_I2C_PB6_FMP_Msk /*!< I2C PB6 Fast mode plus */ @@ -5048,49 +4974,49 @@ typedef struct /****************** Bit definition for SYSCFG_CFGR3 register ****************/ #define SYSCFG_CFGR3_PINMUX0_Pos (0U) -#define SYSCFG_CFGR3_PINMUX0_Msk (0x2UL << SYSCFG_CFGR3_PINMUX0_Pos) /*!< 0x00000003 */ +#define SYSCFG_CFGR3_PINMUX0_Msk (0x3UL << SYSCFG_CFGR3_PINMUX0_Pos) /*!< 0x00000003 */ #define SYSCFG_CFGR3_PINMUX0 SYSCFG_CFGR3_PINMUX0_Msk /*!< Pin GPIO multiplexer 0 */ #define SYSCFG_CFGR3_PINMUX0_0 (0x1UL << SYSCFG_CFGR3_PINMUX0_Pos) /*!< 0x00000001 */ #define SYSCFG_CFGR3_PINMUX0_1 (0x2UL << SYSCFG_CFGR3_PINMUX0_Pos) /*!< 0x00000002 */ #define SYSCFG_CFGR3_PINMUX1_Pos (2U) -#define SYSCFG_CFGR3_PINMUX1_Msk (0x2UL << SYSCFG_CFGR3_PINMUX1_Pos) /*!< 0x0000000C */ +#define SYSCFG_CFGR3_PINMUX1_Msk (0x3UL << SYSCFG_CFGR3_PINMUX1_Pos) /*!< 0x0000000C */ #define SYSCFG_CFGR3_PINMUX1 SYSCFG_CFGR3_PINMUX1_Msk /*!< Pin GPIO multiplexer 1 */ #define SYSCFG_CFGR3_PINMUX1_0 (0x1UL << SYSCFG_CFGR3_PINMUX1_Pos) /*!< 0x00000004 */ #define SYSCFG_CFGR3_PINMUX1_1 (0x2UL << SYSCFG_CFGR3_PINMUX1_Pos) /*!< 0x00000008 */ #define SYSCFG_CFGR3_PINMUX2_Pos (4U) -#define SYSCFG_CFGR3_PINMUX2_Msk (0x2UL << SYSCFG_CFGR3_PINMUX2_Pos) /*!< 0x00000030 */ +#define SYSCFG_CFGR3_PINMUX2_Msk (0x3UL << SYSCFG_CFGR3_PINMUX2_Pos) /*!< 0x00000030 */ #define SYSCFG_CFGR3_PINMUX2 SYSCFG_CFGR3_PINMUX2_Msk /*!< Pin GPIO multiplexer 2 */ #define SYSCFG_CFGR3_PINMUX2_0 (0x1UL << SYSCFG_CFGR3_PINMUX2_Pos) /*!< 0x00000010 */ #define SYSCFG_CFGR3_PINMUX2_1 (0x2UL << SYSCFG_CFGR3_PINMUX2_Pos) /*!< 0x00000020 */ #define SYSCFG_CFGR3_PINMUX3_Pos (6U) -#define SYSCFG_CFGR3_PINMUX3_Msk (0x2UL << SYSCFG_CFGR3_PINMUX3_Pos) /*!< 0x000000C0 */ +#define SYSCFG_CFGR3_PINMUX3_Msk (0x3UL << SYSCFG_CFGR3_PINMUX3_Pos) /*!< 0x000000C0 */ #define SYSCFG_CFGR3_PINMUX3 SYSCFG_CFGR3_PINMUX3_Msk /*!< Pin GPIO multiplexer 3 */ #define SYSCFG_CFGR3_PINMUX3_0 (0x1UL << SYSCFG_CFGR3_PINMUX3_Pos) /*!< 0x00000040 */ #define SYSCFG_CFGR3_PINMUX3_1 (0x2UL << SYSCFG_CFGR3_PINMUX3_Pos) /*!< 0x00000080 */ #define SYSCFG_CFGR3_PINMUX4_Pos (8U) -#define SYSCFG_CFGR3_PINMUX4_Msk (0x2UL << SYSCFG_CFGR3_PINMUX4_Pos) /*!< 0x00000300 */ +#define SYSCFG_CFGR3_PINMUX4_Msk (0x3UL << SYSCFG_CFGR3_PINMUX4_Pos) /*!< 0x00000300 */ #define SYSCFG_CFGR3_PINMUX4 SYSCFG_CFGR3_PINMUX4_Msk /*!< Pin GPIO multiplexer 4 */ #define SYSCFG_CFGR3_PINMUX4_0 (0x1UL << SYSCFG_CFGR3_PINMUX4_Pos) /*!< 0x00000100 */ #define SYSCFG_CFGR3_PINMUX4_1 (0x2UL << SYSCFG_CFGR3_PINMUX4_Pos) /*!< 0x00000200 */ #define SYSCFG_CFGR3_PINMUX5_Pos (10U) -#define SYSCFG_CFGR3_PINMUX5_Msk (0x2UL << SYSCFG_CFGR3_PINMUX5_Pos) /*!< 0x00000C00 */ +#define SYSCFG_CFGR3_PINMUX5_Msk (0x3UL << SYSCFG_CFGR3_PINMUX5_Pos) /*!< 0x00000C00 */ #define SYSCFG_CFGR3_PINMUX5 SYSCFG_CFGR3_PINMUX5_Msk /*!< Pin GPIO multiplexer 5 */ #define SYSCFG_CFGR3_PINMUX5_0 (0x1UL << SYSCFG_CFGR3_PINMUX5_Pos) /*!< 0x00000400 */ #define SYSCFG_CFGR3_PINMUX5_1 (0x2UL << SYSCFG_CFGR3_PINMUX5_Pos) /*!< 0x00000800 */ /***************** Bit definition for SYSCFG_ITLINEx ISR Wrapper register ****************/ -#define SYSCFG_ITLINE0_SR_EWDG_Pos (0U) -#define SYSCFG_ITLINE0_SR_EWDG_Msk (0x1UL << SYSCFG_ITLINE0_SR_EWDG_Pos) /*!< 0x00000001 */ -#define SYSCFG_ITLINE0_SR_EWDG SYSCFG_ITLINE0_SR_EWDG_Msk /*!< EWDG interrupt */ +#define SYSCFG_ITLINE0_SR_WWDG_Pos (0U) +#define SYSCFG_ITLINE0_SR_WWDG_Msk (0x1UL << SYSCFG_ITLINE0_SR_WWDG_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE0_SR_WWDG SYSCFG_ITLINE0_SR_WWDG_Msk /*!< EWDG interrupt */ #define SYSCFG_ITLINE2_SR_RTC_Pos (1U) #define SYSCFG_ITLINE2_SR_RTC_Msk (0x1UL << SYSCFG_ITLINE2_SR_RTC_Pos) /*!< 0x00000002 */ #define SYSCFG_ITLINE2_SR_RTC SYSCFG_ITLINE2_SR_RTC_Msk /*!< RTC interrupt */ #define SYSCFG_ITLINE3_SR_FLASH_ITF_Pos (1U) #define SYSCFG_ITLINE3_SR_FLASH_ITF_Msk (0x1UL << SYSCFG_ITLINE3_SR_FLASH_ITF_Pos) /*!< 0x00000002 */ #define SYSCFG_ITLINE3_SR_FLASH_ITF SYSCFG_ITLINE3_SR_FLASH_ITF_Msk /*!< FLASH ITF interrupt */ -#define SYSCFG_ITLINE4_SR_CLK_CTRL_Pos (0U) -#define SYSCFG_ITLINE4_SR_CLK_CTRL_Msk (0x1UL << SYSCFG_ITLINE4_SR_CLK_CTRL_Pos) /*!< 0x00000001 */ -#define SYSCFG_ITLINE4_SR_CLK_CTRL SYSCFG_ITLINE4_SR_CLK_CTRL_Msk /*!< RCC interrupt */ +#define SYSCFG_ITLINE4_SR_RCC_Pos (0U) +#define SYSCFG_ITLINE4_SR_RCC_Msk (0x1UL << SYSCFG_ITLINE4_SR_RCC_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE4_SR_RCC SYSCFG_ITLINE4_SR_RCC_Msk /*!< RCC interrupt */ #define SYSCFG_ITLINE5_SR_EXTI0_Pos (0U) #define SYSCFG_ITLINE5_SR_EXTI0_Msk (0x1UL << SYSCFG_ITLINE5_SR_EXTI0_Pos) /*!< 0x00000001 */ #define SYSCFG_ITLINE5_SR_EXTI0 SYSCFG_ITLINE5_SR_EXTI0_Msk /*!< External Interrupt 0 */ @@ -5148,9 +5074,9 @@ typedef struct #define SYSCFG_ITLINE10_SR_DMA1_CH3_Pos (1U) #define SYSCFG_ITLINE10_SR_DMA1_CH3_Msk (0x1UL << SYSCFG_ITLINE10_SR_DMA1_CH3_Pos) /*!< 0x00000002 */ #define SYSCFG_ITLINE10_SR_DMA1_CH3 SYSCFG_ITLINE10_SR_DMA1_CH3_Msk /*!< DMA1 Channel 3 Interrupt */ -#define SYSCFG_ITLINE11_SR_DMAMUX1_Pos (0U) -#define SYSCFG_ITLINE11_SR_DMAMUX1_Msk (0x1UL << SYSCFG_ITLINE11_SR_DMAMUX1_Pos) /*!< 0x00000001 */ -#define SYSCFG_ITLINE11_SR_DMAMUX1 SYSCFG_ITLINE11_SR_DMAMUX1_Msk /*!< DMAMUX Interrupt */ +#define SYSCFG_ITLINE11_SR_DMAMUX1_Pos (0U) +#define SYSCFG_ITLINE11_SR_DMAMUX1_Msk (0x1UL << SYSCFG_ITLINE11_SR_DMAMUX1_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE11_SR_DMAMUX1 SYSCFG_ITLINE11_SR_DMAMUX1_Msk /*!< DMAMUX Interrupt */ #define SYSCFG_ITLINE12_SR_ADC_Pos (0U) #define SYSCFG_ITLINE12_SR_ADC_Msk (0x1UL << SYSCFG_ITLINE12_SR_ADC_Pos) /*!< 0x00000001 */ #define SYSCFG_ITLINE12_SR_ADC SYSCFG_ITLINE12_SR_ADC_Msk /*!< ADC Interrupt */ @@ -5751,27 +5677,27 @@ typedef struct /******************* Bit definition for TIM_CCR1 register *******************/ #define TIM_CCR1_CCR1_Pos (0U) -#define TIM_CCR1_CCR1_Msk (0xFFFFUL << TIM_CCR1_CCR1_Pos) /*!< 0x0000FFFF */ +#define TIM_CCR1_CCR1_Msk (0xFFFFFFFFUL << TIM_CCR1_CCR1_Pos) /*!< 0xFFFFFFFF */ #define TIM_CCR1_CCR1 TIM_CCR1_CCR1_Msk /*! + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ +typedef struct +{ + __IO uint32_t ISR; /*!< ADC interrupt and status register, Address offset: 0x00 */ + __IO uint32_t IER; /*!< ADC interrupt enable register, Address offset: 0x04 */ + __IO uint32_t CR; /*!< ADC control register, Address offset: 0x08 */ + __IO uint32_t CFGR1; /*!< ADC configuration register 1, Address offset: 0x0C */ + __IO uint32_t CFGR2; /*!< ADC configuration register 2, Address offset: 0x10 */ + __IO uint32_t SMPR; /*!< ADC sampling time register, Address offset: 0x14 */ + uint32_t RESERVED1; /*!< Reserved, 0x18 */ + uint32_t RESERVED2; /*!< Reserved, 0x1C */ + __IO uint32_t AWD1TR; /*!< ADC analog watchdog 1 threshold register, Address offset: 0x20 */ + __IO uint32_t AWD2TR; /*!< ADC analog watchdog 2 threshold register, Address offset: 0x24 */ + __IO uint32_t CHSELR; /*!< ADC group regular sequencer register, Address offset: 0x28 */ + __IO uint32_t AWD3TR; /*!< ADC analog watchdog 3 threshold register, Address offset: 0x2C */ + uint32_t RESERVED3[4]; /*!< Reserved, 0x30 - 0x3C */ + __IO uint32_t DR; /*!< ADC group regular data register, Address offset: 0x40 */ + uint32_t RESERVED4[23];/*!< Reserved, 0x44 - 0x9C */ + __IO uint32_t AWD2CR; /*!< ADC analog watchdog 2 configuration register, Address offset: 0xA0 */ + __IO uint32_t AWD3CR; /*!< ADC analog watchdog 3 configuration register, Address offset: 0xA4 */ + uint32_t RESERVED5[3]; /*!< Reserved, 0xA8 - 0xB0 */ + __IO uint32_t CALFACT; /*!< ADC Calibration factor register, Address offset: 0xB4 */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CCR; /*!< ADC common configuration register, Address offset: ADC1 base address + 0x308 */ +} ADC_Common_TypeDef; + +/* Legacy registers naming */ +#define TR1 AWD1TR +#define TR2 AWD2TR +#define TR3 AWD3TR + +/** + * @brief CRC calculation unit + */ +typedef struct +{ + __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint32_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ + __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ + uint32_t RESERVED1; /*!< Reserved, 0x0C */ + __IO uint32_t INIT; /*!< Initial CRC value register, Address offset: 0x10 */ + __IO uint32_t POL; /*!< CRC polynomial register, Address offset: 0x14 */ +} CRC_TypeDef; + +/** + * @brief Clock Recovery System + */ +typedef struct +{ + __IO uint32_t CR; /*!< CRS control register, Address offset: 0x00 */ + __IO uint32_t CFGR; /*!< CRS configuration register, Address offset: 0x04 */ + __IO uint32_t ISR; /*!< CRS interrupt and status register, Address offset: 0x08 */ + __IO uint32_t ICR; /*!< CRS interrupt flag clear register, Address offset: 0x0C */ +} CRS_TypeDef; + +/** + * @brief Debug MCU + */ +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CR; /*!< Debug configuration register, Address offset: 0x04 */ + __IO uint32_t APBFZ1; /*!< Debug APB freeze register 1, Address offset: 0x08 */ + __IO uint32_t APBFZ2; /*!< Debug APB freeze register 2, Address offset: 0x0C */ +} DBG_TypeDef; + +/** + * @brief DMA Controller + */ +typedef struct +{ + __IO uint32_t CCR; /*!< DMA channel x configuration register */ + __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ + __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ + __IO uint32_t CMAR; /*!< DMA channel x memory address register */ +} DMA_Channel_TypeDef; + +typedef struct +{ + __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ + __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ +} DMA_TypeDef; + +/** + * @brief DMA Multiplexer + */ +typedef struct +{ + __IO uint32_t CCR; /*!< DMA Multiplexer Channel x Control Register Address offset: 0x0004 * (channel x) */ +}DMAMUX_Channel_TypeDef; + +typedef struct +{ + __IO uint32_t CSR; /*!< DMA Channel Status Register Address offset: 0x0080 */ + __IO uint32_t CFR; /*!< DMA Channel Clear Flag Register Address offset: 0x0084 */ +}DMAMUX_ChannelStatus_TypeDef; + +typedef struct +{ + __IO uint32_t RGCR; /*!< DMA Request Generator x Control Register Address offset: 0x0100 + 0x0004 * (Req Gen x) */ +}DMAMUX_RequestGen_TypeDef; + +typedef struct +{ + __IO uint32_t RGSR; /*!< DMA Request Generator Status Register Address offset: 0x0140 */ + __IO uint32_t RGCFR; /*!< DMA Request Generator Clear Flag Register Address offset: 0x0144 */ +}DMAMUX_RequestGenStatus_TypeDef; + +/** + * @brief Asynch Interrupt/Event Controller (EXTI) + */ +typedef struct +{ + __IO uint32_t RTSR1; /*!< EXTI Rising Trigger Selection Register 1, Address offset: 0x00 */ + __IO uint32_t FTSR1; /*!< EXTI Falling Trigger Selection Register 1, Address offset: 0x04 */ + __IO uint32_t SWIER1; /*!< EXTI Software Interrupt event Register 1, Address offset: 0x08 */ + __IO uint32_t RPR1; /*!< EXTI Rising Pending Register 1, Address offset: 0x0C */ + __IO uint32_t FPR1; /*!< EXTI Falling Pending Register 1, Address offset: 0x10 */ + uint32_t RESERVED1[3]; /*!< Reserved 1, 0x14 -- 0x1C */ + __IO uint32_t RTSR2; /*!< EXTI Rising Trigger Selection Register 2, Address offset: 0x28 */ + __IO uint32_t FTSR2; /*!< EXTI Falling Trigger Selection Register 2, Address offset: 0x2C */ + __IO uint32_t SWIER2; /*!< EXTI Software Interrupt event Register 2, Address offset: 0x30 */ + __IO uint32_t RPR2; /*!< EXTI Rising Pending Register 2, Address offset: 0x34 */ + __IO uint32_t FPR2; /*!< EXTI Falling Pending Register 2, Address offset: 0x38 */ + uint32_t RESERVED3[11]; /*!< Reserved 3, 0x3C -- 0x5F */ + __IO uint32_t EXTICR[4]; /*!< EXTI External Interrupt Configuration Register, 0x60 -- 0x6C */ + uint32_t RESERVED4[4]; /*!< Reserved 4, 0x70 -- 0x7C */ + __IO uint32_t IMR1; /*!< EXTI Interrupt Mask Register 1, Address offset: 0x80 */ + __IO uint32_t EMR1; /*!< EXTI Event Mask Register 1, Address offset: 0x84 */ + uint32_t RESERVED5[2]; /*!< Reserved 5, 0x88 -- 0x8C */ + __IO uint32_t IMR2; /*!< EXTI Interrupt Mask Register 2, Address offset: 0x90 */ + __IO uint32_t EMR2; /*!< EXTI Event Mask Register 2, Address offset: 0x94 */ +} EXTI_TypeDef; + +/** + * @brief FLASH Registers + */ +typedef struct +{ + __IO uint32_t ACR; /*!< FLASH Access Control register, Address offset: 0x00 */ + uint32_t RESERVED1; /*!< Reserved1, Address offset: 0x04 */ + __IO uint32_t KEYR; /*!< FLASH Key register, Address offset: 0x08 */ + __IO uint32_t OPTKEYR; /*!< FLASH Option Key register, Address offset: 0x0C */ + __IO uint32_t SR; /*!< FLASH Status register, Address offset: 0x10 */ + __IO uint32_t CR; /*!< FLASH Control register, Address offset: 0x14 */ + uint32_t RESERVED2[2]; /*!< Reserved2, Address offset: 0x18 */ + __IO uint32_t OPTR; /*!< FLASH Option register, Address offset: 0x20 */ + __IO uint32_t PCROP1ASR; /*!< FLASH Bank PCROP area A Start address register, Address offset: 0x24 */ + __IO uint32_t PCROP1AER; /*!< FLASH Bank PCROP area A End address register, Address offset: 0x28 */ + __IO uint32_t WRP1AR; /*!< FLASH Bank WRP area A address register, Address offset: 0x2C */ + __IO uint32_t WRP1BR; /*!< FLASH Bank WRP area B address register, Address offset: 0x30 */ + __IO uint32_t PCROP1BSR; /*!< FLASH Bank PCROP area B Start address register, Address offset: 0x34 */ + __IO uint32_t PCROP1BER; /*!< FLASH Bank PCROP area B End address register, Address offset: 0x38 */ + uint32_t RESERVED3[17];/*!< Reserved3, Address offset: 0x3C */ + __IO uint32_t SECR; /*!< FLASH security register , Address offset: 0x80 */ +} FLASH_TypeDef; + +/** + * @brief General Purpose I/O + */ +typedef struct +{ + __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ + __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ + __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ + __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ + __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ + __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ + __IO uint32_t BSRR; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ + __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ + __IO uint32_t AFR[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ + __IO uint32_t BRR; /*!< GPIO Bit Reset register, Address offset: 0x28 */ +} GPIO_TypeDef; + + +/** + * @brief Inter-integrated Circuit Interface + */ +typedef struct +{ + __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ + __IO uint32_t OAR1; /*!< I2C Own address 1 register, Address offset: 0x08 */ + __IO uint32_t OAR2; /*!< I2C Own address 2 register, Address offset: 0x0C */ + __IO uint32_t TIMINGR; /*!< I2C Timing register, Address offset: 0x10 */ + __IO uint32_t TIMEOUTR; /*!< I2C Timeout register, Address offset: 0x14 */ + __IO uint32_t ISR; /*!< I2C Interrupt and status register, Address offset: 0x18 */ + __IO uint32_t ICR; /*!< I2C Interrupt clear register, Address offset: 0x1C */ + __IO uint32_t PECR; /*!< I2C PEC register, Address offset: 0x20 */ + __IO uint32_t RXDR; /*!< I2C Receive data register, Address offset: 0x24 */ + __IO uint32_t TXDR; /*!< I2C Transmit data register, Address offset: 0x28 */ +} I2C_TypeDef; + +/** + * @brief Independent WATCHDOG + */ +typedef struct +{ + __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ + __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ + __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ + __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ + __IO uint32_t WINR; /*!< IWDG Window register, Address offset: 0x10 */ +} IWDG_TypeDef; + + +/** + * @brief Power Control + */ +typedef struct +{ + __IO uint32_t CR1; /*!< PWR Power Control Register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< PWR Power Control Register 2, Address offset: 0x04 */ + __IO uint32_t CR3; /*!< PWR Power Control Register 3, Address offset: 0x08 */ + __IO uint32_t CR4; /*!< PWR Power Control Register 4, Address offset: 0x0C */ + __IO uint32_t SR1; /*!< PWR Power Status Register 1, Address offset: 0x10 */ + __IO uint32_t SR2; /*!< PWR Power Status Register 2, Address offset: 0x14 */ + __IO uint32_t SCR; /*!< PWR Power Status Clear Register, Address offset: 0x18 */ + uint32_t RESERVED2; /*!< Reserved, Address offset: 0x1C */ + __IO uint32_t PUCRA; /*!< PWR Pull-Up Control Register of port A, Address offset: 0x20 */ + __IO uint32_t PDCRA; /*!< PWR Pull-Down Control Register of port A, Address offset: 0x24 */ + __IO uint32_t PUCRB; /*!< PWR Pull-Up Control Register of port B, Address offset: 0x28 */ + __IO uint32_t PDCRB; /*!< PWR Pull-Down Control Register of port B, Address offset: 0x2C */ + __IO uint32_t PUCRC; /*!< PWR Pull-Up Control Register of port C, Address offset: 0x30 */ + __IO uint32_t PDCRC; /*!< PWR Pull-Down Control Register of port C, Address offset: 0x34 */ + __IO uint32_t PUCRD; /*!< PWR Pull-Up Control Register of port D, Address offset: 0x38 */ + __IO uint32_t PDCRD; /*!< PWR Pull-Down Control Register of port D, Address offset: 0x3C */ + uint32_t RESERVED5; /*!< Reserved, Address offset: 0x40 */ + uint32_t RESERVED6; /*!< Reserved, Address offset: 0x44 */ + __IO uint32_t PUCRF; /*!< PWR Pull-Up Control Register of port F, Address offset: 0x48 */ + __IO uint32_t PDCRF; /*!< PWR Pull-Down Control Register of port F, Address offset: 0x4C */ + uint32_t RESERVED7[8]; /*!< Reserved, Address offset: 0x50 */ + __IO uint32_t BKP0R; /*!< Backup register 0, Address offset: 0x70 */ + __IO uint32_t BKP1R; /*!< Backup register 1, Address offset: 0x74 */ + __IO uint32_t BKP2R; /*!< Backup register 2, Address offset: 0x78 */ + __IO uint32_t BKP3R; /*!< Backup register 3, Address offset: 0x7C */ +} PWR_TypeDef; + +/** + * @brief Reset and Clock Control + */ +typedef struct +{ + __IO uint32_t CR; /*!< RCC Clock Sources Control Register, Address offset: 0x00 */ + __IO uint32_t ICSCR; /*!< RCC Internal Clock Sources Calibration Register, Address offset: 0x04 */ + __IO uint32_t CFGR; /*!< RCC Regulated Domain Clocks Configuration Register, Address offset: 0x08 */ + uint32_t RESERVED0[2]; /*!< Reserved, Address offset: 0x0C -- 0x10 */ + __IO uint32_t CRRCR; /*!< RCC Clock Configuration Register, Address offset: 0x14 */ + __IO uint32_t CIER; /*!< RCC Clock Interrupt Enable Register, Address offset: 0x18 */ + __IO uint32_t CIFR; /*!< RCC Clock Interrupt Flag Register, Address offset: 0x1C */ + __IO uint32_t CICR; /*!< RCC Clock Interrupt Clear Register, Address offset: 0x20 */ + __IO uint32_t IOPRSTR; /*!< RCC IO port reset register, Address offset: 0x24 */ + __IO uint32_t AHBRSTR; /*!< RCC AHB peripherals reset register, Address offset: 0x28 */ + __IO uint32_t APBRSTR1; /*!< RCC APB peripherals reset register 1, Address offset: 0x2C */ + __IO uint32_t APBRSTR2; /*!< RCC APB peripherals reset register 2, Address offset: 0x30 */ + __IO uint32_t IOPENR; /*!< RCC IO port enable register, Address offset: 0x34 */ + __IO uint32_t AHBENR; /*!< RCC AHB peripherals clock enable register, Address offset: 0x38 */ + __IO uint32_t APBENR1; /*!< RCC APB peripherals clock enable register1, Address offset: 0x3C */ + __IO uint32_t APBENR2; /*!< RCC APB peripherals clock enable register2, Address offset: 0x40 */ + __IO uint32_t IOPSMENR; /*!< RCC IO port clocks enable in sleep mode register, Address offset: 0x44 */ + __IO uint32_t AHBSMENR; /*!< RCC AHB peripheral clocks enable in sleep mode register, Address offset: 0x48 */ + __IO uint32_t APBSMENR1; /*!< RCC APB peripheral clocks enable in sleep mode register1, Address offset: 0x4C */ + __IO uint32_t APBSMENR2; /*!< RCC APB peripheral clocks enable in sleep mode register2, Address offset: 0x50 */ + __IO uint32_t CCIPR; /*!< RCC Peripherals Independent Clocks Configuration Register, Address offset: 0x54 */ + __IO uint32_t CCIPR2; /*!< RCC Peripherals Independent Clocks Configuration Register2, Address offset: 0x58 */ + __IO uint32_t CSR1; /*!< RCC Control and status Register 1, Address offset: 0x5C */ + __IO uint32_t CSR2; /*!< RCC Control and status Register 2, Address offset: 0x60 */ +} RCC_TypeDef; + +/** + * @brief Real-Time Clock + */ +typedef struct +{ + __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ + __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ + __IO uint32_t SSR; /*!< RTC sub second register, Address offset: 0x08 */ + __IO uint32_t ICSR; /*!< RTC initialization control and status register, Address offset: 0x0C */ + __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ + uint32_t RESERVED0; /*!< Reserved Address offset: 0x14 */ + __IO uint32_t CR; /*!< RTC control register, Address offset: 0x18 */ + uint32_t RESERVED1; /*!< Reserved Address offset: 0x1C */ + uint32_t RESERVED2; /*!< Reserved Address offset: 0x20 */ + __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ + __IO uint32_t CALR; /*!< RTC calibration register, Address offset: 0x28 */ + __IO uint32_t SHIFTR; /*!< RTC shift control register, Address offset: 0x2C */ + __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ + __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ + __IO uint32_t TSSSR; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ + uint32_t RESERVED3; /*!< Reserved Address offset: 0x1C */ + __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x40 */ + __IO uint32_t ALRMASSR; /*!< RTC alarm A sub second register, Address offset: 0x44 */ + uint32_t RESERVED4; /*!< Reserved Address offset: 0x48 */ + uint32_t RESERVED5; /*!< Reserved Address offset: 0x4C */ + __IO uint32_t SR; /*!< RTC Status register, Address offset: 0x50 */ + __IO uint32_t MISR; /*!< RTC Masked Interrupt Status register, Address offset: 0x54 */ + uint32_t RESERVED6; /*!< Reserved Address offset: 0x58 */ + __IO uint32_t SCR; /*!< RTC Status Clear register, Address offset: 0x5C */ +} RTC_TypeDef; + + /** + * @brief Serial Peripheral Interface + */ +typedef struct +{ + __IO uint32_t CR1; /*!< SPI Control register 1 (not used in I2S mode), Address offset: 0x00 */ + __IO uint32_t CR2; /*!< SPI Control register 2, Address offset: 0x04 */ + __IO uint32_t SR; /*!< SPI Status register, Address offset: 0x08 */ + __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ + __IO uint32_t CRCPR; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ + __IO uint32_t RXCRCR; /*!< SPI Rx CRC register (not used in I2S mode), Address offset: 0x14 */ + __IO uint32_t TXCRCR; /*!< SPI Tx CRC register (not used in I2S mode), Address offset: 0x18 */ + __IO uint32_t I2SCFGR; /*!< SPI_I2S configuration register, Address offset: 0x1C */ + __IO uint32_t I2SPR; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ +} SPI_TypeDef; + +/** + * @brief System configuration controller + */ +typedef struct +{ + __IO uint32_t CFGR1; /*!< SYSCFG configuration register 1, Address offset: 0x00 */ + uint32_t RESERVED0[5]; /*!< Reserved, 0x04 --0x14 */ + __IO uint32_t CFGR2; /*!< SYSCFG configuration register 2, Address offset: 0x18 */ + uint32_t RESERVED1[8]; /*!< Reserved 0x1C --0x38 */ + __IO uint32_t CFGR3; /*!< SYSCFG configuration register 3, Address offset: 0x3C */ + uint32_t RESERVED2[16]; /*!< Reserved 0x40 --0x7C */ + __IO uint32_t IT_LINE_SR[32]; /*!< SYSCFG configuration IT_LINE register, Address offset: 0x80 */ +} SYSCFG_TypeDef; + +/** + * @brief TIM + */ +typedef struct +{ + __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ + __IO uint32_t SMCR; /*!< TIM slave mode control register, Address offset: 0x08 */ + __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ + __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ + __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ + __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ + __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ + __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ + __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ + __IO uint32_t PSC; /*!< TIM prescaler register, Address offset: 0x28 */ + __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ + __IO uint32_t RCR; /*!< TIM repetition counter register, Address offset: 0x30 */ + __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ + __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ + __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ + __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ + __IO uint32_t BDTR; /*!< TIM break and dead-time register, Address offset: 0x44 */ + __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ + __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ + __IO uint32_t RESERVED; /*!< Reserved, Address offset: 0x50 */ + __IO uint32_t CCMR3; /*!< TIM capture/compare mode register 3, Address offset: 0x54 */ + __IO uint32_t CCR5; /*!< TIM capture/compare register5, Address offset: 0x58 */ + __IO uint32_t CCR6; /*!< TIM capture/compare register6, Address offset: 0x5C */ + __IO uint32_t AF1; /*!< TIM alternate function register 1, Address offset: 0x60 */ + __IO uint32_t AF2; /*!< TIM alternate function register 2, Address offset: 0x64 */ + __IO uint32_t TISEL; /*!< TIM Input Selection register, Address offset: 0x68 */ +} TIM_TypeDef; + +/** + * @brief Universal Synchronous Asynchronous Receiver Transmitter + */ +typedef struct +{ + __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x00 */ + __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x04 */ + __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x08 */ + __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x0C */ + __IO uint32_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x10 */ + __IO uint32_t RTOR; /*!< USART Receiver Time Out register, Address offset: 0x14 */ + __IO uint32_t RQR; /*!< USART Request register, Address offset: 0x18 */ + __IO uint32_t ISR; /*!< USART Interrupt and status register, Address offset: 0x1C */ + __IO uint32_t ICR; /*!< USART Interrupt flag Clear register, Address offset: 0x20 */ + __IO uint32_t RDR; /*!< USART Receive Data register, Address offset: 0x24 */ + __IO uint32_t TDR; /*!< USART Transmit Data register, Address offset: 0x28 */ + __IO uint32_t PRESC; /*!< USART Prescaler register, Address offset: 0x2C */ + +} USART_TypeDef; + +/** + * @brief Window WATCHDOG + */ +typedef struct +{ + __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ + __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ + __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ +} WWDG_TypeDef; + +/** +  * @brief Universal Serial Bus Full Speed Dual Role Device +  */ + +typedef struct +{ + __IO uint32_t CHEP0R; /*!< USB Channel/Endpoint 0 register, Address offset: 0x00 */ + __IO uint32_t CHEP1R; /*!< USB Channel/Endpoint 1 register, Address offset: 0x04 */ + __IO uint32_t CHEP2R; /*!< USB Channel/Endpoint 2 register, Address offset: 0x08 */ + __IO uint32_t CHEP3R; /*!< USB Channel/Endpoint 3 register, Address offset: 0x0C */ + __IO uint32_t CHEP4R; /*!< USB Channel/Endpoint 4 register, Address offset: 0x10 */ + __IO uint32_t CHEP5R; /*!< USB Channel/Endpoint 5 register, Address offset: 0x14 */ + __IO uint32_t CHEP6R; /*!< USB Channel/Endpoint 6 register, Address offset: 0x18 */ + __IO uint32_t CHEP7R; /*!< USB Channel/Endpoint 7 register, Address offset: 0x1C */ + __IO uint32_t RESERVED0[8]; /*!< Reserved, */ + __IO uint32_t CNTR; /*!< Control register, Address offset: 0x40 */ + __IO uint32_t ISTR; /*!< Interrupt status register, Address offset: 0x44 */ + __IO uint32_t FNR; /*!< Frame number register, Address offset: 0x48 */ + __IO uint32_t DADDR; /*!< Device address register, Address offset: 0x4C */ + __IO uint32_t RESERVED1; /*!< Reserved */ + __IO uint32_t LPMCSR; /*!< LPM Control and Status register, Address offset: 0x54 */ + __IO uint32_t BCDR; /*!< Battery Charging detector register,   Address offset: 0x58 */ +} USB_DRD_TypeDef; + +/** +  * @brief Universal Serial Bus PacketMemoryArea Buffer Descriptor Table +  */ +typedef struct +{ + __IO uint32_t TXBD; /*! */ +#define RTC_CR_ALRAIE_Pos (12U) +#define RTC_CR_ALRAIE_Msk (0x1UL << RTC_CR_ALRAIE_Pos) /*!< 0x00001000 */ +#define RTC_CR_ALRAIE RTC_CR_ALRAIE_Msk +#define RTC_CR_TSE_Pos (11U) +#define RTC_CR_TSE_Msk (0x1UL << RTC_CR_TSE_Pos) /*!< 0x00000800 */ +#define RTC_CR_TSE RTC_CR_TSE_Msk /*!< timestamp enable > */ +#define RTC_CR_ALRAE_Pos (8U) +#define RTC_CR_ALRAE_Msk (0x1UL << RTC_CR_ALRAE_Pos) /*!< 0x00000100 */ +#define RTC_CR_ALRAE RTC_CR_ALRAE_Msk +#define RTC_CR_FMT_Pos (6U) +#define RTC_CR_FMT_Msk (0x1UL << RTC_CR_FMT_Pos) /*!< 0x00000040 */ +#define RTC_CR_FMT RTC_CR_FMT_Msk +#define RTC_CR_BYPSHAD_Pos (5U) +#define RTC_CR_BYPSHAD_Msk (0x1UL << RTC_CR_BYPSHAD_Pos) /*!< 0x00000020 */ +#define RTC_CR_BYPSHAD RTC_CR_BYPSHAD_Msk +#define RTC_CR_REFCKON_Pos (4U) +#define RTC_CR_REFCKON_Msk (0x1UL << RTC_CR_REFCKON_Pos) /*!< 0x00000010 */ +#define RTC_CR_REFCKON RTC_CR_REFCKON_Msk +#define RTC_CR_TSEDGE_Pos (3U) +#define RTC_CR_TSEDGE_Msk (0x1UL << RTC_CR_TSEDGE_Pos) /*!< 0x00000008 */ +#define RTC_CR_TSEDGE RTC_CR_TSEDGE_Msk /*!< Timestamp event active edge > */ + +/******************** Bits definition for RTC_WPR register ******************/ +#define RTC_WPR_KEY_Pos (0U) +#define RTC_WPR_KEY_Msk (0xFFUL << RTC_WPR_KEY_Pos) /*!< 0x000000FF */ +#define RTC_WPR_KEY RTC_WPR_KEY_Msk + +/******************** Bits definition for RTC_CALR register *****************/ +#define RTC_CALR_CALP_Pos (15U) +#define RTC_CALR_CALP_Msk (0x1UL << RTC_CALR_CALP_Pos) /*!< 0x00008000 */ +#define RTC_CALR_CALP RTC_CALR_CALP_Msk +#define RTC_CALR_CALW8_Pos (14U) +#define RTC_CALR_CALW8_Msk (0x1UL << RTC_CALR_CALW8_Pos) /*!< 0x00004000 */ +#define RTC_CALR_CALW8 RTC_CALR_CALW8_Msk +#define RTC_CALR_CALW16_Pos (13U) +#define RTC_CALR_CALW16_Msk (0x1UL << RTC_CALR_CALW16_Pos) /*!< 0x00002000 */ +#define RTC_CALR_CALW16 RTC_CALR_CALW16_Msk +#define RTC_CALR_CALM_Pos (0U) +#define RTC_CALR_CALM_Msk (0x1FFUL << RTC_CALR_CALM_Pos) /*!< 0x000001FF */ +#define RTC_CALR_CALM RTC_CALR_CALM_Msk +#define RTC_CALR_CALM_0 (0x001UL << RTC_CALR_CALM_Pos) /*!< 0x00000001 */ +#define RTC_CALR_CALM_1 (0x002UL << RTC_CALR_CALM_Pos) /*!< 0x00000002 */ +#define RTC_CALR_CALM_2 (0x004UL << RTC_CALR_CALM_Pos) /*!< 0x00000004 */ +#define RTC_CALR_CALM_3 (0x008UL << RTC_CALR_CALM_Pos) /*!< 0x00000008 */ +#define RTC_CALR_CALM_4 (0x010UL << RTC_CALR_CALM_Pos) /*!< 0x00000010 */ +#define RTC_CALR_CALM_5 (0x020UL << RTC_CALR_CALM_Pos) /*!< 0x00000020 */ +#define RTC_CALR_CALM_6 (0x040UL << RTC_CALR_CALM_Pos) /*!< 0x00000040 */ +#define RTC_CALR_CALM_7 (0x080UL << RTC_CALR_CALM_Pos) /*!< 0x00000080 */ +#define RTC_CALR_CALM_8 (0x100UL << RTC_CALR_CALM_Pos) /*!< 0x00000100 */ + +/******************** Bits definition for RTC_SHIFTR register ***************/ +#define RTC_SHIFTR_ADD1S_Pos (31U) +#define RTC_SHIFTR_ADD1S_Msk (0x1UL << RTC_SHIFTR_ADD1S_Pos) /*!< 0x80000000 */ +#define RTC_SHIFTR_ADD1S RTC_SHIFTR_ADD1S_Msk +#define RTC_SHIFTR_SUBFS_Pos (0U) +#define RTC_SHIFTR_SUBFS_Msk (0x7FFFUL << RTC_SHIFTR_SUBFS_Pos) /*!< 0x00007FFF */ +#define RTC_SHIFTR_SUBFS RTC_SHIFTR_SUBFS_Msk +/******************** Bits definition for RTC_TSTR register *****************/ +#define RTC_TSTR_PM_Pos (22U) +#define RTC_TSTR_PM_Msk (0x1UL << RTC_TSTR_PM_Pos) /*!< 0x00400000 */ +#define RTC_TSTR_PM RTC_TSTR_PM_Msk /*!< AM-PM notation > */ +#define RTC_TSTR_HT_Pos (20U) +#define RTC_TSTR_HT_Msk (0x3UL << RTC_TSTR_HT_Pos) /*!< 0x00300000 */ +#define RTC_TSTR_HT RTC_TSTR_HT_Msk +#define RTC_TSTR_HT_0 (0x1UL << RTC_TSTR_HT_Pos) /*!< 0x00100000 */ +#define RTC_TSTR_HT_1 (0x2UL << RTC_TSTR_HT_Pos) /*!< 0x00200000 */ +#define RTC_TSTR_HU_Pos (16U) +#define RTC_TSTR_HU_Msk (0xFUL << RTC_TSTR_HU_Pos) /*!< 0x000F0000 */ +#define RTC_TSTR_HU RTC_TSTR_HU_Msk +#define RTC_TSTR_HU_0 (0x1UL << RTC_TSTR_HU_Pos) /*!< 0x00010000 */ +#define RTC_TSTR_HU_1 (0x2UL << RTC_TSTR_HU_Pos) /*!< 0x00020000 */ +#define RTC_TSTR_HU_2 (0x4UL << RTC_TSTR_HU_Pos) /*!< 0x00040000 */ +#define RTC_TSTR_HU_3 (0x8UL << RTC_TSTR_HU_Pos) /*!< 0x00080000 */ +#define RTC_TSTR_MNT_Pos (12U) +#define RTC_TSTR_MNT_Msk (0x7UL << RTC_TSTR_MNT_Pos) /*!< 0x00007000 */ +#define RTC_TSTR_MNT RTC_TSTR_MNT_Msk +#define RTC_TSTR_MNT_0 (0x1UL << RTC_TSTR_MNT_Pos) /*!< 0x00001000 */ +#define RTC_TSTR_MNT_1 (0x2UL << RTC_TSTR_MNT_Pos) /*!< 0x00002000 */ +#define RTC_TSTR_MNT_2 (0x4UL << RTC_TSTR_MNT_Pos) /*!< 0x00004000 */ +#define RTC_TSTR_MNU_Pos (8U) +#define RTC_TSTR_MNU_Msk (0xFUL << RTC_TSTR_MNU_Pos) /*!< 0x00000F00 */ +#define RTC_TSTR_MNU RTC_TSTR_MNU_Msk +#define RTC_TSTR_MNU_0 (0x1UL << RTC_TSTR_MNU_Pos) /*!< 0x00000100 */ +#define RTC_TSTR_MNU_1 (0x2UL << RTC_TSTR_MNU_Pos) /*!< 0x00000200 */ +#define RTC_TSTR_MNU_2 (0x4UL << RTC_TSTR_MNU_Pos) /*!< 0x00000400 */ +#define RTC_TSTR_MNU_3 (0x8UL << RTC_TSTR_MNU_Pos) /*!< 0x00000800 */ +#define RTC_TSTR_ST_Pos (4U) +#define RTC_TSTR_ST_Msk (0x7UL << RTC_TSTR_ST_Pos) /*!< 0x00000070 */ +#define RTC_TSTR_ST RTC_TSTR_ST_Msk +#define RTC_TSTR_ST_0 (0x1UL << RTC_TSTR_ST_Pos) /*!< 0x00000010 */ +#define RTC_TSTR_ST_1 (0x2UL << RTC_TSTR_ST_Pos) /*!< 0x00000020 */ +#define RTC_TSTR_ST_2 (0x4UL << RTC_TSTR_ST_Pos) /*!< 0x00000040 */ +#define RTC_TSTR_SU_Pos (0U) +#define RTC_TSTR_SU_Msk (0xFUL << RTC_TSTR_SU_Pos) /*!< 0x0000000F */ +#define RTC_TSTR_SU RTC_TSTR_SU_Msk +#define RTC_TSTR_SU_0 (0x1UL << RTC_TSTR_SU_Pos) /*!< 0x00000001 */ +#define RTC_TSTR_SU_1 (0x2UL << RTC_TSTR_SU_Pos) /*!< 0x00000002 */ +#define RTC_TSTR_SU_2 (0x4UL << RTC_TSTR_SU_Pos) /*!< 0x00000004 */ +#define RTC_TSTR_SU_3 (0x8UL << RTC_TSTR_SU_Pos) /*!< 0x00000008 */ + +/******************** Bits definition for RTC_TSDR register *****************/ +#define RTC_TSDR_WDU_Pos (13U) +#define RTC_TSDR_WDU_Msk (0x7UL << RTC_TSDR_WDU_Pos) /*!< 0x0000E000 */ +#define RTC_TSDR_WDU RTC_TSDR_WDU_Msk /*!< Week day units > */ +#define RTC_TSDR_WDU_0 (0x1UL << RTC_TSDR_WDU_Pos) /*!< 0x00002000 */ +#define RTC_TSDR_WDU_1 (0x2UL << RTC_TSDR_WDU_Pos) /*!< 0x00004000 */ +#define RTC_TSDR_WDU_2 (0x4UL << RTC_TSDR_WDU_Pos) /*!< 0x00008000 */ +#define RTC_TSDR_MT_Pos (12U) +#define RTC_TSDR_MT_Msk (0x1UL << RTC_TSDR_MT_Pos) /*!< 0x00001000 */ +#define RTC_TSDR_MT RTC_TSDR_MT_Msk +#define RTC_TSDR_MU_Pos (8U) +#define RTC_TSDR_MU_Msk (0xFUL << RTC_TSDR_MU_Pos) /*!< 0x00000F00 */ +#define RTC_TSDR_MU RTC_TSDR_MU_Msk +#define RTC_TSDR_MU_0 (0x1UL << RTC_TSDR_MU_Pos) /*!< 0x00000100 */ +#define RTC_TSDR_MU_1 (0x2UL << RTC_TSDR_MU_Pos) /*!< 0x00000200 */ +#define RTC_TSDR_MU_2 (0x4UL << RTC_TSDR_MU_Pos) /*!< 0x00000400 */ +#define RTC_TSDR_MU_3 (0x8UL << RTC_TSDR_MU_Pos) /*!< 0x00000800 */ +#define RTC_TSDR_DT_Pos (4U) +#define RTC_TSDR_DT_Msk (0x3UL << RTC_TSDR_DT_Pos) /*!< 0x00000030 */ +#define RTC_TSDR_DT RTC_TSDR_DT_Msk +#define RTC_TSDR_DT_0 (0x1UL << RTC_TSDR_DT_Pos) /*!< 0x00000010 */ +#define RTC_TSDR_DT_1 (0x2UL << RTC_TSDR_DT_Pos) /*!< 0x00000020 */ +#define RTC_TSDR_DU_Pos (0U) +#define RTC_TSDR_DU_Msk (0xFUL << RTC_TSDR_DU_Pos) /*!< 0x0000000F */ +#define RTC_TSDR_DU RTC_TSDR_DU_Msk +#define RTC_TSDR_DU_0 (0x1UL << RTC_TSDR_DU_Pos) /*!< 0x00000001 */ +#define RTC_TSDR_DU_1 (0x2UL << RTC_TSDR_DU_Pos) /*!< 0x00000002 */ +#define RTC_TSDR_DU_2 (0x4UL << RTC_TSDR_DU_Pos) /*!< 0x00000004 */ +#define RTC_TSDR_DU_3 (0x8UL << RTC_TSDR_DU_Pos) /*!< 0x00000008 */ + +/******************** Bits definition for RTC_TSSSR register ****************/ +#define RTC_TSSSR_SS_Pos (0U) +#define RTC_TSSSR_SS_Msk (0xFFFFUL << RTC_TSSSR_SS_Pos) /*!< 0x0000FFFF */ +#define RTC_TSSSR_SS RTC_TSSSR_SS_Msk /*!< Sub second value > */ + +/******************** Bits definition for RTC_ALRMAR register ***************/ +#define RTC_ALRMAR_MSK4_Pos (31U) +#define RTC_ALRMAR_MSK4_Msk (0x1UL << RTC_ALRMAR_MSK4_Pos) /*!< 0x80000000 */ +#define RTC_ALRMAR_MSK4 RTC_ALRMAR_MSK4_Msk +#define RTC_ALRMAR_WDSEL_Pos (30U) +#define RTC_ALRMAR_WDSEL_Msk (0x1UL << RTC_ALRMAR_WDSEL_Pos) /*!< 0x40000000 */ +#define RTC_ALRMAR_WDSEL RTC_ALRMAR_WDSEL_Msk +#define RTC_ALRMAR_DT_Pos (28U) +#define RTC_ALRMAR_DT_Msk (0x3UL << RTC_ALRMAR_DT_Pos) /*!< 0x30000000 */ +#define RTC_ALRMAR_DT RTC_ALRMAR_DT_Msk +#define RTC_ALRMAR_DT_0 (0x1UL << RTC_ALRMAR_DT_Pos) /*!< 0x10000000 */ +#define RTC_ALRMAR_DT_1 (0x2UL << RTC_ALRMAR_DT_Pos) /*!< 0x20000000 */ +#define RTC_ALRMAR_DU_Pos (24U) +#define RTC_ALRMAR_DU_Msk (0xFUL << RTC_ALRMAR_DU_Pos) /*!< 0x0F000000 */ +#define RTC_ALRMAR_DU RTC_ALRMAR_DU_Msk +#define RTC_ALRMAR_DU_0 (0x1UL << RTC_ALRMAR_DU_Pos) /*!< 0x01000000 */ +#define RTC_ALRMAR_DU_1 (0x2UL << RTC_ALRMAR_DU_Pos) /*!< 0x02000000 */ +#define RTC_ALRMAR_DU_2 (0x4UL << RTC_ALRMAR_DU_Pos) /*!< 0x04000000 */ +#define RTC_ALRMAR_DU_3 (0x8UL << RTC_ALRMAR_DU_Pos) /*!< 0x08000000 */ +#define RTC_ALRMAR_MSK3_Pos (23U) +#define RTC_ALRMAR_MSK3_Msk (0x1UL << RTC_ALRMAR_MSK3_Pos) /*!< 0x00800000 */ +#define RTC_ALRMAR_MSK3 RTC_ALRMAR_MSK3_Msk +#define RTC_ALRMAR_PM_Pos (22U) +#define RTC_ALRMAR_PM_Msk (0x1UL << RTC_ALRMAR_PM_Pos) /*!< 0x00400000 */ +#define RTC_ALRMAR_PM RTC_ALRMAR_PM_Msk +#define RTC_ALRMAR_HT_Pos (20U) +#define RTC_ALRMAR_HT_Msk (0x3UL << RTC_ALRMAR_HT_Pos) /*!< 0x00300000 */ +#define RTC_ALRMAR_HT RTC_ALRMAR_HT_Msk +#define RTC_ALRMAR_HT_0 (0x1UL << RTC_ALRMAR_HT_Pos) /*!< 0x00100000 */ +#define RTC_ALRMAR_HT_1 (0x2UL << RTC_ALRMAR_HT_Pos) /*!< 0x00200000 */ +#define RTC_ALRMAR_HU_Pos (16U) +#define RTC_ALRMAR_HU_Msk (0xFUL << RTC_ALRMAR_HU_Pos) /*!< 0x000F0000 */ +#define RTC_ALRMAR_HU RTC_ALRMAR_HU_Msk +#define RTC_ALRMAR_HU_0 (0x1UL << RTC_ALRMAR_HU_Pos) /*!< 0x00010000 */ +#define RTC_ALRMAR_HU_1 (0x2UL << RTC_ALRMAR_HU_Pos) /*!< 0x00020000 */ +#define RTC_ALRMAR_HU_2 (0x4UL << RTC_ALRMAR_HU_Pos) /*!< 0x00040000 */ +#define RTC_ALRMAR_HU_3 (0x8UL << RTC_ALRMAR_HU_Pos) /*!< 0x00080000 */ +#define RTC_ALRMAR_MSK2_Pos (15U) +#define RTC_ALRMAR_MSK2_Msk (0x1UL << RTC_ALRMAR_MSK2_Pos) /*!< 0x00008000 */ +#define RTC_ALRMAR_MSK2 RTC_ALRMAR_MSK2_Msk +#define RTC_ALRMAR_MNT_Pos (12U) +#define RTC_ALRMAR_MNT_Msk (0x7UL << RTC_ALRMAR_MNT_Pos) /*!< 0x00007000 */ +#define RTC_ALRMAR_MNT RTC_ALRMAR_MNT_Msk +#define RTC_ALRMAR_MNT_0 (0x1UL << RTC_ALRMAR_MNT_Pos) /*!< 0x00001000 */ +#define RTC_ALRMAR_MNT_1 (0x2UL << RTC_ALRMAR_MNT_Pos) /*!< 0x00002000 */ +#define RTC_ALRMAR_MNT_2 (0x4UL << RTC_ALRMAR_MNT_Pos) /*!< 0x00004000 */ +#define RTC_ALRMAR_MNU_Pos (8U) +#define RTC_ALRMAR_MNU_Msk (0xFUL << RTC_ALRMAR_MNU_Pos) /*!< 0x00000F00 */ +#define RTC_ALRMAR_MNU RTC_ALRMAR_MNU_Msk +#define RTC_ALRMAR_MNU_0 (0x1UL << RTC_ALRMAR_MNU_Pos) /*!< 0x00000100 */ +#define RTC_ALRMAR_MNU_1 (0x2UL << RTC_ALRMAR_MNU_Pos) /*!< 0x00000200 */ +#define RTC_ALRMAR_MNU_2 (0x4UL << RTC_ALRMAR_MNU_Pos) /*!< 0x00000400 */ +#define RTC_ALRMAR_MNU_3 (0x8UL << RTC_ALRMAR_MNU_Pos) /*!< 0x00000800 */ +#define RTC_ALRMAR_MSK1_Pos (7U) +#define RTC_ALRMAR_MSK1_Msk (0x1UL << RTC_ALRMAR_MSK1_Pos) /*!< 0x00000080 */ +#define RTC_ALRMAR_MSK1 RTC_ALRMAR_MSK1_Msk +#define RTC_ALRMAR_ST_Pos (4U) +#define RTC_ALRMAR_ST_Msk (0x7UL << RTC_ALRMAR_ST_Pos) /*!< 0x00000070 */ +#define RTC_ALRMAR_ST RTC_ALRMAR_ST_Msk +#define RTC_ALRMAR_ST_0 (0x1UL << RTC_ALRMAR_ST_Pos) /*!< 0x00000010 */ +#define RTC_ALRMAR_ST_1 (0x2UL << RTC_ALRMAR_ST_Pos) /*!< 0x00000020 */ +#define RTC_ALRMAR_ST_2 (0x4UL << RTC_ALRMAR_ST_Pos) /*!< 0x00000040 */ +#define RTC_ALRMAR_SU_Pos (0U) +#define RTC_ALRMAR_SU_Msk (0xFUL << RTC_ALRMAR_SU_Pos) /*!< 0x0000000F */ +#define RTC_ALRMAR_SU RTC_ALRMAR_SU_Msk +#define RTC_ALRMAR_SU_0 (0x1UL << RTC_ALRMAR_SU_Pos) /*!< 0x00000001 */ +#define RTC_ALRMAR_SU_1 (0x2UL << RTC_ALRMAR_SU_Pos) /*!< 0x00000002 */ +#define RTC_ALRMAR_SU_2 (0x4UL << RTC_ALRMAR_SU_Pos) /*!< 0x00000004 */ +#define RTC_ALRMAR_SU_3 (0x8UL << RTC_ALRMAR_SU_Pos) /*!< 0x00000008 */ + +/******************** Bits definition for RTC_ALRMASSR register *************/ +#define RTC_ALRMASSR_MASKSS_Pos (24U) +#define RTC_ALRMASSR_MASKSS_Msk (0xFUL << RTC_ALRMASSR_MASKSS_Pos) /*!< 0x0F000000 */ +#define RTC_ALRMASSR_MASKSS RTC_ALRMASSR_MASKSS_Msk +#define RTC_ALRMASSR_MASKSS_0 (0x1UL << RTC_ALRMASSR_MASKSS_Pos) /*!< 0x01000000 */ +#define RTC_ALRMASSR_MASKSS_1 (0x2UL << RTC_ALRMASSR_MASKSS_Pos) /*!< 0x02000000 */ +#define RTC_ALRMASSR_MASKSS_2 (0x4UL << RTC_ALRMASSR_MASKSS_Pos) /*!< 0x04000000 */ +#define RTC_ALRMASSR_MASKSS_3 (0x8UL << RTC_ALRMASSR_MASKSS_Pos) /*!< 0x08000000 */ +#define RTC_ALRMASSR_SS_Pos (0U) +#define RTC_ALRMASSR_SS_Msk (0x7FFFUL << RTC_ALRMASSR_SS_Pos) /*!< 0x00007FFF */ +#define RTC_ALRMASSR_SS RTC_ALRMASSR_SS_Msk + +/******************** Bits definition for RTC_SR register *******************/ +#define RTC_SR_TSOVF_Pos (4U) +#define RTC_SR_TSOVF_Msk (0x1UL << RTC_SR_TSOVF_Pos) /*!< 0x00000010 */ +#define RTC_SR_TSOVF RTC_SR_TSOVF_Msk /*!< Timestamp overflow flag > */ +#define RTC_SR_TSF_Pos (3U) +#define RTC_SR_TSF_Msk (0x1UL << RTC_SR_TSF_Pos) /*!< 0x00000008 */ +#define RTC_SR_TSF RTC_SR_TSF_Msk /*!< Timestamp flag > */ +#define RTC_SR_ALRAF_Pos (0U) +#define RTC_SR_ALRAF_Msk (0x1UL << RTC_SR_ALRAF_Pos) /*!< 0x00000001 */ +#define RTC_SR_ALRAF RTC_SR_ALRAF_Msk + +/******************** Bits definition for RTC_MISR register *****************/ +#define RTC_MISR_TSOVMF_Pos (4U) +#define RTC_MISR_TSOVMF_Msk (0x1UL << RTC_MISR_TSOVMF_Pos) /*!< 0x00000010 */ +#define RTC_MISR_TSOVMF RTC_MISR_TSOVMF_Msk /*!< Timestamp overflow masked flag > */ +#define RTC_MISR_TSMF_Pos (3U) +#define RTC_MISR_TSMF_Msk (0x1UL << RTC_MISR_TSMF_Pos) /*!< 0x00000008 */ +#define RTC_MISR_TSMF RTC_MISR_TSMF_Msk /*!< Timestamp masked flag > */ +#define RTC_MISR_ALRAMF_Pos (0U) +#define RTC_MISR_ALRAMF_Msk (0x1UL << RTC_MISR_ALRAMF_Pos) /*!< 0x00000001 */ +#define RTC_MISR_ALRAMF RTC_MISR_ALRAMF_Msk + +/******************** Bits definition for RTC_SCR register ******************/ +#define RTC_SCR_CTSOVF_Pos (4U) +#define RTC_SCR_CTSOVF_Msk (0x1UL << RTC_SCR_CTSOVF_Pos) /*!< 0x00000010 */ +#define RTC_SCR_CTSOVF RTC_SCR_CTSOVF_Msk /*!< Clear timestamp overflow flag > */ +#define RTC_SCR_CTSF_Pos (3U) +#define RTC_SCR_CTSF_Msk (0x1UL << RTC_SCR_CTSF_Pos) /*!< 0x00000008 */ +#define RTC_SCR_CTSF RTC_SCR_CTSF_Msk /*!< Clear timestamp flag > */ +#define RTC_SCR_CALRAF_Pos (0U) +#define RTC_SCR_CALRAF_Msk (0x1UL << RTC_SCR_CALRAF_Pos) /*!< 0x00000001 */ +#define RTC_SCR_CALRAF RTC_SCR_CALRAF_Msk + +/******************************************************************************/ +/* */ +/* Serial Peripheral Interface (SPI) */ +/* */ +/******************************************************************************/ + +#define SPI_I2S_SUPPORT /*!< I2S support */ + +/******************* Bit definition for SPI_CR1 register ********************/ +#define SPI_CR1_CPHA_Pos (0U) +#define SPI_CR1_CPHA_Msk (0x1UL << SPI_CR1_CPHA_Pos) /*!< 0x00000001 */ +#define SPI_CR1_CPHA SPI_CR1_CPHA_Msk /*! exti[22]*/ +#define SYSCFG_ITLINE25_SR_SPI1_Pos (0U) +#define SYSCFG_ITLINE25_SR_SPI1_Msk (0x1UL << SYSCFG_ITLINE25_SR_SPI1_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE25_SR_SPI1 SYSCFG_ITLINE25_SR_SPI1_Msk /*!< SPI1 Interrupt */ +#define SYSCFG_ITLINE26_SR_SPI2_Pos (0U) +#define SYSCFG_ITLINE26_SR_SPI2_Msk (0x1UL << SYSCFG_ITLINE26_SR_SPI2_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE26_SR_SPI2 SYSCFG_ITLINE26_SR_SPI2_Msk /*!< SPI2 Interrupt */ +#define SYSCFG_ITLINE27_SR_USART1_GLB_Pos (0U) +#define SYSCFG_ITLINE27_SR_USART1_GLB_Msk (0x1UL << SYSCFG_ITLINE27_SR_USART1_GLB_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE27_SR_USART1_GLB SYSCFG_ITLINE27_SR_USART1_GLB_Msk /*!< USART1 GLB Interrupt */ +#define SYSCFG_ITLINE28_SR_USART2_GLB_Pos (0U) +#define SYSCFG_ITLINE28_SR_USART2_GLB_Msk (0x1UL << SYSCFG_ITLINE28_SR_USART2_GLB_Pos) /*!< 0x00000001 */ +#define SYSCFG_ITLINE28_SR_USART2_GLB SYSCFG_ITLINE28_SR_USART2_GLB_Msk /*!< USART2 GLB Interrupt */ + +/******************************************************************************/ +/* */ +/* TIM */ +/* */ +/******************************************************************************/ +/******************* Bit definition for TIM_CR1 register ********************/ +#define TIM_CR1_CEN_Pos (0U) +#define TIM_CR1_CEN_Msk (0x1UL << TIM_CR1_CEN_Pos) /*!< 0x00000001 */ +#define TIM_CR1_CEN TIM_CR1_CEN_Msk /*!CR & RCC_CR_SYSDIV) >> RCC_CR_SYSDIV_Pos) + 1U); +#else + sysdiv = 1U; +#endif /* RCC_CR_SYSDIV */ /* Get SYSCLK source -------------------------------------------------------*/ switch (RCC->CFGR & RCC_CFGR_SWS) { case RCC_CFGR_SWS_0: /* HSE used as system clock */ - SystemCoreClock = HSE_VALUE; + SystemCoreClock = (HSE_VALUE / sysdiv); + break; + +#if defined(RCC_HSI48_SUPPORT) + case RCC_CFGR_SW_1: /* HSI48 used as system clock */ + SystemCoreClock = (HSI48_VALUE / sysdiv); break; +#endif /* RCC_HSI48_SUPPORT */ case (RCC_CFGR_SWS_1 | RCC_CFGR_SWS_0): /* LSI used as system clock */ - SystemCoreClock = LSI_VALUE; + SystemCoreClock = (LSI_VALUE / sysdiv); break; case RCC_CFGR_SWS_2: /* LSE used as system clock */ - SystemCoreClock = LSE_VALUE; + SystemCoreClock = (LSE_VALUE / sysdiv); break; case 0x00000000U: /* HSI used as system clock */ default: /* HSI used as system clock */ hsidiv = (1UL << ((READ_BIT(RCC->CR, RCC_CR_HSIDIV))>> RCC_CR_HSIDIV_Pos)); - SystemCoreClock = (HSI_VALUE/hsidiv); + SystemCoreClock = ((HSI_VALUE / sysdiv) / hsidiv); break; } /* Compute HCLK clock frequency --------------------------------------------*/ From 726f23b09c0dd31cdd78f5b25fb3cd6cb3dd10fa Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 14:51:48 +0200 Subject: [PATCH 02/11] stm32cube: update stm32f1 to cube version V1.8.6 Update Cube version for STM32F1xx series on https://github.com/STMicroelectronics from version v1.8.5 to version v1.8.6 Signed-off-by: Guillaume Gautier --- stm32cube/stm32f1xx/README | 13 +- .../drivers/include/Legacy/stm32_hal_legacy.h | 91 ++-- .../drivers/include/stm32f1xx_hal_can.h | 4 + .../drivers/include/stm32f1xx_hal_cortex.h | 3 +- .../drivers/include/stm32f1xx_hal_nand.h | 2 +- .../drivers/include/stm32f1xx_hal_pccard.h | 13 +- .../drivers/include/stm32f1xx_hal_spi.h | 44 +- .../drivers/include/stm32f1xx_hal_tim.h | 35 +- .../drivers/include/stm32f1xx_hal_usart.h | 2 +- .../drivers/include/stm32f1xx_hal_wwdg.h | 2 +- .../drivers/include/stm32f1xx_ll_adc.h | 4 +- .../drivers/include/stm32f1xx_ll_cortex.h | 2 +- .../drivers/include/stm32f1xx_ll_dac.h | 3 +- .../drivers/include/stm32f1xx_ll_fsmc.h | 167 ++++---- .../drivers/include/stm32f1xx_ll_iwdg.h | 10 +- .../drivers/include/stm32f1xx_ll_sdmmc.h | 8 +- .../drivers/include/stm32f1xx_ll_spi.h | 137 +++--- .../drivers/include/stm32f1xx_ll_tim.h | 25 +- .../drivers/include/stm32f1xx_ll_usart.h | 114 ++--- .../drivers/include/stm32f1xx_ll_usb.h | 101 +++-- .../drivers/include/stm32f1xx_ll_utils.h | 2 +- .../drivers/include/stm32f1xx_ll_wwdg.h | 12 +- .../stm32f1xx/drivers/src/stm32f1xx_hal.c | 2 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_can.c | 41 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_cec.c | 2 +- .../drivers/src/stm32f1xx_hal_cortex.c | 82 ++-- .../stm32f1xx/drivers/src/stm32f1xx_hal_dac.c | 5 +- .../drivers/src/stm32f1xx_hal_dac_ex.c | 1 - .../drivers/src/stm32f1xx_hal_flash.c | 5 - .../drivers/src/stm32f1xx_hal_flash_ex.c | 3 - .../drivers/src/stm32f1xx_hal_gpio.c | 2 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_hcd.c | 37 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_i2c.c | 51 ++- .../stm32f1xx/drivers/src/stm32f1xx_hal_i2s.c | 78 ++-- .../drivers/src/stm32f1xx_hal_iwdg.c | 3 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_mmc.c | 2 +- .../drivers/src/stm32f1xx_hal_nand.c | 4 +- .../drivers/src/stm32f1xx_hal_pccard.c | 40 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_pcd.c | 30 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_sd.c | 21 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_spi.c | 400 +++++++++--------- .../drivers/src/stm32f1xx_hal_sram.c | 5 +- .../stm32f1xx/drivers/src/stm32f1xx_hal_tim.c | 62 +-- .../drivers/src/stm32f1xx_hal_tim_ex.c | 34 +- ...tm32f1xx_hal_timebase_rtc_alarm_template.c | 110 +++-- .../src/stm32f1xx_hal_timebase_tim_template.c | 23 +- .../drivers/src/stm32f1xx_hal_uart.c | 61 ++- .../drivers/src/stm32f1xx_hal_usart.c | 9 +- .../drivers/src/stm32f1xx_hal_wwdg.c | 130 +++--- .../stm32f1xx/drivers/src/stm32f1xx_ll_fsmc.c | 45 +- .../stm32f1xx/drivers/src/stm32f1xx_ll_spi.c | 9 +- .../stm32f1xx/drivers/src/stm32f1xx_ll_tim.c | 22 +- .../stm32f1xx/drivers/src/stm32f1xx_ll_usb.c | 88 ++-- stm32cube/stm32f1xx/release_note.html | 356 ++++++++++++---- stm32cube/stm32f1xx/soc/stm32f100xb.h | 2 - stm32cube/stm32f1xx/soc/stm32f100xe.h | 2 - stm32cube/stm32f1xx/soc/stm32f101x6.h | 2 - stm32cube/stm32f1xx/soc/stm32f101xb.h | 2 - stm32cube/stm32f1xx/soc/stm32f101xe.h | 2 - stm32cube/stm32f1xx/soc/stm32f101xg.h | 2 - stm32cube/stm32f1xx/soc/stm32f102x6.h | 2 - stm32cube/stm32f1xx/soc/stm32f102xb.h | 2 - stm32cube/stm32f1xx/soc/stm32f103x6.h | 2 - stm32cube/stm32f1xx/soc/stm32f103xb.h | 2 - stm32cube/stm32f1xx/soc/stm32f103xe.h | 2 - stm32cube/stm32f1xx/soc/stm32f103xg.h | 2 - stm32cube/stm32f1xx/soc/stm32f105xc.h | 2 - stm32cube/stm32f1xx/soc/stm32f107xc.h | 2 - stm32cube/stm32f1xx/soc/stm32f1xx.h | 3 +- stm32cube/stm32f1xx/soc/system_stm32f1xx.c | 2 +- 70 files changed, 1487 insertions(+), 1103 deletions(-) diff --git a/stm32cube/stm32f1xx/README b/stm32cube/stm32f1xx/README index 547e8e2e9..110e712ce 100644 --- a/stm32cube/stm32f1xx/README +++ b/stm32cube/stm32f1xx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubef1.html Status: - version v1.8.5 + version v1.8.6 Purpose: ST Microelectronics official MCU package for STM32F1 series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeF1 Commit: - 5326afcfb2ecfb27b7e473fd43e1adec9e3595ec + 42472d601caa457b02d849c7de5f9792629ee324 Maintained-by: External @@ -52,11 +52,8 @@ Patch List: -Added stm32cube/stm32f1xx/drivers/include/stm32_assert.h -Removed unused stm32cube/stm32f1xx/drivers/include/stm32_assert_template.h - *Wrap define UNUSED with an ifndef - This will prevent a compiler warning for the case the UNUSED macro - is already defined elsewhere in the project - Impacted files: - drivers/include/stm32f1xx_hal_def.h - ST Internal Reference: 136825 + *Fix to remove PAGESIZE definition which conflicts with POSIX + Impacted files: + drivers/include/Legacy/stm32_hal_legacy.h See release_note.html from STM32Cube diff --git a/stm32cube/stm32f1xx/drivers/include/Legacy/stm32_hal_legacy.h b/stm32cube/stm32f1xx/drivers/include/Legacy/stm32_hal_legacy.h index a1fc260ec..6bacae34d 100644 --- a/stm32cube/stm32f1xx/drivers/include/Legacy/stm32_hal_legacy.h +++ b/stm32cube/stm32f1xx/drivers/include/Legacy/stm32_hal_legacy.h @@ -37,16 +37,12 @@ extern "C" { #define AES_CLEARFLAG_CCF CRYP_CLEARFLAG_CCF #define AES_CLEARFLAG_RDERR CRYP_CLEARFLAG_RDERR #define AES_CLEARFLAG_WRERR CRYP_CLEARFLAG_WRERR -#if defined(STM32U5) || defined(STM32H7) || defined(STM32MP1) +#if defined(STM32H7) || defined(STM32MP1) #define CRYP_DATATYPE_32B CRYP_NO_SWAP #define CRYP_DATATYPE_16B CRYP_HALFWORD_SWAP #define CRYP_DATATYPE_8B CRYP_BYTE_SWAP #define CRYP_DATATYPE_1B CRYP_BIT_SWAP -#if defined(STM32U5) -#define CRYP_CCF_CLEAR CRYP_CLEAR_CCF -#define CRYP_ERR_CLEAR CRYP_CLEAR_RWEIF -#endif /* STM32U5 */ -#endif /* STM32U5 || STM32H7 || STM32MP1 */ +#endif /* STM32H7 || STM32MP1 */ /** * @} */ @@ -279,7 +275,7 @@ extern "C" { #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE -#if defined(STM32G4) || defined(STM32L5) || defined(STM32H7) || defined (STM32U5) +#if defined(STM32G4) || defined(STM32H7) || defined (STM32U5) #define DAC_CHIPCONNECT_DISABLE DAC_CHIPCONNECT_EXTERNAL #define DAC_CHIPCONNECT_ENABLE DAC_CHIPCONNECT_INTERNAL #endif @@ -476,7 +472,9 @@ extern "C" { #define TYPEPROGRAMDATA_FASTBYTE FLASH_TYPEPROGRAMDATA_FASTBYTE #define TYPEPROGRAMDATA_FASTHALFWORD FLASH_TYPEPROGRAMDATA_FASTHALFWORD #define TYPEPROGRAMDATA_FASTWORD FLASH_TYPEPROGRAMDATA_FASTWORD +#if !defined(STM32F2) && !defined(STM32F4) && !defined(STM32F7) && !defined(STM32H7) /* #define PAGESIZE FLASH_PAGE_SIZE */ +#endif /* STM32F2 && STM32F4 && STM32F7 && STM32H7 */ #define TYPEPROGRAM_FASTBYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_FASTHALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_FASTWORD FLASH_TYPEPROGRAM_WORD @@ -552,6 +550,16 @@ extern "C" { #define OB_SRAM134_RST_ERASE OB_SRAM_RST_ERASE #define OB_SRAM134_RST_NOT_ERASE OB_SRAM_RST_NOT_ERASE #endif /* STM32U5 */ +#if defined(STM32U0) +#define OB_USER_nRST_STOP OB_USER_NRST_STOP +#define OB_USER_nRST_STDBY OB_USER_NRST_STDBY +#define OB_USER_nRST_SHDW OB_USER_NRST_SHDW +#define OB_USER_nBOOT_SEL OB_USER_NBOOT_SEL +#define OB_USER_nBOOT0 OB_USER_NBOOT0 +#define OB_USER_nBOOT1 OB_USER_NBOOT1 +#define OB_nBOOT0_RESET OB_NBOOT0_RESET +#define OB_nBOOT0_SET OB_NBOOT0_SET +#endif /* STM32U0 */ /** * @} @@ -800,6 +808,21 @@ extern "C" { #define GPIO_AF0_S2DSTOP GPIO_AF0_SRDSTOP #define GPIO_AF11_LPGPIO GPIO_AF11_LPGPIO1 #endif /* STM32U5 */ + +#if defined(STM32WBA) +#define GPIO_AF11_RF_ANTSW0 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW1 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO1 GPIO_AF11_RF +#define GPIO_AF11_RF_IO2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO3 GPIO_AF11_RF +#define GPIO_AF11_RF_IO4 GPIO_AF11_RF +#define GPIO_AF11_RF_IO5 GPIO_AF11_RF +#define GPIO_AF11_RF_IO6 GPIO_AF11_RF +#define GPIO_AF11_RF_IO7 GPIO_AF11_RF +#define GPIO_AF11_RF_IO8 GPIO_AF11_RF +#define GPIO_AF11_RF_IO9 GPIO_AF11_RF +#endif /* STM32WBA */ /** * @} */ @@ -1243,10 +1266,10 @@ extern "C" { #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 -#if defined(STM32H5) +#if defined(STM32H5) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_BKP_SRAM TAMP_DEVICESECRETS_ERASE_BKPSRAM -#endif /* STM32H5 */ +#endif /* STM32H5 || STM32H7RS */ #if defined(STM32WBA) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE @@ -1258,10 +1281,10 @@ extern "C" { #define TAMP_SECRETDEVICE_ERASE_ALL TAMP_DEVICESECRETS_ERASE_ALL #endif /* STM32WBA */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_DISABLE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_ENABLE TAMP_SECRETDEVICE_ERASE_ALL -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ #if defined(STM32F7) #define RTC_TAMPCR_TAMPXE RTC_TAMPER_ENABLE_BITS_MASK @@ -1599,6 +1622,8 @@ extern "C" { #define ETH_MAC_SMALL_FIFO_RW_ACTIVE 0x00000006U /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE 0x00000001U /* MAC MII receive protocol engine active */ +#define ETH_TxPacketConfig ETH_TxPacketConfigTypeDef /* Transmit Packet Configuration structure definition */ + /** * @} */ @@ -1809,7 +1834,7 @@ extern "C" { #define HAL_FMPI2CEx_AnalogFilter_Config HAL_FMPI2CEx_ConfigAnalogFilter #define HAL_FMPI2CEx_DigitalFilter_Config HAL_FMPI2CEx_ConfigDigitalFilter -#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) ((cmd == ENABLE)? \ +#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd) == ENABLE)? \ HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): \ HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) @@ -1991,12 +2016,12 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Functions HAL RTC Aliased Functions maintained for legacy purpose * @{ */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define HAL_RTCEx_SetBoothardwareKey HAL_RTCEx_LockBootHardwareKey #define HAL_RTCEx_BKUPBlock_Enable HAL_RTCEx_BKUPBlock #define HAL_RTCEx_BKUPBlock_Disable HAL_RTCEx_BKUPUnblock #define HAL_RTCEx_Erase_SecretDev_Conf HAL_RTCEx_ConfigEraseDeviceSecrets -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ /** * @} @@ -2311,8 +2336,8 @@ extern "C" { #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F302xE) || defined(STM32F302xC) +#endif +#if defined(STM32F302xE) || defined(STM32F302xC) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_ENABLE_RISING_EDGE() : \ @@ -2345,8 +2370,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) +#endif +#if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP3) ? __HAL_COMP_COMP3_EXTI_ENABLE_RISING_EDGE() : \ @@ -2403,8 +2428,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP5) ? __HAL_COMP_COMP5_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP6) ? __HAL_COMP_COMP6_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP7_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F373xC) ||defined(STM32F378xx) +#endif +#if defined(STM32F373xC) ||defined(STM32F378xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE() : \ @@ -2421,7 +2446,7 @@ extern "C" { __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) -# endif +#endif #else #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) @@ -2723,6 +2748,12 @@ extern "C" { #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET +#if defined(STM32C0) +#define __HAL_RCC_APB1_FORCE_RESET __HAL_RCC_APB1_GRP1_FORCE_RESET +#define __HAL_RCC_APB1_RELEASE_RESET __HAL_RCC_APB1_GRP1_RELEASE_RESET +#define __HAL_RCC_APB2_FORCE_RESET __HAL_RCC_APB1_GRP2_FORCE_RESET +#define __HAL_RCC_APB2_RELEASE_RESET __HAL_RCC_APB1_GRP2_RELEASE_RESET +#endif /* STM32C0 */ #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET @@ -3646,8 +3677,12 @@ extern "C" { #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 +#if defined(STM32U0) +#define RCC_SYSCLKSOURCE_STATUS_PLLR RCC_SYSCLKSOURCE_STATUS_PLLCLK +#endif + #if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) || \ - defined(STM32WL) || defined(STM32C0) + defined(STM32WL) || defined(STM32C0) || defined(STM32H7RS) || defined(STM32U0) #define RCC_RTCCLKSOURCE_NO_CLK RCC_RTCCLKSOURCE_NONE #else #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK @@ -3749,8 +3784,10 @@ extern "C" { #define __HAL_RCC_GET_DFSDM_SOURCE __HAL_RCC_GET_DFSDM1_SOURCE #define RCC_DFSDM1CLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 #define RCC_SWPMI1CLKSOURCE_PCLK RCC_SWPMI1CLKSOURCE_PCLK1 +#if !defined(STM32U0) #define RCC_LPTIM1CLKSOURCE_PCLK RCC_LPTIM1CLKSOURCE_PCLK1 #define RCC_LPTIM2CLKSOURCE_PCLK RCC_LPTIM2CLKSOURCE_PCLK1 +#endif #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM1AUDIOCLKSOURCE_I2S1 #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM1AUDIOCLKSOURCE_I2S2 @@ -3896,7 +3933,8 @@ extern "C" { */ #if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || \ defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || \ - defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) + defined (STM32WBA) || defined (STM32H5) || \ + defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) #else #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #endif @@ -3932,7 +3970,9 @@ extern "C" { #endif /* STM32F1 */ #if defined (STM32F0) || defined (STM32F2) || defined (STM32F3) || defined (STM32F4) || defined (STM32F7) || \ - defined (STM32L0) || defined (STM32L1) + defined (STM32H7) || \ + defined (STM32L0) || defined (STM32L1) || \ + defined (STM32WB) #define __HAL_RTC_TAMPER_GET_IT __HAL_RTC_TAMPER_GET_FLAG #endif @@ -4217,6 +4257,9 @@ extern "C" { #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_BREAKINPUTSOURCE_DFSDM TIM_BREAKINPUTSOURCE_DFSDM1 + +#define TIM_OCMODE_ASSYMETRIC_PWM1 TIM_OCMODE_ASYMMETRIC_PWM1 +#define TIM_OCMODE_ASSYMETRIC_PWM2 TIM_OCMODE_ASYMMETRIC_PWM2 /** * @} */ diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_can.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_can.h index 287c9919e..db8cc92fb 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_can.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_can.h @@ -209,7 +209,11 @@ typedef struct /** * @brief CAN handle Structure definition */ +#if USE_HAL_CAN_REGISTER_CALLBACKS == 1 typedef struct __CAN_HandleTypeDef +#else +typedef struct +#endif /* USE_HAL_CAN_REGISTER_CALLBACKS */ { CAN_TypeDef *Instance; /*!< Register base address */ diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_cortex.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_cortex.h index cea3dc759..5d03cd3cc 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_cortex.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_cortex.h @@ -285,6 +285,8 @@ void HAL_SYSTICK_Callback(void); #if (__MPU_PRESENT == 1U) void HAL_MPU_Enable(uint32_t MPU_Control); void HAL_MPU_Disable(void); +void HAL_MPU_EnableRegion(uint32_t RegionNumber); +void HAL_MPU_DisableRegion(uint32_t RegionNumber); void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ /** @@ -405,4 +407,3 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __STM32F1xx_HAL_CORTEX_H */ - diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_nand.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_nand.h index 38093c3e7..81562cee7 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_nand.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_nand.h @@ -194,7 +194,7 @@ HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FSMC_NAND_PCC_Timing FSMC_NAND_PCC_TimingTypeDef *AttSpace_Timing); HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand); -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig); +HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, const NAND_DeviceConfigTypeDef *pDeviceConfig); HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_pccard.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_pccard.h index 58ec0eaff..dc726caa0 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_pccard.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_pccard.h @@ -68,7 +68,7 @@ typedef enum typedef struct __PCCARD_HandleTypeDef #else typedef struct -#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ { FSMC_PCCARD_TypeDef *Instance; /*!< Register base address for PCCARD device */ @@ -82,7 +82,7 @@ typedef struct void (* MspInitCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD Msp Init callback */ void (* MspDeInitCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD Msp DeInit callback */ void (* ItCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD IT callback */ -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ } PCCARD_HandleTypeDef; #if (USE_HAL_PCCARD_REGISTER_CALLBACKS == 1) @@ -100,7 +100,7 @@ typedef enum * @brief HAL PCCARD Callback pointer definition */ typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} */ @@ -122,7 +122,7 @@ typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); } while(0) #else #define __HAL_PCCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_PCCARD_STATE_RESET) -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} */ @@ -137,7 +137,8 @@ typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FSMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, - FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); + FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, + FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard); @@ -165,7 +166,7 @@ HAL_StatusTypeDef HAL_PCCARD_RegisterCallback(PCCARD_HandleTypeDef *hpccard, HA pPCCARD_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_PCCARD_UnRegisterCallback(PCCARD_HandleTypeDef *hpccard, HAL_PCCARD_CallbackIDTypeDef CallbackId); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} */ diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_spi.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_spi.h index 73073fc8f..309eb5bd2 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_spi.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_spi.h @@ -107,7 +107,7 @@ typedef struct __SPI_HandleTypeDef SPI_InitTypeDef Init; /*!< SPI communication parameters */ - uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ + const uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /*!< SPI Tx Transfer size */ @@ -336,11 +336,12 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * @retval None */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) -#define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->State = HAL_SPI_STATE_RESET; \ - (__HANDLE__)->MspInitCallback = NULL; \ - (__HANDLE__)->MspDeInitCallback = NULL; \ - } while(0) +#define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) \ + do{ \ + (__HANDLE__)->State = HAL_SPI_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) #else #define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) #endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ @@ -482,8 +483,11 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ -#define SPI_RESET_CRC(__HANDLE__) do{CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);\ - SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);}while(0U) +#define SPI_RESET_CRC(__HANDLE__) \ + do{ \ + CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN); \ + SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN); \ + } while(0U) /** @brief Check whether the specified SPI flag is set or not. * @param __SR__ copy of SPI SR register. @@ -498,7 +502,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * @retval SET or RESET. */ #define SPI_CHECK_FLAG(__SR__, __FLAG__) ((((__SR__) & ((__FLAG__) & SPI_FLAG_MASK)) == \ - ((__FLAG__) & SPI_FLAG_MASK)) ? SET : RESET) + ((__FLAG__) & SPI_FLAG_MASK)) ? SET : RESET) /** @brief Check whether the specified SPI Interrupt is set or not. * @param __CR2__ copy of SPI CR2 register. @@ -510,7 +514,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * @retval SET or RESET. */ #define SPI_CHECK_IT_SOURCE(__CR2__, __INTERRUPT__) ((((__CR2__) & (__INTERRUPT__)) == \ - (__INTERRUPT__)) ? SET : RESET) + (__INTERRUPT__)) ? SET : RESET) /** @brief Checks if SPI Mode parameter is in allowed range. * @param __MODE__ specifies the SPI Mode. @@ -619,7 +623,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to */ #define IS_SPI_CRC_POLYNOMIAL(__POLYNOMIAL__) (((__POLYNOMIAL__) >= 0x1U) && \ ((__POLYNOMIAL__) <= 0xFFFFU) && \ - (((__POLYNOMIAL__)&0x1U) != 0U)) + (((__POLYNOMIAL__)&0x1U) != 0U)) /** @brief Checks if DMA handle is valid. * @param __HANDLE__ specifies a DMA Handle. @@ -668,17 +672,17 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @{ */ /* I/O operation functions ***************************************************/ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, - uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); @@ -704,8 +708,8 @@ void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi); * @{ */ /* Peripheral State and Error functions ***************************************/ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi); +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi); /** * @} */ diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_tim.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_tim.h index 53951f77c..ac7207586 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_tim.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_tim.h @@ -385,29 +385,28 @@ typedef struct */ typedef enum { - HAL_TIM_BASE_MSPINIT_CB_ID = 0x00U /*!< TIM Base MspInit Callback ID */ - , HAL_TIM_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TIM Base MspDeInit Callback ID */ - , HAL_TIM_IC_MSPINIT_CB_ID = 0x02U /*!< TIM IC MspInit Callback ID */ - , HAL_TIM_IC_MSPDEINIT_CB_ID = 0x03U /*!< TIM IC MspDeInit Callback ID */ - , HAL_TIM_OC_MSPINIT_CB_ID = 0x04U /*!< TIM OC MspInit Callback ID */ - , HAL_TIM_OC_MSPDEINIT_CB_ID = 0x05U /*!< TIM OC MspDeInit Callback ID */ - , HAL_TIM_PWM_MSPINIT_CB_ID = 0x06U /*!< TIM PWM MspInit Callback ID */ - , HAL_TIM_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TIM PWM MspDeInit Callback ID */ - , HAL_TIM_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TIM One Pulse MspInit Callback ID */ - , HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TIM One Pulse MspDeInit Callback ID */ - , HAL_TIM_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TIM Encoder MspInit Callback ID */ - , HAL_TIM_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TIM Encoder MspDeInit Callback ID */ - , HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TIM Hall Sensor MspDeInit Callback ID */ - , HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TIM Hall Sensor MspDeInit Callback ID */ + HAL_TIM_BASE_MSPINIT_CB_ID = 0x00U /*!< TIM Base MspInit Callback ID */ + , HAL_TIM_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TIM Base MspDeInit Callback ID */ + , HAL_TIM_IC_MSPINIT_CB_ID = 0x02U /*!< TIM IC MspInit Callback ID */ + , HAL_TIM_IC_MSPDEINIT_CB_ID = 0x03U /*!< TIM IC MspDeInit Callback ID */ + , HAL_TIM_OC_MSPINIT_CB_ID = 0x04U /*!< TIM OC MspInit Callback ID */ + , HAL_TIM_OC_MSPDEINIT_CB_ID = 0x05U /*!< TIM OC MspDeInit Callback ID */ + , HAL_TIM_PWM_MSPINIT_CB_ID = 0x06U /*!< TIM PWM MspInit Callback ID */ + , HAL_TIM_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TIM PWM MspDeInit Callback ID */ + , HAL_TIM_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TIM One Pulse MspInit Callback ID */ + , HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TIM One Pulse MspDeInit Callback ID */ + , HAL_TIM_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TIM Encoder MspInit Callback ID */ + , HAL_TIM_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TIM Encoder MspDeInit Callback ID */ + , HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TIM Hall Sensor MspDeInit Callback ID */ + , HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TIM Hall Sensor MspDeInit Callback ID */ , HAL_TIM_PERIOD_ELAPSED_CB_ID = 0x0EU /*!< TIM Period Elapsed Callback ID */ , HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID = 0x0FU /*!< TIM Period Elapsed half complete Callback ID */ , HAL_TIM_TRIGGER_CB_ID = 0x10U /*!< TIM Trigger Callback ID */ , HAL_TIM_TRIGGER_HALF_CB_ID = 0x11U /*!< TIM Trigger half complete Callback ID */ - , HAL_TIM_IC_CAPTURE_CB_ID = 0x12U /*!< TIM Input Capture Callback ID */ , HAL_TIM_IC_CAPTURE_HALF_CB_ID = 0x13U /*!< TIM Input Capture half complete Callback ID */ , HAL_TIM_OC_DELAY_ELAPSED_CB_ID = 0x14U /*!< TIM Output Compare Delay Elapsed Callback ID */ - , HAL_TIM_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TIM PWM Pulse Finished Callback ID */ + , HAL_TIM_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TIM PWM Pulse Finished Callback ID */ , HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID = 0x16U /*!< TIM PWM Pulse Finished half complete Callback ID */ , HAL_TIM_ERROR_CB_ID = 0x17U /*!< TIM Error Callback ID */ , HAL_TIM_COMMUTATION_CB_ID = 0x18U /*!< TIM Commutation Callback ID */ @@ -1707,7 +1706,6 @@ typedef void (*pTIM_CallbackTypeDef)(TIM_HandleTypeDef *htim); /*!< pointer to #define IS_TIM_BREAK_FILTER(__BRKFILTER__) ((__BRKFILTER__) <= 0xFUL) - #define IS_TIM_BREAK_STATE(__STATE__) (((__STATE__) == TIM_BREAK_ENABLE) || \ ((__STATE__) == TIM_BREAK_DISABLE)) @@ -2045,7 +2043,8 @@ HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_S HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro_IT(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength); + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_MultiWriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength, uint32_t DataLength); diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_usart.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_usart.h index 551171cb5..cb0f638b9 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_usart.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_usart.h @@ -624,7 +624,7 @@ uint32_t HAL_USART_GetError(const USART_HandleTypeDef *husart); */ /* Private functions ---------------------------------------------------------*/ -/** @defgroup USART_Private_Functions USART Private Functions +/** @addtogroup USART_Private_Functions * @{ */ diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_wwdg.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_wwdg.h index 6179e20b7..081a918ac 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_wwdg.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_wwdg.h @@ -183,7 +183,7 @@ typedef void (*pWWDG_CallbackTypeDef)(WWDG_HandleTypeDef *hppp); /*!< pointer t /** * @brief Enable the WWDG early wakeup interrupt. - * @param __HANDLE__ WWDG handle + * @param __HANDLE__: WWDG handle * @param __INTERRUPT__ specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_adc.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_adc.h index fb65098bb..e341933e3 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_adc.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_adc.h @@ -3686,7 +3686,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_JEOS(ADC_Common_TypeDef *ADCxy_ /* end of unitary conversion. */ /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ /* in other STM32 families). */ - return (READ_BIT(ADC1->SR, ADC_SR_JEOC) == (ADC_SR_JEOC)); + return (READ_BIT(ADCxy_COMMON->SR, ADC_SR_JEOC) == (ADC_SR_JEOC)); } /** @@ -3717,7 +3717,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV_JEOS(ADC_Common_TypeDef *ADCxy_ */ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) { - return (READ_BIT(ADC1->SR, LL_ADC_FLAG_AWD1) == (LL_ADC_FLAG_AWD1)); + return (READ_BIT(ADCxy_COMMON->SR, LL_ADC_FLAG_AWD1) == (LL_ADC_FLAG_AWD1)); } /** diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_cortex.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_cortex.h index c8b503c99..c1fb2c774 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_cortex.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_cortex.h @@ -587,7 +587,7 @@ __STATIC_INLINE void LL_MPU_ConfigRegion(uint32_t Region, uint32_t SubRegionDisa /* Set base address */ WRITE_REG(MPU->RBAR, (Address & 0xFFFFFFE0U)); /* Configure MPU */ - WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | SubRegionDisable << MPU_RASR_SRD_Pos)); + WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | (SubRegionDisable << MPU_RASR_SRD_Pos))); } /** diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_dac.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_dac.h index 3e17bbf6e..6e885f036 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_dac.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_dac.h @@ -87,7 +87,6 @@ extern "C" { #define DAC_REG_DORX_REGOFFSET_MASK (DAC_REG_DOR1_REGOFFSET | DAC_REG_DOR2_REGOFFSET) - #define DAC_REG_DHR_REGOFFSET_MASK_POSBIT0 0x0000000FUL /* Mask of data hold registers offset (DHR12Rx, DHR12Lx, DHR8Rx, ...) when shifted to position 0 */ #define DAC_REG_DORX_REGOFFSET_MASK_POSBIT0 0x00000001UL /* Mask of DORx registers offset when shifted @@ -473,7 +472,7 @@ typedef struct * @arg @ref LL_DAC_RESOLUTION_8B * @retval DAC conversion data (unit: digital value) */ -#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__, __DAC_VOLTAGE__, __DAC_RESOLUTION__) \ +#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__, __DAC_VOLTAGE__, __DAC_RESOLUTION__) \ ((__DAC_VOLTAGE__) * __LL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ / (__VREFANALOG_VOLTAGE__) \ ) diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_fsmc.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_fsmc.h index abd47886c..118137b52 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_fsmc.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_fsmc.h @@ -41,47 +41,47 @@ extern "C" { #if defined(FSMC_BANK1) #define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_NORSRAM_BANK1) || \ - ((__BANK__) == FSMC_NORSRAM_BANK2) || \ - ((__BANK__) == FSMC_NORSRAM_BANK3) || \ - ((__BANK__) == FSMC_NORSRAM_BANK4)) + ((__BANK__) == FSMC_NORSRAM_BANK2) || \ + ((__BANK__) == FSMC_NORSRAM_BANK3) || \ + ((__BANK__) == FSMC_NORSRAM_BANK4)) #define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ - ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) + ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) #define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ - ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ - ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) + ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ + ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) #define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ - ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ - ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) + ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ + ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) #define IS_FSMC_PAGESIZE(__SIZE__) (((__SIZE__) == FSMC_PAGE_SIZE_NONE) || \ - ((__SIZE__) == FSMC_PAGE_SIZE_128) || \ - ((__SIZE__) == FSMC_PAGE_SIZE_256) || \ - ((__SIZE__) == FSMC_PAGE_SIZE_512) || \ - ((__SIZE__) == FSMC_PAGE_SIZE_1024)) + ((__SIZE__) == FSMC_PAGE_SIZE_128) || \ + ((__SIZE__) == FSMC_PAGE_SIZE_256) || \ + ((__SIZE__) == FSMC_PAGE_SIZE_512) || \ + ((__SIZE__) == FSMC_PAGE_SIZE_1024)) #define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ - ((__MODE__) == FSMC_ACCESS_MODE_B) || \ - ((__MODE__) == FSMC_ACCESS_MODE_C) || \ - ((__MODE__) == FSMC_ACCESS_MODE_D)) + ((__MODE__) == FSMC_ACCESS_MODE_B) || \ + ((__MODE__) == FSMC_ACCESS_MODE_C) || \ + ((__MODE__) == FSMC_ACCESS_MODE_D)) #define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ - ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) + ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) #define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ - ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) + ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) #define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ - ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) + ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) #define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ - ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) + ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) #define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ - ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) + ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) #define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ - ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) + ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) #define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ - ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) + ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) #define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ - ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) + ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) #define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1U) && ((__LATENCY__) <= 17U)) #define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ - ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) + ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) #define IS_FSMC_CONTINOUS_CLOCK(__CCLOCK__) (((__CCLOCK__) == FSMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ - ((__CCLOCK__) == FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) + ((__CCLOCK__) == FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) #define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15U) #define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 15U)) #define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 255U)) @@ -96,18 +96,18 @@ extern "C" { #define IS_FSMC_NAND_BANK(__BANK__) ((__BANK__) == FSMC_NAND_BANK3) #define IS_FSMC_WAIT_FEATURE(__FEATURE__) (((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ - ((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) + ((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) #define IS_FSMC_NAND_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ - ((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) + ((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) #define IS_FSMC_ECC_STATE(__STATE__) (((__STATE__) == FSMC_NAND_ECC_DISABLE) || \ - ((__STATE__) == FSMC_NAND_ECC_ENABLE)) + ((__STATE__) == FSMC_NAND_ECC_ENABLE)) #define IS_FSMC_ECCPAGE_SIZE(__SIZE__) (((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) #define IS_FSMC_TCLR_TIME(__TIME__) ((__TIME__) <= 255U) #define IS_FSMC_TAR_TIME(__TIME__) ((__TIME__) <= 255U) #define IS_FSMC_SETUP_TIME(__TIME__) ((__TIME__) <= 254U) @@ -161,56 +161,57 @@ extern "C" { typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. - This parameter can be a value of @ref FSMC_NORSRAM_Bank */ + This parameter can be a value of @ref FSMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. - This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing */ + This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing*/ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. - This parameter can be a value of @ref FSMC_Memory_Type */ + This parameter can be a value of @ref FSMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. - This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ + This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. - This parameter can be a value of @ref FSMC_Burst_Access_Mode */ + This parameter can be a value of @ref FSMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. - This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ + This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. - This parameter can be a value of @ref FSMC_Wrap_Mode */ + This parameter can be a value of @ref FSMC_Wrap_Mode */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. - This parameter can be a value of @ref FSMC_Wait_Timing */ + This parameter can be a value of @ref FSMC_Wait_Timing */ - uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FSMC. - This parameter can be a value of @ref FSMC_Write_Operation */ + uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device + by the FSMC. + This parameter can be a value of @ref FSMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. - This parameter can be a value of @ref FSMC_Wait_Signal */ + This parameter can be a value of @ref FSMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. - This parameter can be a value of @ref FSMC_Extended_Mode */ + This parameter can be a value of @ref FSMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. - This parameter can be a value of @ref FSMC_AsynchronousWait */ + This parameter can be a value of @ref FSMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. - This parameter can be a value of @ref FSMC_Write_Burst */ + This parameter can be a value of @ref FSMC_Write_Burst */ uint32_t PageSize; /*!< Specifies the memory page size. - This parameter can be a value of @ref FSMC_Page_Size */ + This parameter can be a value of @ref FSMC_Page_Size */ } FSMC_NORSRAM_InitTypeDef; /** @@ -254,7 +255,7 @@ typedef struct in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. - This parameter can be a value of @ref FSMC_Access_Mode */ + This parameter can be a value of @ref FSMC_Access_Mode */ } FSMC_NORSRAM_TimingTypeDef; #endif /* FSMC_BANK1 */ @@ -338,7 +339,7 @@ typedef struct uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ -}FSMC_PCCARD_InitTypeDef; +} FSMC_PCCARD_InitTypeDef; #endif /* FSMC_BANK4 */ /** @@ -643,7 +644,7 @@ typedef struct * @retval None */ #define __FSMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)]\ - |= FSMC_BCRx_MBKEN) + |= FSMC_BCRx_MBKEN) /** * @brief Disable the NORSRAM device access. @@ -652,7 +653,7 @@ typedef struct * @retval None */ #define __FSMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)]\ - &= ~FSMC_BCRx_MBKEN) + &= ~FSMC_BCRx_MBKEN) /** * @} @@ -671,8 +672,9 @@ typedef struct * @param __BANK__ FSMC_NAND Bank * @retval None */ -#define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 |= FSMC_PCRx_PBKEN): \ - ((__INSTANCE__)->PCR3 |= FSMC_PCRx_PBKEN)) +#define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->PCR2 |= FSMC_PCRx_PBKEN) : \ + ((__INSTANCE__)->PCR3 |= FSMC_PCRx_PBKEN)) /** * @brief Disable the NAND device access. @@ -680,8 +682,9 @@ typedef struct * @param __BANK__ FSMC_NAND Bank * @retval None */ -#define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? CLEAR_BIT((__INSTANCE__)->PCR2, FSMC_PCRx_PBKEN): \ - CLEAR_BIT((__INSTANCE__)->PCR3, FSMC_PCRx_PBKEN)) +#define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + CLEAR_BIT((__INSTANCE__)->PCR2, FSMC_PCRx_PBKEN) : \ + CLEAR_BIT((__INSTANCE__)->PCR3, FSMC_PCRx_PBKEN)) /** * @} @@ -710,7 +713,7 @@ typedef struct * @} */ -#endif +#endif /* FSMC_BANK4 */ #if defined(FSMC_BANK3) /** @defgroup FSMC_LL_NAND_Interrupt FSMC NAND Interrupt * @brief macros to handle NAND interrupts @@ -728,8 +731,9 @@ typedef struct * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ -#define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 |= (__INTERRUPT__)): \ - ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) +#define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->SR2 |= (__INTERRUPT__)) : \ + ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) /** * @brief Disable the NAND device interrupt. @@ -742,8 +746,9 @@ typedef struct * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ -#define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)): \ - ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) +#define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)) : \ + ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) /** * @brief Get flag status of the NAND device. @@ -757,8 +762,9 @@ typedef struct * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ -#define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ - (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) +#define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)) : \ + (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) /** * @brief Clear flag status of the NAND device. @@ -772,8 +778,9 @@ typedef struct * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ -#define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__FLAG__)): \ - ((__INSTANCE__)->SR3 &= ~(__FLAG__))) +#define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->SR2 &= ~(__FLAG__)) : \ + ((__INSTANCE__)->SR3 &= ~(__FLAG__))) /** * @} @@ -839,7 +846,7 @@ typedef struct /** * @} */ -#endif +#endif /* FSMC_BANK4 */ /** * @} @@ -862,14 +869,14 @@ typedef struct * @{ */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_InitTypeDef *Init); + const FSMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeDef *Device, - FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, - uint32_t ExtendedMode); + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, + uint32_t ExtendedMode); HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); + FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); /** * @} */ @@ -894,11 +901,11 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Dev /** @defgroup FSMC_LL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions * @{ */ -HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init); +HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, const FSMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); /** * @} @@ -909,8 +916,8 @@ HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); */ HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank); -HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, - uint32_t Timeout); +HAL_StatusTypeDef FSMC_NAND_GetECC(const FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout); /** * @} */ @@ -926,13 +933,13 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, /** @defgroup FSMC_LL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions * @{ */ -HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init); +HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, const FSMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing); + const FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing); + const FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing); + const FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); /** * @} diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_iwdg.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_iwdg.h index ea718ecd9..5dce390ff 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_iwdg.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_iwdg.h @@ -207,7 +207,7 @@ __STATIC_INLINE void LL_IWDG_SetPrescaler(IWDG_TypeDef *IWDGx, uint32_t Prescale * @arg @ref LL_IWDG_PRESCALER_128 * @arg @ref LL_IWDG_PRESCALER_256 */ -__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->PR)); } @@ -230,7 +230,7 @@ __STATIC_INLINE void LL_IWDG_SetReloadCounter(IWDG_TypeDef *IWDGx, uint32_t Coun * @param IWDGx IWDG Instance * @retval Value between Min_Data=0 and Max_Data=0x0FFF */ -__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->RLR)); } @@ -249,7 +249,7 @@ __STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_PVU) == (IWDG_SR_PVU)) ? 1UL : 0UL); } @@ -260,7 +260,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_RVU) == (IWDG_SR_RVU)) ? 1UL : 0UL); } @@ -272,7 +272,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bits (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsReady(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsReady(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_PVU | IWDG_SR_RVU) == 0U) ? 1UL : 0UL); } diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_sdmmc.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_sdmmc.h index 0234caeed..704a7f02d 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_sdmmc.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_sdmmc.h @@ -300,10 +300,14 @@ typedef struct #define SDMMC_SINGLE_BUS_SUPPORT 0x00010000U #define SDMMC_CARD_LOCKED 0x02000000U -#ifndef SDMMC_DATATIMEOUT -#define SDMMC_DATATIMEOUT 0xFFFFFFFFU +#ifndef SDMMC_DATATIMEOUT /*Hardware Data Timeout (ms) */ +#define SDMMC_DATATIMEOUT ((uint32_t)0xFFFFFFFFU) #endif /* SDMMC_DATATIMEOUT */ +#ifndef SDMMC_SWDATATIMEOUT /*Software Data Timeout (ms) */ +#define SDMMC_SWDATATIMEOUT SDMMC_DATATIMEOUT +#endif /* SDMMC_SWDATATIMEOUT */ + #define SDMMC_0TO7BITS 0x000000FFU #define SDMMC_8TO15BITS 0x0000FF00U #define SDMMC_16TO23BITS 0x00FF0000U diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_spi.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_spi.h index 37e00b125..15bfc9af6 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_spi.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_spi.h @@ -55,53 +55,66 @@ typedef struct uint32_t TransferDirection; /*!< Specifies the SPI unidirectional or bidirectional data mode. This parameter can be a value of @ref SPI_LL_EC_TRANSFER_MODE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferDirection().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetTransferDirection().*/ uint32_t Mode; /*!< Specifies the SPI mode (Master/Slave). This parameter can be a value of @ref SPI_LL_EC_MODE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetMode().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetMode().*/ uint32_t DataWidth; /*!< Specifies the SPI data width. This parameter can be a value of @ref SPI_LL_EC_DATAWIDTH. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetDataWidth().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetDataWidth().*/ uint32_t ClockPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_LL_EC_POLARITY. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPolarity().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetClockPolarity().*/ uint32_t ClockPhase; /*!< Specifies the clock active edge for the bit capture. This parameter can be a value of @ref SPI_LL_EC_PHASE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPhase().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetClockPhase().*/ - uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) + or by software using the SSI bit. This parameter can be a value of @ref SPI_LL_EC_NSS_MODE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetNSSMode().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetNSSMode().*/ - uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used to configure the transmit and receive SCK clock. + uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used + to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_LL_EC_BAUDRATEPRESCALER. - @note The communication clock is derived from the master clock. The slave clock does not need to be set. + @note The communication clock is derived from the master clock. + The slave clock does not need to be set. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetBaudRatePrescaler().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetBaudRatePrescaler().*/ uint32_t BitOrder; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_LL_EC_BIT_ORDER. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferBitOrder().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetTransferBitOrder().*/ uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. This parameter can be a value of @ref SPI_LL_EC_CRC_CALCULATION. - This feature can be modified afterwards using unitary functions @ref LL_SPI_EnableCRC() and @ref LL_SPI_DisableCRC().*/ + This feature can be modified afterwards using unitary + functions @ref LL_SPI_EnableCRC() and @ref LL_SPI_DisableCRC().*/ uint32_t CRCPoly; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetCRCPolynomial().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetCRCPolynomial().*/ } LL_SPI_InitTypeDef; @@ -309,7 +322,7 @@ __STATIC_INLINE void LL_SPI_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_SPE) == (SPI_CR1_SPE)) ? 1UL : 0UL); } @@ -339,7 +352,7 @@ __STATIC_INLINE void LL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_SPI_MODE_MASTER * @arg @ref LL_SPI_MODE_SLAVE */ -__STATIC_INLINE uint32_t LL_SPI_GetMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI)); } @@ -369,7 +382,7 @@ __STATIC_INLINE void LL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase * @arg @ref LL_SPI_PHASE_1EDGE * @arg @ref LL_SPI_PHASE_2EDGE */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPHA)); } @@ -398,7 +411,7 @@ __STATIC_INLINE void LL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_SPI_POLARITY_LOW * @arg @ref LL_SPI_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPOL)); } @@ -438,7 +451,7 @@ __STATIC_INLINE void LL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t Bau * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 */ -__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_BR)); } @@ -466,7 +479,7 @@ __STATIC_INLINE void LL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitO * @arg @ref LL_SPI_LSB_FIRST * @arg @ref LL_SPI_MSB_FIRST */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_LSBFIRST)); } @@ -503,7 +516,7 @@ __STATIC_INLINE void LL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t Tra * @arg @ref LL_SPI_HALF_DUPLEX_RX * @arg @ref LL_SPI_HALF_DUPLEX_TX */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE)); } @@ -530,7 +543,7 @@ __STATIC_INLINE void LL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) * @arg @ref LL_SPI_DATAWIDTH_8BIT * @arg @ref LL_SPI_DATAWIDTH_16BIT */ -__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_DFF)); } @@ -574,7 +587,7 @@ __STATIC_INLINE void LL_SPI_DisableCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_CRCEN) == (SPI_CR1_CRCEN)) ? 1UL : 0UL); } @@ -609,7 +622,7 @@ __STATIC_INLINE void LL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->CRCPR)); } @@ -620,7 +633,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->RXCRCR)); } @@ -631,7 +644,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->TXCRCR)); } @@ -672,7 +685,7 @@ __STATIC_INLINE void LL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) * @arg @ref LL_SPI_NSS_HARD_INPUT * @arg @ref LL_SPI_NSS_HARD_OUTPUT */ -__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(const SPI_TypeDef *SPIx) { uint32_t Ssm = (READ_BIT(SPIx->CR1, SPI_CR1_SSM)); uint32_t Ssoe = (READ_BIT(SPIx->CR2, SPI_CR2_SSOE) << 16U); @@ -693,7 +706,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_RXNE) == (SPI_SR_RXNE)) ? 1UL : 0UL); } @@ -704,7 +717,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_TXE) == (SPI_SR_TXE)) ? 1UL : 0UL); } @@ -715,7 +728,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CRCERR) == (SPI_SR_CRCERR)) ? 1UL : 0UL); } @@ -726,7 +739,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_MODF) == (SPI_SR_MODF)) ? 1UL : 0UL); } @@ -737,7 +750,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_OVR) == (SPI_SR_OVR)) ? 1UL : 0UL); } @@ -755,7 +768,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_BSY) == (SPI_SR_BSY)) ? 1UL : 0UL); } @@ -829,7 +842,8 @@ __STATIC_INLINE void LL_SPI_ClearFlag_FRE(SPI_TypeDef *SPIx) /** * @brief Enable error interrupt - * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @note This bit controls the generation of an interrupt when an error condition + * occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). * @rmtoll CR2 ERRIE LL_SPI_EnableIT_ERR * @param SPIx SPI Instance * @retval None @@ -863,7 +877,8 @@ __STATIC_INLINE void LL_SPI_EnableIT_TXE(SPI_TypeDef *SPIx) /** * @brief Disable error interrupt - * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @note This bit controls the generation of an interrupt when an error condition + * occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). * @rmtoll CR2 ERRIE LL_SPI_DisableIT_ERR * @param SPIx SPI Instance * @retval None @@ -901,7 +916,7 @@ __STATIC_INLINE void LL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_ERRIE) == (SPI_CR2_ERRIE)) ? 1UL : 0UL); } @@ -912,7 +927,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXNEIE) == (SPI_CR2_RXNEIE)) ? 1UL : 0UL); } @@ -923,7 +938,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXEIE) == (SPI_CR2_TXEIE)) ? 1UL : 0UL); } @@ -964,7 +979,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXDMAEN) == (SPI_CR2_RXDMAEN)) ? 1UL : 0UL); } @@ -997,7 +1012,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXDMAEN) == (SPI_CR2_TXDMAEN)) ? 1UL : 0UL); } @@ -1008,7 +1023,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Address of data register */ -__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(const SPI_TypeDef *SPIx) { return (uint32_t) &(SPIx->DR); } @@ -1085,7 +1100,7 @@ __STATIC_INLINE void LL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct); void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct); @@ -1353,7 +1368,7 @@ __STATIC_INLINE void LL_I2S_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SE) == (SPI_I2SCFGR_I2SE)) ? 1UL : 0UL); } @@ -1386,7 +1401,7 @@ __STATIC_INLINE void LL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat * @arg @ref LL_I2S_DATAFORMAT_24B * @arg @ref LL_I2S_DATAFORMAT_32B */ -__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)); } @@ -1413,7 +1428,7 @@ __STATIC_INLINE void LL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_I2S_POLARITY_LOW * @arg @ref LL_I2S_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_CKPOL)); } @@ -1448,7 +1463,7 @@ __STATIC_INLINE void LL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_I2S_STANDARD_PCM_SHORT * @arg @ref LL_I2S_STANDARD_PCM_LONG */ -__STATIC_INLINE uint32_t LL_I2S_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC)); } @@ -1479,7 +1494,7 @@ __STATIC_INLINE void LL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_I2S_MODE_MASTER_TX * @arg @ref LL_I2S_MODE_MASTER_RX */ -__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG)); } @@ -1502,7 +1517,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t Presca * @param SPIx SPI Instance * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_I2SDIV)); } @@ -1529,7 +1544,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t Presc * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN * @arg @ref LL_I2S_PRESCALER_PARITY_ODD */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_ODD) >> 8U); } @@ -1562,7 +1577,7 @@ __STATIC_INLINE void LL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE) == (SPI_I2SPR_MCKOE)) ? 1UL : 0UL); } @@ -1581,7 +1596,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_RXNE(SPIx); } @@ -1592,7 +1607,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_TXE(SPIx); } @@ -1603,7 +1618,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_BSY(SPIx); } @@ -1614,7 +1629,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_OVR(SPIx); } @@ -1625,7 +1640,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_UDR) == (SPI_SR_UDR)) ? 1UL : 0UL); } @@ -1640,7 +1655,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CHSIDE) == (SPI_SR_CHSIDE)) ? 1UL : 0UL); } @@ -1762,7 +1777,7 @@ __STATIC_INLINE void LL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_ERR(SPIx); } @@ -1773,7 +1788,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_RXNE(SPIx); } @@ -1784,7 +1799,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_TXE(SPIx); } @@ -1825,7 +1840,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_RX(SPIx); } @@ -1858,7 +1873,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_TX(SPIx); } @@ -1903,7 +1918,7 @@ __STATIC_INLINE void LL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_tim.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_tim.h index f1bceb797..d54a00ead 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_tim.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_tim.h @@ -556,10 +556,10 @@ typedef struct /** @defgroup TIM_LL_EC_COUNTERMODE Counter Mode * @{ */ -#define LL_TIM_COUNTERMODE_UP 0x00000000U /*!CR2, TIM_CR2_CCPC); } +/** + * @brief Indicates whether the capture/compare control bits (CCxE, CCxNE and OCxM) preload is enabled. + * @rmtoll CR2 CCPC LL_TIM_CC_IsEnabledPreload + * @param TIMx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_TIM_CC_IsEnabledPreload(const TIM_TypeDef *TIMx) +{ + return ((READ_BIT(TIMx->CR2, TIM_CR2_CCPC) == (TIM_CR2_CCPC)) ? 1UL : 0UL); +} + /** * @brief Set the updated source of the capture/compare control bits (CCxE, CCxNE and OCxM). * @note Macro IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usart.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usart.h index ffe41927e..6d370619a 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usart.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usart.h @@ -347,7 +347,7 @@ typedef struct * @} */ -/** @defgroup USART_LL_EM_Exported_Macros_Helper Exported_Macros_Helper +/** @defgroup USART_LL_EM_Exported_Macros_Helper Exported Macros Helper * @{ */ @@ -636,7 +636,7 @@ __STATIC_INLINE uint32_t LL_USART_GetOverSampling(const USART_TypeDef *USARTx) #endif /* USART_OverSampling_Feature */ /** * @brief Configure if Clock pulse of the last data bit is output to the SCLK pin or not - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 LBCL LL_USART_SetLastClkPulseOutput * @param USARTx USART Instance @@ -653,7 +653,7 @@ __STATIC_INLINE void LL_USART_SetLastClkPulseOutput(USART_TypeDef *USARTx, uint3 /** * @brief Retrieve Clock pulse of the last data bit output configuration * (Last bit Clock pulse output to the SCLK pin or not) - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 LBCL LL_USART_GetLastClkPulseOutput * @param USARTx USART Instance @@ -668,7 +668,7 @@ __STATIC_INLINE uint32_t LL_USART_GetLastClkPulseOutput(const USART_TypeDef *USA /** * @brief Select the phase of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPHA LL_USART_SetClockPhase * @param USARTx USART Instance @@ -684,7 +684,7 @@ __STATIC_INLINE void LL_USART_SetClockPhase(USART_TypeDef *USARTx, uint32_t Cloc /** * @brief Return phase of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPHA LL_USART_GetClockPhase * @param USARTx USART Instance @@ -699,7 +699,7 @@ __STATIC_INLINE uint32_t LL_USART_GetClockPhase(const USART_TypeDef *USARTx) /** * @brief Select the polarity of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPOL LL_USART_SetClockPolarity * @param USARTx USART Instance @@ -715,7 +715,7 @@ __STATIC_INLINE void LL_USART_SetClockPolarity(USART_TypeDef *USARTx, uint32_t C /** * @brief Return polarity of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPOL LL_USART_GetClockPolarity * @param USARTx USART Instance @@ -730,7 +730,7 @@ __STATIC_INLINE uint32_t LL_USART_GetClockPolarity(const USART_TypeDef *USARTx) /** * @brief Configure Clock signal format (Phase Polarity and choice about output of last bit clock pulse) - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clock Phase configuration using @ref LL_USART_SetClockPhase() function @@ -758,7 +758,7 @@ __STATIC_INLINE void LL_USART_ConfigClock(USART_TypeDef *USARTx, uint32_t Phase, /** * @brief Enable Clock output on SCLK pin - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CLKEN LL_USART_EnableSCLKOutput * @param USARTx USART Instance @@ -771,7 +771,7 @@ __STATIC_INLINE void LL_USART_EnableSCLKOutput(USART_TypeDef *USARTx) /** * @brief Disable Clock output on SCLK pin - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CLKEN LL_USART_DisableSCLKOutput * @param USARTx USART Instance @@ -784,7 +784,7 @@ __STATIC_INLINE void LL_USART_DisableSCLKOutput(USART_TypeDef *USARTx) /** * @brief Indicate if Clock output on SCLK pin is enabled - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CLKEN LL_USART_IsEnabledSCLKOutput * @param USARTx USART Instance @@ -886,7 +886,7 @@ __STATIC_INLINE uint32_t LL_USART_GetNodeAddress(const USART_TypeDef *USARTx) /** * @brief Enable RTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_EnableRTSHWFlowCtrl * @param USARTx USART Instance @@ -899,7 +899,7 @@ __STATIC_INLINE void LL_USART_EnableRTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Disable RTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_DisableRTSHWFlowCtrl * @param USARTx USART Instance @@ -912,7 +912,7 @@ __STATIC_INLINE void LL_USART_DisableRTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Enable CTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSE LL_USART_EnableCTSHWFlowCtrl * @param USARTx USART Instance @@ -925,7 +925,7 @@ __STATIC_INLINE void LL_USART_EnableCTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Disable CTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSE LL_USART_DisableCTSHWFlowCtrl * @param USARTx USART Instance @@ -938,7 +938,7 @@ __STATIC_INLINE void LL_USART_DisableCTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Configure HW Flow Control mode (both CTS and RTS) - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_SetHWFlowCtrl\n * CR3 CTSE LL_USART_SetHWFlowCtrl @@ -957,7 +957,7 @@ __STATIC_INLINE void LL_USART_SetHWFlowCtrl(USART_TypeDef *USARTx, uint32_t Hard /** * @brief Return HW Flow Control configuration (both CTS and RTS) - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_GetHWFlowCtrl\n * CR3 CTSE LL_USART_GetHWFlowCtrl @@ -1125,7 +1125,7 @@ __STATIC_INLINE uint32_t LL_USART_GetBaudRate(const USART_TypeDef *USARTx, uint3 /** * @brief Enable IrDA mode - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IREN LL_USART_EnableIrda * @param USARTx USART Instance @@ -1138,7 +1138,7 @@ __STATIC_INLINE void LL_USART_EnableIrda(USART_TypeDef *USARTx) /** * @brief Disable IrDA mode - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IREN LL_USART_DisableIrda * @param USARTx USART Instance @@ -1151,7 +1151,7 @@ __STATIC_INLINE void LL_USART_DisableIrda(USART_TypeDef *USARTx) /** * @brief Indicate if IrDA mode is enabled - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IREN LL_USART_IsEnabledIrda * @param USARTx USART Instance @@ -1164,7 +1164,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledIrda(const USART_TypeDef *USARTx) /** * @brief Configure IrDA Power Mode (Normal or Low Power) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IRLP LL_USART_SetIrdaPowerMode * @param USARTx USART Instance @@ -1180,7 +1180,7 @@ __STATIC_INLINE void LL_USART_SetIrdaPowerMode(USART_TypeDef *USARTx, uint32_t P /** * @brief Retrieve IrDA Power Mode configuration (Normal or Low Power) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IRLP LL_USART_GetIrdaPowerMode * @param USARTx USART Instance @@ -1196,7 +1196,7 @@ __STATIC_INLINE uint32_t LL_USART_GetIrdaPowerMode(const USART_TypeDef *USARTx) /** * @brief Set Irda prescaler value, used for dividing the USART clock source * to achieve the Irda Low Power frequency (8 bits value) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_SetIrdaPrescaler * @param USARTx USART Instance @@ -1211,7 +1211,7 @@ __STATIC_INLINE void LL_USART_SetIrdaPrescaler(USART_TypeDef *USARTx, uint32_t P /** * @brief Return Irda prescaler value, used for dividing the USART clock source * to achieve the Irda Low Power frequency (8 bits value) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_GetIrdaPrescaler * @param USARTx USART Instance @@ -1232,7 +1232,7 @@ __STATIC_INLINE uint32_t LL_USART_GetIrdaPrescaler(const USART_TypeDef *USARTx) /** * @brief Enable Smartcard NACK transmission - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 NACK LL_USART_EnableSmartcardNACK * @param USARTx USART Instance @@ -1245,7 +1245,7 @@ __STATIC_INLINE void LL_USART_EnableSmartcardNACK(USART_TypeDef *USARTx) /** * @brief Disable Smartcard NACK transmission - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 NACK LL_USART_DisableSmartcardNACK * @param USARTx USART Instance @@ -1258,7 +1258,7 @@ __STATIC_INLINE void LL_USART_DisableSmartcardNACK(USART_TypeDef *USARTx) /** * @brief Indicate if Smartcard NACK transmission is enabled - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 NACK LL_USART_IsEnabledSmartcardNACK * @param USARTx USART Instance @@ -1271,7 +1271,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledSmartcardNACK(const USART_TypeDef *US /** * @brief Enable Smartcard mode - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 SCEN LL_USART_EnableSmartcard * @param USARTx USART Instance @@ -1284,7 +1284,7 @@ __STATIC_INLINE void LL_USART_EnableSmartcard(USART_TypeDef *USARTx) /** * @brief Disable Smartcard mode - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 SCEN LL_USART_DisableSmartcard * @param USARTx USART Instance @@ -1297,7 +1297,7 @@ __STATIC_INLINE void LL_USART_DisableSmartcard(USART_TypeDef *USARTx) /** * @brief Indicate if Smartcard mode is enabled - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 SCEN LL_USART_IsEnabledSmartcard * @param USARTx USART Instance @@ -1311,7 +1311,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledSmartcard(const USART_TypeDef *USARTx /** * @brief Set Smartcard prescaler value, used for dividing the USART clock * source to provide the SMARTCARD Clock (5 bits value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_SetSmartcardPrescaler * @param USARTx USART Instance @@ -1326,7 +1326,7 @@ __STATIC_INLINE void LL_USART_SetSmartcardPrescaler(USART_TypeDef *USARTx, uint3 /** * @brief Return Smartcard prescaler value, used for dividing the USART clock * source to provide the SMARTCARD Clock (5 bits value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_GetSmartcardPrescaler * @param USARTx USART Instance @@ -1340,7 +1340,7 @@ __STATIC_INLINE uint32_t LL_USART_GetSmartcardPrescaler(const USART_TypeDef *USA /** * @brief Set Smartcard Guard time value, expressed in nb of baud clocks periods * (GT[7:0] bits : Guard time value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR GT LL_USART_SetSmartcardGuardTime * @param USARTx USART Instance @@ -1355,7 +1355,7 @@ __STATIC_INLINE void LL_USART_SetSmartcardGuardTime(USART_TypeDef *USARTx, uint3 /** * @brief Return Smartcard Guard time value, expressed in nb of baud clocks periods * (GT[7:0] bits : Guard time value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR GT LL_USART_GetSmartcardGuardTime * @param USARTx USART Instance @@ -1376,7 +1376,7 @@ __STATIC_INLINE uint32_t LL_USART_GetSmartcardGuardTime(const USART_TypeDef *USA /** * @brief Enable Single Wire Half-Duplex mode - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @rmtoll CR3 HDSEL LL_USART_EnableHalfDuplex * @param USARTx USART Instance @@ -1389,7 +1389,7 @@ __STATIC_INLINE void LL_USART_EnableHalfDuplex(USART_TypeDef *USARTx) /** * @brief Disable Single Wire Half-Duplex mode - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @rmtoll CR3 HDSEL LL_USART_DisableHalfDuplex * @param USARTx USART Instance @@ -1402,7 +1402,7 @@ __STATIC_INLINE void LL_USART_DisableHalfDuplex(USART_TypeDef *USARTx) /** * @brief Indicate if Single Wire Half-Duplex mode is enabled - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @rmtoll CR3 HDSEL LL_USART_IsEnabledHalfDuplex * @param USARTx USART Instance @@ -1423,7 +1423,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledHalfDuplex(const USART_TypeDef *USART /** * @brief Set LIN Break Detection Length - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDL LL_USART_SetLINBrkDetectionLen * @param USARTx USART Instance @@ -1439,7 +1439,7 @@ __STATIC_INLINE void LL_USART_SetLINBrkDetectionLen(USART_TypeDef *USARTx, uint3 /** * @brief Return LIN Break Detection Length - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDL LL_USART_GetLINBrkDetectionLen * @param USARTx USART Instance @@ -1454,7 +1454,7 @@ __STATIC_INLINE uint32_t LL_USART_GetLINBrkDetectionLen(const USART_TypeDef *USA /** * @brief Enable LIN mode - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LINEN LL_USART_EnableLIN * @param USARTx USART Instance @@ -1467,7 +1467,7 @@ __STATIC_INLINE void LL_USART_EnableLIN(USART_TypeDef *USARTx) /** * @brief Disable LIN mode - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LINEN LL_USART_DisableLIN * @param USARTx USART Instance @@ -1480,7 +1480,7 @@ __STATIC_INLINE void LL_USART_DisableLIN(USART_TypeDef *USARTx) /** * @brief Indicate if LIN mode is enabled - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LINEN LL_USART_IsEnabledLIN * @param USARTx USART Instance @@ -1541,7 +1541,7 @@ __STATIC_INLINE void LL_USART_ConfigAsyncMode(USART_TypeDef *USARTx) * - IREN bit in the USART_CR3 register, * - HDSEL bit in the USART_CR3 register. * This function also sets the USART in Synchronous mode. - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1579,7 +1579,7 @@ __STATIC_INLINE void LL_USART_ConfigSyncMode(USART_TypeDef *USARTx) * - IREN bit in the USART_CR3 register, * - HDSEL bit in the USART_CR3 register. * This function also set the UART/USART in LIN mode. - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function @@ -1619,7 +1619,7 @@ __STATIC_INLINE void LL_USART_ConfigLINMode(USART_TypeDef *USARTx) * - SCEN bit in the USART_CR3 register, * - IREN bit in the USART_CR3 register, * This function also sets the UART/USART in Half Duplex mode. - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1658,7 +1658,7 @@ __STATIC_INLINE void LL_USART_ConfigHalfDuplexMode(USART_TypeDef *USARTx) * This function also configures Stop bits to 1.5 bits and * sets the USART in Smartcard mode (SCEN bit). * Clock Output is also enabled (CLKEN). - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1700,7 +1700,7 @@ __STATIC_INLINE void LL_USART_ConfigSmartcardMode(USART_TypeDef *USARTx) * - SCEN bit in the USART_CR3 register, * - HDSEL bit in the USART_CR3 register. * This function also sets the UART/USART in IRDA mode (IREN bit). - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1866,7 +1866,7 @@ __STATIC_INLINE uint32_t LL_USART_IsActiveFlag_TXE(const USART_TypeDef *USARTx) /** * @brief Check if the USART LIN Break Detection Flag is set or not - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll SR LBD LL_USART_IsActiveFlag_LBD * @param USARTx USART Instance @@ -1879,7 +1879,7 @@ __STATIC_INLINE uint32_t LL_USART_IsActiveFlag_LBD(const USART_TypeDef *USARTx) /** * @brief Check if the USART CTS Flag is set or not - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll SR CTS LL_USART_IsActiveFlag_nCTS * @param USARTx USART Instance @@ -2031,7 +2031,7 @@ __STATIC_INLINE void LL_USART_ClearFlag_RXNE(USART_TypeDef *USARTx) /** * @brief Clear LIN Break Detection Flag - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll SR LBD LL_USART_ClearFlag_LBD * @param USARTx USART Instance @@ -2044,7 +2044,7 @@ __STATIC_INLINE void LL_USART_ClearFlag_LBD(USART_TypeDef *USARTx) /** * @brief Clear CTS Interrupt Flag - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll SR CTS LL_USART_ClearFlag_nCTS * @param USARTx USART Instance @@ -2120,7 +2120,7 @@ __STATIC_INLINE void LL_USART_EnableIT_PE(USART_TypeDef *USARTx) /** * @brief Enable LIN Break Detection Interrupt - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDIE LL_USART_EnableIT_LBD * @param USARTx USART Instance @@ -2148,7 +2148,7 @@ __STATIC_INLINE void LL_USART_EnableIT_ERROR(USART_TypeDef *USARTx) /** * @brief Enable CTS Interrupt - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSIE LL_USART_EnableIT_CTS * @param USARTx USART Instance @@ -2216,7 +2216,7 @@ __STATIC_INLINE void LL_USART_DisableIT_PE(USART_TypeDef *USARTx) /** * @brief Disable LIN Break Detection Interrupt - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDIE LL_USART_DisableIT_LBD * @param USARTx USART Instance @@ -2244,7 +2244,7 @@ __STATIC_INLINE void LL_USART_DisableIT_ERROR(USART_TypeDef *USARTx) /** * @brief Disable CTS Interrupt - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSIE LL_USART_DisableIT_CTS * @param USARTx USART Instance @@ -2312,7 +2312,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledIT_PE(const USART_TypeDef *USARTx) /** * @brief Check if the USART LIN Break Detection Interrupt is enabled or disabled. - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDIE LL_USART_IsEnabledIT_LBD * @param USARTx USART Instance @@ -2336,7 +2336,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledIT_ERROR(const USART_TypeDef *USARTx) /** * @brief Check if the USART CTS Interrupt is enabled or disabled. - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSIE LL_USART_IsEnabledIT_CTS * @param USARTx USART Instance diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usb.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usb.h index c3a548eef..f0e13e80c 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usb.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_usb.h @@ -37,6 +37,13 @@ extern "C" { */ /* Exported types ------------------------------------------------------------*/ +#ifndef HAL_USB_TIMEOUT +#define HAL_USB_TIMEOUT 0xF000000U +#endif /* define HAL_USB_TIMEOUT */ + +#ifndef HAL_USB_CURRENT_MODE_MAX_DELAY_MS +#define HAL_USB_CURRENT_MODE_MAX_DELAY_MS 200U +#endif /* define HAL_USB_CURRENT_MODE_MAX_DELAY_MS */ /** * @brief USB Mode definition @@ -85,42 +92,42 @@ typedef enum */ typedef struct { - uint32_t dev_endpoints; /*!< Device Endpoints number. + uint8_t dev_endpoints; /*!< Device Endpoints number. This parameter depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ #if defined (USB_OTG_FS) - uint32_t Host_channels; /*!< Host Channels number. + uint8_t Host_channels; /*!< Host Channels number. This parameter Depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ +#endif /* defined (USB_OTG_FS) */ - uint32_t dma_enable; /*!< USB DMA state. + uint8_t dma_enable; /*!< USB DMA state. If DMA is not supported this parameter shall be set by default to zero */ -#endif /* defined (USB_OTG_FS) */ - uint32_t speed; /*!< USB Core speed. - This parameter can be any value of @ref PCD_Speed/HCD_Speed - (HCD_SPEED_xxx, HCD_SPEED_xxx) */ + uint8_t speed; /*!< USB Core speed. + This parameter can be any value of @ref PCD_Speed/HCD_Speed + (HCD_SPEED_xxx, HCD_SPEED_xxx) */ - uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */ + uint8_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */ - uint32_t phy_itface; /*!< Select the used PHY interface. - This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */ + uint8_t phy_itface; /*!< Select the used PHY interface. + This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */ - uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ + uint8_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ - uint32_t low_power_enable; /*!< Enable or disable the low Power Mode. */ + uint8_t low_power_enable; /*!< Enable or disable the low Power Mode. */ - uint32_t lpm_enable; /*!< Enable or disable Link Power Management. */ + uint8_t lpm_enable; /*!< Enable or disable Link Power Management. */ - uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */ + uint8_t battery_charging_enable; /*!< Enable or disable Battery charging. */ #if defined (USB_OTG_FS) - uint32_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ + uint8_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ - uint32_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ + uint8_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ - uint32_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ + uint8_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ #endif /* defined (USB_OTG_FS) */ } USB_CfgTypeDef; @@ -513,41 +520,41 @@ HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_SetTurnaroundTime(USB_OTG_GlobalTypeDef *USBx, uint32_t hclk, uint8_t speed); HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_ModeTypeDef mode); -HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed); +HAL_StatusTypeDef USB_SetDevSpeed(const USB_OTG_GlobalTypeDef *USBx, uint8_t speed); HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num); -HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_ActivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_DeactivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, +HAL_StatusTypeDef USB_WritePacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len); -void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); -HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address); -HAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_DevDisconnect(USB_OTG_GlobalTypeDef *USBx); +void *USB_ReadPacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); +HAL_StatusTypeDef USB_EPSetStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPClearStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPStopXfer(const USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_SetDevAddress(const USB_OTG_GlobalTypeDef *USBx, uint8_t address); +HAL_StatusTypeDef USB_DevConnect(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_DevDisconnect(const USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t *psetup); -uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx); -uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_ActivateSetup(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_EP0_OutStart(const USB_OTG_GlobalTypeDef *USBx, const uint8_t *psetup); +uint8_t USB_GetDevSpeed(const USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_GetMode(const USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef const *USBx); -uint32_t USB_ReadChInterrupts(USB_OTG_GlobalTypeDef *USBx, uint8_t chnum); -uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx); -uint32_t USB_ReadDevOutEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); -uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx); -uint32_t USB_ReadDevInEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); +uint32_t USB_ReadChInterrupts(const USB_OTG_GlobalTypeDef *USBx, uint8_t chnum); +uint32_t USB_ReadDevAllOutEpInterrupt(const USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevOutEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); +uint32_t USB_ReadDevAllInEpInterrupt(const USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevInEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); void USB_ClearInterrupts(USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt); HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); -HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq); -HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_DriveVbus(USB_OTG_GlobalTypeDef *USBx, uint8_t state); +HAL_StatusTypeDef USB_InitFSLSPClkSel(const USB_OTG_GlobalTypeDef *USBx, uint8_t freq); +HAL_StatusTypeDef USB_ResetPort(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_DriveVbus(const USB_OTG_GlobalTypeDef *USBx, uint8_t state); uint32_t USB_GetHostSpeed(USB_OTG_GlobalTypeDef const *USBx); uint32_t USB_GetCurrentFrame(USB_OTG_GlobalTypeDef const *USBx); HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, @@ -556,12 +563,12 @@ HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc); -uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num); -HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num); +uint32_t USB_HC_ReadInterrupt(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_HC_Halt(const USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num); +HAL_StatusTypeDef USB_DoPing(const USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num); HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_ActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx); #endif /* defined (USB_OTG_FS) */ #if defined (USB) diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_utils.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_utils.h index d938fa364..69483bda0 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_utils.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_utils.h @@ -212,7 +212,7 @@ __STATIC_INLINE uint32_t LL_GetFlashSize(void) * @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCC helper macro) * @note When a RTOS is used, it is recommended to avoid changing the SysTick * configuration by calling this function, for a delay use rather osDelay RTOS service. - * @param Ticks Number of ticks + * @param Ticks Frequency of Ticks (Hz) * @retval None */ __STATIC_INLINE void LL_InitTick(uint32_t HCLKFrequency, uint32_t Ticks) diff --git a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_wwdg.h b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_wwdg.h index 6f9e1b703..565d18c5a 100644 --- a/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_wwdg.h +++ b/stm32cube/stm32f1xx/drivers/include/stm32f1xx_ll_wwdg.h @@ -131,7 +131,7 @@ __STATIC_INLINE void LL_WWDG_Enable(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->CR, WWDG_CR_WDGA) == (WWDG_CR_WDGA)) ? 1UL : 0UL); } @@ -158,7 +158,7 @@ __STATIC_INLINE void LL_WWDG_SetCounter(WWDG_TypeDef *WWDGx, uint32_t Counter) * @param WWDGx WWDG Instance * @retval 7 bit Watchdog Counter value */ -__STATIC_INLINE uint32_t LL_WWDG_GetCounter(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetCounter(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CR, WWDG_CR_T)); } @@ -191,7 +191,7 @@ __STATIC_INLINE void LL_WWDG_SetPrescaler(WWDG_TypeDef *WWDGx, uint32_t Prescale * @arg @ref LL_WWDG_PRESCALER_4 * @arg @ref LL_WWDG_PRESCALER_8 */ -__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CFR, WWDG_CFR_WDGTB)); } @@ -223,7 +223,7 @@ __STATIC_INLINE void LL_WWDG_SetWindow(WWDG_TypeDef *WWDGx, uint32_t Window) * @param WWDGx WWDG Instance * @retval 7 bit Watchdog Window value */ -__STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetWindow(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CFR, WWDG_CFR_W)); } @@ -244,7 +244,7 @@ __STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->SR, WWDG_SR_EWIF) == (WWDG_SR_EWIF)) ? 1UL : 0UL); } @@ -286,7 +286,7 @@ __STATIC_INLINE void LL_WWDG_EnableIT_EWKUP(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->CFR, WWDG_CFR_EWI) == (WWDG_CFR_EWI)) ? 1UL : 0UL); } diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal.c index 6756fb445..688e2becb 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal.c @@ -57,7 +57,7 @@ */ #define __STM32F1xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ #define __STM32F1xx_HAL_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */ -#define __STM32F1xx_HAL_VERSION_SUB2 (0x09U) /*!< [15:8] sub2 version */ +#define __STM32F1xx_HAL_VERSION_SUB2 (0x0AU) /*!< [15:8] sub2 version */ #define __STM32F1xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32F1xx_HAL_VERSION ((__STM32F1xx_HAL_VERSION_MAIN << 24)\ |(__STM32F1xx_HAL_VERSION_SUB1 << 16)\ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_can.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_can.c index b143ac869..207d19646 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_can.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_can.c @@ -33,7 +33,7 @@ (++) Enable the CAN interface clock using __HAL_RCC_CANx_CLK_ENABLE() (++) Configure CAN pins (+++) Enable the clock for the CAN GPIOs - (+++) Configure CAN pins as alternate function open-drain + (+++) Configure CAN pins as alternate function (++) In case of using interrupts (e.g. HAL_CAN_ActivateNotification()) (+++) Configure the CAN interrupt priority using HAL_NVIC_SetPriority() @@ -235,6 +235,7 @@ * @{ */ #define CAN_TIMEOUT_VALUE 10U +#define CAN_WAKEUP_TIMEOUT_COUNTER 1000000U /** * @} */ @@ -248,8 +249,8 @@ */ /** @defgroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim ============================================================================== ##### Initialization and de-initialization functions ##### @@ -328,7 +329,7 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef *hcan) /* Init the low level hardware: CLOCK, NVIC */ HAL_CAN_MspInit(hcan); } -#endif /* (USE_HAL_CAN_REGISTER_CALLBACKS) */ +#endif /* USE_HAL_CAN_REGISTER_CALLBACKS */ /* Request initialisation */ SET_BIT(hcan->Instance->MCR, CAN_MCR_INRQ); @@ -482,7 +483,7 @@ HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef *hcan) #else /* DeInit the low level hardware: CLOCK, NVIC */ HAL_CAN_MspDeInit(hcan); -#endif /* (USE_HAL_CAN_REGISTER_CALLBACKS) */ +#endif /* USE_HAL_CAN_REGISTER_CALLBACKS */ /* Reset the CAN peripheral */ SET_BIT(hcan->Instance->MCR, CAN_MCR_RESET); @@ -814,8 +815,8 @@ HAL_StatusTypeDef HAL_CAN_UnRegisterCallback(CAN_HandleTypeDef *hcan, HAL_CAN_Ca */ /** @defgroup CAN_Exported_Functions_Group2 Configuration functions - * @brief Configuration functions. - * + * @brief Configuration functions. + * @verbatim ============================================================================== ##### Configuration functions ##### @@ -868,7 +869,7 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, const CAN_Filter /* Check the parameters */ assert_param(IS_CAN_FILTER_BANK_SINGLE(sFilterConfig->FilterBank)); -#endif +#endif /* CAN3 */ /* Initialisation mode for the filter */ SET_BIT(can_ip->FMR, CAN_FMR_FINIT); @@ -878,7 +879,7 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, const CAN_Filter CLEAR_BIT(can_ip->FMR, CAN_FMR_CAN2SB); SET_BIT(can_ip->FMR, sFilterConfig->SlaveStartFilterBank << CAN_FMR_CAN2SB_Pos); -#endif +#endif /* CAN3 */ /* Convert filter number into bit position */ filternbrbitpos = (uint32_t)1 << (sFilterConfig->FilterBank & 0x1FU); @@ -970,8 +971,8 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, const CAN_Filter */ /** @defgroup CAN_Exported_Functions_Group3 Control functions - * @brief Control functions - * + * @brief Control functions + * @verbatim ============================================================================== ##### Control functions ##### @@ -1143,7 +1144,6 @@ HAL_StatusTypeDef HAL_CAN_RequestSleep(CAN_HandleTypeDef *hcan) HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan) { __IO uint32_t count = 0; - uint32_t timeout = 1000000U; HAL_CAN_StateTypeDef state = hcan->State; if ((state == HAL_CAN_STATE_READY) || @@ -1159,15 +1159,14 @@ HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan) count++; /* Check if timeout is reached */ - if (count > timeout) + if (count > CAN_WAKEUP_TIMEOUT_COUNTER) { /* Update error code */ hcan->ErrorCode |= HAL_CAN_ERROR_TIMEOUT; return HAL_ERROR; } - } - while ((hcan->Instance->MSR & CAN_MSR_SLAK) != 0U); + } while ((hcan->Instance->MSR & CAN_MSR_SLAK) != 0U); /* Return function status */ return HAL_OK; @@ -1608,8 +1607,8 @@ uint32_t HAL_CAN_GetRxFifoFillLevel(const CAN_HandleTypeDef *hcan, uint32_t RxFi */ /** @defgroup CAN_Exported_Functions_Group4 Interrupts management - * @brief Interrupts management - * + * @brief Interrupts management + * @verbatim ============================================================================== ##### Interrupts management ##### @@ -2074,8 +2073,8 @@ void HAL_CAN_IRQHandler(CAN_HandleTypeDef *hcan) */ /** @defgroup CAN_Exported_Functions_Group5 Callback functions - * @brief CAN Callback functions - * + * @brief CAN Callback functions + * @verbatim ============================================================================== ##### Callback functions ##### @@ -2324,8 +2323,8 @@ __weak void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) */ /** @defgroup CAN_Exported_Functions_Group6 Peripheral State and Error functions - * @brief CAN Peripheral State functions - * + * @brief CAN Peripheral State functions + * @verbatim ============================================================================== ##### Peripheral State and Error functions ##### diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cec.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cec.c index c0a173dfb..e2c9ffdfe 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cec.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cec.c @@ -924,7 +924,7 @@ static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec) hcec->TxXferCount--; /* Write data to TX buffer*/ - hcec->Instance->TXD = (uint8_t)*hcec->pTxBuffPtr++; + hcec->Instance->TXD = (uint8_t) * hcec->pTxBuffPtr++; /* If this is the last byte of the ongoing transmission */ if (hcec->TxXferCount == 0U) diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cortex.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cortex.c index d5ee73b8f..35cd222f9 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cortex.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_cortex.c @@ -290,6 +290,38 @@ void HAL_MPU_Enable(uint32_t MPU_Control) __ISB(); } +/** + * @brief Enable the MPU Region. + * @retval None + */ +void HAL_MPU_EnableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Enable the Region */ + SET_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @brief Disable the MPU Region. + * @retval None + */ +void HAL_MPU_DisableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + /** * @brief Initializes and configures the Region and the memory to be protected. * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains @@ -301,38 +333,32 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); + assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); + assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); + assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); + assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); + assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); + assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); + assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); + assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; - if ((MPU_Init->Enable) != RESET) - { - /* Check the parameters */ - assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); - assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); - assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); - assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); - assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); - assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); - assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); - assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); - - MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | - ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | - ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | - ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | - ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | - ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | - ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | - ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | - ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); - } - else - { - MPU->RBAR = 0x00U; - MPU->RASR = 0x00U; - } + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); + + /* Apply configuration */ + MPU->RBAR = MPU_Init->BaseAddress; + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | + ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | + ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | + ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | + ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | + ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | + ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } #endif /* __MPU_PRESENT */ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac.c index c890cade2..2e86c4abd 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac.c @@ -959,10 +959,7 @@ uint32_t HAL_DAC_GetValue(const DAC_HandleTypeDef *hdac, uint32_t Channel) uint32_t result; /* Check the DAC peripheral handle */ - if (hdac == NULL) - { - return HAL_ERROR; - } + assert_param(hdac != NULL); /* Check the parameters */ assert_param(IS_DAC_CHANNEL(Channel)); diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac_ex.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac_ex.c index 3c4fbb8fc..87a718471 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac_ex.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_dac_ex.c @@ -387,7 +387,6 @@ __weak void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac) } - /** * @} */ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash.c index 1801cae74..f71d2a765 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash.c @@ -266,9 +266,6 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u { HAL_StatusTypeDef status = HAL_OK; - /* Process Locked */ - __HAL_LOCK(&pFlash); - /* Check the parameters */ assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); assert_param(IS_FLASH_PROGRAM_ADDRESS(Address)); @@ -587,8 +584,6 @@ void HAL_FLASH_IRQHandler(void) __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP | FLASH_IT_ERR); #endif /* FLASH_BANK2_END */ - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); } } diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash_ex.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash_ex.c index 6c818a4c5..a836cfe4c 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash_ex.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_flash_ex.c @@ -318,9 +318,6 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit) { HAL_StatusTypeDef status = HAL_OK; - /* Process Locked */ - __HAL_LOCK(&pFlash); - /* If procedure already ongoing, reject the next one */ if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE) { diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_gpio.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_gpio.c index d994cf02d..ec5e3791d 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_gpio.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_gpio.c @@ -505,7 +505,7 @@ void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) * the next reset. * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral * @param GPIO_Pin: specifies the port bit to be locked. -* This parameter can be any combination of GPIO_Pin_x where x can be (0..15). +* This parameter can be any combination of GPIO_PIN_x where x can be (0..15). * @retval None */ HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_hcd.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_hcd.c index 67c86af92..5e9d53161 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_hcd.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_hcd.c @@ -106,8 +106,6 @@ static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd); */ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) { - USB_OTG_GlobalTypeDef *USBx; - /* Check the HCD handle allocation */ if (hhcd == NULL) { @@ -117,8 +115,6 @@ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) /* Check the parameters */ assert_param(IS_HCD_ALL_INSTANCE(hhcd->Instance)); - USBx = hhcd->Instance; - if (hhcd->State == HAL_HCD_STATE_RESET) { /* Allocate lock resource and initialize it */ @@ -148,22 +144,31 @@ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) hhcd->State = HAL_HCD_STATE_BUSY; /* Disable DMA mode for FS instance */ - if ((USBx->CID & (0x1U << 8)) == 0U) - { - hhcd->Init.dma_enable = 0U; - } + hhcd->Init.dma_enable = 0U; /* Disable the Interrupts */ __HAL_HCD_DISABLE(hhcd); /* Init the Core (common init.) */ - (void)USB_CoreInit(hhcd->Instance, hhcd->Init); + if (USB_CoreInit(hhcd->Instance, hhcd->Init) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } - /* Force Host Mode*/ - (void)USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE); + /* Force Host Mode */ + if (USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } /* Init Host */ - (void)USB_HostInit(hhcd->Instance, hhcd->Init); + if (USB_HostInit(hhcd->Instance, hhcd->Init) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } hhcd->State = HAL_HCD_STATE_READY; @@ -1212,7 +1217,7 @@ HAL_StatusTypeDef HAL_HCD_HC_ClearHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_nu */ static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1428,7 +1433,7 @@ static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) */ static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; uint32_t num_packets; @@ -1569,7 +1574,7 @@ static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) */ static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; uint32_t pktsts; uint32_t pktcnt; @@ -1635,7 +1640,7 @@ static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) */ static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; __IO uint32_t hprt0; __IO uint32_t hprt0_dup; diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2c.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2c.c index 0651e867a..00287cb8a 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2c.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2c.c @@ -89,7 +89,7 @@ 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() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() @@ -139,7 +139,7 @@ or using HAL_I2C_Master_Seq_Receive_DMA() (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() HAL_I2C_DisableListen_IT() @@ -193,7 +193,7 @@ 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() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() @@ -2937,6 +2937,11 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { + if (hi2c->XferSize == 3U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); + } /* Read data from DR */ *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; @@ -4810,7 +4815,7 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) } /** - * @brief Abort a master I2C IT or DMA process communication with Interrupt. + * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress Target device address: The device 7 bits address value @@ -4826,7 +4831,8 @@ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevA UNUSED(DevAddress); /* Abort Master transfer during Receive or Transmit process */ - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && (CurrentMode == HAL_I2C_MODE_MASTER)) + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && ((CurrentMode == HAL_I2C_MODE_MASTER) || + (CurrentMode == HAL_I2C_MODE_MEM))) { /* Process Locked */ __HAL_LOCK(hi2c); @@ -5621,7 +5627,9 @@ static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { uint32_t tmp; + uint32_t CurrentXferOptions; + CurrentXferOptions = hi2c->XferOptions; tmp = hi2c->XferCount; if (tmp > 3U) { @@ -5677,7 +5685,14 @@ static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) else { hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) hi2c->MasterRxCpltCallback(hi2c); @@ -5780,15 +5795,11 @@ static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) /* Enable Acknowledge */ SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); } - else if (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP) + else { /* Generate Stop */ SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); } - else - { - /* Do nothing */ - } /* Read data from DR */ *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; @@ -5825,7 +5836,14 @@ static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) else { hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) hi2c->MasterRxCpltCallback(hi2c); #else @@ -7136,7 +7154,14 @@ static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma) else { hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) hi2c->MasterRxCpltCallback(hi2c); diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2s.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2s.c index 0ae903eec..9aaa18acb 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2s.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_i2s.c @@ -777,15 +777,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uin return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -896,15 +895,14 @@ HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -994,15 +992,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1021,6 +1018,8 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, hi2s->TxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable TXE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); @@ -1031,7 +1030,6 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1060,15 +1058,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1087,6 +1084,8 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u hi2s->RxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable RXNE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); @@ -1097,7 +1096,6 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1124,15 +1122,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1174,12 +1171,7 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Tx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_TXDMAEN)) @@ -1188,7 +1180,13 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } @@ -1215,15 +1213,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1271,12 +1268,7 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Rx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_RXDMAEN)) @@ -1285,7 +1277,13 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_iwdg.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_iwdg.c index c65b792c9..1d61feb9b 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_iwdg.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_iwdg.c @@ -120,7 +120,8 @@ The timeout value is multiplied by 1000 to be converted in milliseconds. LSI startup time is also considered here by adding LSI_STARTUP_TIME converted in milliseconds. */ -#define HAL_IWDG_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) +#define HAL_IWDG_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / (LSI_VALUE / 128U)) + \ + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) #define IWDG_KERNEL_UPDATE_FLAGS (IWDG_SR_RVU | IWDG_SR_PVU) /** * @} diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_mmc.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_mmc.c index 68cf226a2..4dd65562e 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_mmc.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_mmc.c @@ -2328,7 +2328,7 @@ HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32 if(errorstate != HAL_MMC_ERROR_NONE) { /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); hmmc->ErrorCode |= errorstate; return HAL_ERROR; } diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_nand.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_nand.c index 88930cad3..c536e2118 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_nand.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_nand.c @@ -507,7 +507,7 @@ HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand) * @param pDeviceConfig pointer to NAND_DeviceConfigTypeDef structure * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig) +HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, const NAND_DeviceConfigTypeDef *pDeviceConfig) { hnand->Config.PageSize = pDeviceConfig->PageSize; hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize; @@ -2037,6 +2037,7 @@ HAL_StatusTypeDef HAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_ status = HAL_ERROR; } + return status; } /** @@ -2095,6 +2096,7 @@ HAL_StatusTypeDef HAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAN status = HAL_ERROR; } + return status; } #endif /* USE_HAL_NAND_REGISTER_CALLBACKS */ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pccard.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pccard.c index ec246b445..49e9b59ee 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pccard.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pccard.c @@ -163,7 +163,8 @@ * @retval HAL status */ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FSMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, - FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming) + FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, + FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming) { /* Check the PCCARD controller state */ if (hpccard == NULL) @@ -187,7 +188,7 @@ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FSMC_NAND_PCC_T #else /* Initialize the low level hardware (MSP) */ HAL_PCCARD_MspInit(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ } /* Initialize the PCCARD state */ @@ -234,7 +235,7 @@ HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard) #else /* De-Initialize the low level hardware (MSP) */ HAL_PCCARD_MspDeInit(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Configure the PCCARD registers with their reset values */ FSMC_PCCARD_DeInit(hpccard->Instance); @@ -307,8 +308,9 @@ __weak void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard) */ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_ID, index = 0U; - uint8_t status = 0; + uint32_t timeout = 0U; + uint32_t index = 0U; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -371,8 +373,9 @@ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t Comp HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR, index = 0U; - uint8_t status = 0; + uint32_t timeout = 0U; + uint32_t index = 0U; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -448,8 +451,9 @@ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR, index = 0U; - uint8_t status = 0; + uint32_t timeout = 0U; + uint32_t index = 0U; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -522,7 +526,7 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ HAL_StatusTypeDef HAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus) { uint32_t timeout = PCCARD_TIMEOUT_ERASE_SECTOR; - uint8_t status = 0; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -624,7 +628,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt Rising edge pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_RISING_EDGE); @@ -638,7 +642,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt Level pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_LEVEL); @@ -652,7 +656,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt Falling edge pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_FALLING_EDGE); @@ -666,7 +670,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt FIFO empty pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_FEMPT); @@ -823,7 +827,7 @@ HAL_StatusTypeDef HAL_PCCARD_UnRegisterCallback(PCCARD_HandleTypeDef *hpccard, H __HAL_UNLOCK(hpccard); return status; } -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} @@ -866,7 +870,8 @@ HAL_PCCARD_StateTypeDef HAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard) */ HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) { - uint32_t timeout = PCCARD_TIMEOUT_STATUS, status_pccard = 0U; + uint32_t timeout = PCCARD_TIMEOUT_STATUS; + uint32_t status_pccard = 0U; /* Check the PCCARD controller state */ if (hpccard->State == HAL_PCCARD_STATE_BUSY) @@ -902,7 +907,8 @@ HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) */ HAL_PCCARD_StatusTypeDef HAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard) { - uint8_t data = 0U, status_pccard = PCCARD_BUSY; + uint8_t data = 0U; + uint8_t status_pccard = PCCARD_BUSY; /* Check the PCCARD controller state */ if (hpccard->State == HAL_PCCARD_STATE_BUSY) diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pcd.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pcd.c index e01efe5ed..6a897389f 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pcd.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_pcd.c @@ -130,9 +130,6 @@ static uint16_t HAL_PCD_EP_DB_Receive(PCD_HandleTypeDef *hpcd, PCD_EPTypeDef *ep */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) { -#if defined (USB_OTG_FS) - USB_OTG_GlobalTypeDef *USBx; -#endif /* defined (USB_OTG_FS) */ uint8_t i; /* Check the PCD handle allocation */ @@ -144,10 +141,6 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) /* Check the parameters */ assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); -#if defined (USB_OTG_FS) - USBx = hpcd->Instance; -#endif /* defined (USB_OTG_FS) */ - if (hpcd->State == HAL_PCD_STATE_RESET) { /* Allocate lock resource and initialize it */ @@ -181,13 +174,8 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) hpcd->State = HAL_PCD_STATE_BUSY; -#if defined (USB_OTG_FS) /* Disable DMA mode for FS instance */ - if ((USBx->CID & (0x1U << 8)) == 0U) - { - hpcd->Init.dma_enable = 0U; - } -#endif /* defined (USB_OTG_FS) */ + hpcd->Init.dma_enable = 0U; /* Disable the Interrupts */ __HAL_PCD_DISABLE(hpcd); @@ -199,8 +187,12 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) return HAL_ERROR; } - /* Force Device Mode*/ - (void)USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE); + /* Force Device Mode */ + if (USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE) != HAL_OK) + { + hpcd->State = HAL_PCD_STATE_ERROR; + return HAL_ERROR; + } /* Init endpoints structures */ for (i = 0U; i < hpcd->Init.dev_endpoints; i++) @@ -2115,9 +2107,9 @@ static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t */ static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) { - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->CID + 0x1U); + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; if (gSNPSiD == USB_OTG_CORE_ID_310A) @@ -2162,9 +2154,9 @@ static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint */ static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) { - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->CID + 0x1U); + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; if ((gSNPSiD > USB_OTG_CORE_ID_300A) && diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sd.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sd.c index db94d3b50..8713b9f2a 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sd.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sd.c @@ -403,7 +403,6 @@ HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd) HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) { uint32_t errorstate; - HAL_StatusTypeDef status; SD_InitTypeDef Init; /* Default SDIO peripheral configuration for SD card initialization */ @@ -415,11 +414,7 @@ HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) Init.ClockDiv = SDIO_INIT_CLK_DIV; /* Initialize SDIO peripheral interface with default configuration */ - status = SDIO_Init(hsd->Instance, Init); - if(status != HAL_OK) - { - return HAL_ERROR; - } + SDIO_Init(hsd->Instance, Init); /* Disable SDIO Clock */ __HAL_SD_DISABLE(hsd); @@ -692,7 +687,7 @@ HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint3 } /* Get error state */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { /* Clear all the static flags */ __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); @@ -903,7 +898,7 @@ HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint } /* Get error state */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { /* Clear all the static flags */ __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); @@ -2864,13 +2859,13 @@ static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) } } - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + if((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) { return HAL_SD_ERROR_TIMEOUT; } } - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { return HAL_SD_ERROR_DATA_TIMEOUT; } @@ -2892,7 +2887,7 @@ static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) *pData = SDIO_ReadFIFO(hsd->Instance); pData++; - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + if((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) { return HAL_SD_ERROR_TIMEOUT; } @@ -3084,13 +3079,13 @@ static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) break; } - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + if((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) { return HAL_SD_ERROR_TIMEOUT; } } - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_spi.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_spi.c index 634cdd0df..16c9c9350 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_spi.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_spi.c @@ -44,7 +44,8 @@ (+++) Configure the DMA handle parameters (+++) Configure the DMA Tx or Rx Stream/Channel (+++) Associate the initialized hdma_tx(or _rx) 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/Channel + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx + or Rx Stream/Channel (#) Program the Mode, BidirectionalMode , Data size, Baudrate Prescaler, NSS management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure. @@ -190,7 +191,8 @@ @note The max SPI frequency depend on SPI data size (8bits, 16bits), SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA). @note - (#) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and HAL_SPI_TransmitReceive_DMA() + (#) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and + HAL_SPI_TransmitReceive_DMA() (#) RX processes are HAL_SPI_Receive(), HAL_SPI_Receive_IT() and HAL_SPI_Receive_DMA() (#) TX processes are HAL_SPI_Transmit(), HAL_SPI_Transmit_IT() and HAL_SPI_Transmit_DMA() @@ -790,38 +792,35 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @param Timeout Timeout duration * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; uint16_t initial_TxXferCount; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); initial_TxXferCount = Size; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -860,7 +859,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -870,7 +869,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -879,9 +878,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -891,7 +890,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; } @@ -900,7 +899,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; } @@ -909,9 +908,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -936,19 +935,18 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint __HAL_SPI_CLEAR_OVRFLAG(hspi); } + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -966,12 +964,10 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 __IO uint32_t tmpreg = 0U; #endif /* USE_SPI_CRC */ uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) @@ -981,18 +977,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); } - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1051,9 +1046,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1075,9 +1070,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1100,8 +1095,8 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { /* the latest data has not been received */ - errorcode = HAL_TIMEOUT; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Receive last data in 16 Bit mode */ @@ -1119,8 +1114,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC to Flush DR and RXNE flag */ @@ -1155,18 +1151,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 } #endif /* USE_SPI_CRC */ + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1179,8 +1174,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) { uint16_t initial_TxXferCount; uint32_t tmp_mode; @@ -1192,14 +1187,10 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Variable used to alternate Rx and Tx during transfer */ uint32_t txallowed = 1U; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); @@ -1209,18 +1200,20 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD initial_TxXferCount = Size; if (!((tmp_state == HAL_SPI_STATE_READY) || \ - ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && + (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1232,7 +1225,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD hspi->pRxBuffPtr = (uint8_t *)pRxData; hspi->RxXferCount = Size; hspi->RxXferSize = Size; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferCount = Size; hspi->TxXferSize = Size; @@ -1260,16 +1253,25 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } +#endif /* USE_SPI_CRC */ + } while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) { /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1295,9 +1297,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if (((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1306,16 +1308,24 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } +#endif /* USE_SPI_CRC */ } while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) { /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1341,9 +1351,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if ((((HAL_GetTick() - tickstart) >= Timeout) && ((Timeout != HAL_MAX_DELAY))) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1357,8 +1367,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { /* Error on the CRC reception */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC */ tmpreg = READ_REG(hspi->Instance->DR); @@ -1376,8 +1387,8 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Reset CRC Calculation */ SPI_RESET_CRC(hspi); - - errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } else { @@ -1389,9 +1400,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Check the end of the transaction */ if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK) { - errorcode = HAL_ERROR; hspi->ErrorCode = HAL_SPI_ERROR_FLAG; - goto error; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Clear overrun flag in 2 Lines communication mode because received is not read */ @@ -1400,18 +1411,19 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD __HAL_SPI_CLEAR_OVRFLAG(hspi); } + + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1422,32 +1434,30 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1483,10 +1493,6 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u } #endif /* USE_SPI_CRC */ - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); - - /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) { @@ -1494,9 +1500,12 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } -error : + /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1509,13 +1518,10 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) @@ -1525,15 +1531,15 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1573,9 +1579,6 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui } #endif /* USE_SPI_CRC */ - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); - /* Note : The SPI must be enabled after unlocking current process to avoid the risk of SPI interrupt handle execution before current process unlock */ @@ -1587,10 +1590,12 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui __HAL_SPI_ENABLE(hspi); } -error : /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1602,35 +1607,34 @@ error : * @param Size amount of data to be sent and received * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; if (!((tmp_state == HAL_SPI_STATE_READY) || \ - ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && + (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1639,7 +1643,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1666,8 +1670,6 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p } #endif /* USE_SPI_CRC */ - /* Enable TXE, RXNE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) @@ -1676,10 +1678,12 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p __HAL_SPI_ENABLE(hspi); } -error : /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable TXE, RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1690,9 +1694,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check tx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx)); @@ -1700,25 +1703,23 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1763,9 +1764,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1775,16 +1776,16 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1799,15 +1800,12 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - /* Check rx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) @@ -1821,15 +1819,14 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); - if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1877,9 +1874,9 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1889,16 +1886,16 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Rx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1911,12 +1908,11 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u * @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, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check rx & tx dma handles */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); @@ -1925,26 +1921,25 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; if (!((tmp_state == HAL_SPI_STATE_READY) || - ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && + (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1953,7 +1948,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1998,9 +1993,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Enable Rx DMA Request */ @@ -2019,9 +2014,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -2030,16 +2025,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Enable SPI peripheral */ __HAL_SPI_ENABLE(hspi); } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -2403,9 +2399,11 @@ HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) { HAL_StatusTypeDef errorcode = HAL_OK; /* The Lock is not implemented on this API to allow the user application - to call the HAL SPI API under callbacks HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback(): + to call the HAL SPI API under callbacks HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or + HAL_SPI_TxRxCpltCallback(): when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated - and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback() + and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or + HAL_SPI_TxRxCpltCallback() */ /* Abort the SPI DMA tx Stream/Channel */ @@ -2690,7 +2688,7 @@ __weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI state */ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi) { /* Return SPI handle state */ return hspi->State; @@ -2702,7 +2700,7 @@ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI error code in bitmap format */ -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi) { /* Return SPI ErrorCode */ return hspi->ErrorCode; @@ -2729,7 +2727,7 @@ uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) */ static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); uint32_t tickstart; /* Init tickstart for timeout management*/ @@ -2786,7 +2784,7 @@ static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); uint32_t tickstart; #if (USE_SPI_CRC != 0U) __IO uint32_t tmpreg = 0U; @@ -2885,7 +2883,7 @@ static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); uint32_t tickstart; #if (USE_SPI_CRC != 0U) __IO uint32_t tmpreg = 0U; @@ -2975,7 +2973,7 @@ static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Call user Tx half complete callback */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) @@ -2993,7 +2991,7 @@ static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Call user Rx half complete callback */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) @@ -3011,7 +3009,7 @@ static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Call user TxRx half complete callback */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) @@ -3029,7 +3027,7 @@ static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAError(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Stop the disable DMA transfer on SPI side */ CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); @@ -3052,7 +3050,7 @@ static void SPI_DMAError(DMA_HandleTypeDef *hdma) */ static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); hspi->RxXferCount = 0U; hspi->TxXferCount = 0U; @@ -3074,7 +3072,7 @@ static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) */ static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); __IO uint32_t count; hspi->hdmatx->XferAbortCallback = NULL; @@ -3138,7 +3136,7 @@ static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) */ static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Disable SPI Peripheral */ __HAL_SPI_DISABLE(hspi); @@ -3259,7 +3257,7 @@ static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) */ static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3352,7 +3350,7 @@ static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3514,7 +3512,7 @@ static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) */ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3540,7 +3538,7 @@ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3673,6 +3671,13 @@ static HAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t */ static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart) { + /* Wait until TXE flag */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_TXE, SET, Timeout, Tickstart) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + return HAL_TIMEOUT; + } + /* Control the BSY flag */ if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != HAL_OK) { @@ -3988,7 +3993,8 @@ uint8_t SPI_ISCRCErrorValid(SPI_HandleTypeDef *hspi) { #if defined(SPI_CRC_ERROR_WORKAROUND_FEATURE) && (USE_SPI_CRC_ERROR_WORKAROUND != 0U) /* Check how to handle this CRC error (workaround to be applied or not) */ - /* If CRC errors could be wrongly detected (issue 2.15.2 in STM32F10xxC/D/E silicon limitations ES (DocID14732 Rev 13) */ + /* If CRC errors could be wrongly detected (issue 2.15.2 in STM32F10xxC/D/E silicon limitations ES + (DocID14732 Rev 13)) */ if (hspi->Instance == SPI2) { if (hspi->Instance->RXCRCR == 0U) diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sram.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sram.c index d136ea439..c5a37190d 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sram.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_sram.c @@ -209,7 +209,7 @@ HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FSMC_NORSRAM_TimingTy /* Initialize SRAM extended mode timing Interface */ (void)FSMC_NORSRAM_Extended_Timing_Init(hsram->Extended, ExtTiming, hsram->Init.NSBank, - hsram->Init.ExtendedMode); + hsram->Init.ExtendedMode); /* Enable the NORSRAM device */ __FSMC_NORSRAM_ENABLE(hsram->Instance, hsram->Init.NSBank); @@ -1038,6 +1038,7 @@ HAL_SRAM_StateTypeDef HAL_SRAM_GetState(const SRAM_HandleTypeDef *hsram) */ static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) { + /* Derogation MISRAC2012-Rule-11.5 */ SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); /* Disable the DMA channel */ @@ -1060,6 +1061,7 @@ static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) */ static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) { + /* Derogation MISRAC2012-Rule-11.5 */ SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); /* Disable the DMA channel */ @@ -1082,6 +1084,7 @@ static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) */ static void SRAM_DMAError(DMA_HandleTypeDef *hdma) { + /* Derogation MISRAC2012-Rule-11.5 */ SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); /* Disable the DMA channel */ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim.c index 40cee887d..c00a9deff 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim.c @@ -3821,13 +3821,16 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Cha */ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { + uint32_t itsource = htim->Instance->DIER; + uint32_t itflag = htim->Instance->SR; + /* Capture compare 1 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET) + if ((itflag & (TIM_FLAG_CC1)) == (TIM_FLAG_CC1)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) != RESET) + if ((itsource & (TIM_IT_CC1)) == (TIM_IT_CC1)) { { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC1); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; /* Input capture event */ @@ -3855,11 +3858,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* Capture compare 2 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET) + if ((itflag & (TIM_FLAG_CC2)) == (TIM_FLAG_CC2)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) != RESET) + if ((itsource & (TIM_IT_CC2)) == (TIM_IT_CC2)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC2); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; /* Input capture event */ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) @@ -3885,11 +3888,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* Capture compare 3 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET) + if ((itflag & (TIM_FLAG_CC3)) == (TIM_FLAG_CC3)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) != RESET) + if ((itsource & (TIM_IT_CC3)) == (TIM_IT_CC3)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC3); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) @@ -3915,11 +3918,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* Capture compare 4 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET) + if ((itflag & (TIM_FLAG_CC4)) == (TIM_FLAG_CC4)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) != RESET) + if ((itsource & (TIM_IT_CC4)) == (TIM_IT_CC4)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC4); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) @@ -3945,11 +3948,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Update event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET) + if ((itflag & (TIM_FLAG_UPDATE)) == (TIM_FLAG_UPDATE)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) != RESET) + if ((itsource & (TIM_IT_UPDATE)) == (TIM_IT_UPDATE)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_UPDATE); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PeriodElapsedCallback(htim); #else @@ -3958,11 +3961,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Break input event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET) + if ((itflag & (TIM_FLAG_BREAK)) == (TIM_FLAG_BREAK)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET) + if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->BreakCallback(htim); #else @@ -3971,11 +3974,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Trigger detection event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET) + if ((itflag & (TIM_FLAG_TRIGGER)) == (TIM_FLAG_TRIGGER)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) != RESET) + if ((itsource & (TIM_IT_TRIGGER)) == (TIM_IT_TRIGGER)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TRIGGER); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TriggerCallback(htim); #else @@ -3984,11 +3987,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM commutation event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET) + if ((itflag & (TIM_FLAG_COM)) == (TIM_FLAG_COM)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) != RESET) + if ((itsource & (TIM_IT_COM)) == (TIM_IT_COM)) { - __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_COM); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->CommutationCallback(htim); #else @@ -4475,7 +4478,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_O * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength) + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength) { HAL_StatusTypeDef status; @@ -6809,6 +6813,13 @@ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, const TIM_Base_InitTypeDef *Structure /* Generate an update event to reload the Prescaler and the repetition counter (only for advanced timer) value immediately */ TIMx->EGR = TIM_EGR_UG; + + /* Check if the update flag is set after the Update Generation, if so clear the UIF flag */ + if (HAL_IS_BIT_SET(TIMx->SR, TIM_FLAG_UPDATE)) + { + /* Clear the update flag */ + CLEAR_BIT(TIMx->SR, TIM_FLAG_UPDATE); + } } /** @@ -6933,7 +6944,6 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) tmpccer |= (OC_Config->OCNPolarity << 4U); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC2NE; - } if (IS_TIM_BREAK_INSTANCE(TIMx)) diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim_ex.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim_ex.c index ff8c8f59f..8a565a6b9 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim_ex.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_tim_ex.c @@ -835,7 +835,7 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channe /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; - if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == (uint32_t)RESET) + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } @@ -1081,17 +1081,6 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chann (+) 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 * @{ */ @@ -1317,7 +1306,7 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Chann /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; - if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == (uint32_t)RESET) + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } @@ -2100,7 +2089,7 @@ HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) */ /** - * @brief Hall commutation changed callback in non-blocking mode + * @brief Commutation callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2114,7 +2103,7 @@ __weak void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) */ } /** - * @brief Hall commutation changed half complete callback in non-blocking mode + * @brief Commutation half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2129,7 +2118,7 @@ __weak void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim) } /** - * @brief Hall Break detection callback in non-blocking mode + * @brief Break detection callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2280,15 +2269,6 @@ static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - - if (hdma->Init.Mode == DMA_NORMAL) - { - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); - } - } else { /* nothing to do */ @@ -2357,13 +2337,13 @@ static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Cha { uint32_t tmp; - tmp = TIM_CCER_CC1NE << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ + tmp = TIM_CCER_CC1NE << (Channel & 0xFU); /* 0xFU = 15 bits max shift */ /* Reset the CCxNE Bit */ TIMx->CCER &= ~tmp; /* Set or reset the CCxNE Bit */ - TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ + TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0xFU)); /* 0xFU = 15 bits max shift */ } /** * @} diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_rtc_alarm_template.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_rtc_alarm_template.c index 6ab2edd0f..dba7cbbdd 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_rtc_alarm_template.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_rtc_alarm_template.c @@ -112,76 +112,94 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) #else #error Please select the RTC Clock source #endif /* RTC_CLOCK_SOURCE_LSE */ - - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) + status = HAL_RCC_OscConfig(&RCC_OscInitStruct); + if (status == HAL_OK) { PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; - if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) == HAL_OK) + status = HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct); + if (status == HAL_OK) { /* Enable RTC Clock */ __HAL_RCC_RTC_ENABLE(); - hRTC_Handle.Instance = RTC; /* Configure RTC time base to 10Khz */ + hRTC_Handle.Instance = RTC; hRTC_Handle.Init.AsynchPrediv = (HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_RTC) / 10000) - 1; hRTC_Handle.Init.OutPut = RTC_OUTPUTSOURCE_NONE; - HAL_RTC_Init(&hRTC_Handle); - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); + status = HAL_RTC_Init(&hRTC_Handle); + } + } + if (status == HAL_OK) + { + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(&hRTC_Handle); - /* Clear flag alarm A */ - __HAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF); + /* Clear flag alarm A */ + __HAL_RTC_ALARM_CLEAR_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF); - counter = 0U; - /* Wait till RTC ALRAF flag is set and if Time out is reached exit */ - while (__HAL_RTC_ALARM_GET_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF) != RESET) + counter = 0U; + /* Wait till RTC ALRAF flag is set and if Time out is reached exit */ + while (__HAL_RTC_ALARM_GET_FLAG(&hRTC_Handle, RTC_FLAG_ALRAF) != RESET) + { + if (counter++ == SystemCoreClock / 48U) /* Timeout = ~ 1s */ { - if (counter++ == SystemCoreClock / 48U) /* Timeout = ~ 1s */ - { - return HAL_ERROR; - } + status = HAL_ERROR; } + } + } + if (status == HAL_OK) + { + /* Set RTC COUNTER MSB word */ + hRTC_Handle.Instance->ALRH = 0x00U; + /* Set RTC COUNTER LSB word */ + hRTC_Handle.Instance->ALRL = 0x09U; - /* Set RTC COUNTER MSB word */ - hRTC_Handle.Instance->ALRH = 0x00U; - /* Set RTC COUNTER LSB word */ - hRTC_Handle.Instance->ALRL = 0x09U; - - /* RTC Alarm Interrupt Configuration: EXTI configuration */ - __HAL_RTC_ALARM_EXTI_ENABLE_IT(); - __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE() + /* RTC Alarm Interrupt Configuration: EXTI configuration */ + __HAL_RTC_ALARM_EXTI_ENABLE_IT(); + __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE(); - /* Clear Second and overflow flags */ - CLEAR_BIT(hRTC_Handle.Instance->CRL, (RTC_FLAG_SEC | RTC_FLAG_OW)); + /* Clear Second and overflow flags */ + CLEAR_BIT(hRTC_Handle.Instance->CRL, (RTC_FLAG_SEC | RTC_FLAG_OW)); - /* Set RTC COUNTER MSB word */ - hRTC_Handle.Instance->CNTH = 0x00U; - /* Set RTC COUNTER LSB word */ - hRTC_Handle.Instance->CNTL = 0x00U; + /* Set RTC COUNTER MSB word */ + hRTC_Handle.Instance->CNTH = 0x00U; + /* Set RTC COUNTER LSB word */ + hRTC_Handle.Instance->CNTL = 0x00U; - /* Configure the Alarm interrupt */ - __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA); + /* Configure the Alarm interrupt */ + __HAL_RTC_ALARM_ENABLE_IT(&hRTC_Handle, RTC_IT_ALRA); - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(&hRTC_Handle); - /* Wait till RTC is in INIT state and if Time out is reached exit */ - counter = 0U; - while ((hRTC_Handle.Instance->CRL & RTC_CRL_RTOFF) == (uint32_t)RESET) + /* Wait till RTC is in INIT state and if Time out is reached exit */ + counter = 0U; + while ((hRTC_Handle.Instance->CRL & RTC_CRL_RTOFF) == (uint32_t)RESET) + { + if (counter++ == SystemCoreClock / 48U) /* Timeout = ~ 1s */ { - if (counter++ == SystemCoreClock / 48U) /* Timeout = ~ 1s */ - { - return HAL_ERROR; - } + status = HAL_ERROR; } + } + } + if (status == HAL_OK) + { + /* Enable the RTC global Interrupt */ + HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn); - HAL_NVIC_SetPriority(RTC_Alarm_IRQn, TickPriority, 0U); - HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn); - return HAL_OK; + /* Configure the SysTick IRQ priority */ + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + HAL_NVIC_SetPriority(RTC_Alarm_IRQn, TickPriority ,0U); + uwTickPrio = TickPriority; + } + else + { + status = HAL_ERROR; } } - return HAL_ERROR; + + return status; } /** diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_tim_template.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_tim_template.c index 9e2dee084..4a00f663e 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_tim_template.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_timebase_tim_template.c @@ -100,14 +100,31 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) TimHandle.Init.ClockDivision = 0U; TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; - if (HAL_TIM_Base_Init(&TimHandle) == HAL_OK) + status = HAL_TIM_Base_Init(&TimHandle); + if (status == HAL_OK) { /* Start the TIM time Base generation in interrupt mode */ - return HAL_TIM_Base_Start_IT(&TimHandle); + status = HAL_TIM_Base_Start_IT(&TimHandle); + if (status == HAL_OK) + { + /* Enable the TIM2 global Interrupt */ + HAL_NVIC_EnableIRQ(TIM2_IRQn); + + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + /*Configure the TIM2 IRQ priority */ + HAL_NVIC_SetPriority(TIM2_IRQn, TickPriority ,0); + uwTickPrio = TickPriority; + } + else + { + status = HAL_ERROR; + } + } } /* Return function status */ - return HAL_ERROR; + return status; } /** diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_uart.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_uart.c index db1f087bd..b7cf66cc7 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_uart.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_uart.c @@ -1174,6 +1174,8 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pD { if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { + huart->gState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; } if (pdata8bits == NULL) @@ -1191,6 +1193,8 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pD if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) { + huart->gState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; } @@ -1258,6 +1262,8 @@ HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, ui { if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) { + huart->RxState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; } if (pdata8bits == NULL) @@ -1786,21 +1792,18 @@ HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_ status = UART_Start_Receive_DMA(huart, pData, Size); /* Check Rx process has been successfully started */ - if (status == HAL_OK) + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - __HAL_UART_CLEAR_IDLEFLAG(huart); - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - } - else - { - /* In case of errors already pending when reception is started, - Interrupts may have already been raised and lead to reception abortion. - (Overrun error for instance). - In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ - status = HAL_ERROR; - } + __HAL_UART_CLEAR_IDLEFLAG(huart); + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + } + else + { + /* In case of errors already pending when reception is started, + Interrupts may have already been raised and lead to reception abortion. + (Overrun error for instance). + In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ + status = HAL_ERROR; } return status; @@ -3188,19 +3191,31 @@ static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; + } - /* Process Unlocked */ - __HAL_UNLOCK(huart); + if ((READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) && (Flag != UART_FLAG_TXE) && (Flag != UART_FLAG_TC)) + { + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) == SET) + { + /* Clear Overrun Error flag*/ + __HAL_UART_CLEAR_OREFLAG(huart); - return HAL_TIMEOUT; + /* Blocking error : transfer is aborted + Set the UART state ready to be able to start again the process, + Disable Rx Interrupts if ongoing */ + UART_EndRxTransfer(huart); + + huart->ErrorCode = HAL_UART_ERROR_ORE; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_ERROR; + } } } } diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_usart.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_usart.c index eb5bacd01..4423252ea 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_usart.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_usart.c @@ -2081,6 +2081,9 @@ uint32_t HAL_USART_GetError(const USART_HandleTypeDef *husart) return husart->ErrorCode; } +/** + * @} + */ /** * @} */ @@ -2782,7 +2785,7 @@ static void USART_SetConfig(USART_HandleTypeDef *husart) CLEAR_BIT(husart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE)); /*-------------------------- USART BRR Configuration -----------------------*/ - if((husart->Instance == USART1)) + if (husart->Instance == USART1) { pclk = HAL_RCC_GetPCLK2Freq(); husart->Instance->BRR = USART_BRR(pclk, husart->Init.BaudRate); @@ -2794,10 +2797,6 @@ static void USART_SetConfig(USART_HandleTypeDef *husart) } } -/** - * @} - */ - /** * @} */ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_wwdg.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_wwdg.c index af3093a4b..dbf3aadee 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_wwdg.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_hal_wwdg.c @@ -21,82 +21,108 @@ ****************************************************************************** @verbatim ============================================================================== - ##### WWDG specific features ##### + ##### 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) + time period, unless the program refreshes the counter (T[6;0] downcounter) before reaching 0x3F value (i.e. a reset is generated when the counter - value rolls over from 0x40 to 0x3F). + value rolls down 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 + (+) If required by application, an Early Wakeup Interrupt can be triggered + in order to be warned before WWDG expiration. The Early Wakeup Interrupt + (EWI) can be used if specific safety operations or data logging must + be performed before the actual reset is generated. When the downcounter + reaches 0x40, interrupt occurs. This mechanism requires WWDG interrupt + line to be enabled in NVIC. Once enabled, EWI interrupt 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 timeout (mS) = 1000 * (T[5;0] + 1) / WWDG clock (Hz) + where T[5;0] are the lowest 6 bits of Counter. (+) 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 36 MHz(PCLK1): 910 us / 58.25 ms - - (+) The Early Wakeup Interrupt (EWI) can be used if specific safety - operations or data logging must be performed before the actual reset is - generated. When the downcounter reaches the value 0x40, an 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. - In some applications, the EWI interrupt can be used to manage a software - system check and/or system recovery/graceful degradation, without - generating a WWDG reset. In this case, the corresponding interrupt - service routine (ISR) should reload the WWDG counter to avoid the WWDG - reset, then trigger the required actions. - Note:When the EWI interrupt cannot be served, e.g. due to a system lock - in a higher priority task, the WWDG reset will eventually be generated. - - (+) Debug mode : When the microcontroller enters debug mode (core halted), - the WWDG counter either continues to work normally or stops, depending - on DBG_WWDG_STOP configuration bit in DBG module, accessible through - __HAL_DBGMCU_FREEZE_WWDG() and __HAL_DBGMCU_UNFREEZE_WWDG() macros + (++) min time (mS) = 1000 * (Counter - Window) / WWDG clock + (++) max time (mS) = 1000 * (Counter - 0x40) / WWDG clock + (+) Typical values: + (++) Counter min (T[5;0] = 0x00) at 36MHz (PCLK1) with zero prescaler: + max timeout before reset: approximately 910us + (++) Counter max (T[5;0] = 0x3F) at 36MHz (PCLK1) with prescaler + dividing by 8: + max timeout before reset: approximately 58.25ms ##### How to use this driver ##### ============================================================================== - [..] - (+) Enable WWDG APB1 clock using __HAL_RCC_WWDG_CLK_ENABLE(). - (+) Set the WWDG prescaler, refresh window, counter value and Early Wakeup - Interrupt mode using using HAL_WWDG_Init() function. - This enables WWDG peripheral and the downcounter starts downcounting - from given counter value. - Init function can be called again to modify all watchdog parameters, - however if EWI mode has been set once, it can't be clear until next - reset. + *** Common driver usage *** + =========================== - (+) The application program must refresh the WWDG counter at regular - intervals during normal operation to prevent an MCU reset using + [..] + (+) Enable WWDG APB1 clock using __HAL_RCC_WWDG_CLK_ENABLE(). + (+) Configure the WWDG prescaler, refresh window value, counter value and early + interrupt status using HAL_WWDG_Init() function. This will automatically + enable WWDG and start its downcounter. Time reference can be taken from + function exit. Care must be taken to provide a counter value + greater than 0x40 to prevent generation of immediate reset. + (+) If the Early Wakeup Interrupt (EWI) feature is enabled, an interrupt is + generated when the counter reaches 0x40. When HAL_WWDG_IRQHandler is + triggered by the interrupt service routine, flag will be automatically + cleared and HAL_WWDG_WakeupCallback user callback will be executed. User + can add his own code by customization of callback HAL_WWDG_WakeupCallback. + (+) 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 window value already programmed. + the counter is lower than the refresh window value already programmed. - (+) if Early Wakeup Interrupt mode is enable an interrupt is generated when - the counter reaches 0x40. User can add his own code in weak function - HAL_WWDG_EarlyWakeupCallback(). + *** Callback registration *** + ============================= - *** WWDG HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in WWDG HAL driver. - - (+) __HAL_WWDG_GET_IT_SOURCE: Check the selected WWDG's interrupt source. - (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status. - (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags. + [..] + The compilation define USE_HAL_WWDG_REGISTER_CALLBACKS when set to 1 allows + the user to configure dynamically the driver callbacks. Use Functions + HAL_WWDG_RegisterCallback() to register a user callback. + + (+) Function HAL_WWDG_RegisterCallback() allows to register following + callbacks: + (++) EwiCallback : callback for Early WakeUp Interrupt. + (++) MspInitCallback : WWDG MspInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + (+) Use function HAL_WWDG_UnRegisterCallback() to reset a callback to + the default weak (surcharged) function. HAL_WWDG_UnRegisterCallback() + takes as parameters the HAL peripheral handle and the Callback ID. + This function allows to reset following callbacks: + (++) EwiCallback : callback for Early WakeUp Interrupt. + (++) MspInitCallback : WWDG MspInit. + + [..] + When calling HAL_WWDG_Init function, callbacks are reset to the + corresponding legacy weak (surcharged) functions: + HAL_WWDG_EarlyWakeupCallback() and HAL_WWDG_MspInit() only if they have + not been registered before. + + [..] + When compilation define USE_HAL_WWDG_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + *** WWDG HAL driver macros list *** + =================================== + [..] + Below the list of available macros in WWDG HAL driver. + (+) __HAL_WWDG_ENABLE: Enable the WWDG peripheral + (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status + (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags + (+) __HAL_WWDG_ENABLE_IT: Enable the WWDG early wakeup interrupt @endverbatim - ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_fsmc.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_fsmc.c index 3d42565db..f783c9977 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_fsmc.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_fsmc.c @@ -60,7 +60,7 @@ * @{ */ #if defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) || defined(HAL_PCCARD_MODULE_ENABLED) \ - || defined(HAL_SRAM_MODULE_ENABLED) + || defined(HAL_SRAM_MODULE_ENABLED) /** @defgroup FSMC_LL FSMC Low Layer * @brief FSMC driver modules @@ -206,7 +206,7 @@ * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_InitTypeDef *Init) + const FSMC_NORSRAM_InitTypeDef *Init) { uint32_t flashaccess; uint32_t btcr_reg; @@ -289,7 +289,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank) + FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank) { /* Check the parameters */ assert_param(IS_FSMC_NORSRAM_DEVICE(Device)); @@ -326,7 +326,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank) + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank) { /* Check the parameters */ @@ -341,13 +341,14 @@ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, assert_param(IS_FSMC_NORSRAM_BANK(Bank)); /* Set FSMC_NORSRAM device timing parameters */ - MODIFY_REG(Device->BTCR[Bank + 1U], BTR_CLEAR_MASK, (Timing->AddressSetupTime | - ((Timing->AddressHoldTime) << FSMC_BTRx_ADDHLD_Pos) | - ((Timing->DataSetupTime) << FSMC_BTRx_DATAST_Pos) | - ((Timing->BusTurnAroundDuration) << FSMC_BTRx_BUSTURN_Pos) | - (((Timing->CLKDivision) - 1U) << FSMC_BTRx_CLKDIV_Pos) | - (((Timing->DataLatency) - 2U) << FSMC_BTRx_DATLAT_Pos) | - (Timing->AccessMode))); + Device->BTCR[Bank + 1U] = + (Timing->AddressSetupTime << FSMC_BTRx_ADDSET_Pos) | + (Timing->AddressHoldTime << FSMC_BTRx_ADDHLD_Pos) | + (Timing->DataSetupTime << FSMC_BTRx_DATAST_Pos) | + (Timing->BusTurnAroundDuration << FSMC_BTRx_BUSTURN_Pos) | + ((Timing->CLKDivision - 1U) << FSMC_BTRx_CLKDIV_Pos) | + ((Timing->DataLatency - 2U) << FSMC_BTRx_DATLAT_Pos) | + Timing->AccessMode; return HAL_OK; } @@ -365,8 +366,8 @@ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, * @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) + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, + uint32_t ExtendedMode) { /* Check the parameters */ assert_param(IS_FSMC_EXTENDED_MODE(ExtendedMode)); @@ -526,7 +527,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Devi * @param Init Pointer to NAND Initialization structure * @retval HAL status */ -HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init) +HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, const FSMC_NAND_InitTypeDef *Init) { /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); @@ -574,7 +575,7 @@ HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDe * @retval HAL status */ HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) { /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); @@ -614,7 +615,7 @@ HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, * @retval HAL status */ HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) { /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); @@ -761,8 +762,8 @@ HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank * @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) +HAL_StatusTypeDef FSMC_NAND_GetECC(const FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout) { uint32_t tickstart; @@ -854,7 +855,7 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, * @param Init Pointer to PCCARD Initialization structure * @retval HAL status */ -HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init) +HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, const FSMC_PCCARD_InitTypeDef *Init) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); @@ -888,7 +889,7 @@ HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_Init * @retval HAL status */ HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing) + const FSMC_NAND_PCC_TimingTypeDef *Timing) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); @@ -917,7 +918,7 @@ HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Devic * @retval HAL status */ HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing) + const FSMC_NAND_PCC_TimingTypeDef *Timing) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); @@ -946,7 +947,7 @@ HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *De * @retval HAL status */ HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing) + const FSMC_NAND_PCC_TimingTypeDef *Timing) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_spi.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_spi.c index 5f557d3aa..e528a6958 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_spi.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_spi.c @@ -119,7 +119,7 @@ * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx) { ErrorStatus status = ERROR; @@ -168,8 +168,9 @@ ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) /** * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. - * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), - * SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. + * @note As some bits in SPI configuration registers can only be written when the + * SPI is disabled (SPI_CR1_SPE bit = 0), SPI peripheral should be in disabled state prior + * calling this function. Otherwise, ERROR result will be returned. * @param SPIx SPI Instance * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure * @retval An ErrorStatus enumeration value. (Return always SUCCESS) @@ -348,7 +349,7 @@ void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx) { return LL_SPI_DeInit(SPIx); } diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_tim.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_tim.c index 6e01d0f68..f111d51b1 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_tim.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_tim.c @@ -766,8 +766,6 @@ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 1: Reset the CC1E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); @@ -795,8 +793,10 @@ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); @@ -845,8 +845,6 @@ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 2: Reset the CC2E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); @@ -874,8 +872,10 @@ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); @@ -924,8 +924,6 @@ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 3: Reset the CC3E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); @@ -953,8 +951,10 @@ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); @@ -1003,8 +1003,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); /* Disable the Channel 4: Reset the CC4E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); @@ -1032,7 +1030,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the Output Idle state */ @@ -1054,7 +1051,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM return SUCCESS; } - /** * @brief Configure the TIMx input channel 1. * @param TIMx Timer Instance diff --git a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_usb.c b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_usb.c index a25f30580..7e481aafe 100644 --- a/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_usb.c +++ b/stm32cube/stm32f1xx/drivers/src/stm32f1xx_ll_usb.c @@ -221,9 +221,9 @@ HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_ModeTypeDe do { - HAL_Delay(1U); - ms++; - } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < 50U)); + HAL_Delay(10U); + ms += 10U; + } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); } else if (mode == USB_DEVICE_MODE) { @@ -231,16 +231,16 @@ HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_ModeTypeDe do { - HAL_Delay(1U); - ms++; - } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < 50U)); + HAL_Delay(10U); + ms += 10U; + } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); } else { return HAL_ERROR; } - if (ms == 50U) + if (ms == HAL_USB_CURRENT_MODE_MAX_DELAY_MS) { return HAL_ERROR; } @@ -383,7 +383,7 @@ HAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -397,7 +397,7 @@ HAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -420,7 +420,7 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -434,7 +434,7 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -452,7 +452,7 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) * @arg USB_OTG_SPEED_FULL: Full speed mode * @retval Hal status */ -HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed) +HAL_StatusTypeDef USB_SetDevSpeed(const USB_OTG_GlobalTypeDef *USBx, uint8_t speed) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -467,7 +467,7 @@ HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed) * This parameter can be one of these values: * @arg USBD_FS_SPEED: Full speed mode */ -uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) +uint8_t USB_GetDevSpeed(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; uint8_t speed; @@ -492,7 +492,7 @@ uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_ActivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -530,7 +530,7 @@ HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTy * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -569,7 +569,7 @@ HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_DeactivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -616,7 +616,7 @@ HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EP * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -792,7 +792,7 @@ HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_EPStopXfer(const USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) { __IO uint32_t count = 0U; HAL_StatusTypeDef ret = HAL_OK; @@ -852,7 +852,7 @@ HAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef * @param len Number of bytes to write * @retval HAL status */ -HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, +HAL_StatusTypeDef USB_WritePacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -880,7 +880,7 @@ HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, * @param len Number of bytes to read * @retval pointer to destination buffer */ -void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) +void *USB_ReadPacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) { uint32_t USBx_BASE = (uint32_t)USBx; uint8_t *pDest = dest; @@ -922,7 +922,7 @@ void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_EPSetStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -953,7 +953,7 @@ HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_EPClearStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -1023,7 +1023,7 @@ HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx) * This parameter can be a value from 0 to 255 * @retval HAL status */ -HAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address) +HAL_StatusTypeDef USB_SetDevAddress(const USB_OTG_GlobalTypeDef *USBx, uint8_t address) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1038,7 +1038,7 @@ HAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_DevConnect(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1055,7 +1055,7 @@ HAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_DevDisconnect(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_DevDisconnect(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1088,7 +1088,7 @@ uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef const *USBx) * @param chnum Channel number * @retval USB Channel Interrupt status */ -uint32_t USB_ReadChInterrupts(USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) +uint32_t USB_ReadChInterrupts(const USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1104,7 +1104,7 @@ uint32_t USB_ReadChInterrupts(USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) * @param USBx Selected device * @retval USB Device OUT EP interrupt status */ -uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_ReadDevAllOutEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1120,7 +1120,7 @@ uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval USB Device IN EP interrupt status */ -uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_ReadDevAllInEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1138,7 +1138,7 @@ uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx) * 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 USB_ReadDevOutEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1156,7 +1156,7 @@ uint32_t USB_ReadDevOutEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) * 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 USB_ReadDevInEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1190,7 +1190,7 @@ void USB_ClearInterrupts(USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt) * 0 : Host * 1 : Device */ -uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_GetMode(const USB_OTG_GlobalTypeDef *USBx) { return ((USBx->GINTSTS) & 0x1U); } @@ -1200,7 +1200,7 @@ uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_ActivateSetup(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1218,10 +1218,10 @@ HAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx) * @param psetup pointer to setup packet * @retval HAL status */ -HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t *psetup) +HAL_StatusTypeDef USB_EP0_OutStart(const USB_OTG_GlobalTypeDef *USBx, const uint8_t *psetup) { uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->CID + 0x1U); + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); UNUSED(psetup); if (gSNPSiD > USB_OTG_CORE_ID_300A) @@ -1254,7 +1254,7 @@ static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -1268,7 +1268,7 @@ static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -1349,7 +1349,7 @@ HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef c * HCFG_6_MHZ : Low Speed 6 MHz Clock * @retval HAL status */ -HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq) +HAL_StatusTypeDef USB_InitFSLSPClkSel(const USB_OTG_GlobalTypeDef *USBx, uint8_t freq) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1379,7 +1379,7 @@ HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq) * @note (1)The application must wait at least 10 ms * before clearing the reset bit. */ -HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_ResetPort(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1406,7 +1406,7 @@ HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) * 1 : Activate VBUS * @retval HAL status */ -HAL_StatusTypeDef USB_DriveVbus(USB_OTG_GlobalTypeDef *USBx, uint8_t state) +HAL_StatusTypeDef USB_DriveVbus(const USB_OTG_GlobalTypeDef *USBx, uint8_t state) { uint32_t USBx_BASE = (uint32_t)USBx; __IO uint32_t hprt0 = 0U; @@ -1704,7 +1704,7 @@ HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDe * @param USBx Selected device * @retval HAL state */ -uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_HC_ReadInterrupt(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1718,7 +1718,7 @@ uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx) * 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) +HAL_StatusTypeDef USB_HC_Halt(const USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t hcnum = (uint32_t)hc_num; @@ -1802,7 +1802,7 @@ HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) * 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) +HAL_StatusTypeDef USB_DoPing(const USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t chnum = (uint32_t)ch_num; @@ -1891,7 +1891,7 @@ HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_ActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1909,7 +1909,7 @@ HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; diff --git a/stm32cube/stm32f1xx/release_note.html b/stm32cube/stm32f1xx/release_note.html index 754d1b084..f7b5c57ca 100644 --- a/stm32cube/stm32f1xx/release_note.html +++ b/stm32cube/stm32f1xx/release_note.html @@ -36,7 +36,7 @@

    Purpose

  • A consistent set of middleware components such as RTOS, USB, TCP/IP, Graphics
  • All embedded software utilities come with a full set of examples.
  • -
  • The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements STM32Cube architecture
  • +
  • The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements STM32Cube architecture
  • The HAL (Hardware Abstraction Layer) drivers provided within this package supports the following STM32F100xx STM32F101xx, STM32F102xx, STM32F103xx, STM32F105xx and STM32F107xx Series.

      @@ -59,12 +59,224 @@

      Purpose

      Update History

      - +

      Maintenance release

      Main Changes

      • Patch release to fix known defects and enhancements implementation.
      • +
      • Upgrade FreeRTOS Lib to use v10.3.1 (ST modified 2023-08-18).

      • +
      • CMSIS updates +
          +
        • Update defined value of SystemCoreClock to be aligned with HSI value.
        • +
      • +
      • HAL updates +
          +
        • HAL code quality enhancement for MISRA-C Rule-8.13 by adding const qualifiers.
        • +
        • LL/HAL CORTEX driver +
            +
          • Update HAL_MPU_ConfigRegion() to allow the configuration of the MPU registers independently of the value of Enable/Disable field.
          • +
          • Add new APIs HAL_MPU_EnableRegion() / HAL_MPU_DisableRegion().
          • +
        • +
        • HAL FLASH driver +
            +
          • Remove HAL_LOCK/HAL_UNLOCK() from HAL_FLASH_Program_IT() and HAL_FLASHEx_Erase_IT() APIs.
          • +
        • +
        • HAL GPIO driver +
            +
          • Replace GPIO_Pin_x with GPIO_PIN_x to be compliant with macros definition.
          • +
        • +
        • HAL CAN driver +
            +
          • Clarify pin configuration in driver header by removing open-drain information.
          • +
        • +
        • HAL I2C driver +
            +
          • Update HAL_I2C_Mem_Read() API to clear ACK bit once 3 bytes to read remain to be able to send the NACK once the transfer ends.
          • +
          • Update HAL_I2C_Master_Abort_IT() API to support memory abort transfer.
          • +
          • Update the HAL I2C driver to reset PreviousState to I2C_STATE_NONE at the end of transfer.
          • +
        • +
        • HAL SDMMC driver +
            +
          • Update HAL SD processes to manage STBITERR flag.
          • +
        • +
        • HAL SPI driver +
            +
          • Update HAL_SPI_TransmitReceive() API to set the bit CRCNEXT in case of one byte transaction
          • +
          • Update IT APIs to enable interrupts after process unlock.
          • +
          • Add wait on flag TXE to be set at the end of transaction to be aligned with reference manual.
          • +
        • +
        • HAL I2S driver +
            +
          • Update HAL I2S driver to fix misplaced __HAL_LOCK() and remove ‘go to’ instruction.
          • +
        • +
        • LL/HAL TIM driver +
            +
          • Improve performance by removing multiple volatile reads or writes in interrupt handler.
          • +
          • HAL TIM driver’s operational behavior improvement.
          • +
          • Improve period configuration parameter check.
          • +
          • Update interrupt flag is cleared when the update event is generated by software.
          • +
          • Remove unnecessary change of MOE bitfield in LL_TIM_BDTR_Init().
          • +
          • Add LL_TIM_CC_IsEnabledPreload() API.
          • +
        • +
        • HAL UART driver +
            +
          • Avoid ORE flag to be cleared by a transmit process in polling mode.
          • +
          • Rework of UART_WaitOnFlagUntilTimeout() API to avoid being stuck forever when UART overrun error occurs and to enhance behavior.
          • +
        • +
        • HAL USB_OTG driver +
            +
          • Fix device connection in case battery charging is used with HS instance linked to internal FS PHY.
          • +
          • ll_usb.c: increase timeout value to allow core reset to complete
          • +
          • ll_usb.c: improve delay management to set core mode
          • +
        • +
        • LL UTILS driver +
            +
          • Fix ‘Ticks’ parameter’s description of LL_InitTick() API.
          • +
        • +
      • +
      • Middleware +
          +
        • Upgrade FreeRTOS Lib to use v10.3.1 (ST modified 2023-08-18).
        • +
      • +
      • Projects updates +
          +
        • STM3210C_EVAL +
            +
          • USB Host MSC applications: fix stack corruption due to inconsistent type of local variable in MSC_File_Operations() API.
          • +
        • +
      • +
      +

      Contents

      +
        +
      • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
      • +
      + + + + + + + + + + + + + + + + +
      Projects
      NameVersionRelease notes
      Projectssee Projects Release note for detailsrelease notes
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Drivers
      NameVersionRelease note
      STM32F1xx CMSISV4.3.5release notes
      STM32F1xx HALV1.1.10release notes
      BSP STM3210E_EVALV7.0.2release notes
      BSP STM3210C_EVALV6.1.1release notes
      BSP STM32VL-DiscoveryV1.0.3release notes
      BSP STM32F1xx_NucleoV1.0.5release notes
      + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Utilities
      NameVersionRelease note
      CPUV1.1.4release notes
      FontsV1.0.3release notes
      LogV1.0.4release notes
      + + + + + + + + + + + + + + + + +
      Middlewares
      NameVersionRelease note
      FreeRTOSV10.3.1release notes ST modified 20230818 release notes
      +

      Known Limitations

      +
        +
      • SW4STM32 projects aren’t provided for STM32VL-Discovery board because it embeds STLinv1 version that is not hardware supported by SW4STM32 toolchain.
      • +
      +

      Development Toolchains and Compilers

      +
        +
      • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9+ ST-Link
      • +
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.38 (or upper) + ST-LINK, pack available here: +
          +
        • www.keil.com/dd2/Pack/ (Section : STMicroelectronics STM32F1 Series Device Support)
        • +
        • Only template projects are migrated to Arm Compiler 6 with MDK-ARM 5.31 (“AC-like Warnings” mode).
        • +
      • +
      • System Workbench for STM32 (SW4STM32) (7-2018-q2-update) toolchain V2.9.0 + ST-Link
      • +
      +
      +
      +
      + +
      +

      Maintenance release

      +

      Main Changes

      +
        +
      • Patch release to fix known defects and enhancements implementation.
      • All source files: update disclaimer to add reference to the new license agreement.

      • CMSIS updates
          @@ -212,7 +424,7 @@

          Main Changes

    -

    Contents

    +

    Contents

    • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
    @@ -302,7 +514,7 @@

    Contents

    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.40.2+ ST-Link
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31 (or upper) + ST-LINK, pack available here: @@ -317,8 +529,8 @@

      Development Toolchains and Compile
      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release to fix known defects and enhancements implementation.

      • CMSIS updates @@ -451,7 +663,7 @@

        Main Changes

      • Update examples and applications to avoid clearing DMA using global flag GIFx.

    -

    Contents

    +

    Contents

    • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
    • Projects release notes @@ -516,7 +728,7 @@

      Contents

    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.40.2+ ST-Link
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31 + ST-LINK
    • @@ -527,8 +739,8 @@

      Development Toolchains and Compi
      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release of STM32CubeF1 Firmware Package.

      • HAL

        @@ -546,7 +758,7 @@

        Main Changes

    -

    Contents

    +

    Contents

    @@ -569,8 +781,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Patch release to fix known defects and enhancements implementation

    • HAL @@ -758,7 +970,7 @@

      Main Changes

    • SystemInit(): update to don’t reset RCC registers to its reset values.
    -

    Contents

    +

    Contents

    • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
    • Projects release notes @@ -818,11 +1030,11 @@

      Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • SW4STM32 projects aren’t provided for STM32VL-Discovery board because it embeds STLinv1 version that is not hardware supported by SW4STM32 toolchain.
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2+ ST-Link
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.26 + ST-LINK
    • @@ -849,8 +1061,8 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release to fix known defects and enhancements implementation

      • HAL

        @@ -902,7 +1114,7 @@

        Main Changes

    -

    Contents

    +

    Contents

    @@ -925,8 +1137,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • General updates to fix known defects and enhancements implementation
    • Remove support of TrueSTUDIO tool chain
    • @@ -1018,7 +1230,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component

  • -

    Contents

    +

    Contents

    • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
    • Projects release notes @@ -1233,12 +1445,12 @@

      Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • SW4STM32 projects aren’t provided for STM32VL-Discovery board because it embeds STLinv1 version that is not hardware supported by SW4STM32 toolchain.
    • Register callback feature will be deployed on HAL I2C driver in next release
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2+ ST-Link
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.26 + ST-LINK
    • @@ -1265,8 +1477,8 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • General update to fix known defects and several implementations enhancement
      • The following changes done on the HAL drivers require an update on the application code based on older HAL versions @@ -1294,7 +1506,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component
    -

    Contents

    +

    Contents

    • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
    • Projects release notes @@ -1509,11 +1721,11 @@

      Contents

    -

    Known Limitations

    +

    Known Limitations

    • SW4STM32 projects aren’t provided for STM32VL-Discovery board because it embeds STLinv1 version that is not hardware supported by SW4STM32 toolchain.
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.23
    • @@ -1541,12 +1753,12 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release to fix issues in GPIO, RCC, SMARTCARD, I2C and Generic HAL/LL drivers
      -

      Contents

      +

      Contents

      @@ -1568,8 +1780,8 @@

      Contents

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • General update to fix known defects and several implementations enhancement

      • HAL @@ -1584,7 +1796,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component

    • -

      Contents

      +

      Contents

      • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
      • Projects release notes @@ -1799,11 +2011,11 @@

        Contents

    -

    Known Limitations

    +

    Known Limitations

    • SW4STM32 projects aren’t provided for STM32VL-Discovery board because it embeds STLinv1 version that is not hardware supported by SW4STM32 toolchain.
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.23
    • @@ -1831,8 +2043,8 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Add Low Layer drivers under Drivers32F1xx_HAL_Driver
          @@ -1919,7 +2131,7 @@

          Main Changes

      • For the complete list of changes, please refer to the release notes of each firmware component

      -

      Contents

      +

      Contents

      • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
      • Projects release notes @@ -2134,11 +2346,11 @@

        Contents

      -

      Known Limitations

      +

      Known Limitations

      • None
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain V7.80.4
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.23
      • @@ -2166,8 +2378,8 @@

        Dependencies

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • Maintenance release to fix known defects and several enhancements implementation.

        • HAL @@ -2233,7 +2445,7 @@

          Main Changes

        • Add latest version of STM32CubeUpdater (V4.10.0).
      -

      Contents

      +

      Contents

      • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
      • Projects release notes @@ -2447,11 +2659,11 @@

        Contents

      -

      Known Limitations

      +

      Known Limitations

      • None
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain V7.20 + ST-LINK
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.17 + ST-LINK
      • @@ -2479,15 +2691,15 @@

        Dependencies

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • Patch release to fix issue in HAL driver:
          • Remove the #if defined(USE_HAL_LEGACY) condition to include Legacy/stm32_hal_legacy.h by default, in stm32f1xx_hal_def.h.
        -

        Contents

        +

        Contents

        @@ -2504,11 +2716,11 @@

        Contents

        -

        Known Limitations

        +

        Known Limitations

        • None
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V7.20 + ST-LINK
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.17 + ST-LINK
        • @@ -2536,8 +2748,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • Maintenance release to fix known defects and several enhancements implementation.

          • HAL @@ -2570,7 +2782,7 @@

            Main Changes

          • Add latest version of STM32CubeUpdater (V4.10.0).
        -

        Contents

        +

        Contents

        • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
        • Projects release notes @@ -2785,11 +2997,11 @@

          Contents

        -

        Known Limitations

        +

        Known Limitations

        • None
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V7.20 + ST-LINK
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.17 + ST-LINK
        • @@ -2817,8 +3029,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • Maintenance release.
          • Fix known defects and several enhancements implementation.

          • @@ -2864,7 +3076,7 @@

            Main Changes

          • CMSIS-RTOS V1.02 (unchanged)
        -

        Contents

        +

        Contents

        • The STM32CubeF1 Firmware package comes with a rich set of examples running on STMicroelectronics boards, organized by board and provided with pre-configured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html.
        • Projects release notes @@ -3072,11 +3284,11 @@

          Contents

        -

        Known Limitations

        +

        Known Limitations

        • None
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V7.20 + ST-LINK
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.10 + ST-LINK @@ -3107,8 +3319,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • Add support of System Workbench for STM32 (SW4STM32) toolchain

          • HAL
          • @@ -3120,7 +3332,7 @@

            Main Changes

          • Projects
          • Add projects for SW4STM32 toolchain

          -

          Contents

          +

          Contents

          @@ -3297,11 +3509,11 @@

          Contents

          Drivers
          -

          Known Limitations

          +

          Known Limitations

          • None
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V7.20 + ST-LINK
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.10 + ST-LINK
          • @@ -3329,12 +3541,12 @@

            Dependencies

            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • First official release of STM32CubeF1 (STM32Cube for STM32F1 Series)
            -

            Contents

            +

            Contents

            @@ -3548,11 +3760,11 @@

            Contents

            Drivers
            -

            Known Limitations

            +

            Known Limitations

            • None
            -

            Development Toolchains and Compilers

            +

            Development Toolchains and Compilers

            • IAR Embedded Workbench for ARM (EWARM) toolchain V7.20 + ST-LINK
            • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.10 + ST-LINK
            • diff --git a/stm32cube/stm32f1xx/soc/stm32f100xb.h b/stm32cube/stm32f1xx/soc/stm32f100xb.h index 52d47f73f..64844f38b 100644 --- a/stm32cube/stm32f1xx/soc/stm32f100xb.h +++ b/stm32cube/stm32f1xx/soc/stm32f100xb.h @@ -5968,5 +5968,3 @@ typedef struct #endif /* __STM32F100xB_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f100xe.h b/stm32cube/stm32f1xx/soc/stm32f100xe.h index 32713a6b7..aca340fa8 100644 --- a/stm32cube/stm32f1xx/soc/stm32f100xe.h +++ b/stm32cube/stm32f1xx/soc/stm32f100xe.h @@ -6583,5 +6583,3 @@ typedef struct #endif /* __STM32F100xE_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f101x6.h b/stm32cube/stm32f1xx/soc/stm32f101x6.h index dd530b0ea..154ddb48c 100644 --- a/stm32cube/stm32f1xx/soc/stm32f101x6.h +++ b/stm32cube/stm32f1xx/soc/stm32f101x6.h @@ -5311,5 +5311,3 @@ typedef struct #endif /* __STM32F101x6_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f101xb.h b/stm32cube/stm32f1xx/soc/stm32f101xb.h index 78ebc3683..3ffe6dece 100644 --- a/stm32cube/stm32f1xx/soc/stm32f101xb.h +++ b/stm32cube/stm32f1xx/soc/stm32f101xb.h @@ -5442,5 +5442,3 @@ typedef struct #endif /* __STM32F101xB_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f101xe.h b/stm32cube/stm32f1xx/soc/stm32f101xe.h index dd78553bc..a7488ce45 100644 --- a/stm32cube/stm32f1xx/soc/stm32f101xe.h +++ b/stm32cube/stm32f1xx/soc/stm32f101xe.h @@ -6499,5 +6499,3 @@ typedef struct #endif /* __STM32F101xE_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f101xg.h b/stm32cube/stm32f1xx/soc/stm32f101xg.h index 301e685d0..df038e905 100644 --- a/stm32cube/stm32f1xx/soc/stm32f101xg.h +++ b/stm32cube/stm32f1xx/soc/stm32f101xg.h @@ -6709,5 +6709,3 @@ typedef struct #endif /* __STM32F101xG_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f102x6.h b/stm32cube/stm32f1xx/soc/stm32f102x6.h index 8e51cb9f1..82324c3d1 100644 --- a/stm32cube/stm32f1xx/soc/stm32f102x6.h +++ b/stm32cube/stm32f1xx/soc/stm32f102x6.h @@ -6444,5 +6444,3 @@ typedef struct #endif /* __STM32F102x6_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f102xb.h b/stm32cube/stm32f1xx/soc/stm32f102xb.h index bc7d13db7..533687506 100644 --- a/stm32cube/stm32f1xx/soc/stm32f102xb.h +++ b/stm32cube/stm32f1xx/soc/stm32f102xb.h @@ -6566,5 +6566,3 @@ typedef struct #endif /* __STM32F102xB_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f103x6.h b/stm32cube/stm32f1xx/soc/stm32f103x6.h index 597177244..2df6fd95c 100644 --- a/stm32cube/stm32f1xx/soc/stm32f103x6.h +++ b/stm32cube/stm32f1xx/soc/stm32f103x6.h @@ -10105,5 +10105,3 @@ typedef struct #endif /* __STM32F103x6_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f103xb.h b/stm32cube/stm32f1xx/soc/stm32f103xb.h index 6ff8b2d3c..f7b488fdb 100644 --- a/stm32cube/stm32f1xx/soc/stm32f103xb.h +++ b/stm32cube/stm32f1xx/soc/stm32f103xb.h @@ -10236,5 +10236,3 @@ typedef struct #endif /* __STM32F103xB_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f103xe.h b/stm32cube/stm32f1xx/soc/stm32f103xe.h index faeb9fdc7..4ff358269 100644 --- a/stm32cube/stm32f1xx/soc/stm32f103xe.h +++ b/stm32cube/stm32f1xx/soc/stm32f103xe.h @@ -11763,5 +11763,3 @@ typedef struct #endif /* __STM32F103xE_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f103xg.h b/stm32cube/stm32f1xx/soc/stm32f103xg.h index 9d3db0fa7..e4152fe1d 100644 --- a/stm32cube/stm32f1xx/soc/stm32f103xg.h +++ b/stm32cube/stm32f1xx/soc/stm32f103xg.h @@ -11947,5 +11947,3 @@ typedef struct #endif /* __STM32F103xG_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f105xc.h b/stm32cube/stm32f1xx/soc/stm32f105xc.h index f042315c9..2ac428505 100644 --- a/stm32cube/stm32f1xx/soc/stm32f105xc.h +++ b/stm32cube/stm32f1xx/soc/stm32f105xc.h @@ -14337,5 +14337,3 @@ typedef struct #endif /* __STM32F105xC_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f107xc.h b/stm32cube/stm32f1xx/soc/stm32f107xc.h index 3a0fcc274..e6273cf23 100644 --- a/stm32cube/stm32f1xx/soc/stm32f107xc.h +++ b/stm32cube/stm32f1xx/soc/stm32f107xc.h @@ -15249,5 +15249,3 @@ typedef struct #endif /* __STM32F107xC_H */ - - diff --git a/stm32cube/stm32f1xx/soc/stm32f1xx.h b/stm32cube/stm32f1xx/soc/stm32f1xx.h index 5d4e0d84f..504934239 100644 --- a/stm32cube/stm32f1xx/soc/stm32f1xx.h +++ b/stm32cube/stm32f1xx/soc/stm32f1xx.h @@ -93,7 +93,7 @@ */ #define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ #define __STM32F1_CMSIS_VERSION_SUB1 (0x03) /*!< [23:16] sub1 version */ -#define __STM32F1_CMSIS_VERSION_SUB2 (0x04) /*!< [15:8] sub2 version */ +#define __STM32F1_CMSIS_VERSION_SUB2 (0x05) /*!< [15:8] sub2 version */ #define __STM32F1_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F1_CMSIS_VERSION ((__STM32F1_CMSIS_VERSION_MAIN << 24)\ |(__STM32F1_CMSIS_VERSION_SUB1 << 16)\ @@ -270,4 +270,3 @@ typedef enum - diff --git a/stm32cube/stm32f1xx/soc/system_stm32f1xx.c b/stm32cube/stm32f1xx/soc/system_stm32f1xx.c index 23a5a4e9a..4fff57208 100644 --- a/stm32cube/stm32f1xx/soc/system_stm32f1xx.c +++ b/stm32cube/stm32f1xx/soc/system_stm32f1xx.c @@ -138,7 +138,7 @@ is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ -uint32_t SystemCoreClock = 16000000; +uint32_t SystemCoreClock = 8000000; const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4}; From b8a89f05626d97b511078b40bfdfbe6d3dc58bc8 Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 14:56:43 +0200 Subject: [PATCH 03/11] stm32cube: update stm32f2 to cube version V1.9.5 Update Cube version for STM32F2xx series on https://github.com/STMicroelectronics from version v1.9.4 to version v1.9.5 Signed-off-by: Guillaume Gautier --- stm32cube/stm32f2xx/README | 11 +- .../drivers/include/Legacy/stm32_hal_legacy.h | 94 +++-- .../stm32f2xx/drivers/include/stm32f2xx_hal.h | 2 +- .../drivers/include/stm32f2xx_hal_can.h | 4 + .../drivers/include/stm32f2xx_hal_cortex.h | 7 +- .../drivers/include/stm32f2xx_hal_dcmi.h | 160 ++++--- .../drivers/include/stm32f2xx_hal_dcmi_ex.h | 12 +- .../drivers/include/stm32f2xx_hal_hash.h | 78 ++-- .../drivers/include/stm32f2xx_hal_nand.h | 2 +- .../drivers/include/stm32f2xx_hal_pccard.h | 13 +- .../drivers/include/stm32f2xx_hal_pcd.h | 2 +- .../drivers/include/stm32f2xx_hal_rtc.h | 2 +- .../drivers/include/stm32f2xx_hal_rtc_ex.h | 6 +- .../drivers/include/stm32f2xx_hal_spi.h | 46 +- .../drivers/include/stm32f2xx_hal_tim.h | 40 +- .../drivers/include/stm32f2xx_hal_usart.h | 2 +- .../drivers/include/stm32f2xx_hal_wwdg.h | 2 +- .../drivers/include/stm32f2xx_ll_adc.h | 23 +- .../drivers/include/stm32f2xx_ll_cortex.h | 2 +- .../drivers/include/stm32f2xx_ll_dac.h | 3 +- .../drivers/include/stm32f2xx_ll_fsmc.h | 153 +++---- .../drivers/include/stm32f2xx_ll_iwdg.h | 10 +- .../drivers/include/stm32f2xx_ll_rtc.h | 24 +- .../drivers/include/stm32f2xx_ll_sdmmc.h | 10 +- .../drivers/include/stm32f2xx_ll_spi.h | 143 ++++--- .../drivers/include/stm32f2xx_ll_tim.h | 25 +- .../drivers/include/stm32f2xx_ll_usart.h | 114 ++--- .../drivers/include/stm32f2xx_ll_usb.h | 99 +++-- .../drivers/include/stm32f2xx_ll_utils.h | 2 +- .../drivers/include/stm32f2xx_ll_wwdg.h | 12 +- .../stm32f2xx/drivers/src/stm32f2xx_hal.c | 4 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_can.c | 41 +- .../drivers/src/stm32f2xx_hal_cortex.c | 103 +++-- .../stm32f2xx/drivers/src/stm32f2xx_hal_dac.c | 5 +- .../drivers/src/stm32f2xx_hal_dac_ex.c | 1 - .../drivers/src/stm32f2xx_hal_dcmi.c | 268 +++++++----- .../drivers/src/stm32f2xx_hal_dcmi_ex.c | 1 - .../drivers/src/stm32f2xx_hal_flash.c | 5 - .../drivers/src/stm32f2xx_hal_flash_ex.c | 3 - .../drivers/src/stm32f2xx_hal_hash.c | 180 +++++--- .../stm32f2xx/drivers/src/stm32f2xx_hal_hcd.c | 38 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_i2c.c | 51 ++- .../stm32f2xx/drivers/src/stm32f2xx_hal_i2s.c | 78 ++-- .../drivers/src/stm32f2xx_hal_iwdg.c | 4 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_mmc.c | 2 +- .../drivers/src/stm32f2xx_hal_nand.c | 4 +- .../drivers/src/stm32f2xx_hal_pccard.c | 49 ++- .../stm32f2xx/drivers/src/stm32f2xx_hal_pcd.c | 35 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_rng.c | 7 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_rtc.c | 90 ++-- .../drivers/src/stm32f2xx_hal_rtc_ex.c | 24 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_sd.c | 21 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_spi.c | 397 +++++++++--------- .../drivers/src/stm32f2xx_hal_sram.c | 5 +- .../stm32f2xx/drivers/src/stm32f2xx_hal_tim.c | 62 +-- .../drivers/src/stm32f2xx_hal_tim_ex.c | 34 +- .../drivers/src/stm32f2xx_hal_uart.c | 61 ++- .../drivers/src/stm32f2xx_hal_usart.c | 7 +- .../drivers/src/stm32f2xx_hal_wwdg.c | 1 - .../stm32f2xx/drivers/src/stm32f2xx_ll_fsmc.c | 45 +- .../stm32f2xx/drivers/src/stm32f2xx_ll_spi.c | 9 +- .../stm32f2xx/drivers/src/stm32f2xx_ll_tim.c | 24 +- .../stm32f2xx/drivers/src/stm32f2xx_ll_usb.c | 105 ++--- .../drivers/src/stm32f2xx_ll_utils.c | 31 +- stm32cube/stm32f2xx/release_note.html | 366 +++++++++++++--- stm32cube/stm32f2xx/soc/stm32f2xx.h | 1 - 66 files changed, 1927 insertions(+), 1338 deletions(-) diff --git a/stm32cube/stm32f2xx/README b/stm32cube/stm32f2xx/README index 8a7eccb30..3a4746a8f 100644 --- a/stm32cube/stm32f2xx/README +++ b/stm32cube/stm32f2xx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubef2.html Status: - version v1.9.4 + version v1.9.5 Purpose: ST Microelectronics official MCU package for STM32F2 series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeF2 Commit: - a20e30a3c5ebd39621fb81c31bf3de141ed43dd2 + 63e02baff3d0c0c96cd9009aa2f9dc198a08e947 Maintained-by: External @@ -52,13 +52,6 @@ Patch List: -Added stm32cube/stm32f2xx/drivers/include/stm32_assert.h -Removed unused stm32cube/stm32f2xx/drivers/include/stm32_assert_template.h - *Wrap define UNUSED with an ifndef - This will prevent a compiler warning for the case the UNUSED macro - is already defined elsewhere in the project - Impacted files: - drivers/include/stm32f2xx_hal_def.h - ST Internal Reference: 136825 - *Fix to remove PAGESIZE definition which conflicts with POSIX Impacted files: drivers/include/Legacy/stm32_hal_legacy.h diff --git a/stm32cube/stm32f2xx/drivers/include/Legacy/stm32_hal_legacy.h b/stm32cube/stm32f2xx/drivers/include/Legacy/stm32_hal_legacy.h index a1fc260ec..8700eb1ea 100644 --- a/stm32cube/stm32f2xx/drivers/include/Legacy/stm32_hal_legacy.h +++ b/stm32cube/stm32f2xx/drivers/include/Legacy/stm32_hal_legacy.h @@ -37,16 +37,12 @@ extern "C" { #define AES_CLEARFLAG_CCF CRYP_CLEARFLAG_CCF #define AES_CLEARFLAG_RDERR CRYP_CLEARFLAG_RDERR #define AES_CLEARFLAG_WRERR CRYP_CLEARFLAG_WRERR -#if defined(STM32U5) || defined(STM32H7) || defined(STM32MP1) +#if defined(STM32H7) || defined(STM32MP1) #define CRYP_DATATYPE_32B CRYP_NO_SWAP #define CRYP_DATATYPE_16B CRYP_HALFWORD_SWAP #define CRYP_DATATYPE_8B CRYP_BYTE_SWAP #define CRYP_DATATYPE_1B CRYP_BIT_SWAP -#if defined(STM32U5) -#define CRYP_CCF_CLEAR CRYP_CLEAR_CCF -#define CRYP_ERR_CLEAR CRYP_CLEAR_RWEIF -#endif /* STM32U5 */ -#endif /* STM32U5 || STM32H7 || STM32MP1 */ +#endif /* STM32H7 || STM32MP1 */ /** * @} */ @@ -279,7 +275,7 @@ extern "C" { #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE -#if defined(STM32G4) || defined(STM32L5) || defined(STM32H7) || defined (STM32U5) +#if defined(STM32G4) || defined(STM32H7) || defined (STM32U5) #define DAC_CHIPCONNECT_DISABLE DAC_CHIPCONNECT_EXTERNAL #define DAC_CHIPCONNECT_ENABLE DAC_CHIPCONNECT_INTERNAL #endif @@ -476,7 +472,9 @@ extern "C" { #define TYPEPROGRAMDATA_FASTBYTE FLASH_TYPEPROGRAMDATA_FASTBYTE #define TYPEPROGRAMDATA_FASTHALFWORD FLASH_TYPEPROGRAMDATA_FASTHALFWORD #define TYPEPROGRAMDATA_FASTWORD FLASH_TYPEPROGRAMDATA_FASTWORD +#if !defined(STM32F2) && !defined(STM32F4) && !defined(STM32F7) && !defined(STM32H7) /* #define PAGESIZE FLASH_PAGE_SIZE */ +#endif /* STM32F2 && STM32F4 && STM32F7 && STM32H7 */ #define TYPEPROGRAM_FASTBYTE FLASH_TYPEPROGRAM_BYTE #define TYPEPROGRAM_FASTHALFWORD FLASH_TYPEPROGRAM_HALFWORD #define TYPEPROGRAM_FASTWORD FLASH_TYPEPROGRAM_WORD @@ -552,6 +550,16 @@ extern "C" { #define OB_SRAM134_RST_ERASE OB_SRAM_RST_ERASE #define OB_SRAM134_RST_NOT_ERASE OB_SRAM_RST_NOT_ERASE #endif /* STM32U5 */ +#if defined(STM32U0) +#define OB_USER_nRST_STOP OB_USER_NRST_STOP +#define OB_USER_nRST_STDBY OB_USER_NRST_STDBY +#define OB_USER_nRST_SHDW OB_USER_NRST_SHDW +#define OB_USER_nBOOT_SEL OB_USER_NBOOT_SEL +#define OB_USER_nBOOT0 OB_USER_NBOOT0 +#define OB_USER_nBOOT1 OB_USER_NBOOT1 +#define OB_nBOOT0_RESET OB_NBOOT0_RESET +#define OB_nBOOT0_SET OB_NBOOT0_SET +#endif /* STM32U0 */ /** * @} @@ -800,6 +808,21 @@ extern "C" { #define GPIO_AF0_S2DSTOP GPIO_AF0_SRDSTOP #define GPIO_AF11_LPGPIO GPIO_AF11_LPGPIO1 #endif /* STM32U5 */ + +#if defined(STM32WBA) +#define GPIO_AF11_RF_ANTSW0 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW1 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO1 GPIO_AF11_RF +#define GPIO_AF11_RF_IO2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO3 GPIO_AF11_RF +#define GPIO_AF11_RF_IO4 GPIO_AF11_RF +#define GPIO_AF11_RF_IO5 GPIO_AF11_RF +#define GPIO_AF11_RF_IO6 GPIO_AF11_RF +#define GPIO_AF11_RF_IO7 GPIO_AF11_RF +#define GPIO_AF11_RF_IO8 GPIO_AF11_RF +#define GPIO_AF11_RF_IO9 GPIO_AF11_RF +#endif /* STM32WBA */ /** * @} */ @@ -1243,10 +1266,10 @@ extern "C" { #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 -#if defined(STM32H5) +#if defined(STM32H5) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_BKP_SRAM TAMP_DEVICESECRETS_ERASE_BKPSRAM -#endif /* STM32H5 */ +#endif /* STM32H5 || STM32H7RS */ #if defined(STM32WBA) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE @@ -1258,10 +1281,10 @@ extern "C" { #define TAMP_SECRETDEVICE_ERASE_ALL TAMP_DEVICESECRETS_ERASE_ALL #endif /* STM32WBA */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_DISABLE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_ENABLE TAMP_SECRETDEVICE_ERASE_ALL -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ #if defined(STM32F7) #define RTC_TAMPCR_TAMPXE RTC_TAMPER_ENABLE_BITS_MASK @@ -1599,6 +1622,8 @@ extern "C" { #define ETH_MAC_SMALL_FIFO_RW_ACTIVE 0x00000006U /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE 0x00000001U /* MAC MII receive protocol engine active */ +#define ETH_TxPacketConfig ETH_TxPacketConfigTypeDef /* Transmit Packet Configuration structure definition */ + /** * @} */ @@ -1809,7 +1834,7 @@ extern "C" { #define HAL_FMPI2CEx_AnalogFilter_Config HAL_FMPI2CEx_ConfigAnalogFilter #define HAL_FMPI2CEx_DigitalFilter_Config HAL_FMPI2CEx_ConfigDigitalFilter -#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) ((cmd == ENABLE)? \ +#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd) == ENABLE)? \ HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): \ HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) @@ -1991,12 +2016,12 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Functions HAL RTC Aliased Functions maintained for legacy purpose * @{ */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define HAL_RTCEx_SetBoothardwareKey HAL_RTCEx_LockBootHardwareKey #define HAL_RTCEx_BKUPBlock_Enable HAL_RTCEx_BKUPBlock #define HAL_RTCEx_BKUPBlock_Disable HAL_RTCEx_BKUPUnblock #define HAL_RTCEx_Erase_SecretDev_Conf HAL_RTCEx_ConfigEraseDeviceSecrets -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ /** * @} @@ -2311,8 +2336,8 @@ extern "C" { #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F302xE) || defined(STM32F302xC) +#endif +#if defined(STM32F302xE) || defined(STM32F302xC) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_ENABLE_RISING_EDGE() : \ @@ -2345,8 +2370,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) +#endif +#if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP3) ? __HAL_COMP_COMP3_EXTI_ENABLE_RISING_EDGE() : \ @@ -2403,8 +2428,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP5) ? __HAL_COMP_COMP5_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP6) ? __HAL_COMP_COMP6_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP7_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F373xC) ||defined(STM32F378xx) +#endif +#if defined(STM32F373xC) ||defined(STM32F378xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE() : \ @@ -2421,7 +2446,7 @@ extern "C" { __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) -# endif +#endif #else #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) @@ -2723,6 +2748,12 @@ extern "C" { #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET +#if defined(STM32C0) +#define __HAL_RCC_APB1_FORCE_RESET __HAL_RCC_APB1_GRP1_FORCE_RESET +#define __HAL_RCC_APB1_RELEASE_RESET __HAL_RCC_APB1_GRP1_RELEASE_RESET +#define __HAL_RCC_APB2_FORCE_RESET __HAL_RCC_APB1_GRP2_FORCE_RESET +#define __HAL_RCC_APB2_RELEASE_RESET __HAL_RCC_APB1_GRP2_RELEASE_RESET +#endif /* STM32C0 */ #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET @@ -3646,8 +3677,12 @@ extern "C" { #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 +#if defined(STM32U0) +#define RCC_SYSCLKSOURCE_STATUS_PLLR RCC_SYSCLKSOURCE_STATUS_PLLCLK +#endif + #if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) || \ - defined(STM32WL) || defined(STM32C0) + defined(STM32WL) || defined(STM32C0) || defined(STM32H7RS) || defined(STM32U0) #define RCC_RTCCLKSOURCE_NO_CLK RCC_RTCCLKSOURCE_NONE #else #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK @@ -3749,8 +3784,10 @@ extern "C" { #define __HAL_RCC_GET_DFSDM_SOURCE __HAL_RCC_GET_DFSDM1_SOURCE #define RCC_DFSDM1CLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 #define RCC_SWPMI1CLKSOURCE_PCLK RCC_SWPMI1CLKSOURCE_PCLK1 +#if !defined(STM32U0) #define RCC_LPTIM1CLKSOURCE_PCLK RCC_LPTIM1CLKSOURCE_PCLK1 #define RCC_LPTIM2CLKSOURCE_PCLK RCC_LPTIM2CLKSOURCE_PCLK1 +#endif #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM1AUDIOCLKSOURCE_I2S1 #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM1AUDIOCLKSOURCE_I2S2 @@ -3894,9 +3931,9 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Macros HAL RTC Aliased Macros maintained for legacy purpose * @{ */ -#if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || \ - defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || \ - defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) +#if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || defined (STM32L4P5xx)|| \ + defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || defined (STM32WBA) || \ + defined (STM32H5) || defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) #else #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #endif @@ -3932,7 +3969,9 @@ extern "C" { #endif /* STM32F1 */ #if defined (STM32F0) || defined (STM32F2) || defined (STM32F3) || defined (STM32F4) || defined (STM32F7) || \ - defined (STM32L0) || defined (STM32L1) + defined (STM32H7) || \ + defined (STM32L0) || defined (STM32L1) || \ + defined (STM32WB) #define __HAL_RTC_TAMPER_GET_IT __HAL_RTC_TAMPER_GET_FLAG #endif @@ -4217,6 +4256,9 @@ extern "C" { #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_BREAKINPUTSOURCE_DFSDM TIM_BREAKINPUTSOURCE_DFSDM1 + +#define TIM_OCMODE_ASSYMETRIC_PWM1 TIM_OCMODE_ASYMMETRIC_PWM1 +#define TIM_OCMODE_ASSYMETRIC_PWM2 TIM_OCMODE_ASYMMETRIC_PWM2 /** * @} */ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal.h index 929ccfb4d..678b77bc9 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal.h @@ -184,7 +184,7 @@ extern HAL_TickFreqTypeDef uwTickFreq; */ /* Peripheral Control functions ************************************************/ void HAL_IncTick(void); -void HAL_Delay(__IO uint32_t Delay); +void HAL_Delay(uint32_t Delay); uint32_t HAL_GetTick(void); uint32_t HAL_GetTickPrio(void); HAL_StatusTypeDef HAL_SetTickFreq(HAL_TickFreqTypeDef Freq); diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_can.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_can.h index 8022d290f..1ac619950 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_can.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_can.h @@ -209,7 +209,11 @@ typedef struct /** * @brief CAN handle Structure definition */ +#if USE_HAL_CAN_REGISTER_CALLBACKS == 1 typedef struct __CAN_HandleTypeDef +#else +typedef struct +#endif /* USE_HAL_CAN_REGISTER_CALLBACKS */ { CAN_TypeDef *Instance; /*!< Register base address */ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_cortex.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_cortex.h index 429565367..5a0cd623d 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_cortex.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_cortex.h @@ -9,8 +9,8 @@ * Copyright (c) 2017 STMicroelectronics. * All rights reserved. * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** @@ -285,6 +285,8 @@ void HAL_SYSTICK_Callback(void); #if (__MPU_PRESENT == 1U) void HAL_MPU_Enable(uint32_t MPU_Control); void HAL_MPU_Disable(void); +void HAL_MPU_EnableRegion(uint32_t RegionNumber); +void HAL_MPU_DisableRegion(uint32_t RegionNumber); void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ /** @@ -405,4 +407,3 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __STM32F2xx_HAL_CORTEX_H */ - diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi.h index c79293119..888220276 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi.h @@ -6,13 +6,12 @@ ****************************************************************************** * @attention * - *

              © Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

              + * Copyright (c) 2016 STMicroelectronics. + * All rights reserved. * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ @@ -57,7 +56,7 @@ typedef enum } HAL_DCMI_StateTypeDef; /** - * @brief DCMIEx Embedded Synchronisation CODE Init structure definition + * @brief DCMI Embedded Synchronisation CODE Init structure definition */ typedef struct { @@ -68,7 +67,7 @@ typedef struct } DCMI_CodesInitTypeDef; /** - * @brief DCMI Embedded Synchronisation CODE Init structure definition + * @brief DCMI Embedded Synchronisation UNMASK Init structure definition */ typedef struct { @@ -110,7 +109,11 @@ typedef struct /** * @brief DCMI handle Structure definition */ -typedef struct __DCMI_HandleTypeDef +#if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) +typedef struct __DCMI_HandleTypeDef +#else +typedef struct +#endif /* USE_HAL_DCMI_REGISTER_CALLBACKS */ { DCMI_TypeDef *Instance; /*!< DCMI Register base address */ @@ -131,6 +134,7 @@ typedef struct __DCMI_HandleTypeDef DMA_HandleTypeDef *DMA_Handle; /*!< Pointer to the DMA handler */ __IO uint32_t ErrorCode; /*!< DCMI Error code */ + #if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) void (* FrameEventCallback)(struct __DCMI_HandleTypeDef *hdcmi); /*!< DCMI Frame Event Callback */ void (* VsyncEventCallback)(struct __DCMI_HandleTypeDef *hdcmi); /*!< DCMI Vsync Event Callback */ @@ -142,6 +146,9 @@ typedef struct __DCMI_HandleTypeDef } DCMI_HandleTypeDef; #if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) +/** + * @brief HAL DCMI Callback ID enumeration definition + */ typedef enum { HAL_DCMI_FRAME_EVENT_CB_ID = 0x00U, /*!< DCMI Frame Event Callback ID */ @@ -153,7 +160,10 @@ typedef enum } HAL_DCMI_CallbackIDTypeDef; -typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); +/** + * @brief HAL DCMI Callback pointer definition + */ +typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /*!< pointer to a DCMI callback function */ #endif /* USE_HAL_DCMI_REGISTER_CALLBACKS */ @@ -169,14 +179,14 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Error_Code DCMI Error Code * @{ */ -#define HAL_DCMI_ERROR_NONE ((uint32_t)0x00000000U) /*!< No error */ -#define HAL_DCMI_ERROR_OVR ((uint32_t)0x00000001U) /*!< Overrun error */ -#define HAL_DCMI_ERROR_SYNC ((uint32_t)0x00000002U) /*!< Synchronization error */ -#define HAL_DCMI_ERROR_TIMEOUT ((uint32_t)0x00000020U) /*!< Timeout error */ -#define HAL_DCMI_ERROR_DMA ((uint32_t)0x00000040U) /*!< DMA error */ +#define HAL_DCMI_ERROR_NONE (0x00000000U) /*!< No error */ +#define HAL_DCMI_ERROR_OVR (0x00000001U) /*!< Overrun error */ +#define HAL_DCMI_ERROR_SYNC (0x00000002U) /*!< Synchronization error */ +#define HAL_DCMI_ERROR_TIMEOUT (0x00000020U) /*!< Timeout error */ +#define HAL_DCMI_ERROR_DMA (0x00000040U) /*!< DMA error */ #if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) -#define HAL_DCMI_ERROR_INVALID_CALLBACK ((uint32_t)0x00000080U) /*!< Invalid callback error */ -#endif +#define HAL_DCMI_ERROR_INVALID_CALLBACK (0x00000080U) /*!< Invalid callback error */ +#endif /* USE_HAL_DCMI_REGISTER_CALLBACKS */ /** * @} */ @@ -184,10 +194,11 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Capture_Mode DCMI Capture Mode * @{ */ -#define DCMI_MODE_CONTINUOUS ((uint32_t)0x00000000U) /*!< The received data are transferred continuously - into the destination memory through the DMA */ -#define DCMI_MODE_SNAPSHOT ((uint32_t)DCMI_CR_CM) /*!< Once activated, the interface waits for the start of - frame and then transfers a single frame through the DMA */ +#define DCMI_MODE_CONTINUOUS (0x00000000U) /*!< The received data are transferred continuously + into the destination memory through the DMA */ +#define DCMI_MODE_SNAPSHOT ((uint32_t)DCMI_CR_CM) /*!< Once activated, the interface waits for the start of + frame and then transfers a single frame + through the DMA */ /** * @} */ @@ -195,10 +206,10 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Synchronization_Mode DCMI Synchronization Mode * @{ */ -#define DCMI_SYNCHRO_HARDWARE ((uint32_t)0x00000000U) /*!< Hardware synchronization data capture (frame/line start/stop) - is synchronized with the HSYNC/VSYNC signals */ -#define DCMI_SYNCHRO_EMBEDDED ((uint32_t)DCMI_CR_ESS) /*!< Embedded synchronization data capture is synchronized with - synchronization codes embedded in the data flow */ +#define DCMI_SYNCHRO_HARDWARE (0x00000000U) /*!< Hardware synchronization data capture (frame/line start/stop) + is synchronized with the HSYNC/VSYNC signals */ +#define DCMI_SYNCHRO_EMBEDDED ((uint32_t)DCMI_CR_ESS) /*!< Embedded synchronization data capture is synchronized + with synchronization codes embedded in the data flow */ /** * @} @@ -207,7 +218,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_PIXCK_Polarity DCMI PIXCK Polarity * @{ */ -#define DCMI_PCKPOLARITY_FALLING ((uint32_t)0x00000000U) /*!< Pixel clock active on Falling edge */ +#define DCMI_PCKPOLARITY_FALLING (0x00000000U) /*!< Pixel clock active on Falling edge */ #define DCMI_PCKPOLARITY_RISING ((uint32_t)DCMI_CR_PCKPOL) /*!< Pixel clock active on Rising edge */ /** @@ -217,7 +228,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_VSYNC_Polarity DCMI VSYNC Polarity * @{ */ -#define DCMI_VSPOLARITY_LOW ((uint32_t)0x00000000U) /*!< Vertical synchronization active Low */ +#define DCMI_VSPOLARITY_LOW (0x00000000U) /*!< Vertical synchronization active Low */ #define DCMI_VSPOLARITY_HIGH ((uint32_t)DCMI_CR_VSPOL) /*!< Vertical synchronization active High */ /** @@ -227,7 +238,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_HSYNC_Polarity DCMI HSYNC Polarity * @{ */ -#define DCMI_HSPOLARITY_LOW ((uint32_t)0x00000000U) /*!< Horizontal synchronization active Low */ +#define DCMI_HSPOLARITY_LOW (0x00000000U) /*!< Horizontal synchronization active Low */ #define DCMI_HSPOLARITY_HIGH ((uint32_t)DCMI_CR_HSPOL) /*!< Horizontal synchronization active High */ /** @@ -237,7 +248,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_MODE_JPEG DCMI MODE JPEG * @{ */ -#define DCMI_JPEG_DISABLE ((uint32_t)0x00000000U) /*!< Mode JPEG Disabled */ +#define DCMI_JPEG_DISABLE (0x00000000U) /*!< Mode JPEG Disabled */ #define DCMI_JPEG_ENABLE ((uint32_t)DCMI_CR_JPEG) /*!< Mode JPEG Enabled */ /** @@ -247,7 +258,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Capture_Rate DCMI Capture Rate * @{ */ -#define DCMI_CR_ALL_FRAME ((uint32_t)0x00000000U) /*!< All frames are captured */ +#define DCMI_CR_ALL_FRAME (0x00000000U) /*!< All frames are captured */ #define DCMI_CR_ALTERNATE_2_FRAME ((uint32_t)DCMI_CR_FCRC_0) /*!< Every alternate frame captured */ #define DCMI_CR_ALTERNATE_4_FRAME ((uint32_t)DCMI_CR_FCRC_1) /*!< One frame in 4 frames captured */ @@ -258,10 +269,11 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Extended_Data_Mode DCMI Extended Data Mode * @{ */ -#define DCMI_EXTEND_DATA_8B ((uint32_t)0x00000000U) /*!< Interface captures 8-bit data on every pixel clock */ -#define DCMI_EXTEND_DATA_10B ((uint32_t)DCMI_CR_EDM_0) /*!< Interface captures 10-bit data on every pixel clock */ -#define DCMI_EXTEND_DATA_12B ((uint32_t)DCMI_CR_EDM_1) /*!< Interface captures 12-bit data on every pixel clock */ -#define DCMI_EXTEND_DATA_14B ((uint32_t)(DCMI_CR_EDM_0 | DCMI_CR_EDM_1)) /*!< Interface captures 14-bit data on every pixel clock */ +#define DCMI_EXTEND_DATA_8B (0x00000000U) /*!< Interface captures 8-bit data on every pixel clock */ +#define DCMI_EXTEND_DATA_10B ((uint32_t)DCMI_CR_EDM_0) /*!< Interface captures 10-bit data on every pixel clock */ +#define DCMI_EXTEND_DATA_12B ((uint32_t)DCMI_CR_EDM_1) /*!< Interface captures 12-bit data on every pixel clock */ +#define DCMI_EXTEND_DATA_14B ((uint32_t)(DCMI_CR_EDM_0 |\ + DCMI_CR_EDM_1)) /*!< Interface captures 14-bit data on every pixel clock */ /** * @} @@ -270,7 +282,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Window_Coordinate DCMI Window Coordinate * @{ */ -#define DCMI_WINDOW_COORDINATE ((uint32_t)0x3FFFU) /*!< Window coordinate */ +#define DCMI_WINDOW_COORDINATE (0x3FFFU) /*!< Window coordinate */ /** * @} @@ -279,7 +291,7 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Window_Height DCMI Window Height * @{ */ -#define DCMI_WINDOW_HEIGHT ((uint32_t)0x1FFFU) /*!< Window Height */ +#define DCMI_WINDOW_HEIGHT (0x1FFFU) /*!< Window Height */ /** * @} @@ -304,9 +316,11 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** * @brief DCMI SR register */ -#define DCMI_FLAG_HSYNC ((uint32_t)DCMI_SR_INDEX|DCMI_SR_HSYNC) /*!< HSYNC pin state (active line / synchronization between lines) */ -#define DCMI_FLAG_VSYNC ((uint32_t)DCMI_SR_INDEX|DCMI_SR_VSYNC) /*!< VSYNC pin state (active frame / synchronization between frames) */ -#define DCMI_FLAG_FNE ((uint32_t)DCMI_SR_INDEX|DCMI_SR_FNE) /*!< FIFO not empty flag */ +#define DCMI_FLAG_HSYNC ((uint32_t)DCMI_SR_INDEX|DCMI_SR_HSYNC) /*!< HSYNC pin state (active line / synchronization + between lines) */ +#define DCMI_FLAG_VSYNC ((uint32_t)DCMI_SR_INDEX|DCMI_SR_VSYNC) /*!< VSYNC pin state (active frame / synchronization + between frames) */ +#define DCMI_FLAG_FNE ((uint32_t)DCMI_SR_INDEX|DCMI_SR_FNE) /*!< FIFO not empty flag */ /** * @brief DCMI RIS register */ @@ -318,7 +332,8 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); /** * @brief DCMI MIS register */ -#define DCMI_FLAG_FRAMEMI ((uint32_t)DCMI_MIS_INDEX|DCMI_MIS_FRAME_MIS) /*!< DCMI Frame capture complete masked interrupt status */ +#define DCMI_FLAG_FRAMEMI ((uint32_t)DCMI_MIS_INDEX|DCMI_MIS_FRAME_MIS) /*!< DCMI Frame capture complete masked + interrupt status */ #define DCMI_FLAG_OVRMI ((uint32_t)DCMI_MIS_INDEX|DCMI_MIS_OVR_MIS ) /*!< DCMI Overrun masked interrupt status */ #define DCMI_FLAG_ERRMI ((uint32_t)DCMI_MIS_INDEX|DCMI_MIS_ERR_MIS ) /*!< DCMI Synchronization error masked interrupt status */ #define DCMI_FLAG_VSYNCMI ((uint32_t)DCMI_MIS_INDEX|DCMI_MIS_VSYNC_MIS) /*!< DCMI VSYNC masked interrupt status */ @@ -340,11 +355,15 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); * @param __HANDLE__ specifies the DCMI handle. * @retval None */ -#define __HAL_DCMI_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->State = HAL_DCMI_STATE_RESET; \ - (__HANDLE__)->MspInitCallback = NULL; \ - (__HANDLE__)->MspDeInitCallback = NULL; \ - } while(0) +#if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) +#define __HAL_DCMI_RESET_HANDLE_STATE(__HANDLE__) do{ \ + (__HANDLE__)->State = HAL_DCMI_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) +#else +#define __HAL_DCMI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DCMI_STATE_RESET) +#endif /* USE_HAL_DCMI_REGISTER_CALLBACKS */ /** * @brief Enable the DCMI. @@ -382,8 +401,9 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); * @retval The state of FLAG. */ #define __HAL_DCMI_GET_FLAG(__HANDLE__, __FLAG__)\ -((((__FLAG__) & (DCMI_SR_INDEX|DCMI_MIS_INDEX)) == 0x0)? ((__HANDLE__)->Instance->RIS & (__FLAG__)) :\ - (((__FLAG__) & DCMI_SR_INDEX) == 0x0)? ((__HANDLE__)->Instance->MIS & (__FLAG__)) : ((__HANDLE__)->Instance->SR & (__FLAG__))) + ((((__FLAG__) & (DCMI_SR_INDEX|DCMI_MIS_INDEX)) == 0x0)? ((__HANDLE__)->Instance->RIS & (__FLAG__)) :\ + (((__FLAG__) & DCMI_SR_INDEX) == 0x0)? ((__HANDLE__)->Instance->MIS & (__FLAG__)) :\ + ((__HANDLE__)->Instance->SR & (__FLAG__))) /** * @brief Clear the DCMI pending flags. @@ -451,8 +471,8 @@ typedef void (*pDCMI_CallbackTypeDef)(DCMI_HandleTypeDef *hdcmi); */ /** @addtogroup DCMI_Exported_Functions_Group1 Initialization and Configuration functions - * @{ - */ + * @{ + */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_DCMI_Init(DCMI_HandleTypeDef *hdcmi); HAL_StatusTypeDef HAL_DCMI_DeInit(DCMI_HandleTypeDef *hdcmi); @@ -461,7 +481,8 @@ void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef *hdcmi); /* Callbacks Register/UnRegister functions ***********************************/ #if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) -HAL_StatusTypeDef HAL_DCMI_RegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_CallbackIDTypeDef CallbackID, pDCMI_CallbackTypeDef pCallback); +HAL_StatusTypeDef HAL_DCMI_RegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_CallbackIDTypeDef CallbackID, + pDCMI_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_DCMI_UnRegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_CallbackIDTypeDef CallbackID); #endif /* USE_HAL_DCMI_REGISTER_CALLBACKS */ /** @@ -469,8 +490,8 @@ HAL_StatusTypeDef HAL_DCMI_UnRegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCM */ /** @addtogroup DCMI_Exported_Functions_Group2 IO operation functions - * @{ - */ + * @{ + */ /* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef *hdcmi, uint32_t DCMI_Mode, uint32_t pData, uint32_t Length); HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef *hdcmi); @@ -486,24 +507,25 @@ void HAL_DCMI_IRQHandler(DCMI_HandleTypeDef *hdcmi); */ /** @addtogroup DCMI_Exported_Functions_Group3 Peripheral Control functions - * @{ - */ + * @{ + */ /* Peripheral Control functions ***********************************************/ -HAL_StatusTypeDef HAL_DCMI_ConfigCrop(DCMI_HandleTypeDef *hdcmi, uint32_t X0, uint32_t Y0, uint32_t XSize, uint32_t YSize); +HAL_StatusTypeDef HAL_DCMI_ConfigCrop(DCMI_HandleTypeDef *hdcmi, uint32_t X0, uint32_t Y0, uint32_t XSize, + uint32_t YSize); HAL_StatusTypeDef HAL_DCMI_EnableCrop(DCMI_HandleTypeDef *hdcmi); HAL_StatusTypeDef HAL_DCMI_DisableCrop(DCMI_HandleTypeDef *hdcmi); -HAL_StatusTypeDef HAL_DCMI_ConfigSyncUnmask(DCMI_HandleTypeDef *hdcmi, DCMI_SyncUnmaskTypeDef *SyncUnmask); +HAL_StatusTypeDef HAL_DCMI_ConfigSyncUnmask(DCMI_HandleTypeDef *hdcmi, const DCMI_SyncUnmaskTypeDef *SyncUnmask); /** * @} */ /** @addtogroup DCMI_Exported_Functions_Group4 Peripheral State functions - * @{ - */ + * @{ + */ /* Peripheral State functions *************************************************/ -HAL_DCMI_StateTypeDef HAL_DCMI_GetState(DCMI_HandleTypeDef *hdcmi); -uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi); +HAL_DCMI_StateTypeDef HAL_DCMI_GetState(const DCMI_HandleTypeDef *hdcmi); +uint32_t HAL_DCMI_GetError(const DCMI_HandleTypeDef *hdcmi); /** * @} */ @@ -518,8 +540,24 @@ uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi); /** @defgroup DCMI_Private_Constants DCMI Private Constants * @{ */ +/** @defgroup DCMI_MIS_INDEX DCMI Mis Index + * @{ + */ #define DCMI_MIS_INDEX ((uint32_t)0x1000) /*!< DCMI MIS register index */ + +/** + * @} + */ + +/** @defgroup DCMI_SR_INDEX DCMI SR Index + * @{ + */ #define DCMI_SR_INDEX ((uint32_t)0x2000) /*!< DCMI SR register index */ + +/** + * @} + */ + /** * @} */ @@ -584,5 +622,3 @@ uint32_t HAL_DCMI_GetError(DCMI_HandleTypeDef *hdcmi); #endif #endif /* STM32F2xx_HAL_DCMI_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi_ex.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi_ex.h index 9d917e6f1..44502a374 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi_ex.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_dcmi_ex.h @@ -6,13 +6,12 @@ ****************************************************************************** * @attention * - *

              © Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

              + * Copyright (c) 2016 STMicroelectronics. + * All rights reserved. * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ @@ -34,4 +33,3 @@ #endif /* __STM32F2xx_HAL_DCMI_H */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_hash.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_hash.h index 5712f532d..c14670185 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_hash.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_hash.h @@ -117,13 +117,13 @@ typedef struct { HASH_InitTypeDef Init; /*!< HASH required parameters */ - uint8_t *pHashInBuffPtr; /*!< Pointer to input buffer */ + uint8_t const *pHashInBuffPtr; /*!< Pointer to input buffer */ uint8_t *pHashOutBuffPtr; /*!< Pointer to output buffer (digest) */ uint8_t *pHashKeyBuffPtr; /*!< Pointer to key buffer (HMAC only) */ - uint8_t *pHashMsgBuffPtr; /*!< Pointer to message buffer (HMAC only) */ + uint8_t const *pHashMsgBuffPtr; /*!< Pointer to message buffer (HMAC only) */ uint32_t HashBuffSize; /*!< Size of buffer to be processed */ @@ -434,15 +434,17 @@ HAL_StatusTypeDef HAL_HASH_UnRegisterCallback(HASH_HandleTypeDef *hhash, HAL_HAS /* HASH processing using polling *********************************************/ -HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); -HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer, uint32_t Timeout); -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer, uint32_t Timeout); @@ -455,15 +457,15 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *p */ /* HASH processing using IT **************************************************/ -HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer); -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer); -HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer); -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer); void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash); /** @@ -475,9 +477,9 @@ void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash); */ /* HASH processing using DMA *************************************************/ -HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); -HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); HAL_StatusTypeDef HAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); /** @@ -489,9 +491,11 @@ HAL_StatusTypeDef HAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBu */ /* HASH-MAC processing using polling *****************************************/ -HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); -HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout); /** @@ -502,9 +506,9 @@ HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuff * @{ */ -HAL_StatusTypeDef HAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer); -HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer); /** @@ -516,8 +520,8 @@ HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pIn */ /* HASH-HMAC processing using DMA ********************************************/ -HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); -HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); +HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); /** * @} @@ -529,13 +533,13 @@ HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pIn /* Peripheral State methods **************************************************/ -HAL_HASH_StateTypeDef HAL_HASH_GetState(HASH_HandleTypeDef *hhash); -HAL_StatusTypeDef HAL_HASH_GetStatus(HASH_HandleTypeDef *hhash); +HAL_HASH_StateTypeDef HAL_HASH_GetState(const HASH_HandleTypeDef *hhash); +HAL_StatusTypeDef HAL_HASH_GetStatus(const HASH_HandleTypeDef *hhash); void HAL_HASH_ContextSaving(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer); void HAL_HASH_ContextRestoring(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer); void HAL_HASH_SwFeed_ProcessSuspend(HASH_HandleTypeDef *hhash); HAL_StatusTypeDef HAL_HASH_DMAFeed_ProcessSuspend(HASH_HandleTypeDef *hhash); -uint32_t HAL_HASH_GetError(HASH_HandleTypeDef *hhash); +uint32_t HAL_HASH_GetError(const HASH_HandleTypeDef *hhash); /** * @} @@ -552,19 +556,27 @@ uint32_t HAL_HASH_GetError(HASH_HandleTypeDef *hhash); */ /* Private functions */ -HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout, uint32_t Algorithm); -HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); -HAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); -HAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm); +HAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm); +HAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Algorithm); -HAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); +HAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm); HAL_StatusTypeDef HASH_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, uint32_t Timeout); -HAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout, uint32_t Algorithm); -HAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Algorithm); -HAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm); +HAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm); /** * @} diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_nand.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_nand.h index 9dca732b0..75289858a 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_nand.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_nand.h @@ -193,7 +193,7 @@ HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FSMC_NAND_PCC_Timing FSMC_NAND_PCC_TimingTypeDef *AttSpace_Timing); HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand); -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig); +HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, const NAND_DeviceConfigTypeDef *pDeviceConfig); HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pccard.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pccard.h index ef7df02c0..f9e23b996 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pccard.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pccard.h @@ -67,7 +67,7 @@ typedef enum typedef struct __PCCARD_HandleTypeDef #else typedef struct -#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ { FSMC_PCCARD_TypeDef *Instance; /*!< Register base address for PCCARD device */ @@ -81,7 +81,7 @@ typedef struct void (* MspInitCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD Msp Init callback */ void (* MspDeInitCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD Msp DeInit callback */ void (* ItCallback)(struct __PCCARD_HandleTypeDef *hpccard); /*!< PCCARD IT callback */ -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ } PCCARD_HandleTypeDef; #if (USE_HAL_PCCARD_REGISTER_CALLBACKS == 1) @@ -99,7 +99,7 @@ typedef enum * @brief HAL PCCARD Callback pointer definition */ typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} */ @@ -121,7 +121,7 @@ typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); } while(0) #else #define __HAL_PCCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_PCCARD_STATE_RESET) -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} */ @@ -136,7 +136,8 @@ typedef void (*pPCCARD_CallbackTypeDef)(PCCARD_HandleTypeDef *hpccard); */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FSMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, - FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); + FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, + FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming); HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspInit(PCCARD_HandleTypeDef *hpccard); void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard); @@ -164,7 +165,7 @@ HAL_StatusTypeDef HAL_PCCARD_RegisterCallback(PCCARD_HandleTypeDef *hpccard, HA pPCCARD_CallbackTypeDef pCallback); HAL_StatusTypeDef HAL_PCCARD_UnRegisterCallback(PCCARD_HandleTypeDef *hpccard, HAL_PCCARD_CallbackIDTypeDef CallbackId); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} */ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pcd.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pcd.h index 173d4d22b..247c3ee87 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pcd.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_pcd.h @@ -354,7 +354,7 @@ HAL_StatusTypeDef HAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd); #if defined (USB_OTG_FS) || defined (USB_OTG_HS) -HAL_StatusTypeDef HAL_PCD_SetTestMode(PCD_HandleTypeDef *hpcd, uint8_t testmode); +HAL_StatusTypeDef HAL_PCD_SetTestMode(const PCD_HandleTypeDef *hpcd, uint8_t testmode); #endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ uint32_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef const *hpcd, uint8_t ep_addr); diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc.h index e975bdcfe..e93c9caf8 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc.h @@ -726,7 +726,7 @@ HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); #define RTC_TIMEOUT_VALUE 1000U -#define RTC_EXTI_LINE_ALARM_EVENT EXTI_IMR_MR17 /*!< External interrupt line 17 Connected to the RTC Alarm event */ +#define RTC_EXTI_LINE_ALARM_EVENT EXTI_IMR_MR17 /*!< External interrupt line 17 connected to the RTC Alarm event */ /** * @} */ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc_ex.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc_ex.h index b72c22f9d..520cf31e6 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc_ex.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_rtc_ex.h @@ -527,13 +527,13 @@ typedef struct * @brief Enable event on the RTC Tamper and Timestamp associated EXTI line. * @retval None. */ -#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) +#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_EVENT() (EXTI->EMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Disable event on the RTC Tamper and Timestamp associated EXTI line. * @retval None. */ -#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) +#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_EVENT() (EXTI->EMR &= ~RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT) /** * @brief Enable falling edge trigger on the RTC Tamper and Timestamp associated EXTI line. @@ -715,7 +715,7 @@ HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); * @{ */ /* Extended RTC features functions *******************************************/ -void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_spi.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_spi.h index 68503e4e4..072c88853 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_spi.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_spi.h @@ -107,7 +107,7 @@ typedef struct __SPI_HandleTypeDef SPI_InitTypeDef Init; /*!< SPI communication parameters */ - uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ + const uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /*!< SPI Tx Transfer size */ @@ -339,11 +339,12 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * @retval None */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) -#define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->State = HAL_SPI_STATE_RESET; \ - (__HANDLE__)->MspInitCallback = NULL; \ - (__HANDLE__)->MspDeInitCallback = NULL; \ - } while(0) +#define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) \ + do{ \ + (__HANDLE__)->State = HAL_SPI_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ + } while(0) #else #define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) #endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ @@ -444,7 +445,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to __IO uint32_t tmpreg_fre = 0x00U; \ tmpreg_fre = (__HANDLE__)->Instance->SR; \ UNUSED(tmpreg_fre); \ - }while(0U) + } while(0U) /** @brief Enable the SPI peripheral. * @param __HANDLE__ specifies the SPI Handle. @@ -488,8 +489,11 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ -#define SPI_RESET_CRC(__HANDLE__) do{CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);\ - SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);}while(0U) +#define SPI_RESET_CRC(__HANDLE__) \ + do{ \ + CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN); \ + SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN); \ + } while(0U) /** @brief Check whether the specified SPI flag is set or not. * @param __SR__ copy of SPI SR register. @@ -505,7 +509,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * @retval SET or RESET. */ #define SPI_CHECK_FLAG(__SR__, __FLAG__) ((((__SR__) & ((__FLAG__) & SPI_FLAG_MASK)) == \ - ((__FLAG__) & SPI_FLAG_MASK)) ? SET : RESET) + ((__FLAG__) & SPI_FLAG_MASK)) ? SET : RESET) /** @brief Check whether the specified SPI Interrupt is set or not. * @param __CR2__ copy of SPI CR2 register. @@ -517,7 +521,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to * @retval SET or RESET. */ #define SPI_CHECK_IT_SOURCE(__CR2__, __INTERRUPT__) ((((__CR2__) & (__INTERRUPT__)) == \ - (__INTERRUPT__)) ? SET : RESET) + (__INTERRUPT__)) ? SET : RESET) /** @brief Checks if SPI Mode parameter is in allowed range. * @param __MODE__ specifies the SPI Mode. @@ -627,7 +631,7 @@ typedef void (*pSPI_CallbackTypeDef)(SPI_HandleTypeDef *hspi); /*!< pointer to */ #define IS_SPI_CRC_POLYNOMIAL(__POLYNOMIAL__) (((__POLYNOMIAL__) >= 0x1U) && \ ((__POLYNOMIAL__) <= 0xFFFFU) && \ - (((__POLYNOMIAL__)&0x1U) != 0U)) + (((__POLYNOMIAL__)&0x1U) != 0U)) /** @brief Checks if DMA handle is valid. * @param __HANDLE__ specifies a DMA Handle. @@ -667,17 +671,17 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @{ */ /* I/O operation functions ***************************************************/ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, - uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); @@ -703,8 +707,8 @@ void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi); * @{ */ /* Peripheral State and Error functions ***************************************/ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi); +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi); /** * @} */ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_tim.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_tim.h index 1eb13ac4d..235806abe 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_tim.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_tim.h @@ -385,29 +385,28 @@ typedef struct */ typedef enum { - HAL_TIM_BASE_MSPINIT_CB_ID = 0x00U /*!< TIM Base MspInit Callback ID */ - , HAL_TIM_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TIM Base MspDeInit Callback ID */ - , HAL_TIM_IC_MSPINIT_CB_ID = 0x02U /*!< TIM IC MspInit Callback ID */ - , HAL_TIM_IC_MSPDEINIT_CB_ID = 0x03U /*!< TIM IC MspDeInit Callback ID */ - , HAL_TIM_OC_MSPINIT_CB_ID = 0x04U /*!< TIM OC MspInit Callback ID */ - , HAL_TIM_OC_MSPDEINIT_CB_ID = 0x05U /*!< TIM OC MspDeInit Callback ID */ - , HAL_TIM_PWM_MSPINIT_CB_ID = 0x06U /*!< TIM PWM MspInit Callback ID */ - , HAL_TIM_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TIM PWM MspDeInit Callback ID */ - , HAL_TIM_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TIM One Pulse MspInit Callback ID */ - , HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TIM One Pulse MspDeInit Callback ID */ - , HAL_TIM_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TIM Encoder MspInit Callback ID */ - , HAL_TIM_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TIM Encoder MspDeInit Callback ID */ - , HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TIM Hall Sensor MspDeInit Callback ID */ - , HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TIM Hall Sensor MspDeInit Callback ID */ + HAL_TIM_BASE_MSPINIT_CB_ID = 0x00U /*!< TIM Base MspInit Callback ID */ + , HAL_TIM_BASE_MSPDEINIT_CB_ID = 0x01U /*!< TIM Base MspDeInit Callback ID */ + , HAL_TIM_IC_MSPINIT_CB_ID = 0x02U /*!< TIM IC MspInit Callback ID */ + , HAL_TIM_IC_MSPDEINIT_CB_ID = 0x03U /*!< TIM IC MspDeInit Callback ID */ + , HAL_TIM_OC_MSPINIT_CB_ID = 0x04U /*!< TIM OC MspInit Callback ID */ + , HAL_TIM_OC_MSPDEINIT_CB_ID = 0x05U /*!< TIM OC MspDeInit Callback ID */ + , HAL_TIM_PWM_MSPINIT_CB_ID = 0x06U /*!< TIM PWM MspInit Callback ID */ + , HAL_TIM_PWM_MSPDEINIT_CB_ID = 0x07U /*!< TIM PWM MspDeInit Callback ID */ + , HAL_TIM_ONE_PULSE_MSPINIT_CB_ID = 0x08U /*!< TIM One Pulse MspInit Callback ID */ + , HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID = 0x09U /*!< TIM One Pulse MspDeInit Callback ID */ + , HAL_TIM_ENCODER_MSPINIT_CB_ID = 0x0AU /*!< TIM Encoder MspInit Callback ID */ + , HAL_TIM_ENCODER_MSPDEINIT_CB_ID = 0x0BU /*!< TIM Encoder MspDeInit Callback ID */ + , HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID = 0x0CU /*!< TIM Hall Sensor MspDeInit Callback ID */ + , HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID = 0x0DU /*!< TIM Hall Sensor MspDeInit Callback ID */ , HAL_TIM_PERIOD_ELAPSED_CB_ID = 0x0EU /*!< TIM Period Elapsed Callback ID */ , HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID = 0x0FU /*!< TIM Period Elapsed half complete Callback ID */ , HAL_TIM_TRIGGER_CB_ID = 0x10U /*!< TIM Trigger Callback ID */ , HAL_TIM_TRIGGER_HALF_CB_ID = 0x11U /*!< TIM Trigger half complete Callback ID */ - , HAL_TIM_IC_CAPTURE_CB_ID = 0x12U /*!< TIM Input Capture Callback ID */ , HAL_TIM_IC_CAPTURE_HALF_CB_ID = 0x13U /*!< TIM Input Capture half complete Callback ID */ , HAL_TIM_OC_DELAY_ELAPSED_CB_ID = 0x14U /*!< TIM Output Compare Delay Elapsed Callback ID */ - , HAL_TIM_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TIM PWM Pulse Finished Callback ID */ + , HAL_TIM_PWM_PULSE_FINISHED_CB_ID = 0x15U /*!< TIM PWM Pulse Finished Callback ID */ , HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID = 0x16U /*!< TIM PWM Pulse Finished half complete Callback ID */ , HAL_TIM_ERROR_CB_ID = 0x17U /*!< TIM Error Callback ID */ , HAL_TIM_COMMUTATION_CB_ID = 0x18U /*!< TIM Commutation Callback ID */ @@ -1654,8 +1653,9 @@ typedef void (*pTIM_CallbackTypeDef)(TIM_HandleTypeDef *htim); /*!< pointer to #define IS_TIM_OPM_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TIM_CHANNEL_1) || \ ((__CHANNEL__) == TIM_CHANNEL_2)) -#define IS_TIM_PERIOD(__HANDLE__, __PERIOD__) \ - ((IS_TIM_32B_COUNTER_INSTANCE(((__HANDLE__)->Instance)) == 0U) ? (((__PERIOD__) > 0U) && ((__PERIOD__) <= 0x0000FFFFU)) : ((__PERIOD__) > 0U)) +#define IS_TIM_PERIOD(__HANDLE__, __PERIOD__) ((IS_TIM_32B_COUNTER_INSTANCE(((__HANDLE__)->Instance)) == 0U) ? \ + (((__PERIOD__) > 0U) && ((__PERIOD__) <= 0x0000FFFFU)) : \ + ((__PERIOD__) > 0U)) #define IS_TIM_COMPLEMENTARY_CHANNELS(__CHANNEL__) (((__CHANNEL__) == TIM_CHANNEL_1) || \ ((__CHANNEL__) == TIM_CHANNEL_2) || \ @@ -1708,7 +1708,6 @@ typedef void (*pTIM_CallbackTypeDef)(TIM_HandleTypeDef *htim); /*!< pointer to #define IS_TIM_BREAK_FILTER(__BRKFILTER__) ((__BRKFILTER__) <= 0xFUL) - #define IS_TIM_BREAK_STATE(__STATE__) (((__STATE__) == TIM_BREAK_ENABLE) || \ ((__STATE__) == TIM_BREAK_DISABLE)) @@ -2046,7 +2045,8 @@ HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_S HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig); HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro_IT(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig); HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength); + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength); HAL_StatusTypeDef HAL_TIM_DMABurst_MultiWriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength, uint32_t DataLength); diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_usart.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_usart.h index 552a6ebe2..eb4b00df4 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_usart.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_usart.h @@ -624,7 +624,7 @@ uint32_t HAL_USART_GetError(const USART_HandleTypeDef *husart); */ /* Private functions ---------------------------------------------------------*/ -/** @defgroup USART_Private_Functions USART Private Functions +/** @addtogroup USART_Private_Functions * @{ */ diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_wwdg.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_wwdg.h index 3d865e5cb..f95211d44 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_wwdg.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_hal_wwdg.h @@ -183,7 +183,7 @@ typedef void (*pWWDG_CallbackTypeDef)(WWDG_HandleTypeDef *hppp); /*!< pointer t /** * @brief Enable the WWDG early wakeup interrupt. - * @param __HANDLE__ WWDG handle + * @param __HANDLE__: WWDG handle * @param __INTERRUPT__ specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_adc.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_adc.h index 8eb1987a1..59fd2e71d 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_adc.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_adc.h @@ -1656,18 +1656,17 @@ typedef struct __TEMPSENSOR_CALX_TEMP__,\ __VREFANALOG_VOLTAGE__,\ __TEMPSENSOR_ADC_DATA__,\ - __ADC_RESOLUTION__) \ - ((( ( \ - (int32_t)(((__TEMPSENSOR_TYP_CALX_V__)) \ - * 1000) \ - - \ - (int32_t)((((__TEMPSENSOR_ADC_DATA__) * (__VREFANALOG_VOLTAGE__)) \ - / __LL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__)) \ - * 1000) \ - ) \ - ) / (__TEMPSENSOR_TYP_AVGSLOPE__) \ - ) + (__TEMPSENSOR_CALX_TEMP__) \ - ) + __ADC_RESOLUTION__) \ +(((((int32_t)((((__TEMPSENSOR_ADC_DATA__) * (__VREFANALOG_VOLTAGE__)) \ + / __LL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__)) \ + * 1000UL) \ + - \ + (int32_t)(((__TEMPSENSOR_TYP_CALX_V__)) \ + * 1000UL) \ + ) \ + ) / (int32_t)(__TEMPSENSOR_TYP_AVGSLOPE__) \ + ) + (int32_t)(__TEMPSENSOR_CALX_TEMP__) \ +) /** * @} diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_cortex.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_cortex.h index 33a836243..3c76a065e 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_cortex.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_cortex.h @@ -587,7 +587,7 @@ __STATIC_INLINE void LL_MPU_ConfigRegion(uint32_t Region, uint32_t SubRegionDisa /* Set base address */ WRITE_REG(MPU->RBAR, (Address & 0xFFFFFFE0U)); /* Configure MPU */ - WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | SubRegionDisable << MPU_RASR_SRD_Pos)); + WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | (SubRegionDisable << MPU_RASR_SRD_Pos))); } /** diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_dac.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_dac.h index 9207a1035..1ab688c92 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_dac.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_dac.h @@ -87,7 +87,6 @@ extern "C" { #define DAC_REG_DORX_REGOFFSET_MASK (DAC_REG_DOR1_REGOFFSET | DAC_REG_DOR2_REGOFFSET) - #define DAC_REG_DHR_REGOFFSET_MASK_POSBIT0 0x0000000FUL /* Mask of data hold registers offset (DHR12Rx, DHR12Lx, DHR8Rx, ...) when shifted to position 0 */ #define DAC_REG_DORX_REGOFFSET_MASK_POSBIT0 0x00000001UL /* Mask of DORx registers offset when shifted @@ -471,7 +470,7 @@ typedef struct * @arg @ref LL_DAC_RESOLUTION_8B * @retval DAC conversion data (unit: digital value) */ -#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__, __DAC_VOLTAGE__, __DAC_RESOLUTION__) \ +#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__, __DAC_VOLTAGE__, __DAC_RESOLUTION__) \ ((__DAC_VOLTAGE__) * __LL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ / (__VREFANALOG_VOLTAGE__) \ ) diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_fsmc.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_fsmc.h index 771cfff33..29abb61cd 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_fsmc.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_fsmc.h @@ -40,42 +40,42 @@ extern "C" { */ #define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_NORSRAM_BANK1) || \ - ((__BANK__) == FSMC_NORSRAM_BANK2) || \ - ((__BANK__) == FSMC_NORSRAM_BANK3) || \ - ((__BANK__) == FSMC_NORSRAM_BANK4)) + ((__BANK__) == FSMC_NORSRAM_BANK2) || \ + ((__BANK__) == FSMC_NORSRAM_BANK3) || \ + ((__BANK__) == FSMC_NORSRAM_BANK4)) #define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ - ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) + ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) #define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ - ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ - ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) + ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ + ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) #define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ - ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ - ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) + ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ + ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) #define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ - ((__MODE__) == FSMC_ACCESS_MODE_B) || \ - ((__MODE__) == FSMC_ACCESS_MODE_C) || \ - ((__MODE__) == FSMC_ACCESS_MODE_D)) + ((__MODE__) == FSMC_ACCESS_MODE_B) || \ + ((__MODE__) == FSMC_ACCESS_MODE_C) || \ + ((__MODE__) == FSMC_ACCESS_MODE_D)) #define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ - ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) + ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) #define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ - ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) + ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) #define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ - ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) + ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) #define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ - ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) + ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) #define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ - ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) + ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) #define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ - ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) + ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) #define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ - ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) + ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) #define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ - ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) + ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) #define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1U) && ((__LATENCY__) <= 17U)) #define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ - ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) + ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) #define IS_FSMC_CONTINOUS_CLOCK(__CCLOCK__) (((__CCLOCK__) == FSMC_CONTINUOUS_CLOCK_SYNC_ONLY) || \ - ((__CCLOCK__) == FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) + ((__CCLOCK__) == FSMC_CONTINUOUS_CLOCK_SYNC_ASYNC)) #define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15U) #define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 15U)) #define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 255U)) @@ -88,18 +88,18 @@ extern "C" { #define IS_FSMC_NAND_BANK(__BANK__) ((__BANK__) == FSMC_NAND_BANK3) #define IS_FSMC_WAIT_FEATURE(__FEATURE__) (((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ - ((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) + ((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) #define IS_FSMC_NAND_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ - ((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) + ((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) #define IS_FSMC_ECC_STATE(__STATE__) (((__STATE__) == FSMC_NAND_ECC_DISABLE) || \ - ((__STATE__) == FSMC_NAND_ECC_ENABLE)) + ((__STATE__) == FSMC_NAND_ECC_ENABLE)) #define IS_FSMC_ECCPAGE_SIZE(__SIZE__) (((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) #define IS_FSMC_TCLR_TIME(__TIME__) ((__TIME__) <= 255U) #define IS_FSMC_TAR_TIME(__TIME__) ((__TIME__) <= 255U) #define IS_FSMC_SETUP_TIME(__TIME__) ((__TIME__) <= 254U) @@ -137,52 +137,53 @@ extern "C" { typedef struct { uint32_t NSBank; /*!< Specifies the NORSRAM memory device that will be used. - This parameter can be a value of @ref FSMC_NORSRAM_Bank */ + This parameter can be a value of @ref FSMC_NORSRAM_Bank */ uint32_t DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the data bus or not. - This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing */ + This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing*/ uint32_t MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory device. - This parameter can be a value of @ref FSMC_Memory_Type */ + This parameter can be a value of @ref FSMC_Memory_Type */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. - This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ + This parameter can be a value of @ref FSMC_NORSRAM_Data_Width */ uint32_t BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. - This parameter can be a value of @ref FSMC_Burst_Access_Mode */ + This parameter can be a value of @ref FSMC_Burst_Access_Mode */ uint32_t WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. - This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ + This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ uint32_t WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. - This parameter can be a value of @ref FSMC_Wrap_Mode */ + This parameter can be a value of @ref FSMC_Wrap_Mode */ uint32_t WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. - This parameter can be a value of @ref FSMC_Wait_Timing */ + This parameter can be a value of @ref FSMC_Wait_Timing */ - uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device by the FSMC. - This parameter can be a value of @ref FSMC_Write_Operation */ + uint32_t WriteOperation; /*!< Enables or disables the write operation in the selected device + by the FSMC. + This parameter can be a value of @ref FSMC_Write_Operation */ uint32_t WaitSignal; /*!< Enables or disables the wait state insertion via wait signal, valid for Flash memory access in burst mode. - This parameter can be a value of @ref FSMC_Wait_Signal */ + This parameter can be a value of @ref FSMC_Wait_Signal */ uint32_t ExtendedMode; /*!< Enables or disables the extended mode. - This parameter can be a value of @ref FSMC_Extended_Mode */ + This parameter can be a value of @ref FSMC_Extended_Mode */ uint32_t AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. - This parameter can be a value of @ref FSMC_AsynchronousWait */ + This parameter can be a value of @ref FSMC_AsynchronousWait */ uint32_t WriteBurst; /*!< Enables or disables the write burst operation. - This parameter can be a value of @ref FSMC_Write_Burst */ + This parameter can be a value of @ref FSMC_Write_Burst */ } FSMC_NORSRAM_InitTypeDef; @@ -227,7 +228,7 @@ typedef struct in NOR Flash memories with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. - This parameter can be a value of @ref FSMC_Access_Mode */ + This parameter can be a value of @ref FSMC_Access_Mode */ } FSMC_NORSRAM_TimingTypeDef; /** @@ -305,7 +306,7 @@ typedef struct uint32_t TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ -}FSMC_PCCARD_InitTypeDef; +} FSMC_PCCARD_InitTypeDef; /** * @} @@ -586,7 +587,7 @@ typedef struct * @retval None */ #define __FSMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)]\ - |= FSMC_BCR1_MBKEN) + |= FSMC_BCR1_MBKEN) /** * @brief Disable the NORSRAM device access. @@ -595,7 +596,7 @@ typedef struct * @retval None */ #define __FSMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) ((__INSTANCE__)->BTCR[(__BANK__)]\ - &= ~FSMC_BCR1_MBKEN) + &= ~FSMC_BCR1_MBKEN) /** * @} @@ -612,8 +613,9 @@ typedef struct * @param __BANK__ FSMC_NAND Bank * @retval None */ -#define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->PCR2 |= FSMC_PCR2_PBKEN): \ - ((__INSTANCE__)->PCR3 |= FSMC_PCR3_PBKEN)) +#define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->PCR2 |= FSMC_PCR2_PBKEN) : \ + ((__INSTANCE__)->PCR3 |= FSMC_PCR3_PBKEN)) /** * @brief Disable the NAND device access. @@ -621,8 +623,9 @@ typedef struct * @param __BANK__ FSMC_NAND Bank * @retval None */ -#define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? CLEAR_BIT((__INSTANCE__)->PCR2, FSMC_PCR2_PBKEN): \ - CLEAR_BIT((__INSTANCE__)->PCR3, FSMC_PCR3_PBKEN)) +#define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + CLEAR_BIT((__INSTANCE__)->PCR2, FSMC_PCR2_PBKEN) : \ + CLEAR_BIT((__INSTANCE__)->PCR3, FSMC_PCR3_PBKEN)) /** * @} @@ -665,8 +668,9 @@ typedef struct * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ -#define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 |= (__INTERRUPT__)): \ - ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) +#define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->SR2 |= (__INTERRUPT__)) : \ + ((__INSTANCE__)->SR3 |= (__INTERRUPT__))) /** * @brief Disable the NAND device interrupt. @@ -679,8 +683,9 @@ typedef struct * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. * @retval None */ -#define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)): \ - ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) +#define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->SR2 &= ~(__INTERRUPT__)) : \ + ((__INSTANCE__)->SR3 &= ~(__INTERRUPT__))) /** * @brief Get flag status of the NAND device. @@ -694,8 +699,9 @@ typedef struct * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ -#define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ - (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) +#define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)) : \ + (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) /** * @brief Clear flag status of the NAND device. @@ -709,8 +715,9 @@ typedef struct * @arg FSMC_FLAG_FEMPT: FIFO empty flag. * @retval None */ -#define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? ((__INSTANCE__)->SR2 &= ~(__FLAG__)): \ - ((__INSTANCE__)->SR3 &= ~(__FLAG__))) +#define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2) ? \ + ((__INSTANCE__)->SR2 &= ~(__FLAG__)) : \ + ((__INSTANCE__)->SR3 &= ~(__FLAG__))) /** * @} @@ -795,14 +802,14 @@ typedef struct * @{ */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_InitTypeDef *Init); + const FSMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeDef *Device, - FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, - uint32_t ExtendedMode); + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, + uint32_t ExtendedMode); HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); + FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); /** * @} */ @@ -825,11 +832,11 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Dev /** @defgroup FSMC_LL_NAND_Private_Functions_Group1 NAND Initialization/de-initialization functions * @{ */ -HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init); +HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, const FSMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); /** * @} @@ -840,8 +847,8 @@ HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); */ HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank); -HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, - uint32_t Timeout); +HAL_StatusTypeDef FSMC_NAND_GetECC(const FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout); /** * @} */ @@ -855,13 +862,13 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, /** @defgroup FSMC_LL_PCCARD_Private_Functions_Group1 PCCARD Initialization/de-initialization functions * @{ */ -HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init); +HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, const FSMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing); + const FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing); + const FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing); + const FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); /** * @} diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_iwdg.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_iwdg.h index dc0eb4dac..91c38004a 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_iwdg.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_iwdg.h @@ -207,7 +207,7 @@ __STATIC_INLINE void LL_IWDG_SetPrescaler(IWDG_TypeDef *IWDGx, uint32_t Prescale * @arg @ref LL_IWDG_PRESCALER_128 * @arg @ref LL_IWDG_PRESCALER_256 */ -__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->PR)); } @@ -230,7 +230,7 @@ __STATIC_INLINE void LL_IWDG_SetReloadCounter(IWDG_TypeDef *IWDGx, uint32_t Coun * @param IWDGx IWDG Instance * @retval Value between Min_Data=0 and Max_Data=0x0FFF */ -__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(const IWDG_TypeDef *IWDGx) { return (READ_REG(IWDGx->RLR)); } @@ -249,7 +249,7 @@ __STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_PVU) == (IWDG_SR_PVU)) ? 1UL : 0UL); } @@ -260,7 +260,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_RVU) == (IWDG_SR_RVU)) ? 1UL : 0UL); } @@ -272,7 +272,7 @@ __STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) * @param IWDGx IWDG Instance * @retval State of bits (1 or 0). */ -__STATIC_INLINE uint32_t LL_IWDG_IsReady(IWDG_TypeDef *IWDGx) +__STATIC_INLINE uint32_t LL_IWDG_IsReady(const IWDG_TypeDef *IWDGx) { return ((READ_BIT(IWDGx->SR, IWDG_SR_PVU | IWDG_SR_RVU) == 0U) ? 1UL : 0UL); } diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_rtc.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_rtc.h index 5ca0a5f99..76da8f3f8 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_rtc.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_rtc.h @@ -391,8 +391,8 @@ typedef struct /** @defgroup RTC_LL_EC_TIMESTAMP_EDGE TIMESTAMP EDGE * @{ */ -#define LL_RTC_TIMESTAMP_EDGE_RISING 0x00000000U /*!< RTC_TS input rising edge generates a time-stamp event */ -#define LL_RTC_TIMESTAMP_EDGE_FALLING RTC_CR_TSEDGE /*!< RTC_TS input falling edge generates a time-stamp even */ +#define LL_RTC_TIMESTAMP_EDGE_RISING 0x00000000U /*!< RTC_TS input rising edge generates a time-stamp event */ +#define LL_RTC_TIMESTAMP_EDGE_FALLING RTC_CR_TSEDGE /*!< RTC_TS input falling edge generates a time-stamp event */ /** * @} */ @@ -935,7 +935,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetFormat(RTC_TypeDef *RTCx, uint32_t TimeForma /** * @brief Get time format (AM or PM notation) - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -969,7 +969,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetHour(RTC_TypeDef *RTCx, uint32_t Hours) /** * @brief Get Hours in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1004,7 +1004,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetMinute(RTC_TypeDef *RTCx, uint32_t Minutes) /** * @brief Get Minutes in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1039,7 +1039,7 @@ __STATIC_INLINE void LL_RTC_TIME_SetSecond(RTC_TypeDef *RTCx, uint32_t Seconds) /** * @brief Get Seconds in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1089,7 +1089,7 @@ __STATIC_INLINE void LL_RTC_TIME_Config(RTC_TypeDef *RTCx, uint32_t Format12_24, /** * @brief Get time (hour, minute and second) in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note Read either RTC_SSR or RTC_TR locks the values in the higher-order calendar * shadow registers until RTC_DR is read (LL_RTC_ReadReg(RTC, DR)). @@ -1193,7 +1193,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetYear(RTC_TypeDef *RTCx, uint32_t Year) /** * @brief Get Year in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Year from BCD to Binary format * @rmtoll DR YT LL_RTC_DATE_GetYear\n @@ -1227,7 +1227,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetWeekDay(RTC_TypeDef *RTCx, uint32_t WeekDay) /** * @brief Get Week day - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @rmtoll DR WDU LL_RTC_DATE_GetWeekDay * @param RTCx RTC Instance @@ -1274,7 +1274,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetMonth(RTC_TypeDef *RTCx, uint32_t Month) /** * @brief Get Month in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Month from BCD to Binary format * @rmtoll DR MT LL_RTC_DATE_GetMonth\n @@ -1316,7 +1316,7 @@ __STATIC_INLINE void LL_RTC_DATE_SetDay(RTC_TypeDef *RTCx, uint32_t Day) /** * @brief Get Day in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macro __LL_RTC_CONVERT_BCD2BIN is available to convert Day from BCD to Binary format * @rmtoll DR DT LL_RTC_DATE_GetDay\n @@ -1378,7 +1378,7 @@ __STATIC_INLINE void LL_RTC_DATE_Config(RTC_TypeDef *RTCx, uint32_t WeekDay, uin /** * @brief Get date (WeekDay, Day, Month and Year) in BCD format - * @note if shadow mode is disabled (BYPSHAD=0), need to check if RSF flag is set + * @note if RTC shadow registers are not bypassed (BYPSHAD=0), need to check if RSF flag is set * before reading this bit * @note helper macros __LL_RTC_GET_WEEKDAY, __LL_RTC_GET_YEAR, __LL_RTC_GET_MONTH, * and __LL_RTC_GET_DAY are available to get independently each parameter. diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_sdmmc.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_sdmmc.h index 255c7f28c..51855dcc7 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_sdmmc.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_sdmmc.h @@ -6,7 +6,7 @@ ****************************************************************************** * @attention * - * Copyright (c) 2018 STMicroelectronics. + * Copyright (c) 2016 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file @@ -300,10 +300,14 @@ typedef struct #define SDMMC_SINGLE_BUS_SUPPORT 0x00010000U #define SDMMC_CARD_LOCKED 0x02000000U -#ifndef SDMMC_DATATIMEOUT -#define SDMMC_DATATIMEOUT 0xFFFFFFFFU +#ifndef SDMMC_DATATIMEOUT /*Hardware Data Timeout (ms) */ +#define SDMMC_DATATIMEOUT ((uint32_t)0xFFFFFFFFU) #endif /* SDMMC_DATATIMEOUT */ +#ifndef SDMMC_SWDATATIMEOUT /*Software Data Timeout (ms) */ +#define SDMMC_SWDATATIMEOUT SDMMC_DATATIMEOUT +#endif /* SDMMC_SWDATATIMEOUT */ + #define SDMMC_0TO7BITS 0x000000FFU #define SDMMC_8TO15BITS 0x0000FF00U #define SDMMC_16TO23BITS 0x00FF0000U diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_spi.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_spi.h index 10d9772f9..a14e286c6 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_spi.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_spi.h @@ -55,53 +55,66 @@ typedef struct uint32_t TransferDirection; /*!< Specifies the SPI unidirectional or bidirectional data mode. This parameter can be a value of @ref SPI_LL_EC_TRANSFER_MODE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferDirection().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetTransferDirection().*/ uint32_t Mode; /*!< Specifies the SPI mode (Master/Slave). This parameter can be a value of @ref SPI_LL_EC_MODE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetMode().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetMode().*/ uint32_t DataWidth; /*!< Specifies the SPI data width. This parameter can be a value of @ref SPI_LL_EC_DATAWIDTH. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetDataWidth().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetDataWidth().*/ uint32_t ClockPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_LL_EC_POLARITY. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPolarity().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetClockPolarity().*/ uint32_t ClockPhase; /*!< Specifies the clock active edge for the bit capture. This parameter can be a value of @ref SPI_LL_EC_PHASE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPhase().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetClockPhase().*/ - uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) + or by software using the SSI bit. This parameter can be a value of @ref SPI_LL_EC_NSS_MODE. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetNSSMode().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetNSSMode().*/ - uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used to configure the transmit and receive SCK clock. + uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used + to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_LL_EC_BAUDRATEPRESCALER. - @note The communication clock is derived from the master clock. The slave clock does not need to be set. + @note The communication clock is derived from the master clock. + The slave clock does not need to be set. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetBaudRatePrescaler().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetBaudRatePrescaler().*/ uint32_t BitOrder; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_LL_EC_BIT_ORDER. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferBitOrder().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetTransferBitOrder().*/ uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. This parameter can be a value of @ref SPI_LL_EC_CRC_CALCULATION. - This feature can be modified afterwards using unitary functions @ref LL_SPI_EnableCRC() and @ref LL_SPI_DisableCRC().*/ + This feature can be modified afterwards using unitary + functions @ref LL_SPI_EnableCRC() and @ref LL_SPI_DisableCRC().*/ uint32_t CRCPoly; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF. - This feature can be modified afterwards using unitary function @ref LL_SPI_SetCRCPolynomial().*/ + This feature can be modified afterwards using unitary + function @ref LL_SPI_SetCRCPolynomial().*/ } LL_SPI_InitTypeDef; @@ -317,7 +330,7 @@ __STATIC_INLINE void LL_SPI_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_SPE) == (SPI_CR1_SPE)) ? 1UL : 0UL); } @@ -347,7 +360,7 @@ __STATIC_INLINE void LL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_SPI_MODE_MASTER * @arg @ref LL_SPI_MODE_SLAVE */ -__STATIC_INLINE uint32_t LL_SPI_GetMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI)); } @@ -375,7 +388,7 @@ __STATIC_INLINE void LL_SPI_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_SPI_PROTOCOL_MOTOROLA * @arg @ref LL_SPI_PROTOCOL_TI */ -__STATIC_INLINE uint32_t LL_SPI_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_FRF)); } @@ -404,7 +417,7 @@ __STATIC_INLINE void LL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase * @arg @ref LL_SPI_PHASE_1EDGE * @arg @ref LL_SPI_PHASE_2EDGE */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPHA)); } @@ -433,7 +446,7 @@ __STATIC_INLINE void LL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_SPI_POLARITY_LOW * @arg @ref LL_SPI_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPOL)); } @@ -473,7 +486,7 @@ __STATIC_INLINE void LL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t Bau * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 */ -__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_BR)); } @@ -501,7 +514,7 @@ __STATIC_INLINE void LL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitO * @arg @ref LL_SPI_LSB_FIRST * @arg @ref LL_SPI_MSB_FIRST */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_LSBFIRST)); } @@ -538,7 +551,7 @@ __STATIC_INLINE void LL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t Tra * @arg @ref LL_SPI_HALF_DUPLEX_RX * @arg @ref LL_SPI_HALF_DUPLEX_TX */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE)); } @@ -565,7 +578,7 @@ __STATIC_INLINE void LL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) * @arg @ref LL_SPI_DATAWIDTH_8BIT * @arg @ref LL_SPI_DATAWIDTH_16BIT */ -__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_DFF)); } @@ -609,7 +622,7 @@ __STATIC_INLINE void LL_SPI_DisableCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_CRCEN) == (SPI_CR1_CRCEN)) ? 1UL : 0UL); } @@ -644,7 +657,7 @@ __STATIC_INLINE void LL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->CRCPR)); } @@ -655,7 +668,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->RXCRCR)); } @@ -666,7 +679,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->TXCRCR)); } @@ -707,7 +720,7 @@ __STATIC_INLINE void LL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) * @arg @ref LL_SPI_NSS_HARD_INPUT * @arg @ref LL_SPI_NSS_HARD_OUTPUT */ -__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(const SPI_TypeDef *SPIx) { uint32_t Ssm = (READ_BIT(SPIx->CR1, SPI_CR1_SSM)); uint32_t Ssoe = (READ_BIT(SPIx->CR2, SPI_CR2_SSOE) << 16U); @@ -728,7 +741,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_RXNE) == (SPI_SR_RXNE)) ? 1UL : 0UL); } @@ -739,7 +752,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_TXE) == (SPI_SR_TXE)) ? 1UL : 0UL); } @@ -750,7 +763,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CRCERR) == (SPI_SR_CRCERR)) ? 1UL : 0UL); } @@ -761,7 +774,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_MODF) == (SPI_SR_MODF)) ? 1UL : 0UL); } @@ -772,7 +785,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_OVR) == (SPI_SR_OVR)) ? 1UL : 0UL); } @@ -790,7 +803,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_BSY) == (SPI_SR_BSY)) ? 1UL : 0UL); } @@ -801,7 +814,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_FRE) == (SPI_SR_FRE)) ? 1UL : 0UL); } @@ -874,7 +887,8 @@ __STATIC_INLINE void LL_SPI_ClearFlag_FRE(SPI_TypeDef *SPIx) /** * @brief Enable error interrupt - * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @note This bit controls the generation of an interrupt when an error condition + * occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). * @rmtoll CR2 ERRIE LL_SPI_EnableIT_ERR * @param SPIx SPI Instance * @retval None @@ -908,7 +922,8 @@ __STATIC_INLINE void LL_SPI_EnableIT_TXE(SPI_TypeDef *SPIx) /** * @brief Disable error interrupt - * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). + * @note This bit controls the generation of an interrupt when an error condition + * occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). * @rmtoll CR2 ERRIE LL_SPI_DisableIT_ERR * @param SPIx SPI Instance * @retval None @@ -946,7 +961,7 @@ __STATIC_INLINE void LL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_ERRIE) == (SPI_CR2_ERRIE)) ? 1UL : 0UL); } @@ -957,7 +972,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXNEIE) == (SPI_CR2_RXNEIE)) ? 1UL : 0UL); } @@ -968,7 +983,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXEIE) == (SPI_CR2_TXEIE)) ? 1UL : 0UL); } @@ -1009,7 +1024,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXDMAEN) == (SPI_CR2_RXDMAEN)) ? 1UL : 0UL); } @@ -1042,7 +1057,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXDMAEN) == (SPI_CR2_TXDMAEN)) ? 1UL : 0UL); } @@ -1053,7 +1068,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Address of data register */ -__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(const SPI_TypeDef *SPIx) { return (uint32_t) &(SPIx->DR); } @@ -1130,7 +1145,7 @@ __STATIC_INLINE void LL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct); void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct); @@ -1397,7 +1412,7 @@ __STATIC_INLINE void LL_I2S_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SE) == (SPI_I2SCFGR_I2SE)) ? 1UL : 0UL); } @@ -1430,7 +1445,7 @@ __STATIC_INLINE void LL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat * @arg @ref LL_I2S_DATAFORMAT_24B * @arg @ref LL_I2S_DATAFORMAT_32B */ -__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)); } @@ -1457,7 +1472,7 @@ __STATIC_INLINE void LL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_I2S_POLARITY_LOW * @arg @ref LL_I2S_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_CKPOL)); } @@ -1492,7 +1507,7 @@ __STATIC_INLINE void LL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_I2S_STANDARD_PCM_SHORT * @arg @ref LL_I2S_STANDARD_PCM_LONG */ -__STATIC_INLINE uint32_t LL_I2S_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC)); } @@ -1523,7 +1538,7 @@ __STATIC_INLINE void LL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_I2S_MODE_MASTER_TX * @arg @ref LL_I2S_MODE_MASTER_RX */ -__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG)); } @@ -1546,7 +1561,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t Presca * @param SPIx SPI Instance * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_I2SDIV)); } @@ -1573,7 +1588,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t Presc * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN * @arg @ref LL_I2S_PRESCALER_PARITY_ODD */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_ODD) >> 8U); } @@ -1606,7 +1621,7 @@ __STATIC_INLINE void LL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE) == (SPI_I2SPR_MCKOE)) ? 1UL : 0UL); } @@ -1625,7 +1640,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_RXNE(SPIx); } @@ -1636,7 +1651,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_TXE(SPIx); } @@ -1647,7 +1662,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_BSY(SPIx); } @@ -1658,7 +1673,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_OVR(SPIx); } @@ -1669,7 +1684,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_UDR) == (SPI_SR_UDR)) ? 1UL : 0UL); } @@ -1680,7 +1695,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_FRE(SPIx); } @@ -1694,7 +1709,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CHSIDE) == (SPI_SR_CHSIDE)) ? 1UL : 0UL); } @@ -1816,7 +1831,7 @@ __STATIC_INLINE void LL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_ERR(SPIx); } @@ -1827,7 +1842,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_RXNE(SPIx); } @@ -1838,7 +1853,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_TXE(SPIx); } @@ -1879,7 +1894,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_RX(SPIx); } @@ -1912,7 +1927,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_TX(SPIx); } @@ -1957,7 +1972,7 @@ __STATIC_INLINE void LL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_tim.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_tim.h index 3608090af..7d3b66ace 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_tim.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_tim.h @@ -562,10 +562,10 @@ typedef struct /** @defgroup TIM_LL_EC_COUNTERMODE Counter Mode * @{ */ -#define LL_TIM_COUNTERMODE_UP 0x00000000U /*!CR2, TIM_CR2_CCPC); } +/** + * @brief Indicates whether the capture/compare control bits (CCxE, CCxNE and OCxM) preload is enabled. + * @rmtoll CR2 CCPC LL_TIM_CC_IsEnabledPreload + * @param TIMx Timer instance + * @retval State of bit (1 or 0). + */ +__STATIC_INLINE uint32_t LL_TIM_CC_IsEnabledPreload(const TIM_TypeDef *TIMx) +{ + return ((READ_BIT(TIMx->CR2, TIM_CR2_CCPC) == (TIM_CR2_CCPC)) ? 1UL : 0UL); +} + /** * @brief Set the updated source of the capture/compare control bits (CCxE, CCxNE and OCxM). * @note Macro IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usart.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usart.h index 7da1de68f..1bbd4bcb6 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usart.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usart.h @@ -345,7 +345,7 @@ typedef struct * @} */ -/** @defgroup USART_LL_EM_Exported_Macros_Helper Exported_Macros_Helper +/** @defgroup USART_LL_EM_Exported_Macros_Helper Exported Macros Helper * @{ */ @@ -632,7 +632,7 @@ __STATIC_INLINE uint32_t LL_USART_GetOverSampling(const USART_TypeDef *USARTx) /** * @brief Configure if Clock pulse of the last data bit is output to the SCLK pin or not - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 LBCL LL_USART_SetLastClkPulseOutput * @param USARTx USART Instance @@ -649,7 +649,7 @@ __STATIC_INLINE void LL_USART_SetLastClkPulseOutput(USART_TypeDef *USARTx, uint3 /** * @brief Retrieve Clock pulse of the last data bit output configuration * (Last bit Clock pulse output to the SCLK pin or not) - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 LBCL LL_USART_GetLastClkPulseOutput * @param USARTx USART Instance @@ -664,7 +664,7 @@ __STATIC_INLINE uint32_t LL_USART_GetLastClkPulseOutput(const USART_TypeDef *USA /** * @brief Select the phase of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPHA LL_USART_SetClockPhase * @param USARTx USART Instance @@ -680,7 +680,7 @@ __STATIC_INLINE void LL_USART_SetClockPhase(USART_TypeDef *USARTx, uint32_t Cloc /** * @brief Return phase of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPHA LL_USART_GetClockPhase * @param USARTx USART Instance @@ -695,7 +695,7 @@ __STATIC_INLINE uint32_t LL_USART_GetClockPhase(const USART_TypeDef *USARTx) /** * @brief Select the polarity of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPOL LL_USART_SetClockPolarity * @param USARTx USART Instance @@ -711,7 +711,7 @@ __STATIC_INLINE void LL_USART_SetClockPolarity(USART_TypeDef *USARTx, uint32_t C /** * @brief Return polarity of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CPOL LL_USART_GetClockPolarity * @param USARTx USART Instance @@ -726,7 +726,7 @@ __STATIC_INLINE uint32_t LL_USART_GetClockPolarity(const USART_TypeDef *USARTx) /** * @brief Configure Clock signal format (Phase Polarity and choice about output of last bit clock pulse) - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clock Phase configuration using @ref LL_USART_SetClockPhase() function @@ -754,7 +754,7 @@ __STATIC_INLINE void LL_USART_ConfigClock(USART_TypeDef *USARTx, uint32_t Phase, /** * @brief Enable Clock output on SCLK pin - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CLKEN LL_USART_EnableSCLKOutput * @param USARTx USART Instance @@ -767,7 +767,7 @@ __STATIC_INLINE void LL_USART_EnableSCLKOutput(USART_TypeDef *USARTx) /** * @brief Disable Clock output on SCLK pin - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CLKEN LL_USART_DisableSCLKOutput * @param USARTx USART Instance @@ -780,7 +780,7 @@ __STATIC_INLINE void LL_USART_DisableSCLKOutput(USART_TypeDef *USARTx) /** * @brief Indicate if Clock output on SCLK pin is enabled - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @rmtoll CR2 CLKEN LL_USART_IsEnabledSCLKOutput * @param USARTx USART Instance @@ -882,7 +882,7 @@ __STATIC_INLINE uint32_t LL_USART_GetNodeAddress(const USART_TypeDef *USARTx) /** * @brief Enable RTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_EnableRTSHWFlowCtrl * @param USARTx USART Instance @@ -895,7 +895,7 @@ __STATIC_INLINE void LL_USART_EnableRTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Disable RTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_DisableRTSHWFlowCtrl * @param USARTx USART Instance @@ -908,7 +908,7 @@ __STATIC_INLINE void LL_USART_DisableRTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Enable CTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSE LL_USART_EnableCTSHWFlowCtrl * @param USARTx USART Instance @@ -921,7 +921,7 @@ __STATIC_INLINE void LL_USART_EnableCTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Disable CTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSE LL_USART_DisableCTSHWFlowCtrl * @param USARTx USART Instance @@ -934,7 +934,7 @@ __STATIC_INLINE void LL_USART_DisableCTSHWFlowCtrl(USART_TypeDef *USARTx) /** * @brief Configure HW Flow Control mode (both CTS and RTS) - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_SetHWFlowCtrl\n * CR3 CTSE LL_USART_SetHWFlowCtrl @@ -953,7 +953,7 @@ __STATIC_INLINE void LL_USART_SetHWFlowCtrl(USART_TypeDef *USARTx, uint32_t Hard /** * @brief Return HW Flow Control configuration (both CTS and RTS) - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 RTSE LL_USART_GetHWFlowCtrl\n * CR3 CTSE LL_USART_GetHWFlowCtrl @@ -1077,7 +1077,7 @@ __STATIC_INLINE uint32_t LL_USART_GetBaudRate(const USART_TypeDef *USARTx, uint3 /** * @brief Enable IrDA mode - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IREN LL_USART_EnableIrda * @param USARTx USART Instance @@ -1090,7 +1090,7 @@ __STATIC_INLINE void LL_USART_EnableIrda(USART_TypeDef *USARTx) /** * @brief Disable IrDA mode - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IREN LL_USART_DisableIrda * @param USARTx USART Instance @@ -1103,7 +1103,7 @@ __STATIC_INLINE void LL_USART_DisableIrda(USART_TypeDef *USARTx) /** * @brief Indicate if IrDA mode is enabled - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IREN LL_USART_IsEnabledIrda * @param USARTx USART Instance @@ -1116,7 +1116,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledIrda(const USART_TypeDef *USARTx) /** * @brief Configure IrDA Power Mode (Normal or Low Power) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IRLP LL_USART_SetIrdaPowerMode * @param USARTx USART Instance @@ -1132,7 +1132,7 @@ __STATIC_INLINE void LL_USART_SetIrdaPowerMode(USART_TypeDef *USARTx, uint32_t P /** * @brief Retrieve IrDA Power Mode configuration (Normal or Low Power) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll CR3 IRLP LL_USART_GetIrdaPowerMode * @param USARTx USART Instance @@ -1148,7 +1148,7 @@ __STATIC_INLINE uint32_t LL_USART_GetIrdaPowerMode(const USART_TypeDef *USARTx) /** * @brief Set Irda prescaler value, used for dividing the USART clock source * to achieve the Irda Low Power frequency (8 bits value) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_SetIrdaPrescaler * @param USARTx USART Instance @@ -1163,7 +1163,7 @@ __STATIC_INLINE void LL_USART_SetIrdaPrescaler(USART_TypeDef *USARTx, uint32_t P /** * @brief Return Irda prescaler value, used for dividing the USART clock source * to achieve the Irda Low Power frequency (8 bits value) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_GetIrdaPrescaler * @param USARTx USART Instance @@ -1184,7 +1184,7 @@ __STATIC_INLINE uint32_t LL_USART_GetIrdaPrescaler(const USART_TypeDef *USARTx) /** * @brief Enable Smartcard NACK transmission - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 NACK LL_USART_EnableSmartcardNACK * @param USARTx USART Instance @@ -1197,7 +1197,7 @@ __STATIC_INLINE void LL_USART_EnableSmartcardNACK(USART_TypeDef *USARTx) /** * @brief Disable Smartcard NACK transmission - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 NACK LL_USART_DisableSmartcardNACK * @param USARTx USART Instance @@ -1210,7 +1210,7 @@ __STATIC_INLINE void LL_USART_DisableSmartcardNACK(USART_TypeDef *USARTx) /** * @brief Indicate if Smartcard NACK transmission is enabled - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 NACK LL_USART_IsEnabledSmartcardNACK * @param USARTx USART Instance @@ -1223,7 +1223,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledSmartcardNACK(const USART_TypeDef *US /** * @brief Enable Smartcard mode - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 SCEN LL_USART_EnableSmartcard * @param USARTx USART Instance @@ -1236,7 +1236,7 @@ __STATIC_INLINE void LL_USART_EnableSmartcard(USART_TypeDef *USARTx) /** * @brief Disable Smartcard mode - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 SCEN LL_USART_DisableSmartcard * @param USARTx USART Instance @@ -1249,7 +1249,7 @@ __STATIC_INLINE void LL_USART_DisableSmartcard(USART_TypeDef *USARTx) /** * @brief Indicate if Smartcard mode is enabled - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll CR3 SCEN LL_USART_IsEnabledSmartcard * @param USARTx USART Instance @@ -1263,7 +1263,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledSmartcard(const USART_TypeDef *USARTx /** * @brief Set Smartcard prescaler value, used for dividing the USART clock * source to provide the SMARTCARD Clock (5 bits value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_SetSmartcardPrescaler * @param USARTx USART Instance @@ -1278,7 +1278,7 @@ __STATIC_INLINE void LL_USART_SetSmartcardPrescaler(USART_TypeDef *USARTx, uint3 /** * @brief Return Smartcard prescaler value, used for dividing the USART clock * source to provide the SMARTCARD Clock (5 bits value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR PSC LL_USART_GetSmartcardPrescaler * @param USARTx USART Instance @@ -1292,7 +1292,7 @@ __STATIC_INLINE uint32_t LL_USART_GetSmartcardPrescaler(const USART_TypeDef *USA /** * @brief Set Smartcard Guard time value, expressed in nb of baud clocks periods * (GT[7:0] bits : Guard time value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR GT LL_USART_SetSmartcardGuardTime * @param USARTx USART Instance @@ -1307,7 +1307,7 @@ __STATIC_INLINE void LL_USART_SetSmartcardGuardTime(USART_TypeDef *USARTx, uint3 /** * @brief Return Smartcard Guard time value, expressed in nb of baud clocks periods * (GT[7:0] bits : Guard time value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @rmtoll GTPR GT LL_USART_GetSmartcardGuardTime * @param USARTx USART Instance @@ -1328,7 +1328,7 @@ __STATIC_INLINE uint32_t LL_USART_GetSmartcardGuardTime(const USART_TypeDef *USA /** * @brief Enable Single Wire Half-Duplex mode - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @rmtoll CR3 HDSEL LL_USART_EnableHalfDuplex * @param USARTx USART Instance @@ -1341,7 +1341,7 @@ __STATIC_INLINE void LL_USART_EnableHalfDuplex(USART_TypeDef *USARTx) /** * @brief Disable Single Wire Half-Duplex mode - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @rmtoll CR3 HDSEL LL_USART_DisableHalfDuplex * @param USARTx USART Instance @@ -1354,7 +1354,7 @@ __STATIC_INLINE void LL_USART_DisableHalfDuplex(USART_TypeDef *USARTx) /** * @brief Indicate if Single Wire Half-Duplex mode is enabled - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @rmtoll CR3 HDSEL LL_USART_IsEnabledHalfDuplex * @param USARTx USART Instance @@ -1375,7 +1375,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledHalfDuplex(const USART_TypeDef *USART /** * @brief Set LIN Break Detection Length - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDL LL_USART_SetLINBrkDetectionLen * @param USARTx USART Instance @@ -1391,7 +1391,7 @@ __STATIC_INLINE void LL_USART_SetLINBrkDetectionLen(USART_TypeDef *USARTx, uint3 /** * @brief Return LIN Break Detection Length - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDL LL_USART_GetLINBrkDetectionLen * @param USARTx USART Instance @@ -1406,7 +1406,7 @@ __STATIC_INLINE uint32_t LL_USART_GetLINBrkDetectionLen(const USART_TypeDef *USA /** * @brief Enable LIN mode - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LINEN LL_USART_EnableLIN * @param USARTx USART Instance @@ -1419,7 +1419,7 @@ __STATIC_INLINE void LL_USART_EnableLIN(USART_TypeDef *USARTx) /** * @brief Disable LIN mode - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LINEN LL_USART_DisableLIN * @param USARTx USART Instance @@ -1432,7 +1432,7 @@ __STATIC_INLINE void LL_USART_DisableLIN(USART_TypeDef *USARTx) /** * @brief Indicate if LIN mode is enabled - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LINEN LL_USART_IsEnabledLIN * @param USARTx USART Instance @@ -1493,7 +1493,7 @@ __STATIC_INLINE void LL_USART_ConfigAsyncMode(USART_TypeDef *USARTx) * - IREN bit in the USART_CR3 register, * - HDSEL bit in the USART_CR3 register. * This function also sets the USART in Synchronous mode. - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_USART_INSTANCE(USARTx) can be used to check whether or not * Synchronous mode is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1531,7 +1531,7 @@ __STATIC_INLINE void LL_USART_ConfigSyncMode(USART_TypeDef *USARTx) * - IREN bit in the USART_CR3 register, * - HDSEL bit in the USART_CR3 register. * This function also set the UART/USART in LIN mode. - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function @@ -1571,7 +1571,7 @@ __STATIC_INLINE void LL_USART_ConfigLINMode(USART_TypeDef *USARTx) * - SCEN bit in the USART_CR3 register, * - IREN bit in the USART_CR3 register, * This function also sets the UART/USART in Half Duplex mode. - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not * Half-Duplex mode is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1610,7 +1610,7 @@ __STATIC_INLINE void LL_USART_ConfigHalfDuplexMode(USART_TypeDef *USARTx) * This function also configures Stop bits to 1.5 bits and * sets the USART in Smartcard mode (SCEN bit). * Clock Output is also enabled (CLKEN). - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not * Smartcard feature is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1652,7 +1652,7 @@ __STATIC_INLINE void LL_USART_ConfigSmartcardMode(USART_TypeDef *USARTx) * - SCEN bit in the USART_CR3 register, * - HDSEL bit in the USART_CR3 register. * This function also sets the UART/USART in IRDA mode (IREN bit). - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_IRDA_INSTANCE(USARTx) can be used to check whether or not * IrDA feature is supported by the USARTx instance. * @note Call of this function is equivalent to following function call sequence : * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function @@ -1818,7 +1818,7 @@ __STATIC_INLINE uint32_t LL_USART_IsActiveFlag_TXE(const USART_TypeDef *USARTx) /** * @brief Check if the USART LIN Break Detection Flag is set or not - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll SR LBD LL_USART_IsActiveFlag_LBD * @param USARTx USART Instance @@ -1831,7 +1831,7 @@ __STATIC_INLINE uint32_t LL_USART_IsActiveFlag_LBD(const USART_TypeDef *USARTx) /** * @brief Check if the USART CTS Flag is set or not - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll SR CTS LL_USART_IsActiveFlag_nCTS * @param USARTx USART Instance @@ -1983,7 +1983,7 @@ __STATIC_INLINE void LL_USART_ClearFlag_RXNE(USART_TypeDef *USARTx) /** * @brief Clear LIN Break Detection Flag - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll SR LBD LL_USART_ClearFlag_LBD * @param USARTx USART Instance @@ -1996,7 +1996,7 @@ __STATIC_INLINE void LL_USART_ClearFlag_LBD(USART_TypeDef *USARTx) /** * @brief Clear CTS Interrupt Flag - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll SR CTS LL_USART_ClearFlag_nCTS * @param USARTx USART Instance @@ -2072,7 +2072,7 @@ __STATIC_INLINE void LL_USART_EnableIT_PE(USART_TypeDef *USARTx) /** * @brief Enable LIN Break Detection Interrupt - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDIE LL_USART_EnableIT_LBD * @param USARTx USART Instance @@ -2100,7 +2100,7 @@ __STATIC_INLINE void LL_USART_EnableIT_ERROR(USART_TypeDef *USARTx) /** * @brief Enable CTS Interrupt - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSIE LL_USART_EnableIT_CTS * @param USARTx USART Instance @@ -2168,7 +2168,7 @@ __STATIC_INLINE void LL_USART_DisableIT_PE(USART_TypeDef *USARTx) /** * @brief Disable LIN Break Detection Interrupt - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDIE LL_USART_DisableIT_LBD * @param USARTx USART Instance @@ -2196,7 +2196,7 @@ __STATIC_INLINE void LL_USART_DisableIT_ERROR(USART_TypeDef *USARTx) /** * @brief Disable CTS Interrupt - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSIE LL_USART_DisableIT_CTS * @param USARTx USART Instance @@ -2264,7 +2264,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledIT_PE(const USART_TypeDef *USARTx) /** * @brief Check if the USART LIN Break Detection Interrupt is enabled or disabled. - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not * LIN feature is supported by the USARTx instance. * @rmtoll CR2 LBDIE LL_USART_IsEnabledIT_LBD * @param USARTx USART Instance @@ -2288,7 +2288,7 @@ __STATIC_INLINE uint32_t LL_USART_IsEnabledIT_ERROR(const USART_TypeDef *USARTx) /** * @brief Check if the USART CTS Interrupt is enabled or disabled. - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not + * @note Macro IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not * Hardware Flow control feature is supported by the USARTx instance. * @rmtoll CR3 CTSIE LL_USART_IsEnabledIT_CTS * @param USARTx USART Instance diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usb.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usb.h index 553bd1c9b..905690603 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usb.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_usb.h @@ -37,6 +37,13 @@ extern "C" { */ /* Exported types ------------------------------------------------------------*/ +#ifndef HAL_USB_TIMEOUT +#define HAL_USB_TIMEOUT 0xF000000U +#endif /* define HAL_USB_TIMEOUT */ + +#ifndef HAL_USB_CURRENT_MODE_MAX_DELAY_MS +#define HAL_USB_CURRENT_MODE_MAX_DELAY_MS 200U +#endif /* define HAL_USB_CURRENT_MODE_MAX_DELAY_MS */ /** * @brief USB Mode definition @@ -85,39 +92,39 @@ typedef enum */ typedef struct { - uint32_t dev_endpoints; /*!< Device Endpoints number. + uint8_t dev_endpoints; /*!< Device Endpoints number. This parameter depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ - uint32_t Host_channels; /*!< Host Channels number. + uint8_t Host_channels; /*!< Host Channels number. This parameter Depends on the used USB core. This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ - uint32_t dma_enable; /*!< USB DMA state. + uint8_t dma_enable; /*!< USB DMA state. If DMA is not supported this parameter shall be set by default to zero */ - uint32_t speed; /*!< USB Core speed. - This parameter can be any value of @ref PCD_Speed/HCD_Speed - (HCD_SPEED_xxx, HCD_SPEED_xxx) */ + uint8_t speed; /*!< USB Core speed. + This parameter can be any value of @ref PCD_Speed/HCD_Speed + (HCD_SPEED_xxx, HCD_SPEED_xxx) */ - uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */ + uint8_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. */ - uint32_t phy_itface; /*!< Select the used PHY interface. - This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */ + uint8_t phy_itface; /*!< Select the used PHY interface. + This parameter can be any value of @ref PCD_PHY_Module/HCD_PHY_Module */ - uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ + uint8_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */ - uint32_t low_power_enable; /*!< Enable or disable the low Power Mode. */ + uint8_t low_power_enable; /*!< Enable or disable the low Power Mode. */ - uint32_t lpm_enable; /*!< Enable or disable Link Power Management. */ + uint8_t lpm_enable; /*!< Enable or disable Link Power Management. */ - uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. */ + uint8_t battery_charging_enable; /*!< Enable or disable Battery charging. */ - uint32_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ + uint8_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */ - uint32_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ + uint8_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */ - uint32_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ + uint8_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */ } USB_CfgTypeDef; @@ -495,41 +502,41 @@ HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_SetTurnaroundTime(USB_OTG_GlobalTypeDef *USBx, uint32_t hclk, uint8_t speed); HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTypeDef mode); -HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed); +HAL_StatusTypeDef USB_SetDevSpeed(const USB_OTG_GlobalTypeDef *USBx, uint8_t speed); HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num); -HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_ActivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_DeactivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep, uint8_t dma); -HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, +HAL_StatusTypeDef USB_WritePacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len, uint8_t dma); -void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); -HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); -HAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address); -HAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_DevDisconnect(USB_OTG_GlobalTypeDef *USBx); +void *USB_ReadPacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len); +HAL_StatusTypeDef USB_EPSetStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPClearStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_EPStopXfer(const USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep); +HAL_StatusTypeDef USB_SetDevAddress(const USB_OTG_GlobalTypeDef *USBx, uint8_t address); +HAL_StatusTypeDef USB_DevConnect(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_DevDisconnect(const USB_OTG_GlobalTypeDef *USBx); HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup); -uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx); -uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_ActivateSetup(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_EP0_OutStart(const USB_OTG_GlobalTypeDef *USBx, uint8_t dma, const uint8_t *psetup); +uint8_t USB_GetDevSpeed(const USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_GetMode(const USB_OTG_GlobalTypeDef *USBx); uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef const *USBx); -uint32_t USB_ReadChInterrupts(USB_OTG_GlobalTypeDef *USBx, uint8_t chnum); -uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx); -uint32_t USB_ReadDevOutEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); -uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx); -uint32_t USB_ReadDevInEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); +uint32_t USB_ReadChInterrupts(const USB_OTG_GlobalTypeDef *USBx, uint8_t chnum); +uint32_t USB_ReadDevAllOutEpInterrupt(const USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevOutEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); +uint32_t USB_ReadDevAllInEpInterrupt(const USB_OTG_GlobalTypeDef *USBx); +uint32_t USB_ReadDevInEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum); void USB_ClearInterrupts(USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt); HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg); -HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq); -HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_DriveVbus(USB_OTG_GlobalTypeDef *USBx, uint8_t state); +HAL_StatusTypeDef USB_InitFSLSPClkSel(const USB_OTG_GlobalTypeDef *USBx, uint8_t freq); +HAL_StatusTypeDef USB_ResetPort(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_DriveVbus(const USB_OTG_GlobalTypeDef *USBx, uint8_t state); uint32_t USB_GetHostSpeed(USB_OTG_GlobalTypeDef const *USBx); uint32_t USB_GetCurrentFrame(USB_OTG_GlobalTypeDef const *USBx); HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, @@ -538,12 +545,12 @@ HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma); -uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num); -HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num); +uint32_t USB_HC_ReadInterrupt(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_HC_Halt(const USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num); +HAL_StatusTypeDef USB_DoPing(const USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num); HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx); -HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_ActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx); +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx); #endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ /** diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_utils.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_utils.h index f4e01c689..f40a9a2f5 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_utils.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_utils.h @@ -218,7 +218,7 @@ __STATIC_INLINE uint32_t LL_GetFlashSize(void) * @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCC helper macro) * @note When a RTOS is used, it is recommended to avoid changing the SysTick * configuration by calling this function, for a delay use rather osDelay RTOS service. - * @param Ticks Number of ticks + * @param Ticks Frequency of Ticks (Hz) * @retval None */ __STATIC_INLINE void LL_InitTick(uint32_t HCLKFrequency, uint32_t Ticks) diff --git a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_wwdg.h b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_wwdg.h index 6c94d2ddd..f94171435 100644 --- a/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_wwdg.h +++ b/stm32cube/stm32f2xx/drivers/include/stm32f2xx_ll_wwdg.h @@ -131,7 +131,7 @@ __STATIC_INLINE void LL_WWDG_Enable(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->CR, WWDG_CR_WDGA) == (WWDG_CR_WDGA)) ? 1UL : 0UL); } @@ -158,7 +158,7 @@ __STATIC_INLINE void LL_WWDG_SetCounter(WWDG_TypeDef *WWDGx, uint32_t Counter) * @param WWDGx WWDG Instance * @retval 7 bit Watchdog Counter value */ -__STATIC_INLINE uint32_t LL_WWDG_GetCounter(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetCounter(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CR, WWDG_CR_T)); } @@ -191,7 +191,7 @@ __STATIC_INLINE void LL_WWDG_SetPrescaler(WWDG_TypeDef *WWDGx, uint32_t Prescale * @arg @ref LL_WWDG_PRESCALER_4 * @arg @ref LL_WWDG_PRESCALER_8 */ -__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CFR, WWDG_CFR_WDGTB)); } @@ -223,7 +223,7 @@ __STATIC_INLINE void LL_WWDG_SetWindow(WWDG_TypeDef *WWDGx, uint32_t Window) * @param WWDGx WWDG Instance * @retval 7 bit Watchdog Window value */ -__STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_GetWindow(const WWDG_TypeDef *WWDGx) { return (READ_BIT(WWDGx->CFR, WWDG_CFR_W)); } @@ -244,7 +244,7 @@ __STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->SR, WWDG_SR_EWIF) == (WWDG_SR_EWIF)) ? 1UL : 0UL); } @@ -286,7 +286,7 @@ __STATIC_INLINE void LL_WWDG_EnableIT_EWKUP(WWDG_TypeDef *WWDGx) * @param WWDGx WWDG Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(WWDG_TypeDef *WWDGx) +__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(const WWDG_TypeDef *WWDGx) { return ((READ_BIT(WWDGx->CFR, WWDG_CFR_EWI) == (WWDG_CFR_EWI)) ? 1UL : 0UL); } diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal.c index e3939af9d..ffba97b6a 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal.c @@ -54,7 +54,7 @@ */ #define __STM32F2xx_HAL_VERSION_MAIN 0x01U /*!< [31:24] main version */ #define __STM32F2xx_HAL_VERSION_SUB1 0x02U /*!< [23:16] sub1 version */ -#define __STM32F2xx_HAL_VERSION_SUB2 0x08U /*!< [15:8] sub2 version */ +#define __STM32F2xx_HAL_VERSION_SUB2 0x09U /*!< [15:8] sub2 version */ #define __STM32F2xx_HAL_VERSION_RC 0x00U /*!< [7:0] release candidate */ #define __STM32F2xx_HAL_VERSION ((__STM32F2xx_HAL_VERSION_MAIN << 24U)\ |(__STM32F2xx_HAL_VERSION_SUB1 << 16U)\ @@ -381,7 +381,7 @@ HAL_TickFreqTypeDef HAL_GetTickFreq(void) * @param Delay specifies the delay time length, in milliseconds. * @retval None */ -__weak void HAL_Delay(__IO uint32_t Delay) +__weak void HAL_Delay(uint32_t Delay) { uint32_t tickstart = HAL_GetTick(); uint32_t wait = Delay; diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_can.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_can.c index c43c873fe..6d565b554 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_can.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_can.c @@ -33,7 +33,7 @@ (++) Enable the CAN interface clock using __HAL_RCC_CANx_CLK_ENABLE() (++) Configure CAN pins (+++) Enable the clock for the CAN GPIOs - (+++) Configure CAN pins as alternate function open-drain + (+++) Configure CAN pins as alternate function (++) In case of using interrupts (e.g. HAL_CAN_ActivateNotification()) (+++) Configure the CAN interrupt priority using HAL_NVIC_SetPriority() @@ -235,6 +235,7 @@ * @{ */ #define CAN_TIMEOUT_VALUE 10U +#define CAN_WAKEUP_TIMEOUT_COUNTER 1000000U /** * @} */ @@ -248,8 +249,8 @@ */ /** @defgroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim ============================================================================== ##### Initialization and de-initialization functions ##### @@ -328,7 +329,7 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef *hcan) /* Init the low level hardware: CLOCK, NVIC */ HAL_CAN_MspInit(hcan); } -#endif /* (USE_HAL_CAN_REGISTER_CALLBACKS) */ +#endif /* USE_HAL_CAN_REGISTER_CALLBACKS */ /* Request initialisation */ SET_BIT(hcan->Instance->MCR, CAN_MCR_INRQ); @@ -482,7 +483,7 @@ HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef *hcan) #else /* DeInit the low level hardware: CLOCK, NVIC */ HAL_CAN_MspDeInit(hcan); -#endif /* (USE_HAL_CAN_REGISTER_CALLBACKS) */ +#endif /* USE_HAL_CAN_REGISTER_CALLBACKS */ /* Reset the CAN peripheral */ SET_BIT(hcan->Instance->MCR, CAN_MCR_RESET); @@ -814,8 +815,8 @@ HAL_StatusTypeDef HAL_CAN_UnRegisterCallback(CAN_HandleTypeDef *hcan, HAL_CAN_Ca */ /** @defgroup CAN_Exported_Functions_Group2 Configuration functions - * @brief Configuration functions. - * + * @brief Configuration functions. + * @verbatim ============================================================================== ##### Configuration functions ##### @@ -868,7 +869,7 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, const CAN_Filter /* Check the parameters */ assert_param(IS_CAN_FILTER_BANK_SINGLE(sFilterConfig->FilterBank)); -#endif +#endif /* CAN3 */ /* Initialisation mode for the filter */ SET_BIT(can_ip->FMR, CAN_FMR_FINIT); @@ -878,7 +879,7 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, const CAN_Filter CLEAR_BIT(can_ip->FMR, CAN_FMR_CAN2SB); SET_BIT(can_ip->FMR, sFilterConfig->SlaveStartFilterBank << CAN_FMR_CAN2SB_Pos); -#endif +#endif /* CAN3 */ /* Convert filter number into bit position */ filternbrbitpos = (uint32_t)1 << (sFilterConfig->FilterBank & 0x1FU); @@ -970,8 +971,8 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, const CAN_Filter */ /** @defgroup CAN_Exported_Functions_Group3 Control functions - * @brief Control functions - * + * @brief Control functions + * @verbatim ============================================================================== ##### Control functions ##### @@ -1143,7 +1144,6 @@ HAL_StatusTypeDef HAL_CAN_RequestSleep(CAN_HandleTypeDef *hcan) HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan) { __IO uint32_t count = 0; - uint32_t timeout = 1000000U; HAL_CAN_StateTypeDef state = hcan->State; if ((state == HAL_CAN_STATE_READY) || @@ -1159,15 +1159,14 @@ HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan) count++; /* Check if timeout is reached */ - if (count > timeout) + if (count > CAN_WAKEUP_TIMEOUT_COUNTER) { /* Update error code */ hcan->ErrorCode |= HAL_CAN_ERROR_TIMEOUT; return HAL_ERROR; } - } - while ((hcan->Instance->MSR & CAN_MSR_SLAK) != 0U); + } while ((hcan->Instance->MSR & CAN_MSR_SLAK) != 0U); /* Return function status */ return HAL_OK; @@ -1608,8 +1607,8 @@ uint32_t HAL_CAN_GetRxFifoFillLevel(const CAN_HandleTypeDef *hcan, uint32_t RxFi */ /** @defgroup CAN_Exported_Functions_Group4 Interrupts management - * @brief Interrupts management - * + * @brief Interrupts management + * @verbatim ============================================================================== ##### Interrupts management ##### @@ -2074,8 +2073,8 @@ void HAL_CAN_IRQHandler(CAN_HandleTypeDef *hcan) */ /** @defgroup CAN_Exported_Functions_Group5 Callback functions - * @brief CAN Callback functions - * + * @brief CAN Callback functions + * @verbatim ============================================================================== ##### Callback functions ##### @@ -2324,8 +2323,8 @@ __weak void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) */ /** @defgroup CAN_Exported_Functions_Group6 Peripheral State and Error functions - * @brief CAN Peripheral State functions - * + * @brief CAN Peripheral State functions + * @verbatim ============================================================================== ##### Peripheral State and Error functions ##### diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_cortex.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_cortex.c index 0429b1204..9d04e38bd 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_cortex.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_cortex.c @@ -8,17 +8,6 @@ * + Initialization and de-initialization functions * + Peripheral Control functions * - ****************************************************************************** - * @attention - * - * Copyright (c) 2017 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** @verbatim ============================================================================== ##### How to use this driver ##### @@ -77,6 +66,16 @@ @endverbatim ****************************************************************************** + * @attention + * + * Copyright (c) 2017 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file in + * the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ @@ -291,6 +290,38 @@ void HAL_MPU_Enable(uint32_t MPU_Control) __ISB(); } +/** + * @brief Enable the MPU Region. + * @retval None + */ +void HAL_MPU_EnableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Enable the Region */ + SET_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @brief Disable the MPU Region. + * @retval None + */ +void HAL_MPU_DisableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + /** * @brief Initializes and configures the Region and the memory to be protected. * @param MPU_Init Pointer to a MPU_Region_InitTypeDef structure that contains @@ -302,38 +333,32 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); + assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); + assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); + assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); + assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); + assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); + assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); + assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); + assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; - if ((MPU_Init->Enable) != RESET) - { - /* Check the parameters */ - assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); - assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); - assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); - assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); - assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); - assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); - assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); - assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); - - MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | - ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | - ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | - ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | - ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | - ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | - ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | - ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | - ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); - } - else - { - MPU->RBAR = 0x00U; - MPU->RASR = 0x00U; - } + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); + + /* Apply configuration */ + MPU->RBAR = MPU_Init->BaseAddress; + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | + ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | + ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | + ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | + ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | + ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | + ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } #endif /* __MPU_PRESENT */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac.c index a27cc292e..657a19825 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac.c @@ -938,10 +938,7 @@ uint32_t HAL_DAC_GetValue(const DAC_HandleTypeDef *hdac, uint32_t Channel) uint32_t result; /* Check the DAC peripheral handle */ - if (hdac == NULL) - { - return HAL_ERROR; - } + assert_param(hdac != NULL); /* Check the parameters */ assert_param(IS_DAC_CHANNEL(Channel)); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac_ex.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac_ex.c index bc2c874af..95c73a7c8 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac_ex.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dac_ex.c @@ -387,7 +387,6 @@ __weak void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac) } - /** * @} */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi.c index 98c70f442..bdaf01a71 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi.c @@ -10,6 +10,17 @@ * + Peripheral Control functions * + Peripheral State and Error functions * + ****************************************************************************** + * @attention + * + * Copyright (c) 2016 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** @verbatim ============================================================================== ##### How to use this driver ##### @@ -26,7 +37,7 @@ 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 + (#) Configure the selected DMA stream to transfer Data from DCMI DR register to the destination memory buffer. (#) Program the required configuration through following parameters: @@ -35,7 +46,7 @@ (#) 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 + and HAL_DCMI_EnableCrop() functions (#) The capture can be stopped using HAL_DCMI_Stop() function. @@ -65,33 +76,33 @@ Use functions HAL_DCMI_RegisterCallback() to register a user callback. Function HAL_DCMI_RegisterCallback() allows to register following callbacks: - (+) FrameEventCallback : DCMI Frame Event. - (+) VsyncEventCallback : DCMI Vsync Event. - (+) LineEventCallback : DCMI Line Event. - (+) ErrorCallback : DCMI error. - (+) MspInitCallback : DCMI MspInit. - (+) MspDeInitCallback : DCMI MspDeInit. - This function takes as parameters the HAL peripheral handle, the callback ID + (+) FrameEventCallback : callback for DCMI Frame Event. + (+) VsyncEventCallback : callback for DCMI Vsync Event. + (+) LineEventCallback : callback for DCMI Line Event. + (+) ErrorCallback : callback for DCMI error detection. + (+) MspInitCallback : callback for DCMI MspInit. + (+) MspDeInitCallback : callback for DCMI MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID and a pointer to the user callback function. Use function HAL_DCMI_UnRegisterCallback() to reset a callback to the default - weak (surcharged) function. + weak (overridden) function. HAL_DCMI_UnRegisterCallback() takes as parameters the HAL peripheral handle, and the callback ID. This function allows to reset following callbacks: - (+) FrameEventCallback : DCMI Frame Event. - (+) VsyncEventCallback : DCMI Vsync Event. - (+) LineEventCallback : DCMI Line Event. - (+) ErrorCallback : DCMI error. - (+) MspInitCallback : DCMI MspInit. - (+) MspDeInitCallback : DCMI MspDeInit. + (+) FrameEventCallback : callback for DCMI Frame Event. + (+) VsyncEventCallback : callback for DCMI Vsync Event. + (+) LineEventCallback : callback for DCMI Line Event. + (+) ErrorCallback : callback for DCMI error. + (+) MspInitCallback : callback for DCMI MspInit. + (+) MspDeInitCallback : callback for DCMI MspDeInit. By default, after the HAL_DCMI_Init and if the state is HAL_DCMI_STATE_RESET - all callbacks are reset to the corresponding legacy weak (surcharged) functions: + all callbacks are reset to the corresponding legacy weak (overridden) functions: examples FrameEventCallback(), HAL_DCMI_ErrorCallback(). Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (surcharged) functions in the HAL_DCMI_Init - and HAL_DCMI_DeInit only when these callbacks are null (not registered beforehand). + reset to the legacy weak (overridden) functions in the HAL_DCMI_Init + and HAL_DCMI_DeInit only when these callbacks are null (not registered beforehand). If not, MspInit or MspDeInit are not null, the HAL_DCMI_Init and HAL_DCMI_DeInit keep and use the user MspInit/MspDeInit callbacks (registered beforehand). @@ -105,24 +116,16 @@ When the compilation define USE_HAL_DCMI_REGISTER_CALLBACKS is set to 0 or not defined, the callback registering feature is not available - and weak (surcharged) callbacks are used. + and weak (overridden) callbacks are used. @endverbatim ****************************************************************************** - * @attention - * - * Copyright (c) 2016 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f2xx_hal.h" +#ifdef HAL_DCMI_MODULE_ENABLED +#if defined (DCMI) /** @addtogroup STM32F2xx_HAL_Driver * @{ @@ -132,19 +135,35 @@ * @{ */ -#ifdef HAL_DCMI_MODULE_ENABLED -#if defined (DCMI) - /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ +/** @defgroup DCMI_Private_Constants DCMI Private Constants + * @{ + */ + +/** @defgroup DCMI_Stop_TimeOut DCMI Stop Time Out + * @{ + */ #define HAL_TIMEOUT_DCMI_STOP ((uint32_t)1000) /* Set timeout to 1s */ +/** + * @} + */ +/** + * @} + */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ +/** @addtogroup DCMI_Private_Functions DCMI Private Functions + * @{ + */ static void DCMI_DMAXferCplt(DMA_HandleTypeDef *hdma); static void DCMI_DMAError(DMA_HandleTypeDef *hdma); +/** + * @} + */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DCMI_Exported_Functions DCMI Exported Functions @@ -152,8 +171,8 @@ static void DCMI_DMAError(DMA_HandleTypeDef *hdma); */ /** @defgroup DCMI_Exported_Functions_Group1 Initialization and Configuration functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### @@ -195,6 +214,7 @@ HAL_StatusTypeDef HAL_DCMI_Init(DCMI_HandleTypeDef *hdcmi) { /* Init the DCMI Callback settings */ #if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) + /* Reset callback pointers to the weak predefined callbacks */ hdcmi->FrameEventCallback = HAL_DCMI_FrameEventCallback; /* Legacy weak FrameEventCallback */ hdcmi->VsyncEventCallback = HAL_DCMI_VsyncEventCallback; /* Legacy weak VsyncEventCallback */ hdcmi->LineEventCallback = HAL_DCMI_LineEventCallback; /* Legacy weak LineEventCallback */ @@ -317,8 +337,8 @@ __weak void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef *hdcmi) * @} */ /** @defgroup DCMI_Exported_Functions_Group2 IO operation functions - * @brief IO operation functions - * + * @brief IO operation functions + * @verbatim =============================================================================== ##### IO operation functions ##### @@ -344,8 +364,9 @@ __weak void HAL_DCMI_MspDeInit(DCMI_HandleTypeDef *hdcmi) */ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef *hdcmi, uint32_t DCMI_Mode, uint32_t pData, uint32_t Length) { + uint32_t tmp_length = Length; /* Initialize the second memory address */ - uint32_t SecondMemAddress = 0; + uint32_t SecondMemAddress; /* Check function parameters */ assert_param(IS_DCMI_CAPTURE_MODE(DCMI_Mode)); @@ -378,11 +399,18 @@ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef *hdcmi, uint32_t DCMI_Mo hdcmi->XferSize = 0; hdcmi->pBuffPtr = 0; - if (Length <= 0xFFFFU) + if (tmp_length <= 0xFFFFU) { /* Enable the DMA Stream */ - if (HAL_DMA_Start_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, Length) != HAL_OK) + if (HAL_DMA_Start_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, tmp_length) != HAL_OK) { + /* Set Error Code */ + hdcmi->ErrorCode = HAL_DCMI_ERROR_DMA; + /* Change DCMI state */ + hdcmi->State = HAL_DCMI_STATE_READY; + /* Release Lock */ + __HAL_UNLOCK(hdcmi); + /* Return function status */ return HAL_ERROR; } } @@ -393,7 +421,7 @@ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef *hdcmi, uint32_t DCMI_Mo /* Initialize transfer parameters */ hdcmi->XferCount = 1; - hdcmi->XferSize = Length; + hdcmi->XferSize = tmp_length; hdcmi->pBuffPtr = pData; /* Get the number of buffer */ @@ -408,11 +436,18 @@ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef *hdcmi, uint32_t DCMI_Mo hdcmi->XferTransferNumber = hdcmi->XferCount; /* Update second memory address */ - SecondMemAddress = (uint32_t)(pData + (4 * hdcmi->XferSize)); + SecondMemAddress = (uint32_t)(pData + (4U * hdcmi->XferSize)); /* Start DMA multi buffer transfer */ if (HAL_DMAEx_MultiBufferStart_IT(hdcmi->DMA_Handle, (uint32_t)&hdcmi->Instance->DR, (uint32_t)pData, SecondMemAddress, hdcmi->XferSize) != HAL_OK) { + /* Set Error Code */ + hdcmi->ErrorCode = HAL_DCMI_ERROR_DMA; + /* Change DCMI state */ + hdcmi->State = HAL_DCMI_STATE_READY; + /* Release Lock */ + __HAL_UNLOCK(hdcmi); + /* Return function status */ return HAL_ERROR; } } @@ -435,7 +470,7 @@ HAL_StatusTypeDef HAL_DCMI_Start_DMA(DCMI_HandleTypeDef *hdcmi, uint32_t DCMI_Mo */ HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef *hdcmi) { - register uint32_t count = HAL_TIMEOUT_DCMI_STOP * (SystemCoreClock / 8U / 1000U); + uint32_t count = HAL_TIMEOUT_DCMI_STOP * (SystemCoreClock / 8U / 1000U); HAL_StatusTypeDef status = HAL_OK; /* Process locked */ @@ -450,7 +485,8 @@ HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef *hdcmi) /* Check if the DCMI capture effectively disabled */ do { - if (count-- == 0U) + count-- ; + if (count == 0U) { /* Update error code */ hdcmi->ErrorCode |= HAL_DCMI_ERROR_TIMEOUT; @@ -458,8 +494,7 @@ HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef *hdcmi) status = HAL_TIMEOUT; break; } - } - while ((hdcmi->Instance->CR & DCMI_CR_CAPTURE) != 0U); + } while ((hdcmi->Instance->CR & DCMI_CR_CAPTURE) != 0U); /* Disable the DCMI */ __HAL_DCMI_DISABLE(hdcmi); @@ -488,7 +523,7 @@ HAL_StatusTypeDef HAL_DCMI_Stop(DCMI_HandleTypeDef *hdcmi) */ HAL_StatusTypeDef HAL_DCMI_Suspend(DCMI_HandleTypeDef *hdcmi) { - register uint32_t count = HAL_TIMEOUT_DCMI_STOP * (SystemCoreClock / 8U / 1000U); + uint32_t count = HAL_TIMEOUT_DCMI_STOP * (SystemCoreClock / 8U / 1000U); HAL_StatusTypeDef status = HAL_OK; /* Process locked */ @@ -505,7 +540,8 @@ HAL_StatusTypeDef HAL_DCMI_Suspend(DCMI_HandleTypeDef *hdcmi) /* Check if the DCMI capture effectively disabled */ do { - if (count-- == 0U) + count-- ; + if (count == 0U) { /* Update error code */ hdcmi->ErrorCode |= HAL_DCMI_ERROR_TIMEOUT; @@ -516,8 +552,7 @@ HAL_StatusTypeDef HAL_DCMI_Suspend(DCMI_HandleTypeDef *hdcmi) status = HAL_TIMEOUT; break; } - } - while ((hdcmi->Instance->CR & DCMI_CR_CAPTURE) != 0U); + } while ((hdcmi->Instance->CR & DCMI_CR_CAPTURE) != 0U); } /* Process Unlocked */ __HAL_UNLOCK(hdcmi); @@ -542,7 +577,7 @@ HAL_StatusTypeDef HAL_DCMI_Resume(DCMI_HandleTypeDef *hdcmi) /* Change DCMI state */ hdcmi->State = HAL_DCMI_STATE_BUSY; - /* Disable Capture */ + /* Enable Capture */ hdcmi->Instance->CR |= DCMI_CR_CAPTURE; } /* Process Unlocked */ @@ -578,7 +613,10 @@ void HAL_DCMI_IRQHandler(DCMI_HandleTypeDef *hdcmi) hdcmi->DMA_Handle->XferAbortCallback = DCMI_DMAError; /* Abort the DMA Transfer */ - (void)HAL_DMA_Abort_IT(hdcmi->DMA_Handle); + if (HAL_DMA_Abort_IT(hdcmi->DMA_Handle) != HAL_OK) + { + DCMI_DMAError(hdcmi->DMA_Handle); + } } /* Overflow interrupt management ********************************************/ if ((isr_value & DCMI_FLAG_OVRRI) == DCMI_FLAG_OVRRI) @@ -679,6 +717,8 @@ __weak void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *hdcmi) */ __weak void HAL_DCMI_LineEventCallback(DCMI_HandleTypeDef *hdcmi) { + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdcmi); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_DCMI_LineEventCallback could be implemented in the user file */ @@ -721,8 +761,8 @@ __weak void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi) */ /** @defgroup DCMI_Exported_Functions_Group3 Peripheral Control functions - * @brief Peripheral Control functions - * + * @brief Peripheral Control functions + * @verbatim =============================================================================== ##### Peripheral Control functions ##### @@ -746,7 +786,8 @@ __weak void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi) * @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) +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); @@ -833,7 +874,7 @@ HAL_StatusTypeDef HAL_DCMI_EnableCrop(DCMI_HandleTypeDef *hdcmi) * the embedded synchronization delimiters unmasks. * @retval HAL status */ -HAL_StatusTypeDef HAL_DCMI_ConfigSyncUnmask(DCMI_HandleTypeDef *hdcmi, DCMI_SyncUnmaskTypeDef *SyncUnmask) +HAL_StatusTypeDef HAL_DCMI_ConfigSyncUnmask(DCMI_HandleTypeDef *hdcmi, const DCMI_SyncUnmaskTypeDef *SyncUnmask) { /* Process Locked */ __HAL_LOCK(hdcmi); @@ -861,8 +902,8 @@ HAL_StatusTypeDef HAL_DCMI_ConfigSyncUnmask(DCMI_HandleTypeDef *hdcmi, DCMI_Syn */ /** @defgroup DCMI_Exported_Functions_Group4 Peripheral State functions - * @brief Peripheral State functions - * + * @brief Peripheral State functions + * @verbatim =============================================================================== ##### Peripheral State and Errors functions ##### @@ -882,32 +923,40 @@ HAL_StatusTypeDef HAL_DCMI_ConfigSyncUnmask(DCMI_HandleTypeDef *hdcmi, DCMI_Syn * the configuration information for DCMI. * @retval HAL state */ -HAL_DCMI_StateTypeDef HAL_DCMI_GetState(DCMI_HandleTypeDef *hdcmi) +HAL_DCMI_StateTypeDef HAL_DCMI_GetState(const DCMI_HandleTypeDef *hdcmi) { return hdcmi->State; } /** -* @brief Return the DCMI error code -* @param hdcmi pointer to a DCMI_HandleTypeDef structure that contains + * @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) + * @retval DCMI Error Code + */ +uint32_t HAL_DCMI_GetError(const DCMI_HandleTypeDef *hdcmi) { return hdcmi->ErrorCode; } #if (USE_HAL_DCMI_REGISTER_CALLBACKS == 1) /** - * @brief DCMI Callback registering - * @param hdcmi pointer to a DCMI_HandleTypeDef structure that contains - * the configuration information for DCMI. - * @param CallbackID dcmi Callback ID - * @param pCallback pointer to DCMI_CallbackTypeDef structure - * @retval status + * @brief Register a User DCMI Callback + * To be used instead of the weak predefined callback + * @param hdcmi DCMI handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_DCMI_LINE_EVENT_CB_ID Line Event callback ID + * @arg @ref HAL_DCMI_FRAME_EVENT_CB_ID Frame Event callback ID + * @arg @ref HAL_DCMI_VSYNC_EVENT_CB_ID Vsync Event callback ID + * @arg @ref HAL_DCMI_ERROR_CB_ID Error callback ID + * @arg @ref HAL_DCMI_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_DCMI_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status */ -HAL_StatusTypeDef HAL_DCMI_RegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_CallbackIDTypeDef CallbackID, pDCMI_CallbackTypeDef pCallback) +HAL_StatusTypeDef HAL_DCMI_RegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_CallbackIDTypeDef CallbackID, + pDCMI_CallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; @@ -987,10 +1036,18 @@ HAL_StatusTypeDef HAL_DCMI_RegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_ } /** - * @brief DCMI Callback Unregistering - * @param hdcmi dcmi handle - * @param CallbackID dcmi Callback ID - * @retval status + * @brief Unregister a DCMI Callback + * DCMI callback is redirected to the weak predefined callback + * @param hdcmi DCMI handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_DCMI_LINE_EVENT_CB_ID Line Event callback ID + * @arg @ref HAL_DCMI_FRAME_EVENT_CB_ID Frame Event callback ID + * @arg @ref HAL_DCMI_VSYNC_EVENT_CB_ID Vsync Event callback ID + * @arg @ref HAL_DCMI_ERROR_CB_ID Error callback ID + * @arg @ref HAL_DCMI_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_DCMI_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status */ HAL_StatusTypeDef HAL_DCMI_UnRegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCMI_CallbackIDTypeDef CallbackID) { @@ -1005,15 +1062,15 @@ HAL_StatusTypeDef HAL_DCMI_UnRegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCM break; case HAL_DCMI_VSYNC_EVENT_CB_ID : - hdcmi->VsyncEventCallback = HAL_DCMI_VsyncEventCallback; /* Legacy weak VsyncEventCallback */ + hdcmi->VsyncEventCallback = HAL_DCMI_VsyncEventCallback; /* Legacy weak VsyncEventCallback */ break; case HAL_DCMI_LINE_EVENT_CB_ID : - hdcmi->LineEventCallback = HAL_DCMI_LineEventCallback; /* Legacy weak LineEventCallback */ + hdcmi->LineEventCallback = HAL_DCMI_LineEventCallback; /* Legacy weak LineEventCallback */ break; case HAL_DCMI_ERROR_CB_ID : - hdcmi->ErrorCallback = HAL_DCMI_ErrorCallback; /* Legacy weak ErrorCallback */ + hdcmi->ErrorCallback = HAL_DCMI_ErrorCallback; /* Legacy weak ErrorCallback */ break; case HAL_DCMI_MSPINIT_CB_ID : @@ -1067,52 +1124,65 @@ HAL_StatusTypeDef HAL_DCMI_UnRegisterCallback(DCMI_HandleTypeDef *hdcmi, HAL_DCM /** * @} */ + +/** + * @} + */ + /* Private functions ---------------------------------------------------------*/ /** @defgroup DCMI_Private_Functions DCMI Private Functions * @{ */ /** -* @brief DMA conversion complete callback. -* @param hdma pointer to a DMA_HandleTypeDef structure that contains -* the configuration information for the specified DMA module. -* @retval None -*/ + * @brief DMA conversion complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ static void DCMI_DMAXferCplt(DMA_HandleTypeDef *hdma) { - uint32_t tmp = 0; + uint32_t tmp ; DCMI_HandleTypeDef *hdcmi = (DCMI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - if (hdcmi->XferCount != 0) + if (hdcmi->XferCount != 0U) { /* Update memory 0 address location */ - tmp = ((hdcmi->DMA_Handle->Instance->CR) & DMA_SxCR_CT); - if (((hdcmi->XferCount % 2) == 0) && (tmp != 0)) + tmp = ((((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->CR) & DMA_SxCR_CT); + if (((hdcmi->XferCount % 2U) == 0U) && (tmp != 0U)) { - tmp = hdcmi->DMA_Handle->Instance->M0AR; - HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8 * hdcmi->XferSize)), MEMORY0); + tmp = ((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->M0AR; + (void)HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8U * hdcmi->XferSize)), MEMORY0); hdcmi->XferCount--; } /* Update memory 1 address location */ - else if ((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) == 0) + else if ((((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->CR & DMA_SxCR_CT) == 0U) { - tmp = hdcmi->DMA_Handle->Instance->M1AR; - HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8 * hdcmi->XferSize)), MEMORY1); + tmp = ((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->M1AR; + (void)HAL_DMAEx_ChangeMemory(hdcmi->DMA_Handle, (tmp + (8U * hdcmi->XferSize)), MEMORY1); hdcmi->XferCount--; } + else + { + /* Nothing to do */ + } } /* Update memory 0 address location */ - else if ((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) != 0) + else if ((((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->CR & DMA_SxCR_CT) != 0U) { - hdcmi->DMA_Handle->Instance->M0AR = hdcmi->pBuffPtr; + ((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->M0AR = hdcmi->pBuffPtr; } /* Update memory 1 address location */ - else if ((hdcmi->DMA_Handle->Instance->CR & DMA_SxCR_CT) == 0) + else if ((((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->CR & DMA_SxCR_CT) == 0U) { tmp = hdcmi->pBuffPtr; - hdcmi->DMA_Handle->Instance->M1AR = (tmp + (4 * hdcmi->XferSize)); + ((DMA_Stream_TypeDef *)(hdcmi->DMA_Handle->Instance))->M1AR = (tmp + (4U * hdcmi->XferSize)); hdcmi->XferCount = hdcmi->XferTransferNumber; } + else + { + /* Nothing to do */ + } /* Check if the frame is transferred */ if (hdcmi->XferCount == hdcmi->XferTransferNumber) @@ -1157,10 +1227,6 @@ static void DCMI_DMAError(DMA_HandleTypeDef *hdma) } -/** - * @} - */ - /** * @} */ @@ -1173,5 +1239,3 @@ static void DCMI_DMAError(DMA_HandleTypeDef *hdma) /** * @} */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi_ex.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi_ex.c index aa737d293..77009818a 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi_ex.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_dcmi_ex.c @@ -30,4 +30,3 @@ /* Exported functions --------------------------------------------------------*/ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash.c index 81fa0638f..5aa3fd1dc 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash.c @@ -216,9 +216,6 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u { HAL_StatusTypeDef status = HAL_OK; - /* Process Locked */ - __HAL_LOCK(&pFlash); - /* Check the parameters */ assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); @@ -363,8 +360,6 @@ void HAL_FLASH_IRQHandler(void) /* Disable Error source interrupt */ __HAL_FLASH_DISABLE_IT(FLASH_IT_ERR); - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); } } diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash_ex.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash_ex.c index be7aecc33..4d60fecc1 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash_ex.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_flash_ex.c @@ -205,9 +205,6 @@ 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_FLASH_TYPEERASE(pEraseInit->TypeErase)); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hash.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hash.c index 6a72b3d2f..8919c4476 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hash.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hash.c @@ -119,7 +119,7 @@ (#) HAL in interruption mode (interruptions driven) (##)Due to HASH peripheral hardware design, the peripheral interruption is triggered every 64 bytes. - This is why, for driver implementation simplicity’s sake, user is requested to enter a message the + This is why, for driver implementation simplicity s sake, user is requested to enter a message the length of which is a multiple of 4 bytes. (##) When the message length (in bytes) is not a multiple of words, a specific field exists in HASH_STR @@ -268,10 +268,10 @@ */ 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_GetDigest(const uint8_t *pMsgDigest, uint8_t Size); static HAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, uint32_t Timeout); -static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size); +static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size); static HAL_StatusTypeDef HASH_IT(HASH_HandleTypeDef *hhash); static uint32_t HASH_Write_Block_Data(HASH_HandleTypeDef *hhash); static HAL_StatusTypeDef HMAC_Processing(HASH_HandleTypeDef *hhash, uint32_t Timeout); @@ -751,7 +751,8 @@ HAL_StatusTypeDef HAL_HASH_UnRegisterCallback(HASH_HandleTypeDef *hhash, HAL_HAS * @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, +HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) { return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_MD5); @@ -777,7 +778,7 @@ HAL_StatusTypeDef HAL_HASH_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuff * @param Size length of the input buffer in bytes, must be a multiple of 4. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HASH_Accumulate(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); } @@ -792,7 +793,7 @@ HAL_StatusTypeDef HAL_HASH_MD5_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuf * @param Timeout Timeout value * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer, uint32_t Timeout) { return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_MD5); @@ -809,7 +810,8 @@ HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pI * @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, +HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) { return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA1); @@ -835,7 +837,7 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuf * @param Size length of the input buffer in bytes, must be a multiple of 4. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HASH_Accumulate(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); } @@ -850,7 +852,7 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt(HASH_HandleTypeDef *hhash, uint8_t *pInBu * @param Timeout Timeout value * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer, uint32_t Timeout) { return HASH_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA1); @@ -898,7 +900,7 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End(HASH_HandleTypeDef *hhash, uint8_t *p * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer) { return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_MD5); @@ -922,7 +924,7 @@ HAL_StatusTypeDef HAL_HASH_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInB * @param Size length of the input buffer in bytes, must be a multiple of 4. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HASH_Accumulate_IT(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); } @@ -936,7 +938,7 @@ HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pIn * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer) { return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_MD5); @@ -952,7 +954,7 @@ HAL_StatusTypeDef HAL_HASH_MD5_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer) { return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA1); @@ -977,7 +979,7 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pIn * @param Size length of the input buffer in bytes, must be a multiple of 4. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HASH_Accumulate_IT(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); } @@ -991,7 +993,7 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_IT(HASH_HandleTypeDef *hhash, uint8_t *pI * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HASH_SHA1_Accmlt_End_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer) { return HASH_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA1); @@ -1060,7 +1062,7 @@ void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash) * @param Size length of the input buffer in bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HASH_MD5_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HASH_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); } @@ -1090,7 +1092,7 @@ HAL_StatusTypeDef HAL_HASH_MD5_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBu * @param Size length of the input buffer in bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HASH_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HASH_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); } @@ -1147,7 +1149,8 @@ HAL_StatusTypeDef HAL_HASH_SHA1_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutB * @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, +HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) { return HMAC_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_MD5); @@ -1166,7 +1169,8 @@ HAL_StatusTypeDef HAL_HMAC_MD5_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuff * @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, +HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout) { return HMAC_Start(hhash, pInBuffer, Size, pOutBuffer, Timeout, HASH_ALGOSELECTION_SHA1); @@ -1208,7 +1212,7 @@ HAL_StatusTypeDef HAL_HMAC_SHA1_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuf * @param pOutBuffer pointer to the computed digest. Digest size is 16 bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer) { return HMAC_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_MD5); @@ -1226,7 +1230,7 @@ HAL_StatusTypeDef HAL_HMAC_MD5_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInB * @param pOutBuffer pointer to the computed digest. Digest size is 20 bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, +HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, uint8_t *pOutBuffer) { return HMAC_Start_IT(hhash, pInBuffer, Size, pOutBuffer, HASH_ALGOSELECTION_SHA1); @@ -1237,7 +1241,6 @@ HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pIn */ - /** @defgroup HASH_Exported_Functions_Group7 HMAC processing functions in DMA mode * @brief HMAC processing functions using DMA modes. * @@ -1274,7 +1277,7 @@ HAL_StatusTypeDef HAL_HMAC_SHA1_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pIn * @param Size length of the input buffer in bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_MD5); } @@ -1293,7 +1296,7 @@ HAL_StatusTypeDef HAL_HMAC_MD5_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pIn * @param Size length of the input buffer in bytes. * @retval HAL status */ -HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { return HMAC_Start_DMA(hhash, pInBuffer, Size, HASH_ALGOSELECTION_SHA1); } @@ -1340,7 +1343,7 @@ HAL_StatusTypeDef HAL_HMAC_SHA1_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pI * @param hhash HASH handle. * @retval HAL HASH state */ -HAL_HASH_StateTypeDef HAL_HASH_GetState(HASH_HandleTypeDef *hhash) +HAL_HASH_StateTypeDef HAL_HASH_GetState(const HASH_HandleTypeDef *hhash) { return hhash->State; } @@ -1353,7 +1356,7 @@ HAL_HASH_StateTypeDef HAL_HASH_GetState(HASH_HandleTypeDef *hhash) * @param hhash HASH handle. * @retval HAL status */ -HAL_StatusTypeDef HAL_HASH_GetStatus(HASH_HandleTypeDef *hhash) +HAL_StatusTypeDef HAL_HASH_GetStatus(const HASH_HandleTypeDef *hhash) { return hhash->Status; } @@ -1591,7 +1594,7 @@ HAL_StatusTypeDef HAL_HASH_DMAFeed_ProcessSuspend(HASH_HandleTypeDef *hhash) * @param hhash pointer to a HASH_HandleTypeDef structure. * @retval HASH Error Code */ -uint32_t HAL_HASH_GetError(HASH_HandleTypeDef *hhash) +uint32_t HAL_HASH_GetError(const HASH_HandleTypeDef *hhash) { /* Return HASH Error Code */ return hhash->ErrorCode; @@ -1785,12 +1788,13 @@ static void HASH_DMAError(DMA_HandleTypeDef *hdma) * suspension time is stored in the handle for resumption later on. * @retval HAL status */ -static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size) +static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) { uint32_t buffercounter; __IO uint32_t inputaddr = (uint32_t) pInBuffer; + uint32_t tmp; - for (buffercounter = 0U; buffercounter < Size; buffercounter += 4U) + for (buffercounter = 0U; buffercounter < (Size / 4U); buffercounter++) { /* Write input data 4 bytes at a time */ HASH->DIN = *(uint32_t *)inputaddr; @@ -1798,8 +1802,16 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB /* If the suspension flag has been raised and if the processing is not about to end, suspend processing */ - if ((hhash->SuspendRequest == HAL_HASH_SUSPEND) && ((buffercounter + 4U) < Size)) + if ((hhash->SuspendRequest == HAL_HASH_SUSPEND) && (((buffercounter * 4U) + 4U) < Size)) { + /* wait for flag BUSY not set before Wait for DINIS = 1*/ + if ((buffercounter * 4U) >= 64U) + { + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, HASH_TIMEOUTVALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + } /* Wait for DINIS = 1, which occurs when 16 32-bit locations are free in the input buffer */ if (__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) @@ -1814,14 +1826,14 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB /* Save current reading and writing locations of Input and Output buffers */ hhash->pHashInBuffPtr = (uint8_t *)inputaddr; /* Save the number of bytes that remain to be processed at this point */ - hhash->HashInCount = Size - (buffercounter + 4U); + hhash->HashInCount = Size - ((buffercounter * 4U) + 4U); } else if ((hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_1) || (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_3)) { /* Save current reading and writing locations of Input and Output buffers */ hhash->pHashKeyBuffPtr = (uint8_t *)inputaddr; /* Save the number of bytes that remain to be processed at this point */ - hhash->HashKeyCount = Size - (buffercounter + 4U); + hhash->HashKeyCount = Size - ((buffercounter * 4U) + 4U); } else { @@ -1840,6 +1852,51 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB } /* for(buffercounter = 0; buffercounter < Size; buffercounter+=4) */ /* At this point, all the data have been entered to the Peripheral: exit */ + + if ((Size % 4U) != 0U) + { + if (hhash->Init.DataType == HASH_DATATYPE_16B) + { + /* Write remaining input data */ + + if ((Size % 4U) <= 2U) + { + HASH->DIN = (uint32_t) * (uint16_t *)inputaddr; + } + if ((Size % 4U) == 3U) + { + HASH->DIN = *(uint32_t *)inputaddr; + } + + } + else if ((hhash->Init.DataType == HASH_DATATYPE_8B) + || (hhash->Init.DataType == HASH_DATATYPE_1B)) /* byte swap or bit swap or */ + { + /* Write remaining input data */ + if ((Size % 4U) == 1U) + { + HASH->DIN = (uint32_t) * (uint8_t *)inputaddr; + } + if ((Size % 4U) == 2U) + { + HASH->DIN = (uint32_t) * (uint16_t *)inputaddr; + } + if ((Size % 4U) == 3U) + { + tmp = *(uint8_t *)inputaddr; + tmp |= (uint32_t) * (uint8_t *)(inputaddr + 1U) << 8U; + tmp |= (uint32_t) * (uint8_t *)(inputaddr + 2U) << 16U; + HASH->DIN = tmp; + } + + } + else + { + HASH->DIN = *(uint32_t *)inputaddr; + } + } + + return HAL_OK; } @@ -1849,7 +1906,7 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB * @param Size message digest size in bytes. * @retval None */ -static void HASH_GetDigest(uint8_t *pMsgDigest, uint8_t Size) +static void HASH_GetDigest(const uint8_t *pMsgDigest, uint8_t Size) { uint32_t msgdigest = (uint32_t)pMsgDigest; @@ -1882,7 +1939,6 @@ static void HASH_GetDigest(uint8_t *pMsgDigest, uint8_t Size) } - /** * @brief Handle HASH processing Timeout. * @param hhash HASH handle. @@ -2368,10 +2424,11 @@ static HAL_StatusTypeDef HMAC_Processing(HASH_HandleTypeDef *hhash, uint32_t Tim * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout, uint32_t Algorithm) { - uint8_t *pInBuffer_tmp; /* input data address, input parameter of HASH_WriteData() */ + const uint8_t *pInBuffer_tmp; /* input data address, input parameter of HASH_WriteData() */ uint32_t Size_tmp; /* input data size (in bytes), input parameter of HASH_WriteData() */ HAL_HASH_StateTypeDef State_tmp = hhash->State; @@ -2403,7 +2460,7 @@ HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint /* pInBuffer_tmp and Size_tmp are initialized to be used afterwards as input parameters of HASH_WriteData() */ - pInBuffer_tmp = pInBuffer; /* pInBuffer_tmp is set to the input data address */ + pInBuffer_tmp = (const uint8_t *)pInBuffer; /* pInBuffer_tmp is set to the input data address */ Size_tmp = Size; /* Size_tmp contains the input data size in bytes */ /* Set the phase */ @@ -2419,7 +2476,7 @@ HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint /* Since this is resumption, pInBuffer_tmp and Size_tmp are not set to the API input parameters but to those saved beforehand by HASH_WriteData() when the processing was suspended */ - pInBuffer_tmp = hhash->pHashInBuffPtr; + pInBuffer_tmp = (const uint8_t *)hhash->pHashInBuffPtr; Size_tmp = hhash->HashInCount; } /* ... or multi-buffer HASH processing end */ @@ -2427,7 +2484,7 @@ HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint { /* pInBuffer_tmp and Size_tmp are initialized to be used afterwards as input parameters of HASH_WriteData() */ - pInBuffer_tmp = pInBuffer; + pInBuffer_tmp = (const uint8_t *)pInBuffer; Size_tmp = Size; /* Configure the number of valid bits in last word of the message */ __HAL_HASH_SET_NBVALIDBITS(Size); @@ -2505,9 +2562,10 @@ HAL_StatusTypeDef HASH_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm) { - uint8_t *pInBuffer_tmp; /* input data address, input parameter of HASH_WriteData() */ + const uint8_t *pInBuffer_tmp; /* input data address, input parameter of HASH_WriteData() */ uint32_t Size_tmp; /* input data size (in bytes), input parameter of HASH_WriteData() */ HAL_HASH_StateTypeDef State_tmp = hhash->State; @@ -2539,7 +2597,7 @@ HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, /* Since this is resumption, pInBuffer_tmp and Size_tmp are not set to the API input parameters but to those saved beforehand by HASH_WriteData() when the processing was suspended */ - pInBuffer_tmp = hhash->pHashInBuffPtr; /* pInBuffer_tmp is set to the input data address */ + pInBuffer_tmp = (const uint8_t *)hhash->pHashInBuffPtr; /* pInBuffer_tmp is set to the input data address */ Size_tmp = hhash->HashInCount; /* Size_tmp contains the input data size in bytes */ } @@ -2550,7 +2608,7 @@ HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, /* pInBuffer_tmp and Size_tmp are initialized to be used afterwards as input parameters of HASH_WriteData() */ - pInBuffer_tmp = pInBuffer; /* pInBuffer_tmp is set to the input data address */ + pInBuffer_tmp = (const uint8_t *)pInBuffer; /* pInBuffer_tmp is set to the input data address */ Size_tmp = Size; /* Size_tmp contains the input data size in bytes */ /* Check if initialization phase has already be performed */ @@ -2608,7 +2666,8 @@ HAL_StatusTypeDef HASH_Accumulate(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +HAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm) { HAL_HASH_StateTypeDef State_tmp = hhash->State; __IO uint32_t inputaddr = (uint32_t) pInBuffer; @@ -2718,7 +2777,6 @@ HAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuff } - /** * @brief Initialize the HASH peripheral, next process pInBuffer then * read the computed digest in interruption mode. @@ -2730,7 +2788,8 @@ HAL_StatusTypeDef HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuff * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Algorithm) { HAL_HASH_StateTypeDef State_tmp = hhash->State; @@ -2779,6 +2838,19 @@ HAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, u hhash->pHashOutBuffPtr = pOutBuffer; /* Points at the computed digest */ } + else if ((hhash->Phase == HAL_HASH_PHASE_PROCESS) && (SizeVar < 4U)) + { + if (__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) + { + /* It remains data to enter and the Peripheral is ready to trigger DINIE,carry on as usual. + Update HashInCount and pHashInBuffPtr accordingly. */ + hhash->HashInCount = SizeVar; + hhash->pHashInBuffPtr = (uint8_t *)inputaddr; + /* Update the configuration of the number of valid bits in last word of the message */ + __HAL_HASH_SET_NBVALIDBITS(SizeVar); + hhash->pHashOutBuffPtr = pOutBuffer; /* Points at the computed digest */ + } + } else { initialization_skipped = 1; /* info user later on in case of multi-buffer */ @@ -2882,7 +2954,8 @@ HAL_StatusTypeDef HASH_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, u * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +HAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm) { uint32_t inputaddr; uint32_t inputSize; @@ -3054,7 +3127,8 @@ HAL_StatusTypeDef HASH_Finish(HASH_HandleTypeDef *hhash, uint8_t *pOutBuffer, ui * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Timeout, uint32_t Algorithm) { HAL_HASH_StateTypeDef State_tmp = hhash->State; @@ -3118,7 +3192,6 @@ HAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint } - /** * @brief Initialize the HASH peripheral in HMAC mode, next process pInBuffer then * read the computed digest in interruption mode. @@ -3132,7 +3205,8 @@ HAL_StatusTypeDef HMAC_Start(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint8_t *pOutBuffer, +HAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *pOutBuffer, uint32_t Algorithm) { HAL_HASH_StateTypeDef State_tmp = hhash->State; @@ -3227,7 +3301,6 @@ HAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, u } - /** * @brief Initialize the HASH peripheral in HMAC mode then initiate the required * DMA transfers to feed the key and the input buffer to the Peripheral. @@ -3243,7 +3316,8 @@ HAL_StatusTypeDef HMAC_Start_IT(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, u * @param Algorithm HASH algorithm. * @retval HAL status */ -HAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, uint32_t Size, uint32_t Algorithm) +HAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Algorithm) { uint32_t inputaddr; uint32_t inputSize; @@ -3362,7 +3436,7 @@ HAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, /* Enable the DMA In DMA stream */ status = HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, \ (((inputSize % 4U) != 0U) ? ((inputSize + (4U - (inputSize % 4U))) / 4U) \ - : (inputSize / 4U))); + : (inputSize / 4U))); /* Enable DMA requests */ SET_BIT(HASH->CR, HASH_CR_DMAE); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hcd.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hcd.c index 47603637a..8df2d18af 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hcd.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_hcd.c @@ -109,7 +109,9 @@ static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd); */ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) { - USB_OTG_GlobalTypeDef *USBx; +#if defined (USB_OTG_FS) + const USB_OTG_GlobalTypeDef *USBx; +#endif /* defined (USB_OTG_FS) */ /* Check the HCD handle allocation */ if (hhcd == NULL) @@ -120,7 +122,9 @@ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) /* Check the parameters */ assert_param(IS_HCD_ALL_INSTANCE(hhcd->Instance)); +#if defined (USB_OTG_FS) USBx = hhcd->Instance; +#endif /* defined (USB_OTG_FS) */ if (hhcd->State == HAL_HCD_STATE_RESET) { @@ -150,23 +154,37 @@ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) hhcd->State = HAL_HCD_STATE_BUSY; +#if defined (USB_OTG_FS) /* Disable DMA mode for FS instance */ - if ((USBx->CID & (0x1U << 8)) == 0U) + if (USBx == USB_OTG_FS) { hhcd->Init.dma_enable = 0U; } +#endif /* defined (USB_OTG_FS) */ /* Disable the Interrupts */ __HAL_HCD_DISABLE(hhcd); /* Init the Core (common init.) */ - (void)USB_CoreInit(hhcd->Instance, hhcd->Init); + if (USB_CoreInit(hhcd->Instance, hhcd->Init) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } - /* Force Host Mode*/ - (void)USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE); + /* Force Host Mode */ + if (USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } /* Init Host */ - (void)USB_HostInit(hhcd->Instance, hhcd->Init); + if (USB_HostInit(hhcd->Instance, hhcd->Init) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } hhcd->State = HAL_HCD_STATE_READY; @@ -1261,7 +1279,7 @@ HAL_StatusTypeDef HAL_HCD_HC_ClearHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_nu */ static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1580,7 +1598,7 @@ static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) */ static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; uint32_t num_packets; @@ -1815,7 +1833,7 @@ static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) */ static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; uint32_t pktsts; uint32_t pktcnt; @@ -1881,7 +1899,7 @@ static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) */ static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd) { - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; __IO uint32_t hprt0; __IO uint32_t hprt0_dup; diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2c.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2c.c index 48eef2f09..af0030752 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2c.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2c.c @@ -89,7 +89,7 @@ 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() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() @@ -139,7 +139,7 @@ or using HAL_I2C_Master_Seq_Receive_DMA() (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() HAL_I2C_DisableListen_IT() @@ -193,7 +193,7 @@ 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() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() @@ -2831,6 +2831,11 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { + if (hi2c->XferSize == 3U) + { + /* Disable Acknowledge */ + CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); + } /* Read data from DR */ *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; @@ -4708,7 +4713,7 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) } /** - * @brief Abort a master I2C IT or DMA process communication with Interrupt. + * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress Target device address: The device 7 bits address value @@ -4724,7 +4729,8 @@ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevA UNUSED(DevAddress); /* Abort Master transfer during Receive or Transmit process */ - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && (CurrentMode == HAL_I2C_MODE_MASTER)) + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && ((CurrentMode == HAL_I2C_MODE_MASTER) || + (CurrentMode == HAL_I2C_MODE_MEM))) { /* Process Locked */ __HAL_LOCK(hi2c); @@ -5516,7 +5522,9 @@ static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { uint32_t tmp; + uint32_t CurrentXferOptions; + CurrentXferOptions = hi2c->XferOptions; tmp = hi2c->XferCount; if (tmp > 3U) { @@ -5572,7 +5580,14 @@ static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) else { hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) hi2c->MasterRxCpltCallback(hi2c); @@ -5675,15 +5690,11 @@ static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) /* Enable Acknowledge */ SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); } - else if (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP) + else { /* Generate Stop */ SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); } - else - { - /* Do nothing */ - } /* Read data from DR */ *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; @@ -5720,7 +5731,14 @@ static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) else { hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) hi2c->MasterRxCpltCallback(hi2c); #else @@ -7028,7 +7046,14 @@ static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma) else { hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) + { + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) hi2c->MasterRxCpltCallback(hi2c); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2s.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2s.c index 3f891a67b..af307e4b6 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2s.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_i2s.c @@ -796,15 +796,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uin return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -915,15 +914,14 @@ HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1013,15 +1011,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1040,6 +1037,8 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, hi2s->TxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable TXE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); @@ -1050,7 +1049,6 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1079,15 +1077,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1106,6 +1103,8 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u hi2s->RxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable RXNE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); @@ -1116,7 +1115,6 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1143,15 +1141,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1193,12 +1190,7 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Tx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_TXDMAEN)) @@ -1207,7 +1199,13 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } @@ -1234,15 +1232,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1290,12 +1287,7 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Rx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_RXDMAEN)) @@ -1304,7 +1296,13 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_iwdg.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_iwdg.c index 89d06006e..d9878d03f 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_iwdg.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_iwdg.c @@ -91,7 +91,6 @@ the reload register @endverbatim - ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ @@ -121,7 +120,8 @@ The timeout value is multiplied by 1000 to be converted in milliseconds. LSI startup time is also considered here by adding LSI_STARTUP_TIME converted in milliseconds. */ -#define HAL_IWDG_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) +#define HAL_IWDG_DEFAULT_TIMEOUT (((6UL * 256UL * 1000UL) / (LSI_VALUE / 128U)) + \ + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) #define IWDG_KERNEL_UPDATE_FLAGS (IWDG_SR_RVU | IWDG_SR_PVU) /** * @} diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_mmc.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_mmc.c index 9dcc03614..3cb2b1f2c 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_mmc.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_mmc.c @@ -2328,7 +2328,7 @@ HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32 if(errorstate != HAL_MMC_ERROR_NONE) { /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); hmmc->ErrorCode |= errorstate; return HAL_ERROR; } diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_nand.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_nand.c index 0976a7a6f..2bf27d23a 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_nand.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_nand.c @@ -506,7 +506,7 @@ HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand) * @param pDeviceConfig pointer to NAND_DeviceConfigTypeDef structure * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig) +HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, const NAND_DeviceConfigTypeDef *pDeviceConfig) { hnand->Config.PageSize = pDeviceConfig->PageSize; hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize; @@ -2036,6 +2036,7 @@ HAL_StatusTypeDef HAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_ status = HAL_ERROR; } + return status; } /** @@ -2094,6 +2095,7 @@ HAL_StatusTypeDef HAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAN status = HAL_ERROR; } + return status; } #endif /* USE_HAL_NAND_REGISTER_CALLBACKS */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pccard.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pccard.c index 2361d7e5e..fd998d9f9 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pccard.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pccard.c @@ -162,7 +162,8 @@ * @retval HAL status */ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FSMC_NAND_PCC_TimingTypeDef *ComSpaceTiming, - FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming) + FSMC_NAND_PCC_TimingTypeDef *AttSpaceTiming, + FSMC_NAND_PCC_TimingTypeDef *IOSpaceTiming) { /* Check the PCCARD controller state */ if (hpccard == NULL) @@ -186,7 +187,7 @@ HAL_StatusTypeDef HAL_PCCARD_Init(PCCARD_HandleTypeDef *hpccard, FSMC_NAND_PCC_T #else /* Initialize the low level hardware (MSP) */ HAL_PCCARD_MspInit(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ } /* Initialize the PCCARD state */ @@ -233,7 +234,7 @@ HAL_StatusTypeDef HAL_PCCARD_DeInit(PCCARD_HandleTypeDef *hpccard) #else /* De-Initialize the low level hardware (MSP) */ HAL_PCCARD_MspDeInit(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Configure the PCCARD registers with their reset values */ FSMC_PCCARD_DeInit(hpccard->Instance); @@ -306,8 +307,9 @@ __weak void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard) */ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_ID, index = 0U; - uint8_t status = 0; + uint32_t timeout = 0U; + uint32_t index = 0U; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -318,6 +320,9 @@ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t Comp return HAL_BUSY; } + /* Initialize timeout value */ + timeout = PCCARD_TIMEOUT_READ_ID; + /* Update the PCCARD controller state */ hpccard->State = HAL_PCCARD_STATE_BUSY; @@ -370,8 +375,9 @@ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t Comp HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR, index = 0U; - uint8_t status = 0; + uint32_t timeout = 0U; + uint32_t index = 0U; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -382,6 +388,9 @@ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t return HAL_BUSY; } + /* Initialize timeout value */ + timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR; + /* Update the PCCARD controller state */ hpccard->State = HAL_PCCARD_STATE_BUSY; @@ -447,8 +456,9 @@ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR, index = 0U; - uint8_t status = 0; + uint32_t timeout = 0U; + uint32_t index = 0U; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -459,6 +469,9 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ return HAL_BUSY; } + /* Initialize timeout value */ + timeout = PCCARD_TIMEOUT_READ_WRITE_SECTOR; + /* Update the PCCARD controller state */ hpccard->State = HAL_PCCARD_STATE_BUSY; @@ -521,7 +534,7 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ HAL_StatusTypeDef HAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus) { uint32_t timeout = PCCARD_TIMEOUT_ERASE_SECTOR; - uint8_t status = 0; + uint8_t status = 0U; /* Process Locked */ __HAL_LOCK(hpccard); @@ -623,7 +636,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt Rising edge pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_RISING_EDGE); @@ -637,7 +650,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt Level pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_LEVEL); @@ -651,7 +664,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt Falling edge pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_FALLING_EDGE); @@ -665,7 +678,7 @@ void HAL_PCCARD_IRQHandler(PCCARD_HandleTypeDef *hpccard) hpccard->ItCallback(hpccard); #else HAL_PCCARD_ITCallback(hpccard); -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /* Clear PCCARD interrupt FIFO empty pending bit */ __FSMC_PCCARD_CLEAR_FLAG(hpccard->Instance, FSMC_FLAG_FEMPT); @@ -822,7 +835,7 @@ HAL_StatusTypeDef HAL_PCCARD_UnRegisterCallback(PCCARD_HandleTypeDef *hpccard, H __HAL_UNLOCK(hpccard); return status; } -#endif +#endif /* USE_HAL_PCCARD_REGISTER_CALLBACKS */ /** * @} @@ -865,7 +878,8 @@ HAL_PCCARD_StateTypeDef HAL_PCCARD_GetState(PCCARD_HandleTypeDef *hpccard) */ HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) { - uint32_t timeout = PCCARD_TIMEOUT_STATUS, status_pccard = 0U; + uint32_t timeout = PCCARD_TIMEOUT_STATUS; + uint32_t status_pccard = 0U; /* Check the PCCARD controller state */ if (hpccard->State == HAL_PCCARD_STATE_BUSY) @@ -901,7 +915,8 @@ HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) */ HAL_PCCARD_StatusTypeDef HAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard) { - uint8_t data = 0U, status_pccard = PCCARD_BUSY; + uint8_t data = 0U; + uint8_t status_pccard = PCCARD_BUSY; /* Check the PCCARD controller state */ if (hpccard->State == HAL_PCCARD_STATE_BUSY) diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pcd.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pcd.c index 9946ab054..ae9999a87 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pcd.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_pcd.c @@ -122,7 +122,9 @@ static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) { - USB_OTG_GlobalTypeDef *USBx; +#if defined (USB_OTG_FS) + const USB_OTG_GlobalTypeDef *USBx; +#endif /* defined (USB_OTG_FS) */ uint8_t i; /* Check the PCD handle allocation */ @@ -134,7 +136,9 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) /* Check the parameters */ assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); +#if defined (USB_OTG_FS) USBx = hpcd->Instance; +#endif /* defined (USB_OTG_FS) */ if (hpcd->State == HAL_PCD_STATE_RESET) { @@ -169,11 +173,13 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) hpcd->State = HAL_PCD_STATE_BUSY; +#if defined (USB_OTG_FS) /* Disable DMA mode for FS instance */ - if ((USBx->CID & (0x1U << 8)) == 0U) + if (USBx == USB_OTG_FS) { hpcd->Init.dma_enable = 0U; } +#endif /* defined (USB_OTG_FS) */ /* Disable the Interrupts */ __HAL_PCD_DISABLE(hpcd); @@ -185,8 +191,12 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) return HAL_ERROR; } - /* Force Device Mode*/ - (void)USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE); + /* Force Device Mode */ + if (USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE) != HAL_OK) + { + hpcd->State = HAL_PCD_STATE_ERROR; + return HAL_ERROR; + } /* Init endpoints structures */ for (i = 0U; i < hpcd->Init.dev_endpoints; i++) @@ -1300,16 +1310,17 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) */ void HAL_PCD_WKUP_IRQHandler(PCD_HandleTypeDef *hpcd) { +#if defined (USB_OTG_FS) USB_OTG_GlobalTypeDef *USBx; - USBx = hpcd->Instance; - if ((USBx->CID & (0x1U << 8)) == 0U) + if (USBx == USB_OTG_FS) { /* Clear EXTI pending Bit */ __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG(); } else +#endif /* defined (USB_OTG_FS) */ { /* Clear EXTI pending Bit */ __HAL_USB_OTG_HS_WAKEUP_EXTI_CLEAR_FLAG(); @@ -1886,9 +1897,9 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef const *hpcd) * @param testmode USB Device high speed test mode * @retval HAL status */ -HAL_StatusTypeDef HAL_PCD_SetTestMode(PCD_HandleTypeDef *hpcd, uint8_t testmode) +HAL_StatusTypeDef HAL_PCD_SetTestMode(const PCD_HandleTypeDef *hpcd, uint8_t testmode) { - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; switch (testmode) @@ -1990,9 +2001,9 @@ static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) { USB_OTG_EPTypeDef *ep; - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->CID + 0x1U); + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; if (hpcd->Init.dma_enable == 1U) @@ -2101,9 +2112,9 @@ static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint */ static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) { - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->CID + 0x1U); + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; if ((gSNPSiD > USB_OTG_CORE_ID_300A) && diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rng.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rng.c index a49894b3f..acaf0e9e2 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rng.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rng.c @@ -689,15 +689,16 @@ uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng) void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng) { uint32_t rngclockerror = 0U; + uint32_t itflag = hrng->Instance->SR; /* RNG clock error interrupt occurred */ - if (__HAL_RNG_GET_IT(hrng, RNG_IT_CEI) != RESET) + if ((itflag & RNG_IT_CEI) == RNG_IT_CEI) { /* Update the error code */ hrng->ErrorCode = HAL_RNG_ERROR_CLOCK; rngclockerror = 1U; } - else if (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET) + else if ((itflag & RNG_IT_SEI) == RNG_IT_SEI) { /* Update the error code */ hrng->ErrorCode = HAL_RNG_ERROR_SEED; @@ -728,7 +729,7 @@ void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng) } /* Check RNG data ready interrupt occurred */ - if (__HAL_RNG_GET_IT(hrng, RNG_IT_DRDY) != RESET) + if ((itflag & RNG_IT_DRDY) == RNG_IT_DRDY) { /* Generate random number once, so disable the IT */ __HAL_RNG_DISABLE_IT(hrng); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc.c index 30fe52ca4..71cae3520 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc.c @@ -6,8 +6,8 @@ * This file provides firmware functions to manage the following * functionalities of the Real-Time Clock (RTC) peripheral: * + Initialization and de-initialization functions - * + RTC Calendar (Time and Date) configuration functions - * + RTC Alarms (Alarm A and Alarm B) configuration functions + * + Calendar (Time and Date) configuration functions + * + Alarms (Alarm A and Alarm B) configuration functions * + Peripheral Control functions * + Peripheral State functions * @@ -121,6 +121,12 @@ *** Callback registration *** ============================================= [..] + When the compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all + callbacks are set to the corresponding weak functions. + This is the recommended configuration in order to optimize memory/code + consumption footprint/performances. + [..] The compilation define USE_HAL_RTC_REGISTER_CALLBACKS when set to 1 allows the user to configure dynamically the driver callbacks. Use Function HAL_RTC_RegisterCallback() to register an interrupt callback. @@ -152,25 +158,21 @@ [..] By default, after the HAL_RTC_Init() and when the state is HAL_RTC_STATE_RESET, all callbacks are set to the corresponding weak functions: - examples AlarmAEventCallback(), WakeUpTimerEventCallback(). + examples AlarmAEventCallback(), TimeStampEventCallback(). Exception done for MspInit() and MspDeInit() callbacks that are reset to the - legacy weak function in the HAL_RTC_Init()/HAL_RTC_DeInit() only - when these callbacks are null (not registered beforehand). + legacy weak function in the HAL_RTC_Init()/HAL_RTC_DeInit() only when these + callbacks are null (not registered beforehand). If not, MspInit() or MspDeInit() are not null, HAL_RTC_Init()/HAL_RTC_DeInit() keep and use the user MspInit()/MspDeInit() callbacks (registered beforehand). [..] Callbacks can be registered/unregistered in HAL_RTC_STATE_READY state only. - Exception done MspInit()/MspDeInit() that can be registered/unregistered + Exception done for MspInit() and MspDeInit() that can be registered/unregistered in HAL_RTC_STATE_READY or HAL_RTC_STATE_RESET state. Thus registered (user) MspInit()/MspDeInit() callbacks can be used during the Init/DeInit. - In that case first register the MspInit()/MspDeInit() user callbacks - using HAL_RTC_RegisterCallback() before calling HAL_RTC_DeInit() - or HAL_RTC_Init() functions. - [..] - When The compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all - callbacks are set to the corresponding weak functions. + In that case first register the MspInit()/MspDeInit() user callbacks using + HAL_RTC_RegisterCallback() before calling HAL_RTC_DeInit() or HAL_RTC_Init() + functions. @endverbatim ****************************************************************************** @@ -426,9 +428,9 @@ HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) * @arg @ref HAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID * @arg @ref HAL_RTC_TIMESTAMP_EVENT_CB_ID Timestamp Event Callback ID * @arg @ref HAL_RTC_WAKEUPTIMER_EVENT_CB_ID Wakeup Timer Event Callback ID - * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID - * @arg @ref HAL_RTC_MSPINIT_CB_ID Msp Init callback ID - * @arg @ref HAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID + * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Event Callback ID + * @arg @ref HAL_RTC_MSPINIT_CB_ID MSP Init callback ID + * @arg @ref HAL_RTC_MSPDEINIT_CB_ID MSP DeInit callback ID * @param pCallback pointer to the Callback function * @retval HAL status */ @@ -523,9 +525,9 @@ HAL_StatusTypeDef HAL_RTC_RegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_Call * @arg @ref HAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID * @arg @ref HAL_RTC_TIMESTAMP_EVENT_CB_ID Timestamp Event Callback ID * @arg @ref HAL_RTC_WAKEUPTIMER_EVENT_CB_ID Wakeup Timer Event Callback ID - * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID - * @arg @ref HAL_RTC_MSPINIT_CB_ID Msp Init callback ID - * @arg @ref HAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID + * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Event Callback ID + * @arg @ref HAL_RTC_MSPINIT_CB_ID MSP Init callback ID + * @arg @ref HAL_RTC_MSPDEINIT_CB_ID MSP DeInit callback ID * @retval HAL status */ HAL_StatusTypeDef HAL_RTC_UnRegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_CallbackIDTypeDef CallbackID) @@ -1006,7 +1008,7 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TR_PM_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ ((uint32_t)sAlarm->AlarmMask)); @@ -1039,7 +1041,7 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ ((uint32_t) sAlarm->AlarmTime.Seconds) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TR_PM_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ ((uint32_t) sAlarm->AlarmDateWeekDaySel) | \ ((uint32_t) sAlarm->AlarmMask)); @@ -1048,16 +1050,15 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA /* 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 */ + /* Disable Alarm A */ __HAL_RTC_ALARMA_DISABLE(hrtc); /* In case interrupt mode is used, the interrupt source must be disabled */ __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); - /* Clear the Alarm flag */ + /* Clear Alarm A flag */ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); /* Get tick */ @@ -1080,19 +1081,20 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA } } + /* Configure Alarm A register */ hrtc->Instance->ALRMAR = (uint32_t)tmpreg; - /* Configure the Alarm state: Enable Alarm */ + /* Enable Alarm A */ __HAL_RTC_ALARMA_ENABLE(hrtc); } else { - /* Disable the Alarm B */ + /* Disable Alarm B */ __HAL_RTC_ALARMB_DISABLE(hrtc); /* In case interrupt mode is used, the interrupt source must be disabled */ __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRB); - /* Clear the Alarm flag */ + /* Clear Alarm B flag */ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); /* Get tick */ @@ -1115,8 +1117,9 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA } } + /* Configure Alarm B register */ hrtc->Instance->ALRMBR = (uint32_t)tmpreg; - /* Configure the Alarm state: Enable Alarm */ + /* Enable Alarm B */ __HAL_RTC_ALARMB_ENABLE(hrtc); } @@ -1192,7 +1195,7 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TR_PM_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ ((uint32_t)sAlarm->AlarmMask)); @@ -1225,7 +1228,7 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ ((uint32_t) sAlarm->AlarmTime.Seconds) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_TR_PM_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ ((uint32_t) sAlarm->AlarmDateWeekDaySel) | \ ((uint32_t) sAlarm->AlarmMask)); @@ -1234,13 +1237,12 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef /* 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 */ + /* Disable Alarm A */ __HAL_RTC_ALARMA_DISABLE(hrtc); - /* Clear the Alarm flag */ + /* Clear Alarm A flag */ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); /* Wait till RTC ALRAWF flag is set and if timeout is reached exit */ @@ -1261,18 +1263,19 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef } } while (__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == 0U); + /* Configure Alarm A register */ hrtc->Instance->ALRMAR = (uint32_t)tmpreg; - /* Configure the Alarm state: Enable Alarm */ + /* Enable Alarm A */ __HAL_RTC_ALARMA_ENABLE(hrtc); - /* Configure the Alarm interrupt */ + /* Enable Alarm A interrupt */ __HAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRA); } else { - /* Disable the Alarm B */ + /* Disable Alarm B */ __HAL_RTC_ALARMB_DISABLE(hrtc); - /* Clear the Alarm flag */ + /* Clear Alarm B flag */ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); /* Reload the counter */ @@ -1296,14 +1299,15 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef } } while (__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == 0U); + /* Configure Alarm B register */ hrtc->Instance->ALRMBR = (uint32_t)tmpreg; - /* Configure the Alarm state: Enable Alarm */ + /* Enable Alarm B */ __HAL_RTC_ALARMB_ENABLE(hrtc); - /* Configure the Alarm interrupt */ + /* Enable Alarm B interrupt */ __HAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRB); } - /* RTC Alarm Interrupt Configuration: EXTI configuration */ + /* Enable and configure the EXTI line associated to the RTC Alarm interrupt */ __HAL_RTC_ALARM_EXTI_ENABLE_IT(); __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE(); @@ -1355,7 +1359,7 @@ HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alar /* Get tick */ tickstart = HAL_GetTick(); - /* Wait till RTC ALRxWF flag is set and if timeout is reached exit */ + /* Wait till RTC ALRAWF flag is set and if timeout is reached exit */ while (__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == 0U) { if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) @@ -1383,7 +1387,7 @@ HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alar /* Get tick */ tickstart = HAL_GetTick(); - /* Wait till RTC ALRxWF flag is set and if timeout is reached exit */ + /* Wait till RTC ALRBWF flag is set and if timeout is reached exit */ while (__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == 0U) { if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) @@ -1476,7 +1480,7 @@ HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA */ void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc) { - /* Clear the EXTI's line Flag for RTC Alarm */ + /* Clear the EXTI flag associated to the RTC Alarm interrupt */ __HAL_RTC_ALARM_EXTI_CLEAR_FLAG(); /* Get the Alarm A interrupt source enable status */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc_ex.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc_ex.c index bacc521da..bcfa52e14 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc_ex.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_rtc_ex.c @@ -58,7 +58,7 @@ *** Tamper configuration *** ============================ [..] - (+) To Enable the RTC Tamper and configure the Tamper filter count, trigger + (+) To enable the RTC Tamper and configure the Tamper filter count, trigger Edge or Level according to the Tamper filter value (if equal to 0 Edge else Level), sampling frequency, precharge or discharge and Pull-UP use the HAL_RTCEx_SetTamper() function. @@ -96,8 +96,8 @@ 0 to 62. (+) In order to measure the clock deviation, a 512 Hz clock is output for calibration. - (+) The RTC Coarse Digital Calibration value and sign can be calibrated using - the HAL_RTCEx_SetCoarseCalib() function. + (+) To configure the RTC Coarse Digital Calibration value and sign use the + HAL_RTCEx_SetCoarseCalib() function. @endverbatim ****************************************************************************** @@ -272,7 +272,7 @@ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t RT /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - /* RTC Timestamp Interrupt Configuration: EXTI configuration */ + /* Enable and configure the EXTI line associated to the RTC Timestamp and Tamper interrupts */ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT(); __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE(); @@ -303,7 +303,7 @@ HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - /* In case of interrupt mode is used, the interrupt source must disabled */ + /* In case 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 */ @@ -493,7 +493,7 @@ HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperType /* Copy desired configuration into configuration register */ hrtc->Instance->TAFCR = tmpreg; - /* RTC Tamper Interrupt Configuration: EXTI configuration */ + /* Enable and configure the EXTI line associated to the RTC Timestamp and Tamper interrupts */ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT(); __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE(); @@ -543,7 +543,7 @@ HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t T */ void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc) { - /* Clear the EXTI's Flag for RTC Timestamp and Tamper */ + /* Clear the EXTI flag associated to the RTC Timestamp and Tamper interrupts */ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG(); /* Get the Timestamp interrupt source enable status */ @@ -894,7 +894,7 @@ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t /* Configure the Wakeup Timer counter */ hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; - /* RTC wakeup timer Interrupt Configuration: EXTI configuration */ + /* Enable and configure the EXTI line associated to the RTC Wakeup Timer interrupt */ __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT(); __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE(); @@ -936,7 +936,7 @@ HAL_StatusTypeDef HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) /* Disable the Wakeup Timer */ __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); - /* In case of interrupt mode is used, the interrupt source must disabled */ + /* In case interrupt mode is used, the interrupt source must disabled */ __HAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc, RTC_IT_WUT); /* Get tick */ @@ -995,7 +995,7 @@ uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc) */ void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) { - /* Clear the EXTI's line Flag for RTC WakeUpTimer */ + /* Clear the EXTI flag associated to the RTC Wakeup Timer interrupt */ __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG(); /* Get the pending status of the Wakeup timer Interrupt */ @@ -1111,7 +1111,7 @@ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint3 /* Check the parameters */ assert_param(IS_RTC_BKP(BackupRegister)); - tmp = (uint32_t) & (hrtc->Instance->BKP0R); + tmp = (uint32_t) &(hrtc->Instance->BKP0R); tmp += (BackupRegister * 4U); /* Write the specified register */ @@ -1134,7 +1134,7 @@ uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) /* Check the parameters */ assert_param(IS_RTC_BKP(BackupRegister)); - tmp = (uint32_t) & (hrtc->Instance->BKP0R); + tmp = (uint32_t) &(hrtc->Instance->BKP0R); tmp += (BackupRegister * 4U); /* Read the specified register */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sd.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sd.c index 30dddb5eb..dc21c76c7 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sd.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sd.c @@ -403,7 +403,6 @@ HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd) HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) { uint32_t errorstate; - HAL_StatusTypeDef status; SD_InitTypeDef Init; /* Default SDIO peripheral configuration for SD card initialization */ @@ -415,11 +414,7 @@ HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) Init.ClockDiv = SDIO_INIT_CLK_DIV; /* Initialize SDIO peripheral interface with default configuration */ - status = SDIO_Init(hsd->Instance, Init); - if(status != HAL_OK) - { - return HAL_ERROR; - } + SDIO_Init(hsd->Instance, Init); /* Disable SDIO Clock */ __HAL_SD_DISABLE(hsd); @@ -692,7 +687,7 @@ HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint3 } /* Get error state */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { /* Clear all the static flags */ __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); @@ -903,7 +898,7 @@ HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint } /* Get error state */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { /* Clear all the static flags */ __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); @@ -2868,13 +2863,13 @@ static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) } } - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + if((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) { return HAL_SD_ERROR_TIMEOUT; } } - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { return HAL_SD_ERROR_DATA_TIMEOUT; } @@ -2896,7 +2891,7 @@ static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) *pData = SDIO_ReadFIFO(hsd->Instance); pData++; - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + if((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) { return HAL_SD_ERROR_TIMEOUT; } @@ -3088,13 +3083,13 @@ static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) break; } - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + if((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) { return HAL_SD_ERROR_TIMEOUT; } } - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) || (__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR))) { __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_spi.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_spi.c index de0b4a998..c82cd4fff 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_spi.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_spi.c @@ -44,7 +44,8 @@ (+++) Configure the DMA handle parameters (+++) Configure the DMA Tx or Rx Stream/Channel (+++) Associate the initialized hdma_tx(or _rx) 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/Channel + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx + or Rx Stream/Channel (#) Program the Mode, BidirectionalMode , Data size, Baudrate Prescaler, NSS management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure. @@ -190,7 +191,8 @@ @note The max SPI frequency depend on SPI data size (8bits, 16bits), SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA). @note - (#) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and HAL_SPI_TransmitReceive_DMA() + (#) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and + HAL_SPI_TransmitReceive_DMA() (#) RX processes are HAL_SPI_Receive(), HAL_SPI_Receive_IT() and HAL_SPI_Receive_DMA() (#) TX processes are HAL_SPI_Transmit(), HAL_SPI_Transmit_IT() and HAL_SPI_Transmit_DMA() @@ -765,38 +767,35 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @param Timeout Timeout duration * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; uint16_t initial_TxXferCount; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); initial_TxXferCount = Size; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -835,7 +834,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -845,7 +844,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -854,9 +853,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -866,7 +865,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; } @@ -875,7 +874,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; } @@ -884,9 +883,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -911,19 +910,18 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint __HAL_SPI_CLEAR_OVRFLAG(hspi); } + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -941,12 +939,10 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 __IO uint32_t tmpreg = 0U; #endif /* USE_SPI_CRC */ uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) @@ -956,18 +952,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); } - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1026,9 +1021,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1050,9 +1045,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1069,8 +1064,8 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { /* the latest data has not been received */ - errorcode = HAL_TIMEOUT; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Receive last data in 16 Bit mode */ @@ -1088,8 +1083,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC to Flush DR and RXNE flag */ @@ -1114,18 +1110,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 } #endif /* USE_SPI_CRC */ + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1138,8 +1133,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) { uint16_t initial_TxXferCount; uint32_t tmp_mode; @@ -1151,14 +1146,10 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Variable used to alternate Rx and Tx during transfer */ uint32_t txallowed = 1U; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); @@ -1168,18 +1159,20 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD initial_TxXferCount = Size; if (!((tmp_state == HAL_SPI_STATE_READY) || \ - ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && + (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1191,7 +1184,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD hspi->pRxBuffPtr = (uint8_t *)pRxData; hspi->RxXferCount = Size; hspi->RxXferSize = Size; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferCount = Size; hspi->TxXferSize = Size; @@ -1219,16 +1212,25 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } +#endif /* USE_SPI_CRC */ + } while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) { /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1254,9 +1256,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if (((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1265,16 +1267,24 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; + +#if (USE_SPI_CRC != 0U) + /* Enable CRC Transmission */ + if ((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } +#endif /* USE_SPI_CRC */ } while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) { /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1300,9 +1310,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if ((((HAL_GetTick() - tickstart) >= Timeout) && ((Timeout != HAL_MAX_DELAY))) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1316,8 +1326,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { /* Error on the CRC reception */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC */ tmpreg = READ_REG(hspi->Instance->DR); @@ -1331,17 +1342,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); /* Clear CRC Flag */ __HAL_SPI_CLEAR_CRCERRFLAG(hspi); - - errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } #endif /* USE_SPI_CRC */ /* Check the end of the transaction */ if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK) { - errorcode = HAL_ERROR; hspi->ErrorCode = HAL_SPI_ERROR_FLAG; - goto error; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Clear overrun flag in 2 Lines communication mode because received is not read */ @@ -1350,18 +1361,19 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD __HAL_SPI_CLEAR_OVRFLAG(hspi); } + + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1372,32 +1384,30 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1433,10 +1443,6 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u } #endif /* USE_SPI_CRC */ - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); - - /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) { @@ -1444,9 +1450,12 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } -error : + /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1459,13 +1468,10 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) @@ -1475,15 +1481,15 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1523,9 +1529,6 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui } #endif /* USE_SPI_CRC */ - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); - /* Note : The SPI must be enabled after unlocking current process to avoid the risk of SPI interrupt handle execution before current process unlock */ @@ -1537,10 +1540,12 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui __HAL_SPI_ENABLE(hspi); } -error : /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1552,35 +1557,34 @@ error : * @param Size amount of data to be sent and received * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; if (!((tmp_state == HAL_SPI_STATE_READY) || \ - ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && + (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1589,7 +1593,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1616,8 +1620,6 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p } #endif /* USE_SPI_CRC */ - /* Enable TXE, RXNE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); /* Check if the SPI is already enabled */ if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) @@ -1626,10 +1628,12 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p __HAL_SPI_ENABLE(hspi); } -error : /* Process Unlocked */ __HAL_UNLOCK(hspi); - return errorcode; + /* Enable TXE, RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + return HAL_OK; } /** @@ -1640,9 +1644,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check tx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx)); @@ -1650,25 +1653,23 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1713,9 +1714,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1725,16 +1726,16 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1749,15 +1750,12 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - /* Check rx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) @@ -1771,15 +1769,14 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); - if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1827,9 +1824,9 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1839,16 +1836,16 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Rx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1861,12 +1858,11 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u * @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, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check rx & tx dma handles */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); @@ -1875,26 +1871,25 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; if (!((tmp_state == HAL_SPI_STATE_READY) || - ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) + ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && + (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1903,7 +1898,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1948,9 +1943,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Enable Rx DMA Request */ @@ -1969,9 +1964,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1980,16 +1975,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Enable SPI peripheral */ __HAL_SPI_ENABLE(hspi); } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -2355,9 +2351,11 @@ HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) { HAL_StatusTypeDef errorcode = HAL_OK; /* The Lock is not implemented on this API to allow the user application - to call the HAL SPI API under callbacks HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback(): + to call the HAL SPI API under callbacks HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or + HAL_SPI_TxRxCpltCallback(): when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated - and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback() + and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or + HAL_SPI_TxRxCpltCallback() */ /* Abort the SPI DMA tx Stream/Channel */ @@ -2647,7 +2645,7 @@ __weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI state */ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi) { /* Return SPI handle state */ return hspi->State; @@ -2659,7 +2657,7 @@ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI error code in bitmap format */ -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi) { /* Return SPI ErrorCode */ return hspi->ErrorCode; @@ -2686,7 +2684,7 @@ uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) */ static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); uint32_t tickstart; /* Init tickstart for timeout management*/ @@ -2743,7 +2741,7 @@ static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); uint32_t tickstart; #if (USE_SPI_CRC != 0U) __IO uint32_t tmpreg = 0U; @@ -2832,7 +2830,7 @@ static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); uint32_t tickstart; #if (USE_SPI_CRC != 0U) __IO uint32_t tmpreg = 0U; @@ -2912,7 +2910,7 @@ static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Call user Tx half complete callback */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) @@ -2930,7 +2928,7 @@ static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Call user Rx half complete callback */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) @@ -2948,7 +2946,7 @@ static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Call user TxRx half complete callback */ #if (USE_HAL_SPI_REGISTER_CALLBACKS == 1U) @@ -2966,7 +2964,7 @@ static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) */ static void SPI_DMAError(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Stop the disable DMA transfer on SPI side */ CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); @@ -2989,7 +2987,7 @@ static void SPI_DMAError(DMA_HandleTypeDef *hdma) */ static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); hspi->RxXferCount = 0U; hspi->TxXferCount = 0U; @@ -3011,7 +3009,7 @@ static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) */ static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); __IO uint32_t count; hspi->hdmatx->XferAbortCallback = NULL; @@ -3076,7 +3074,7 @@ static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) */ static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma) { - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Derogation MISRAC2012-Rule-11.5 */ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); /* Disable SPI Peripheral */ __HAL_SPI_DISABLE(hspi); @@ -3198,7 +3196,7 @@ static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) */ static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3291,7 +3289,7 @@ static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3439,7 +3437,7 @@ static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) */ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3465,7 +3463,7 @@ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3586,6 +3584,13 @@ static HAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t */ static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart) { + /* Wait until TXE flag */ + if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_TXE, SET, Timeout, Tickstart) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + return HAL_TIMEOUT; + } + /* Control the BSY flag */ if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != HAL_OK) { diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sram.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sram.c index 2d907eb3e..04738f3b9 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sram.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_sram.c @@ -208,7 +208,7 @@ HAL_StatusTypeDef HAL_SRAM_Init(SRAM_HandleTypeDef *hsram, FSMC_NORSRAM_TimingTy /* Initialize SRAM extended mode timing Interface */ (void)FSMC_NORSRAM_Extended_Timing_Init(hsram->Extended, ExtTiming, hsram->Init.NSBank, - hsram->Init.ExtendedMode); + hsram->Init.ExtendedMode); /* Enable the NORSRAM device */ __FSMC_NORSRAM_ENABLE(hsram->Instance, hsram->Init.NSBank); @@ -1037,6 +1037,7 @@ HAL_SRAM_StateTypeDef HAL_SRAM_GetState(const SRAM_HandleTypeDef *hsram) */ static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) { + /* Derogation MISRAC2012-Rule-11.5 */ SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); /* Disable the DMA channel */ @@ -1059,6 +1060,7 @@ static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) */ static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) { + /* Derogation MISRAC2012-Rule-11.5 */ SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); /* Disable the DMA channel */ @@ -1081,6 +1083,7 @@ static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) */ static void SRAM_DMAError(DMA_HandleTypeDef *hdma) { + /* Derogation MISRAC2012-Rule-11.5 */ SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); /* Disable the DMA channel */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim.c index 80cc1e8cb..30037a4c1 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim.c @@ -3822,13 +3822,16 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Cha */ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) { + uint32_t itsource = htim->Instance->DIER; + uint32_t itflag = htim->Instance->SR; + /* Capture compare 1 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET) + if ((itflag & (TIM_FLAG_CC1)) == (TIM_FLAG_CC1)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) != RESET) + if ((itsource & (TIM_IT_CC1)) == (TIM_IT_CC1)) { { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC1); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; /* Input capture event */ @@ -3856,11 +3859,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* Capture compare 2 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET) + if ((itflag & (TIM_FLAG_CC2)) == (TIM_FLAG_CC2)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) != RESET) + if ((itsource & (TIM_IT_CC2)) == (TIM_IT_CC2)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC2); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; /* Input capture event */ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) @@ -3886,11 +3889,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* Capture compare 3 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET) + if ((itflag & (TIM_FLAG_CC3)) == (TIM_FLAG_CC3)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) != RESET) + if ((itsource & (TIM_IT_CC3)) == (TIM_IT_CC3)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC3); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) @@ -3916,11 +3919,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* Capture compare 4 event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET) + if ((itflag & (TIM_FLAG_CC4)) == (TIM_FLAG_CC4)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) != RESET) + if ((itsource & (TIM_IT_CC4)) == (TIM_IT_CC4)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC4); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; /* Input capture event */ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) @@ -3946,11 +3949,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Update event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET) + if ((itflag & (TIM_FLAG_UPDATE)) == (TIM_FLAG_UPDATE)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) != RESET) + if ((itsource & (TIM_IT_UPDATE)) == (TIM_IT_UPDATE)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_UPDATE); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->PeriodElapsedCallback(htim); #else @@ -3959,11 +3962,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Break input event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET) + if ((itflag & (TIM_FLAG_BREAK)) == (TIM_FLAG_BREAK)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET) + if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->BreakCallback(htim); #else @@ -3972,11 +3975,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM Trigger detection event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET) + if ((itflag & (TIM_FLAG_TRIGGER)) == (TIM_FLAG_TRIGGER)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) != RESET) + if ((itsource & (TIM_IT_TRIGGER)) == (TIM_IT_TRIGGER)) { - __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TRIGGER); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->TriggerCallback(htim); #else @@ -3985,11 +3988,11 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) } } /* TIM commutation event */ - if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET) + if ((itflag & (TIM_FLAG_COM)) == (TIM_FLAG_COM)) { - if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) != RESET) + if ((itsource & (TIM_IT_COM)) == (TIM_IT_COM)) { - __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM); + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_COM); #if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) htim->CommutationCallback(htim); #else @@ -4476,7 +4479,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_O * @retval HAL status */ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, uint32_t BurstLength) + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength) { HAL_StatusTypeDef status; @@ -6810,6 +6814,13 @@ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, const TIM_Base_InitTypeDef *Structure /* Generate an update event to reload the Prescaler and the repetition counter (only for advanced timer) value immediately */ TIMx->EGR = TIM_EGR_UG; + + /* Check if the update flag is set after the Update Generation, if so clear the UIF flag */ + if (HAL_IS_BIT_SET(TIMx->SR, TIM_FLAG_UPDATE)) + { + /* Clear the update flag */ + CLEAR_BIT(TIMx->SR, TIM_FLAG_UPDATE); + } } /** @@ -6934,7 +6945,6 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) tmpccer |= (OC_Config->OCNPolarity << 4U); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC2NE; - } if (IS_TIM_BREAK_INSTANCE(TIMx)) diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim_ex.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim_ex.c index 85e84f50d..2af37ec3b 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim_ex.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_tim_ex.c @@ -835,7 +835,7 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channe /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; - if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == (uint32_t)RESET) + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } @@ -1081,17 +1081,6 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chann (+) 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 * @{ */ @@ -1317,7 +1306,7 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Chann /* Disable the TIM Break interrupt (only if no more channel is active) */ tmpccer = htim->Instance->CCER; - if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == (uint32_t)RESET) + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) { __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); } @@ -2122,7 +2111,7 @@ HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) */ /** - * @brief Hall commutation changed callback in non-blocking mode + * @brief Commutation callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2136,7 +2125,7 @@ __weak void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) */ } /** - * @brief Hall commutation changed half complete callback in non-blocking mode + * @brief Commutation half complete callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2151,7 +2140,7 @@ __weak void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim) } /** - * @brief Hall Break detection callback in non-blocking mode + * @brief Break detection callback in non-blocking mode * @param htim TIM handle * @retval None */ @@ -2302,15 +2291,6 @@ static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); } } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - - if (hdma->Init.Mode == DMA_NORMAL) - { - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); - } - } else { /* nothing to do */ @@ -2379,13 +2359,13 @@ static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Cha { uint32_t tmp; - tmp = TIM_CCER_CC1NE << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ + tmp = TIM_CCER_CC1NE << (Channel & 0xFU); /* 0xFU = 15 bits max shift */ /* Reset the CCxNE Bit */ TIMx->CCER &= ~tmp; /* Set or reset the CCxNE Bit */ - TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ + TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0xFU)); /* 0xFU = 15 bits max shift */ } /** * @} diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_uart.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_uart.c index 0e117a598..3ea2da539 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_uart.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_uart.c @@ -1165,6 +1165,8 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pD { if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { + huart->gState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; } if (pdata8bits == NULL) @@ -1182,6 +1184,8 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pD if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) { + huart->gState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; } @@ -1249,6 +1253,8 @@ HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, ui { if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) { + huart->RxState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; } if (pdata8bits == NULL) @@ -1777,21 +1783,18 @@ HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_ status = UART_Start_Receive_DMA(huart, pData, Size); /* Check Rx process has been successfully started */ - if (status == HAL_OK) + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) { - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - __HAL_UART_CLEAR_IDLEFLAG(huart); - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - } - else - { - /* In case of errors already pending when reception is started, - Interrupts may have already been raised and lead to reception abortion. - (Overrun error for instance). - In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ - status = HAL_ERROR; - } + __HAL_UART_CLEAR_IDLEFLAG(huart); + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + } + else + { + /* In case of errors already pending when reception is started, + Interrupts may have already been raised and lead to reception abortion. + (Overrun error for instance). + In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ + status = HAL_ERROR; } return status; @@ -3179,19 +3182,31 @@ static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; + return HAL_TIMEOUT; + } - /* Process Unlocked */ - __HAL_UNLOCK(huart); + if ((READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) && (Flag != UART_FLAG_TXE) && (Flag != UART_FLAG_TC)) + { + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) == SET) + { + /* Clear Overrun Error flag*/ + __HAL_UART_CLEAR_OREFLAG(huart); - return HAL_TIMEOUT; + /* Blocking error : transfer is aborted + Set the UART state ready to be able to start again the process, + Disable Rx Interrupts if ongoing */ + UART_EndRxTransfer(huart); + + huart->ErrorCode = HAL_UART_ERROR_ORE; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_ERROR; + } } } } diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_usart.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_usart.c index dcc8ea9c9..32d42ead4 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_usart.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_usart.c @@ -2080,6 +2080,9 @@ uint32_t HAL_USART_GetError(const USART_HandleTypeDef *husart) return husart->ErrorCode; } +/** + * @} + */ /** * @} */ @@ -2794,10 +2797,6 @@ static void USART_SetConfig(USART_HandleTypeDef *husart) } } -/** - * @} - */ - /** * @} */ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_wwdg.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_wwdg.c index 9cc9b1235..8ac487ee7 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_wwdg.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_hal_wwdg.c @@ -122,7 +122,6 @@ (+) __HAL_WWDG_ENABLE_IT: Enable the WWDG early wakeup interrupt @endverbatim - ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_fsmc.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_fsmc.c index d4f52dc3d..5c0c20d73 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_fsmc.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_fsmc.c @@ -60,7 +60,7 @@ * @{ */ #if defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) || defined(HAL_PCCARD_MODULE_ENABLED) \ - || defined(HAL_SRAM_MODULE_ENABLED) + || defined(HAL_SRAM_MODULE_ENABLED) /** @defgroup FSMC_LL FSMC Low Layer * @brief FSMC driver modules @@ -193,7 +193,7 @@ * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_InitTypeDef *Init) + const FSMC_NORSRAM_InitTypeDef *Init) { uint32_t flashaccess; uint32_t btcr_reg; @@ -273,7 +273,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank) + FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank) { /* Check the parameters */ assert_param(IS_FSMC_NORSRAM_DEVICE(Device)); @@ -310,7 +310,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, - FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank) + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank) { /* Check the parameters */ @@ -325,13 +325,14 @@ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, assert_param(IS_FSMC_NORSRAM_BANK(Bank)); /* Set FSMC_NORSRAM device timing parameters */ - MODIFY_REG(Device->BTCR[Bank + 1U], BTR_CLEAR_MASK, (Timing->AddressSetupTime | - ((Timing->AddressHoldTime) << FSMC_BTR1_ADDHLD_Pos) | - ((Timing->DataSetupTime) << FSMC_BTR1_DATAST_Pos) | - ((Timing->BusTurnAroundDuration) << FSMC_BTR1_BUSTURN_Pos) | - (((Timing->CLKDivision) - 1U) << FSMC_BTR1_CLKDIV_Pos) | - (((Timing->DataLatency) - 2U) << FSMC_BTR1_DATLAT_Pos) | - (Timing->AccessMode))); + Device->BTCR[Bank + 1U] = + (Timing->AddressSetupTime << FSMC_BTR1_ADDSET_Pos) | + (Timing->AddressHoldTime << FSMC_BTR1_ADDHLD_Pos) | + (Timing->DataSetupTime << FSMC_BTR1_DATAST_Pos) | + (Timing->BusTurnAroundDuration << FSMC_BTR1_BUSTURN_Pos) | + ((Timing->CLKDivision - 1U) << FSMC_BTR1_CLKDIV_Pos) | + ((Timing->DataLatency - 2U) << FSMC_BTR1_DATLAT_Pos) | + Timing->AccessMode; return HAL_OK; } @@ -349,8 +350,8 @@ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, * @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) + const FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, + uint32_t ExtendedMode) { /* Check the parameters */ assert_param(IS_FSMC_EXTENDED_MODE(ExtendedMode)); @@ -494,7 +495,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Devi * @param Init Pointer to NAND Initialization structure * @retval HAL status */ -HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init) +HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, const FSMC_NAND_InitTypeDef *Init) { /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); @@ -542,7 +543,7 @@ HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDe * @retval HAL status */ HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) { /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); @@ -582,7 +583,7 @@ HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, * @retval HAL status */ HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) + const FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) { /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); @@ -729,8 +730,8 @@ HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank * @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) +HAL_StatusTypeDef FSMC_NAND_GetECC(const FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout) { uint32_t tickstart; @@ -820,7 +821,7 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, * @param Init Pointer to PCCARD Initialization structure * @retval HAL status */ -HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init) +HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, const FSMC_PCCARD_InitTypeDef *Init) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); @@ -854,7 +855,7 @@ HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_Init * @retval HAL status */ HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing) + const FSMC_NAND_PCC_TimingTypeDef *Timing) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); @@ -883,7 +884,7 @@ HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Devic * @retval HAL status */ HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing) + const FSMC_NAND_PCC_TimingTypeDef *Timing) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); @@ -912,7 +913,7 @@ HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *De * @retval HAL status */ HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, - FSMC_NAND_PCC_TimingTypeDef *Timing) + const FSMC_NAND_PCC_TimingTypeDef *Timing) { /* Check the parameters */ assert_param(IS_FSMC_PCCARD_DEVICE(Device)); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_spi.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_spi.c index 097ebf630..1ed0a4e00 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_spi.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_spi.c @@ -119,7 +119,7 @@ * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx) { ErrorStatus status = ERROR; @@ -168,8 +168,9 @@ ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) /** * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. - * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), - * SPI peripheral should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. + * @note As some bits in SPI configuration registers can only be written when the + * SPI is disabled (SPI_CR1_SPE bit = 0), SPI peripheral should be in disabled state prior + * calling this function. Otherwise, ERROR result will be returned. * @param SPIx SPI Instance * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure * @retval An ErrorStatus enumeration value. (Return always SUCCESS) @@ -345,7 +346,7 @@ void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx) { return LL_SPI_DeInit(SPIx); } diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_tim.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_tim.c index 4d067b304..e025d0406 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_tim.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_tim.c @@ -748,8 +748,6 @@ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 1: Reset the CC1E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); @@ -777,8 +775,10 @@ static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); @@ -827,8 +827,6 @@ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 2: Reset the CC2E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); @@ -856,8 +854,10 @@ static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); @@ -906,8 +906,6 @@ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); /* Disable the Channel 3: Reset the CC3E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); @@ -935,8 +933,10 @@ static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); /* Set the complementary output Polarity */ MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); @@ -985,8 +985,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); /* Disable the Channel 4: Reset the CC4E Bit */ CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); @@ -1014,7 +1012,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM if (IS_TIM_BREAK_INSTANCE(TIMx)) { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); /* Set the Output Idle state */ @@ -1036,7 +1033,6 @@ static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM return SUCCESS; } - /** * @brief Configure the TIMx input channel 1. * @param TIMx Timer Instance @@ -1161,7 +1157,7 @@ static ErrorStatus IC4Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); - /* Select the Polarity and set the CC2E Bit */ + /* Select the Polarity and set the CC4E Bit */ MODIFY_REG(TIMx->CCER, (TIM_CCER_CC4P | TIM_CCER_CC4NP), ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_usb.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_usb.c index fbf6f2eed..5477e95ac 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_usb.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_usb.c @@ -250,9 +250,9 @@ HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTy do { - HAL_Delay(1U); - ms++; - } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < 50U)); + HAL_Delay(10U); + ms += 10U; + } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); } else if (mode == USB_DEVICE_MODE) { @@ -260,16 +260,16 @@ HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTy do { - HAL_Delay(1U); - ms++; - } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < 50U)); + HAL_Delay(10U); + ms += 10U; + } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); } else { return HAL_ERROR; } - if (ms == 50U) + if (ms == HAL_USB_CURRENT_MODE_MAX_DELAY_MS) { return HAL_ERROR; } @@ -447,7 +447,7 @@ HAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -461,7 +461,7 @@ HAL_StatusTypeDef USB_FlushTxFifo(USB_OTG_GlobalTypeDef *USBx, uint32_t num) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -484,7 +484,7 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -498,7 +498,7 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -518,7 +518,7 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) * @arg USB_OTG_SPEED_FULL: Full speed mode * @retval Hal status */ -HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed) +HAL_StatusTypeDef USB_SetDevSpeed(const USB_OTG_GlobalTypeDef *USBx, uint8_t speed) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -534,7 +534,7 @@ HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx, uint8_t speed) * @arg USBD_HS_SPEED: High speed mode * @arg USBD_FS_SPEED: Full speed mode */ -uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) +uint8_t USB_GetDevSpeed(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; uint8_t speed; @@ -563,7 +563,7 @@ uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_ActivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -601,7 +601,7 @@ HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTy * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -640,7 +640,7 @@ HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_DeactivateEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -687,7 +687,7 @@ HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EP * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -901,7 +901,7 @@ HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_EPStopXfer(const USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) { __IO uint32_t count = 0U; HAL_StatusTypeDef ret = HAL_OK; @@ -965,7 +965,7 @@ HAL_StatusTypeDef USB_EPStopXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef * 1 : DMA feature used * @retval HAL status */ -HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, +HAL_StatusTypeDef USB_WritePacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len, uint8_t dma) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -996,7 +996,7 @@ HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, * @param len Number of bytes to read * @retval pointer to destination buffer */ -void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) +void *USB_ReadPacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) { uint32_t USBx_BASE = (uint32_t)USBx; uint8_t *pDest = dest; @@ -1038,7 +1038,7 @@ void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_EPSetStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -1069,7 +1069,7 @@ HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef * @param ep pointer to endpoint structure * @retval HAL status */ -HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +HAL_StatusTypeDef USB_EPClearStall(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t epnum = (uint32_t)ep->num; @@ -1139,7 +1139,7 @@ HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx) * This parameter can be a value from 0 to 255 * @retval HAL status */ -HAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address) +HAL_StatusTypeDef USB_SetDevAddress(const USB_OTG_GlobalTypeDef *USBx, uint8_t address) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1154,7 +1154,7 @@ HAL_StatusTypeDef USB_SetDevAddress(USB_OTG_GlobalTypeDef *USBx, uint8_t address * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_DevConnect(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1171,7 +1171,7 @@ HAL_StatusTypeDef USB_DevConnect(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_DevDisconnect(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_DevDisconnect(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1204,7 +1204,7 @@ uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef const *USBx) * @param chnum Channel number * @retval USB Channel Interrupt status */ -uint32_t USB_ReadChInterrupts(USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) +uint32_t USB_ReadChInterrupts(const USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1220,7 +1220,7 @@ uint32_t USB_ReadChInterrupts(USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) * @param USBx Selected device * @retval USB Device OUT EP interrupt status */ -uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_ReadDevAllOutEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1236,7 +1236,7 @@ uint32_t USB_ReadDevAllOutEpInterrupt(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval USB Device IN EP interrupt status */ -uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_ReadDevAllInEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1254,7 +1254,7 @@ uint32_t USB_ReadDevAllInEpInterrupt(USB_OTG_GlobalTypeDef *USBx) * 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 USB_ReadDevOutEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1272,7 +1272,7 @@ uint32_t USB_ReadDevOutEPInterrupt(USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) * 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 USB_ReadDevInEPInterrupt(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t tmpreg; @@ -1306,7 +1306,7 @@ void USB_ClearInterrupts(USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt) * 0 : Host * 1 : Device */ -uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_GetMode(const USB_OTG_GlobalTypeDef *USBx) { return ((USBx->GINTSTS) & 0x1U); } @@ -1316,7 +1316,7 @@ uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_ActivateSetup(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1338,10 +1338,10 @@ HAL_StatusTypeDef USB_ActivateSetup(USB_OTG_GlobalTypeDef *USBx) * @param psetup pointer to setup packet * @retval HAL status */ -HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup) +HAL_StatusTypeDef USB_EP0_OutStart(const USB_OTG_GlobalTypeDef *USBx, uint8_t dma, const uint8_t *psetup) { uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO uint32_t *)(&USBx->CID + 0x1U); + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); if (gSNPSiD > USB_OTG_CORE_ID_300A) { @@ -1380,7 +1380,7 @@ static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -1394,7 +1394,7 @@ static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx) { count++; - if (count > 200000U) + if (count > HAL_USB_TIMEOUT) { return HAL_TIMEOUT; } @@ -1425,7 +1425,7 @@ HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef c USBx->GCCFG &= ~(USB_OTG_GCCFG_VBUSASEN); USBx->GCCFG &= ~(USB_OTG_GCCFG_VBUSBSEN); - if ((USBx->CID & (0x1U << 8)) != 0U) + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) { if (cfg.speed == USBH_FSLS_SPEED) { @@ -1467,8 +1467,8 @@ HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef c /* Clear any pending interrupts */ USBx->GINTSTS = CLEAR_INTERRUPT_MASK; - - if ((USBx->CID & (0x1U << 8)) != 0U) +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) { /* set Rx FIFO size */ USBx->GRXFSIZ = 0x200U; @@ -1476,6 +1476,7 @@ HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef c USBx->HPTXFSIZ = (uint32_t)(((0xE0U << 16) & USB_OTG_HPTXFSIZ_PTXFD) | 0x300U); } else +#endif /* defined (USB_OTG_HS) */ { /* set Rx FIFO size */ USBx->GRXFSIZ = 0x80U; @@ -1507,7 +1508,7 @@ HAL_StatusTypeDef USB_HostInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef c * HCFG_6_MHZ : Low Speed 6 MHz Clock * @retval HAL status */ -HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq) +HAL_StatusTypeDef USB_InitFSLSPClkSel(const USB_OTG_GlobalTypeDef *USBx, uint8_t freq) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1537,7 +1538,7 @@ HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx, uint8_t freq) * @note (1)The application must wait at least 10 ms * before clearing the reset bit. */ -HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_ResetPort(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -1564,7 +1565,7 @@ HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) * 1 : Activate VBUS * @retval HAL status */ -HAL_StatusTypeDef USB_DriveVbus(USB_OTG_GlobalTypeDef *USBx, uint8_t state) +HAL_StatusTypeDef USB_DriveVbus(const USB_OTG_GlobalTypeDef *USBx, uint8_t state) { uint32_t USBx_BASE = (uint32_t)USBx; __IO uint32_t hprt0 = 0U; @@ -1670,11 +1671,13 @@ HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num, } else { - if ((USBx->CID & (0x1U << 8)) != 0U) +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) { USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_NYET | USB_OTG_HCINTMSK_ACKM; } +#endif /* defined (USB_OTG_HS) */ } break; @@ -1779,12 +1782,13 @@ HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDe uint16_t num_packets; uint16_t max_hc_pkt_count = HC_MAX_PKT_CNT; - if ((USBx->CID & (0x1U << 8)) != 0U) +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) { /* in DMA mode host Core automatically issues ping in case of NYET/NAK */ if (dma == 1U) { - if ((hc->ep_type == EP_TYPE_CTRL) || (hc->ep_type == EP_TYPE_BULK)) + if (((hc->ep_type == EP_TYPE_CTRL) || (hc->ep_type == EP_TYPE_BULK)) && (hc->do_ssplit == 0U)) { USBx_HC((uint32_t)ch_num)->HCINTMSK &= ~(USB_OTG_HCINTMSK_NYET | @@ -1801,6 +1805,7 @@ HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDe } } } +#endif /* defined (USB_OTG_HS) */ if (hc->do_ssplit == 1U) { @@ -2030,7 +2035,7 @@ HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDe * @param USBx Selected device * @retval HAL state */ -uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx) +uint32_t USB_HC_ReadInterrupt(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -2044,7 +2049,7 @@ uint32_t USB_HC_ReadInterrupt(USB_OTG_GlobalTypeDef *USBx) * 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) +HAL_StatusTypeDef USB_HC_Halt(const USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t hcnum = (uint32_t)hc_num; @@ -2128,7 +2133,7 @@ HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) * 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) +HAL_StatusTypeDef USB_DoPing(const USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num) { uint32_t USBx_BASE = (uint32_t)USBx; uint32_t chnum = (uint32_t)ch_num; @@ -2217,7 +2222,7 @@ HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_ActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; @@ -2235,7 +2240,7 @@ HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) * @param USBx Selected device * @retval HAL status */ -HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) { uint32_t USBx_BASE = (uint32_t)USBx; diff --git a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_utils.c b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_utils.c index 38ca8d95e..a12641085 100644 --- a/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_utils.c +++ b/stm32cube/stm32f2xx/drivers/src/stm32f2xx_ll_utils.c @@ -339,28 +339,25 @@ ErrorStatus LL_SetFlashLatency(uint32_t HCLK_Frequency) latency = LL_FLASH_LATENCY_0; } } - if (status != ERROR) - { - LL_FLASH_SetLatency(latency); + LL_FLASH_SetLatency(latency); - /* Check that the new number of wait states is taken into account to access the Flash - memory by reading the FLASH_ACR register */ - timeout = 2; - do - { + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACR register */ + timeout = 2; + do + { /* Wait for Flash latency to be updated */ getlatency = LL_FLASH_GetLatency(); timeout--; - } while ((getlatency != latency) && (timeout > 0)); + } while ((getlatency != latency) && (timeout > 0)); - if(getlatency != latency) - { - status = ERROR; - } - else - { - status = SUCCESS; - } + if(getlatency != latency) + { + status = ERROR; + } + else + { + /* No thing to do */ } } return status; diff --git a/stm32cube/stm32f2xx/release_note.html b/stm32cube/stm32f2xx/release_note.html index 4b730ea97..2ce81e847 100644 --- a/stm32cube/stm32f2xx/release_note.html +++ b/stm32cube/stm32f2xx/release_note.html @@ -37,7 +37,7 @@

              Purpose

            • A consistent set of middleware components such as RTOS, USB, TCP/IP, Graphics
            • All embedded software utilities come with a full set of examples.
            -
          • The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements STM32Cube architecture
          • +
          • The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements STM32Cube architecture

          The HAL (Hardware Abstraction Layer) drivers provided within this package supports the following STM32F2 product lines 205xx/215xx/207xx/217xx

            @@ -58,12 +58,240 @@

            Purpose

            Update History

            - +

            Maintenance release

            Main Changes

            • Patch release to fix known defects and enhancements implementation.
            • +
            • Upgrade FreeRTOS Lib to use v10.3.1 (ST modified 2023-08-18).

            • +
            • HAL updates +
                +
              • HAL code quality enhancement for MISRA-C Rule-8.13 by adding const qualifiers.
              • +
              • HAL/LL CORTEX driver +
                  +
                • Update HAL_MPU_ConfigRegion() to allow the configuration of the MPU registers independently of the value of Enable/Disable field.
                • +
                • Add new APIs HAL_MPU_EnableRegion() / HAL_MPU_DisableRegion().
                • +
              • +
              • HAL/LL ADC driver +
                  +
                • Update __LL_ADC_CALC_TEMPERATURE_TYP_PARAMS() formula to be aligned with reference manual.
                • +
              • +
              • HAL FLASH driver +
                  +
                • Remove HAL_LOCK()/HAL_UNLOCK() from HAL_FLASH_Program_IT() and HAL_FLASHEx_Erase_IT() APIs.
                • +
              • +
              • HAL HASH driver +
                  +
                • Read the last remaining bytes (3 or 2 or 1) of the data in a temporary variable (taking into account swap mode) and enter this variable into the HASH->DIN when the data is not a multiple of 4 bytes.
                • +
              • +
              • HAL CAN driver +
                  +
                • Clarify pin configuration in driver header by removing open-drain information.
                • +
              • +
              • HAL I2C driver +
                  +
                • Solve Slave No stretch not functional by using HAL Slave interface.
                • +
                • Clear ACK bit once 3 bytes to read remain to be able to send the NACK once the transfer ends.
                • +
                • Update HAL_I2C_Master_Abort_IT() API to support memory abort transfer.
                • +
                • Update the HAL I2C driver to reset PreviousState to I2C_STATE_NONE at the end of transfer.
                • +
              • +
              • HAL RNG driver +
                  +
                • Improve performance by removing multiple volatile reads or writes in interrupt handler.
                • +
              • +
              • LL RTC_BKP driver +
                  +
                • Correct misleading note about shadow registers.
                • +
              • +
              • HAL SDMMC driver +
                  +
                • Update HAL SD processes to manage STBITERR flag.
                • +
              • +
              • HAL DCMI driver +
                  +
                • Remove ‘register’ storage class specifier.
                • +
              • +
              • HAL SPI driver +
                  +
                • Update HAL_SPI_TransmitReceive() API to set the bit CRCNEXT in case of one byte transaction.
                • +
                • Update IT APIs to enable interrupts after process unlock.
                • +
                • Add wait on flag TXE to be set at the end of transaction to be aligned with reference manual.
                • +
              • +
              • HAL I2S driver +
                  +
                • Update HAL I2S driver to fix misplaced __HAL_LOCK() and remove ‘go to’ instruction.
                • +
              • +
              • HAL/LL TIM driver +
                  +
                • Improve performance by removing multiple volatile reads or writes in interrupt handler.
                • +
                • Update interrupt flag is cleared when the update event is generated by software.
                • +
                • Improve HAL TIM driver’s operational behavior.
                • +
                • Improve period configuration parameter check.
                • +
                • Remove unnecessary change of MOE bitfield in LL_TIM_BDTR_Init().
                • +
                • Add LL_TIM_CC_IsEnabledPreload() API.
                • +
              • +
              • HAL UART driver +
                  +
                • Avoid ORE flag to be cleared by a transmit process in polling mode.
                • +
                • Rework of UART_WaitOnFlagUntilTimeout() API to avoid being stuck forever when UART overrun error occurs and to enhance behavior.
                • +
              • +
              • HAL IWDG driver +
                  +
                • Calculate the maximum IWDG Timeout period “HAL_IWDG_DEFAULT_TIMEOUT” based on a Prescaler=128 at LSI frequency=32kHz.
                • +
              • +
              • HAL USB_OTG driver +
                  +
                • Fix device connection in case battery charging is used with HS instance linked to internal FS PHY.
                • +
                • ll_usb.c: increase timeout value to allow core reset to complete.
                • +
                • ll_usb.c: improve delay management to set core mode.
                • +
                • hal_hcd.c: ensure to reactivate the usb channel in case of transfer error.
                • +
              • +
              • LL UTILS_ driver +
                  +
                • Fix a note about Ticks parameter.
                • +
              • +
            • +
            • Middleware +
                +
              • Upgrade FreeRTOS Lib to use v10.3.1 (ST modified 2023-08-18).
              • +
            • +
            • Projects updates +
                +
              • NUCLEO-F207ZG +
                  +
                • USB Host MSC applications: fix Stack corruption due to inconsistent type of local variable in MSC_File_Operations().
                • +
              • +
              • STM322xG_EVAL +
                  +
                • FreeRTOS_LowPower application: Update FreeRTOS LowPower application to support FreeRTOS v10.3.1.
                • +
              • +
            • +
            +

            Contents

            + + + + + + + + + + + + + + + + +
            Projects
            NameVersionRelease notes
            Projectssee Projects Release note for detailsrelease notes
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Drivers
            NameVersionRelease note
            STM32F2xx CMSISV2.2.6release notes
            STM32F2xx HALV1.2.9release notes
            BSP Adafruit_ShieldV3.0.6release notes
            BSP STM32F2xx_Nucleo_144V1.0.3release notes
            BSP STM322xG_EVALV7.0.2release notes
            + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Utilities
            NameVersionRelease note
            CPUV1.1.4release notes
            FontsV1.0.3release notes
            LogV1.0.4release notes
            + + + + + + + + + + + + + + + + +
            Middlewares
            NameVersionRelease note
            FreeRTOSV10.3.1release notes ST modified 20230818 release notes
            +

            Known Limitations

            +
              +
            • Warnings detected with LibJPEG applications are related to the Libjpeg third party MW stack V8d with System Workbench for STM32 (SW4STM32) V2.9: +
                +
              • No impact of these warnings on the functional behavior
              • +
            • +
            +

            Development Toolchains and Compilers

            +
              +
            • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9+ ST-Link
            • +
            • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.38 + ST-LINK +
                +
              • Only template projects are migrated to Arm Compiler 6 with MDK-ARM 5.31 (“AC-like Warnings” mode).
              • +
            • +
            • System Workbench for STM32 (SW4STM32) (7-2018-q2-update) toolchain V2.9.0 + ST-Link
            • +
            +
            +
            +
            + +
            +

            Maintenance release

            +

            Main Changes

            +
              +
            • Patch release to fix known defects and enhancements implementation.
            • All source files: update disclaimer to add reference to the new license agreement.

            • CMSIS updates
                @@ -223,7 +451,7 @@

                Main Changes

          -

          Contents

          +

          Contents

          @@ -305,14 +533,14 @@

          Contents

          Projects
          -

          Known Limitations

          +

          Known Limitations

          • Warnings detected with LibJPEG applications are related to the Libjpeg third party MW stack V8d with System Workbench for STM32 (SW4STM32) V2.9:
            • No impact of these warnings on the functional behavior
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V8.40.2+ ST-Link
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31 + ST-LINK @@ -326,8 +554,8 @@

            Development Toolchains and Compile
            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • Patch release of STM32CubeF2 Firmware Package.

            • CMSIS updates @@ -464,7 +692,7 @@

              Main Changes

            • Fix include path on some SW4STM32 Projects.

          -

          Contents

          +

          Contents

          @@ -486,14 +714,14 @@

          Contents

          -

          Known Limitations

          +

          Known Limitations

          • Warnings detected with LibJPEG applications are related to the Libjpeg third party MW stack V8d with System Workbench for STM32 (SW4STM32) V2.9:
            • No impact of these warnings on the functional behavior
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V8.40.2+ ST-Link
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31 + ST-LINK
          • @@ -517,8 +745,8 @@

            Dependencies

            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • Patch release of STM32CubeF2 Firmware Package.

            • HAL

              @@ -532,7 +760,7 @@

              Main Changes

        -

        Contents

        +

        Contents

        @@ -555,8 +783,8 @@

        Contents

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • General updates to fix known defects and enhancements implementation

        • HAL @@ -816,7 +1044,7 @@

          Main Changes

      • For the complete list of changes, please refer to the release notes of each firmware component

      • -

        Contents

        +

        Contents

        Drivers
        @@ -838,11 +1066,11 @@

        Contents

        -

        Known Limitations

        +

        Known Limitations

        • None
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2+ ST-Link
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.26 + ST-LINK
        • @@ -866,8 +1094,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • General updates to fix known defects and enhancements implementation

          • HAL @@ -904,7 +1132,7 @@

            Main Changes

        • For the complete list of changes, please refer to the release notes of each firmware component

        -

        Contents

        +

        Contents

        @@ -1065,14 +1293,14 @@

        Contents

        -

        Known Limitations

        +

        Known Limitations

        • Warnings detected with LibJPEG applications are related to the Libjpeg third party MW stack V8d with System Workbench for STM32 (SW4STM32) V2.9:
          • No impact of these warnings on the functional behavior
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2+ ST-Link
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.26 + ST-LINK
        • @@ -1096,8 +1324,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • General updates to fix known defects and enhancements implementation
          • General updates to fix CodeSonar compilation warnings
          • @@ -1220,7 +1448,7 @@

            Main Changes

        • For the complete list of changes, please refer to the release notes of each firmware component

        -

        Contents

        +

        Contents

        @@ -1381,14 +1609,14 @@

        Contents

        -

        Known Limitations

        +

        Known Limitations

        • Warnings detected with LibJPEG applications are related to the Libjpeg third party MW stack V8d with System Workbench for STM32 (SW4STM32) V2.9:
          • No impact of these warnings on the functional behavior
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2+ ST-Link
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.26 + ST-LINK
        • @@ -1412,8 +1640,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • General updates to be compliant with Linux platforms
          • General update to fix known defects and several implementations enhancement
          • @@ -1439,7 +1667,7 @@

            Main Changes

        • For the complete list of changes, please refer to the release notes of each firmware component

        -

        Contents

        +

        Contents

        @@ -1601,11 +1829,11 @@

        Contents

        Drivers
        -

        Known Limitations

        +

        Known Limitations

        • None
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V7.80.4 + ST-Link
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.23 + ST-LINK
        • @@ -1629,8 +1857,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • General update to fix known defects and several implementations enhancement

          • HAL @@ -1649,7 +1877,7 @@

            Main Changes

      -

      Contents

      +

      Contents

      @@ -1811,11 +2039,11 @@

      Contents

      Drivers
      -

      Known Limitations

      +

      Known Limitations

      • STemWin sample demo application on STM322xG_EVAL is not fully functional with MDK-ARM toolchain: the application doesn’t run successfully after the second hit of the Hide Button. in fact when pressing the button again while the progress bar displays the next steps, pressing Hide or Next Buttons are not working anymore.
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain V7.80.1
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.23
      • @@ -1840,8 +2068,8 @@

        Dependencies

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • Add Low Layer drivers under Drivers32F2xx_HAL_Driver
            @@ -1901,7 +2129,7 @@

            Main Changes

          • Update overall projects to be aligned with latest version of HAL, BSP and Middleware drivers
        -

        Contents

        +

        Contents

        @@ -2063,11 +2291,11 @@

        Contents

        Drivers
        -

        Known Limitations

        +

        Known Limitations

        • STemWin sample demo application on STM322xG_EVAL is not fully functional with MDK-ARM toolchain: the application doesn’t run successfully after the second hit of the Hide Button. in fact when pressing the button again while the progress bar displays the next steps, pressing Hide or Next Buttons are not working anymore.
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V7.80.1
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.23
        • @@ -2092,8 +2320,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • Maintenance release to fix known defects and several enhancements implementation

          • HAL @@ -2148,7 +2376,7 @@

            Main Changes

        • For the complete list of changes, please refer to the release notes of each firmware component

        -

        Contents

        +

        Contents

        @@ -2310,11 +2538,11 @@

        Contents

        Drivers
        -

        Known Limitations

        +

        Known Limitations

        • STemWin sample demo application on STM322xG_EVAL is not fully functional with MDK-ARM toolchain: the application doesn’t run successfully after the second hit of the Hide Button. in fact when pressing the button again while the progress bar displays the next steps, pressing Hide or Next Buttons are not working anymore.
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain v7.60.1
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.20
        • @@ -2339,12 +2567,12 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • Patch release to fix issue in Ethernet HAL driver
          -

          Contents

          +

          Contents

          @@ -2362,11 +2590,11 @@

          Contents

          Drivers
          -

          Known Limitations

          +

          Known Limitations

          • None
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V7.40.1
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.16
          • @@ -2391,8 +2619,8 @@

            Dependencies

            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • Support new board: STM32F207ZG NUCLEO144
            • Fix known defects and enhancements implementation

            • @@ -2428,7 +2656,7 @@

              Main Changes

          • For the complete list of changes, please refer to the release notes of each firmware component

          -

          Contents

          +

          Contents

          @@ -2590,11 +2818,11 @@

          Contents

          Drivers
          -

          Known Limitations

          +

          Known Limitations

          • None
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V7.40.1
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.16
          • @@ -2619,8 +2847,8 @@

            Dependencies

            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • Maintenance release to fix known defects and several enhancements implementation

            • HAL @@ -2659,7 +2887,7 @@

              Main Changes

          • For the complete list of changes, please refer to the release notes of each firmware components

          -

          Contents

          +

          Contents

          @@ -2811,11 +3039,11 @@

          Contents

          Drivers
          -

          Known Limitations

          +

          Known Limitations

          • None
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain v7.40.1
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.16
          • @@ -2839,8 +3067,8 @@

            Dependencies

            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • Added LCD ili9320 component
            • BSP ili9320 V1.0.0 release notes
            • @@ -2850,12 +3078,12 @@

              Main Changes

              -

              Maintenance release

              -

              Main Changes

              +

              Maintenance release

              +

              Main Changes

              • First official release of STM32CubeF2 (STM32Cube for STM32F2 Series)
              -

              Contents

              +

              Contents

              @@ -3000,7 +3228,7 @@

              Known Limitations (planned
            • TrueSTUDIO projects are not provided for a few Applications
            • The LCD ili9320 mounted on previous versions of the STM322xG_EVAL board will be supported in a future version of the STM32Cube F2 FW package (V1.1.0)
            • -

              Development Toolchains and Compilers

              +

              Development Toolchains and Compilers

              • IAR Embedded Workbench for ARM (EWARM) toolchain V6.70.2 + ST-Link
              • RealView Microcontroller Development Kit (MDK-ARM toolchain v4.73)
              • diff --git a/stm32cube/stm32f2xx/soc/stm32f2xx.h b/stm32cube/stm32f2xx/soc/stm32f2xx.h index dfd679e1a..956fd4ce5 100644 --- a/stm32cube/stm32f2xx/soc/stm32f2xx.h +++ b/stm32cube/stm32f2xx/soc/stm32f2xx.h @@ -240,4 +240,3 @@ typedef enum - From 9f2cc149bf4ff04711dbf76446ba5ba5e4f22d80 Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 15:13:15 +0200 Subject: [PATCH 04/11] stm32cube: update stm32f4 to cube version V1.28.1 Update Cube version for STM32F4xx series on https://github.com/STMicroelectronics from version v1.28.0 to version v1.28.1 Signed-off-by: Guillaume Gautier --- stm32cube/stm32f4xx/README | 14 +- .../drivers/include/Legacy/stm32_hal_legacy.h | 61 +- .../drivers/include/stm32f4xx_hal_conf.h | 5 +- .../drivers/include/stm32f4xx_hal_cortex.h | 2 + .../drivers/include/stm32f4xx_hal_dsi.h | 6 +- .../drivers/include/stm32f4xx_hal_eth.h | 253 +- .../drivers/include/stm32f4xx_hal_flash.h | 8 +- .../drivers/include/stm32f4xx_hal_flash_ex.h | 6 +- .../include/stm32f4xx_hal_flash_ramfunc.h | 2 +- .../drivers/include/stm32f4xx_hal_lptim.h | 4 +- .../drivers/include/stm32f4xx_hal_pcd_ex.h | 1 - .../drivers/include/stm32f4xx_hal_qspi.h | 6 +- .../drivers/include/stm32f4xx_hal_rcc.h | 332 +- .../drivers/include/stm32f4xx_hal_rcc_ex.h | 2691 +++++++++-------- .../drivers/include/stm32f4xx_hal_spi.h | 20 +- .../drivers/include/stm32f4xx_ll_adc.h | 140 +- .../drivers/include/stm32f4xx_ll_bus.h | 70 +- .../drivers/include/stm32f4xx_ll_cortex.h | 2 +- .../drivers/include/stm32f4xx_ll_dma.h | 2 +- .../drivers/include/stm32f4xx_ll_rcc.h | 51 +- .../drivers/include/stm32f4xx_ll_spi.h | 100 +- .../drivers/include/stm32f4xx_ll_utils.h | 2 +- .../stm32f4xx/drivers/src/stm32f4xx_hal.c | 4 +- .../drivers/src/stm32f4xx_hal_adc_ex.c | 3 + .../drivers/src/stm32f4xx_hal_cortex.c | 84 +- .../stm32f4xx/drivers/src/stm32f4xx_hal_dsi.c | 63 +- .../stm32f4xx/drivers/src/stm32f4xx_hal_eth.c | 323 +- .../drivers/src/stm32f4xx_hal_exti.c | 6 + .../drivers/src/stm32f4xx_hal_flash.c | 118 +- .../drivers/src/stm32f4xx_hal_flash_ex.c | 7 +- .../drivers/src/stm32f4xx_hal_hash.c | 71 +- .../stm32f4xx/drivers/src/stm32f4xx_hal_hcd.c | 6 + .../stm32f4xx/drivers/src/stm32f4xx_hal_i2s.c | 78 +- .../drivers/src/stm32f4xx_hal_i2s_ex.c | 92 +- .../stm32f4xx/drivers/src/stm32f4xx_hal_pcd.c | 6 +- .../drivers/src/stm32f4xx_hal_qspi.c | 18 +- .../stm32f4xx/drivers/src/stm32f4xx_hal_rcc.c | 188 +- .../drivers/src/stm32f4xx_hal_rcc_ex.c | 863 +++--- .../stm32f4xx/drivers/src/stm32f4xx_hal_spi.c | 297 +- .../stm32f4xx/drivers/src/stm32f4xx_ll_rcc.c | 211 +- .../stm32f4xx/drivers/src/stm32f4xx_ll_spi.c | 4 +- .../stm32f4xx/drivers/src/stm32f4xx_ll_usb.c | 16 +- stm32cube/stm32f4xx/release_note.html | 1071 +++++-- stm32cube/stm32f4xx/soc/stm32f412cx.h | 12 + stm32cube/stm32f4xx/soc/stm32f4xx.h | 4 +- 45 files changed, 3988 insertions(+), 3335 deletions(-) diff --git a/stm32cube/stm32f4xx/README b/stm32cube/stm32f4xx/README index e511dd101..c23c0b802 100644 --- a/stm32cube/stm32f4xx/README +++ b/stm32cube/stm32f4xx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubef4.html Status: - version v1.28.0 + version v1.28.1 Purpose: ST Microelectronics official MCU package for STM32F4 series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeF4 Commit: - 9e7d2aa86197059fc29cf89931d46d0ab64e6081 + 83778d5c95cb01695c7facbf095db3ab445532ea Maintained-by: External @@ -52,16 +52,6 @@ Patch List: -Added stm32cube/stm32f4xx/drivers/include/stm32_assert.h -Removed unused stm32cube/stm32f4xx/drivers/include/stm32_assert_template.h - *Unused variable in HAL_QSPI_Command_IT - -removed tickstart variable declaration - Impacted files: - drivers/src/stm32f4xx_hal_qspi.c - ST Bug tracker ID: 112664 - - *Enable legacy ethernet driver using HAL_ETH_LEGACY_MODULE_ENABLED - This will have to be removed once Zephyr driver is migrated ot the new - Cube HAL ethernet API. - *Fix to remove PAGESIZE definition which conflicts with POSIX Impacted files: drivers/include/Legacy/stm32_hal_legacy.h diff --git a/stm32cube/stm32f4xx/drivers/include/Legacy/stm32_hal_legacy.h b/stm32cube/stm32f4xx/drivers/include/Legacy/stm32_hal_legacy.h index a13bbfc71..ab13eefe0 100644 --- a/stm32cube/stm32f4xx/drivers/include/Legacy/stm32_hal_legacy.h +++ b/stm32cube/stm32f4xx/drivers/include/Legacy/stm32_hal_legacy.h @@ -548,6 +548,16 @@ extern "C" { #define OB_SRAM134_RST_ERASE OB_SRAM_RST_ERASE #define OB_SRAM134_RST_NOT_ERASE OB_SRAM_RST_NOT_ERASE #endif /* STM32U5 */ +#if defined(STM32U0) +#define OB_USER_nRST_STOP OB_USER_NRST_STOP +#define OB_USER_nRST_STDBY OB_USER_NRST_STDBY +#define OB_USER_nRST_SHDW OB_USER_NRST_SHDW +#define OB_USER_nBOOT_SEL OB_USER_NBOOT_SEL +#define OB_USER_nBOOT0 OB_USER_NBOOT0 +#define OB_USER_nBOOT1 OB_USER_NBOOT1 +#define OB_nBOOT0_RESET OB_NBOOT0_RESET +#define OB_nBOOT0_SET OB_NBOOT0_SET +#endif /* STM32U0 */ /** * @} @@ -1239,10 +1249,10 @@ extern "C" { #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 -#if defined(STM32H5) +#if defined(STM32H5) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_BKP_SRAM TAMP_DEVICESECRETS_ERASE_BKPSRAM -#endif /* STM32H5 */ +#endif /* STM32H5 || STM32H7RS */ #if defined(STM32WBA) #define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE @@ -1254,10 +1264,10 @@ extern "C" { #define TAMP_SECRETDEVICE_ERASE_ALL TAMP_DEVICESECRETS_ERASE_ALL #endif /* STM32WBA */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define TAMP_SECRETDEVICE_ERASE_DISABLE TAMP_DEVICESECRETS_ERASE_NONE #define TAMP_SECRETDEVICE_ERASE_ENABLE TAMP_SECRETDEVICE_ERASE_ALL -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ #if defined(STM32F7) #define RTC_TAMPCR_TAMPXE RTC_TAMPER_ENABLE_BITS_MASK @@ -1595,7 +1605,7 @@ extern "C" { #define ETH_MAC_SMALL_FIFO_RW_ACTIVE 0x00000006U /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE 0x00000001U /* MAC MII receive protocol engine active */ -#define ETH_TxPacketConfig ETH_TxPacketConfig_t /* Transmit Packet Configuration structure definition */ +#define ETH_TxPacketConfig ETH_TxPacketConfigTypeDef /* Transmit Packet Configuration structure definition */ /** * @} @@ -1807,7 +1817,7 @@ extern "C" { #define HAL_FMPI2CEx_AnalogFilter_Config HAL_FMPI2CEx_ConfigAnalogFilter #define HAL_FMPI2CEx_DigitalFilter_Config HAL_FMPI2CEx_ConfigDigitalFilter -#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) ((cmd == ENABLE)? \ +#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd) == ENABLE)? \ HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): \ HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) @@ -1989,12 +1999,12 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Functions HAL RTC Aliased Functions maintained for legacy purpose * @{ */ -#if defined(STM32H5) || defined(STM32WBA) +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) #define HAL_RTCEx_SetBoothardwareKey HAL_RTCEx_LockBootHardwareKey #define HAL_RTCEx_BKUPBlock_Enable HAL_RTCEx_BKUPBlock #define HAL_RTCEx_BKUPBlock_Disable HAL_RTCEx_BKUPUnblock #define HAL_RTCEx_Erase_SecretDev_Conf HAL_RTCEx_ConfigEraseDeviceSecrets -#endif /* STM32H5 || STM32WBA */ +#endif /* STM32H5 || STM32WBA || STM32H7RS */ /** * @} @@ -2309,8 +2319,8 @@ extern "C" { #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F302xE) || defined(STM32F302xC) +#endif +#if defined(STM32F302xE) || defined(STM32F302xC) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_ENABLE_RISING_EDGE() : \ @@ -2343,8 +2353,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) +#endif +#if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP3) ? __HAL_COMP_COMP3_EXTI_ENABLE_RISING_EDGE() : \ @@ -2401,8 +2411,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP5) ? __HAL_COMP_COMP5_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP6) ? __HAL_COMP_COMP6_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP7_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F373xC) ||defined(STM32F378xx) +#endif +#if defined(STM32F373xC) ||defined(STM32F378xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE() : \ @@ -2419,7 +2429,7 @@ extern "C" { __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) -# endif +#endif #else #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) @@ -2721,6 +2731,12 @@ extern "C" { #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET +#if defined(STM32C0) +#define __HAL_RCC_APB1_FORCE_RESET __HAL_RCC_APB1_GRP1_FORCE_RESET +#define __HAL_RCC_APB1_RELEASE_RESET __HAL_RCC_APB1_GRP1_RELEASE_RESET +#define __HAL_RCC_APB2_FORCE_RESET __HAL_RCC_APB1_GRP2_FORCE_RESET +#define __HAL_RCC_APB2_RELEASE_RESET __HAL_RCC_APB1_GRP2_RELEASE_RESET +#endif /* STM32C0 */ #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET @@ -3644,8 +3660,12 @@ extern "C" { #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 -#if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) || \ - defined(STM32WL) || defined(STM32C0) +#if defined(STM32U0) +#define RCC_SYSCLKSOURCE_STATUS_PLLR RCC_SYSCLKSOURCE_STATUS_PLLCLK +#endif + +#if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) || \ + defined(STM32WL) || defined(STM32C0) || defined(STM32H7RS) || defined(STM32U0) #define RCC_RTCCLKSOURCE_NO_CLK RCC_RTCCLKSOURCE_NONE #else #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK @@ -3747,8 +3767,10 @@ extern "C" { #define __HAL_RCC_GET_DFSDM_SOURCE __HAL_RCC_GET_DFSDM1_SOURCE #define RCC_DFSDM1CLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 #define RCC_SWPMI1CLKSOURCE_PCLK RCC_SWPMI1CLKSOURCE_PCLK1 +#if !defined(STM32U0) #define RCC_LPTIM1CLKSOURCE_PCLK RCC_LPTIM1CLKSOURCE_PCLK1 #define RCC_LPTIM2CLKSOURCE_PCLK RCC_LPTIM2CLKSOURCE_PCLK1 +#endif #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM1AUDIOCLKSOURCE_I2S1 #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM1AUDIOCLKSOURCE_I2S2 @@ -3894,7 +3916,7 @@ extern "C" { */ #if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || \ defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || \ - defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) + defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) #else #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #endif @@ -4217,6 +4239,9 @@ extern "C" { #define __HAL_TIM_GetCompare __HAL_TIM_GET_COMPARE #define TIM_BREAKINPUTSOURCE_DFSDM TIM_BREAKINPUTSOURCE_DFSDM1 + +#define TIM_OCMODE_ASSYMETRIC_PWM1 TIM_OCMODE_ASYMMETRIC_PWM1 +#define TIM_OCMODE_ASSYMETRIC_PWM2 TIM_OCMODE_ASYMMETRIC_PWM2 /** * @} */ diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_conf.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_conf.h index 76e96a1c8..3569770fb 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_conf.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_conf.h @@ -45,6 +45,7 @@ #define HAL_DMA_MODULE_ENABLED #define HAL_DMA2D_MODULE_ENABLED #define HAL_ETH_MODULE_ENABLED +/* #define HAL_ETH_LEGACY_MODULE_ENABLED */ #define HAL_FLASH_MODULE_ENABLED #define HAL_NAND_MODULE_ENABLED #define HAL_NOR_MODULE_ENABLED @@ -333,8 +334,8 @@ #endif /* HAL_ETH_MODULE_ENABLED */ #ifdef HAL_ETH_LEGACY_MODULE_ENABLED - #include "Legacy/stm32f4xx_hal_eth_legacy.h" -#endif /* HAL_ETH_MODULE_ENABLED */ + #include "stm32f4xx_hal_eth_legacy.h" +#endif /* HAL_ETH_LEGACY_MODULE_ENABLED */ #ifdef HAL_FLASH_MODULE_ENABLED #include "stm32f4xx_hal_flash.h" diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_cortex.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_cortex.h index 51ab36780..0fea5e0ed 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_cortex.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_cortex.h @@ -284,6 +284,8 @@ void HAL_SYSTICK_Callback(void); #if (__MPU_PRESENT == 1U) void HAL_MPU_Enable(uint32_t MPU_Control); void HAL_MPU_Disable(void); +void HAL_MPU_EnableRegion(uint32_t RegionNumber); +void HAL_MPU_DisableRegion(uint32_t RegionNumber); void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ void HAL_CORTEX_ClearEvent(void); diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_dsi.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_dsi.h index 6b51ecb2d..faf4cf4de 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_dsi.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_dsi.h @@ -1184,7 +1184,7 @@ HAL_StatusTypeDef HAL_DSI_LongWrite(DSI_HandleTypeDef *hdsi, uint32_t Mode, uint32_t NbParams, uint32_t Param1, - uint8_t *ParametersTable); + const uint8_t *ParametersTable); HAL_StatusTypeDef HAL_DSI_Read(DSI_HandleTypeDef *hdsi, uint32_t ChannelNbr, uint8_t *Array, @@ -1222,8 +1222,8 @@ HAL_StatusTypeDef HAL_DSI_SetContentionDetectionOff(DSI_HandleTypeDef *hdsi, Fun * @brief Peripheral State and Errors functions * @{ */ -uint32_t HAL_DSI_GetError(DSI_HandleTypeDef *hdsi); -HAL_DSI_StateTypeDef HAL_DSI_GetState(DSI_HandleTypeDef *hdsi); +uint32_t HAL_DSI_GetError(const DSI_HandleTypeDef *hdsi); +HAL_DSI_StateTypeDef HAL_DSI_GetState(const DSI_HandleTypeDef *hdsi); /** * @} diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_eth.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_eth.h index 91fdb62be..9024fff0b 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_eth.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_eth.h @@ -24,7 +24,6 @@ extern "C" { #endif - /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" @@ -153,7 +152,7 @@ typedef struct void *pData; /*!< Specifies Application packet pointer to save */ -} ETH_TxPacketConfig; +} ETH_TxPacketConfigTypeDef; /** * */ @@ -755,7 +754,6 @@ TDES7 | Transmit Time Stamp High [31:0] * @} */ - /** @defgroup ETH_DMA_Rx_Descriptor_Bit_Definition ETH DMA Rx Descriptor Bit Definition * @{ */ @@ -915,15 +913,6 @@ TDES7 | Transmit Time Stamp High [31:0] * @} */ -/** @defgroup ETH_Tx_Packet_Source_Addr_Control ETH Tx Packet Source Addr Control - * @{ - */ -#define ETH_SRC_ADDR_CONTROL_DISABLE ETH_DMATXNDESCRF_SAIC_DISABLE -#define ETH_SRC_ADDR_INSERT ETH_DMATXNDESCRF_SAIC_INSERT -#define ETH_SRC_ADDR_REPLACE ETH_DMATXNDESCRF_SAIC_REPLACE -/** - * @} - */ /** @defgroup ETH_Tx_Packet_CRC_Pad_Control ETH Tx Packet CRC Pad Control * @{ @@ -946,28 +935,6 @@ TDES7 | Transmit Time Stamp High [31:0] * @} */ -/** @defgroup ETH_Tx_Packet_VLAN_Control ETH Tx Packet VLAN Control - * @{ - */ -#define ETH_VLAN_DISABLE ETH_DMATXNDESCRF_VTIR_DISABLE -#define ETH_VLAN_REMOVE ETH_DMATXNDESCRF_VTIR_REMOVE -#define ETH_VLAN_INSERT ETH_DMATXNDESCRF_VTIR_INSERT -#define ETH_VLAN_REPLACE ETH_DMATXNDESCRF_VTIR_REPLACE -/** - * @} - */ - -/** @defgroup ETH_Tx_Packet_Inner_VLAN_Control ETH Tx Packet Inner VLAN Control - * @{ - */ -#define ETH_INNER_VLAN_DISABLE ETH_DMATXCDESC_IVTIR_DISABLE -#define ETH_INNER_VLAN_REMOVE ETH_DMATXCDESC_IVTIR_REMOVE -#define ETH_INNER_VLAN_INSERT ETH_DMATXCDESC_IVTIR_INSERT -#define ETH_INNER_VLAN_REPLACE ETH_DMATXCDESC_IVTIR_REPLACE -/** - * @} - */ - /** @defgroup ETH_Rx_MAC_Filter_Status ETH Rx MAC Filter Status * @{ @@ -995,15 +962,11 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_DMA_Arbitration ETH DMA Arbitration * @{ */ -#define ETH_DMAARBITRATION_RX ETH_DMAMR_DA +#define ETH_DMAARBITRATION_RX ETH_DMABMR_DA #define ETH_DMAARBITRATION_RX1_TX1 0x00000000U -#define ETH_DMAARBITRATION_RX2_TX1 ETH_DMAMR_PR_2_1 -#define ETH_DMAARBITRATION_RX3_TX1 ETH_DMAMR_PR_3_1 -#define ETH_DMAARBITRATION_RX4_TX1 ETH_DMAMR_PR_4_1 -#define ETH_DMAARBITRATION_RX5_TX1 ETH_DMAMR_PR_5_1 -#define ETH_DMAARBITRATION_RX6_TX1 ETH_DMAMR_PR_6_1 -#define ETH_DMAARBITRATION_RX7_TX1 ETH_DMAMR_PR_7_1 -#define ETH_DMAARBITRATION_RX8_TX1 ETH_DMAMR_PR_8_1 +#define ETH_DMAARBITRATION_RX2_TX1 ETH_DMABMR_RTPR_2_1 +#define ETH_DMAARBITRATION_RX3_TX1 ETH_DMABMR_RTPR_3_1 +#define ETH_DMAARBITRATION_RX4_TX1 ETH_DMABMR_RTPR_4_1 #define ETH_DMAARBITRATION_TX (ETH_DMAMR_TXPR | ETH_DMAMR_DA) #define ETH_DMAARBITRATION_TX1_RX1 0x00000000U #define ETH_DMAARBITRATION_TX2_RX1 (ETH_DMAMR_TXPR | ETH_DMAMR_PR_2_1) @@ -1068,19 +1031,18 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_DMA_Interrupts ETH DMA Interrupts * @{ */ -#define ETH_DMA_NORMAL_IT ETH_DMACIER_NIE -#define ETH_DMA_ABNORMAL_IT ETH_DMACIER_AIE -#define ETH_DMA_CONTEXT_DESC_ERROR_IT ETH_DMACIER_CDEE -#define ETH_DMA_FATAL_BUS_ERROR_IT ETH_DMACIER_FBEE -#define ETH_DMA_EARLY_RX_IT ETH_DMACIER_ERIE -#define ETH_DMA_EARLY_TX_IT ETH_DMACIER_ETIE -#define ETH_DMA_RX_WATCHDOG_TIMEOUT_IT ETH_DMACIER_RWTE -#define ETH_DMA_RX_PROCESS_STOPPED_IT ETH_DMACIER_RSE -#define ETH_DMA_RX_BUFFER_UNAVAILABLE_IT ETH_DMACIER_RBUE -#define ETH_DMA_RX_IT ETH_DMACIER_RIE -#define ETH_DMA_TX_BUFFER_UNAVAILABLE_IT ETH_DMACIER_TBUE -#define ETH_DMA_TX_PROCESS_STOPPED_IT ETH_DMACIER_TXSE -#define ETH_DMA_TX_IT ETH_DMACIER_TIE +#define ETH_DMA_NORMAL_IT ETH_DMAIER_NISE +#define ETH_DMA_ABNORMAL_IT ETH_DMAIER_AISE +#define ETH_DMA_FATAL_BUS_ERROR_IT ETH_DMAIER_FBEIE +#define ETH_DMA_EARLY_RX_IT ETH_DMAIER_ERIE +#define ETH_DMA_EARLY_TX_IT ETH_DMAIER_ETIE +#define ETH_DMA_RX_WATCHDOG_TIMEOUT_IT ETH_DMAIER_RWTIE +#define ETH_DMA_RX_PROCESS_STOPPED_IT ETH_DMAIER_RPSIE +#define ETH_DMA_RX_BUFFER_UNAVAILABLE_IT ETH_DMAIER_RBUIE +#define ETH_DMA_RX_IT ETH_DMAIER_RIE +#define ETH_DMA_TX_BUFFER_UNAVAILABLE_IT ETH_DMAIER_TBUIE +#define ETH_DMA_TX_PROCESS_STOPPED_IT ETH_DMAIER_TPSIE +#define ETH_DMA_TX_IT ETH_DMAIER_TIE /** * @} */ @@ -1088,23 +1050,19 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_DMA_Status_Flags ETH DMA Status Flags * @{ */ -#define ETH_DMA_RX_NO_ERROR_FLAG 0x00000000U -#define ETH_DMA_RX_DESC_READ_ERROR_FLAG (ETH_DMACSR_REB_BIT_2 | ETH_DMACSR_REB_BIT_1 | ETH_DMACSR_REB_BIT_0) -#define ETH_DMA_RX_DESC_WRITE_ERROR_FLAG (ETH_DMACSR_REB_BIT_2 | ETH_DMACSR_REB_BIT_1) -#define ETH_DMA_RX_BUFFER_READ_ERROR_FLAG (ETH_DMACSR_REB_BIT_2 | ETH_DMACSR_REB_BIT_0) -#define ETH_DMA_RX_BUFFER_WRITE_ERROR_FLAG ETH_DMACSR_REB_BIT_2 -#define ETH_DMA_TX_NO_ERROR_FLAG 0x00000000U -#define ETH_DMA_TX_DESC_READ_ERROR_FLAG (ETH_DMACSR_TEB_BIT_2 | ETH_DMACSR_TEB_BIT_1 | ETH_DMACSR_TEB_BIT_0) -#define ETH_DMA_TX_DESC_WRITE_ERROR_FLAG (ETH_DMACSR_TEB_BIT_2 | ETH_DMACSR_TEB_BIT_1) -#define ETH_DMA_TX_BUFFER_READ_ERROR_FLAG (ETH_DMACSR_TEB_BIT_2 | ETH_DMACSR_TEB_BIT_0) -#define ETH_DMA_TX_BUFFER_WRITE_ERROR_FLAG ETH_DMACSR_TEB_BIT_2 -#define ETH_DMA_CONTEXT_DESC_ERROR_FLAG ETH_DMACSR_CDE -#define ETH_DMA_FATAL_BUS_ERROR_FLAG ETH_DMACSR_FBE -#define ETH_DMA_EARLY_TX_IT_FLAG ETH_DMACSR_ERI -#define ETH_DMA_RX_WATCHDOG_TIMEOUT_FLAG ETH_DMACSR_RWT -#define ETH_DMA_RX_PROCESS_STOPPED_FLAG ETH_DMACSR_RPS -#define ETH_DMA_RX_BUFFER_UNAVAILABLE_FLAG ETH_DMACSR_RBU -#define ETH_DMA_TX_PROCESS_STOPPED_FLAG ETH_DMACSR_TPS +#define ETH_DMA_NO_ERROR_FLAG 0x00000000U +#define ETH_DMA_TX_DATA_TRANS_ERROR_FLAG ETH_DMASR_EBS_DataTransfTx +#define ETH_DMA_RX_DATA_TRANS_ERROR_FLAG 0x00000000U +#define ETH_DMA_READ_TRANS_ERROR_FLAG ETH_DMASR_EBS_ReadTransf +#define ETH_DMA_WRITE_TRANS_ERROR_FLAG 0x00000000U +#define ETH_DMA_DESC_ACCESS_ERROR_FLAG ETH_DMASR_EBS_DescAccess +#define ETH_DMA_DATA_BUFF_ACCESS_ERROR_FLAG 0x00000000U +#define ETH_DMA_FATAL_BUS_ERROR_FLAG ETH_DMASR_FBES +#define ETH_DMA_EARLY_TX_IT_FLAG ETH_DMASR_ETS +#define ETH_DMA_RX_WATCHDOG_TIMEOUT_FLAG ETH_DMASR_RWTS +#define ETH_DMA_RX_PROCESS_STOPPED_FLAG ETH_DMASR_RPSS +#define ETH_DMA_RX_BUFFER_UNAVAILABLE_FLAG ETH_DMASR_RBUS +#define ETH_DMA_TX_PROCESS_STOPPED_FLAG ETH_DMASR_TPS /** * @} */ @@ -1112,15 +1070,15 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_Transmit_Mode ETH Transmit Mode * @{ */ -#define ETH_TRANSMITSTOREFORWARD ETH_MTLTQOMR_TSF -#define ETH_TRANSMITTHRESHOLD_32 ETH_MTLTQOMR_TTC_32BITS -#define ETH_TRANSMITTHRESHOLD_64 ETH_MTLTQOMR_TTC_64BITS -#define ETH_TRANSMITTHRESHOLD_96 ETH_MTLTQOMR_TTC_96BITS -#define ETH_TRANSMITTHRESHOLD_128 ETH_MTLTQOMR_TTC_128BITS -#define ETH_TRANSMITTHRESHOLD_192 ETH_MTLTQOMR_TTC_192BITS -#define ETH_TRANSMITTHRESHOLD_256 ETH_MTLTQOMR_TTC_256BITS -#define ETH_TRANSMITTHRESHOLD_384 ETH_MTLTQOMR_TTC_384BITS -#define ETH_TRANSMITTHRESHOLD_512 ETH_MTLTQOMR_TTC_512BITS +#define ETH_TRANSMITSTOREFORWARD ETH_DMAOMR_TSF +#define ETH_TRANSMITTHRESHOLD_16 ETH_DMAOMR_TTC_16Bytes +#define ETH_TRANSMITTHRESHOLD_24 ETH_DMAOMR_TTC_24Bytes +#define ETH_TRANSMITTHRESHOLD_32 ETH_DMAOMR_TTC_32Bytes +#define ETH_TRANSMITTHRESHOLD_40 ETH_DMAOMR_TTC_40Bytes +#define ETH_TRANSMITTHRESHOLD_64 ETH_DMAOMR_TTC_64Bytes +#define ETH_TRANSMITTHRESHOLD_128 ETH_DMAOMR_TTC_128Bytes +#define ETH_TRANSMITTHRESHOLD_192 ETH_DMAOMR_TTC_192Bytes +#define ETH_TRANSMITTHRESHOLD_256 ETH_DMAOMR_TTC_256Bytes /** * @} */ @@ -1128,11 +1086,11 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_Receive_Mode ETH Receive Mode * @{ */ -#define ETH_RECEIVESTOREFORWARD ETH_MTLRQOMR_RSF -#define ETH_RECEIVETHRESHOLD8_64 ETH_MTLRQOMR_RTC_64BITS -#define ETH_RECEIVETHRESHOLD8_32 ETH_MTLRQOMR_RTC_32BITS -#define ETH_RECEIVETHRESHOLD8_96 ETH_MTLRQOMR_RTC_96BITS -#define ETH_RECEIVETHRESHOLD8_128 ETH_MTLRQOMR_RTC_128BITS +#define ETH_RECEIVESTOREFORWARD ETH_DMAOMR_RSF +#define ETH_RECEIVETHRESHOLD8_64 ETH_DMAOMR_RTC_64Bytes +#define ETH_RECEIVETHRESHOLD8_32 ETH_DMAOMR_RTC_32Bytes +#define ETH_RECEIVETHRESHOLD8_96 ETH_DMAOMR_RTC_96Bytes +#define ETH_RECEIVETHRESHOLD8_128 ETH_DMAOMR_RTC_128Bytes /** * @} */ @@ -1140,52 +1098,14 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_Pause_Low_Threshold ETH Pause Low Threshold * @{ */ -#define ETH_PAUSELOWTHRESHOLD_MINUS_4 ETH_MACTFCR_PLT_MINUS4 -#define ETH_PAUSELOWTHRESHOLD_MINUS_28 ETH_MACTFCR_PLT_MINUS28 -#define ETH_PAUSELOWTHRESHOLD_MINUS_36 ETH_MACTFCR_PLT_MINUS36 -#define ETH_PAUSELOWTHRESHOLD_MINUS_144 ETH_MACTFCR_PLT_MINUS144 -#define ETH_PAUSELOWTHRESHOLD_MINUS_256 ETH_MACTFCR_PLT_MINUS256 -#define ETH_PAUSELOWTHRESHOLD_MINUS_512 ETH_MACTFCR_PLT_MINUS512 +#define ETH_PAUSELOWTHRESHOLD_MINUS_4 ETH_MACFCR_PLT_Minus4 +#define ETH_PAUSELOWTHRESHOLD_MINUS_28 ETH_MACFCR_PLT_Minus28 +#define ETH_PAUSELOWTHRESHOLD_MINUS_144 ETH_MACFCR_PLT_Minus144 +#define ETH_PAUSELOWTHRESHOLD_MINUS_256 ETH_MACFCR_PLT_Minus256 /** * @} */ -/** @defgroup ETH_Watchdog_Timeout ETH Watchdog Timeout - * @{ - */ -#define ETH_WATCHDOGTIMEOUT_2KB ETH_MACWTR_WTO_2KB -#define ETH_WATCHDOGTIMEOUT_3KB ETH_MACWTR_WTO_3KB -#define ETH_WATCHDOGTIMEOUT_4KB ETH_MACWTR_WTO_4KB -#define ETH_WATCHDOGTIMEOUT_5KB ETH_MACWTR_WTO_5KB -#define ETH_WATCHDOGTIMEOUT_6KB ETH_MACWTR_WTO_6KB -#define ETH_WATCHDOGTIMEOUT_7KB ETH_MACWTR_WTO_7KB -#define ETH_WATCHDOGTIMEOUT_8KB ETH_MACWTR_WTO_8KB -#define ETH_WATCHDOGTIMEOUT_9KB ETH_MACWTR_WTO_9KB -#define ETH_WATCHDOGTIMEOUT_10KB ETH_MACWTR_WTO_10KB -#define ETH_WATCHDOGTIMEOUT_11KB ETH_MACWTR_WTO_12KB -#define ETH_WATCHDOGTIMEOUT_12KB ETH_MACWTR_WTO_12KB -#define ETH_WATCHDOGTIMEOUT_13KB ETH_MACWTR_WTO_13KB -#define ETH_WATCHDOGTIMEOUT_14KB ETH_MACWTR_WTO_14KB -#define ETH_WATCHDOGTIMEOUT_15KB ETH_MACWTR_WTO_15KB -#define ETH_WATCHDOGTIMEOUT_16KB ETH_MACWTR_WTO_16KB -/** - * @} - */ - -/** @defgroup ETH_Inter_Packet_Gap ETH Inter Packet Gap - * @{ - */ -#define ETH_INTERPACKETGAP_96BIT ETH_MACCR_IPG_96BIT -#define ETH_INTERPACKETGAP_88BIT ETH_MACCR_IPG_88BIT -#define ETH_INTERPACKETGAP_80BIT ETH_MACCR_IPG_80BIT -#define ETH_INTERPACKETGAP_72BIT ETH_MACCR_IPG_72BIT -#define ETH_INTERPACKETGAP_64BIT ETH_MACCR_IPG_64BIT -#define ETH_INTERPACKETGAP_56BIT ETH_MACCR_IPG_56BIT -#define ETH_INTERPACKETGAP_48BIT ETH_MACCR_IPG_48BIT -#define ETH_INTERPACKETGAP_40BIT ETH_MACCR_IPG_40BIT -/** - * @} - */ /** @defgroup ETH_Speed ETH Speed * @{ @@ -1216,15 +1136,6 @@ TDES7 | Transmit Time Stamp High [31:0] * @} */ -/** @defgroup ETH_Preamble_Length ETH Preamble Length - * @{ - */ -#define ETH_PREAMBLELENGTH_7 ETH_MACCR_PRELEN_7 -#define ETH_PREAMBLELENGTH_5 ETH_MACCR_PRELEN_5 -#define ETH_PREAMBLELENGTH_3 ETH_MACCR_PRELEN_3 -/** - * @} - */ /** @defgroup ETH_Source_Addr_Control ETH Source Addr Control * @{ @@ -1238,16 +1149,6 @@ TDES7 | Transmit Time Stamp High [31:0] * @} */ -/** @defgroup ETH_Control_Packets_Filter ETH Control Packets Filter - * @{ - */ -#define ETH_CTRLPACKETS_BLOCK_ALL ETH_MACPFR_PCF_BLOCKALL -#define ETH_CTRLPACKETS_FORWARD_ALL_EXCEPT_PA ETH_MACPFR_PCF_FORWARDALLEXCEPTPA -#define ETH_CTRLPACKETS_FORWARD_ALL ETH_MACPFR_PCF_FORWARDALL -#define ETH_CTRLPACKETS_FORWARD_PASSED_ADDR_FILTER ETH_MACPFR_PCF_FORWARDPASSEDADDRFILTER -/** - * @} - */ /** @defgroup ETH_VLAN_Tag_Comparison ETH VLAN Tag Comparison * @{ @@ -1280,25 +1181,12 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_MAC_Wake_Up_Event ETH MAC Wake Up Event * @{ */ -#define ETH_WAKEUP_PACKET_RECIEVED ETH_MACPCSR_RWKPRCVD -#define ETH_MAGIC_PACKET_RECIEVED ETH_MACPCSR_MGKPRCVD +#define ETH_WAKEUP_FRAME_RECIEVED ETH_MACPMTCSR_WFR +#define ETH_MAGIC_PACKET_RECIEVED ETH_MACPMTCSR_MPR /** * @} */ -/** @defgroup ETH_MAC_Rx_Tx_Status ETH MAC Rx Tx Status - * @{ - */ -#define ETH_RECEIVE_WATCHDOG_TIMEOUT ETH_MACRXTXSR_RWT -#define ETH_EXECESSIVE_COLLISIONS ETH_MACRXTXSR_EXCOL -#define ETH_LATE_COLLISIONS ETH_MACRXTXSR_LCOL -#define ETH_EXECESSIVE_DEFERRAL ETH_MACRXTXSR_EXDEF -#define ETH_LOSS_OF_CARRIER ETH_MACRXTXSR_LCARR -#define ETH_NO_CARRIER ETH_MACRXTXSR_NCARR -#define ETH_TRANSMIT_JABBR_TIMEOUT ETH_MACRXTXSR_TJT -/** - * @} - */ /** @defgroup ETH_State_Codes ETH States * @{ @@ -1804,11 +1692,12 @@ TDES7 | Transmit Time Stamp High [31:0] /** @defgroup ETH_PTP_Config_Status ETH PTP Config Status * @{ */ -#define HAL_ETH_PTP_NOT_CONFIGURATED 0x00000000U /*!< ETH PTP Configuration not done */ -#define HAL_ETH_PTP_CONFIGURATED 0x00000001U /*!< ETH PTP Configuration done */ +#define HAL_ETH_PTP_NOT_CONFIGURED 0x00000000U /*!< ETH PTP Configuration not done */ +#define HAL_ETH_PTP_CONFIGURED 0x00000001U /*!< ETH PTP Configuration done */ /** * @} */ + /** * @} */ @@ -1886,7 +1775,7 @@ TDES7 | Transmit Time Stamp High [31:0] * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Status_Flags * @retval The state of ETH DMA FLAG (SET or RESET). */ -#define __HAL_ETH_DMA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->DMACSR &\ +#define __HAL_ETH_DMA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->DMASR &\ ( __FLAG__)) == ( __FLAG__)) /** @@ -1895,28 +1784,9 @@ TDES7 | Transmit Time Stamp High [31:0] * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Status_Flags * @retval The state of ETH DMA FLAG (SET or RESET). */ -#define __HAL_ETH_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->DMACSR = ( __FLAG__)) - -/** - * @brief Enables the specified ETHERNET MAC interrupts. - * @param __HANDLE__ : ETH Handle - * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be - * enabled @ref ETH_MAC_Interrupts - * @retval None - */ +#define __HAL_ETH_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->DMASR = ( __FLAG__)) -#define __HAL_ETH_MAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIER \ - |= (__INTERRUPT__)) -/** - * @brief Disables the specified ETHERNET MAC interrupts. - * @param __HANDLE__ : ETH Handle - * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be - * enabled @ref ETH_MAC_Interrupts - * @retval None - */ -#define __HAL_ETH_MAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIER \ - &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified ETHERNET MAC flag is set or not. @@ -1954,7 +1824,6 @@ TDES7 | Transmit Time Stamp High [31:0] */ #define __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) - /** * @brief enable rising edge interrupt on selected EXTI line. * @param __EXTI_LINE__: specifies the ETH WAKEUP EXTI sources to be disabled. @@ -2041,7 +1910,7 @@ HAL_StatusTypeDef HAL_ETH_RegisterRxAllocateCallback(ETH_HandleTypeDef *heth, HAL_StatusTypeDef HAL_ETH_UnRegisterRxAllocateCallback(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_RegisterRxLinkCallback(ETH_HandleTypeDef *heth, pETH_rxLinkCallbackTypeDef rxLinkCallback); HAL_StatusTypeDef HAL_ETH_UnRegisterRxLinkCallback(ETH_HandleTypeDef *heth); -HAL_StatusTypeDef HAL_ETH_GetRxDataErrorCode(ETH_HandleTypeDef *heth, uint32_t *pErrorCode); +HAL_StatusTypeDef HAL_ETH_GetRxDataErrorCode(const ETH_HandleTypeDef *heth, uint32_t *pErrorCode); HAL_StatusTypeDef HAL_ETH_RegisterTxFreeCallback(ETH_HandleTypeDef *heth, pETH_txFreeCallbackTypeDef txFreeCallback); HAL_StatusTypeDef HAL_ETH_UnRegisterTxFreeCallback(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth); @@ -2060,8 +1929,8 @@ HAL_StatusTypeDef HAL_ETH_RegisterTxPtpCallback(ETH_HandleTypeDef *heth, pETH_tx HAL_StatusTypeDef HAL_ETH_UnRegisterTxPtpCallback(ETH_HandleTypeDef *heth); #endif /* HAL_ETH_USE_PTP */ -HAL_StatusTypeDef HAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t Timeout); -HAL_StatusTypeDef HAL_ETH_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig); +HAL_StatusTypeDef HAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfigTypeDef *pTxConfig, uint32_t Timeout); +HAL_StatusTypeDef HAL_ETH_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfigTypeDef *pTxConfig); HAL_StatusTypeDef HAL_ETH_WritePHYRegister(const ETH_HandleTypeDef *heth, uint32_t PHYAddr, uint32_t PHYReg, uint32_t RegValue); @@ -2087,8 +1956,8 @@ void HAL_ETH_TxPtpCallback(uint32_t *buff, ETH_TimeStampTypeDef *ti */ /* Peripheral Control functions **********************************************/ /* MAC & DMA Configuration APIs **********************************************/ -HAL_StatusTypeDef HAL_ETH_GetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); -HAL_StatusTypeDef HAL_ETH_GetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); +HAL_StatusTypeDef HAL_ETH_GetMACConfig(const ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); +HAL_StatusTypeDef HAL_ETH_GetDMAConfig(const ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); HAL_StatusTypeDef HAL_ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); HAL_StatusTypeDef HAL_ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); void HAL_ETH_SetMDIOClockRange(ETH_HandleTypeDef *heth); @@ -2098,7 +1967,7 @@ void HAL_ETH_SetRxVLANIdentifier(ETH_HandleTypeDef *heth, uint32_t uint32_t VLANIdentifier); /* MAC L2 Packet Filtering APIs **********************************************/ -HAL_StatusTypeDef HAL_ETH_GetMACFilterConfig(ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig); +HAL_StatusTypeDef HAL_ETH_GetMACFilterConfig(const ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig); HAL_StatusTypeDef HAL_ETH_SetMACFilterConfig(ETH_HandleTypeDef *heth, const ETH_MACFilterConfigTypeDef *pFilterConfig); HAL_StatusTypeDef HAL_ETH_SetHashTable(ETH_HandleTypeDef *heth, uint32_t *pHashTable); HAL_StatusTypeDef HAL_ETH_SetSourceMACAddrMatch(const ETH_HandleTypeDef *heth, uint32_t AddrNbr, diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash.h index c2d0bf493..41f77d28f 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash.h @@ -20,7 +20,7 @@ #define __STM32F4xx_HAL_FLASH_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Includes ------------------------------------------------------------------*/ @@ -71,7 +71,7 @@ typedef struct __IO uint32_t ErrorCode; /* FLASH error code */ -}FLASH_ProcessTypeDef; +} FLASH_ProcessTypeDef; /** * @} @@ -224,7 +224,7 @@ typedef struct * @retval None */ #define __HAL_FLASH_INSTRUCTION_CACHE_RESET() do {FLASH->ACR |= FLASH_ACR_ICRST; \ - FLASH->ACR &= ~FLASH_ACR_ICRST; \ + FLASH->ACR &= ~FLASH_ACR_ICRST; \ }while(0U) /** @@ -233,7 +233,7 @@ typedef struct * @retval None */ #define __HAL_FLASH_DATA_CACHE_RESET() do {FLASH->ACR |= FLASH_ACR_DCRST; \ - FLASH->ACR &= ~FLASH_ACR_DCRST; \ + FLASH->ACR &= ~FLASH_ACR_DCRST; \ }while(0U) /** * @brief Enable the specified FLASH interrupt. diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ex.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ex.h index 63dcc9a2d..6d495de3f 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ex.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ex.h @@ -20,7 +20,7 @@ #define __STM32F4xx_HAL_FLASH_EX_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Includes ------------------------------------------------------------------*/ @@ -125,7 +125,7 @@ typedef struct This parameter can be a value of @ref FLASHEx_Dual_Boot */ #endif /*STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ -}FLASH_AdvOBProgramInitTypeDef; +} FLASH_AdvOBProgramInitTypeDef; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */ /** @@ -732,7 +732,7 @@ void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit); defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) ||\ defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx) -HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram (FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); +HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); void HAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); HAL_StatusTypeDef HAL_FLASHEx_OB_SelectPCROP(void); HAL_StatusTypeDef HAL_FLASHEx_OB_DeSelectPCROP(void); diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ramfunc.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ramfunc.h index 014b10967..2112e747c 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ramfunc.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_flash_ramfunc.h @@ -20,7 +20,7 @@ #define __STM32F4xx_FLASH_RAMFUNC_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F411xE) || defined(STM32F446xx) || defined(STM32F412Zx) ||\ defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F412Cx) diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_lptim.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_lptim.h index fba2d52c0..ddaf51c25 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_lptim.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_lptim.h @@ -399,6 +399,7 @@ typedef void (*pLPTIM_CallbackTypeDef)(LPTIM_HandleTypeDef *hlptim); /*!< poin * @brief Write the passed parameter in the Autoreload register. * @param __HANDLE__ LPTIM handle * @param __VALUE__ Autoreload value + * This parameter must be a value between Min_Data = 0x0001 and Max_Data = 0xFFFF. * @retval None * @note The ARR register can only be modified when the LPTIM instance is enabled. */ @@ -818,9 +819,6 @@ HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(const LPTIM_HandleTypeDef *hlptim); #define IS_LPTIM_COUNTER_SOURCE(__SOURCE__) (((__SOURCE__) == LPTIM_COUNTERSOURCE_INTERNAL) || \ ((__SOURCE__) == LPTIM_COUNTERSOURCE_EXTERNAL)) -#define IS_LPTIM_AUTORELOAD(__AUTORELOAD__) ((0x00000001UL <= (__AUTORELOAD__)) &&\ - ((__AUTORELOAD__) <= 0x0000FFFFUL)) - #define IS_LPTIM_COMPARE(__COMPARE__) ((__COMPARE__) <= 0x0000FFFFUL) #define IS_LPTIM_PERIOD(__PERIOD__) ((0x00000001UL <= (__PERIOD__)) &&\ diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_pcd_ex.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_pcd_ex.h index 0c6f2e01d..284c9d565 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_pcd_ex.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_pcd_ex.h @@ -45,7 +45,6 @@ extern "C" { /** @addtogroup PCDEx_Exported_Functions_Group1 Peripheral Control functions * @{ */ - #if defined (USB_OTG_FS) || defined (USB_OTG_HS) HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size); HAL_StatusTypeDef HAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size); diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_qspi.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_qspi.h index 56287af6c..12b08022c 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_qspi.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_qspi.h @@ -623,13 +623,13 @@ HAL_StatusTypeDef HAL_QSPI_UnRegisterCallback (QSPI_HandleTypeDef *hqspi, * @{ */ /* Peripheral Control and State functions ************************************/ -HAL_QSPI_StateTypeDef HAL_QSPI_GetState (QSPI_HandleTypeDef *hqspi); -uint32_t HAL_QSPI_GetError (QSPI_HandleTypeDef *hqspi); +HAL_QSPI_StateTypeDef HAL_QSPI_GetState (const QSPI_HandleTypeDef *hqspi); +uint32_t HAL_QSPI_GetError (const QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_Abort (QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_Abort_IT (QSPI_HandleTypeDef *hqspi); void HAL_QSPI_SetTimeout (QSPI_HandleTypeDef *hqspi, uint32_t Timeout); HAL_StatusTypeDef HAL_QSPI_SetFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t Threshold); -uint32_t HAL_QSPI_GetFifoThreshold(QSPI_HandleTypeDef *hqspi); +uint32_t HAL_QSPI_GetFifoThreshold(const QSPI_HandleTypeDef *hqspi); HAL_StatusTypeDef HAL_QSPI_SetFlashID (QSPI_HandleTypeDef *hqspi, uint32_t FlashID); /** * @} diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc.h index c348e5eff..cf01e5147 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc.h @@ -20,7 +20,7 @@ #define __STM32F4xx_HAL_RCC_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Includes ------------------------------------------------------------------*/ @@ -67,7 +67,7 @@ typedef struct This parameter can be a value of @ref RCC_LSI_Config */ RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ -}RCC_OscInitTypeDef; +} RCC_OscInitTypeDef; /** * @brief RCC System, AHB and APB busses clock configuration structure definition @@ -89,7 +89,7 @@ typedef struct uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ -}RCC_ClkInitTypeDef; +} RCC_ClkInitTypeDef; /** * @} @@ -382,47 +382,47 @@ typedef struct * @{ */ #define __HAL_RCC_GPIOA_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOAEN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_GPIOB_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOBEN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_GPIOC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_GPIOH_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOHEN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_DMA1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA1EN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_DMA2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOA_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOAEN)) #define __HAL_RCC_GPIOB_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOBEN)) @@ -466,53 +466,53 @@ typedef struct * @{ */ #define __HAL_RCC_TIM5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_WWDG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_PWR_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_TIM5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM5EN)) @@ -560,61 +560,61 @@ typedef struct * @{ */ #define __HAL_RCC_TIM1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SYSCFG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM9_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM11_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM1EN)) #define __HAL_RCC_USART1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART1EN)) @@ -839,7 +839,7 @@ typedef struct * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(__HSICalibrationValue__) (MODIFY_REG(RCC->CR,\ - RCC_CR_HSITRIM, (uint32_t)(__HSICalibrationValue__) << RCC_CR_HSITRIM_Pos)) + RCC_CR_HSITRIM, (uint32_t)(__HSICalibrationValue__) << RCC_CR_HSITRIM_Pos)) /** * @} */ @@ -888,22 +888,22 @@ typedef struct * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock. */ #define __HAL_RCC_HSE_CONFIG(__STATE__) \ - do { \ - if ((__STATE__) == RCC_HSE_ON) \ - { \ - SET_BIT(RCC->CR, RCC_CR_HSEON); \ - } \ - else if ((__STATE__) == RCC_HSE_BYPASS) \ - { \ - SET_BIT(RCC->CR, RCC_CR_HSEBYP); \ - SET_BIT(RCC->CR, RCC_CR_HSEON); \ - } \ - else \ - { \ - CLEAR_BIT(RCC->CR, RCC_CR_HSEON); \ - CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); \ - } \ - } while(0U) + do { \ + if ((__STATE__) == RCC_HSE_ON) \ + { \ + SET_BIT(RCC->CR, RCC_CR_HSEON); \ + } \ + else if ((__STATE__) == RCC_HSE_BYPASS) \ + { \ + SET_BIT(RCC->CR, RCC_CR_HSEBYP); \ + SET_BIT(RCC->CR, RCC_CR_HSEON); \ + } \ + else \ + { \ + CLEAR_BIT(RCC->CR, RCC_CR_HSEON); \ + CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); \ + } \ + } while(0U) /** * @} */ @@ -931,22 +931,22 @@ typedef struct * @arg RCC_LSE_BYPASS: LSE oscillator bypassed with external clock. */ #define __HAL_RCC_LSE_CONFIG(__STATE__) \ - do { \ - if((__STATE__) == RCC_LSE_ON) \ - { \ - SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ - } \ - else if((__STATE__) == RCC_LSE_BYPASS) \ - { \ - SET_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ - SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ - } \ - else \ - { \ - CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ - CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ - } \ - } while(0U) + do { \ + if((__STATE__) == RCC_LSE_ON) \ + { \ + SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ + } \ + else if((__STATE__) == RCC_LSE_BYPASS) \ + { \ + SET_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ + SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ + } \ + else \ + { \ + CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ + CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ + } \ + } while(0U) /** * @} */ @@ -983,7 +983,7 @@ typedef struct * RTC clock source). */ #define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) (((__RTCCLKSource__) & RCC_BDCR_RTCSEL) == RCC_BDCR_RTCSEL) ? \ - MODIFY_REG(RCC->CFGR, RCC_CFGR_RTCPRE, ((__RTCCLKSource__) & 0xFFFFCFFU)) : CLEAR_BIT(RCC->CFGR, RCC_CFGR_RTCPRE) + MODIFY_REG(RCC->CFGR, RCC_CFGR_RTCPRE, ((__RTCCLKSource__) & 0xFFFFCFFU)) : CLEAR_BIT(RCC->CFGR, RCC_CFGR_RTCPRE) #define __HAL_RCC_RTC_CONFIG(__RTCCLKSource__) do { __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__); \ RCC->BDCR |= ((__RTCCLKSource__) & 0x00000FFFU); \ @@ -1001,7 +1001,7 @@ typedef struct /** * @brief Get the RTC and HSE clock divider (RTCPRE). * @retval Returned value can be one of the following values: - * @arg @ref RCC_RTCCLKSOURCE_HSE_DIVX HSE divided by X selected as RTC clock (X can be retrieved thanks to @ref __HAL_RCC_GET_RTC_HSE_PRESCALER() + * @arg @ref RCC_RTCCLKSOURCE_HSE_DIVX HSE divided by X selected as RTC clock (X can be retrieved thanks to @ref __HAL_RCC_GET_RTC_HSE_PRESCALER() */ #define __HAL_RCC_GET_RTC_HSE_PRESCALER() (READ_BIT(RCC->CFGR, RCC_CFGR_RTCPRE) | RCC_BDCR_RTCSEL) @@ -1111,7 +1111,7 @@ typedef struct * @arg RCC_MCODIV_5: division by 5 applied to MCOx clock */ #define __HAL_RCC_MCO1_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ - MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO1 | RCC_CFGR_MCO1PRE), ((__MCOCLKSOURCE__) | (__MCODIV__))) + MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO1 | RCC_CFGR_MCO1PRE), ((__MCOCLKSOURCE__) | (__MCODIV__))) /** @brief Macro to configure the MCO2 clock. * @param __MCOCLKSOURCE__ specifies the MCO clock source. @@ -1132,7 +1132,7 @@ typedef struct * at least one of the SPI clocks enabled (SPI1, SPI2 or SPI5). */ #define __HAL_RCC_MCO2_CONFIG(__MCOCLKSOURCE__, __MCODIV__) \ - MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO2 | RCC_CFGR_MCO2PRE), ((__MCOCLKSOURCE__) | ((__MCODIV__) << 3U))); + MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO2 | RCC_CFGR_MCO2PRE), ((__MCOCLKSOURCE__) | ((__MCODIV__) << 3U))); /** * @} */ @@ -1220,7 +1220,9 @@ typedef struct * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define RCC_FLAG_MASK ((uint8_t)0x1FU) -#define __HAL_RCC_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5U) == 1U)? RCC->CR :((((__FLAG__) >> 5U) == 2U) ? RCC->BDCR :((((__FLAG__) >> 5U) == 3U)? RCC->CSR :RCC->CIR))) & (1U << ((__FLAG__) & RCC_FLAG_MASK)))!= 0U)? 1U : 0U) +#define __HAL_RCC_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5U)\ + == 1U)? RCC->CR :((((__FLAG__) >> 5U) == 2U) ? RCC->BDCR :((((__FLAG__) >> 5U) == 3U)? RCC->CSR :RCC->CIR))) &\ + (1U << ((__FLAG__) & RCC_FLAG_MASK)))!= 0U)? 1U : 0U) /** * @} @@ -1231,9 +1233,9 @@ typedef struct */ /* Exported functions --------------------------------------------------------*/ - /** @addtogroup RCC_Exported_Functions +/** @addtogroup RCC_Exported_Functions * @{ - */ + */ /** @addtogroup RCC_Exported_Functions_Group1 * @{ @@ -1428,8 +1430,8 @@ void HAL_RCC_CSSCallback(void); ((SOURCE) == RCC_MCO1SOURCE_HSE) || ((SOURCE) == RCC_MCO1SOURCE_PLLCLK)) #define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCODIV_1) || ((DIV) == RCC_MCODIV_2) || \ - ((DIV) == RCC_MCODIV_3) || ((DIV) == RCC_MCODIV_4) || \ - ((DIV) == RCC_MCODIV_5)) + ((DIV) == RCC_MCODIV_3) || ((DIV) == RCC_MCODIV_4) || \ + ((DIV) == RCC_MCODIV_5)) #define IS_RCC_CALIBRATION_VALUE(VALUE) ((VALUE) <= 0x1FU) /** diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc_ex.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc_ex.h index 735c8f7c6..0b37d9a19 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc_ex.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_rcc_ex.h @@ -20,7 +20,7 @@ #define __STM32F4xx_HAL_RCC_EX_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Includes ------------------------------------------------------------------*/ @@ -70,7 +70,7 @@ typedef struct and STM32F412Zx/STM32F412Vx/STM32F412Rx/STM32F412Cx/STM32F413xx/STM32F423xx devices. This parameter must be a number between Min_Data = 2 and Max_Data = 7 */ #endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */ -}RCC_PLLInitTypeDef; +} RCC_PLLInitTypeDef; #if defined(STM32F446xx) /** @@ -94,7 +94,7 @@ typedef struct uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S */ -}RCC_PLLI2SInitTypeDef; +} RCC_PLLI2SInitTypeDef; /** * @brief PLLSAI Clock structure definition @@ -113,7 +113,7 @@ typedef struct uint32_t PLLSAIQ; /*!< Specifies the division factor for SAI clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLSAI is selected as Clock Source SAI */ -}RCC_PLLSAIInitTypeDef; +} RCC_PLLSAIInitTypeDef; /** * @brief RCC extended clocks structure definition @@ -169,7 +169,7 @@ typedef struct uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ -}RCC_PeriphCLKInitTypeDef; +} RCC_PeriphCLKInitTypeDef; #endif /* STM32F446xx */ #if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) @@ -195,7 +195,7 @@ typedef struct uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ -}RCC_PeriphCLKInitTypeDef; +} RCC_PeriphCLKInitTypeDef; #endif /* STM32F410Tx || STM32F410Cx || STM32F410Rx */ #if defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx) @@ -217,7 +217,7 @@ typedef struct uint32_t PLLI2SR; /*!< Specifies the division factor for I2S clock. This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S */ -}RCC_PLLI2SInitTypeDef; +} RCC_PLLI2SInitTypeDef; /** * @brief RCC extended clocks structure definition @@ -286,7 +286,7 @@ typedef struct uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ -}RCC_PeriphCLKInitTypeDef; +} RCC_PeriphCLKInitTypeDef; #endif /* STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) @@ -307,7 +307,7 @@ typedef struct uint32_t PLLI2SQ; /*!< Specifies the division factor for SAI1 clock. This parameter must be a number between Min_Data = 2 and Max_Data = 15. This parameter will be used only when PLLI2S is selected as Clock Source SAI */ -}RCC_PLLI2SInitTypeDef; +} RCC_PLLI2SInitTypeDef; /** * @brief PLLSAI Clock structure definition @@ -331,7 +331,7 @@ typedef struct This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLSAI is selected as Clock Source LTDC */ -}RCC_PLLSAIInitTypeDef; +} RCC_PLLSAIInitTypeDef; /** * @brief RCC extended clocks structure definition @@ -370,7 +370,7 @@ typedef struct uint32_t SdioClockSelection; /*!< Specifies SDIO Clock Source Selection. This parameter can be a value of @ref RCCEx_SDIO_Clock_Source */ #endif /* STM32F469xx || STM32F479xx */ -}RCC_PeriphCLKInitTypeDef; +} RCC_PeriphCLKInitTypeDef; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ @@ -395,7 +395,7 @@ typedef struct This parameter must be a number between Min_Data = 2 and Max_Data = 7. This parameter will be used only when PLLI2S is selected as Clock Source I2S or SAI */ -}RCC_PLLI2SInitTypeDef; +} RCC_PLLI2SInitTypeDef; /** * @brief RCC extended clocks structure definition @@ -414,7 +414,7 @@ typedef struct uint8_t TIMPresSelection; /*!< Specifies TIM Clock Source Selection. This parameter can be a value of @ref RCCEx_TIM_PRescaler_Selection */ #endif /* STM32F401xC || STM32F401xE || STM32F411xE */ -}RCC_PeriphCLKInitTypeDef; +} RCC_PeriphCLKInitTypeDef; #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F401xC || STM32F401xE || STM32F411xE */ /** * @} @@ -922,7 +922,7 @@ typedef struct defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) || \ - defined(STM32F412Rx) || defined(STM32F413xx) || defined(STM32F423xx) + defined(STM32F412Rx) || defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx) /** @defgroup RCC_MCO2_Clock_Source MCO2 Clock Source * @{ */ @@ -968,124 +968,124 @@ typedef struct * @{ */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOJ_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOJEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOK_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOKEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DMA2D_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_DMA2DEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMACPTP_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) @@ -1183,48 +1183,48 @@ typedef struct * using it. * @{ */ - #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ - UNUSED(tmpreg); \ - } while(0U) +#define __HAL_RCC_DCMI_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #if defined(STM32F437xx)|| defined(STM32F439xx) || defined(STM32F479xx) #define __HAL_RCC_CRYP_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_HASH_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRYP_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_CRYPEN)) #define __HAL_RCC_HASH_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_HASHEN)) #endif /* STM32F437xx || STM32F439xx || STM32F479xx */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ - __HAL_RCC_SYSCFG_CLK_ENABLE();\ + __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0U) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN)) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) /** * @} @@ -1265,21 +1265,21 @@ typedef struct * @{ */ #define __HAL_RCC_FMC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_FMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FMCEN)) #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) #endif /* STM32F469xx || STM32F479xx */ /** @@ -1312,138 +1312,138 @@ typedef struct * @{ */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART7_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART8_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) @@ -1522,68 +1522,68 @@ typedef struct * @{ */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) @@ -1596,23 +1596,23 @@ typedef struct #if defined(STM32F429xx)|| defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_LTDC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_LTDCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_LTDC_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_LTDCEN)) #endif /* STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #if defined(STM32F469xx) || defined(STM32F479xx) #define __HAL_RCC_DSI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ - UNUSED(tmpreg); \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DSIEN);\ + UNUSED(tmpreg); \ } while(0U) #define __HAL_RCC_DSI_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_DSIEN)) @@ -2035,75 +2035,75 @@ typedef struct * @{ */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) @@ -2119,38 +2119,38 @@ typedef struct * @brief Enable ETHERNET clock. */ #define __HAL_RCC_ETHMAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACTXEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACRXEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETHMACPTP_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_ETHMACPTPEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ETH_CLK_ENABLE() do { \ - __HAL_RCC_ETHMAC_CLK_ENABLE(); \ - __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ - __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ - } while(0U) + __HAL_RCC_ETHMAC_CLK_ENABLE(); \ + __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ + __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ + } while(0U) /** * @brief Disable ETHERNET clock. @@ -2160,10 +2160,10 @@ typedef struct #define __HAL_RCC_ETHMACRX_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACRXEN)) #define __HAL_RCC_ETHMACPTP_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_ETHMACPTPEN)) #define __HAL_RCC_ETH_CLK_DISABLE() do { \ - __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ - __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ - __HAL_RCC_ETHMAC_CLK_DISABLE(); \ - } while(0U) + __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ + __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ + __HAL_RCC_ETHMAC_CLK_DISABLE(); \ + } while(0U) #endif /* STM32F407xx || STM32F417xx */ /** * @} @@ -2231,46 +2231,46 @@ typedef struct * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ - __HAL_RCC_SYSCFG_CLK_ENABLE();\ + __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0U) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN)) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) #if defined(STM32F407xx)|| defined(STM32F417xx) #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #endif /* STM32F407xx || STM32F417xx */ #if defined(STM32F415xx) || defined(STM32F417xx) #define __HAL_RCC_CRYP_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_CRYPEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_HASH_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_HASHEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRYP_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_CRYPEN)) #define __HAL_RCC_HASH_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_HASHEN)) #endif /* STM32F415xx || STM32F417xx */ @@ -2316,12 +2316,12 @@ typedef struct * @{ */ #define __HAL_RCC_FSMC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_FSMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FSMCEN)) /** * @} @@ -2348,117 +2348,117 @@ typedef struct * @{ */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) @@ -2519,7 +2519,7 @@ typedef struct #define __HAL_RCC_CAN1_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CAN1EN)) == RESET) #define __HAL_RCC_CAN2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_CAN2EN)) == RESET) #define __HAL_RCC_DAC_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_DACEN)) == RESET) - /** +/** * @} */ @@ -2531,47 +2531,47 @@ typedef struct * @{ */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) @@ -2916,33 +2916,33 @@ typedef struct * @{ */ #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) @@ -2980,7 +2980,7 @@ typedef struct * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ - __HAL_RCC_SYSCFG_CLK_ENABLE();\ + __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0U) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN)) @@ -3009,40 +3009,40 @@ typedef struct * @{ */ #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) @@ -3082,26 +3082,26 @@ typedef struct * @{ */ #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) @@ -3297,19 +3297,19 @@ typedef struct * @{ */ #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRC_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CRCEN)) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_RNGEN)) /** @@ -3337,40 +3337,40 @@ typedef struct * @{ */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_LPTIM1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_RTCAPB_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_RTCAPB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_RTCAPBEN)) @@ -3408,19 +3408,19 @@ typedef struct * @{ */ #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_EXTIT_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI5_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI5EN)) #define __HAL_RCC_EXTIT_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_EXTITEN)) /** @@ -3580,33 +3580,33 @@ typedef struct * @{ */ #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_CCMDATARAMEN_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_CCMDATARAMEN)) @@ -3643,7 +3643,7 @@ typedef struct * @{ */ #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ - __HAL_RCC_SYSCFG_CLK_ENABLE();\ + __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0U) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN)) @@ -3670,42 +3670,42 @@ typedef struct * is disabled and the application software has to enable this clock before * using it. * @{ - */ -#define __HAL_RCC_TIM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - UNUSED(tmpreg); \ - } while(0U) -#define __HAL_RCC_TIM3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - UNUSED(tmpreg); \ - } while(0U) + */ +#define __HAL_RCC_TIM2_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + UNUSED(tmpreg); \ + } while(0U) +#define __HAL_RCC_TIM3_CLK_ENABLE() do { \ + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) @@ -3742,33 +3742,33 @@ typedef struct * @{ */ #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) @@ -3959,68 +3959,68 @@ typedef struct * @{ */ #define __HAL_RCC_BKPSRAM_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_BKPSRAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CCMDATARAMEN_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CCMDATARAMEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_OTGHSULPIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOEEN)) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIOFEN)) @@ -4072,26 +4072,26 @@ typedef struct * @{ */ #define __HAL_RCC_DCMI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_DCMIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DCMI_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_DCMIEN)) #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ - __HAL_RCC_SYSCFG_CLK_ENABLE();\ + __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0U) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN)) #define __HAL_RCC_RNG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) /** * @} @@ -4124,19 +4124,19 @@ typedef struct * @{ */ #define __HAL_RCC_FMC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_FMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FMCEN)) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) @@ -4168,138 +4168,138 @@ typedef struct * @{ */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPDIFRX_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPDIFRXEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CEC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) @@ -4381,61 +4381,61 @@ typedef struct * @{ */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SAI2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SDIOEN)) #define __HAL_RCC_SPI4_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI4EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) @@ -4767,45 +4767,45 @@ typedef struct */ #if defined(STM32F412Rx) || defined(STM32F412Vx) || defined(STM32F412Zx) || defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F412Rx || STM32F412Vx || STM32F412Zx || STM32F413xx || STM32F423xx */ #if defined(STM32F412Vx) || defined(STM32F412Zx) || defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_GPIOE_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOEEN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F412Vx || STM32F412Zx || STM32F413xx || STM32F423xx */ #if defined(STM32F412Zx) || defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_GPIOF_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOFEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOGEN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F412Zx || STM32F413xx || STM32F423xx */ #define __HAL_RCC_CRC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_CRCEN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F412Rx) || defined(STM32F412Vx) || defined(STM32F412Zx) || defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_GPIOD_CLK_DISABLE() (RCC->AHB1ENR &= ~(RCC_AHB1ENR_GPIODEN)) #endif /* STM32F412Rx || STM32F412Vx || STM32F412Zx || STM32F413xx || STM32F423xx */ @@ -4864,27 +4864,27 @@ typedef struct */ #if defined(STM32F423xx) #define __HAL_RCC_AES_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_AESEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_AESEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_AESEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_AESEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_AES_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_AESEN)) #endif /* STM32F423xx */ #define __HAL_RCC_RNG_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_RNG_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_RNGEN)) #define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() do {(RCC->AHB2ENR |= (RCC_AHB2ENR_OTGFSEN));\ - __HAL_RCC_SYSCFG_CLK_ENABLE();\ + __HAL_RCC_SYSCFG_CLK_ENABLE();\ }while(0U) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHB2ENR &= ~(RCC_AHB2ENR_OTGFSEN)) @@ -4922,19 +4922,19 @@ typedef struct */ #if defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_FSMC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_QSPI_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_QSPIEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_FSMC_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_FSMCEN)) #define __HAL_RCC_QSPI_CLK_DISABLE() (RCC->AHB3ENR &= ~(RCC_AHB3ENR_QSPIEN)) @@ -4970,168 +4970,168 @@ typedef struct * @{ */ #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_LPTIM1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_LPTIM1EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_RTCAPB_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_RTCAPBEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_FMPI2C1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_FMPI2C1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_CAN2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_CAN3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN3EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_TIM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_I2C3_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C3EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART7_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART7EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART8_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART8EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) @@ -5242,87 +5242,87 @@ typedef struct * @{ */ #define __HAL_RCC_TIM8_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_UART9_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_UART9EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_UART9EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_UART9EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_UART9EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_UART10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_UART10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_UART10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_UART10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_UART10EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_SDIO_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SDIOEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI4_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI4EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_EXTIT_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_EXTITEN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ + UNUSED(tmpreg); \ + } while(0U) #define __HAL_RCC_SPI5_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI5EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_SAI1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SAI1EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_DFSDM1_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM1EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM1EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM1EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM1EN);\ + UNUSED(tmpreg); \ + } while(0U) #if defined(STM32F413xx) || defined(STM32F423xx) #define __HAL_RCC_DFSDM2_CLK_ENABLE() do { \ - __IO uint32_t tmpreg = 0x00U; \ - SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM2EN);\ - /* Delay after an RCC peripheral clock enabling */ \ - tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM2EN);\ - UNUSED(tmpreg); \ - } while(0U) + __IO uint32_t tmpreg = 0x00U; \ + SET_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM2EN);\ + /* Delay after an RCC peripheral clock enabling */ \ + tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_DFSDM2EN);\ + UNUSED(tmpreg); \ + } while(0U) #endif /* STM32F413xx || STM32F423xx */ #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) @@ -5439,14 +5439,14 @@ typedef struct * @brief Force or release AHB2 peripheral reset. * @{ */ -#define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0x000000C0U) -#define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00U) - #if defined(STM32F423xx) #define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0x000000D0U) #define __HAL_RCC_AES_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_AESRST)) #define __HAL_RCC_AES_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_AESRST)) +#else +#define __HAL_RCC_AHB2_FORCE_RESET() (RCC->AHB2RSTR = 0x000000C0U) #endif /* STM32F423xx */ +#define __HAL_RCC_AHB2_RELEASE_RESET() (RCC->AHB2RSTR = 0x00U) #define __HAL_RCC_USB_OTG_FS_FORCE_RESET() (RCC->AHB2RSTR |= (RCC_AHB2RSTR_OTGFSRST)) #define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() (RCC->AHB2RSTR &= ~(RCC_AHB2RSTR_OTGFSRST)) @@ -5832,11 +5832,11 @@ typedef struct * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__, __PLLM__, __PLLN__, __PLLP__, __PLLQ__,__PLLR__) \ - (RCC->PLLCFGR = ((__RCC_PLLSource__) | (__PLLM__) | \ - ((__PLLN__) << RCC_PLLCFGR_PLLN_Pos) | \ - ((((__PLLP__) >> 1U) -1U) << RCC_PLLCFGR_PLLP_Pos) | \ - ((__PLLQ__) << RCC_PLLCFGR_PLLQ_Pos) | \ - ((__PLLR__) << RCC_PLLCFGR_PLLR_Pos))) + (RCC->PLLCFGR = ((__RCC_PLLSource__) | (__PLLM__) | \ + ((__PLLN__) << RCC_PLLCFGR_PLLN_Pos) | \ + ((((__PLLP__) >> 1U) -1U) << RCC_PLLCFGR_PLLP_Pos) | \ + ((__PLLQ__) << RCC_PLLCFGR_PLLQ_Pos) | \ + ((__PLLR__) << RCC_PLLCFGR_PLLR_Pos))) #else /** @brief Macro to configure the main PLL clock source, multiplication and division factors. * @note This function must be used only when the main PLL is disabled. @@ -5868,11 +5868,11 @@ typedef struct * */ #define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__, __PLLM__, __PLLN__, __PLLP__, __PLLQ__) \ - (RCC->PLLCFGR = (0x20000000U | (__RCC_PLLSource__) | (__PLLM__)| \ - ((__PLLN__) << RCC_PLLCFGR_PLLN_Pos) | \ - ((((__PLLP__) >> 1U) -1U) << RCC_PLLCFGR_PLLP_Pos) | \ - ((__PLLQ__) << RCC_PLLCFGR_PLLQ_Pos))) - #endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx */ + (RCC->PLLCFGR = (0x20000000U | (__RCC_PLLSource__) | (__PLLM__)| \ + ((__PLLN__) << RCC_PLLCFGR_PLLN_Pos) | \ + ((((__PLLP__) >> 1U) -1U) << RCC_PLLCFGR_PLLP_Pos) | \ + ((__PLLQ__) << RCC_PLLCFGR_PLLQ_Pos))) +#endif /* STM32F410xx || STM32F446xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx */ /*----------------------------------------------------------------------------*/ /*----------------------------PLLI2S Configuration ---------------------------*/ @@ -5920,11 +5920,11 @@ typedef struct * This parameter must be a number between Min_Data = 2 and Max_Data = 15. */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SP__, __PLLI2SQ__, __PLLI2SR__) \ - (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ - ((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ - ((((__PLLI2SP__) >> 1U) -1U) << RCC_PLLI2SCFGR_PLLI2SP_Pos) |\ - ((__PLLI2SQ__) << RCC_PLLI2SCFGR_PLLI2SQ_Pos) |\ - ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) + (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ + ((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ + ((((__PLLI2SP__) >> 1U) -1U) << RCC_PLLI2SCFGR_PLLI2SP_Pos) |\ + ((__PLLI2SQ__) << RCC_PLLI2SCFGR_PLLI2SQ_Pos) |\ + ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) #elif defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F412Cx) ||\ defined(STM32F413xx) || defined(STM32F423xx) /** @brief Macro to configure the PLLI2S clock multiplication and division factors . @@ -5951,10 +5951,10 @@ typedef struct * This parameter must be a number between Min_Data = 2 and Max_Data = 15. */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SQ__, __PLLI2SR__) \ - (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ - ((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ - ((__PLLI2SQ__) << RCC_PLLI2SCFGR_PLLI2SQ_Pos) |\ - ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) + (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ + ((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ + ((__PLLI2SQ__) << RCC_PLLI2SCFGR_PLLI2SQ_Pos) |\ + ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) #else /** @brief Macro to configure the PLLI2S clock multiplication and division factors . * @note This macro must be used only when the PLLI2S is disabled. @@ -5972,8 +5972,8 @@ typedef struct * */ #define __HAL_RCC_PLLI2S_CONFIG(__PLLI2SN__, __PLLI2SR__) \ - (RCC->PLLI2SCFGR = (((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ - ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) + (RCC->PLLI2SCFGR = (((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ + ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) #endif /* STM32F446xx */ #if defined(STM32F411xE) @@ -5998,8 +5998,8 @@ typedef struct * on the I2S clock frequency. */ #define __HAL_RCC_PLLI2S_I2SCLK_CONFIG(__PLLI2SM__, __PLLI2SN__, __PLLI2SR__) (RCC->PLLI2SCFGR = ((__PLLI2SM__) |\ - ((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ - ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) + ((__PLLI2SN__) << RCC_PLLI2SCFGR_PLLI2SN_Pos) |\ + ((__PLLI2SR__) << RCC_PLLI2SCFGR_PLLI2SR_Pos))) #endif /* STM32F411xE */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) @@ -6021,8 +6021,8 @@ typedef struct * on the I2S clock frequency. */ #define __HAL_RCC_PLLI2S_SAICLK_CONFIG(__PLLI2SN__, __PLLI2SQ__, __PLLI2SR__) (RCC->PLLI2SCFGR = ((__PLLI2SN__) << 6U) |\ - ((__PLLI2SQ__) << 24U) |\ - ((__PLLI2SR__) << 28U)) + ((__PLLI2SQ__) << 24U) |\ + ((__PLLI2SR__) << 28U)) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*----------------------------------------------------------------------------*/ @@ -6062,10 +6062,10 @@ typedef struct * @note the PLLI2SR parameter is only available with STM32F427/437/429/439xx Devices */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIM__, __PLLSAIN__, __PLLSAIP__, __PLLSAIQ__, __PLLSAIR__) \ - (RCC->PLLSAICFGR = ((__PLLSAIM__) | \ - ((__PLLSAIN__) << RCC_PLLSAICFGR_PLLSAIN_Pos) | \ - ((((__PLLSAIP__) >> 1U) -1U) << RCC_PLLSAICFGR_PLLSAIP_Pos) | \ - ((__PLLSAIQ__) << RCC_PLLSAICFGR_PLLSAIQ_Pos))) + (RCC->PLLSAICFGR = ((__PLLSAIM__) | \ + ((__PLLSAIN__) << RCC_PLLSAICFGR_PLLSAIN_Pos) | \ + ((((__PLLSAIP__) >> 1U) -1U) << RCC_PLLSAICFGR_PLLSAIP_Pos) | \ + ((__PLLSAIQ__) << RCC_PLLSAICFGR_PLLSAIQ_Pos))) #endif /* STM32F446xx */ #if defined(STM32F469xx) || defined(STM32F479xx) @@ -6086,10 +6086,10 @@ typedef struct * This parameter must be a number between Min_Data = 2 and Max_Data = 7. */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIN__, __PLLSAIP__, __PLLSAIQ__, __PLLSAIR__) \ - (RCC->PLLSAICFGR = (((__PLLSAIN__) << RCC_PLLSAICFGR_PLLSAIN_Pos) |\ - ((((__PLLSAIP__) >> 1U) -1U) << RCC_PLLSAICFGR_PLLSAIP_Pos) |\ - ((__PLLSAIQ__) << RCC_PLLSAICFGR_PLLSAIQ_Pos) |\ - ((__PLLSAIR__) << RCC_PLLSAICFGR_PLLSAIR_Pos))) + (RCC->PLLSAICFGR = (((__PLLSAIN__) << RCC_PLLSAICFGR_PLLSAIN_Pos) |\ + ((((__PLLSAIP__) >> 1U) -1U) << RCC_PLLSAICFGR_PLLSAIP_Pos) |\ + ((__PLLSAIQ__) << RCC_PLLSAICFGR_PLLSAIQ_Pos) |\ + ((__PLLSAIR__) << RCC_PLLSAICFGR_PLLSAIR_Pos))) #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) @@ -6108,9 +6108,9 @@ typedef struct * @note the PLLI2SR parameter is only available with STM32F427/437/429/439xx Devices */ #define __HAL_RCC_PLLSAI_CONFIG(__PLLSAIN__, __PLLSAIQ__, __PLLSAIR__) \ - (RCC->PLLSAICFGR = (((__PLLSAIN__) << RCC_PLLSAICFGR_PLLSAIN_Pos) | \ - ((__PLLSAIQ__) << RCC_PLLSAICFGR_PLLSAIQ_Pos) | \ - ((__PLLSAIR__) << RCC_PLLSAICFGR_PLLSAIR_Pos))) + (RCC->PLLSAICFGR = (((__PLLSAIN__) << RCC_PLLSAICFGR_PLLSAIN_Pos) | \ + ((__PLLSAIQ__) << RCC_PLLSAICFGR_PLLSAIQ_Pos) | \ + ((__PLLSAIR__) << RCC_PLLSAICFGR_PLLSAIR_Pos))) #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ @@ -6440,13 +6440,13 @@ typedef struct #if defined(STM32F412Zx) || defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F412Cx) ||\ defined(STM32F413xx) || defined(STM32F423xx) - /** @brief Macro to configure the DFSDM1 clock. +/** @brief Macro to configure the DFSDM1 clock. * @param __DFSDM1_CLKSOURCE__ specifies the DFSDM1 clock source. * This parameter can be one of the following values: * @arg RCC_DFSDM1CLKSOURCE_PCLK2: PCLK2 clock used as kernel clock. * @arg RCC_DFSDM1CLKSOURCE_SYSCLK: System clock used as kernel clock. * @retval None - */ + */ #define __HAL_RCC_DFSDM1_CONFIG(__DFSDM1_CLKSOURCE__) MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_CKDFSDM1SEL, (__DFSDM1_CLKSOURCE__)) /** @brief Macro to get the DFSDM1 clock source. @@ -6476,13 +6476,13 @@ typedef struct #define __HAL_RCC_GET_DFSDM1AUDIO_SOURCE() (READ_BIT(RCC->DCKCFGR, RCC_DCKCFGR_CKDFSDM1ASEL)) #if defined(STM32F413xx) || defined(STM32F423xx) - /** @brief Macro to configure the DFSDM2 clock. +/** @brief Macro to configure the DFSDM2 clock. * @param __DFSDM2_CLKSOURCE__ specifies the DFSDM1 clock source. * This parameter can be one of the following values: * @arg RCC_DFSDM2CLKSOURCE_PCLK2: PCLK2 clock used as kernel clock. * @arg RCC_DFSDM2CLKSOURCE_SYSCLK: System clock used as kernel clock. * @retval None - */ + */ #define __HAL_RCC_DFSDM2_CONFIG(__DFSDM2_CLKSOURCE__) MODIFY_REG(RCC->DCKCFGR, RCC_DCKCFGR_CKDFSDM1SEL, (__DFSDM2_CLKSOURCE__)) /** @brief Macro to get the DFSDM2 clock source. @@ -6896,7 +6896,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLSAI(void); #define RCC_PLLI2SCFGR_OFFSET (RCC_OFFSET + 0x84U) /* Alias word address of PLLI2SSRC bit */ #define RCC_PLLI2SSRC_BIT_NUMBER 0x16U -#define RCC_PLLI2SCFGR_PLLI2SSRC_BB (PERIPH_BB_BASE + (RCC_PLLI2SCFGR_OFFSET * 32U) + (RCC_PLLI2SSRC_BIT_NUMBER * 4U)) +#define RCC_PLLI2SCFGR_PLLI2SSRC_BB (PERIPH_BB_BASE\ + + (RCC_PLLI2SCFGR_OFFSET * 32U) + (RCC_PLLI2SSRC_BIT_NUMBER * 4U)) #define PLLI2S_TIMEOUT_VALUE 2U /* Timeout value fixed to 2 ms */ #endif /* STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx | STM32F423xx */ @@ -7042,10 +7043,10 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLSAI(void); ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLSRC)) - #define IS_RCC_I2SAPB2CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLI2S) ||\ - ((SOURCE) == RCC_I2SAPB2CLKSOURCE_EXT) ||\ - ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLR) ||\ - ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLSRC)) +#define IS_RCC_I2SAPB2CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLI2S) ||\ + ((SOURCE) == RCC_I2SAPB2CLKSOURCE_EXT) ||\ + ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLR) ||\ + ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLSRC)) #define IS_RCC_FMPI2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_FMPI2C1CLKSOURCE_PCLK1) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_SYSCLK) ||\ @@ -7099,10 +7100,10 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLSAI(void); ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLR) ||\ ((SOURCE) == RCC_I2SAPB1CLKSOURCE_PLLSRC)) - #define IS_RCC_I2SAPB2CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLI2S) ||\ - ((SOURCE) == RCC_I2SAPB2CLKSOURCE_EXT) ||\ - ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLR) ||\ - ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLSRC)) +#define IS_RCC_I2SAPB2CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLI2S) ||\ + ((SOURCE) == RCC_I2SAPB2CLKSOURCE_EXT) ||\ + ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLR) ||\ + ((SOURCE) == RCC_I2SAPB2CLKSOURCE_PLLSRC)) #define IS_RCC_FMPI2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_FMPI2C1CLKSOURCE_PCLK1) ||\ ((SOURCE) == RCC_FMPI2C1CLKSOURCE_SYSCLK) ||\ @@ -7153,7 +7154,7 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLSAI(void); defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || \ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) || defined(STM32F446xx) || \ defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) || \ - defined(STM32F412Rx) || defined(STM32F413xx) || defined(STM32F423xx) + defined(STM32F412Rx) || defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx) #define IS_RCC_MCO2SOURCE(SOURCE) (((SOURCE) == RCC_MCO2SOURCE_SYSCLK) || ((SOURCE) == RCC_MCO2SOURCE_PLLI2SCLK)|| \ ((SOURCE) == RCC_MCO2SOURCE_HSE) || ((SOURCE) == RCC_MCO2SOURCE_PLLCLK)) diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_spi.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_spi.h index d7997a317..856314948 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_spi.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_hal_spi.h @@ -107,7 +107,7 @@ typedef struct __SPI_HandleTypeDef SPI_InitTypeDef Init; /*!< SPI communication parameters */ - uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ + const uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ uint16_t TxXferSize; /*!< SPI Tx Transfer size */ @@ -667,17 +667,17 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @{ */ /* I/O operation functions ***************************************************/ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, - uint32_t Timeout); -HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); @@ -703,8 +703,8 @@ void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi); * @{ */ /* Peripheral State and Error functions ***************************************/ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi); +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi); /** * @} */ diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_adc.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_adc.h index 43b4a1ed5..13f6751b2 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_adc.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_adc.h @@ -1859,7 +1859,7 @@ typedef struct * @retval ADC register address */ #if defined(ADC_MULTIMODE_SUPPORT) -__STATIC_INLINE uint32_t LL_ADC_DMA_GetRegAddr(ADC_TypeDef *ADCx, uint32_t Register) +__STATIC_INLINE uint32_t LL_ADC_DMA_GetRegAddr(const ADC_TypeDef *ADCx, uint32_t Register) { uint32_t data_reg_addr = 0UL; @@ -1923,7 +1923,7 @@ __STATIC_INLINE void LL_ADC_SetCommonClock(ADC_Common_TypeDef *ADCxy_COMMON, uin * @arg @ref LL_ADC_CLOCK_SYNC_PCLK_DIV6 * @arg @ref LL_ADC_CLOCK_SYNC_PCLK_DIV8 */ -__STATIC_INLINE uint32_t LL_ADC_GetCommonClock(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_GetCommonClock(const ADC_Common_TypeDef *ADCxy_COMMON) { return (uint32_t)(READ_BIT(ADCxy_COMMON->CCR, ADC_CCR_ADCPRE)); } @@ -1977,7 +1977,7 @@ __STATIC_INLINE void LL_ADC_SetCommonPathInternalCh(ADC_Common_TypeDef *ADCxy_CO * @arg @ref LL_ADC_PATH_INTERNAL_TEMPSENSOR * @arg @ref LL_ADC_PATH_INTERNAL_VBAT */ -__STATIC_INLINE uint32_t LL_ADC_GetCommonPathInternalCh(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_GetCommonPathInternalCh(const ADC_Common_TypeDef *ADCxy_COMMON) { return (uint32_t)(READ_BIT(ADCxy_COMMON->CCR, ADC_CCR_TSVREFE | ADC_CCR_VBATE)); } @@ -2020,7 +2020,7 @@ __STATIC_INLINE void LL_ADC_SetResolution(ADC_TypeDef *ADCx, uint32_t Resolution * @arg @ref LL_ADC_RESOLUTION_8B * @arg @ref LL_ADC_RESOLUTION_6B */ -__STATIC_INLINE uint32_t LL_ADC_GetResolution(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_GetResolution(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_RES)); } @@ -2051,7 +2051,7 @@ __STATIC_INLINE void LL_ADC_SetDataAlignment(ADC_TypeDef *ADCx, uint32_t DataAli * @arg @ref LL_ADC_DATA_ALIGN_RIGHT * @arg @ref LL_ADC_DATA_ALIGN_LEFT */ -__STATIC_INLINE uint32_t LL_ADC_GetDataAlignment(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_GetDataAlignment(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_ALIGN)); } @@ -2102,7 +2102,7 @@ __STATIC_INLINE void LL_ADC_SetSequencersScanMode(ADC_TypeDef *ADCx, uint32_t Sc * @arg @ref LL_ADC_SEQ_SCAN_DISABLE * @arg @ref LL_ADC_SEQ_SCAN_ENABLE */ -__STATIC_INLINE uint32_t LL_ADC_GetSequencersScanMode(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_GetSequencersScanMode(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_SCAN)); } @@ -2190,7 +2190,7 @@ __STATIC_INLINE void LL_ADC_REG_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t Tri * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO * @arg @ref LL_ADC_REG_TRIG_EXT_EXTI_LINE11 */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerSource(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerSource(const ADC_TypeDef *ADCx) { uint32_t TriggerSource = READ_BIT(ADCx->CR2, ADC_CR2_EXTSEL | ADC_CR2_EXTEN); @@ -2217,7 +2217,7 @@ __STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerSource(ADC_TypeDef *ADCx) * @retval Value "0" if trigger source external trigger * Value "1" if trigger source SW start. */ -__STATIC_INLINE uint32_t LL_ADC_REG_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_IsTriggerSourceSWStart(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->CR2, ADC_CR2_EXTEN) == (LL_ADC_REG_TRIG_SOFTWARE & ADC_CR2_EXTEN)); } @@ -2234,7 +2234,7 @@ __STATIC_INLINE uint32_t LL_ADC_REG_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) * @arg @ref LL_ADC_REG_TRIG_EXT_FALLING * @arg @ref LL_ADC_REG_TRIG_EXT_RISINGFALLING */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerEdge(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerEdge(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_EXTEN)); } @@ -2356,7 +2356,7 @@ __STATIC_INLINE void LL_ADC_REG_SetSequencerLength(ADC_TypeDef *ADCx, uint32_t S * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerLength(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerLength(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->SQR1, ADC_SQR1_L)); } @@ -2407,7 +2407,7 @@ __STATIC_INLINE void LL_ADC_REG_SetSequencerDiscont(ADC_TypeDef *ADCx, uint32_t * @arg @ref LL_ADC_REG_SEQ_DISCONT_7RANKS * @arg @ref LL_ADC_REG_SEQ_DISCONT_8RANKS */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerDiscont(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerDiscont(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_DISCEN | ADC_CR1_DISCNUM)); } @@ -2587,9 +2587,9 @@ __STATIC_INLINE void LL_ADC_REG_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Ra * comparison with internal channel parameter to be done * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerRanks(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SQR1, __ADC_MASK_SHIFT(Rank, ADC_REG_SQRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->SQR1, __ADC_MASK_SHIFT(Rank, ADC_REG_SQRX_REGOFFSET_MASK)); return (uint32_t)(READ_BIT(*preg, ADC_CHANNEL_ID_NUMBER_MASK << (Rank & ADC_REG_RANK_ID_SQRX_MASK)) @@ -2629,7 +2629,7 @@ __STATIC_INLINE void LL_ADC_REG_SetContinuousMode(ADC_TypeDef *ADCx, uint32_t Co * @arg @ref LL_ADC_REG_CONV_SINGLE * @arg @ref LL_ADC_REG_CONV_CONTINUOUS */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetContinuousMode(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetContinuousMode(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_CONT)); } @@ -2700,7 +2700,7 @@ __STATIC_INLINE void LL_ADC_REG_SetDMATransfer(ADC_TypeDef *ADCx, uint32_t DMATr * @arg @ref LL_ADC_REG_DMA_TRANSFER_LIMITED * @arg @ref LL_ADC_REG_DMA_TRANSFER_UNLIMITED */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetDMATransfer(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetDMATransfer(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_DMA | ADC_CR2_DDS)); } @@ -2737,7 +2737,7 @@ __STATIC_INLINE void LL_ADC_REG_SetFlagEndOfConversion(ADC_TypeDef *ADCx, uint32 * @arg @ref LL_ADC_REG_FLAG_EOC_SEQUENCE_CONV * @arg @ref LL_ADC_REG_FLAG_EOC_UNITARY_CONV */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetFlagEndOfConversion(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_GetFlagEndOfConversion(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_EOCS)); } @@ -2825,7 +2825,7 @@ __STATIC_INLINE void LL_ADC_INJ_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t Tri * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4 * @arg @ref LL_ADC_INJ_TRIG_EXT_EXTI_LINE15 */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetTriggerSource(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetTriggerSource(const ADC_TypeDef *ADCx) { uint32_t TriggerSource = READ_BIT(ADCx->CR2, ADC_CR2_JEXTSEL | ADC_CR2_JEXTEN); @@ -2852,7 +2852,7 @@ __STATIC_INLINE uint32_t LL_ADC_INJ_GetTriggerSource(ADC_TypeDef *ADCx) * @retval Value "0" if trigger source external trigger * Value "1" if trigger source SW start. */ -__STATIC_INLINE uint32_t LL_ADC_INJ_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_INJ_IsTriggerSourceSWStart(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->CR2, ADC_CR2_JEXTEN) == (LL_ADC_INJ_TRIG_SOFTWARE & ADC_CR2_JEXTEN)); } @@ -2867,7 +2867,7 @@ __STATIC_INLINE uint32_t LL_ADC_INJ_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) * @arg @ref LL_ADC_INJ_TRIG_EXT_FALLING * @arg @ref LL_ADC_INJ_TRIG_EXT_RISINGFALLING */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetTriggerEdge(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetTriggerEdge(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_JEXTEN)); } @@ -2922,7 +2922,7 @@ __STATIC_INLINE void LL_ADC_INJ_SetSequencerLength(ADC_TypeDef *ADCx, uint32_t S * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerLength(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerLength(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->JSQR, ADC_JSQR_JL)); } @@ -2955,7 +2955,7 @@ __STATIC_INLINE void LL_ADC_INJ_SetSequencerDiscont(ADC_TypeDef *ADCx, uint32_t * @arg @ref LL_ADC_INJ_SEQ_DISCONT_DISABLE * @arg @ref LL_ADC_INJ_SEQ_DISCONT_1RANK */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerDiscont(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerDiscont(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_JDISCEN)); } @@ -3076,7 +3076,7 @@ __STATIC_INLINE void LL_ADC_INJ_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Ra * comparison with internal channel parameter to be done * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerRanks(const ADC_TypeDef *ADCx, uint32_t Rank) { uint32_t tmpreg1 = (READ_BIT(ADCx->JSQR, ADC_JSQR_JL) >> ADC_JSQR_JL_Pos) + 1UL; @@ -3126,7 +3126,7 @@ __STATIC_INLINE void LL_ADC_INJ_SetTrigAuto(ADC_TypeDef *ADCx, uint32_t TrigAuto * @arg @ref LL_ADC_INJ_TRIG_INDEPENDENT * @arg @ref LL_ADC_INJ_TRIG_FROM_GRP_REGULAR */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetTrigAuto(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetTrigAuto(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_JAUTO)); } @@ -3183,9 +3183,9 @@ __STATIC_INLINE void LL_ADC_INJ_SetOffset(ADC_TypeDef *ADCx, uint32_t Rank, uint * @arg @ref LL_ADC_INJ_RANK_4 * @retval Value between Min_Data=0x000 and Max_Data=0xFFF */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetOffset(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint32_t LL_ADC_INJ_GetOffset(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JOFR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JOFRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->JOFR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JOFRX_REGOFFSET_MASK)); return (uint32_t)(READ_BIT(*preg, ADC_JOFR1_JOFFSET1) @@ -3353,9 +3353,9 @@ __STATIC_INLINE void LL_ADC_SetChannelSamplingTime(ADC_TypeDef *ADCx, uint32_t C * @arg @ref LL_ADC_SAMPLINGTIME_144CYCLES * @arg @ref LL_ADC_SAMPLINGTIME_480CYCLES */ -__STATIC_INLINE uint32_t LL_ADC_GetChannelSamplingTime(ADC_TypeDef *ADCx, uint32_t Channel) +__STATIC_INLINE uint32_t LL_ADC_GetChannelSamplingTime(const ADC_TypeDef *ADCx, uint32_t Channel) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SMPR1, __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->SMPR1, __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPRX_REGOFFSET_MASK)); return (uint32_t)(READ_BIT(*preg, ADC_SMPR2_SMP0 << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK)) @@ -3563,7 +3563,7 @@ __STATIC_INLINE void LL_ADC_SetAnalogWDMonitChannels(ADC_TypeDef *ADCx, uint32_t * @arg @ref LL_ADC_AWD_CHANNEL_18_INJ * @arg @ref LL_ADC_AWD_CHANNEL_18_REG_INJ */ -__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDMonitChannels(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDMonitChannels(const ADC_TypeDef *ADCx) { return (uint32_t)(READ_BIT(ADCx->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL | ADC_CR1_AWDCH))); } @@ -3613,9 +3613,9 @@ __STATIC_INLINE void LL_ADC_SetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AW * @arg @ref LL_ADC_AWD_THRESHOLD_LOW * @retval Value between Min_Data=0x000 and Max_Data=0xFFF */ -__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AWDThresholdsHighLow) +__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDThresholds(const ADC_TypeDef *ADCx, uint32_t AWDThresholdsHighLow) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->HTR, AWDThresholdsHighLow); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->HTR, AWDThresholdsHighLow); return (uint32_t)(READ_BIT(*preg, ADC_HTR_HT)); } @@ -3685,7 +3685,7 @@ __STATIC_INLINE void LL_ADC_SetMultimode(ADC_Common_TypeDef *ADCxy_COMMON, uint3 * @arg @ref LL_ADC_MULTI_TRIPLE_REG_INTERL * @arg @ref LL_ADC_MULTI_TRIPLE_INJ_ALTERN */ -__STATIC_INLINE uint32_t LL_ADC_GetMultimode(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_GetMultimode(const ADC_Common_TypeDef *ADCxy_COMMON) { return (uint32_t)(READ_BIT(ADCxy_COMMON->CCR, ADC_CCR_MULTI)); } @@ -3782,7 +3782,7 @@ __STATIC_INLINE void LL_ADC_SetMultiDMATransfer(ADC_Common_TypeDef *ADCxy_COMMON * @arg @ref LL_ADC_MULTI_REG_DMA_UNLMT_2 * @arg @ref LL_ADC_MULTI_REG_DMA_UNLMT_3 */ -__STATIC_INLINE uint32_t LL_ADC_GetMultiDMATransfer(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_GetMultiDMATransfer(const ADC_Common_TypeDef *ADCxy_COMMON) { return (uint32_t)(READ_BIT(ADCxy_COMMON->CCR, ADC_CCR_DMA | ADC_CCR_DDS)); } @@ -3844,7 +3844,7 @@ __STATIC_INLINE void LL_ADC_SetMultiTwoSamplingDelay(ADC_Common_TypeDef *ADCxy_C * @arg @ref LL_ADC_MULTI_TWOSMP_DELAY_19CYCLES * @arg @ref LL_ADC_MULTI_TWOSMP_DELAY_20CYCLES */ -__STATIC_INLINE uint32_t LL_ADC_GetMultiTwoSamplingDelay(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_GetMultiTwoSamplingDelay(const ADC_Common_TypeDef *ADCxy_COMMON) { return (uint32_t)(READ_BIT(ADCxy_COMMON->CCR, ADC_CCR_DELAY)); } @@ -3889,7 +3889,7 @@ __STATIC_INLINE void LL_ADC_Disable(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval 0: ADC is disabled, 1: ADC is enabled. */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabled(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsEnabled(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->CR2, ADC_CR2_ADON) == (ADC_CR2_ADON)); } @@ -3971,7 +3971,7 @@ __STATIC_INLINE void LL_ADC_REG_StopConversionExtTrig(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF */ -__STATIC_INLINE uint32_t LL_ADC_REG_ReadConversionData32(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_REG_ReadConversionData32(const ADC_TypeDef *ADCx) { return (uint16_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); } @@ -3986,7 +3986,7 @@ __STATIC_INLINE uint32_t LL_ADC_REG_ReadConversionData32(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval Value between Min_Data=0x000 and Max_Data=0xFFF */ -__STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData12(ADC_TypeDef *ADCx) +__STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData12(const ADC_TypeDef *ADCx) { return (uint16_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); } @@ -4001,7 +4001,7 @@ __STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData12(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval Value between Min_Data=0x000 and Max_Data=0x3FF */ -__STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData10(ADC_TypeDef *ADCx) +__STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData10(const ADC_TypeDef *ADCx) { return (uint16_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); } @@ -4016,7 +4016,7 @@ __STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData10(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval Value between Min_Data=0x00 and Max_Data=0xFF */ -__STATIC_INLINE uint8_t LL_ADC_REG_ReadConversionData8(ADC_TypeDef *ADCx) +__STATIC_INLINE uint8_t LL_ADC_REG_ReadConversionData8(const ADC_TypeDef *ADCx) { return (uint8_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); } @@ -4031,7 +4031,7 @@ __STATIC_INLINE uint8_t LL_ADC_REG_ReadConversionData8(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval Value between Min_Data=0x00 and Max_Data=0x3F */ -__STATIC_INLINE uint8_t LL_ADC_REG_ReadConversionData6(ADC_TypeDef *ADCx) +__STATIC_INLINE uint8_t LL_ADC_REG_ReadConversionData6(const ADC_TypeDef *ADCx) { return (uint8_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); } @@ -4058,7 +4058,7 @@ __STATIC_INLINE uint8_t LL_ADC_REG_ReadConversionData6(ADC_TypeDef *ADCx) * @arg @ref LL_ADC_MULTI_MASTER_SLAVE * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF */ -__STATIC_INLINE uint32_t LL_ADC_REG_ReadMultiConversionData32(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t ConversionData) +__STATIC_INLINE uint32_t LL_ADC_REG_ReadMultiConversionData32(const ADC_Common_TypeDef *ADCxy_COMMON, uint32_t ConversionData) { return (uint32_t)(READ_BIT(ADCxy_COMMON->CDR, ADC_DR_ADC2DATA) @@ -4152,9 +4152,9 @@ __STATIC_INLINE void LL_ADC_INJ_StopConversionExtTrig(ADC_TypeDef *ADCx) * @arg @ref LL_ADC_INJ_RANK_4 * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF */ -__STATIC_INLINE uint32_t LL_ADC_INJ_ReadConversionData32(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint32_t LL_ADC_INJ_ReadConversionData32(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); return (uint32_t)(READ_BIT(*preg, ADC_JDR1_JDATA) @@ -4179,9 +4179,9 @@ __STATIC_INLINE uint32_t LL_ADC_INJ_ReadConversionData32(ADC_TypeDef *ADCx, uint * @arg @ref LL_ADC_INJ_RANK_4 * @retval Value between Min_Data=0x000 and Max_Data=0xFFF */ -__STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData12(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData12(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); return (uint16_t)(READ_BIT(*preg, ADC_JDR1_JDATA) @@ -4206,9 +4206,9 @@ __STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData12(ADC_TypeDef *ADCx, uint * @arg @ref LL_ADC_INJ_RANK_4 * @retval Value between Min_Data=0x000 and Max_Data=0x3FF */ -__STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData10(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData10(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); return (uint16_t)(READ_BIT(*preg, ADC_JDR1_JDATA) @@ -4233,9 +4233,9 @@ __STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData10(ADC_TypeDef *ADCx, uint * @arg @ref LL_ADC_INJ_RANK_4 * @retval Value between Min_Data=0x00 and Max_Data=0xFF */ -__STATIC_INLINE uint8_t LL_ADC_INJ_ReadConversionData8(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint8_t LL_ADC_INJ_ReadConversionData8(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); return (uint8_t)(READ_BIT(*preg, ADC_JDR1_JDATA) @@ -4260,9 +4260,9 @@ __STATIC_INLINE uint8_t LL_ADC_INJ_ReadConversionData8(ADC_TypeDef *ADCx, uint32 * @arg @ref LL_ADC_INJ_RANK_4 * @retval Value between Min_Data=0x00 and Max_Data=0x3F */ -__STATIC_INLINE uint8_t LL_ADC_INJ_ReadConversionData6(ADC_TypeDef *ADCx, uint32_t Rank) +__STATIC_INLINE uint8_t LL_ADC_INJ_ReadConversionData6(const ADC_TypeDef *ADCx, uint32_t Rank) { - __IO uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); + __IO uint32_t const *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); return (uint8_t)(READ_BIT(*preg, ADC_JDR1_JDATA) @@ -4287,7 +4287,7 @@ __STATIC_INLINE uint8_t LL_ADC_INJ_ReadConversionData6(ADC_TypeDef *ADCx, uint32 * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_EOCS(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_EOCS(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->SR, LL_ADC_FLAG_EOCS) == (LL_ADC_FLAG_EOCS)); } @@ -4298,7 +4298,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_EOCS(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_OVR(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_OVR(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->SR, LL_ADC_FLAG_OVR) == (LL_ADC_FLAG_OVR)); } @@ -4310,7 +4310,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_OVR(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_JEOS(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_JEOS(const ADC_TypeDef *ADCx) { /* Note: on this STM32 series, there is no flag ADC group injected */ /* end of unitary conversion. */ @@ -4325,7 +4325,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_JEOS(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_AWD1(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_AWD1(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->SR, LL_ADC_FLAG_AWD1) == (LL_ADC_FLAG_AWD1)); } @@ -4395,7 +4395,7 @@ __STATIC_INLINE void LL_ADC_ClearFlag_AWD1(ADC_TypeDef *ADCx) * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_EOCS(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_EOCS(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_EOCS_MST) == (LL_ADC_FLAG_EOCS_MST)); } @@ -4411,7 +4411,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_EOCS(ADC_Common_TypeDef *ADCxy_ * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_EOCS(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_EOCS(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_EOCS_SLV1) == (LL_ADC_FLAG_EOCS_SLV1)); } @@ -4427,7 +4427,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_EOCS(ADC_Common_TypeDef *ADCxy * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_EOCS(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_EOCS(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_EOCS_SLV2) == (LL_ADC_FLAG_EOCS_SLV2)); } @@ -4438,7 +4438,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_EOCS(ADC_Common_TypeDef *ADCxy * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_OVR(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_OVR(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_OVR_MST) == (LL_ADC_FLAG_OVR_MST)); } @@ -4450,7 +4450,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_OVR(ADC_Common_TypeDef *ADCxy_C * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_OVR(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_OVR(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_OVR_SLV1) == (LL_ADC_FLAG_OVR_SLV1)); } @@ -4462,7 +4462,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_OVR(ADC_Common_TypeDef *ADCxy_ * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_OVR(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_OVR(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_OVR_SLV2) == (LL_ADC_FLAG_OVR_SLV2)); } @@ -4475,7 +4475,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_OVR(ADC_Common_TypeDef *ADCxy_ * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_JEOS(const ADC_Common_TypeDef *ADCxy_COMMON) { /* Note: on this STM32 series, there is no flag ADC group injected */ /* end of unitary conversion. */ @@ -4491,7 +4491,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_JEOS(ADC_Common_TypeDef *ADCxy_ * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_JEOS(const ADC_Common_TypeDef *ADCxy_COMMON) { /* Note: on this STM32 series, there is no flag ADC group injected */ /* end of unitary conversion. */ @@ -4507,7 +4507,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_JEOS(ADC_Common_TypeDef *ADCxy * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_JEOS(const ADC_Common_TypeDef *ADCxy_COMMON) { /* Note: on this STM32 series, there is no flag ADC group injected */ /* end of unitary conversion. */ @@ -4523,7 +4523,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_JEOS(ADC_Common_TypeDef *ADCxy * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_AWD1(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_AWD1_MST) == (LL_ADC_FLAG_AWD1_MST)); } @@ -4535,7 +4535,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_AWD1(ADC_Common_TypeDef *ADCxy_ * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_AWD1(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_AWD1_SLV1) == (LL_ADC_FLAG_AWD1_SLV1)); } @@ -4547,7 +4547,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV1_AWD1(ADC_Common_TypeDef *ADCxy * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) +__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV2_AWD1(const ADC_Common_TypeDef *ADCxy_COMMON) { return (READ_BIT(ADCxy_COMMON->CSR, LL_ADC_FLAG_AWD1_SLV2) == (LL_ADC_FLAG_AWD1_SLV2)); } @@ -4679,7 +4679,7 @@ __STATIC_INLINE void LL_ADC_DisableIT_AWD1(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_EOCS(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_EOCS(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->CR1, LL_ADC_IT_EOCS) == (LL_ADC_IT_EOCS)); } @@ -4691,7 +4691,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_EOCS(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_OVR(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_OVR(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->CR1, LL_ADC_IT_OVR) == (LL_ADC_IT_OVR)); } @@ -4704,7 +4704,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_OVR(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_JEOS(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_JEOS(const ADC_TypeDef *ADCx) { /* Note: on this STM32 series, there is no flag ADC group injected */ /* end of unitary conversion. */ @@ -4720,7 +4720,7 @@ __STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_JEOS(ADC_TypeDef *ADCx) * @param ADCx ADC instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_AWD1(ADC_TypeDef *ADCx) +__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_AWD1(const ADC_TypeDef *ADCx) { return (READ_BIT(ADCx->CR1, LL_ADC_IT_AWD1) == (LL_ADC_IT_AWD1)); } diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_bus.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_bus.h index 5083c10dc..ce19d4d96 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_bus.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_bus.h @@ -405,7 +405,7 @@ extern "C" { * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB1_GRP1_EnableClock(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -469,7 +469,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_EnableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval State of Periphs (1 or 0). -*/ + */ __STATIC_INLINE uint32_t LL_AHB1_GRP1_IsEnabledClock(uint32_t Periphs) { return (READ_BIT(RCC->AHB1ENR, Periphs) == Periphs); @@ -529,7 +529,7 @@ __STATIC_INLINE uint32_t LL_AHB1_GRP1_IsEnabledClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB1_GRP1_DisableClock(uint32_t Periphs) { CLEAR_BIT(RCC->AHB1ENR, Periphs); @@ -578,7 +578,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_DisableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB1_GRP1_ForceReset(uint32_t Periphs) { SET_BIT(RCC->AHB1RSTR, Periphs); @@ -627,7 +627,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_ForceReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB1_GRP1_ReleaseReset(uint32_t Periphs) { CLEAR_BIT(RCC->AHB1RSTR, Periphs); @@ -694,7 +694,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_ReleaseReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB1_GRP1_EnableClockLowPower(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -765,7 +765,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_EnableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB1_GRP1_DisableClockLowPower(uint32_t Periphs) { CLEAR_BIT(RCC->AHB1LPENR, Periphs); @@ -798,7 +798,7 @@ __STATIC_INLINE void LL_AHB1_GRP1_DisableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB2_GRP1_EnableClock(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -826,7 +826,7 @@ __STATIC_INLINE void LL_AHB2_GRP1_EnableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval State of Periphs (1 or 0). -*/ + */ __STATIC_INLINE uint32_t LL_AHB2_GRP1_IsEnabledClock(uint32_t Periphs) { return (READ_BIT(RCC->AHB2ENR, Periphs) == Periphs); @@ -850,7 +850,7 @@ __STATIC_INLINE uint32_t LL_AHB2_GRP1_IsEnabledClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB2_GRP1_DisableClock(uint32_t Periphs) { CLEAR_BIT(RCC->AHB2ENR, Periphs); @@ -875,7 +875,7 @@ __STATIC_INLINE void LL_AHB2_GRP1_DisableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB2_GRP1_ForceReset(uint32_t Periphs) { SET_BIT(RCC->AHB2RSTR, Periphs); @@ -900,7 +900,7 @@ __STATIC_INLINE void LL_AHB2_GRP1_ForceReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB2_GRP1_ReleaseReset(uint32_t Periphs) { CLEAR_BIT(RCC->AHB2RSTR, Periphs); @@ -924,7 +924,7 @@ __STATIC_INLINE void LL_AHB2_GRP1_ReleaseReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB2_GRP1_EnableClockLowPower(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -952,7 +952,7 @@ __STATIC_INLINE void LL_AHB2_GRP1_EnableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB2_GRP1_DisableClockLowPower(uint32_t Periphs) { CLEAR_BIT(RCC->AHB2LPENR, Periphs); @@ -980,7 +980,7 @@ __STATIC_INLINE void LL_AHB2_GRP1_DisableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB3_GRP1_EnableClock(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -1002,7 +1002,7 @@ __STATIC_INLINE void LL_AHB3_GRP1_EnableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval State of Periphs (1 or 0). -*/ + */ __STATIC_INLINE uint32_t LL_AHB3_GRP1_IsEnabledClock(uint32_t Periphs) { return (READ_BIT(RCC->AHB3ENR, Periphs) == Periphs); @@ -1020,7 +1020,7 @@ __STATIC_INLINE uint32_t LL_AHB3_GRP1_IsEnabledClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB3_GRP1_DisableClock(uint32_t Periphs) { CLEAR_BIT(RCC->AHB3ENR, Periphs); @@ -1039,7 +1039,7 @@ __STATIC_INLINE void LL_AHB3_GRP1_DisableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB3_GRP1_ForceReset(uint32_t Periphs) { SET_BIT(RCC->AHB3RSTR, Periphs); @@ -1058,7 +1058,7 @@ __STATIC_INLINE void LL_AHB3_GRP1_ForceReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB3_GRP1_ReleaseReset(uint32_t Periphs) { CLEAR_BIT(RCC->AHB3RSTR, Periphs); @@ -1076,7 +1076,7 @@ __STATIC_INLINE void LL_AHB3_GRP1_ReleaseReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB3_GRP1_EnableClockLowPower(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -1098,7 +1098,7 @@ __STATIC_INLINE void LL_AHB3_GRP1_EnableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_AHB3_GRP1_DisableClockLowPower(uint32_t Periphs) { CLEAR_BIT(RCC->AHB3LPENR, Periphs); @@ -1181,7 +1181,7 @@ __STATIC_INLINE void LL_AHB3_GRP1_DisableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB1_GRP1_EnableClock(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -1259,7 +1259,7 @@ __STATIC_INLINE void LL_APB1_GRP1_EnableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval State of Periphs (1 or 0). -*/ + */ __STATIC_INLINE uint32_t LL_APB1_GRP1_IsEnabledClock(uint32_t Periphs) { return (READ_BIT(RCC->APB1ENR, Periphs) == Periphs); @@ -1333,7 +1333,7 @@ __STATIC_INLINE uint32_t LL_APB1_GRP1_IsEnabledClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB1_GRP1_DisableClock(uint32_t Periphs) { CLEAR_BIT(RCC->APB1ENR, Periphs); @@ -1405,7 +1405,7 @@ __STATIC_INLINE void LL_APB1_GRP1_DisableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB1_GRP1_ForceReset(uint32_t Periphs) { SET_BIT(RCC->APB1RSTR, Periphs); @@ -1477,7 +1477,7 @@ __STATIC_INLINE void LL_APB1_GRP1_ForceReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB1_GRP1_ReleaseReset(uint32_t Periphs) { CLEAR_BIT(RCC->APB1RSTR, Periphs); @@ -1551,7 +1551,7 @@ __STATIC_INLINE void LL_APB1_GRP1_ReleaseReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB1_GRP1_EnableClockLowPower(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -1629,7 +1629,7 @@ __STATIC_INLINE void LL_APB1_GRP1_EnableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB1_GRP1_DisableClockLowPower(uint32_t Periphs) { CLEAR_BIT(RCC->APB1LPENR, Periphs); @@ -1700,7 +1700,7 @@ __STATIC_INLINE void LL_APB1_GRP1_DisableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB2_GRP1_EnableClock(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -1766,7 +1766,7 @@ __STATIC_INLINE void LL_APB2_GRP1_EnableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval State of Periphs (1 or 0). -*/ + */ __STATIC_INLINE uint32_t LL_APB2_GRP1_IsEnabledClock(uint32_t Periphs) { return (READ_BIT(RCC->APB2ENR, Periphs) == Periphs); @@ -1828,7 +1828,7 @@ __STATIC_INLINE uint32_t LL_APB2_GRP1_IsEnabledClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB2_GRP1_DisableClock(uint32_t Periphs) { CLEAR_BIT(RCC->APB2ENR, Periphs); @@ -1885,7 +1885,7 @@ __STATIC_INLINE void LL_APB2_GRP1_DisableClock(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB2_GRP1_ForceReset(uint32_t Periphs) { SET_BIT(RCC->APB2RSTR, Periphs); @@ -1943,7 +1943,7 @@ __STATIC_INLINE void LL_APB2_GRP1_ForceReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB2_GRP1_ReleaseReset(uint32_t Periphs) { CLEAR_BIT(RCC->APB2RSTR, Periphs); @@ -2006,7 +2006,7 @@ __STATIC_INLINE void LL_APB2_GRP1_ReleaseReset(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB2_GRP1_EnableClockLowPower(uint32_t Periphs) { __IO uint32_t tmpreg; @@ -2073,7 +2073,7 @@ __STATIC_INLINE void LL_APB2_GRP1_EnableClockLowPower(uint32_t Periphs) * * (*) value not defined in all devices. * @retval None -*/ + */ __STATIC_INLINE void LL_APB2_GRP1_DisableClockLowPower(uint32_t Periphs) { CLEAR_BIT(RCC->APB2LPENR, Periphs); diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_cortex.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_cortex.h index 3861f55ff..9a183ea75 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_cortex.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_cortex.h @@ -596,7 +596,7 @@ __STATIC_INLINE void LL_MPU_ConfigRegion(uint32_t Region, uint32_t SubRegionDisa /* Set base address */ WRITE_REG(MPU->RBAR, (Address & 0xFFFFFFE0U)); /* Configure MPU */ - WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | SubRegionDisable << MPU_RASR_SRD_Pos)); + WRITE_REG(MPU->RASR, (MPU_RASR_ENABLE_Msk | Attributes | (SubRegionDisable << MPU_RASR_SRD_Pos))); } /** diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_dma.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_dma.h index 5169d3b81..53e88138a 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_dma.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_dma.h @@ -1171,7 +1171,7 @@ __STATIC_INLINE void LL_DMA_SetCurrentTargetMem(DMA_TypeDef *DMAx, uint32_t Stre } /** - * @brief Set Current target (only in double buffer mode) to Memory 1 or Memory 0. + * @brief Get Current target (only in double buffer mode). * @rmtoll CR CT LL_DMA_GetCurrentTargetMem * @param DMAx DMAx Instance * @param Stream This parameter can be one of the following values: diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_rcc.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_rcc.h index 59a4dbac9..796f06d86 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_rcc.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_rcc.h @@ -622,7 +622,7 @@ typedef struct #define LL_RCC_SDIO_CLKSOURCE RCC_DCKCFGR2_SDIOSEL /*!< SDIO Clock source selection */ #else #define LL_RCC_SDIO_CLKSOURCE RCC_PLLCFGR_PLLQ /*!< SDIO Clock source selection */ -#endif +#endif /* RCC_DCKCFGR_SDIOSEL */ /** * @} */ @@ -1572,7 +1572,7 @@ typedef struct * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLP__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((((__PLLP__) >> RCC_PLLCFGR_PLLP_Pos ) + 1U) * 2U)) + ((((__PLLP__) >> RCC_PLLCFGR_PLLP_Pos ) + 1U) * 2U)) #if defined(RCC_PLLR_SYSCLK_SUPPORT) /** @@ -1654,7 +1654,7 @@ typedef struct * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLRCLK_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLR__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) + ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) #endif /* RCC_PLLR_SYSCLK_SUPPORT */ @@ -1747,7 +1747,7 @@ typedef struct * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_48M_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLQ__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLQ__) >> RCC_PLLCFGR_PLLQ_Pos )) + ((__PLLQ__) >> RCC_PLLCFGR_PLLQ_Pos )) #if defined(DSI) /** @@ -1829,7 +1829,7 @@ typedef struct * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_DSI_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLR__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) + ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) #endif /* DSI */ #if defined(RCC_PLLR_I2S_CLKSOURCE_SUPPORT) @@ -1912,7 +1912,7 @@ typedef struct * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_I2S_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLR__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) + ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) #endif /* RCC_PLLR_I2S_CLKSOURCE_SUPPORT */ #if defined(SPDIFRX) @@ -1995,7 +1995,7 @@ typedef struct * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_SPDIFRX_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLR__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) + ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) #endif /* SPDIFRX */ #if defined(RCC_PLLCFGR_PLLR) @@ -2114,10 +2114,10 @@ typedef struct */ #if defined(RCC_DCKCFGR_PLLDIVR) #define __LL_RCC_CALC_PLLCLK_SAI_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLR__, __PLLDIVR__) (((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) / ((__PLLDIVR__) >> RCC_DCKCFGR_PLLDIVR_Pos )) + ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) / ((__PLLDIVR__) >> RCC_DCKCFGR_PLLDIVR_Pos )) #else #define __LL_RCC_CALC_PLLCLK_SAI_FREQ(__INPUTFREQ__, __PLLM__, __PLLN__, __PLLR__) ((__INPUTFREQ__) / (__PLLM__) * (__PLLN__) / \ - ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) + ((__PLLR__) >> RCC_PLLCFGR_PLLR_Pos )) #endif /* RCC_DCKCFGR_PLLDIVR */ #endif /* SAI1 */ #endif /* RCC_PLLCFGR_PLLR */ @@ -2245,7 +2245,7 @@ typedef struct * @retval PLLSAI clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLSAI_SAI_FREQ(__INPUTFREQ__, __PLLM__, __PLLSAIN__, __PLLSAIQ__, __PLLSAIDIVQ__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLSAIN__) / \ - (((__PLLSAIQ__) >> RCC_PLLSAICFGR_PLLSAIQ_Pos) * (((__PLLSAIDIVQ__) >> RCC_DCKCFGR_PLLSAIDIVQ_Pos) + 1U))) + (((__PLLSAIQ__) >> RCC_PLLSAICFGR_PLLSAIQ_Pos) * (((__PLLSAIDIVQ__) >> RCC_DCKCFGR_PLLSAIDIVQ_Pos) + 1U))) #if defined(RCC_PLLSAICFGR_PLLSAIP) /** @@ -2325,7 +2325,7 @@ typedef struct * @retval PLLSAI clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLSAI_48M_FREQ(__INPUTFREQ__, __PLLM__, __PLLSAIN__, __PLLSAIP__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLSAIN__) / \ - ((((__PLLSAIP__) >> RCC_PLLSAICFGR_PLLSAIP_Pos) + 1U) * 2U)) + ((((__PLLSAIP__) >> RCC_PLLSAICFGR_PLLSAIP_Pos) + 1U) * 2U)) #endif /* RCC_PLLSAICFGR_PLLSAIP */ #if defined(LTDC) @@ -2415,7 +2415,7 @@ typedef struct * @retval PLLSAI clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLSAI_LTDC_FREQ(__INPUTFREQ__, __PLLM__, __PLLSAIN__, __PLLSAIR__, __PLLSAIDIVR__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLSAIN__) / \ - (((__PLLSAIR__) >> RCC_PLLSAICFGR_PLLSAIR_Pos) * (aRCC_PLLSAIDIVRPrescTable[(__PLLSAIDIVR__) >> RCC_DCKCFGR_PLLSAIDIVR_Pos]))) + (((__PLLSAIR__) >> RCC_PLLSAICFGR_PLLSAIR_Pos) * (aRCC_PLLSAIDIVRPrescTable[(__PLLSAIDIVR__) >> RCC_DCKCFGR_PLLSAIDIVR_Pos]))) #endif /* LTDC */ #endif /* RCC_PLLSAI_SUPPORT */ @@ -2585,10 +2585,10 @@ typedef struct */ #if defined(RCC_DCKCFGR_PLLI2SDIVQ) #define __LL_RCC_CALC_PLLI2S_SAI_FREQ(__INPUTFREQ__, __PLLM__, __PLLI2SN__, __PLLI2SQ_R__, __PLLI2SDIVQ_R__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLI2SN__) / \ - (((__PLLI2SQ_R__) >> RCC_PLLI2SCFGR_PLLI2SQ_Pos) * (((__PLLI2SDIVQ_R__) >> RCC_DCKCFGR_PLLI2SDIVQ_Pos) + 1U))) + (((__PLLI2SQ_R__) >> RCC_PLLI2SCFGR_PLLI2SQ_Pos) * (((__PLLI2SDIVQ_R__) >> RCC_DCKCFGR_PLLI2SDIVQ_Pos) + 1U))) #else #define __LL_RCC_CALC_PLLI2S_SAI_FREQ(__INPUTFREQ__, __PLLM__, __PLLI2SN__, __PLLI2SQ_R__, __PLLI2SDIVQ_R__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLI2SN__) / \ - (((__PLLI2SQ_R__) >> RCC_PLLI2SCFGR_PLLI2SR_Pos) * ((__PLLI2SDIVQ_R__) >> RCC_DCKCFGR_PLLI2SDIVR_Pos))) + (((__PLLI2SQ_R__) >> RCC_PLLI2SCFGR_PLLI2SR_Pos) * ((__PLLI2SDIVQ_R__) >> RCC_DCKCFGR_PLLI2SDIVR_Pos))) #endif /* RCC_DCKCFGR_PLLI2SDIVQ */ #endif /* RCC_DCKCFGR_PLLI2SDIVQ || RCC_DCKCFGR_PLLI2SDIVR */ @@ -2671,7 +2671,7 @@ typedef struct * @retval PLLI2S clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLI2S_SPDIFRX_FREQ(__INPUTFREQ__, __PLLM__, __PLLI2SN__, __PLLI2SP__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLI2SN__) / \ - ((((__PLLI2SP__) >> RCC_PLLI2SCFGR_PLLI2SP_Pos) + 1U) * 2U)) + ((((__PLLI2SP__) >> RCC_PLLI2SCFGR_PLLI2SP_Pos) + 1U) * 2U)) #endif /* SPDIFRX */ @@ -2756,7 +2756,7 @@ typedef struct * @retval PLLI2S clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLI2S_I2S_FREQ(__INPUTFREQ__, __PLLM__, __PLLI2SN__, __PLLI2SR__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLI2SN__) / \ - ((__PLLI2SR__) >> RCC_PLLI2SCFGR_PLLI2SR_Pos)) + ((__PLLI2SR__) >> RCC_PLLI2SCFGR_PLLI2SR_Pos)) #if defined(RCC_PLLI2SCFGR_PLLI2SQ) && !defined(RCC_DCKCFGR_PLLI2SDIVQ) /** @@ -2846,7 +2846,7 @@ typedef struct * @retval PLLI2S clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLI2S_48M_FREQ(__INPUTFREQ__, __PLLM__, __PLLI2SN__, __PLLI2SQ__) (((__INPUTFREQ__) / (__PLLM__)) * (__PLLI2SN__) / \ - ((__PLLI2SQ__) >> RCC_PLLI2SCFGR_PLLI2SQ_Pos)) + ((__PLLI2SQ__) >> RCC_PLLI2SCFGR_PLLI2SQ_Pos)) #endif /* RCC_PLLI2SCFGR_PLLI2SQ && !RCC_DCKCFGR_PLLI2SDIVQ */ #endif /* RCC_PLLI2S_SUPPORT */ @@ -2866,7 +2866,8 @@ typedef struct * @arg @ref LL_RCC_SYSCLK_DIV_512 * @retval HCLK clock frequency (in Hz) */ -#define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__, __AHBPRESCALER__) ((__SYSCLKFREQ__) >> AHBPrescTable[((__AHBPRESCALER__) & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos]) +#define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__, __AHBPRESCALER__) ((__SYSCLKFREQ__) >> AHBPrescTable[((__AHBPRESCALER__) &\ + RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos]) /** * @brief Helper macro to calculate the PCLK1 frequency (ABP1) @@ -3389,7 +3390,7 @@ __STATIC_INLINE void LL_RCC_MCO2_Disable(void) */ __STATIC_INLINE void LL_RCC_ConfigMCO(uint32_t MCOxSource, uint32_t MCOxPrescaler) { - MODIFY_REG(RCC->CFGR, (MCOxSource & 0xFFFF0000U) | (MCOxPrescaler & 0xFFFF0000U), (MCOxSource << 16U) | (MCOxPrescaler << 16U)); + MODIFY_REG(RCC->CFGR, (MCOxSource & 0xFFFF0000U) | (MCOxPrescaler & 0xFFFF0000U), (MCOxSource << 16U) | (MCOxPrescaler << 16U)); } /** @@ -4819,7 +4820,8 @@ __STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SPDIFRX(uint32_t Source, uint32_t P * @retval None */ #if defined(RCC_DCKCFGR_PLLDIVR) -__STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLR, uint32_t PLLDIVR) +__STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLR, + uint32_t PLLDIVR) #else __STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLR) #endif /* RCC_DCKCFGR_PLLDIVR */ @@ -5334,7 +5336,8 @@ __STATIC_INLINE uint32_t LL_RCC_PLLI2S_IsReady(void) * (*) value not defined in all devices. * @retval None */ -__STATIC_INLINE void LL_RCC_PLLI2S_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLQ_R, uint32_t PLLDIVQ_R) +__STATIC_INLINE void LL_RCC_PLLI2S_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLQ_R, + uint32_t PLLDIVQ_R) { __IO uint32_t *pReg = (__IO uint32_t *)((uint32_t)((uint32_t)(&RCC->PLLCFGR) + (Source & 0x80U))); MODIFY_REG(*pReg, RCC_PLLCFGR_PLLSRC, (Source & (~0x80U))); @@ -6102,7 +6105,8 @@ __STATIC_INLINE uint32_t LL_RCC_PLLSAI_IsReady(void) * @arg @ref LL_RCC_PLLSAIDIVQ_DIV_32 * @retval None */ -__STATIC_INLINE void LL_RCC_PLLSAI_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLQ, uint32_t PLLDIVQ) +__STATIC_INLINE void LL_RCC_PLLSAI_ConfigDomain_SAI(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLQ, + uint32_t PLLDIVQ) { MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC, Source); #if defined(RCC_PLLSAICFGR_PLLSAIM) @@ -6307,7 +6311,8 @@ __STATIC_INLINE void LL_RCC_PLLSAI_ConfigDomain_48M(uint32_t Source, uint32_t PL * @arg @ref LL_RCC_PLLSAIDIVR_DIV_16 * @retval None */ -__STATIC_INLINE void LL_RCC_PLLSAI_ConfigDomain_LTDC(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLR, uint32_t PLLDIVR) +__STATIC_INLINE void LL_RCC_PLLSAI_ConfigDomain_LTDC(uint32_t Source, uint32_t PLLM, uint32_t PLLN, uint32_t PLLR, + uint32_t PLLDIVR) { MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLLSRC | RCC_PLLCFGR_PLLM, Source | PLLM); MODIFY_REG(RCC->PLLSAICFGR, RCC_PLLSAICFGR_PLLSAIN | RCC_PLLSAICFGR_PLLSAIR, PLLN << RCC_PLLSAICFGR_PLLSAIN_Pos | PLLR); diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_spi.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_spi.h index 4f3b0306f..371383e0d 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_spi.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_spi.h @@ -317,7 +317,7 @@ __STATIC_INLINE void LL_SPI_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_SPE) == (SPI_CR1_SPE)) ? 1UL : 0UL); } @@ -347,7 +347,7 @@ __STATIC_INLINE void LL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_SPI_MODE_MASTER * @arg @ref LL_SPI_MODE_SLAVE */ -__STATIC_INLINE uint32_t LL_SPI_GetMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI)); } @@ -375,7 +375,7 @@ __STATIC_INLINE void LL_SPI_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_SPI_PROTOCOL_MOTOROLA * @arg @ref LL_SPI_PROTOCOL_TI */ -__STATIC_INLINE uint32_t LL_SPI_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR2, SPI_CR2_FRF)); } @@ -404,7 +404,7 @@ __STATIC_INLINE void LL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase * @arg @ref LL_SPI_PHASE_1EDGE * @arg @ref LL_SPI_PHASE_2EDGE */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPHA)); } @@ -433,7 +433,7 @@ __STATIC_INLINE void LL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_SPI_POLARITY_LOW * @arg @ref LL_SPI_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPOL)); } @@ -473,7 +473,7 @@ __STATIC_INLINE void LL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t Bau * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 */ -__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_BR)); } @@ -501,7 +501,7 @@ __STATIC_INLINE void LL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitO * @arg @ref LL_SPI_LSB_FIRST * @arg @ref LL_SPI_MSB_FIRST */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_LSBFIRST)); } @@ -538,7 +538,7 @@ __STATIC_INLINE void LL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t Tra * @arg @ref LL_SPI_HALF_DUPLEX_RX * @arg @ref LL_SPI_HALF_DUPLEX_TX */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE)); } @@ -565,7 +565,7 @@ __STATIC_INLINE void LL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) * @arg @ref LL_SPI_DATAWIDTH_8BIT * @arg @ref LL_SPI_DATAWIDTH_16BIT */ -__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_DFF)); } @@ -609,7 +609,7 @@ __STATIC_INLINE void LL_SPI_DisableCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR1, SPI_CR1_CRCEN) == (SPI_CR1_CRCEN)) ? 1UL : 0UL); } @@ -644,7 +644,7 @@ __STATIC_INLINE void LL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->CRCPR)); } @@ -655,7 +655,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->RXCRCR)); } @@ -666,7 +666,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF */ -__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_REG(SPIx->TXCRCR)); } @@ -707,7 +707,7 @@ __STATIC_INLINE void LL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) * @arg @ref LL_SPI_NSS_HARD_INPUT * @arg @ref LL_SPI_NSS_HARD_OUTPUT */ -__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(const SPI_TypeDef *SPIx) { uint32_t Ssm = (READ_BIT(SPIx->CR1, SPI_CR1_SSM)); uint32_t Ssoe = (READ_BIT(SPIx->CR2, SPI_CR2_SSOE) << 16U); @@ -728,7 +728,7 @@ __STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_RXNE) == (SPI_SR_RXNE)) ? 1UL : 0UL); } @@ -739,7 +739,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_TXE) == (SPI_SR_TXE)) ? 1UL : 0UL); } @@ -750,7 +750,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CRCERR) == (SPI_SR_CRCERR)) ? 1UL : 0UL); } @@ -761,7 +761,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_MODF) == (SPI_SR_MODF)) ? 1UL : 0UL); } @@ -772,7 +772,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_OVR) == (SPI_SR_OVR)) ? 1UL : 0UL); } @@ -790,7 +790,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_BSY) == (SPI_SR_BSY)) ? 1UL : 0UL); } @@ -801,7 +801,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_FRE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_FRE) == (SPI_SR_FRE)) ? 1UL : 0UL); } @@ -946,7 +946,7 @@ __STATIC_INLINE void LL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_ERRIE) == (SPI_CR2_ERRIE)) ? 1UL : 0UL); } @@ -957,7 +957,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXNEIE) == (SPI_CR2_RXNEIE)) ? 1UL : 0UL); } @@ -968,7 +968,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXEIE) == (SPI_CR2_TXEIE)) ? 1UL : 0UL); } @@ -1009,7 +1009,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_RXDMAEN) == (SPI_CR2_RXDMAEN)) ? 1UL : 0UL); } @@ -1042,7 +1042,7 @@ __STATIC_INLINE void LL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->CR2, SPI_CR2_TXDMAEN) == (SPI_CR2_TXDMAEN)) ? 1UL : 0UL); } @@ -1053,7 +1053,7 @@ __STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval Address of data register */ -__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(const SPI_TypeDef *SPIx) { return (uint32_t) &(SPIx->DR); } @@ -1130,7 +1130,7 @@ __STATIC_INLINE void LL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct); void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct); @@ -1397,7 +1397,7 @@ __STATIC_INLINE void LL_I2S_Disable(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabled(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabled(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SE) == (SPI_I2SCFGR_I2SE)) ? 1UL : 0UL); } @@ -1430,7 +1430,7 @@ __STATIC_INLINE void LL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat * @arg @ref LL_I2S_DATAFORMAT_24B * @arg @ref LL_I2S_DATAFORMAT_32B */ -__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)); } @@ -1457,7 +1457,7 @@ __STATIC_INLINE void LL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPo * @arg @ref LL_I2S_POLARITY_LOW * @arg @ref LL_I2S_POLARITY_HIGH */ -__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_CKPOL)); } @@ -1492,7 +1492,7 @@ __STATIC_INLINE void LL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) * @arg @ref LL_I2S_STANDARD_PCM_SHORT * @arg @ref LL_I2S_STANDARD_PCM_LONG */ -__STATIC_INLINE uint32_t LL_I2S_GetStandard(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetStandard(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC)); } @@ -1523,7 +1523,7 @@ __STATIC_INLINE void LL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) * @arg @ref LL_I2S_MODE_MASTER_TX * @arg @ref LL_I2S_MODE_MASTER_RX */ -__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG)); } @@ -1546,7 +1546,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t Presca * @param SPIx SPI Instance * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_I2SDIV)); } @@ -1573,7 +1573,7 @@ __STATIC_INLINE void LL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t Presc * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN * @arg @ref LL_I2S_PRESCALER_PARITY_ODD */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(const SPI_TypeDef *SPIx) { return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_ODD) >> 8U); } @@ -1606,7 +1606,7 @@ __STATIC_INLINE void LL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE) == (SPI_I2SPR_MCKOE)) ? 1UL : 0UL); } @@ -1640,7 +1640,7 @@ __STATIC_INLINE void LL_I2S_DisableAsyncStart(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_ASTRTEN) == (SPI_I2SCFGR_ASTRTEN)) ? 1UL : 0UL); } @@ -1660,7 +1660,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledAsyncStart(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_RXNE(SPIx); } @@ -1671,7 +1671,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_TXE(SPIx); } @@ -1682,7 +1682,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_BSY(SPIx); } @@ -1693,7 +1693,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_OVR(SPIx); } @@ -1704,7 +1704,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_UDR) == (SPI_SR_UDR)) ? 1UL : 0UL); } @@ -1715,7 +1715,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(const SPI_TypeDef *SPIx) { return LL_SPI_IsActiveFlag_FRE(SPIx); } @@ -1729,7 +1729,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_FRE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(const SPI_TypeDef *SPIx) { return ((READ_BIT(SPIx->SR, SPI_SR_CHSIDE) == (SPI_SR_CHSIDE)) ? 1UL : 0UL); } @@ -1851,7 +1851,7 @@ __STATIC_INLINE void LL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_ERR(SPIx); } @@ -1862,7 +1862,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_RXNE(SPIx); } @@ -1873,7 +1873,7 @@ __STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledIT_TXE(SPIx); } @@ -1914,7 +1914,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_RX(SPIx); } @@ -1947,7 +1947,7 @@ __STATIC_INLINE void LL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) * @param SPIx SPI Instance * @retval State of bit (1 or 0). */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) +__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(const SPI_TypeDef *SPIx) { return LL_SPI_IsEnabledDMAReq_TX(SPIx); } @@ -1992,7 +1992,7 @@ __STATIC_INLINE void LL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) * @{ */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx); +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx); ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct); void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); diff --git a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_utils.h b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_utils.h index 1ea157472..0393ef90b 100644 --- a/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_utils.h +++ b/stm32cube/stm32f4xx/drivers/include/stm32f4xx_ll_utils.h @@ -254,7 +254,7 @@ __STATIC_INLINE uint32_t LL_GetPackageType(void) * @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCC helper macro) * @note When a RTOS is used, it is recommended to avoid changing the SysTick * configuration by calling this function, for a delay use rather osDelay RTOS service. - * @param Ticks Number of ticks + * @param Ticks Frequency of Ticks (Hz) * @retval None */ __STATIC_INLINE void LL_InitTick(uint32_t HCLKFrequency, uint32_t Ticks) diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal.c index de14a0e33..096fd16e9 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal.c @@ -50,11 +50,11 @@ * @{ */ /** - * @brief STM32F4xx HAL Driver version number V1.8.2 + * @brief STM32F4xx HAL Driver version number V1.8.3 */ #define __STM32F4xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ #define __STM32F4xx_HAL_VERSION_SUB1 (0x08U) /*!< [23:16] sub1 version */ -#define __STM32F4xx_HAL_VERSION_SUB2 (0x02U) /*!< [15:8] sub2 version */ +#define __STM32F4xx_HAL_VERSION_SUB2 (0x03U) /*!< [15:8] sub2 version */ #define __STM32F4xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32F4xx_HAL_VERSION ((__STM32F4xx_HAL_VERSION_MAIN << 24U)\ |(__STM32F4xx_HAL_VERSION_SUB1 << 16U)\ diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_adc_ex.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_adc_ex.c index 7db199371..1d8ad7b53 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_adc_ex.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_adc_ex.c @@ -779,6 +779,9 @@ uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef *hadc) { ADC_Common_TypeDef *tmpADC_Common; + /* Prevent unused argument(s) compilation warning */ + UNUSED(hadc); + /* Pointer to the common control register to which is belonging hadc */ /* (Depending on STM32F4 product, there may be up to 3 ADC and 1 common */ /* control register) */ diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_cortex.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_cortex.c index 3de962f8f..bd38f7c60 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_cortex.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_cortex.c @@ -289,9 +289,41 @@ void HAL_MPU_Enable(uint32_t MPU_Control) __ISB(); } +/** + * @brief Enables the MPU Region. + * @retval None + */ +void HAL_MPU_EnableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Enable the Region */ + SET_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @brief Disables the MPU Region. + * @retval None + */ +void HAL_MPU_DisableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + /** * @brief Initializes and configures the Region and the memory to be protected. - * @param MPU_Init Pointer to a MPU_Region_InitTypeDef structure that contains + * @param MPU_Init Pointer to a MPU_Region_InitTypeDef structure that contains * the initialization and configuration information. * @retval None */ @@ -300,38 +332,32 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); + assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); + assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); + assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); + assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); + assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); + assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); + assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); + assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; - if ((MPU_Init->Enable) != RESET) - { - /* Check the parameters */ - assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); - assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); - assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); - assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); - assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); - assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); - assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); - assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); - - MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | - ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | - ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | - ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | - ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | - ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | - ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | - ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | - ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); - } - else - { - MPU->RBAR = 0x00U; - MPU->RASR = 0x00U; - } + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); + + /* Apply configuration */ + MPU->RBAR = MPU_Init->BaseAddress; + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | + ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | + ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | + ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | + ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | + ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | + ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } #endif /* __MPU_PRESENT */ diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_dsi.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_dsi.c index b193c24e6..3fb583661 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_dsi.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_dsi.c @@ -130,7 +130,7 @@ all callbacks are set to the corresponding weak functions: examples HAL_DSI_TearingEffectCallback(), HAL_DSI_EndOfRefreshCallback(). Exception done for MspInit and MspDeInit functions that are respectively - reset to the legacy weak (surcharged) functions in the HAL_DSI_Init() + reset to the legacy weak (overridden) functions in the HAL_DSI_Init() and HAL_DSI_DeInit() only when these callbacks are null (not registered beforehand). If not, MspInit or MspDeInit are not null, the HAL_DSI_Init() and HAL_DSI_DeInit() keep and use the user MspInit/MspDeInit callbacks (registered beforehand). @@ -395,24 +395,53 @@ HAL_StatusTypeDef HAL_DSI_Init(DSI_HandleTypeDef *hdsi, DSI_PLLInitTypeDef *PLLI } } - /*************************** Set the PHY parameters ***************************/ + __HAL_DSI_ENABLE(hdsi); + + /************************ Set the DSI clock parameters ************************/ + /* Set the TX escape clock division factor */ + hdsi->Instance->CCR &= ~DSI_CCR_TXECKDIV; + hdsi->Instance->CCR |= hdsi->Init.TXEscapeCkdiv; + /*************************** Set the PHY parameters ***************************/ /* D-PHY clock and digital enable*/ - hdsi->Instance->PCTLR |= (DSI_PCTLR_CKE | DSI_PCTLR_DEN); + hdsi->Instance->PCTLR |= DSI_PCTLR_DEN; + + hdsi->Instance->PCTLR |= DSI_PCTLR_CKE; - /* Clock lane configuration */ - hdsi->Instance->CLCR &= ~(DSI_CLCR_DPCC | DSI_CLCR_ACR); - hdsi->Instance->CLCR |= (DSI_CLCR_DPCC | hdsi->Init.AutomaticClockLaneControl); /* Configure the number of active data lanes */ hdsi->Instance->PCONFR &= ~DSI_PCONFR_NL; hdsi->Instance->PCONFR |= hdsi->Init.NumberOfLanes; - /************************ Set the DSI clock parameters ************************/ + /* Get tick */ + tickstart = HAL_GetTick(); + if ((hdsi->Instance->PCONFR & DSI_PCONFR_NL) == DSI_ONE_DATA_LANE) + { + while ((hdsi->Instance->PSR & (DSI_PSR_PSS0 | DSI_PSR_PSSC)) != (DSI_PSR_PSS0 | DSI_PSR_PSSC)) + { + if ((HAL_GetTick() - tickstart) > DSI_TIMEOUT_VALUE) + { + /* Process Unlocked */ + __HAL_UNLOCK(hdsi); - /* Set the TX escape clock division factor */ - hdsi->Instance->CCR &= ~DSI_CCR_TXECKDIV; - hdsi->Instance->CCR |= hdsi->Init.TXEscapeCkdiv; + return HAL_TIMEOUT; + } + } + } + else + { + while ((hdsi->Instance->PSR & (DSI_PSR_PSS0 | DSI_PSR_PSS1 | DSI_PSR_PSSC)) != (DSI_PSR_PSS0 | \ + DSI_PSR_PSS1 | DSI_PSR_PSSC)) + { + if ((HAL_GetTick() - tickstart) > DSI_TIMEOUT_VALUE) + { + /* Process Unlocked */ + __HAL_UNLOCK(hdsi); + + return HAL_TIMEOUT; + } + } + } /* Calculate the bit period in high-speed mode in unit of 0.25 ns (UIX4) */ /* The equation is : UIX4 = IntegerPart( (1000/F_PHY_Mhz) * 4 ) */ @@ -431,6 +460,12 @@ HAL_StatusTypeDef HAL_DSI_Init(DSI_HandleTypeDef *hdsi, DSI_PLLInitTypeDef *PLLI hdsi->Instance->IER[1U] = 0U; hdsi->ErrorMsk = 0U; + __HAL_DSI_DISABLE(hdsi); + + /* Clock lane configuration */ + hdsi->Instance->CLCR &= ~(DSI_CLCR_DPCC | DSI_CLCR_ACR); + hdsi->Instance->CLCR |= (DSI_CLCR_DPCC | hdsi->Init.AutomaticClockLaneControl); + /* Initialize the error code */ hdsi->ErrorCode = HAL_DSI_ERROR_NONE; @@ -1628,14 +1663,14 @@ HAL_StatusTypeDef HAL_DSI_LongWrite(DSI_HandleTypeDef *hdsi, uint32_t Mode, uint32_t NbParams, uint32_t Param1, - uint8_t *ParametersTable) + const uint8_t *ParametersTable) { uint32_t uicounter; uint32_t nbBytes; uint32_t count; uint32_t tickstart; uint32_t fifoword; - uint8_t *pparams = ParametersTable; + const uint8_t *pparams = ParametersTable; /* Process locked */ __HAL_LOCK(hdsi); @@ -3099,7 +3134,7 @@ HAL_StatusTypeDef HAL_DSI_SetContentionDetectionOff(DSI_HandleTypeDef *hdsi, Fun * the configuration information for the DSI. * @retval HAL state */ -HAL_DSI_StateTypeDef HAL_DSI_GetState(DSI_HandleTypeDef *hdsi) +HAL_DSI_StateTypeDef HAL_DSI_GetState(const DSI_HandleTypeDef *hdsi) { return hdsi->State; } @@ -3110,7 +3145,7 @@ HAL_DSI_StateTypeDef HAL_DSI_GetState(DSI_HandleTypeDef *hdsi) * the configuration information for the DSI. * @retval DSI Error Code */ -uint32_t HAL_DSI_GetError(DSI_HandleTypeDef *hdsi) +uint32_t HAL_DSI_GetError(const DSI_HandleTypeDef *hdsi) { /* Get the error code */ return hdsi->ErrorCode; diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_eth.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_eth.c index ff0cfec15..f1a00e3f1 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_eth.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_eth.c @@ -234,7 +234,7 @@ #define ETH_REG_WRITE_DELAY 0x00000001U /* ETHERNET MACCR register Mask */ -#define ETH_MACCR_CLEAR_MASK 0xFF20810FU +#define ETH_MACCR_CLEAR_MASK 0xFD20810FU /* ETHERNET MACFCR register Mask */ #define ETH_MACFCR_CLEAR_MASK 0x0000FF41U @@ -276,12 +276,13 @@ /** @defgroup ETH_Private_Functions ETH Private Functions * @{ */ -static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf); -static void ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf); +static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, const ETH_MACConfigTypeDef *macconf); +static void ETH_SetDMAConfig(ETH_HandleTypeDef *heth, const ETH_DMAConfigTypeDef *dmaconf); static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth); static void ETH_DMATxDescListInit(ETH_HandleTypeDef *heth); static void ETH_DMARxDescListInit(ETH_HandleTypeDef *heth); -static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t ItMode); +static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, const ETH_TxPacketConfigTypeDef *pTxConfig, + uint32_t ItMode); static void ETH_UpdateDescriptor(ETH_HandleTypeDef *heth); static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth); static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint8_t *Addr); @@ -406,6 +407,17 @@ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) /*--------------------- ETHERNET MAC Address Configuration ------------------*/ ETH_MACAddressConfig(heth, ETH_MAC_ADDRESS0, heth->Init.MACAddr); + /* Disable MMC Interrupts */ + SET_BIT(heth->Instance->MACIMR, ETH_MACIMR_TSTIM | ETH_MACIMR_PMTIM); + + /* Disable Rx MMC Interrupts */ + SET_BIT(heth->Instance->MMCRIMR, ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFAEM | \ + ETH_MMCRIMR_RFCEM); + + /* Disable Tx MMC Interrupts */ + SET_BIT(heth->Instance->MMCTIMR, ETH_MMCTIMR_TGFM | ETH_MMCTIMR_TGFMSCM | \ + ETH_MMCTIMR_TGFSCM); + heth->ErrorCode = HAL_ETH_ERROR_NONE; heth->gState = HAL_ETH_STATE_READY; @@ -760,16 +772,6 @@ HAL_StatusTypeDef HAL_ETH_Start_IT(ETH_HandleTypeDef *heth) /* save IT mode to ETH Handle */ heth->RxDescList.ItMode = 1U; - /* Disable MMC Interrupts */ - SET_BIT(heth->Instance->MACIMR, ETH_MACIMR_TSTIM | ETH_MACIMR_PMTIM); - - /* Disable Rx MMC Interrupts */ - SET_BIT(heth->Instance->MMCRIMR, ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFAEM | \ - ETH_MMCRIMR_RFCEM); - - /* Disable Tx MMC Interrupts */ - SET_BIT(heth->Instance->MMCTIMR, ETH_MMCTIMR_TGFM | ETH_MMCTIMR_TGFMSCM | \ - ETH_MMCTIMR_TGFSCM); /* Set number of descriptors to build */ heth->RxDescList.RxBuildDescCnt = ETH_RX_DESC_CNT; @@ -777,17 +779,24 @@ HAL_StatusTypeDef HAL_ETH_Start_IT(ETH_HandleTypeDef *heth) /* Build all descriptors */ ETH_UpdateDescriptor(heth); - /* Enable the MAC transmission */ - SET_BIT(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 */ tmpreg1 = (heth->Instance)->MACCR; HAL_Delay(ETH_REG_WRITE_DELAY); (heth->Instance)->MACCR = tmpreg1; - /* Enable the MAC reception */ - SET_BIT(heth->Instance->MACCR, ETH_MACCR_RE); + /* Enable the DMA transmission */ + SET_BIT(heth->Instance->DMAOMR, ETH_DMAOMR_ST); + + /* Enable the DMA reception */ + SET_BIT(heth->Instance->DMAOMR, ETH_DMAOMR_SR); + + /* Flush Transmit FIFO */ + ETH_FlushTransmitFIFO(heth); + + + /* Enable the MAC transmission */ + SET_BIT(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 */ @@ -795,14 +804,8 @@ HAL_StatusTypeDef HAL_ETH_Start_IT(ETH_HandleTypeDef *heth) HAL_Delay(ETH_REG_WRITE_DELAY); (heth->Instance)->MACCR = tmpreg1; - /* Flush Transmit FIFO */ - ETH_FlushTransmitFIFO(heth); - - /* Enable the DMA transmission */ - SET_BIT(heth->Instance->DMAOMR, ETH_DMAOMR_ST); - - /* Enable the DMA reception */ - SET_BIT(heth->Instance->DMAOMR, ETH_DMAOMR_SR); + /* Enable the MAC reception */ + SET_BIT(heth->Instance->MACCR, ETH_MACCR_RE); /* Enable ETH DMA interrupts: - Tx complete interrupt @@ -950,7 +953,7 @@ HAL_StatusTypeDef HAL_ETH_Stop_IT(ETH_HandleTypeDef *heth) * @param Timeout: timeout value * @retval HAL status */ -HAL_StatusTypeDef HAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t Timeout) +HAL_StatusTypeDef HAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfigTypeDef *pTxConfig, uint32_t Timeout) { uint32_t tickstart; ETH_DMADescTypeDef *dmatxdesc; @@ -1025,7 +1028,7 @@ HAL_StatusTypeDef HAL_ETH_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig * * @param pTxConfig: Hold the configuration of packet to be transmitted * @retval HAL status */ -HAL_StatusTypeDef HAL_ETH_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig) +HAL_StatusTypeDef HAL_ETH_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfigTypeDef *pTxConfig) { if (pTxConfig == NULL) { @@ -1121,13 +1124,12 @@ HAL_StatusTypeDef HAL_ETH_ReadData(ETH_HandleTypeDef *heth, void **pAppBuff) heth->RxDescList.RxDataLength = 0; } + /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */ + bufflength = ((dmarxdesc->DESC0 & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT); + /* Check if last descriptor */ - bufflength = heth->Init.RxBuffLen; if (READ_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_LS) != (uint32_t)RESET) { - /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */ - bufflength = ((dmarxdesc->DESC0 & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4U; - /* Save Last descriptor index */ heth->RxDescList.pRxLastRxDesc = dmarxdesc->DESC0; @@ -1193,8 +1195,8 @@ HAL_StatusTypeDef HAL_ETH_ReadData(ETH_HandleTypeDef *heth, void **pAppBuff) */ static void ETH_UpdateDescriptor(ETH_HandleTypeDef *heth) { - uint32_t tailidx; uint32_t descidx; + uint32_t tailidx; uint32_t desccount; ETH_DMADescTypeDef *dmarxdesc; uint8_t *buff = NULL; @@ -1232,11 +1234,11 @@ static void ETH_UpdateDescriptor(ETH_HandleTypeDef *heth) { if (heth->RxDescList.ItMode == 0U) { - WRITE_REG(dmarxdesc->DESC1, ETH_DMARXDESC_DIC | ETH_RX_BUF_SIZE | ETH_DMARXDESC_RCH); + WRITE_REG(dmarxdesc->DESC1, heth->Init.RxBuffLen | ETH_DMARXDESC_DIC | ETH_DMARXDESC_RCH); } else { - WRITE_REG(dmarxdesc->DESC1, ETH_RX_BUF_SIZE | ETH_DMARXDESC_RCH); + WRITE_REG(dmarxdesc->DESC1, heth->Init.RxBuffLen | ETH_DMARXDESC_RCH); } SET_BIT(dmarxdesc->DESC0, ETH_DMARXDESC_OWN); @@ -1377,7 +1379,7 @@ HAL_StatusTypeDef HAL_ETH_UnRegisterRxLinkCallback(ETH_HandleTypeDef *heth) * @param pErrorCode: pointer to uint32_t to hold the error code * @retval HAL status */ -HAL_StatusTypeDef HAL_ETH_GetRxDataErrorCode(ETH_HandleTypeDef *heth, uint32_t *pErrorCode) +HAL_StatusTypeDef HAL_ETH_GetRxDataErrorCode(const ETH_HandleTypeDef *heth, uint32_t *pErrorCode) { /* Get error bits. */ *pErrorCode = READ_BIT(heth->RxDescList.pRxLastRxDesc, ETH_DMARXDESC_ERRORS_MASK); @@ -1460,7 +1462,7 @@ HAL_StatusTypeDef HAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth) if (dmatxdesclist->PacketAddress[idx] == NULL) { /* No packet in use, skip to next. */ - idx = (idx + 1U) & (ETH_TX_DESC_CNT - 1U); + INCR_TX_DESC_INDEX(idx, 1U); pktInUse = 0U; } @@ -1470,17 +1472,28 @@ HAL_StatusTypeDef HAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth) if ((heth->Init.TxDesc[idx].DESC0 & ETH_DMATXDESC_OWN) == 0U) { #ifdef HAL_ETH_USE_PTP - /* Get timestamp low */ - timestamp->TimeStampLow = heth->Init.TxDesc[idx].DESC6; - /* Get timestamp high */ - timestamp->TimeStampHigh = heth->Init.TxDesc[idx].DESC7; + if ((heth->Init.TxDesc[idx].DESC3 & ETH_DMATXDESC_LS) + && (heth->Init.TxDesc[idx].DESC3 & ETH_DMATXDESC_TTSS)) + { + /* Get timestamp low */ + timestamp->TimeStampLow = heth->Init.TxDesc[idx].DESC6; + /* Get timestamp high */ + timestamp->TimeStampHigh = heth->Init.TxDesc[idx].DESC7; + } + else + { + timestamp->TimeStampHigh = timestamp->TimeStampLow = UINT32_MAX; + } #endif /* HAL_ETH_USE_PTP */ #if (USE_HAL_ETH_REGISTER_CALLBACKS == 1) /*Call registered callbacks*/ #ifdef HAL_ETH_USE_PTP /* Handle Ptp */ - heth->txPtpCallback(dmatxdesclist->PacketAddress[idx], timestamp); + if (timestamp->TimeStampHigh != UINT32_MAX && timestamp->TimeStampLow != UINT32_MAX) + { + heth->txPtpCallback(dmatxdesclist->PacketAddress[idx], timestamp); + } #endif /* HAL_ETH_USE_PTP */ /* Release the packet. */ heth->txFreeCallback(dmatxdesclist->PacketAddress[idx]); @@ -1488,7 +1501,10 @@ HAL_StatusTypeDef HAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth) /* Call callbacks */ #ifdef HAL_ETH_USE_PTP /* Handle Ptp */ - HAL_ETH_TxPtpCallback(dmatxdesclist->PacketAddress[idx], timestamp); + if (timestamp->TimeStampHigh != UINT32_MAX && timestamp->TimeStampLow != UINT32_MAX) + { + HAL_ETH_TxPtpCallback(dmatxdesclist->PacketAddress[idx], timestamp); + } #endif /* HAL_ETH_USE_PTP */ /* Release the packet. */ HAL_ETH_TxFreeCallback(dmatxdesclist->PacketAddress[idx]); @@ -1498,7 +1514,7 @@ HAL_StatusTypeDef HAL_ETH_ReleaseTxPacket(ETH_HandleTypeDef *heth) dmatxdesclist->PacketAddress[idx] = NULL; /* Update the transmit relesae index and number of buffers in use. */ - idx = (idx + 1U) & (ETH_TX_DESC_CNT - 1U); + INCR_TX_DESC_INDEX(idx, 1U); dmatxdesclist->BuffersInUse = numOfBuf; dmatxdesclist->releaseIndex = idx; } @@ -1556,25 +1572,24 @@ HAL_StatusTypeDef HAL_ETH_PTP_SetConfig(ETH_HandleTypeDef *heth, ETH_PTP_ConfigT if (ptpconfig->TimestampAddendUpdate == ENABLE) { SET_BIT(heth->Instance->PTPTSCR, ETH_PTPTSCR_TSARU); - while ((heth->Instance->PTPTSCR & ETH_PTPTSCR_TSARU) != 0) {} - } + while ((heth->Instance->PTPTSCR & ETH_PTPTSCR_TSARU) != 0) + { - /* Enable Update mode */ - if (ptpconfig->TimestampUpdateMode == ENABLE) - { - SET_BIT(heth->Instance->PTPTSCR, ETH_PTPTSCR_TSFCU); + } } - /* Initialize Time */ - time.Seconds = 0; - time.NanoSeconds = 0; - HAL_ETH_PTP_SetTime(heth, &time); - /* Ptp Init */ SET_BIT(heth->Instance->PTPTSCR, ETH_PTPTSCR_TSSTI); /* Set PTP Configuration done */ - heth->IsPtpConfigured = HAL_ETH_PTP_CONFIGURATED; + heth->IsPtpConfigured = HAL_ETH_PTP_CONFIGURED; + + /* Set Seconds */ + time.Seconds = heth->Instance->PTPTSHR; + /* Set NanoSeconds */ + time.NanoSeconds = heth->Instance->PTPTSLR; + + HAL_ETH_PTP_SetTime(heth, &time); /* Return function status */ return HAL_OK; @@ -1628,13 +1643,13 @@ HAL_StatusTypeDef HAL_ETH_PTP_GetConfig(ETH_HandleTypeDef *heth, ETH_PTP_ConfigT * @brief Set Seconds and Nanoseconds for the Ethernet PTP registers. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module - * @param heth: pointer to a ETH_TimeTypeDef structure that contains + * @param time: pointer to a ETH_TimeTypeDef structure that contains * time to set * @retval HAL status */ HAL_StatusTypeDef HAL_ETH_PTP_SetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef *time) { - if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURATED) + if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURED) { /* Set Seconds */ heth->Instance->PTPTSHUR = time->Seconds; @@ -1642,6 +1657,9 @@ HAL_StatusTypeDef HAL_ETH_PTP_SetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef * /* Set NanoSeconds */ heth->Instance->PTPTSLUR = time->NanoSeconds; + /* the system time is updated */ + SET_BIT(heth->Instance->PTPTSCR, ETH_PTPTSCR_TSSTU); + /* Return function status */ return HAL_OK; } @@ -1656,17 +1674,16 @@ HAL_StatusTypeDef HAL_ETH_PTP_SetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef * * @brief Get Seconds and Nanoseconds for the Ethernet PTP registers. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module - * @param heth: pointer to a ETH_TimeTypeDef structure that contains + * @param time: pointer to a ETH_TimeTypeDef structure that contains * time to get * @retval HAL status */ HAL_StatusTypeDef HAL_ETH_PTP_GetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef *time) { - if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURATED) + if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURED) { /* Get Seconds */ time->Seconds = heth->Instance->PTPTSHR; - /* Get NanoSeconds */ time->NanoSeconds = heth->Instance->PTPTSLR; @@ -1684,14 +1701,14 @@ HAL_StatusTypeDef HAL_ETH_PTP_GetTime(ETH_HandleTypeDef *heth, ETH_TimeTypeDef * * @brief Update time for the Ethernet PTP registers. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module - * @param timeupdate: pointer to a ETH_TIMEUPDATETypeDef structure that contains + * @param timeoffset: pointer to a ETH_PtpUpdateTypeDef structure that contains * the time update information * @retval HAL status */ HAL_StatusTypeDef HAL_ETH_PTP_AddTimeOffset(ETH_HandleTypeDef *heth, ETH_PtpUpdateTypeDef ptpoffsettype, ETH_TimeTypeDef *timeoffset) { - if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURATED) + if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURED) { if (ptpoffsettype == HAL_ETH_PTP_NEGATIVE_UPDATE) { @@ -1716,6 +1733,8 @@ HAL_StatusTypeDef HAL_ETH_PTP_AddTimeOffset(ETH_HandleTypeDef *heth, ETH_PtpUpda heth->Instance->PTPTSLUR = timeoffset->NanoSeconds; } + SET_BIT(heth->Instance->PTPTSCR, ETH_PTPTSCR_TSSTU); + /* Return function status */ return HAL_OK; } @@ -1730,7 +1749,6 @@ HAL_StatusTypeDef HAL_ETH_PTP_AddTimeOffset(ETH_HandleTypeDef *heth, ETH_PtpUpda * @brief Insert Timestamp in transmission. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module - * @param txtimestampconf: Enable or Disable timestamp in transmission * @retval HAL status */ HAL_StatusTypeDef HAL_ETH_PTP_InsertTxTimestamp(ETH_HandleTypeDef *heth) @@ -1739,7 +1757,7 @@ HAL_StatusTypeDef HAL_ETH_PTP_InsertTxTimestamp(ETH_HandleTypeDef *heth) uint32_t descidx = dmatxdesclist->CurTxDesc; ETH_DMADescTypeDef *dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; - if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURATED) + if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURED) { /* Enable Time Stamp transmission */ SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_TTSE); @@ -1768,7 +1786,7 @@ HAL_StatusTypeDef HAL_ETH_PTP_GetTxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeSt uint32_t idx = dmatxdesclist->releaseIndex; ETH_DMADescTypeDef *dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[idx]; - if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURATED) + if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURED) { /* Get timestamp low */ timestamp->TimeStampLow = dmatxdesc->DESC0; @@ -1795,7 +1813,7 @@ HAL_StatusTypeDef HAL_ETH_PTP_GetTxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeSt */ HAL_StatusTypeDef HAL_ETH_PTP_GetRxTimestamp(ETH_HandleTypeDef *heth, ETH_TimeStampTypeDef *timestamp) { - if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURATED) + if (heth->IsPtpConfigured == HAL_ETH_PTP_CONFIGURED) { /* Get timestamp low */ timestamp->TimeStampLow = heth->RxDescList.TimeStamp.TimeStampLow; @@ -1849,6 +1867,8 @@ HAL_StatusTypeDef HAL_ETH_UnRegisterTxPtpCallback(ETH_HandleTypeDef *heth) /** * @brief Tx Ptp callback. * @param buff: pointer to application buffer + * @param timestamp: pointer to ETH_TimeStampTypeDef structure that contains + * transmission timestamp * @retval None */ __weak void HAL_ETH_TxPtpCallback(uint32_t *buff, ETH_TimeStampTypeDef *timestamp) @@ -1869,84 +1889,79 @@ __weak void HAL_ETH_TxPtpCallback(uint32_t *buff, ETH_TimeStampTypeDef *timestam */ void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth) { + uint32_t mac_flag = READ_REG(heth->Instance->MACSR); + uint32_t dma_flag = READ_REG(heth->Instance->DMASR); + uint32_t dma_itsource = READ_REG(heth->Instance->DMAIER); + uint32_t exti_flag = READ_REG(EXTI->PR); + /* Packet received */ - if (__HAL_ETH_DMA_GET_IT(heth, ETH_DMASR_RS)) + if (((dma_flag & ETH_DMASR_RS) != 0U) && ((dma_itsource & ETH_DMAIER_RIE) != 0U)) { - if (__HAL_ETH_DMA_GET_IT_SOURCE(heth, ETH_DMAIER_RIE)) - { - /* Clear the Eth DMA Rx IT pending bits */ - __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMASR_RS | ETH_DMASR_NIS); + /* Clear the Eth DMA Rx IT pending bits */ + __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMASR_RS | ETH_DMASR_NIS); #if (USE_HAL_ETH_REGISTER_CALLBACKS == 1) - /*Call registered Receive complete callback*/ - heth->RxCpltCallback(heth); + /*Call registered Receive complete callback*/ + heth->RxCpltCallback(heth); #else - /* Receive complete callback */ - HAL_ETH_RxCpltCallback(heth); + /* Receive complete callback */ + HAL_ETH_RxCpltCallback(heth); #endif /* USE_HAL_ETH_REGISTER_CALLBACKS */ - } } /* Packet transmitted */ - if (__HAL_ETH_DMA_GET_IT(heth, ETH_DMASR_TS)) + if (((dma_flag & ETH_DMASR_TS) != 0U) && ((dma_itsource & ETH_DMAIER_TIE) != 0U)) { - if (__HAL_ETH_DMA_GET_IT_SOURCE(heth, ETH_DMAIER_TIE)) - { - /* Clear the Eth DMA Tx IT pending bits */ - __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMASR_TS | ETH_DMASR_NIS); + /* Clear the Eth DMA Tx IT pending bits */ + __HAL_ETH_DMA_CLEAR_IT(heth, ETH_DMASR_TS | ETH_DMASR_NIS); #if (USE_HAL_ETH_REGISTER_CALLBACKS == 1) - /*Call registered Transmit complete callback*/ - heth->TxCpltCallback(heth); + /*Call registered Transmit complete callback*/ + heth->TxCpltCallback(heth); #else - /* Transfer complete callback */ - HAL_ETH_TxCpltCallback(heth); + /* Transfer complete callback */ + HAL_ETH_TxCpltCallback(heth); #endif /* USE_HAL_ETH_REGISTER_CALLBACKS */ - } } /* ETH DMA Error */ - if (__HAL_ETH_DMA_GET_IT(heth, ETH_DMASR_AIS)) + if (((dma_flag & ETH_DMASR_AIS) != 0U) && ((dma_itsource & ETH_DMAIER_AISE) != 0U)) { - if (__HAL_ETH_DMA_GET_IT_SOURCE(heth, ETH_DMAIER_AISE)) + heth->ErrorCode |= HAL_ETH_ERROR_DMA; + /* if fatal bus error occurred */ + if ((dma_flag & ETH_DMASR_FBES) != 0U) { - heth->ErrorCode |= HAL_ETH_ERROR_DMA; - /* if fatal bus error occurred */ - if (__HAL_ETH_DMA_GET_IT(heth, ETH_DMASR_FBES)) - { - /* Get DMA error code */ - heth->DMAErrorCode = READ_BIT(heth->Instance->DMASR, (ETH_DMASR_FBES | ETH_DMASR_TPS | ETH_DMASR_RPS)); + /* Get DMA error code */ + heth->DMAErrorCode = READ_BIT(heth->Instance->DMASR, (ETH_DMASR_FBES | ETH_DMASR_TPS | ETH_DMASR_RPS)); - /* Disable all interrupts */ - __HAL_ETH_DMA_DISABLE_IT(heth, ETH_DMAIER_NISE | ETH_DMAIER_AISE); + /* Disable all interrupts */ + __HAL_ETH_DMA_DISABLE_IT(heth, ETH_DMAIER_NISE | ETH_DMAIER_AISE); - /* Set HAL state to ERROR */ - heth->gState = HAL_ETH_STATE_ERROR; - } - else - { - /* Get DMA error status */ - heth->DMAErrorCode = READ_BIT(heth->Instance->DMASR, (ETH_DMASR_ETS | ETH_DMASR_RWTS | - ETH_DMASR_RBUS | ETH_DMASR_AIS)); + /* Set HAL state to ERROR */ + heth->gState = HAL_ETH_STATE_ERROR; + } + else + { + /* Get DMA error status */ + heth->DMAErrorCode = READ_BIT(heth->Instance->DMASR, (ETH_DMASR_ETS | ETH_DMASR_RWTS | + ETH_DMASR_RBUS | ETH_DMASR_AIS)); - /* Clear the interrupt summary flag */ - __HAL_ETH_DMA_CLEAR_IT(heth, (ETH_DMASR_ETS | ETH_DMASR_RWTS | - ETH_DMASR_RBUS | ETH_DMASR_AIS)); - } + /* Clear the interrupt summary flag */ + __HAL_ETH_DMA_CLEAR_IT(heth, (ETH_DMASR_ETS | ETH_DMASR_RWTS | + ETH_DMASR_RBUS | ETH_DMASR_AIS)); + } #if (USE_HAL_ETH_REGISTER_CALLBACKS == 1) - /* Call registered Error callback*/ - heth->ErrorCallback(heth); + /* Call registered Error callback*/ + heth->ErrorCallback(heth); #else - /* Ethernet DMA Error callback */ - HAL_ETH_ErrorCallback(heth); + /* Ethernet DMA Error callback */ + HAL_ETH_ErrorCallback(heth); #endif /* USE_HAL_ETH_REGISTER_CALLBACKS */ - - } } /* ETH PMT IT */ - if (__HAL_ETH_MAC_GET_IT(heth, ETH_MAC_PMT_IT)) + if ((mac_flag & ETH_MAC_PMT_IT) != 0U) { /* Get MAC Wake-up source and clear the status register pending bit */ heth->MACWakeUpEvent = READ_BIT(heth->Instance->MACPMTCSR, (ETH_MACPMTCSR_WFR | ETH_MACPMTCSR_MPR)); @@ -1964,7 +1979,7 @@ void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth) /* check ETH WAKEUP exti flag */ - if (__HAL_ETH_WAKEUP_EXTI_GET_FLAG(ETH_WAKEUP_EXTI_LINE) != (uint32_t)RESET) + if ((exti_flag & ETH_WAKEUP_EXTI_LINE) != 0U) { /* Clear ETH WAKEUP Exti pending bit */ __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG(ETH_WAKEUP_EXTI_LINE); @@ -2105,7 +2120,6 @@ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint32_t PHYA return HAL_OK; } - /** * @brief Writes to a PHY register. * @param heth: pointer to a ETH_HandleTypeDef structure that contains @@ -2183,7 +2197,7 @@ HAL_StatusTypeDef HAL_ETH_WritePHYRegister(const ETH_HandleTypeDef *heth, uint32 * the configuration of the MAC. * @retval HAL Status */ -HAL_StatusTypeDef HAL_ETH_GetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf) +HAL_StatusTypeDef HAL_ETH_GetMACConfig(const ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf) { if (macconf == NULL) { @@ -2205,7 +2219,7 @@ HAL_StatusTypeDef HAL_ETH_GetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTyp macconf->AutomaticPadCRCStrip = ((READ_BIT(heth->Instance->MACCR, ETH_MACCR_APCS) >> 7) > 0U) ? ENABLE : DISABLE; macconf->InterPacketGapVal = READ_BIT(heth->Instance->MACCR, ETH_MACCR_IFG); macconf->ChecksumOffload = ((READ_BIT(heth->Instance->MACCR, ETH_MACCR_IPCO) >> 10U) > 0U) ? ENABLE : DISABLE; - + macconf->CRCStripTypePacket = ((READ_BIT(heth->Instance->MACCR, ETH_MACCR_CSTF) >> 25U) > 0U) ? ENABLE : DISABLE; macconf->TransmitFlowControl = ((READ_BIT(heth->Instance->MACFCR, ETH_MACFCR_TFCE) >> 1) > 0U) ? ENABLE : DISABLE; macconf->ZeroQuantaPause = ((READ_BIT(heth->Instance->MACFCR, ETH_MACFCR_ZQPD) >> 7) == 0U) ? ENABLE : DISABLE; @@ -2226,7 +2240,7 @@ HAL_StatusTypeDef HAL_ETH_GetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTyp * the configuration of the ETH DMA. * @retval HAL Status */ -HAL_StatusTypeDef HAL_ETH_GetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf) +HAL_StatusTypeDef HAL_ETH_GetDMAConfig(const ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf) { if (dmaconf == NULL) { @@ -2234,7 +2248,7 @@ HAL_StatusTypeDef HAL_ETH_GetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTyp } dmaconf->DMAArbitration = READ_BIT(heth->Instance->DMABMR, - (ETH_DMAARBITRATION_RXPRIORTX | ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1)); + (ETH_DMAARBITRATION_RXPRIORTX | ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1)); dmaconf->AddressAlignedBeats = ((READ_BIT(heth->Instance->DMABMR, ETH_DMABMR_AAB) >> 25U) > 0U) ? ENABLE : DISABLE; dmaconf->BurstMode = READ_BIT(heth->Instance->DMABMR, ETH_DMABMR_FB | ETH_DMABMR_MB); dmaconf->RxDMABurstLength = READ_BIT(heth->Instance->DMABMR, ETH_DMABMR_RDP); @@ -2331,29 +2345,29 @@ void HAL_ETH_SetMDIOClockRange(ETH_HandleTypeDef *heth) hclk = HAL_RCC_GetHCLKFreq(); /* Set CR bits depending on hclk value */ - if ((hclk >= 20000000U) && (hclk < 35000000U)) + if (hclk < 35000000U) { - /* CSR Clock Range between 20-35 MHz */ + /* CSR Clock Range between 0-35 MHz */ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div16; } - else if ((hclk >= 35000000U) && (hclk < 60000000U)) + else if (hclk < 60000000U) { /* CSR Clock Range between 35-60 MHz */ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div26; } - else if ((hclk >= 60000000U) && (hclk < 100000000U)) + else if (hclk < 100000000U) { /* CSR Clock Range between 60-100 MHz */ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div42; } - else if ((hclk >= 100000000U) && (hclk < 150000000U)) + else if (hclk < 150000000U) { /* CSR Clock Range between 100-150 MHz */ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div62; } - else /* ((hclk >= 150000000)&&(hclk <= 183000000))*/ + else /* (hclk >= 150000000) */ { - /* CSR Clock Range between 150-183 MHz */ + /* CSR Clock >= 150 MHz */ tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div102; } @@ -2410,7 +2424,7 @@ HAL_StatusTypeDef HAL_ETH_SetMACFilterConfig(ETH_HandleTypeDef *heth, const ETH_ * the configuration of the ETH MAC filters. * @retval HAL status */ -HAL_StatusTypeDef HAL_ETH_GetMACFilterConfig(ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig) +HAL_StatusTypeDef HAL_ETH_GetMACFilterConfig(const ETH_HandleTypeDef *heth, ETH_MACFilterConfigTypeDef *pFilterConfig) { if (pFilterConfig == NULL) { @@ -2732,17 +2746,18 @@ static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth) (heth->Instance)->DMAOMR = tmpreg; } -static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *macconf) +static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, const ETH_MACConfigTypeDef *macconf) { uint32_t tmpreg1; /*------------------------ ETHERNET MACCR Configuration --------------------*/ /* Get the ETHERNET MACCR value */ tmpreg1 = (heth->Instance)->MACCR; - /* Clear WD, PCE, PS, TE and RE bits */ + /* Clear CSTF, WD, PCE, PS, TE and RE bits */ tmpreg1 &= ETH_MACCR_CLEAR_MASK; - tmpreg1 |= (uint32_t)(((uint32_t)((macconf->Watchdog == DISABLE) ? 1U : 0U) << 23U) | + tmpreg1 |= (uint32_t)(((uint32_t)macconf->CRCStripTypePacket << 25U) | + ((uint32_t)((macconf->Watchdog == DISABLE) ? 1U : 0U) << 23U) | ((uint32_t)((macconf->Jabber == DISABLE) ? 1U : 0U) << 22U) | (uint32_t)macconf->InterPacketGapVal | ((uint32_t)macconf->CarrierSenseDuringTransmit << 16U) | @@ -2789,7 +2804,7 @@ static void ETH_SetMACConfig(ETH_HandleTypeDef *heth, ETH_MACConfigTypeDef *mac (heth->Instance)->MACFCR = tmpreg1; } -static void ETH_SetDMAConfig(ETH_HandleTypeDef *heth, ETH_DMAConfigTypeDef *dmaconf) +static void ETH_SetDMAConfig(ETH_HandleTypeDef *heth, const ETH_DMAConfigTypeDef *dmaconf) { uint32_t tmpreg1; @@ -2855,6 +2870,7 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth) macDefaultConf.CarrierSenseDuringTransmit = DISABLE; macDefaultConf.ReceiveOwn = ENABLE; macDefaultConf.LoopbackMode = DISABLE; + macDefaultConf.CRCStripTypePacket = ENABLE; macDefaultConf.ChecksumOffload = ENABLE; macDefaultConf.RetryTransmission = DISABLE; macDefaultConf.AutomaticPadCRCStrip = DISABLE; @@ -2893,7 +2909,6 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth) /* DMA default configuration */ ETH_SetDMAConfig(heth, &dmaDefaultConf); } - /** * @brief Configures the selected MAC address. * @param heth pointer to a ETH_HandleTypeDef structure that contains @@ -2998,11 +3013,10 @@ static void ETH_DMARxDescListInit(ETH_HandleTypeDef *heth) dmarxdesc->DESC0 = ETH_DMARXDESC_OWN; /* Set Buffer1 size and Second Address Chained bit */ - dmarxdesc->DESC1 = ETH_DMARXDESC_RCH | ETH_RX_BUF_SIZE; + dmarxdesc->DESC1 = heth->Init.RxBuffLen | ETH_DMARXDESC_RCH; /* Enable Ethernet DMA Rx Descriptor interrupt */ dmarxdesc->DESC1 &= ~ETH_DMARXDESC_DIC; - /* Set Rx descritors addresses */ WRITE_REG(heth->RxDescList.RxDesc[i], (uint32_t)dmarxdesc); @@ -3035,7 +3049,8 @@ static void ETH_DMARxDescListInit(ETH_HandleTypeDef *heth) * @param ItMode: Enable or disable Tx EOT interrept * @retval Status */ -static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, uint32_t ItMode) +static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, const ETH_TxPacketConfigTypeDef *pTxConfig, + uint32_t ItMode) { ETH_TxDescListTypeDef *dmatxdesclist = &heth->TxDescList; uint32_t descidx = dmatxdesclist->CurTxDesc; @@ -3046,6 +3061,7 @@ static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacket ETH_BufferTypeDef *txbuffer = pTxConfig->TxBuffer; uint32_t bd_count = 0; + uint32_t primask_bit; /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ if ((READ_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN) == ETH_DMATXDESC_OWN) @@ -3083,11 +3099,6 @@ static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacket /* Mark it as First Descriptor */ SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_FS); - /* Ensure rest of descriptor is written to RAM before the OWN bit */ - __DMB(); - /* set OWN bit of FIRST descriptor */ - SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN); - /* only if the packet is split into more than one descriptors > 1 */ while (txbuffer->next != NULL) { @@ -3108,9 +3119,6 @@ static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacket /* Get current descriptor address */ dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; - /* Clear the FD bit of new Descriptor */ - CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_FS); - /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ if ((READ_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN) == ETH_DMATXDESC_OWN) || (dmatxdesclist->PacketAddress[descidx] != NULL)) @@ -3135,6 +3143,9 @@ static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacket return HAL_ETH_ERROR_BUSY; } + /* Clear the FD bit of new Descriptor */ + CLEAR_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_FS); + descnbr += 1U; /* Get the next Tx buffer in the list */ @@ -3167,18 +3178,26 @@ static uint32_t ETH_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacket /* Mark it as LAST descriptor */ SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_LS); + + /* Get address of first descriptor */ + dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[firstdescidx]; + /* Ensure rest of descriptor is written to RAM before the OWN bit */ + __DMB(); + /* set OWN bit of FIRST descriptor */ + SET_BIT(dmatxdesc->DESC0, ETH_DMATXDESC_OWN); /* Save the current packet address to expose it to the application */ dmatxdesclist->PacketAddress[descidx] = dmatxdesclist->CurrentPacketAddress; dmatxdesclist->CurTxDesc = descidx; - /* disable the interrupt */ - __disable_irq(); - dmatxdesclist->BuffersInUse += bd_count + 1U; + /* Enter critical section */ + primask_bit = __get_PRIMASK(); + __set_PRIMASK(1); - /* Enable interrupts back */ - __enable_irq(); + dmatxdesclist->BuffersInUse += bd_count + 1U; + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); /* Return function status */ return HAL_ETH_ERROR_NONE; diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_exti.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_exti.c index 89166e265..3e4631229 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_exti.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_exti.c @@ -469,6 +469,9 @@ uint32_t HAL_EXTI_GetPending(EXTI_HandleTypeDef *hexti, uint32_t Edge) uint32_t linepos; uint32_t maskline; + /* Prevent unused argument(s) compilation warning */ + UNUSED(Edge); + /* Check parameters */ assert_param(IS_EXTI_LINE(hexti->Line)); assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); @@ -496,6 +499,9 @@ void HAL_EXTI_ClearPending(EXTI_HandleTypeDef *hexti, uint32_t Edge) { uint32_t maskline; + /* Prevent unused argument(s) compilation warning */ + UNUSED(Edge); + /* Check parameters */ assert_param(IS_EXTI_LINE(hexti->Line)); assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash.c index ab7fcd5c1..39f19f2d1 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash.c @@ -128,8 +128,8 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); */ /** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions - * @brief Programming operation functions - * + * @brief Programming operation functions + * @verbatim =============================================================================== ##### Programming operation functions ##### @@ -164,19 +164,19 @@ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); - if(status == HAL_OK) + if (status == HAL_OK) { - if(TypeProgram == FLASH_TYPEPROGRAM_BYTE) + if (TypeProgram == FLASH_TYPEPROGRAM_BYTE) { /*Program byte (8-bit) at a specified address.*/ FLASH_Program_Byte(Address, (uint8_t) Data); } - else if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) + else if (TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) { /*Program halfword (16-bit) at a specified address.*/ FLASH_Program_HalfWord(Address, (uint16_t) Data); } - else if(TypeProgram == FLASH_TYPEPROGRAM_WORD) + else if (TypeProgram == FLASH_TYPEPROGRAM_WORD) { /*Program word (32-bit) at a specified address.*/ FLASH_Program_Word(Address, (uint32_t) Data); @@ -213,9 +213,6 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u { HAL_StatusTypeDef status = HAL_OK; - /* Process Locked */ - __HAL_LOCK(&pFlash); - /* Check the parameters */ assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); @@ -228,17 +225,17 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM; pFlash.Address = Address; - if(TypeProgram == FLASH_TYPEPROGRAM_BYTE) + if (TypeProgram == FLASH_TYPEPROGRAM_BYTE) { /*Program byte (8-bit) at a specified address.*/ - FLASH_Program_Byte(Address, (uint8_t) Data); + FLASH_Program_Byte(Address, (uint8_t) Data); } - else if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) + else if (TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) { /*Program halfword (16-bit) at a specified address.*/ FLASH_Program_HalfWord(Address, (uint16_t) Data); } - else if(TypeProgram == FLASH_TYPEPROGRAM_WORD) + else if (TypeProgram == FLASH_TYPEPROGRAM_WORD) { /*Program word (32-bit) at a specified address.*/ FLASH_Program_Word(Address, (uint32_t) Data); @@ -262,20 +259,20 @@ void HAL_FLASH_IRQHandler(void) /* Check FLASH operation error flags */ #if defined(FLASH_SR_RDERR) - 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 (__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET) #else - if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ - FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR)) != RESET) + if (__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR)) != RESET) #endif /* FLASH_SR_RDERR */ { - if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE) + if (pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE) { /*return the faulty sector*/ addresstmp = pFlash.Sector; pFlash.Sector = 0xFFFFFFFFU; } - else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) + else if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) { /*return the faulty bank*/ addresstmp = pFlash.Bank; @@ -297,18 +294,18 @@ void HAL_FLASH_IRQHandler(void) } /* Check FLASH End of Operation flag */ - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != RESET) { /* Clear FLASH End of Operation pending bit */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); - if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE) + 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 != 0U) + if (pFlash.NbSectorsToErase != 0U) { addresstmp = pFlash.Sector; /*Indicate user which sector has been erased*/ @@ -327,7 +324,7 @@ void HAL_FLASH_IRQHandler(void) pFlash.ProcedureOnGoing = FLASH_PROC_NONE; /* Flush the caches to be sure of the data consistency */ - FLASH_FlushCaches() ; + FLASH_FlushCaches(); /* FLASH EOP interrupt user callback */ HAL_FLASH_EndOfOperationCallback(addresstmp); @@ -335,11 +332,11 @@ void HAL_FLASH_IRQHandler(void) } else { - if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) + if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) { /* MassErase ended. Return the selected bank */ /* Flush the caches to be sure of the data consistency */ - FLASH_FlushCaches() ; + FLASH_FlushCaches(); /* FLASH EOP interrupt user callback */ HAL_FLASH_EndOfOperationCallback(pFlash.Bank); @@ -354,7 +351,7 @@ void HAL_FLASH_IRQHandler(void) } } - if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE) + if (pFlash.ProcedureOnGoing == FLASH_PROC_NONE) { /* Operation is completed, disable the PG, SER, SNB and MER Bits */ CLEAR_BIT(FLASH->CR, (FLASH_CR_PG | FLASH_CR_SER | FLASH_CR_SNB | FLASH_MER_BIT)); @@ -364,9 +361,6 @@ void HAL_FLASH_IRQHandler(void) /* Disable Error source interrupt */ __HAL_FLASH_DISABLE_IT(FLASH_IT_ERR); - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); } } @@ -410,8 +404,8 @@ __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) */ /** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions - * @brief management functions - * + * @brief management functions + * @verbatim =============================================================================== ##### Peripheral Control functions ##### @@ -432,14 +426,14 @@ HAL_StatusTypeDef HAL_FLASH_Unlock(void) { HAL_StatusTypeDef status = HAL_OK; - if(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET) + if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET) { /* Authorize the FLASH Registers access */ WRITE_REG(FLASH->KEYR, FLASH_KEY1); WRITE_REG(FLASH->KEYR, FLASH_KEY2); /* Verify Flash is unlocked */ - if(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET) + if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET) { status = HAL_ERROR; } @@ -466,7 +460,7 @@ HAL_StatusTypeDef HAL_FLASH_Lock(void) */ HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) { - if((FLASH->OPTCR & FLASH_OPTCR_OPTLOCK) != RESET) + if ((FLASH->OPTCR & FLASH_OPTCR_OPTLOCK) != RESET) { /* Authorizes the Option Byte register programming */ FLASH->OPTKEYR = FLASH_OPT_KEY1; @@ -502,7 +496,7 @@ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS |= FLASH_OPTCR_OPTSTRT; /* Wait for last operation to be completed */ - return(FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE)); + return (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE)); } /** @@ -510,8 +504,8 @@ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) */ /** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief Peripheral Errors functions - * + * @brief Peripheral Errors functions + * @verbatim =============================================================================== ##### Peripheral Errors functions ##### @@ -535,7 +529,7 @@ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) */ uint32_t HAL_FLASH_GetError(void) { - return pFlash.ErrorCode; + return pFlash.ErrorCode; } /** @@ -560,11 +554,11 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) /* Get tick */ tickstart = HAL_GetTick(); - while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != RESET) + while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != RESET) { - if(Timeout != HAL_MAX_DELAY) + if (Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout)) + if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) { return HAL_TIMEOUT; } @@ -578,11 +572,11 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); } #if defined(FLASH_SR_RDERR) - 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 (__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET) #else - if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ - FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR)) != RESET) + if (__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \ + FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR)) != RESET) #endif /* FLASH_SR_RDERR */ { /*Save the error code*/ @@ -618,14 +612,14 @@ static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data) FLASH->CR |= FLASH_CR_PG; /* Program first word */ - *(__IO uint32_t*)Address = (uint32_t)Data; + *(__IO uint32_t *)Address = (uint32_t)Data; /* Barrier to ensure programming is performed in 2 steps, in right order (independently of compiler optimization behavior) */ __ISB(); /* Program second word */ - *(__IO uint32_t*)(Address+4) = (uint32_t)(Data >> 32); + *(__IO uint32_t *)(Address + 4) = (uint32_t)(Data >> 32); } @@ -651,7 +645,7 @@ static void FLASH_Program_Word(uint32_t Address, uint32_t Data) FLASH->CR |= FLASH_PSIZE_WORD; FLASH->CR |= FLASH_CR_PG; - *(__IO uint32_t*)Address = Data; + *(__IO uint32_t *)Address = Data; } /** @@ -676,7 +670,7 @@ static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data) FLASH->CR |= FLASH_PSIZE_HALF_WORD; FLASH->CR |= FLASH_CR_PG; - *(__IO uint16_t*)Address = Data; + *(__IO uint16_t *)Address = Data; } /** @@ -701,7 +695,7 @@ static void FLASH_Program_Byte(uint32_t Address, uint8_t Data) FLASH->CR |= FLASH_PSIZE_BYTE; FLASH->CR |= FLASH_CR_PG; - *(__IO uint8_t*)Address = Data; + *(__IO uint8_t *)Address = Data; } /** @@ -710,23 +704,23 @@ static void FLASH_Program_Byte(uint32_t Address, uint8_t Data) */ static void FLASH_SetErrorCode(void) { - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) != RESET) { - pFlash.ErrorCode |= HAL_FLASH_ERROR_WRP; + pFlash.ErrorCode |= HAL_FLASH_ERROR_WRP; - /* Clear FLASH write protection error pending bit */ - __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR); + /* Clear FLASH write protection error pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR); } - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR) != RESET) { - pFlash.ErrorCode |= HAL_FLASH_ERROR_PGA; + pFlash.ErrorCode |= HAL_FLASH_ERROR_PGA; - /* Clear FLASH Programming alignment error pending bit */ - __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGAERR); + /* Clear FLASH Programming alignment error pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGAERR); } - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGPERR) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGPERR) != RESET) { pFlash.ErrorCode |= HAL_FLASH_ERROR_PGP; @@ -734,7 +728,7 @@ static void FLASH_SetErrorCode(void) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGPERR); } - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGSERR) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGSERR) != RESET) { pFlash.ErrorCode |= HAL_FLASH_ERROR_PGS; @@ -742,7 +736,7 @@ static void FLASH_SetErrorCode(void) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGSERR); } #if defined(FLASH_SR_RDERR) - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_RDERR) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_RDERR) != RESET) { pFlash.ErrorCode |= HAL_FLASH_ERROR_RD; @@ -750,7 +744,7 @@ static void FLASH_SetErrorCode(void) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_RDERR); } #endif /* FLASH_SR_RDERR */ - if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPERR) != RESET) + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPERR) != RESET) { pFlash.ErrorCode |= HAL_FLASH_ERROR_OPERATION; diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash_ex.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash_ex.c index d99eacec3..f919fea57 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash_ex.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_flash_ex.c @@ -133,8 +133,8 @@ extern HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); */ /** @defgroup FLASHEx_Exported_Functions_Group1 Extended IO operation functions - * @brief Extended IO operation functions - * + * @brief Extended IO operation functions + * @verbatim =============================================================================== ##### Extended programming operation functions ##### @@ -232,9 +232,6 @@ 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_FLASH_TYPEERASE(pEraseInit->TypeErase)); diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hash.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hash.c index 5fc5cc9d9..7362dedc4 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hash.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hash.c @@ -123,7 +123,7 @@ (#) HAL in interruption mode (interruptions driven) (##)Due to HASH peripheral hardware design, the peripheral interruption is triggered every 64 bytes. - This is why, for driver implementation simplicity’s sake, user is requested to enter a message the + This is why, for driver implementation simplicity s sake, user is requested to enter a message the length of which is a multiple of 4 bytes. (##) When the message length (in bytes) is not a multiple of words, a specific field exists in HASH_STR @@ -1834,8 +1834,9 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB { uint32_t buffercounter; __IO uint32_t inputaddr = (uint32_t) pInBuffer; + uint32_t tmp; - for (buffercounter = 0U; buffercounter < Size; buffercounter += 4U) + for (buffercounter = 0U; buffercounter < Size / 4U; buffercounter++) { /* Write input data 4 bytes at a time */ HASH->DIN = *(uint32_t *)inputaddr; @@ -1843,8 +1844,16 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB /* If the suspension flag has been raised and if the processing is not about to end, suspend processing */ - if ((hhash->SuspendRequest == HAL_HASH_SUSPEND) && ((buffercounter + 4U) < Size)) + if ((hhash->SuspendRequest == HAL_HASH_SUSPEND) && ((buffercounter * 4 + 4U) < Size)) { + /* wait for flag BUSY not set before Wait for DINIS = 1*/ + if (buffercounter * 4 >= 64U) + { + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, HASH_TIMEOUTVALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + } /* Wait for DINIS = 1, which occurs when 16 32-bit locations are free in the input buffer */ if (__HAL_HASH_GET_FLAG(HASH_FLAG_DINIS)) @@ -1859,14 +1868,14 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB /* Save current reading and writing locations of Input and Output buffers */ hhash->pHashInBuffPtr = (uint8_t *)inputaddr; /* Save the number of bytes that remain to be processed at this point */ - hhash->HashInCount = Size - (buffercounter + 4U); + hhash->HashInCount = Size - (buffercounter * 4 + 4U); } else if ((hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_1) || (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_3)) { /* Save current reading and writing locations of Input and Output buffers */ hhash->pHashKeyBuffPtr = (uint8_t *)inputaddr; /* Save the number of bytes that remain to be processed at this point */ - hhash->HashKeyCount = Size - (buffercounter + 4U); + hhash->HashKeyCount = Size - (buffercounter * 4 + 4U); } else { @@ -1885,6 +1894,52 @@ static HAL_StatusTypeDef HASH_WriteData(HASH_HandleTypeDef *hhash, uint8_t *pInB } /* for(buffercounter = 0; buffercounter < Size; buffercounter+=4) */ /* At this point, all the data have been entered to the Peripheral: exit */ + + if (Size % 4U != 0U) + { + if (hhash->Init.DataType == HASH_DATATYPE_16B) + { + /* Write remaining input data */ + + if (Size % 4U <= 2) + { + HASH->DIN = (uint32_t) * (uint16_t *)inputaddr; + } + if (Size % 4U == 3) + { + HASH->DIN = *(uint32_t *)inputaddr; + } + + } + else if ((hhash->Init.DataType == HASH_DATATYPE_8B) + || (hhash->Init.DataType == HASH_DATATYPE_1B)) /* byte swap or bit swap or */ + { + /* Write remaining input data */ + if (Size % 4U == 1) + { + HASH->DIN = (uint32_t) * (uint8_t *)inputaddr; + } + if (Size % 4U == 2) + { + HASH->DIN = (uint32_t) * (uint16_t *)inputaddr; + } + if (Size % 4U == 3) + { + tmp = *(uint8_t *)inputaddr; + tmp |= *(uint8_t *)(inputaddr + 1U) << 8U ; + tmp |= *(uint8_t *)(inputaddr + 2U) << 16U; + HASH->DIN = tmp; + } + + } + else + { + HASH->DIN = *(uint32_t *)inputaddr; + } + /*hhash->HashInCount += 4U;*/ + } + + return HAL_OK; } @@ -2976,11 +3031,11 @@ HAL_StatusTypeDef HASH_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, HAL_StatusTypeDef status ; HAL_HASH_StateTypeDef State_tmp = hhash->State; -#if defined (HASH_CR_MDMAT) + #if defined (HASH_CR_MDMAT) /* Make sure the input buffer size (in bytes) is a multiple of 4 when MDMAT bit is set (case of multi-buffer HASH processing) */ assert_param(IS_HASH_DMA_MULTIBUFFER_SIZE(Size)); -#endif /* MDMA defined*/ + #endif /* MDMA defined*/ /* If State is ready or suspended, start or resume polling-based HASH processing */ if ((State_tmp == HAL_HASH_STATE_READY) || (State_tmp == HAL_HASH_STATE_SUSPENDED)) { @@ -3475,7 +3530,7 @@ HAL_StatusTypeDef HMAC_Start_DMA(HASH_HandleTypeDef *hhash, uint8_t *pInBuffer, /* Enable the DMA In DMA stream */ status = HAL_DMA_Start_IT(hhash->hdmain, inputaddr, (uint32_t)&HASH->DIN, \ (((inputSize % 4U) != 0U) ? ((inputSize + (4U - (inputSize % 4U))) / 4U) \ - : (inputSize / 4U))); + : (inputSize / 4U))); /* Enable DMA requests */ SET_BIT(HASH->CR, HASH_CR_DMAE); diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hcd.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hcd.c index 7ab122272..37afce8ba 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hcd.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_hcd.c @@ -1720,6 +1720,12 @@ static void HCD_HC_OUT_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) else { hhcd->hc[chnum].urb_state = URB_NOTREADY; + + /* Re-activate the channel */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; } } __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR); diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s.c index 700a0cae4..b2fce81a5 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s.c @@ -848,15 +848,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uin return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -967,15 +966,14 @@ HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1065,15 +1063,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1092,6 +1089,8 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, hi2s->TxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable TXE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); @@ -1102,7 +1101,6 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1131,15 +1129,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1158,6 +1155,8 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u hi2s->RxXferCount = Size; } + __HAL_UNLOCK(hi2s); + /* Enable RXNE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); @@ -1168,7 +1167,6 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u __HAL_I2S_ENABLE(hi2s); } - __HAL_UNLOCK(hi2s); return HAL_OK; } @@ -1195,15 +1193,14 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_TX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1245,12 +1242,7 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Tx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_TXDMAEN)) @@ -1259,7 +1251,13 @@ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } @@ -1286,15 +1284,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Process Locked */ - __HAL_LOCK(hi2s); - if (hi2s->State != HAL_I2S_STATE_READY) { - __HAL_UNLOCK(hi2s); return HAL_BUSY; } + /* Process Locked */ + __HAL_LOCK(hi2s); + /* Set state and reset error code */ hi2s->State = HAL_I2S_STATE_BUSY_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; @@ -1342,12 +1339,7 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, return HAL_ERROR; } - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } + __HAL_UNLOCK(hi2s); /* Check if the I2S Rx request is already enabled */ if (HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_RXDMAEN)) @@ -1356,7 +1348,13 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } - __HAL_UNLOCK(hi2s); + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + return HAL_OK; } diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s_ex.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s_ex.c index 643bf74d1..823a8cc5c 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s_ex.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_i2s_ex.c @@ -210,17 +210,15 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, uint32_t Timeout) { uint32_t tmp1 = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; if (hi2s->State != HAL_I2S_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - return HAL_ERROR; + return HAL_ERROR; } /* Process Locked */ @@ -281,8 +279,11 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, { /* Set the error code */ SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - errorcode = HAL_ERROR; - goto error; + hi2s->State = HAL_I2S_STATE_READY; + + /* Process UnLock */ + __HAL_UNLOCK(hi2s); + return HAL_ERROR; } /* Write Data on DR register */ hi2s->Instance->DR = (*pTxData++); @@ -305,8 +306,11 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, { /* Set the error code */ SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - errorcode = HAL_ERROR; - goto error; + hi2s->State = HAL_I2S_STATE_READY; + + /* Process UnLock */ + __HAL_UNLOCK(hi2s); + return HAL_ERROR; } /* Read Data from DR register */ (*pRxData++) = I2SxEXT(hi2s->Instance)->DR; @@ -354,8 +358,11 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, { /* Set the error code */ SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - errorcode = HAL_ERROR; - goto error; + hi2s->State = HAL_I2S_STATE_READY; + + /* Process UnLock */ + __HAL_UNLOCK(hi2s); + return HAL_ERROR; } /* Write Data on DR register */ I2SxEXT(hi2s->Instance)->DR = (*pTxData++); @@ -378,8 +385,11 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, { /* Set the error code */ SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - errorcode = HAL_ERROR; - goto error; + hi2s->State = HAL_I2S_STATE_READY; + + /* Process UnLock */ + __HAL_UNLOCK(hi2s); + return HAL_ERROR; } /* Read Data from DR register */ (*pRxData++) = hi2s->Instance->DR; @@ -398,15 +408,17 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, } } + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + if (hi2s->ErrorCode != HAL_I2S_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; + } + else + { + return HAL_OK; } - -error : - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return errorcode; } /** @@ -430,12 +442,10 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, uint16_t Size) { uint32_t tmp1 = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; if (hi2s->State != HAL_I2S_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) @@ -510,15 +520,14 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, } } + __HAL_UNLOCK(hi2s); /* Enable I2Sext peripheral */ __HAL_I2SEXT_ENABLE(hi2s); /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); -error : - __HAL_UNLOCK(hi2s); - return errorcode; + return HAL_OK; } /** @@ -543,12 +552,10 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, { uint32_t *tmp = NULL; uint32_t tmp1 = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; if (hi2s->State != HAL_I2S_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) @@ -620,16 +627,6 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, /* Enable Tx DMA Request */ SET_BIT(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 */ - __HAL_I2SEXT_ENABLE(hi2s); - - /* Enable I2S peripheral after the I2Sext */ - __HAL_I2S_ENABLE(hi2s); - } } else { @@ -653,20 +650,19 @@ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, /* Enable Rx DMA Request */ SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) - { - /* Enable I2Sext(transmitter) before enabling I2Sx peripheral */ - __HAL_I2SEXT_ENABLE(hi2s); - /* Enable I2S peripheral before the I2Sext */ - __HAL_I2S_ENABLE(hi2s); - } } -error : __HAL_UNLOCK(hi2s); - return errorcode; + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2Sext(transmitter) before enabling I2Sx peripheral */ + __HAL_I2SEXT_ENABLE(hi2s); + /* Enable I2S peripheral before the I2Sext */ + __HAL_I2S_ENABLE(hi2s); + } + + return HAL_OK; } /** diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_pcd.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_pcd.c index fa50ea186..d53e0b1c5 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_pcd.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_pcd.c @@ -1814,7 +1814,7 @@ HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address) 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; + HAL_StatusTypeDef ret = HAL_OK; PCD_EPTypeDef *ep; if ((ep_addr & 0x80U) == 0x80U) @@ -1829,7 +1829,7 @@ HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, } ep->num = ep_addr & EP_ADDR_MSK; - ep->maxpacket = ep_mps; + ep->maxpacket = (uint32_t)ep_mps & 0x7FFU; ep->type = ep_type; if (ep->is_in != 0U) @@ -2379,13 +2379,11 @@ static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint } #endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ - /** * @} */ #endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ #endif /* HAL_PCD_MODULE_ENABLED */ - /** * @} */ diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_qspi.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_qspi.c index 508f0b6d8..5256d18ec 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_qspi.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_qspi.c @@ -2321,7 +2321,7 @@ HAL_StatusTypeDef HAL_QSPI_UnRegisterCallback (QSPI_HandleTypeDef *hqspi, HAL_QS * @param hqspi QSPI handle * @retval HAL state */ -HAL_QSPI_StateTypeDef HAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi) +HAL_QSPI_StateTypeDef HAL_QSPI_GetState(const QSPI_HandleTypeDef *hqspi) { /* Return QSPI handle state */ return hqspi->State; @@ -2332,7 +2332,7 @@ HAL_QSPI_StateTypeDef HAL_QSPI_GetState(QSPI_HandleTypeDef *hqspi) * @param hqspi QSPI handle * @retval QSPI Error Code */ -uint32_t HAL_QSPI_GetError(QSPI_HandleTypeDef *hqspi) +uint32_t HAL_QSPI_GetError(const QSPI_HandleTypeDef *hqspi) { return hqspi->ErrorCode; } @@ -2512,7 +2512,7 @@ HAL_StatusTypeDef HAL_QSPI_SetFifoThreshold(QSPI_HandleTypeDef *hqspi, uint32_t * @param hqspi QSPI handle. * @retval Fifo threshold (value between 1 and 16) */ -uint32_t HAL_QSPI_GetFifoThreshold(QSPI_HandleTypeDef *hqspi) +uint32_t HAL_QSPI_GetFifoThreshold(const QSPI_HandleTypeDef *hqspi) { return ((READ_BIT(hqspi->Instance->CR, QUADSPI_CR_FTHRES) >> QUADSPI_CR_FTHRES_Pos) + 1U); } @@ -2799,6 +2799,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->AlternateBytesSize | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | cmd->Instruction | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } else @@ -2826,6 +2829,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | cmd->Instruction | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } } @@ -2860,6 +2866,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) | cmd->AlternateBytesSize | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } else @@ -2889,6 +2898,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } } diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc.c index 8e494e630..c04d33a6d 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc.c @@ -110,8 +110,8 @@ */ /** @defgroup RCC_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### @@ -218,10 +218,10 @@ __weak HAL_StatusTypeDef HAL_RCC_DeInit(void) */ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { - uint32_t tickstart, pll_config; - + uint32_t tickstart; + uint32_t pll_config; /* Check Null pointer */ - if(RCC_OscInitStruct == NULL) + if (RCC_OscInitStruct == NULL) { return HAL_ERROR; } @@ -229,15 +229,15 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc /* Check the parameters */ assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType)); /*------------------------------- HSE Configuration ------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) + 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_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_OFF)) + if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) && (RCC_OscInitStruct->HSEState == RCC_HSE_OFF)) { return HAL_ERROR; } @@ -248,15 +248,15 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc __HAL_RCC_HSE_CONFIG(RCC_OscInitStruct->HSEState); /* Check the HSE State */ - if((RCC_OscInitStruct->HSEState) != RCC_HSE_OFF) + if ((RCC_OscInitStruct->HSEState) != RCC_HSE_OFF) { /* Get Start Tick */ tickstart = HAL_GetTick(); /* Wait till HSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -268,9 +268,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till HSE is bypassed or disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) { - if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -279,18 +279,18 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc } } /*----------------------------- HSI Configuration --------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) + 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)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - 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_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI) || \ + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSI))) { /* When HSI is used as system clock it will not disabled */ - if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) + if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; } @@ -304,7 +304,7 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc else { /* Check the HSI State */ - if((RCC_OscInitStruct->HSIState)!= RCC_HSI_OFF) + if ((RCC_OscInitStruct->HSIState) != RCC_HSI_OFF) { /* Enable the Internal High Speed oscillator (HSI). */ __HAL_RCC_HSI_ENABLE(); @@ -313,9 +313,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till HSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -333,9 +333,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till HSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -344,13 +344,13 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc } } /*------------------------------ LSI Configuration -------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) + 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) + if ((RCC_OscInitStruct->LSIState) != RCC_LSI_OFF) { /* Enable the Internal Low Speed oscillator (LSI). */ __HAL_RCC_LSI_ENABLE(); @@ -359,9 +359,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till LSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -376,9 +376,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till LSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -386,7 +386,7 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc } } /*------------------------------ LSE Configuration -------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) + if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) { FlagStatus pwrclkchanged = RESET; @@ -395,13 +395,13 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc /* Update LSE configuration in Backup Domain control register */ /* Requires to enable write access to Backup Domain of necessary */ - if(__HAL_RCC_PWR_IS_CLK_DISABLED()) + if (__HAL_RCC_PWR_IS_CLK_DISABLED()) { __HAL_RCC_PWR_CLK_ENABLE(); pwrclkchanged = SET; } - if(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + if (HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) { /* Enable write access to Backup domain */ SET_BIT(PWR->CR, PWR_CR_DBP); @@ -409,9 +409,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc /* Wait for Backup domain Write protection disable */ tickstart = HAL_GetTick(); - while(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + while (HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) { - if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -421,15 +421,15 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc /* Set the new LSE configuration -----------------------------------------*/ __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState); /* Check the LSE State */ - if((RCC_OscInitStruct->LSEState) != RCC_LSE_OFF) + if ((RCC_OscInitStruct->LSEState) != RCC_LSE_OFF) { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -441,9 +441,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -451,7 +451,7 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc } /* Restore clock configuration if changed */ - if(pwrclkchanged == SET) + if (pwrclkchanged == SET) { __HAL_RCC_PWR_CLK_DISABLE(); } @@ -462,9 +462,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc 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 (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) { - if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) + if ((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) { /* Check the parameters */ assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource)); @@ -480,9 +480,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till PLL is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -501,9 +501,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till PLL is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -518,9 +518,9 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc tickstart = HAL_GetTick(); /* Wait till PLL is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -530,7 +530,7 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc else { /* Check if there is a request to disable the PLL used as System clock source */ - if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_OFF) + if ((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_OFF) { return HAL_ERROR; } @@ -553,7 +553,7 @@ __weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc (READ_BIT(pll_config, RCC_PLLCFGR_PLLN) != (RCC_OscInitStruct->PLL.PLLN) << RCC_PLLCFGR_PLLN_Pos) || (READ_BIT(pll_config, RCC_PLLCFGR_PLLP) != (((RCC_OscInitStruct->PLL.PLLP >> 1U) - 1U)) << RCC_PLLCFGR_PLLP_Pos) || (READ_BIT(pll_config, RCC_PLLCFGR_PLLQ) != (RCC_OscInitStruct->PLL.PLLQ << RCC_PLLCFGR_PLLQ_Pos))) -#endif +#endif /* RCC_PLLCFGR_PLLR */ { return HAL_ERROR; } @@ -593,7 +593,7 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui uint32_t tickstart; /* Check Null pointer */ - if(RCC_ClkInitStruct == NULL) + if (RCC_ClkInitStruct == NULL) { return HAL_ERROR; } @@ -607,30 +607,30 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui (HCLK) and the supply voltage of the device. */ /* Increasing the number of wait states because of higher CPU frequency */ - if(FLatency > __HAL_FLASH_GET_LATENCY()) + if (FLatency > __HAL_FLASH_GET_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(__HAL_FLASH_GET_LATENCY() != FLatency) + if (__HAL_FLASH_GET_LATENCY() != FLatency) { return HAL_ERROR; } } /*-------------------------- HCLK Configuration --------------------------*/ - if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) + if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) { /* Set the highest APBx dividers in order to ensure that we do not go through a non-spec phase whatever we decrease or increase HCLK. */ - if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) + if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_HCLK_DIV16); } - if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) + if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, (RCC_HCLK_DIV16 << 3)); } @@ -640,25 +640,25 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui } /*------------------------- SYSCLK Configuration ---------------------------*/ - if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) + 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) + if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) { /* Check the HSE ready flag */ - if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + 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) || - (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLRCLK)) + else if ((RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) || + (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLRCLK)) { /* Check the PLL ready flag */ - if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + if (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) { return HAL_ERROR; } @@ -667,7 +667,7 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui else { /* Check the HSI ready flag */ - if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) { return HAL_ERROR; } @@ -688,38 +688,38 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui } /* Decreasing the number of wait states because of lower CPU frequency */ - if(FLatency < __HAL_FLASH_GET_LATENCY()) + if (FLatency < __HAL_FLASH_GET_LATENCY()) { - /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ + /* 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(__HAL_FLASH_GET_LATENCY() != FLatency) + if (__HAL_FLASH_GET_LATENCY() != FLatency) { return HAL_ERROR; } } /*-------------------------- PCLK1 Configuration ---------------------------*/ - if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) + 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) + 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) << 3U)); } /* Update the SystemCoreClock global variable */ - SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE)>> RCC_CFGR_HPRE_Pos]; + SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos]; /* Configure the source of time base considering new system clocks settings */ - HAL_InitTick (uwTickPrio); + HAL_InitTick(uwTickPrio); return HAL_OK; } @@ -729,8 +729,8 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui */ /** @defgroup RCC_Exported_Functions_Group2 Peripheral Control functions - * @brief RCC clocks control functions - * + * @brief RCC clocks control functions + * @verbatim =============================================================================== ##### Peripheral Control functions ##### @@ -779,7 +779,7 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M assert_param(IS_RCC_MCO(RCC_MCOx)); assert_param(IS_RCC_MCODIV(RCC_MCODiv)); /* RCC_MCO1 */ - if(RCC_MCOx == RCC_MCO1) + if (RCC_MCOx == RCC_MCO1) { assert_param(IS_RCC_MCO1SOURCE(RCC_MCOSource)); @@ -797,7 +797,7 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M /* 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)); - /* This RCC MCO1 enable feature is available only on STM32F410xx devices */ + /* This RCC MCO1 enable feature is available only on STM32F410xx devices */ #if defined(RCC_CFGR_MCO1EN) __HAL_RCC_MCO1_ENABLE(); #endif /* RCC_CFGR_MCO1EN */ @@ -821,7 +821,7 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M /* 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 << 3U))); - /* This RCC MCO2 enable feature is available only on STM32F410Rx devices */ + /* This RCC MCO2 enable feature is available only on STM32F410Rx devices */ #if defined(RCC_CFGR_MCO2EN) __HAL_RCC_MCO2_ENABLE(); #endif /* RCC_CFGR_MCO2EN */ @@ -884,7 +884,9 @@ void HAL_RCC_DisableCSS(void) */ __weak uint32_t HAL_RCC_GetSysClockFreq(void) { - uint32_t pllm = 0U, pllvco = 0U, pllp = 0U; + uint32_t pllm = 0U; + uint32_t pllvco = 0U; + uint32_t pllp = 0U; uint32_t sysclockfreq = 0U; /* Get SYSCLK source -------------------------------------------------------*/ @@ -893,7 +895,7 @@ __weak uint32_t HAL_RCC_GetSysClockFreq(void) case RCC_CFGR_SWS_HSI: /* HSI used as system clock source */ { sysclockfreq = HSI_VALUE; - break; + break; } case RCC_CFGR_SWS_HSE: /* HSE used as system clock source */ { @@ -905,19 +907,19 @@ __weak uint32_t HAL_RCC_GetSysClockFreq(void) /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN SYSCLK = PLL_VCO / PLLP */ pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; - if(__HAL_RCC_GET_PLL_OSCSOURCE() != RCC_PLLSOURCE_HSI) + if (__HAL_RCC_GET_PLL_OSCSOURCE() != RCC_PLLSOURCE_HSI) { /* HSE used as PLL clock source */ - pllvco = (uint32_t) ((((uint64_t) HSE_VALUE * ((uint64_t) ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); + pllvco = (uint32_t)((((uint64_t) HSE_VALUE * ((uint64_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); } else { /* HSI used as PLL clock source */ - pllvco = (uint32_t) ((((uint64_t) HSI_VALUE * ((uint64_t) ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); + pllvco = (uint32_t)((((uint64_t) HSI_VALUE * ((uint64_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); } - pllp = ((((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> RCC_PLLCFGR_PLLP_Pos) + 1U) *2U); + pllp = ((((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> RCC_PLLCFGR_PLLP_Pos) + 1U) * 2U); - sysclockfreq = pllvco/pllp; + sysclockfreq = pllvco / pllp; break; } default: @@ -952,7 +954,7 @@ uint32_t HAL_RCC_GetHCLKFreq(void) uint32_t HAL_RCC_GetPCLK1Freq(void) { /* Get HCLK source and Compute PCLK1 frequency ---------------------------*/ - return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1)>> RCC_CFGR_PPRE1_Pos]); + return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos]); } /** @@ -964,7 +966,7 @@ uint32_t HAL_RCC_GetPCLK1Freq(void) uint32_t HAL_RCC_GetPCLK2Freq(void) { /* Get HCLK source and Compute PCLK2 frequency ---------------------------*/ - return (HAL_RCC_GetHCLKFreq()>> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2)>> RCC_CFGR_PPRE2_Pos]); + return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos]); } /** @@ -980,11 +982,11 @@ __weak void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) 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) + 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) + else if ((RCC->CR & RCC_CR_HSEON) == RCC_CR_HSEON) { RCC_OscInitStruct->HSEState = RCC_HSE_ON; } @@ -994,7 +996,7 @@ __weak void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Get the HSI configuration -----------------------------------------------*/ - if((RCC->CR &RCC_CR_HSION) == RCC_CR_HSION) + if ((RCC->CR & RCC_CR_HSION) == RCC_CR_HSION) { RCC_OscInitStruct->HSIState = RCC_HSI_ON; } @@ -1003,14 +1005,14 @@ __weak void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) RCC_OscInitStruct->HSIState = RCC_HSI_OFF; } - RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR &RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos); + RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR & RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos); /* Get the LSE configuration -----------------------------------------------*/ - if((RCC->BDCR &RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP) + 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) + else if ((RCC->BDCR & RCC_BDCR_LSEON) == RCC_BDCR_LSEON) { RCC_OscInitStruct->LSEState = RCC_LSE_ON; } @@ -1020,7 +1022,7 @@ __weak void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Get the LSI configuration -----------------------------------------------*/ - if((RCC->CSR &RCC_CSR_LSION) == RCC_CSR_LSION) + if ((RCC->CSR & RCC_CSR_LSION) == RCC_CSR_LSION) { RCC_OscInitStruct->LSIState = RCC_LSI_ON; } @@ -1030,7 +1032,7 @@ __weak void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Get the PLL configuration -----------------------------------------------*/ - if((RCC->CR &RCC_CR_PLLON) == RCC_CR_PLLON) + if ((RCC->CR & RCC_CR_PLLON) == RCC_CR_PLLON) { RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON; } @@ -1082,7 +1084,7 @@ void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pF void HAL_RCC_NMI_IRQHandler(void) { /* Check RCC CSSF flag */ - if(__HAL_RCC_GET_IT(RCC_IT_CSS)) + if (__HAL_RCC_GET_IT(RCC_IT_CSS)) { /* RCC Clock Security System interrupt user callback */ HAL_RCC_CSSCallback(); diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc_ex.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc_ex.c index 0250aa722..7b3b20bbd 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc_ex.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_rcc_ex.c @@ -50,8 +50,8 @@ */ /** @defgroup RCCEx_Exported_Functions_Group1 Extended Peripheral Control functions - * @brief Extended Peripheral Control functions - * + * @brief Extended Peripheral Control functions + * @verbatim =============================================================================== ##### Extended Peripheral Control functions ##### @@ -100,7 +100,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); /*------------------------ I2S APB1 configuration --------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == (RCC_PERIPHCLK_I2S_APB1)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == (RCC_PERIPHCLK_I2S_APB1)) { /* Check the parameters */ assert_param(IS_RCC_I2SAPB1CLKSOURCE(PeriphClkInit->I2sApb1ClockSelection)); @@ -108,7 +108,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure I2S Clock source */ __HAL_RCC_I2S_APB1_CONFIG(PeriphClkInit->I2sApb1ClockSelection); /* Enable the PLLI2S when it's used as clock source for I2S */ - if(PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S) + if (PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S) { plli2sused = 1U; } @@ -116,7 +116,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- I2S APB2 configuration ----------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == (RCC_PERIPHCLK_I2S_APB2)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == (RCC_PERIPHCLK_I2S_APB2)) { /* Check the parameters */ assert_param(IS_RCC_I2SAPB2CLKSOURCE(PeriphClkInit->I2sApb2ClockSelection)); @@ -124,7 +124,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure I2S Clock source */ __HAL_RCC_I2S_APB2_CONFIG(PeriphClkInit->I2sApb2ClockSelection); /* Enable the PLLI2S when it's used as clock source for I2S */ - if(PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S) + if (PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S) { plli2sused = 1U; } @@ -132,7 +132,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*--------------------------- SAI1 configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == (RCC_PERIPHCLK_SAI1)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == (RCC_PERIPHCLK_SAI1)) { /* Check the parameters */ assert_param(IS_RCC_SAI1CLKSOURCE(PeriphClkInit->Sai1ClockSelection)); @@ -140,12 +140,12 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure SAI1 Clock source */ __HAL_RCC_SAI1_CONFIG(PeriphClkInit->Sai1ClockSelection); /* Enable the PLLI2S when it's used as clock source for SAI */ - if(PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLI2S) + if (PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLI2S) { plli2sused = 1U; } /* Enable the PLLSAI when it's used as clock source for SAI */ - if(PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLSAI) + if (PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLSAI) { pllsaiused = 1U; } @@ -153,7 +153,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*-------------------------- SAI2 configuration ----------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == (RCC_PERIPHCLK_SAI2)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == (RCC_PERIPHCLK_SAI2)) { /* Check the parameters */ assert_param(IS_RCC_SAI2CLKSOURCE(PeriphClkInit->Sai2ClockSelection)); @@ -162,12 +162,12 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_SAI2_CONFIG(PeriphClkInit->Sai2ClockSelection); /* Enable the PLLI2S when it's used as clock source for SAI */ - if(PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLI2S) + if (PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLI2S) { plli2sused = 1U; } /* Enable the PLLSAI when it's used as clock source for SAI */ - if(PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLSAI) + if (PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLSAI) { pllsaiused = 1U; } @@ -175,7 +175,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*----------------------------- RTC configuration --------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) { /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); @@ -189,16 +189,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); - while((PWR->CR & PWR_CR_DBP) == RESET) + while ((PWR->CR & PWR_CR_DBP) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ tmpreg1 = (RCC->BDCR & RCC_BDCR_RTCSEL); - if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) + if ((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpreg1 = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); @@ -209,15 +209,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk RCC->BDCR = tmpreg1; /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ - if(HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) + if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -229,7 +229,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- TIM configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) { /* Configure Timer Prescaler */ __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection); @@ -237,7 +237,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- FMPI2C1 Configuration -----------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FMPI2C1) == RCC_PERIPHCLK_FMPI2C1) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FMPI2C1) == RCC_PERIPHCLK_FMPI2C1) { /* Check the parameters */ assert_param(IS_RCC_FMPI2C1CLKSOURCE(PeriphClkInit->Fmpi2c1ClockSelection)); @@ -248,7 +248,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------ CEC Configuration -------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CEC) == RCC_PERIPHCLK_CEC) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CEC) == RCC_PERIPHCLK_CEC) { /* Check the parameters */ assert_param(IS_RCC_CECCLKSOURCE(PeriphClkInit->CecClockSelection)); @@ -259,7 +259,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*----------------------------- CLK48 Configuration ------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) { /* Check the parameters */ assert_param(IS_RCC_CLK48CLKSOURCE(PeriphClkInit->Clk48ClockSelection)); @@ -268,7 +268,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_CLK48_CONFIG(PeriphClkInit->Clk48ClockSelection); /* Enable the PLLSAI when it's used as clock source for CLK48 */ - if(PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP) + if (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP) { pllsaiused = 1U; } @@ -276,7 +276,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*----------------------------- SDIO Configuration -------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) { /* Check the parameters */ assert_param(IS_RCC_SDIOCLKSOURCE(PeriphClkInit->SdioClockSelection)); @@ -287,7 +287,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------ SPDIFRX Configuration ---------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPDIFRX) == RCC_PERIPHCLK_SPDIFRX) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPDIFRX) == RCC_PERIPHCLK_SPDIFRX) { /* Check the parameters */ assert_param(IS_RCC_SPDIFRXCLKSOURCE(PeriphClkInit->SpdifClockSelection)); @@ -295,7 +295,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the SPDIFRX clock source */ __HAL_RCC_SPDIFRX_CONFIG(PeriphClkInit->SpdifClockSelection); /* Enable the PLLI2S when it's used as clock source for SPDIFRX */ - if(PeriphClkInit->SpdifClockSelection == RCC_SPDIFRXCLKSOURCE_PLLI2SP) + if (PeriphClkInit->SpdifClockSelection == RCC_SPDIFRXCLKSOURCE_PLLI2SP) { plli2sused = 1U; } @@ -305,16 +305,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*---------------------------- PLLI2S Configuration ------------------------*/ /* PLLI2S is configured when a peripheral will use it as source clock : SAI1, SAI2, I2S on APB1, I2S on APB2 or SPDIFRX */ - if((plli2sused == 1U) || (PeriphClkInit->PeriphClockSelection == RCC_PERIPHCLK_PLLI2S)) + if ((plli2sused == 1U) || (PeriphClkInit->PeriphClockSelection == RCC_PERIPHCLK_PLLI2S)) { /* Disable the PLLI2S */ __HAL_RCC_PLLI2S_DISABLE(); /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -326,8 +326,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PLLI2SN_VALUE(PeriphClkInit->PLLI2S.PLLI2SN)); /*------ In Case of PLLI2S is selected as source clock for I2S -----------*/ - if(((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == RCC_PERIPHCLK_I2S_APB1) && (PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == RCC_PERIPHCLK_I2S_APB2) && (PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S))) + if (((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == RCC_PERIPHCLK_I2S_APB1) + && (PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == RCC_PERIPHCLK_I2S_APB2) && (PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S))) { /* check for Parameters */ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); @@ -338,12 +339,14 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLI2S division factors */ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLLI2SN/PLLI2SM) */ /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SR */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN , plli2sp, plli2sq, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, plli2sp, plli2sq, + PeriphClkInit->PLLI2S.PLLI2SR); } /*------- In Case of PLLI2S is selected as source clock for SAI ----------*/ - if(((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1) && (PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLI2S)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == RCC_PERIPHCLK_SAI2) && (PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLI2S))) + if (((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1) + && (PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLI2S)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == RCC_PERIPHCLK_SAI2) && (PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLI2S))) { /* Check for PLLI2S Parameters */ assert_param(IS_RCC_PLLI2SQ_VALUE(PeriphClkInit->PLLI2S.PLLI2SQ)); @@ -357,14 +360,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ /* SAI_CLK(first level) = PLLI2S_VCO Output/PLLI2SQ */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN , plli2sp, PeriphClkInit->PLLI2S.PLLI2SQ, plli2sr); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, plli2sp, + PeriphClkInit->PLLI2S.PLLI2SQ, plli2sr); /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVQ */ __HAL_RCC_PLLI2S_PLLSAICLKDIVQ_CONFIG(PeriphClkInit->PLLI2SDivQ); } /*------ In Case of PLLI2S is selected as source clock for SPDIFRX -------*/ - if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPDIFRX) == RCC_PERIPHCLK_SPDIFRX) && (PeriphClkInit->SpdifClockSelection == RCC_SPDIFRXCLKSOURCE_PLLI2SP)) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SPDIFRX) == RCC_PERIPHCLK_SPDIFRX) + && (PeriphClkInit->SpdifClockSelection == RCC_SPDIFRXCLKSOURCE_PLLI2SP)) { /* check for Parameters */ assert_param(IS_RCC_PLLI2SP_VALUE(PeriphClkInit->PLLI2S.PLLI2SP)); @@ -374,11 +379,12 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLI2S division factors */ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLLI2SN/PLLI2SM) */ /* SPDIFRXCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SP */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SP, plli2sq, plli2sr); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SP, + plli2sq, plli2sr); } - /*----------------- In Case of PLLI2S is just selected -----------------*/ - if((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) + /*----------------- In Case of PLLI2S is just selected -----------------*/ + if ((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) { /* Check for Parameters */ assert_param(IS_RCC_PLLI2SP_VALUE(PeriphClkInit->PLLI2S.PLLI2SP)); @@ -387,7 +393,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLI2S division factors */ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLLI2SN/PLLI2SM) */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SP, PeriphClkInit->PLLI2S.PLLI2SQ, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SP, + PeriphClkInit->PLLI2S.PLLI2SQ, PeriphClkInit->PLLI2S.PLLI2SR); } /* Enable the PLLI2S */ @@ -395,9 +402,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -408,16 +415,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*----------------------------- PLLSAI Configuration -----------------------*/ /* PLLSAI is configured when a peripheral will use it as source clock : SAI1, SAI2, CLK48 or SDIO */ - if(pllsaiused == 1U) + if (pllsaiused == 1U) { /* Disable PLLSAI Clock */ __HAL_RCC_PLLSAI_DISABLE(); /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLSAI is disabled */ - while(__HAL_RCC_PLLSAI_GET_FLAG() != RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() != RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -429,8 +436,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PLLSAIN_VALUE(PeriphClkInit->PLLSAI.PLLSAIN)); /*------ In Case of PLLSAI is selected as source clock for SAI -----------*/ - if(((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1) && (PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLSAI)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == RCC_PERIPHCLK_SAI2) && (PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLSAI))) + if (((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1) + && (PeriphClkInit->Sai1ClockSelection == RCC_SAI1CLKSOURCE_PLLSAI)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI2) == RCC_PERIPHCLK_SAI2) && (PeriphClkInit->Sai2ClockSelection == RCC_SAI2CLKSOURCE_PLLSAI))) { /* check for PLLSAIQ Parameter */ assert_param(IS_RCC_PLLSAIQ_VALUE(PeriphClkInit->PLLSAI.PLLSAIQ)); @@ -442,7 +450,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* 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.PLLSAIM, PeriphClkInit->PLLSAI.PLLSAIN , pllsaip, PeriphClkInit->PLLSAI.PLLSAIQ, 0U); + __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIM, PeriphClkInit->PLLSAI.PLLSAIN, pllsaip, + PeriphClkInit->PLLSAI.PLLSAIQ, 0U); /* SAI_CLK_x = SAI_CLK(first level)/PLLSAIDIVQ */ __HAL_RCC_PLLSAI_PLLSAICLKDIVQ_CONFIG(PeriphClkInit->PLLSAIDivQ); @@ -450,7 +459,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*------ In Case of PLLSAI is selected as source clock for CLK48 ---------*/ /* In Case of PLLI2S is selected as source clock for CLK48 */ - if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) && (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP)) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) + && (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP)) { /* check for Parameters */ assert_param(IS_RCC_PLLSAIP_VALUE(PeriphClkInit->PLLSAI.PLLSAIP)); @@ -459,7 +469,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLSAI division factors */ /* PLLSAI_VCO = f(VCO clock) = f(PLLSAI clock input) * (PLLI2SN/PLLSAIM) */ /* 48CLK = f(PLLSAI clock output) = f(VCO clock) / PLLSAIP */ - __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIM, PeriphClkInit->PLLSAI.PLLSAIN , PeriphClkInit->PLLSAI.PLLSAIP, pllsaiq, 0U); + __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIM, PeriphClkInit->PLLSAI.PLLSAIN, PeriphClkInit->PLLSAI.PLLSAIP, + pllsaiq, 0U); } /* Enable PLLSAI Clock */ @@ -467,9 +478,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLSAI is ready */ - while(__HAL_RCC_PLLSAI_GET_FLAG() == RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() == RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -491,11 +502,11 @@ 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_APB1 | RCC_PERIPHCLK_I2S_APB2 |\ - RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_SAI2 |\ - RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC |\ - RCC_PERIPHCLK_CEC | RCC_PERIPHCLK_FMPI2C1 |\ - RCC_PERIPHCLK_CLK48 | RCC_PERIPHCLK_SDIO |\ + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S_APB1 | RCC_PERIPHCLK_I2S_APB2 | \ + RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_SAI2 | \ + RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_CEC | RCC_PERIPHCLK_FMPI2C1 | \ + RCC_PERIPHCLK_CLK48 | RCC_PERIPHCLK_SDIO | \ RCC_PERIPHCLK_SPDIFRX; /* Get the PLLI2S Clock configuration --------------------------------------*/ @@ -580,18 +591,18 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) uint32_t vcooutput = 0U; switch (PeriphClk) { - case RCC_PERIPHCLK_SAI1: - case RCC_PERIPHCLK_SAI2: + case RCC_PERIPHCLK_SAI1: + case RCC_PERIPHCLK_SAI2: { saiclocksource = RCC->DCKCFGR; saiclocksource &= (RCC_DCKCFGR_SAI1SRC | RCC_DCKCFGR_SAI2SRC); switch (saiclocksource) { - case 0U: /* PLLSAI is the clock source for SAI*/ + case 0U: /* PLLSAI is the clock source for SAI*/ { /* Configure the PLLSAI division factor */ /* PLLSAI_VCO Input = PLL_SOURCE/PLLSAIM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) { /* In Case the PLL Source is HSI (Internal Clock) */ vcoinput = (HSI_VALUE / (uint32_t)(RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIM)); @@ -604,19 +615,19 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLSAI_VCO Output = PLLSAI_VCO Input * PLLSAIN */ /* SAI_CLK(first level) = PLLSAI_VCO Output/PLLSAIQ */ tmpreg1 = (RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIQ) >> 24U; - frequency = (vcoinput * ((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIN) >> 6U))/(tmpreg1); + frequency = (vcoinput * ((RCC->PLLSAICFGR & RCC_PLLSAICFGR_PLLSAIN) >> 6U)) / (tmpreg1); /* SAI_CLK_x = SAI_CLK(first level)/PLLSAIDIVQ */ tmpreg1 = (((RCC->DCKCFGR & RCC_DCKCFGR_PLLSAIDIVQ) >> 8U) + 1U); - frequency = frequency/(tmpreg1); + frequency = frequency / (tmpreg1); break; } - case RCC_DCKCFGR_SAI1SRC_0: /* PLLI2S is the clock source for SAI*/ - case RCC_DCKCFGR_SAI2SRC_0: /* PLLI2S is the clock source for SAI*/ + case RCC_DCKCFGR_SAI1SRC_0: /* PLLI2S is the clock source for SAI*/ + case RCC_DCKCFGR_SAI2SRC_0: /* PLLI2S is the clock source for SAI*/ { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) { /* In Case the PLL Source is HSI (Internal Clock) */ vcoinput = (HSI_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -630,19 +641,19 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ /* SAI_CLK(first level) = PLLI2S_VCO Output/PLLI2SQ */ tmpreg1 = (RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SQ) >> 24U; - frequency = (vcoinput * ((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U))/(tmpreg1); + frequency = (vcoinput * ((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U)) / (tmpreg1); /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVQ */ tmpreg1 = ((RCC->DCKCFGR & RCC_DCKCFGR_PLLI2SDIVQ) + 1U); - frequency = frequency/(tmpreg1); + frequency = frequency / (tmpreg1); break; } - case RCC_DCKCFGR_SAI1SRC_1: /* PLLR is the clock source for SAI*/ - case RCC_DCKCFGR_SAI2SRC_1: /* PLLR is the clock source for SAI*/ + case RCC_DCKCFGR_SAI1SRC_1: /* PLLR is the clock source for SAI*/ + case RCC_DCKCFGR_SAI2SRC_1: /* PLLR is the clock source for SAI*/ { /* Configure the PLLI2S division factor */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) + 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)); @@ -656,17 +667,17 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLL_VCO Output = PLL_VCO Input * PLLN */ /* SAI_CLK_x = PLL_VCO Output/PLLR */ tmpreg1 = (RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U; - frequency = (vcoinput * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U))/(tmpreg1); + frequency = (vcoinput * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U)) / (tmpreg1); break; } - case RCC_DCKCFGR_SAI1SRC: /* External clock is the clock source for SAI*/ + case RCC_DCKCFGR_SAI1SRC: /* External clock is the clock source for SAI*/ { frequency = EXTERNAL_CLOCK_VALUE; break; } - case RCC_DCKCFGR_SAI2SRC: /* PLLSRC(HSE or HSI) is the clock source for SAI*/ + case RCC_DCKCFGR_SAI2SRC: /* PLLSRC(HSE or HSI) is the clock source for SAI*/ { - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSI) { /* In Case the PLL Source is HSI (Internal Clock) */ frequency = (uint32_t)(HSI_VALUE); @@ -678,32 +689,32 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default : + default : { break; } } break; } - case RCC_PERIPHCLK_I2S_APB1: + case RCC_PERIPHCLK_I2S_APB1: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_APB1_SOURCE(); switch (srcclk) { - /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SAPB1CLKSOURCE_EXT: + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCC_I2SAPB1CLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } - /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SAPB1CLKSOURCE_PLLI2S: + /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ + case RCC_I2SAPB1CLKSOURCE_PLLI2S: { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -717,15 +728,15 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } - /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ - case RCC_I2SAPB1CLKSOURCE_PLLR: + /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ + case RCC_I2SAPB1CLKSOURCE_PLLR: { /* Configure the PLL division factor R */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -739,13 +750,13 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLL_VCO Output = PLL_VCO Input * PLLN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U) & (RCC_PLLCFGR_PLLN >> 6U))); /* I2S_CLK = PLL_VCO Output/PLLR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); break; } - /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ - case RCC_I2SAPB1CLKSOURCE_PLLSRC: + /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ + case RCC_I2SAPB1CLKSOURCE_PLLSRC: { - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { frequency = HSE_VALUE; } @@ -756,7 +767,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -764,25 +775,25 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - case RCC_PERIPHCLK_I2S_APB2: + case RCC_PERIPHCLK_I2S_APB2: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_APB2_SOURCE(); switch (srcclk) { /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SAPB2CLKSOURCE_EXT: + case RCC_I2SAPB2CLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SAPB2CLKSOURCE_PLLI2S: + case RCC_I2SAPB2CLKSOURCE_PLLI2S: { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -796,15 +807,15 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ - case RCC_I2SAPB2CLKSOURCE_PLLR: + case RCC_I2SAPB2CLKSOURCE_PLLR: { /* Configure the PLL division factor R */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -818,13 +829,13 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLL_VCO Output = PLL_VCO Input * PLLN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U) & (RCC_PLLCFGR_PLLN >> 6U))); /* I2S_CLK = PLL_VCO Output/PLLR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); break; } /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ - case RCC_I2SAPB2CLKSOURCE_PLLSRC: + case RCC_I2SAPB2CLKSOURCE_PLLSRC: { - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { frequency = HSE_VALUE; } @@ -835,7 +846,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -843,9 +854,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default: + default: { - break; + break; } } return frequency; @@ -879,7 +890,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); /*--------------------------- CLK48 Configuration --------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) { /* Check the parameters */ assert_param(IS_RCC_CLK48CLKSOURCE(PeriphClkInit->Clk48ClockSelection)); @@ -890,7 +901,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------ SDIO Configuration ------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) { /* Check the parameters */ assert_param(IS_RCC_SDIOCLKSOURCE(PeriphClkInit->SdioClockSelection)); @@ -904,9 +915,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*------------------- 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) || - (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S)) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) || + (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLI2S) == RCC_PERIPHCLK_SAI_PLLI2S) || + (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S)) { /* check for Parameters */ assert_param(IS_RCC_PLLI2SN_VALUE(PeriphClkInit->PLLI2S.PLLI2SN)); @@ -916,9 +927,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -928,20 +939,20 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*---------------------- 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)) + 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) x (PLLI2SN/PLLM) */ /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SR */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.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)) + 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)); @@ -953,20 +964,21 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* 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 , tmpreg1); + __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, tmpreg1); /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVQ */ __HAL_RCC_PLLI2S_PLLSAICLKDIVQ_CONFIG(PeriphClkInit->PLLI2SDivQ); } /*----------------- In Case of PLLI2S is just selected -----------------*/ - if((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) + if ((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) { /* Check for Parameters */ assert_param(IS_RCC_PLLI2SQ_VALUE(PeriphClkInit->PLLI2S.PLLI2SQ)); assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); /* Configure the PLLI2S multiplication and division factors */ - __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, + PeriphClkInit->PLLI2S.PLLI2SR); } /* Enable the PLLI2S */ @@ -974,9 +986,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -989,10 +1001,10 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*----------------------- Common configuration SAI/LTDC --------------------*/ /* In Case of SAI, LTDC or CLK48 Clock Configuration through PLLSAI, PLLSAIN division factor is common parameters for these peripherals */ - if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLSAI) == RCC_PERIPHCLK_SAI_PLLSAI) || - (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LTDC) == RCC_PERIPHCLK_LTDC) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) && - (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP))) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLSAI) == RCC_PERIPHCLK_SAI_PLLSAI) || + (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LTDC) == RCC_PERIPHCLK_LTDC) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) && + (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP))) { /* Check the PLLSAI division factors */ assert_param(IS_RCC_PLLSAIN_VALUE(PeriphClkInit->PLLSAI.PLLSAIN)); @@ -1002,9 +1014,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLSAI is disabled */ - while(__HAL_RCC_PLLSAI_GET_FLAG() != RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() != RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -1014,7 +1026,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*---------------------------- 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)) + 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)); @@ -1032,7 +1044,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } /*---------------------------- LTDC configuration ------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LTDC) == (RCC_PERIPHCLK_LTDC)) + 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)); @@ -1051,8 +1063,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*---------------------------- CLK48 configuration ------------------------*/ /* Configure the PLLSAI when it is used as clock source for CLK48 */ - if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == (RCC_PERIPHCLK_CLK48)) && - (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP)) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == (RCC_PERIPHCLK_CLK48)) && + (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLSAIP)) { assert_param(IS_RCC_PLLSAIP_VALUE(PeriphClkInit->PLLSAI.PLLSAIP)); @@ -1071,9 +1083,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLSAI is ready */ - while(__HAL_RCC_PLLSAI_GET_FLAG() == RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() == RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -1084,7 +1096,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- RTC configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) { /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); @@ -1098,16 +1110,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); - while((PWR->CR & PWR_CR_DBP) == RESET) + while ((PWR->CR & PWR_CR_DBP) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ tmpreg1 = (RCC->BDCR & RCC_BDCR_RTCSEL); - if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) + if ((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpreg1 = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); @@ -1118,15 +1130,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk RCC->BDCR = tmpreg1; /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ - if(HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) + if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -1138,7 +1150,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- TIM configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) { __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection); } @@ -1157,9 +1169,9 @@ 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 |\ + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_SAI_PLLSAI | \ + RCC_PERIPHCLK_SAI_PLLI2S | RCC_PERIPHCLK_LTDC | \ + RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC | \ RCC_PERIPHCLK_CLK48 | RCC_PERIPHCLK_SDIO; /* Get the PLLI2S Clock configuration --------------------------------------*/ @@ -1178,7 +1190,7 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) tempreg = (RCC->CFGR & RCC_CFGR_RTCPRE); PeriphClkInit->RTCClockSelection = (uint32_t)((tempreg) | (RCC->BDCR & RCC_BDCR_RTCSEL)); - /* Get the CLK48 clock configuration -------------------------------------*/ + /* Get the CLK48 clock configuration -------------------------------------*/ PeriphClkInit->Clk48ClockSelection = __HAL_RCC_GET_CLK48_SOURCE(); /* Get the SDIO clock configuration ----------------------------------------*/ @@ -1213,25 +1225,25 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) uint32_t vcooutput = 0U; switch (PeriphClk) { - case RCC_PERIPHCLK_I2S: + case RCC_PERIPHCLK_I2S: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_SOURCE(); switch (srcclk) { - /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SCLKSOURCE_EXT: + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCC_I2SCLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } - /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SCLKSOURCE_PLLI2S: + /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ + case RCC_I2SCLKSOURCE_PLLI2S: { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -1245,11 +1257,11 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -1257,9 +1269,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default: + default: { - break; + break; } } return frequency; @@ -1294,7 +1306,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); /*----------------------------------- I2S APB1 configuration ---------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == (RCC_PERIPHCLK_I2S_APB1)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == (RCC_PERIPHCLK_I2S_APB1)) { /* Check the parameters */ assert_param(IS_RCC_I2SAPB1CLKSOURCE(PeriphClkInit->I2sApb1ClockSelection)); @@ -1302,7 +1314,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure I2S Clock source */ __HAL_RCC_I2S_APB1_CONFIG(PeriphClkInit->I2sApb1ClockSelection); /* Enable the PLLI2S when it's used as clock source for I2S */ - if(PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S) + if (PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S) { plli2sused = 1U; } @@ -1310,7 +1322,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*----------------------------------- I2S APB2 configuration ---------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == (RCC_PERIPHCLK_I2S_APB2)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == (RCC_PERIPHCLK_I2S_APB2)) { /* Check the parameters */ assert_param(IS_RCC_I2SAPB2CLKSOURCE(PeriphClkInit->I2sApb2ClockSelection)); @@ -1318,7 +1330,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure I2S Clock source */ __HAL_RCC_I2S_APB2_CONFIG(PeriphClkInit->I2sApb2ClockSelection); /* Enable the PLLI2S when it's used as clock source for I2S */ - if(PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S) + if (PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S) { plli2sused = 1U; } @@ -1327,7 +1339,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk #if defined(STM32F413xx) || defined(STM32F423xx) /*----------------------- SAI1 Block A configuration -----------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIA) == (RCC_PERIPHCLK_SAIA)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIA) == (RCC_PERIPHCLK_SAIA)) { /* Check the parameters */ assert_param(IS_RCC_SAIACLKSOURCE(PeriphClkInit->SaiAClockSelection)); @@ -1335,12 +1347,12 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure SAI1 Clock source */ __HAL_RCC_SAI_BLOCKACLKSOURCE_CONFIG(PeriphClkInit->SaiAClockSelection); /* Enable the PLLI2S when it's used as clock source for SAI */ - if(PeriphClkInit->SaiAClockSelection == RCC_SAIACLKSOURCE_PLLI2SR) + if (PeriphClkInit->SaiAClockSelection == RCC_SAIACLKSOURCE_PLLI2SR) { plli2sused = 1U; } /* Enable the PLLSAI when it's used as clock source for SAI */ - if(PeriphClkInit->SaiAClockSelection == RCC_SAIACLKSOURCE_PLLR) + if (PeriphClkInit->SaiAClockSelection == RCC_SAIACLKSOURCE_PLLR) { /* Check for PLL/DIVR parameters */ assert_param(IS_RCC_PLL_DIVR_VALUE(PeriphClkInit->PLLDivR)); @@ -1352,7 +1364,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------- SAI1 Block B configuration ------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIB) == (RCC_PERIPHCLK_SAIB)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIB) == (RCC_PERIPHCLK_SAIB)) { /* Check the parameters */ assert_param(IS_RCC_SAIBCLKSOURCE(PeriphClkInit->SaiBClockSelection)); @@ -1360,12 +1372,12 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure SAI1 Clock source */ __HAL_RCC_SAI_BLOCKBCLKSOURCE_CONFIG(PeriphClkInit->SaiBClockSelection); /* Enable the PLLI2S when it's used as clock source for SAI */ - if(PeriphClkInit->SaiBClockSelection == RCC_SAIBCLKSOURCE_PLLI2SR) + if (PeriphClkInit->SaiBClockSelection == RCC_SAIBCLKSOURCE_PLLI2SR) { plli2sused = 1U; } /* Enable the PLLSAI when it's used as clock source for SAI */ - if(PeriphClkInit->SaiBClockSelection == RCC_SAIBCLKSOURCE_PLLR) + if (PeriphClkInit->SaiBClockSelection == RCC_SAIBCLKSOURCE_PLLR) { /* Check for PLL/DIVR parameters */ assert_param(IS_RCC_PLL_DIVR_VALUE(PeriphClkInit->PLLDivR)); @@ -1378,7 +1390,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk #endif /* STM32F413xx || STM32F423xx */ /*------------------------------------ RTC configuration -------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) { /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); @@ -1392,16 +1404,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); - while((PWR->CR & PWR_CR_DBP) == RESET) + while ((PWR->CR & PWR_CR_DBP) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ tmpreg1 = (RCC->BDCR & RCC_BDCR_RTCSEL); - if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) + if ((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpreg1 = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); @@ -1412,15 +1424,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk RCC->BDCR = tmpreg1; /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ - if(HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) + if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -1432,7 +1444,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------------ TIM configuration -------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) { /* Configure Timer Prescaler */ __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection); @@ -1440,7 +1452,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------------- FMPI2C1 Configuration --------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FMPI2C1) == RCC_PERIPHCLK_FMPI2C1) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FMPI2C1) == RCC_PERIPHCLK_FMPI2C1) { /* Check the parameters */ assert_param(IS_RCC_FMPI2C1CLKSOURCE(PeriphClkInit->Fmpi2c1ClockSelection)); @@ -1451,7 +1463,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------------- CLK48 Configuration ----------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) { /* Check the parameters */ assert_param(IS_RCC_CLK48CLKSOURCE(PeriphClkInit->Clk48ClockSelection)); @@ -1460,7 +1472,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_CLK48_CONFIG(PeriphClkInit->Clk48ClockSelection); /* Enable the PLLI2S when it's used as clock source for CLK48 */ - if(PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLI2SQ) + if (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLI2SQ) { plli2sused = 1U; } @@ -1468,7 +1480,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*------------------------------------- SDIO Configuration -----------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) { /* Check the parameters */ assert_param(IS_RCC_SDIOCLKSOURCE(PeriphClkInit->SdioClockSelection)); @@ -1481,16 +1493,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*-------------------------------------- PLLI2S Configuration --------------*/ /* PLLI2S is configured when a peripheral will use it as source clock : I2S on APB1 or I2S on APB2*/ - if((plli2sused == 1U) || (PeriphClkInit->PeriphClockSelection == RCC_PERIPHCLK_PLLI2S)) + if ((plli2sused == 1U) || (PeriphClkInit->PeriphClockSelection == RCC_PERIPHCLK_PLLI2S)) { /* Disable the PLLI2S */ __HAL_RCC_PLLI2S_DISABLE(); /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -1505,10 +1517,11 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_PLL_I2S_CONFIG(PeriphClkInit->PLLI2SSelection); /*------- In Case of PLLI2S is selected as source clock for I2S ----------*/ - if(((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == RCC_PERIPHCLK_I2S_APB1) && (PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == RCC_PERIPHCLK_I2S_APB2) && (PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) && (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLI2SQ)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) && (PeriphClkInit->SdioClockSelection == RCC_SDIOCLKSOURCE_CLK48) && (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLI2SQ))) + if (((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB1) == RCC_PERIPHCLK_I2S_APB1) + && (PeriphClkInit->I2sApb1ClockSelection == RCC_I2SAPB1CLKSOURCE_PLLI2S)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S_APB2) == RCC_PERIPHCLK_I2S_APB2) && (PeriphClkInit->I2sApb2ClockSelection == RCC_I2SAPB2CLKSOURCE_PLLI2S)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CLK48) == RCC_PERIPHCLK_CLK48) && (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLI2SQ)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SDIO) == RCC_PERIPHCLK_SDIO) && (PeriphClkInit->SdioClockSelection == RCC_SDIOCLKSOURCE_CLK48) && (PeriphClkInit->Clk48ClockSelection == RCC_CLK48CLKSOURCE_PLLI2SQ))) { /* check for Parameters */ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); @@ -1517,13 +1530,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLI2S division factors */ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLLI2SN/PLLI2SM)*/ /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SR */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SQ, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, + PeriphClkInit->PLLI2S.PLLI2SR); } #if defined(STM32F413xx) || defined(STM32F423xx) /*------- In Case of PLLI2S is selected as source clock for SAI ----------*/ - if(((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIA) == RCC_PERIPHCLK_SAIA) && (PeriphClkInit->SaiAClockSelection == RCC_SAIACLKSOURCE_PLLI2SR)) || - ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIB) == RCC_PERIPHCLK_SAIB) && (PeriphClkInit->SaiBClockSelection == RCC_SAIBCLKSOURCE_PLLI2SR))) + if (((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIA) == RCC_PERIPHCLK_SAIA) + && (PeriphClkInit->SaiAClockSelection == RCC_SAIACLKSOURCE_PLLI2SR)) || + ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAIB) == RCC_PERIPHCLK_SAIB) && (PeriphClkInit->SaiBClockSelection == RCC_SAIBCLKSOURCE_PLLI2SR))) { /* Check for PLLI2S Parameters */ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); @@ -1536,7 +1551,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ /* SAI_CLK(first level) = PLLI2S_VCO Output/PLLI2SQ */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, plli2sq, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, plli2sq, + PeriphClkInit->PLLI2S.PLLI2SR); /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVR */ __HAL_RCC_PLLI2S_PLLSAICLKDIVR_CONFIG(PeriphClkInit->PLLI2SDivR); @@ -1544,7 +1560,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk #endif /* STM32F413xx || STM32F423xx */ /*----------------- In Case of PLLI2S is just selected ------------------*/ - if((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) + if ((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) { /* Check for Parameters */ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); @@ -1553,7 +1569,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLI2S division factors */ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLLI2SN/PLLI2SM)*/ /* SPDIFRXCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SP */ - __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN , PeriphClkInit->PLLI2S.PLLI2SQ, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, + PeriphClkInit->PLLI2S.PLLI2SR); } /* Enable the PLLI2S */ @@ -1561,9 +1578,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -1573,7 +1590,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*-------------------- DFSDM1 clock source configuration -------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM1) == RCC_PERIPHCLK_DFSDM1) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM1) == RCC_PERIPHCLK_DFSDM1) { /* Check the parameters */ assert_param(IS_RCC_DFSDM1CLKSOURCE(PeriphClkInit->Dfsdm1ClockSelection)); @@ -1584,7 +1601,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*-------------------- DFSDM1 Audio clock source configuration -------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM1_AUDIO) == RCC_PERIPHCLK_DFSDM1_AUDIO) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM1_AUDIO) == RCC_PERIPHCLK_DFSDM1_AUDIO) { /* Check the parameters */ assert_param(IS_RCC_DFSDM1AUDIOCLKSOURCE(PeriphClkInit->Dfsdm1AudioClockSelection)); @@ -1596,7 +1613,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk #if defined(STM32F413xx) || defined(STM32F423xx) /*-------------------- DFSDM2 clock source configuration -------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM2) == RCC_PERIPHCLK_DFSDM2) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM2) == RCC_PERIPHCLK_DFSDM2) { /* Check the parameters */ assert_param(IS_RCC_DFSDM2CLKSOURCE(PeriphClkInit->Dfsdm2ClockSelection)); @@ -1607,7 +1624,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*-------------------- DFSDM2 Audio clock source configuration -------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM2_AUDIO) == RCC_PERIPHCLK_DFSDM2_AUDIO) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_DFSDM2_AUDIO) == RCC_PERIPHCLK_DFSDM2_AUDIO) { /* Check the parameters */ assert_param(IS_RCC_DFSDM2AUDIOCLKSOURCE(PeriphClkInit->Dfsdm2AudioClockSelection)); @@ -1618,7 +1635,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- LPTIM1 Configuration ------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == RCC_PERIPHCLK_LPTIM1) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == RCC_PERIPHCLK_LPTIM1) { /* Check the parameters */ assert_param(IS_RCC_LPTIM1CLKSOURCE(PeriphClkInit->Lptim1ClockSelection)); @@ -1645,18 +1662,18 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) /* Set all possible values for the extended clock type parameter------------*/ #if defined(STM32F413xx) || defined(STM32F423xx) - PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S_APB1 | RCC_PERIPHCLK_I2S_APB2 |\ - RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC |\ - RCC_PERIPHCLK_FMPI2C1 | RCC_PERIPHCLK_CLK48 |\ - RCC_PERIPHCLK_SDIO | RCC_PERIPHCLK_DFSDM1 |\ - RCC_PERIPHCLK_DFSDM1_AUDIO | RCC_PERIPHCLK_DFSDM2 |\ - RCC_PERIPHCLK_DFSDM2_AUDIO | RCC_PERIPHCLK_LPTIM1 |\ + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S_APB1 | RCC_PERIPHCLK_I2S_APB2 | \ + RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_FMPI2C1 | RCC_PERIPHCLK_CLK48 | \ + RCC_PERIPHCLK_SDIO | RCC_PERIPHCLK_DFSDM1 | \ + RCC_PERIPHCLK_DFSDM1_AUDIO | RCC_PERIPHCLK_DFSDM2 | \ + RCC_PERIPHCLK_DFSDM2_AUDIO | RCC_PERIPHCLK_LPTIM1 | \ RCC_PERIPHCLK_SAIA | RCC_PERIPHCLK_SAIB; #else /* STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx */ - PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S_APB1 | RCC_PERIPHCLK_I2S_APB2 |\ - RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC |\ - RCC_PERIPHCLK_FMPI2C1 | RCC_PERIPHCLK_CLK48 |\ - RCC_PERIPHCLK_SDIO | RCC_PERIPHCLK_DFSDM1 |\ + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_I2S_APB1 | RCC_PERIPHCLK_I2S_APB2 | \ + RCC_PERIPHCLK_TIM | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_FMPI2C1 | RCC_PERIPHCLK_CLK48 | \ + RCC_PERIPHCLK_SDIO | RCC_PERIPHCLK_DFSDM1 | \ RCC_PERIPHCLK_DFSDM1_AUDIO; #endif /* STM32F413xx || STM32F423xx */ @@ -1746,23 +1763,23 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) uint32_t vcooutput = 0U; switch (PeriphClk) { - case RCC_PERIPHCLK_I2S_APB1: + case RCC_PERIPHCLK_I2S_APB1: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_APB1_SOURCE(); switch (srcclk) { - /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SAPB1CLKSOURCE_EXT: + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCC_I2SAPB1CLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } - /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SAPB1CLKSOURCE_PLLI2S: + /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ + case RCC_I2SAPB1CLKSOURCE_PLLI2S: { - if((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SSRC) == RCC_PLLI2SCFGR_PLLI2SSRC) + if ((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SSRC) == RCC_PLLI2SCFGR_PLLI2SSRC) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(EXTERNAL_CLOCK_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -1771,7 +1788,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -1785,15 +1802,15 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } - /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ - case RCC_I2SAPB1CLKSOURCE_PLLR: + /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ + case RCC_I2SAPB1CLKSOURCE_PLLR: { /* Configure the PLL division factor R */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -1807,13 +1824,13 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLL_VCO Output = PLL_VCO Input * PLLN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U) & (RCC_PLLCFGR_PLLN >> 6U))); /* I2S_CLK = PLL_VCO Output/PLLR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); break; } - /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ - case RCC_I2SAPB1CLKSOURCE_PLLSRC: + /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ + case RCC_I2SAPB1CLKSOURCE_PLLSRC: { - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { frequency = HSE_VALUE; } @@ -1824,7 +1841,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -1832,23 +1849,23 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - case RCC_PERIPHCLK_I2S_APB2: + case RCC_PERIPHCLK_I2S_APB2: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_APB2_SOURCE(); switch (srcclk) { /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SAPB2CLKSOURCE_EXT: + case RCC_I2SAPB2CLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SAPB2CLKSOURCE_PLLI2S: + case RCC_I2SAPB2CLKSOURCE_PLLI2S: { - if((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SSRC) == RCC_PLLI2SCFGR_PLLI2SSRC) + if ((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SSRC) == RCC_PLLI2SCFGR_PLLI2SSRC) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(EXTERNAL_CLOCK_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -1857,7 +1874,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -1871,15 +1888,15 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ - case RCC_I2SAPB2CLKSOURCE_PLLR: + case RCC_I2SAPB2CLKSOURCE_PLLR: { /* Configure the PLL division factor R */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -1893,13 +1910,13 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLL_VCO Output = PLL_VCO Input * PLLN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U) & (RCC_PLLCFGR_PLLN >> 6U))); /* I2S_CLK = PLL_VCO Output/PLLR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); break; } /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ - case RCC_I2SAPB2CLKSOURCE_PLLSRC: + case RCC_I2SAPB2CLKSOURCE_PLLSRC: { - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { frequency = HSE_VALUE; } @@ -1909,8 +1926,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - /* Clock not enabled for I2S*/ - default: + /* Clock not enabled for I2S*/ + default: { frequency = 0U; break; @@ -1918,9 +1935,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default: + default: { - break; + break; } } return frequency; @@ -1949,7 +1966,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); /*---------------------------- RTC configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) { /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); @@ -1963,16 +1980,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); - while((PWR->CR & PWR_CR_DBP) == RESET) + while ((PWR->CR & PWR_CR_DBP) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ tmpreg1 = (RCC->BDCR & RCC_BDCR_RTCSEL); - if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) + if ((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpreg1 = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); @@ -1983,15 +2000,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk RCC->BDCR = tmpreg1; /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ - if(HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) + if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -2003,14 +2020,14 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- TIM configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) { __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection); } /*--------------------------------------------------------------------------*/ /*---------------------------- FMPI2C1 Configuration -----------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FMPI2C1) == RCC_PERIPHCLK_FMPI2C1) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FMPI2C1) == RCC_PERIPHCLK_FMPI2C1) { /* Check the parameters */ assert_param(IS_RCC_FMPI2C1CLKSOURCE(PeriphClkInit->Fmpi2c1ClockSelection)); @@ -2021,7 +2038,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- LPTIM1 Configuration ------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == RCC_PERIPHCLK_LPTIM1) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == RCC_PERIPHCLK_LPTIM1) { /* Check the parameters */ assert_param(IS_RCC_LPTIM1CLKSOURCE(PeriphClkInit->Lptim1ClockSelection)); @@ -2031,7 +2048,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } /*---------------------------- I2S Configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) { /* Check the parameters */ assert_param(IS_RCC_I2SAPBCLKSOURCE(PeriphClkInit->I2SClockSelection)); @@ -2095,25 +2112,25 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) uint32_t vcooutput = 0U; switch (PeriphClk) { - case RCC_PERIPHCLK_I2S: + case RCC_PERIPHCLK_I2S: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_SOURCE(); switch (srcclk) { - /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SAPBCLKSOURCE_EXT: + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCC_I2SAPBCLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } - /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ - case RCC_I2SAPBCLKSOURCE_PLLR: + /* Check if I2S clock selection is PLL VCO Output divided by PLLR used as I2S clock */ + case RCC_I2SAPBCLKSOURCE_PLLR: { /* Configure the PLL division factor R */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -2127,13 +2144,13 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLL_VCO Output = PLL_VCO Input * PLLN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6U) & (RCC_PLLCFGR_PLLN >> 6U))); /* I2S_CLK = PLL_VCO Output/PLLR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28U) & (RCC_PLLCFGR_PLLR >> 28U))); break; } - /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ - case RCC_I2SAPBCLKSOURCE_PLLSRC: + /* Check if I2S clock selection is HSI or HSE depending from PLL source Clock */ + case RCC_I2SAPBCLKSOURCE_PLLSRC: { - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { frequency = HSE_VALUE; } @@ -2144,7 +2161,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -2152,9 +2169,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default: + default: { - break; + break; } } return frequency; @@ -2188,9 +2205,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*----------------------- 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) || - (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S)) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) || + (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI_PLLI2S) == RCC_PERIPHCLK_SAI_PLLI2S) || + (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S)) { /* check for Parameters */ assert_param(IS_RCC_PLLI2SN_VALUE(PeriphClkInit->PLLI2S.PLLI2SN)); @@ -2200,9 +2217,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2212,20 +2229,20 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*---------------------------- 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)) + 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); + __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)) + 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)); @@ -2237,20 +2254,21 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* 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 , tmpreg1); + __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, tmpreg1); /* SAI_CLK_x = SAI_CLK(first level)/PLLI2SDIVQ */ __HAL_RCC_PLLI2S_PLLSAICLKDIVQ_CONFIG(PeriphClkInit->PLLI2SDivQ); } /*----------------- In Case of PLLI2S is just selected -----------------*/ - if((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) + if ((PeriphClkInit->PeriphClockSelection & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S) { /* Check for Parameters */ assert_param(IS_RCC_PLLI2SQ_VALUE(PeriphClkInit->PLLI2S.PLLI2SQ)); assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); /* Configure the PLLI2S multiplication and division factors */ - __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_SAICLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SQ, + PeriphClkInit->PLLI2S.PLLI2SR); } /* Enable the PLLI2S */ @@ -2258,9 +2276,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2273,8 +2291,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*----------------------- 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)) + 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)); @@ -2284,9 +2302,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLSAI is disabled */ - while(__HAL_RCC_PLLSAI_GET_FLAG() != RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() != RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2296,7 +2314,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*---------------------------- 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)) + 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)); @@ -2306,13 +2324,13 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* 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, tmpreg1); + __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIN, PeriphClkInit->PLLSAI.PLLSAIQ, tmpreg1); /* 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)) + 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)); @@ -2322,7 +2340,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* 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 , tmpreg1, PeriphClkInit->PLLSAI.PLLSAIR); + __HAL_RCC_PLLSAI_CONFIG(PeriphClkInit->PLLSAI.PLLSAIN, tmpreg1, PeriphClkInit->PLLSAI.PLLSAIR); /* LTDC_CLK = LTDC_CLK(first level)/PLLSAIDIVR */ __HAL_RCC_PLLSAI_PLLSAICLKDIVR_CONFIG(PeriphClkInit->PLLSAIDivR); } @@ -2331,9 +2349,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLSAI is ready */ - while(__HAL_RCC_PLLSAI_GET_FLAG() == RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() == RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2343,7 +2361,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- RTC configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) { /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); @@ -2357,16 +2375,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); - while((PWR->CR & PWR_CR_DBP) == RESET) + while ((PWR->CR & PWR_CR_DBP) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ tmpreg1 = (RCC->BDCR & RCC_BDCR_RTCSEL); - if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) + if ((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpreg1 = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); @@ -2377,15 +2395,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk RCC->BDCR = tmpreg1; /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ - if(HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) + if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -2397,7 +2415,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /*--------------------------------------------------------------------------*/ /*---------------------------- TIM configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) { __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection); } @@ -2463,25 +2481,25 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) uint32_t vcooutput = 0U; switch (PeriphClk) { - case RCC_PERIPHCLK_I2S: + case RCC_PERIPHCLK_I2S: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_SOURCE(); switch (srcclk) { - /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SCLKSOURCE_EXT: + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCC_I2SCLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } - /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SCLKSOURCE_PLLI2S: + /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ + case RCC_I2SCLKSOURCE_PLLI2S: { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -2495,11 +2513,11 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -2507,9 +2525,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default: + default: { - break; + break; } } return frequency; @@ -2539,8 +2557,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection)); /*---------------------------- I2S configuration ---------------------------*/ - if((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) || - (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S)) + if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) || + (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_PLLI2S) == RCC_PERIPHCLK_PLLI2S)) { /* check for Parameters */ assert_param(IS_RCC_PLLI2SR_VALUE(PeriphClkInit->PLLI2S.PLLI2SR)); @@ -2553,9 +2571,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2566,12 +2584,13 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the PLLI2S division factors */ /* PLLI2S_VCO = f(VCO clock) = f(PLLI2S clock input) * (PLLI2SN/PLLI2SM) */ /* I2SCLK = f(PLLI2S clock output) = f(VCO clock) / PLLI2SR */ - __HAL_RCC_PLLI2S_I2SCLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SR); + __HAL_RCC_PLLI2S_I2SCLK_CONFIG(PeriphClkInit->PLLI2S.PLLI2SM, PeriphClkInit->PLLI2S.PLLI2SN, + PeriphClkInit->PLLI2S.PLLI2SR); #else /* 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); + __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SN, PeriphClkInit->PLLI2S.PLLI2SR); #endif /* STM32F411xE */ /* Enable the PLLI2S */ @@ -2579,9 +2598,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); /* Wait till PLLI2S is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2590,7 +2609,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } /*---------------------------- RTC configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) { /* Check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); @@ -2604,16 +2623,16 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Get tick */ tickstart = HAL_GetTick(); - while((PWR->CR & PWR_CR_DBP) == RESET) + while ((PWR->CR & PWR_CR_DBP) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ tmpreg1 = (RCC->BDCR & RCC_BDCR_RTCSEL); - if((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) + if ((tmpreg1 != 0x00000000U) && ((tmpreg1) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) { /* Store the content of BDCR register before the reset of Backup Domain */ tmpreg1 = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); @@ -2624,15 +2643,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk RCC->BDCR = tmpreg1; /* Wait for LSE reactivation if LSE was enable prior to Backup Domain reset */ - if(HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) + if (HAL_IS_BIT_SET(RCC->BDCR, RCC_BDCR_LSEON)) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -2643,7 +2662,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } #if defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) /*---------------------------- TIM configuration ---------------------------*/ - if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) + if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_TIM) == (RCC_PERIPHCLK_TIM)) { __HAL_RCC_TIMCLKPRESCALER(PeriphClkInit->TIMPresSelection); } @@ -2707,26 +2726,26 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) uint32_t vcooutput = 0U; switch (PeriphClk) { - case RCC_PERIPHCLK_I2S: + case RCC_PERIPHCLK_I2S: { /* Get the current I2S source */ srcclk = __HAL_RCC_GET_I2S_SOURCE(); switch (srcclk) { - /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ - case RCC_I2SCLKSOURCE_EXT: + /* Check if I2S clock selection is External clock mapped on the I2S_CKIN pin used as I2S clock */ + case RCC_I2SCLKSOURCE_EXT: { /* Set the I2S clock to the external clock value */ frequency = EXTERNAL_CLOCK_VALUE; break; } - /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ - case RCC_I2SCLKSOURCE_PLLI2S: + /* Check if I2S clock selection is PLLI2S VCO output clock divided by PLLI2SR used as I2S clock */ + case RCC_I2SCLKSOURCE_PLLI2S: { #if defined(STM32F411xE) /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); @@ -2739,7 +2758,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) #else /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLM */ - if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); @@ -2753,11 +2772,11 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6U) & (RCC_PLLI2SCFGR_PLLI2SN >> 6U))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ - frequency = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); + frequency = (uint32_t)(vcooutput / (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28U) & (RCC_PLLI2SCFGR_PLLI2SR >> 28U))); break; } /* Clock not enabled for I2S*/ - default: + default: { frequency = 0U; break; @@ -2765,9 +2784,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; } - default: + default: { - break; + break; } } return frequency; @@ -2791,7 +2810,7 @@ void HAL_RCCEx_SelectLSEMode(uint8_t Mode) { /* Check the parameters */ assert_param(IS_RCC_LSE_MODE(Mode)); - if(Mode == RCC_LSE_HIGHDRIVE_MODE) + if (Mode == RCC_LSE_HIGHDRIVE_MODE) { SET_BIT(RCC->BDCR, RCC_BDCR_LSEMOD); } @@ -2804,8 +2823,8 @@ void HAL_RCCEx_SelectLSEMode(uint8_t Mode) #endif /* STM32F410xx || STM32F411xE || STM32F446xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */ /** @defgroup RCCEx_Exported_Functions_Group2 Extended Clock management functions - * @brief Extended Clock management functions - * + * @brief Extended Clock management functions + * @verbatim =============================================================================== ##### Extended clock management functions ##### @@ -2846,9 +2865,9 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit) /* Wait till PLLI2S is disabled */ tickstart = HAL_GetTick(); - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2891,16 +2910,16 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit) /* Wait till PLLI2S is ready */ tickstart = HAL_GetTick(); - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; } } - return HAL_OK; + return HAL_OK; } /** @@ -2916,9 +2935,9 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void) /* Wait till PLLI2S is disabled */ tickstart = HAL_GetTick(); - while(READ_BIT(RCC->CR, RCC_CR_PLLI2SRDY) != RESET) + while (READ_BIT(RCC->CR, RCC_CR_PLLI2SRDY) != RESET) { - if((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2959,9 +2978,9 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLSAI(RCC_PLLSAIInitTypeDef *PLLSAIInit) /* Wait till PLLSAI is disabled */ tickstart = HAL_GetTick(); - while(__HAL_RCC_PLLSAI_GET_FLAG() != RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() != RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -2995,16 +3014,16 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLSAI(RCC_PLLSAIInitTypeDef *PLLSAIInit) /* Wait till PLLSAI is ready */ tickstart = HAL_GetTick(); - while(__HAL_RCC_PLLSAI_GET_FLAG() == RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() == RESET) { - if((HAL_GetTick() - tickstart ) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; } } - return HAL_OK; + return HAL_OK; } /** @@ -3020,9 +3039,9 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLSAI(void) /* Wait till PLLSAI is disabled */ tickstart = HAL_GetTick(); - while(__HAL_RCC_PLLSAI_GET_FLAG() != RESET) + while (__HAL_RCC_PLLSAI_GET_FLAG() != RESET) { - if((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLLSAI_TIMEOUT_VALUE) { /* return in case of Timeout detected */ return HAL_TIMEOUT; @@ -3086,7 +3105,7 @@ uint32_t HAL_RCC_GetSysClockFreq(void) case RCC_CFGR_SWS_HSI: /* HSI used as system clock source */ { sysclockfreq = HSI_VALUE; - break; + break; } case RCC_CFGR_SWS_HSE: /* HSE used as system clock source */ { @@ -3098,19 +3117,19 @@ uint32_t HAL_RCC_GetSysClockFreq(void) /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN SYSCLK = PLL_VCO / PLLP */ pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; - if(__HAL_RCC_GET_PLL_OSCSOURCE() != RCC_PLLSOURCE_HSI) + if (__HAL_RCC_GET_PLL_OSCSOURCE() != RCC_PLLSOURCE_HSI) { /* HSE used as PLL clock source */ - pllvco = (uint32_t) ((((uint64_t) HSE_VALUE * ((uint64_t) ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); + pllvco = (uint32_t)((((uint64_t) HSE_VALUE * ((uint64_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); } else { /* HSI used as PLL clock source */ - pllvco = (uint32_t) ((((uint64_t) HSI_VALUE * ((uint64_t) ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); + pllvco = (uint32_t)((((uint64_t) HSI_VALUE * ((uint64_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); } - pllp = ((((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> RCC_PLLCFGR_PLLP_Pos) + 1U) *2U); + pllp = ((((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> RCC_PLLCFGR_PLLP_Pos) + 1U) * 2U); - sysclockfreq = pllvco/pllp; + sysclockfreq = pllvco / pllp; break; } case RCC_CFGR_SWS_PLLR: /* PLL/PLLR used as system clock source */ @@ -3118,19 +3137,19 @@ uint32_t HAL_RCC_GetSysClockFreq(void) /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN SYSCLK = PLL_VCO / PLLR */ pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; - if(__HAL_RCC_GET_PLL_OSCSOURCE() != RCC_PLLSOURCE_HSI) + if (__HAL_RCC_GET_PLL_OSCSOURCE() != RCC_PLLSOURCE_HSI) { /* HSE used as PLL clock source */ - pllvco = (uint32_t) ((((uint64_t) HSE_VALUE * ((uint64_t) ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); + pllvco = (uint32_t)((((uint64_t) HSE_VALUE * ((uint64_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); } else { /* HSI used as PLL clock source */ - pllvco = (uint32_t) ((((uint64_t) HSI_VALUE * ((uint64_t) ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); + pllvco = (uint32_t)((((uint64_t) HSI_VALUE * ((uint64_t)((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos)))) / (uint64_t)pllm); } pllr = ((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> RCC_PLLCFGR_PLLR_Pos); - sysclockfreq = pllvco/pllr; + sysclockfreq = pllvco / pllr; break; } default: @@ -3306,7 +3325,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void) #endif /* RCC_CIR_PLLSAIRDYIE */ /* Clear all interrupt flags */ - SET_BIT(RCC->CIR, RCC_CIR_LSIRDYC | RCC_CIR_LSERDYC | RCC_CIR_HSIRDYC | RCC_CIR_HSERDYC | RCC_CIR_PLLRDYC | RCC_CIR_CSSC); + SET_BIT(RCC->CIR, RCC_CIR_LSIRDYC | RCC_CIR_LSERDYC | RCC_CIR_HSIRDYC | RCC_CIR_HSERDYC | RCC_CIR_PLLRDYC | + RCC_CIR_CSSC); #if defined(RCC_CIR_PLLI2SRDYC) SET_BIT(RCC->CIR, RCC_CIR_PLLI2SRDYC); @@ -3326,7 +3346,7 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void) SystemCoreClock = HSI_VALUE; /* Adapt Systick interrupt period */ - if(HAL_InitTick(uwTickPrio) != HAL_OK) + if (HAL_InitTick(uwTickPrio) != HAL_OK) { return HAL_ERROR; } @@ -3356,10 +3376,11 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void) */ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { - uint32_t tickstart, pll_config; + uint32_t tickstart; + uint32_t pll_config; /* Check Null pointer */ - if(RCC_OscInitStruct == NULL) + if (RCC_OscInitStruct == NULL) { return HAL_ERROR; } @@ -3367,21 +3388,23 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /* Check the parameters */ assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType)); /*------------------------------- HSE Configuration ------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) + 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 defined(STM32F446xx) - 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)) ||\ - ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLLR) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSE))) + 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)) || \ + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLLR) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSE))) #else - 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_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSE) + || \ + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSE))) #endif /* STM32F446xx */ { - if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) && (RCC_OscInitStruct->HSEState == RCC_HSE_OFF)) + if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) && (RCC_OscInitStruct->HSEState == RCC_HSE_OFF)) { return HAL_ERROR; } @@ -3392,15 +3415,15 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) __HAL_RCC_HSE_CONFIG(RCC_OscInitStruct->HSEState); /* Check the HSE State */ - if((RCC_OscInitStruct->HSEState) != RCC_HSE_OFF) + if ((RCC_OscInitStruct->HSEState) != RCC_HSE_OFF) { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till HSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3412,9 +3435,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till HSE is bypassed or disabled */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) { - if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3423,7 +3446,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } } /*----------------------------- HSI Configuration --------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) + if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) { /* Check the parameters */ assert_param(IS_RCC_HSI(RCC_OscInitStruct->HSIState)); @@ -3431,16 +3454,18 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ #if defined(STM32F446xx) - 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)) ||\ - ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLLR) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSI))) + 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)) || \ + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLLR) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSI))) #else - 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_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI) + || \ + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLCFGR_PLLSRC_HSI))) #endif /* STM32F446xx */ { /* When HSI is used as system clock it will not disabled */ - if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) + if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; } @@ -3454,7 +3479,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) else { /* Check the HSI State */ - if((RCC_OscInitStruct->HSIState)!= RCC_HSI_OFF) + if ((RCC_OscInitStruct->HSIState) != RCC_HSI_OFF) { /* Enable the Internal High Speed oscillator (HSI). */ __HAL_RCC_HSI_ENABLE(); @@ -3463,9 +3488,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till HSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3483,9 +3508,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till HSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3494,13 +3519,13 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } } /*------------------------------ LSI Configuration -------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) + 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) + if ((RCC_OscInitStruct->LSIState) != RCC_LSI_OFF) { /* Enable the Internal Low Speed oscillator (LSI). */ __HAL_RCC_LSI_ENABLE(); @@ -3509,9 +3534,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till LSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3526,9 +3551,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till LSI is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3536,7 +3561,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } } /*------------------------------ LSE Configuration -------------------------*/ - if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) + if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) { FlagStatus pwrclkchanged = RESET; @@ -3545,13 +3570,13 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /* Update LSE configuration in Backup Domain control register */ /* Requires to enable write access to Backup Domain of necessary */ - if(__HAL_RCC_PWR_IS_CLK_DISABLED()) + if (__HAL_RCC_PWR_IS_CLK_DISABLED()) { __HAL_RCC_PWR_CLK_ENABLE(); pwrclkchanged = SET; } - if(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + if (HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) { /* Enable write access to Backup domain */ SET_BIT(PWR->CR, PWR_CR_DBP); @@ -3559,9 +3584,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /* Wait for Backup domain Write protection disable */ tickstart = HAL_GetTick(); - while(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + while (HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) { - if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3571,15 +3596,15 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /* Set the new LSE configuration -----------------------------------------*/ __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState); /* Check the LSE State */ - if((RCC_OscInitStruct->LSEState) != RCC_LSE_OFF) + if ((RCC_OscInitStruct->LSEState) != RCC_LSE_OFF) { /* Get Start Tick*/ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3591,9 +3616,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till LSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) { - if((HAL_GetTick() - tickstart ) > RCC_LSE_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3601,7 +3626,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Restore clock configuration if changed */ - if(pwrclkchanged == SET) + if (pwrclkchanged == SET) { __HAL_RCC_PWR_CLK_DISABLE(); } @@ -3612,9 +3637,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) 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 (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) { - if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) + if ((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) { /* Check the parameters */ assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource)); @@ -3631,9 +3656,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till PLL is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3653,9 +3678,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till PLL is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) { - if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3670,9 +3695,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) tickstart = HAL_GetTick(); /* Wait till PLL is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) { - if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) { return HAL_TIMEOUT; } @@ -3682,7 +3707,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) else { /* Check if there is a request to disable the PLL used as System clock source */ - if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_OFF) + if ((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_OFF) { return HAL_ERROR; } @@ -3705,7 +3730,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) (READ_BIT(pll_config, RCC_PLLCFGR_PLLN) != (RCC_OscInitStruct->PLL.PLLN) << RCC_PLLCFGR_PLLN_Pos) || (READ_BIT(pll_config, RCC_PLLCFGR_PLLP) != (((RCC_OscInitStruct->PLL.PLLP >> 1U) - 1U)) << RCC_PLLCFGR_PLLP_Pos) || (READ_BIT(pll_config, RCC_PLLCFGR_PLLQ) != (RCC_OscInitStruct->PLL.PLLQ << RCC_PLLCFGR_PLLQ_Pos))) -#endif +#endif /* RCC_PLLCFGR_PLLR */ { return HAL_ERROR; } @@ -3730,11 +3755,11 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) 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) + 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) + else if ((RCC->CR & RCC_CR_HSEON) == RCC_CR_HSEON) { RCC_OscInitStruct->HSEState = RCC_HSE_ON; } @@ -3744,7 +3769,7 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Get the HSI configuration -----------------------------------------------*/ - if((RCC->CR &RCC_CR_HSION) == RCC_CR_HSION) + if ((RCC->CR & RCC_CR_HSION) == RCC_CR_HSION) { RCC_OscInitStruct->HSIState = RCC_HSI_ON; } @@ -3753,14 +3778,14 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) RCC_OscInitStruct->HSIState = RCC_HSI_OFF; } - RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR &RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos); + RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR & RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos); /* Get the LSE configuration -----------------------------------------------*/ - if((RCC->BDCR &RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP) + 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) + else if ((RCC->BDCR & RCC_BDCR_LSEON) == RCC_BDCR_LSEON) { RCC_OscInitStruct->LSEState = RCC_LSE_ON; } @@ -3770,7 +3795,7 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Get the LSI configuration -----------------------------------------------*/ - if((RCC->CSR &RCC_CSR_LSION) == RCC_CSR_LSION) + if ((RCC->CSR & RCC_CSR_LSION) == RCC_CSR_LSION) { RCC_OscInitStruct->LSIState = RCC_LSI_ON; } @@ -3780,7 +3805,7 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* Get the PLL configuration -----------------------------------------------*/ - if((RCC->CR &RCC_CR_PLLON) == RCC_CR_PLLON) + if ((RCC->CR & RCC_CR_PLLON) == RCC_CR_PLLON) { RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON; } diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_spi.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_spi.c index 341b7ab59..5e4000a93 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_spi.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_hal_spi.c @@ -766,38 +766,35 @@ HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_Ca * @param Timeout Timeout duration * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; uint16_t initial_TxXferCount; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); initial_TxXferCount = Size; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -836,7 +833,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -846,7 +843,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; } @@ -855,9 +852,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -867,7 +864,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; } @@ -876,7 +873,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Wait until TXE flag is set to send data */ if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; } @@ -885,9 +882,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -912,19 +909,18 @@ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint __HAL_SPI_CLEAR_OVRFLAG(hspi); } + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -942,12 +938,10 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 __IO uint32_t tmpreg = 0U; #endif /* USE_SPI_CRC */ uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) @@ -957,18 +951,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); } - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1027,9 +1020,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1051,9 +1044,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Timeout management */ if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1070,8 +1063,8 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { /* the latest data has not been received */ - errorcode = HAL_TIMEOUT; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Receive last data in 16 Bit mode */ @@ -1089,8 +1082,9 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 if (SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC to Flush DR and RXNE flag */ @@ -1115,18 +1109,17 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 } #endif /* USE_SPI_CRC */ + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1139,8 +1132,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) { uint16_t initial_TxXferCount; uint32_t tmp_mode; @@ -1152,14 +1145,10 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Variable used to alternate Rx and Tx during transfer */ uint32_t txallowed = 1U; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ tickstart = HAL_GetTick(); @@ -1171,16 +1160,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD if (!((tmp_state == HAL_SPI_STATE_READY) || \ ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1192,7 +1182,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD hspi->pRxBuffPtr = (uint8_t *)pRxData; hspi->RxXferCount = Size; hspi->RxXferSize = Size; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferCount = Size; hspi->TxXferSize = Size; @@ -1220,7 +1210,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -1238,7 +1228,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1264,9 +1254,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if (((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1275,7 +1265,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { if ((hspi->Init.Mode == SPI_MODE_SLAVE) || (initial_TxXferCount == 0x01U)) { - *((__IO uint8_t *)&hspi->Instance->DR) = (*hspi->pTxBuffPtr); + *((__IO uint8_t *)&hspi->Instance->DR) = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint8_t); hspi->TxXferCount--; @@ -1292,7 +1282,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD /* Check TXE flag */ if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) && (hspi->TxXferCount > 0U) && (txallowed == 1U)) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; /* Next Data is a reception (Rx). Tx not allowed */ @@ -1318,9 +1308,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD } if ((((HAL_GetTick() - tickstart) >= Timeout) && ((Timeout != HAL_MAX_DELAY))) || (Timeout == 0U)) { - errorcode = HAL_TIMEOUT; hspi->State = HAL_SPI_STATE_READY; - goto error; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } } } @@ -1334,8 +1324,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD { /* Error on the CRC reception */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; } /* Read CRC */ tmpreg = READ_REG(hspi->Instance->DR); @@ -1349,17 +1340,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); /* Clear CRC Flag */ __HAL_SPI_CLEAR_CRCERRFLAG(hspi); - - errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } #endif /* USE_SPI_CRC */ /* Check the end of the transaction */ if (SPI_EndRxTxTransaction(hspi, Timeout, tickstart) != HAL_OK) { - errorcode = HAL_ERROR; hspi->ErrorCode = HAL_SPI_ERROR_FLAG; - goto error; + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Clear overrun flag in 2 Lines communication mode because received is not read */ @@ -1368,18 +1359,19 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxD __HAL_SPI_CLEAR_OVRFLAG(hspi); } + + hspi->State = HAL_SPI_STATE_READY; + /* Unlock the process */ + __HAL_UNLOCK(hspi); + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - errorcode = HAL_ERROR; + return HAL_ERROR; } else { - hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** @@ -1390,9 +1382,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); @@ -1400,14 +1391,12 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } /* Process Locked */ @@ -1416,7 +1405,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1464,8 +1453,7 @@ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, u /* Enable TXE and ERR interrupt */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); -error : - return errorcode; + return HAL_OK; } /** @@ -1478,13 +1466,10 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) @@ -1497,8 +1482,7 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } /* Process Locked */ @@ -1559,8 +1543,7 @@ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, ui /* Enable RXNE and ERR interrupt */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); -error : - return errorcode; + return HAL_OK; } /** @@ -1572,11 +1555,11 @@ error : * @param Size amount of data to be sent and received * @retval HAL status */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); @@ -1588,14 +1571,12 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p if (!((tmp_state == HAL_SPI_STATE_READY) || \ ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } /* Process locked */ @@ -1609,7 +1590,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1649,8 +1630,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *p /* Enable TXE, RXNE and ERR interrupt */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); -error : - return errorcode; + return HAL_OK; } /** @@ -1661,9 +1641,8 @@ error : * @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) +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; /* Check tx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmatx)); @@ -1671,25 +1650,23 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); - if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_TX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; + hspi->pTxBuffPtr = (const uint8_t *)pData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; @@ -1734,9 +1711,9 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1746,16 +1723,16 @@ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1770,15 +1747,12 @@ error : */ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - /* Check rx dma handle */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); if (hspi->State != HAL_SPI_STATE_READY) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) @@ -1792,15 +1766,14 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); } - /* Process Locked */ - __HAL_LOCK(hspi); - if ((pData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hspi); + /* Set the transaction information */ hspi->State = HAL_SPI_STATE_BUSY_RX; hspi->ErrorCode = HAL_SPI_ERROR_NONE; @@ -1848,9 +1821,9 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -1860,16 +1833,16 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u __HAL_SPI_ENABLE(hspi); } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Rx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -1882,12 +1855,11 @@ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, u * @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, +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { uint32_t tmp_mode; HAL_SPI_StateTypeDef tmp_state; - HAL_StatusTypeDef errorcode = HAL_OK; /* Check rx & tx dma handles */ assert_param(IS_SPI_DMA_HANDLE(hspi->hdmarx)); @@ -1896,9 +1868,6 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Check Direction parameter */ assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Process locked */ - __HAL_LOCK(hspi); - /* Init temporary variables */ tmp_state = hspi->State; tmp_mode = hspi->Init.Mode; @@ -1906,16 +1875,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * if (!((tmp_state == HAL_SPI_STATE_READY) || ((tmp_mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp_state == HAL_SPI_STATE_BUSY_RX)))) { - errorcode = HAL_BUSY; - goto error; + return HAL_BUSY; } if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { - errorcode = HAL_ERROR; - goto error; + return HAL_ERROR; } + /* Process locked */ + __HAL_LOCK(hspi); + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ if (hspi->State != HAL_SPI_STATE_BUSY_RX) { @@ -1924,7 +1894,7 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Set the transaction information */ hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; hspi->TxXferSize = Size; hspi->TxXferCount = Size; hspi->pRxBuffPtr = (uint8_t *)pRxData; @@ -1969,9 +1939,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Enable Rx DMA Request */ @@ -1990,9 +1960,9 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * { /* Update SPI error code */ SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - errorcode = HAL_ERROR; - - goto error; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; } /* Check if the SPI is already enabled */ @@ -2001,16 +1971,17 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * /* Enable SPI peripheral */ __HAL_SPI_ENABLE(hspi); } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* Enable the SPI Error Interrupt Bit */ __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_ERR)); /* Enable Tx DMA Request */ SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; } /** @@ -2668,7 +2639,7 @@ __weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI state */ -HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi) { /* Return SPI handle state */ return hspi->State; @@ -2680,7 +2651,7 @@ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) * the configuration information for SPI module. * @retval SPI error code in bitmap format */ -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi) { /* Return SPI ErrorCode */ return hspi->ErrorCode; @@ -3219,7 +3190,7 @@ static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) */ static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3312,7 +3283,7 @@ static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; @@ -3460,7 +3431,7 @@ static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) */ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr); + *(__IO uint8_t *)&hspi->Instance->DR = *((const uint8_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr++; hspi->TxXferCount--; @@ -3486,7 +3457,7 @@ static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) { /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->Instance->DR = *((const uint16_t *)hspi->pTxBuffPtr); hspi->pTxBuffPtr += sizeof(uint16_t); hspi->TxXferCount--; diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_rcc.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_rcc.c index f45504b4e..f59fef4a7 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_rcc.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_rcc.c @@ -19,10 +19,10 @@ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_rcc.h" #ifdef USE_FULL_ASSERT - #include "stm32_assert.h" +#include "stm32_assert.h" #else - #define assert_param(expr) ((void)0U) -#endif +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ /** @addtogroup STM32F4xx_LL_Driver * @{ */ @@ -51,10 +51,10 @@ #if defined(SAI1) #if defined(RCC_DCKCFGR_SAI1SRC) #define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SAI1_CLKSOURCE) \ - || ((__VALUE__) == LL_RCC_SAI2_CLKSOURCE)) + || ((__VALUE__) == LL_RCC_SAI2_CLKSOURCE)) #elif defined(RCC_DCKCFGR_SAI1ASRC) #define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SAI1_A_CLKSOURCE) \ - || ((__VALUE__) == LL_RCC_SAI1_B_CLKSOURCE)) + || ((__VALUE__) == LL_RCC_SAI1_B_CLKSOURCE)) #endif /* RCC_DCKCFGR_SAI1SRC */ #endif /* SAI1 */ @@ -74,7 +74,7 @@ #define IS_LL_RCC_DFSDM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DFSDM1_CLKSOURCE)) #define IS_LL_RCC_DFSDM_AUDIO_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DFSDM1_AUDIO_CLKSOURCE) \ - || ((__VALUE__) == LL_RCC_DFSDM2_AUDIO_CLKSOURCE)) + || ((__VALUE__) == LL_RCC_DFSDM2_AUDIO_CLKSOURCE)) #elif defined(DFSDM1_Channel0) #define IS_LL_RCC_DFSDM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DFSDM1_CLKSOURCE)) @@ -83,7 +83,7 @@ #if defined(RCC_DCKCFGR_I2S2SRC) #define IS_LL_RCC_I2S_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2S1_CLKSOURCE) \ - || ((__VALUE__) == LL_RCC_I2S2_CLKSOURCE)) + || ((__VALUE__) == LL_RCC_I2S2_CLKSOURCE)) #else #define IS_LL_RCC_I2S_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2S1_CLKSOURCE)) #endif /* RCC_DCKCFGR_I2S2SRC */ @@ -189,7 +189,7 @@ ErrorStatus LL_RCC_DeInit(void) LL_RCC_HSI_Enable(); /* Wait for HSI READY bit */ - while(LL_RCC_HSI_IsReady() != 1U) + while (LL_RCC_HSI_IsReady() != 1U) {} /* Reset CFGR register */ @@ -219,7 +219,7 @@ ErrorStatus LL_RCC_DeInit(void) LL_RCC_HSI_SetCalibTrimming(0x10U); /* Wait for PLL READY bit to be reset */ - while(LL_RCC_PLL_IsReady() != 0U) + while (LL_RCC_PLL_IsReady() != 0U) {} /* Reset PLLCFGR register */ @@ -247,7 +247,8 @@ ErrorStatus LL_RCC_DeInit(void) #endif /* RCC_CIR_PLLSAIRDYIE */ /* Clear all interrupt flags */ - SET_BIT(RCC->CIR, RCC_CIR_LSIRDYC | RCC_CIR_LSERDYC | RCC_CIR_HSIRDYC | RCC_CIR_HSERDYC | RCC_CIR_PLLRDYC | RCC_CIR_CSSC); + SET_BIT(RCC->CIR, RCC_CIR_LSIRDYC | RCC_CIR_LSERDYC | RCC_CIR_HSIRDYC | RCC_CIR_HSERDYC | RCC_CIR_PLLRDYC | + RCC_CIR_CSSC); #if defined(RCC_CIR_PLLI2SRDYC) SET_BIT(RCC->CIR, RCC_CIR_PLLI2SRDYC); @@ -398,20 +399,20 @@ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) case LL_RCC_I2S1_CLKSOURCE_PLLSRC: /* I2S1 Clock is PLL Main source */ switch (LL_RCC_PLL_GetMainSource()) { - case LL_RCC_PLLSOURCE_HSE: /* I2S1 Clock is HSE Osc. */ - if (LL_RCC_HSE_IsReady()) - { - i2s_frequency = HSE_VALUE; - } - break; - - case LL_RCC_PLLSOURCE_HSI: /* I2S1 Clock is HSI Osc. */ - default: - if (LL_RCC_HSI_IsReady()) - { - i2s_frequency = HSI_VALUE; - } - break; + case LL_RCC_PLLSOURCE_HSE: /* I2S1 Clock is HSE Osc. */ + if (LL_RCC_HSE_IsReady()) + { + i2s_frequency = HSE_VALUE; + } + break; + + case LL_RCC_PLLSOURCE_HSI: /* I2S1 Clock is HSI Osc. */ + default: + if (LL_RCC_HSI_IsReady()) + { + i2s_frequency = HSI_VALUE; + } + break; } break; #endif /* RCC_DCKCFGR_I2SSRC || RCC_DCKCFGR_I2S1SRC */ @@ -445,20 +446,20 @@ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) case LL_RCC_I2S2_CLKSOURCE_PLLSRC: /* I2S2 Clock is PLL Main source */ switch (LL_RCC_PLL_GetMainSource()) { - case LL_RCC_PLLSOURCE_HSE: /* I2S2 Clock is HSE Osc. */ - if (LL_RCC_HSE_IsReady()) - { - i2s_frequency = HSE_VALUE; - } - break; - - case LL_RCC_PLLSOURCE_HSI: /* I2S2 Clock is HSI Osc. */ - default: - if (LL_RCC_HSI_IsReady()) - { - i2s_frequency = HSI_VALUE; - } - break; + case LL_RCC_PLLSOURCE_HSE: /* I2S2 Clock is HSE Osc. */ + if (LL_RCC_HSE_IsReady()) + { + i2s_frequency = HSE_VALUE; + } + break; + + case LL_RCC_PLLSOURCE_HSI: /* I2S2 Clock is HSI Osc. */ + default: + if (LL_RCC_HSI_IsReady()) + { + i2s_frequency = HSI_VALUE; + } + break; } break; @@ -578,20 +579,20 @@ uint32_t LL_RCC_GetSAIClockFreq(uint32_t SAIxSource) case LL_RCC_SAI2_CLKSOURCE_PLLSRC: switch (LL_RCC_PLL_GetMainSource()) { - case LL_RCC_PLLSOURCE_HSE: /* HSE clock used as SAI2 clock source */ - if (LL_RCC_HSE_IsReady()) - { - sai_frequency = HSE_VALUE; - } - break; - - case LL_RCC_PLLSOURCE_HSI: /* HSI clock used as SAI2 clock source */ - default: - if (LL_RCC_HSI_IsReady()) - { - sai_frequency = HSI_VALUE; - } - break; + case LL_RCC_PLLSOURCE_HSE: /* HSE clock used as SAI2 clock source */ + if (LL_RCC_HSE_IsReady()) + { + sai_frequency = HSE_VALUE; + } + break; + + case LL_RCC_PLLSOURCE_HSI: /* HSI clock used as SAI2 clock source */ + default: + if (LL_RCC_HSI_IsReady()) + { + sai_frequency = HSI_VALUE; + } + break; } break; @@ -639,20 +640,20 @@ uint32_t LL_RCC_GetSAIClockFreq(uint32_t SAIxSource) case LL_RCC_SAI1_B_CLKSOURCE_PLLSRC: switch (LL_RCC_PLL_GetMainSource()) { - case LL_RCC_PLLSOURCE_HSE: /* HSE clock used as SAI1 Block A or B clock source */ - if (LL_RCC_HSE_IsReady()) - { - sai_frequency = HSE_VALUE; - } - break; - - case LL_RCC_PLLSOURCE_HSI: /* HSI clock used as SAI1 Block A or B clock source */ - default: - if (LL_RCC_HSI_IsReady()) - { - sai_frequency = HSI_VALUE; - } - break; + case LL_RCC_PLLSOURCE_HSE: /* HSE clock used as SAI1 Block A or B clock source */ + if (LL_RCC_HSE_IsReady()) + { + sai_frequency = HSE_VALUE; + } + break; + + case LL_RCC_PLLSOURCE_HSI: /* HSI clock used as SAI1 Block A or B clock source */ + default: + if (LL_RCC_HSI_IsReady()) + { + sai_frequency = HSI_VALUE; + } + break; } break; #endif /* RCC_SAI1A_PLLSOURCE_SUPPORT */ @@ -699,7 +700,7 @@ uint32_t LL_RCC_GetSDIOClockFreq(uint32_t SDIOxSource) { SDIO_frequency = RCC_PLL_GetFreqDomain_48M(); } - break; + break; #if defined(RCC_PLLSAI_SUPPORT) case LL_RCC_CK48M_CLKSOURCE_PLLSAI: /* PLLSAI clock used as 48Mhz domain clock */ @@ -725,8 +726,8 @@ uint32_t LL_RCC_GetSDIOClockFreq(uint32_t SDIOxSource) case LL_RCC_SDIO_CLKSOURCE_SYSCLK: /* PLL clock used as SDIO clock source */ default: - SDIO_frequency = RCC_GetSystemClockFreq(); - break; + SDIO_frequency = RCC_GetSystemClockFreq(); + break; } #else /* PLL clock used as 48Mhz domain clock */ @@ -827,7 +828,7 @@ uint32_t LL_RCC_GetCECClockFreq(uint32_t CECxSource) default: if (LL_RCC_HSI_IsReady()) { - cec_frequency = HSI_VALUE/488U; + cec_frequency = HSI_VALUE / 488U; } break; } @@ -1054,7 +1055,7 @@ uint32_t LL_RCC_GetLTDCClockFreq(uint32_t LTDCxSource) if (LL_RCC_PLLSAI_IsReady()) { - ltdc_frequency = RCC_PLLSAI_GetFreqDomain_LTDC(); + ltdc_frequency = RCC_PLLSAI_GetFreqDomain_LTDC(); } return ltdc_frequency; @@ -1188,7 +1189,9 @@ uint32_t RCC_GetPCLK2ClockFreq(uint32_t HCLK_Frequency) */ uint32_t RCC_PLL_GetFreqDomain_SYS(uint32_t SYSCLK_Source) { - uint32_t pllinputfreq = 0U, pllsource = 0U, plloutputfreq = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; + uint32_t plloutputfreq = 0U; /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN SYSCLK = PLL_VCO / (PLLP or PLLR) @@ -1213,13 +1216,13 @@ uint32_t RCC_PLL_GetFreqDomain_SYS(uint32_t SYSCLK_Source) if (SYSCLK_Source == LL_RCC_SYS_CLKSOURCE_STATUS_PLL) { plloutputfreq = __LL_RCC_CALC_PLLCLK_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetP()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetP()); } #if defined(RCC_PLLR_SYSCLK_SUPPORT) else { plloutputfreq = __LL_RCC_CALC_PLLRCLK_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); } #endif /* RCC_PLLR_SYSCLK_SUPPORT */ @@ -1232,7 +1235,8 @@ uint32_t RCC_PLL_GetFreqDomain_SYS(uint32_t SYSCLK_Source) */ uint32_t RCC_PLL_GetFreqDomain_48M(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM ) * PLLN 48M Domain clock = PLL_VCO / PLLQ @@ -1254,7 +1258,7 @@ uint32_t RCC_PLL_GetFreqDomain_48M(void) break; } return __LL_RCC_CALC_PLLCLK_48M_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetQ()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetQ()); } #if defined(DSI) @@ -1264,7 +1268,8 @@ uint32_t RCC_PLL_GetFreqDomain_48M(void) */ uint32_t RCC_PLL_GetFreqDomain_DSI(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN DSICLK = PLL_VCO / PLLR @@ -1283,7 +1288,7 @@ uint32_t RCC_PLL_GetFreqDomain_DSI(void) break; } return __LL_RCC_CALC_PLLCLK_DSI_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); } #endif /* DSI */ @@ -1294,7 +1299,8 @@ uint32_t RCC_PLL_GetFreqDomain_DSI(void) */ uint32_t RCC_PLL_GetFreqDomain_I2S(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN I2SCLK = PLL_VCO / PLLR @@ -1313,7 +1319,7 @@ uint32_t RCC_PLL_GetFreqDomain_I2S(void) break; } return __LL_RCC_CALC_PLLCLK_I2S_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); } #endif /* RCC_DCKCFGR_I2SSRC || RCC_DCKCFGR_I2S1SRC */ @@ -1324,7 +1330,8 @@ uint32_t RCC_PLL_GetFreqDomain_I2S(void) */ uint32_t RCC_PLL_GetFreqDomain_SPDIFRX(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN SPDIFRXCLK = PLL_VCO / PLLR @@ -1343,7 +1350,7 @@ uint32_t RCC_PLL_GetFreqDomain_SPDIFRX(void) break; } return __LL_RCC_CALC_PLLCLK_SPDIFRX_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); } #endif /* SPDIFRX */ @@ -1355,7 +1362,9 @@ uint32_t RCC_PLL_GetFreqDomain_SPDIFRX(void) */ uint32_t RCC_PLL_GetFreqDomain_SAI(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U, plloutputfreq = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; + uint32_t plloutputfreq = 0U; /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN SAICLK = (PLL_VCO / PLLR) / PLLDIVR @@ -1378,10 +1387,10 @@ uint32_t RCC_PLL_GetFreqDomain_SAI(void) #if defined(RCC_DCKCFGR_PLLDIVR) plloutputfreq = __LL_RCC_CALC_PLLCLK_SAI_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR(), LL_RCC_PLL_GetDIVR()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR(), LL_RCC_PLL_GetDIVR()); #else plloutputfreq = __LL_RCC_CALC_PLLCLK_SAI_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(), - LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); + LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR()); #endif /* RCC_DCKCFGR_PLLDIVR */ return plloutputfreq; @@ -1396,7 +1405,8 @@ uint32_t RCC_PLL_GetFreqDomain_SAI(void) */ uint32_t RCC_PLLSAI_GetFreqDomain_SAI(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLLSAI_VCO = (HSE_VALUE or HSI_VALUE / PLLSAIM) * PLLSAIN SAI domain clock = (PLLSAI_VCO / PLLSAIQ) / PLLSAIDIVQ @@ -1418,7 +1428,7 @@ uint32_t RCC_PLLSAI_GetFreqDomain_SAI(void) break; } return __LL_RCC_CALC_PLLSAI_SAI_FREQ(pllinputfreq, LL_RCC_PLLSAI_GetDivider(), - LL_RCC_PLLSAI_GetN(), LL_RCC_PLLSAI_GetQ(), LL_RCC_PLLSAI_GetDIVQ()); + LL_RCC_PLLSAI_GetN(), LL_RCC_PLLSAI_GetQ(), LL_RCC_PLLSAI_GetDIVQ()); } #if defined(RCC_PLLSAICFGR_PLLSAIP) @@ -1428,7 +1438,8 @@ uint32_t RCC_PLLSAI_GetFreqDomain_SAI(void) */ uint32_t RCC_PLLSAI_GetFreqDomain_48M(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLLSAI_VCO = (HSE_VALUE or HSI_VALUE / PLLSAIM) * PLLSAIN 48M Domain clock = PLLSAI_VCO / PLLSAIP @@ -1450,7 +1461,7 @@ uint32_t RCC_PLLSAI_GetFreqDomain_48M(void) break; } return __LL_RCC_CALC_PLLSAI_48M_FREQ(pllinputfreq, LL_RCC_PLLSAI_GetDivider(), - LL_RCC_PLLSAI_GetN(), LL_RCC_PLLSAI_GetP()); + LL_RCC_PLLSAI_GetN(), LL_RCC_PLLSAI_GetP()); } #endif /* RCC_PLLSAICFGR_PLLSAIP */ @@ -1461,7 +1472,8 @@ uint32_t RCC_PLLSAI_GetFreqDomain_48M(void) */ uint32_t RCC_PLLSAI_GetFreqDomain_LTDC(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLLSAI_VCO = (HSE_VALUE or HSI_VALUE / PLLSAIM) * PLLSAIN LTDC Domain clock = (PLLSAI_VCO / PLLSAIR) / PLLSAIDIVR @@ -1496,7 +1508,9 @@ uint32_t RCC_PLLSAI_GetFreqDomain_LTDC(void) */ uint32_t RCC_PLLI2S_GetFreqDomain_SAI(void) { - uint32_t plli2sinputfreq = 0U, plli2ssource = 0U, plli2soutputfreq = 0U; + uint32_t plli2sinputfreq = 0; + uint32_t plli2ssource = 0U; + uint32_t plli2soutputfreq = 0U; /* PLLI2S_VCO = (HSE_VALUE or HSI_VALUE / PLLI2SM) * PLLI2SN SAI domain clock = (PLLI2S_VCO / PLLI2SQ) / PLLI2SDIVQ @@ -1525,10 +1539,10 @@ uint32_t RCC_PLLI2S_GetFreqDomain_SAI(void) #if defined(RCC_DCKCFGR_PLLI2SDIVQ) plli2soutputfreq = __LL_RCC_CALC_PLLI2S_SAI_FREQ(plli2sinputfreq, LL_RCC_PLLI2S_GetDivider(), - LL_RCC_PLLI2S_GetN(), LL_RCC_PLLI2S_GetQ(), LL_RCC_PLLI2S_GetDIVQ()); + LL_RCC_PLLI2S_GetN(), LL_RCC_PLLI2S_GetQ(), LL_RCC_PLLI2S_GetDIVQ()); #else plli2soutputfreq = __LL_RCC_CALC_PLLI2S_SAI_FREQ(plli2sinputfreq, LL_RCC_PLLI2S_GetDivider(), - LL_RCC_PLLI2S_GetN(), LL_RCC_PLLI2S_GetR(), LL_RCC_PLLI2S_GetDIVR()); + LL_RCC_PLLI2S_GetN(), LL_RCC_PLLI2S_GetR(), LL_RCC_PLLI2S_GetDIVR()); #endif /* RCC_DCKCFGR_PLLI2SDIVQ */ return plli2soutputfreq; @@ -1542,7 +1556,8 @@ uint32_t RCC_PLLI2S_GetFreqDomain_SAI(void) */ uint32_t RCC_PLLI2S_GetFreqDomain_SPDIFRX(void) { - uint32_t pllinputfreq = 0U, pllsource = 0U; + uint32_t pllinputfreq = 0U; + uint32_t pllsource = 0U; /* PLLI2S_VCO = (HSE_VALUE or HSI_VALUE / PLLI2SM) * PLLI2SN SPDIFRX Domain clock = PLLI2S_VCO / PLLI2SP @@ -1572,7 +1587,9 @@ uint32_t RCC_PLLI2S_GetFreqDomain_SPDIFRX(void) */ uint32_t RCC_PLLI2S_GetFreqDomain_I2S(void) { - uint32_t plli2sinputfreq = 0U, plli2ssource = 0U, plli2soutputfreq = 0U; + uint32_t plli2sinputfreq = 0U; + uint32_t plli2ssource = 0U; + uint32_t plli2soutputfreq = 0U; /* PLLI2S_VCO = (HSE_VALUE or HSI_VALUE / PLLI2SM) * PLLI2SN I2S Domain clock = PLLI2S_VCO / PLLI2SR @@ -1610,7 +1627,9 @@ uint32_t RCC_PLLI2S_GetFreqDomain_I2S(void) */ uint32_t RCC_PLLI2S_GetFreqDomain_48M(void) { - uint32_t plli2sinputfreq = 0U, plli2ssource = 0U, plli2soutputfreq = 0U; + uint32_t plli2sinputfreq = 0U; + uint32_t plli2ssource = 0U; + uint32_t plli2soutputfreq = 0U; /* PLL48M_VCO = (HSE_VALUE or HSI_VALUE / PLLI2SM) * PLLI2SN 48M Domain clock = PLLI2S_VCO / PLLI2SQ diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_spi.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_spi.c index 02a074068..1371e911e 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_spi.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_spi.c @@ -119,7 +119,7 @@ * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx) { ErrorStatus status = ERROR; @@ -381,7 +381,7 @@ void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) * - SUCCESS: SPI registers are de-initialized * - ERROR: SPI registers are not de-initialized */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx) { return LL_SPI_DeInit(SPIx); } diff --git a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_usb.c b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_usb.c index 2570d422b..40b6d83a4 100644 --- a/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_usb.c +++ b/stm32cube/stm32f4xx/drivers/src/stm32f4xx_ll_usb.c @@ -798,17 +798,17 @@ HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef } else { - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & - (((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket) << 19)); + pktcnt = (uint16_t)((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket); + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (pktcnt << 19)); + + if (ep->type == EP_TYPE_ISOC) + { + USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_MULCNT); + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_MULCNT & (pktcnt << 29)); + } } USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len); - - if (ep->type == EP_TYPE_ISOC) - { - USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_MULCNT); - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_MULCNT & (1U << 29)); - } } if (dma == 1U) diff --git a/stm32cube/stm32f4xx/release_note.html b/stm32cube/stm32f4xx/release_note.html index 58daf9f31..25e8070e2 100644 --- a/stm32cube/stm32f4xx/release_note.html +++ b/stm32cube/stm32f4xx/release_note.html @@ -37,7 +37,7 @@

                Purpose

              • A consistent set of middleware components such as RTOS, USB, TCP/IP, Graphics
              • All embedded software utilities come with a full set of examples.
              -
            • The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements STM32Cube architecture
            • +
            • The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements STM32Cube architecture
            • The HAL (Hardware Abstraction Layer) drivers provided within this package supports the STM32F405/415/407/417/427/437/429/439/401xC/401xE/ 411xC/411xE/412x/413/423/446/469/479/410xx Lines

                @@ -60,12 +60,595 @@

                Purpose

                Update History

                - +

                Maintenance release

                Main Changes

                • General updates to fix known defects and implementation enhancements.
                • +
                • Patch release to deploy HAL Ethernet enhancements.
                • +
                • General fixes to support GCC11 and GCC12 in all STM32CubeIDE projects.
                • +
                • Upgrade USB Device Lib to use V2.11.3.
                • +
                • Upgrade USB Host Lib to use V3.5.2.

                • +
                • CMSIS +
                    +
                  • Add MCO2PRE[2:0] and MCO2[1:0] bits definition within CMSIS files.
                  • +
                • +
                • HAL +
                    +
                  • Enhance HAL code quality for MISRA-C Rule-8.13 by adding const qualifiers.
                  • +
                  • HAL Generic +
                      +
                    • Update stm32h7xx_hal_conf_template.h file to support legacy HAL ETH driver.
                    • +
                  • +
                  • HAL/LL ADC +
                      +
                    • Add macro UNUSED() to avoid the generation of a warning related to the unused argument ‘hadc’.
                    • +
                  • +
                  • HAL RCC +
                      +
                    • Remove duplicate macro definition __HAL_RCC_AHB2_FORCE_RESET() for STM32F423xx devices.
                    • +
                  • +
                  • HAL EXTI +
                      +
                    • Add macro UNUSED() to avoid the generation of a warning related to the unused argument ‘Edge’.
                    • +
                  • +
                  • HAL HASH +
                      +
                    • Read the last remaining bytes (3 or 2 or 1) of the data in a temporary variable (taking into account swap mode) and enter this variable into the HASH->DIN when the data is not a multiple of 4 bytes.
                    • +
                  • +
                  • HAL FLASH +
                      +
                    • Remove HAL_LOCK()/HAL_UNLOCK() APIs from HAL_FLASH_Program_IT() and HAL_FLASHEx_Erase_IT() APIs.
                    • +
                  • +
                  • LL DMA +
                      +
                    • Fix typo in LL_DMA_GetCurrentTargetMem() API.
                    • +
                  • +
                  • HAL LPTIM +
                      +
                    • Remove redundant macro IS_LPTIM_AUTORELOAD().
                    • +
                  • +
                  • HAL/LL CORTEX +
                      +
                    • Updated HAL_MPU_ConfigRegion() API to allow the configuration of the MPU registers independently of the value of Enable/Disable field.
                    • +
                    • Add new HAL_MPU_EnableRegion() / HAL_MPU_DisableRegion() APIs.
                    • +
                    • Add missing parenthesis() in LL_MPU_ConfigRegion() API.
                    • +
                  • +
                  • HAL DSI +
                      +
                    • Align DSI Initialization sequence to the recommended ‘Programing procedure overview’ part to avoid DSI read LCD controller register 0x0A error.
                    • +
                  • +
                  • HAL QSPI +
                      +
                    • Clear the QSPI.AR register when sCommand.AddressMode is QSPI_ADDRESS_NONE.
                    • +
                  • +
                  • HAL I2S +
                      +
                    • Update HAL I2S driver to fix misplaced __HAL_LOCK() API and remove ‘go to’ instruction.
                    • +
                  • +
                  • HAL SPI +
                      +
                    • Update HAL SPI driver to remove “got to” instruction and avoid misplaced __HAL_LOCK() API issue.
                    • +
                  • +
                  • HAL UART +
                      +
                    • Rework of UART_WaitOnFlagUntilTimeout() API to avoid being stuck forever when UART overrun error occurs and to enhance behavior.
                    • +
                  • +
                  • HAL ETH +
                      +
                    • Add missing system time in different PTP APIs.
                    • +
                    • Rename ETH_TxPacketConfig_t to ETH_TxPacketConfigTypeDef.
                    • +
                    • Update ETH_Start_IT sequence.
                    • +
                    • Update the PTP configuration state macros and Fix the wrong Doxygen comment descriptions.
                    • +
                    • Fix wrong Ethernet constant definitions .
                    • +
                    • Add condition to get the Timestamp only when it was captured (Check on Last Descriptor and TimeStamp flag set).
                    • +
                    • Replace ETH_RX_BUF_SIZE define in ETH_UpdateDescriptor() and ETH_DMARxDescListInit() by Init.RxBuffLen.
                    • +
                    • Get the latest buffer length received and not the predefined ethernet frame length.
                    • +
                    • Update HAL_ETH_SetMDIOClockRange API to manage different frequency ranges.
                    • +
                    • Remove multiple volatile reads or writes in interrupt handler for better performance.
                    • +
                    • Move the MMC interrupts disable section from HAL_ETH_Start_IT() to HAL_ETH_Init().
                    • +
                    • Change the way to increment the descriptor index within HAL_ETH_ReleaseTxPacket().
                    • +
                    • Update the entry to critical section without enabling unwanted global interrupts.
                    • +
                    • Add support of CRC stripping for Type frames (CSTF) feature.
                    • +
                    • Fix MisraC-2012 and MCU ASTYLE warnings and remove empty lines.
                    • +
                  • +
                  • HAL USB +
                      +
                    • Ensure to reactivate the usb channel in case of transfer error.
                    • +
                  • +
                  • LL UTILS +
                      +
                    • Fix a note about Ticks parameter.
                    • +
                  • +
                • +
                • BSP +
                    +
                  • BSP Boards +
                      +
                    • STM32F413H-Discovery +
                        +
                      • Update to manage touch screen components (ft6x06 & ft3x67) available on different STM32F413H-Discovery board revisions in dynamic approach.
                      • +
                    • +
                    • STM32412G-Discovery +
                        +
                      • Update to manage touch screen components (ft6x06 & ft3x67) available on different STM32412G-Discovery board revisions in dynamic approach.
                      • +
                    • +
                    • STM32469I-Discovery +
                        +
                      • Update to manage lcd controller components (nt35510 & otm8009a) available on different STM32469I-Discovery board revisions in dynamic approach.
                      • +
                    • +
                  • +
                  • BSP Components +
                      +
                    • nt35510 +
                        +
                      • Fix setting of DPRSLCTR register.
                      • +
                    • +
                    • lan8742 +
                        +
                      • Remove unnecessary delay in PHY driver.
                      • +
                    • +
                  • +
                • +
                • Middlewares +
                    +
                  • Upgrade USB Device Lib to use V2.11.3.
                  • +
                  • Upgrade USB Host Lib to use V3.5.2.
                  • +
                • +
                • Projects +
                    +
                  • Applications MW LwIP +
                      +
                    • Fix Confusing comment in ethernet_if.
                    • +
                    • Fix Wrong use of DHCP API in application code & ethernet_link_thread() API.
                    • +
                    • Fix Ethernet low_level_init() API does not handle return code from LAN8742_init() API.
                    • +
                  • +
                  • Examples I2C +
                      +
                    • Fix wrong check condition on HAL_TIMEOUT: this value is no longer returned by the HAL_I2C_IsDeviceReady() API.
                    • +
                  • +
                • +
                • For the complete list of changes, please refer to the release notes of each firmware component

                • +
                +

                Contents

                +
              Drivers
              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
              Drivers
              NameVersionRelease note
              CMSISV5.9.0release notes
              STM32F4xx CMSISV2.6.10release notes
              STM32F4xx HALV1.8.3release notes
              BSP STM32469I-EVALV2.1.2release notes
              BSP STM32469I-DiscoveryV2.2.0release notes
              BSP STM32446E-EVALV2.1.2release notes
              BSP STM324xG-EVALV3.0.4release notes
              BSP STM324x9I-EVALV3.0.3release notes
              BSP STM32F4-DiscoveryV2.1.5release notes
              BSP STM32F401-DiscoveryV2.2.5release notes
              BSP STM32F411E-DiscoveryV1.0.6release notes
              BSP STM32F429I-DiscoveryV2.1.8release notes
              BSP STM32F4xx-NucleoV1.2.9release notes
              BSP STM32F4xx-Nucleo 144V1.0.5release notes
              BSP STM32412G-DiscoveryV2.1.0release notes
              BSP STM32F413H-DiscoveryV1.1.0release notes
              BSP Adafruit_ShieldV3.0.6release notes
              BSP Components CommonV4.0.1release notes
              BSP Components ampire480272V1.0.4release notes
              BSP Components ampire640480V1.0.4release notes
              BSP Components cs43l22V2.0.5release notes
              BSP Components ili9325V1.2.4release notes
              BSP Components ili9341V1.0.3release notes
              BSP Components l3gd20V2.0.2release notes
              BSP Components lis302dlV2.0.1release notes
              BSP Components lis3dshV2.0.1release notes
              BSP Components lsm303dlhcV2.0.2release notes
              BSP Components ov2640V1.0.3release notes
              BSP Components st7735V1.1.6release notes
              BSP Components stmpe1600V1.1.2release notes
              BSP Components stmpe811V2.0.3release notes
              BSP Components ts3510V1.0.3release notes
              BSP Components wm8994V2.3.2release notes
              BSP Components mfxstm32l152V2.0.5release notes
              BSP Components s5k5cagV1.0.2release notes
              BSP Components n25q256aV1.0.2release notes
              BSP Components exc7200V1.0.3release notes
              BSP Components ft6x06V1.1.1release notes
              BSP Components ft3x67V1.0.2release notes
              BSP Components otm8009aV1.0.7release notes
              BSP Components s25fl512sV1.0.1release notes
              BSP Components n25q512aV1.0.2release notes
              BSP Components n25q128aV1.0.3release notes
              BSP Components ls016b8uyV1.0.2release notes
              BSP Components st7789h2V1.1.5release notes
              BSP Components ov5640V2.0.1release notes
              BSP Components i3g4250dV1.0.1release notes
              BSP Components lsm303agrV1.0.2release notes
              BSP Components nt35510V1.0.3release notes
              BSP Components dp83848V1.0.2release notes
              BSP Components lan8742V1.0.4release notes
              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
              Middlewares
              NameVersionRelease note
              STemWinV5.44release notes
              STM32 PDM audio software decoding LibraryV3.5.1release notes
              STM32 USB Device LibraryV2.11.3release notes
              STM32 USB Host LibraryV3.5.2release notes
              FatFSR0.12crelease notes ST modified 20230818 release notes
              FreeRTOSV10.3.1release notes ST modified 20230818 release notes
              LwIPV2.1.2release notes ST modified ST modified 20230828 release notes
              MbedTLSV2.16.2release notesST modified 20231024 release notes
              LibJPEGV8drelease notes ST modified 20190201 release notes
              TouchGFXv4.10.0release notes
              + + + + + + + + + + + + + + + + + + + + + + + + + + +
              Utilities
              NameVersionRelease note
              CPUV1.1.4release notes
              FontsV1.0.3release notes
              LogV1.0.4release notes
              +

              Known Limitations

              +
                +
              • USB_Device_Standalone application for STM324x9I_EVAL +
                  +
                • MDK-ARM and STM32CubeIDE projects are provided with optimization set to None, to avoid audio glitch when USB cable is disconnected
                • +
              • +
              • STemWin demonstration for STM32F413H-Discovery +
                  +
                • Issue on audio recorder module with MDK-ARM, to be fixed for next releases.
                • +
              • +
              • The following STM32CubeIDE projects include only Release configuration : +
                  +
                • STM32446E_EVAL/Demonstrations/STemWin
                • +
                • STM324x9I_EVAL/Demonstrations/STemWin
                • +
                • STM324xG_EVAL/Demonstrations/STemWin
                • +
                • STM324x9I_EVAL/Applications/FatFs/FatFs_MultiDrives
                • +
                • STM324x9I_EVAL/Applications/FatFs/FatFs_uSD
                • +
                • STM324xG_EVAL/Applications/FatFs/FatFs_MultiDrives
                • +
                • STM324xG_EVAL/Applications/FatFs/FatFs_uSD
                • +
                • STM324x9I_EVAL/Applications/USB_Host/AUDIO_Standalone
                • +
                • STM324xG_EVAL/Applications/USB_Host/AUDIO_Standalone
                • +
                • STM324x9I_EVAL/Applications/USB_Host/DynamicSwitch_Standalone
                • +
                • STM324x9I_EVAL/Applications/LwIP/LwIP_TFTP_Server
                • +
                • STM324xG_EVAL/Applications/LwIP/LwIP_TFTP_Server
                • +
              • +
              • The following STM32CubeIDE project include only Debug configuration : +
                  +
                • STM32469I_EVAL/Applications/Display/LCD_DSI_ImagesSlider
                • +
              • +
              • Only template projects migrated to Arm Compiler 6 with MDK-ARM 5.31 (“AC-like Warnings” mode).
              • +
              +

              Development Toolchains and Compilers

              +
                +
              • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-Link.
              • +
              • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.32 minimum (ARM Compiler 5 (“AC5-like Warnings” selected)) +
                  +
                • Note : MDK-ARM 5.38 comes by default with AC6 only. To use it with AC5, please follow the steps available in this AN: +
                    +
                  • https://developer.arm.com/documentation/ka005073/latest/
                  • +
                • +
              • +
              • STM32CubeIDE toolchain v1.15.0
              • +
              +

              Supported Devices and EVAL boards

              +
                +
              • STM32F469xx/479xx devices STM32469I_EVAL board RevC
              • +
              • STM32F469xx and STM32469I-Discovery board RevC
              • +
              • STM32F410xx and STM32F410xx-Nucleo board RevC
              • +
              • STM32F446xx devices STM32446E_EVAL board RevB
              • +
              • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
              • +
              • STM32F429xx and STM32F429I-Discovery board RevB
              • +
              • STM32F407xx/417xx devices and STM324xG-EVAL board RevC
              • +
              • STM32F407xx and STM32F4-Discovery board RevC
              • +
              • STM32F401xC and STM32F401C-Discovery board RevB
              • +
              • STM32F401xE and STM32F401RE-Nucleo board RevC
              • +
              • STM32F411xE and STM32F411RE-Nucleo board RevC
              • +
              • STM32F411xE and STM32F411E-Discovery board RevC
              • +
              • STM32F412ZG and STM32F412ZG-Discovery board RevD
              • +
              • STM32F446ZE and STM32F446ZE-Nucleo board RevB
              • +
              • STM32F429ZI and STM32F429ZI-Nucleo board RevB
              • +
              • STM32F412ZG and STM32F412ZG-Nucleo board RevB
              • +
              • STM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
              • +
              • STM32F413ZHT6U and STM32F413H-Discovery board RevD
              • +
              +

              Backward Compatibility

              +
                +
              • None
              • +
              +

              Dependencies

              +
                +
              • None
              • +
              +
              +
              +
              + +
              +

              Maintenance release

              +

              Main Changes

              +
                +
              • General updates to fix known defects and implementation enhancements.
              • Deploy the support of STM32CubeIDE toolchain on all projects
                • SW4STM32 toolchain support is discontinued (Warning : Any reference to SW4STM32 in STM32CubeF4 firmware package documents should be interpreted as STM32CubeIDE).
                • @@ -312,7 +895,7 @@

                  Main Changes

              • For the complete list of changes, please refer to the release notes of each firmware component

              -

              Contents

              +

              Contents

              @@ -669,7 +1252,7 @@

              Contents

              Drivers
              -

              Known Limitations

              +

              Known Limitations

              • USB_Device_Standalone application for STM324x9I_EVAL
                  @@ -697,7 +1280,7 @@

                  Known Limitations

              • Only template projects migrated to Arm Compiler 6 with MDK-ARM 5.31 (“AC-like Warnings” mode).
              -

              Development Toolchains and Compilers

              +

              Development Toolchains and Compilers

              • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.4 + ST-Link.
              • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31 @@ -706,7 +1289,7 @@

                Development Toolchains and Compile

            • STM32CubeIDE toolchain v1.14.0
            -

            Supported Devices and EVAL boards

            +

            Supported Devices and EVAL boards

            • STM32F469xx/479xx devices STM32469I_EVAL board RevC
            • STM32F469xx and STM32469I-Discovery board RevC
            • @@ -727,11 +1310,11 @@

              Supported Devices and EVAL boards

              STM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
            • STM32F413ZHT6U and STM32F413H-Discovery board RevD
            -

            Backward Compatibility

            +

            Backward Compatibility

            • None
            -

            Dependencies

            +

            Dependencies

            • None
            @@ -740,8 +1323,8 @@

            Dependencies

            -

            Maintenance release

            -

            Main Changes

            +

            Maintenance release

            +

            Main Changes

            • Patch release of STM32CubeF4 Firmware Package.

            • HAL @@ -756,7 +1339,7 @@

              Main Changes

        -

        Contents

        +

        Contents

        @@ -778,8 +1361,8 @@

        Contents

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • General updates to fix known defects and implementation enhancements.
        • All source files: update disclaimer to add reference to the new license agreement.
        • @@ -983,7 +1566,7 @@

          Main Changes

      • For the complete list of changes, please refer to the release notes of each firmware component

      • -

        Contents

        +

        Contents

        @@ -1340,7 +1923,7 @@

        Contents

        Drivers
        -

        Known Limitations

        +

        Known Limitations

        • USB_Device_Standalone application for STM324x9I_EVAL
            @@ -1353,13 +1936,13 @@

            Known Limitations

          • SW4STM32 projects are not provided for all EVAL demonstrations.
          • Only template projects migrated to Arm Compiler 6 with MDK-ARM 5.31 (“AC-like Warnings” mode).
          -

          Development Toolchains and Compilers

          +

          Development Toolchains and Compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.4 + ST-Link.
          • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31
          • System Workbench for STM32 (SW4STM32) (7-2018-q2-update) toolchain v2.9.0 + ST-Link
          -

          Supported Devices and EVAL boards

          +

          Supported Devices and EVAL boards

          • STM32F469xx/479xx devices STM32469I_EVAL board RevC
          • STM32F469xx and STM32469I-Discovery board RevC
          • @@ -1380,11 +1963,11 @@

            Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
          • STM32F413ZHT6U and STM32F413H-Discovery board RevD
          -

          Backward Compatibility

          +

          Backward Compatibility

          • None
          -

          Dependencies

          +

          Dependencies

          • None
          @@ -1393,8 +1976,8 @@

          Dependencies

          -

          Maintenance release

          -

          Main Changes

          +

          Maintenance release

          +

          Main Changes

          • General updates to fix known defects and enhancements implementation.

          • CMSIS updates @@ -1501,7 +2084,7 @@

            Main Changes

      -

      Contents

      +

      Contents

      @@ -1528,8 +2111,8 @@

      Contents

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release to mainly fix a wrong system clock configuration in some STM32F411/412/413 projects.

      • HAL @@ -1548,7 +2131,7 @@

        Main Changes

      -

      Contents

      +

      Contents

      @@ -1570,8 +2153,8 @@

      Contents

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • General updates to fix known defects and enhancements implementation
      • Add new HAL FMPSMBUS extended driver to support FMPSMBUS fast Mode Plus.
      • @@ -1859,7 +2442,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component
    • -

      Contents

      +

      Contents

      @@ -2201,7 +2784,7 @@

      Contents

      Drivers
      -

      Known Limitations

      +

      Known Limitations

      • USB_Device_Standalone application for STM324x9I_EVAL
          @@ -2214,13 +2797,13 @@

          Known Limitations

        • SW4STM32 projects are not provided for all EVAL demonstrations.
        • Only template projects migrated to Arm Compiler 6 with MDK-ARM 5.31 (“AC-like Warnings” mode).
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.4 + ST-Link.
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31
        • System Workbench for STM32 (SW4STM32) toolchain V2.9.0 + ST-Link
        -

        Supported Devices and EVAL boards

        +

        Supported Devices and EVAL boards

        • STM32F469xx/479xx devices STM32469I_EVAL board RevC
        • STM32F469xx and STM32469I-Discovery board RevC
        • @@ -2241,11 +2824,11 @@

          Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
        • STM32F413ZHT6U and STM32F413H-Discovery board RevD
        -

        Backward Compatibility

        +

        Backward Compatibility

        • None
        -

        Dependencies

        +

        Dependencies

        • None
        @@ -2254,8 +2837,8 @@

        Dependencies

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • Patch release of STM32CubeF4 Firmware Package.

        • HAL

          @@ -2269,7 +2852,7 @@

          Main Changes

    -

    Contents

    +

    Contents

    @@ -2291,8 +2874,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Patch release to fix known defects and enhancements implementation.

    • HAL

      @@ -2323,7 +2906,7 @@

      Main Changes

    -

    Contents

    +

    Contents

    @@ -2345,8 +2928,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Add new HAL FMPSMBUS and LL FMPI2C drivers
    • General updates to fix known defects and enhancements implementation
    • @@ -2447,7 +3030,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component

  • -

    Contents

    +

    Contents

    @@ -2774,7 +3357,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -2786,13 +3369,13 @@

        Known Limitations

    • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2 + ST-Link.
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.27.1
    • System Workbench for STM32 (SW4STM32) toolchain V2.9.0 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -2813,11 +3396,11 @@

      Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -2826,8 +3409,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Patch release to fix known defects and enhancements implementation

    • HAL @@ -2848,7 +3431,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component

  • -

    Contents

    +

    Contents

    @@ -2876,8 +3459,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Patch release to fix mainly the I2C send break issue with IT processes API’s
    • HAL I2C update @@ -2909,7 +3492,7 @@

      Main Changes

    • Software Quality improvement with a fix ofCodeSonar warning on PCD_Port_IRQHandler() and HCD_Port_IRQHandler()interrupt handlers
    -

    Contents

    +

    Contents

    Drivers
    @@ -2932,8 +3515,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • HAL
        @@ -3015,7 +3598,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component
    -

    Contents

    +

    Contents

    Drivers
    @@ -3337,7 +3920,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -3349,13 +3932,13 @@

        Known Limitations

    • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2 + ST-Link.
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.25
    • System Workbench for STM32 (SW4STM32) toolchain V2.6.0 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -3376,11 +3959,11 @@

      Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -3389,8 +3972,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Maintenance release:
        @@ -3402,8 +3985,8 @@

        Main Changes

        -

        Maintenance release

        -

        Main Changes

        +

        Maintenance release

        +

        Main Changes

        • Thanks to the acquisition of Draupner Graphics A/S, ST is extending the STM32 ecosystem with advanced and easy to use graphic software solution enabling stunning GUI additions to embedded devices. TouchGFX solution is now fully part of STM32CubeF4.
        • TouchGFX examples and demonstrations can be accessed directly through the TouchGFX Designer tool. Here you simply create a new project, select the appropriate ST board in the Application Template section and select whatever demonstration or example you want in the UI Template selector. After this you will have a TouchGFX application ready to compile and flash to the selected ST board. More information are available here

        • @@ -3430,7 +4013,7 @@

          Main Changes

      • For the complete list of changes, please refer to the release notes of each firmware component

      -

      Contents

      +

      Contents

      @@ -3752,7 +4335,7 @@

      Contents

      Drivers
      -

      Known Limitations

      +

      Known Limitations

      • USB_Device_Standalone application for STM324x9I_EVAL
          @@ -3768,13 +4351,13 @@

          Known Limitations

      • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain V8.20.2 + ST-Link.
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.25
      • System Workbench for STM32 (SW4STM32) toolchain V2.6.0 + ST-Link
      -

      Supported Devices and EVAL boards

      +

      Supported Devices and EVAL boards

      • STM32F469xx/479xx devices STM32469I_EVAL board RevC
      • STM32F469xx and STM32469I-Discovery board RevB
      • @@ -3795,11 +4378,11 @@

        Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
      • STM32F413ZHT6U and STM32F413H-Discovery board RevD
      -

      Backward Compatibility

      +

      Backward Compatibility

      • None
      -

      Dependencies

      +

      Dependencies

      • None
      @@ -3808,8 +4391,8 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • General updates to fix known defects and enhancements implementation

      • HAL @@ -3839,7 +4422,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component

    -

    Contents

    +

    Contents

    @@ -4156,7 +4739,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -4169,13 +4752,13 @@

        Known Limitations

    • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.23 + Keil.STM32F4xx_DFP.2.11.0.pack
    • System Workbench for STM32 (SW4STM32) toolchain V1.14
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -4196,11 +4779,11 @@

      Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -4209,12 +4792,12 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Package Clean-up: remove unwanted project folders
    -

    Contents

    +

    Contents

    @@ -4531,7 +5114,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -4544,13 +5127,13 @@

        Known Limitations

    • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.23 + Keil.STM32F4xx_DFP.2.11.0.pack
    • System Workbench for STM32 (SW4STM32) toolchain V1.14
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -4571,11 +5154,11 @@

      Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -4584,8 +5167,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • General updates to be compliant with Linux platforms
    • General update to fix known defects and several implementations enhancement
    • @@ -4644,7 +5227,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component
  • -

    Contents

    +

    Contents

    @@ -4961,7 +5544,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -4974,13 +5557,13 @@

        Known Limitations

    • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.23 + Keil.STM32F4xx_DFP.2.11.0.pack
    • System Workbench for STM32 (SW4STM32) toolchain V1.14
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -5001,11 +5584,11 @@

      Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -5014,8 +5597,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • General update to fix known defects and several implementations enhancement

    • HAL @@ -5048,7 +5631,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component

  • -

    Contents

    +

    Contents

    @@ -5360,7 +5943,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -5368,14 +5951,14 @@

        Known Limitations

    • TrueSTUDIO and SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.23 + Keil.STM32F4xx_DFP.2.11.0.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v7.1.2
    • System Workbench for STM32 (SW4STM32) toolchain V1.13
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -5396,11 +5979,11 @@

      Supported Devices and EVAL boardsSTM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -5409,8 +5992,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Add the support of the STM32F413H-Discovery board
        @@ -5485,7 +6068,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component

    -

    Contents

    +

    Contents

    @@ -5797,7 +6380,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -5805,14 +6388,14 @@

        Known Limitations

    • SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.80.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.22 + Keil.STM32F4xx_DFP.2.11.0.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.5.2
    • System Workbench for STM32 (SW4STM32) toolchain V1.13
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -5833,11 +6416,11 @@

      Supported Devices and EVAL boards<
    • STM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
    • STM32F413ZHT6U and STM32F413H-Discovery board RevD
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -5846,8 +6429,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Official release to add the support of STM32F413xx and STM32F423xx devices
    • Fix known defects and several implementation enhancement

    • @@ -5897,7 +6480,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component

  • -

    Contents

    +

    Contents

    @@ -6209,7 +6792,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -6218,14 +6801,14 @@

        Known Limitations

      • TrueSTUDIO and SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
      • STemWin sample demo applications with all STM32 platforms are not fully functional with MDK-ARM toolchain: the application doesn t run successfully after the second hit of the Hide Button. in fact when presing the button again while the progress bar displays the next steps, pressing Hide or Next Buttons are not working anymore.
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain v7.60.1
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.21a + Keil.STM32F4xx_DFP.2.11.0.pack
      • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.5.2
      • System Workbench for STM32 (SW4STM32) toolchain V1.10
      -

      Supported Devices and EVAL boards

      +

      Supported Devices and EVAL boards

      • STM32F469xx/479xx devices STM32469I_EVAL board RevC
      • STM32F469xx and STM32469I-Discovery board RevB
      • @@ -6245,11 +6828,11 @@

        Supported Devices and EVAL boards<
      • STM32F412ZG and STM32F412ZG-Nucleo board RevB
      • STM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
      -

      Backward Compatibility

      +

      Backward Compatibility

      • None
      -

      Dependencies

      +

      Dependencies

      • None
      @@ -6258,12 +6841,12 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release to fix issues in I2C/FMPI2C HAL drivers
      -

      Contents

      +

      Contents

      @@ -6285,8 +6868,8 @@

      Contents

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Fix known defects and enhancements implementation
      • HAL @@ -6333,7 +6916,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component
    • -

      Contents

      +

      Contents

      @@ -6645,21 +7228,21 @@

      Contents

      Drivers
      -

      Known Limitations

      +

      Known Limitations

      • USB_Device_Standalone application for STM324x9I_EVAL
      • MDK-ARM and TrueSTUDIO projects are provided with optimization set to None, to avoid audio glitch when USB cable is disconnected
      • TrueSTUDIO and SW4STM32 projects are not provided for all EVAL and Discovery demonstrations
      • STemWin sample demo applications with all STM32 platforms are not fully functional with MDK-ARM toolchain: the application doesn t run successfully after the second hit of the Hide Button. in fact when presing the button again while the progress bar displays the next steps, pressing Hide or Next Buttons are not working anymore.
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain v7.60.1
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.20 + Keil.STM32F4xx_DFP.2.6.1.pack
      • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.5.2
      • System Workbench for STM32 (SW4STM32) toolchain V1.9
      -

      Supported Devices and EVAL boards

      +

      Supported Devices and EVAL boards

      • STM32F469xx/479xx devices STM32469I_EVAL board RevC
      • STM32F469xx and STM32469I-Discovery board RevB
      • @@ -6679,11 +7262,11 @@

        Supported Devices and EVAL boards<
      • STM32F412ZG and STM32F412ZG-Nucleo board RevB
      • STM32F413ZHT6U and STM32F413ZH-Nucleo board RevB
      -

      Backward Compatibility

      +

      Backward Compatibility

      • None
      -

      Dependencies

      +

      Dependencies

      • None
      @@ -6692,8 +7275,8 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Official release to add the support of STM32F412cx, STM32F412rx, STM32F412vx and STM32F412zx devices
      • Fix known defects and several implementation enhancement

      • @@ -6734,7 +7317,7 @@

        Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component

    -

    Contents

    +

    Contents

    @@ -7046,21 +7629,21 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
    • MDK-ARM and TrueSTUDIO projects are provided with optimization set to None, to avoid audio glitch when USB cable is disconnected
    • TrueSTUDIO projects are not provided for all EVAL and Discovery demonstrations
    • The STM32F412G-Discovery demonstration firmware is not part of this firmware package. It will be added in the next release.
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.60.1
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.17 + Keil.STM32F4xx_DFP.2.6.1.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.3.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.6
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -7079,11 +7662,11 @@

      Supported Devices and EVAL boards<
    • STM32F429ZI and STM32F429ZI-Nucleo board RevB
    • STM32F412ZG and STM32F412ZG-Nucleo board RevB
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -7092,8 +7675,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Fix known defects and enhancements implementation
    • HAL @@ -7130,7 +7713,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component
  • -

    Contents

    +

    Contents

    @@ -7442,7 +8025,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -7450,14 +8033,14 @@

        Known Limitations

    • TrueSTUDIO projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.50.1
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.17 + Keil.STM32F4xx_DFP.2.6.1.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.3.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.6
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -7474,11 +8057,11 @@

      Supported Devices and EVAL boards<
    • STM32F446ZE and STM32F446ZE-Nucleo board RevB
    • STM32F429ZI and STM32F429ZI-Nucleo board RevB
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -7487,12 +8070,12 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • For the complete list of changes, please refer to the release notes of each firmware component
    -

    Contents

    +

    Contents

    @@ -7514,8 +8097,8 @@

    Contents

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Support new boards: STM32F411E-Discovery, STM32F446ZE NUCLEO144 and STM32F429ZI NUCLEO144
    • Fix known defects and enhancements implementation

    • @@ -7551,7 +8134,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component

  • -

    Contents

    +

    Contents

    @@ -7853,7 +8436,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -7861,14 +8444,14 @@

        Known Limitations

    • TrueSTUDIO projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.40.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.14 + Keil.STM32F4xx_DFP.2.6.0.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.4
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -7885,11 +8468,11 @@

      Supported Devices and EVAL boards<
    • STM32F446ZE and STM32F446ZE-Nucleo board RevB
    • STM32F429ZI and STM32F429ZI-Nucleo board RevB
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -7898,8 +8481,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Maintenance release to fix known defects and enhancements implementation
    • HAL @@ -7941,7 +8524,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware component
  • -

    Contents

    +

    Contents

    @@ -8238,7 +8821,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -8246,14 +8829,14 @@

        Known Limitations

    • TrueSTUDIO projects are not provided for all EVAL and Discovery demonstrations
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.40.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.14 + Keil.STM32F4xx_DFP.2.6.0.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.4
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -8267,11 +8850,11 @@

      Supported Devices and EVAL boards<
    • STM32F401xE and STM32F401RE-Nucleo board RevC
    • STM32F411xE and STM32F411RE-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -8280,8 +8863,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Official release to support STM32F469xx, STM32F479xx, STM32F410Cx, STM32F410Rx and STM32F410Tx devices
    • Fix known defects and several enhancements implementation

    • @@ -8320,7 +8903,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware components

  • -

    Contents

    +

    Contents

    @@ -8617,7 +9200,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • USB_Device_Standalone application for STM324x9I_EVAL
        @@ -8628,14 +9211,14 @@

        Known Limitations

      • TrueSTUDIO project is not provided
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.40.4
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.14 + Keil.STM32F4xx_DFP.2.6.0.pack
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.4 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F469xx/479xx devices STM32469I_EVAL board RevC
    • STM32F469xx and STM32469I-Discovery board RevB
    • @@ -8649,11 +9232,11 @@

      Supported Devices and EVAL boards<
    • STM32F401xE and STM32F401RE-Nucleo board RevC
    • STM32F411xE and STM32F411RE-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -8662,8 +9245,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Official release to support STM32446E-Nucleo board
    • Maintenance release to fix known defects

    • @@ -8700,7 +9283,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware components

  • -

    Contents

    +

    Contents

    @@ -8997,7 +9580,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • The following issues are detected when using EWARM V7.30, however they are not present when using EWARM V7.10, they will be fixed in next release:
        @@ -9025,7 +9608,7 @@

        Known Limitations

      • Robustness to be improved, the application may not work correctly after several board reset
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.40.1
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.13 @@ -9039,7 +9622,7 @@

      Development Toolchains and Comp
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.1.0 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F446xx devices STM32446E_EVAL board RevB
    • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
    • @@ -9051,11 +9634,11 @@

      Supported Devices and EVAL boards<
    • STM32F411xE and STM32F411RE-Nucleo board RevC
    • STM32F446RE and STM32446E-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -9064,8 +9647,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Add support of System Workbench for STM32 (SW4STM32) toolchain
    • Maintenance release to fix known defects

    • @@ -9105,7 +9688,7 @@

      Main Changes

  • Fix compile issue in some projects (9 in total), mainly due to bad project settings

  • -

    Contents

    +

    Contents

    @@ -9392,7 +9975,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • SW4STM32 projects are not provided for STM32446E_EVAL board, will be added in next release
    • The following issues are detected when using EWARM V7.30, however they are not present when using EWARM V7.10, they will be fixed in next release: @@ -9424,7 +10007,7 @@

      Known Limitations

    • Robustness to be improved, the application may not work correctly after several board reset
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.30
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.13 @@ -9438,7 +10021,7 @@

      Development Toolchains and Comp
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.1.0 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F446xx devices STM32446E_EVAL board RevB
    • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
    • @@ -9449,11 +10032,11 @@

      Supported Devices and EVAL boards<
    • STM32F401xE and STM32F401RE-Nucleo board RevC
    • STM32F411xE and STM32F411RE-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -9462,8 +10045,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Official release to support STM32F446xx devices
    • Fix known defects and several enhancements implementation

    • @@ -9501,7 +10084,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware components

  • -

    Contents

    +

    Contents

    @@ -9788,7 +10371,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • The following issues are detected when using EWARM V7.30, however they are not present when using EWARM V7.10, they will be fixed in next release:
        @@ -9819,7 +10402,7 @@

        Known Limitations

      • Robustness to be improved, the application may not work correctly after several board reset
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.30
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.13 @@ -9833,7 +10416,7 @@

      Development Toolchains and Comp
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.1.0 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F446xx devices STM32446E_EVAL board RevB
    • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
    • @@ -9844,11 +10427,11 @@

      Supported Devices and EVAL boards<
    • STM32F401xE and STM32F401RE-Nucleo board RevC
    • STM32F411xE and STM32F411RE-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -9857,8 +10440,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Maintenance release to fix known defects and several enhancements implementation
    • HAL @@ -9907,7 +10490,7 @@

      Main Changes

  • For the complete list of changes, please refer to the release notes of each firmware components

  • -

    Contents

    +

    Contents

    @@ -10194,7 +10777,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • The following issues are detected when using EWARM V7.30, however they are not present when using EWARM V7.10, they will be fixed in next release:
        @@ -10217,7 +10800,7 @@

        Known Limitations

      • TrueSTUDIO project is not provided
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain v7.30
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.13 @@ -10231,7 +10814,7 @@

      Development Toolchains and Comp
    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
    • System Workbench for STM32 (SW4STM32) toolchain V1.1.0 + ST-Link
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
    • STM32F429xx and STM32F429I-Discovery board RevB
    • @@ -10241,11 +10824,11 @@

      Supported Devices and EVAL boards<
    • STM32F401xE and STM32F401RE-Nucleo board RevC
    • STM32F411xE and STM32F411RE-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    @@ -10254,8 +10837,8 @@

    Dependencies

    -

    Maintenance release

    -

    Main Changes

    +

    Maintenance release

    +

    Main Changes

    • Full features release, containing all projects sources for the supported boards

    • Projects @@ -10275,7 +10858,7 @@

      Main Changes

  • Use STM32CubeUpdater.exe utility V4.2.0

  • -

    Contents

    +

    Contents

    @@ -10557,7 +11140,7 @@

    Contents

    Drivers
    -

    Known Limitations

    +

    Known Limitations

    • PolarSSL applications for STM324x9I_EVAL and STM324xG_EVAL
        @@ -10574,7 +11157,7 @@

        Known Limitations

      • STM324x9I-EVAL, STM324xG-EVAL and STM32F429I-Discovery demonstration
      • TrueSTUDIO project is not provided
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain v7.30
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.13 @@ -10588,7 +11171,7 @@

        Development Toolchains and Comp
      • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.1.1
      • System Workbench for STM32 (SW4STM32) toolchain V1.1.0 + ST-Link
      -

      Supported Devices and EVAL boards

      +

      Supported Devices and EVAL boards

      • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
      • STM32F429xx and STM32F429I-Discovery board RevB
      • @@ -10598,11 +11181,11 @@

        Supported Devices and EVAL boards<
      • STM32F401xE and STM32F401RE-Nucleo board RevC
      • STM32F411xE and STM32F411RE-Nucleo board RevC
      -

      Backward Compatibility

      +

      Backward Compatibility

      • None
      -

      Dependencies

      +

      Dependencies

      • None
      @@ -10611,20 +11194,24 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Patch release for STM32CubeF4, adding support of STM32F411xE devices with several enhancements and bugs fix
          -
        • In this release; only the Firmware components drivers are provided, the projects for the supported boards will be provided in the upcoming release V1.2.1

        • -
        • HAL and CMSIS
        • +
        • In this release; only the Firmware components drivers are provided, the projects for the supported boards will be provided in the upcoming release V1.2.1
        • +
      • +
      • HAL and CMSIS +
        • Add support of STM32F411xE devices
        • Several enhancements and bugs fix
        • -
        • Update startup files for EWARM toolchain to cope with compiler enhancement of the V7.x version

        • -
        • Middleware
        • +
        • Update startup files for EWARM toolchain to cope with compiler enhancement of the V7.x version
        • +
      • +
      • Middleware +
        • Use updated version V5.24b of STemWin; adding many new features, with PC simulation resources added and binaries compiled for high speed optimization
        • Add LibJPEG library for JPEG images encoding and decoding
        • -
        • Miscellaneous update and minor bugs fix

        • +
        • Miscellaneous update and minor bugs fix
      • BSP
          @@ -10634,7 +11221,7 @@

          Main Changes

      • Note: for the complete list of changes, please refer to the release notes of each Firmware component
      -

      Contents

      +

      Contents

      @@ -10916,17 +11503,17 @@

      Contents

      Drivers
      -

      Known Limitations

      +

      Known Limitations

      • None
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain v7.10.2
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain v5.10
      • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v5.0.0
      -

      Supported Devices and EVAL boards

      +

      Supported Devices and EVAL boards

      • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
      • STM32F429xx and STM32F429I-Discovery board RevB
      • @@ -10936,11 +11523,11 @@

        Supported Devices and EVAL boards<
      • STM32F401xE and STM32F401RE-Nucleo board RevC
      • STM32F411xE and STM32F411RE-Nucleo board RevC
      -

      Backward Compatibility

      +

      Backward Compatibility

      • None
      -

      Dependencies

      +

      Dependencies

      • None
      @@ -10949,8 +11536,8 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • Add sources of STM324x9I-EVAL (both references MB1046 and MB1063), STM324xG-EVAL and STM32F429I-Discovery Demonstration (only for EWARM and MDK-ARM)
          @@ -10960,7 +11547,7 @@

          Main Changes

        • Miscellaneous update on Examples, Applications, Demonstrations and Templates projects for some boards; for more details refer to the associated release notes
        • Minor update in STM324x9I-EVAL, STM324xG-EVAL and STM32F429I-Discovery uSD and EEPROM BSP drivers
        -

        Contents

        +

        Contents

        @@ -11227,11 +11814,11 @@

        Contents

        Drivers
        -

        Known Limitations

        +

        Known Limitations

        • TrueSTUDIO projects are not provided for few Applications and Demonstrations (10 in total)
        -

        Development Toolchains and Compilers

        +

        Development Toolchains and Compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V6.70.3
        • RealView Microcontroller Development Kit (MDK-ARM) toolchain v4.73 @@ -11240,7 +11827,7 @@

          Development Toolchains and Comp

      • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v4.3.0
      -

      Supported Devices and EVAL boards

      +

      Supported Devices and EVAL boards

      • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
      • STM32F429xx and STM32F429I-Discovery board RevB
      • @@ -11249,11 +11836,11 @@

        Supported Devices and EVAL boards<
      • STM32F401xC and STM32F401-Discovery board RevB
      • STM32F401xE and STM32F4xx-Nucleo board RevC
      -

      Backward Compatibility

      +

      Backward Compatibility

      • None
      -

      Dependencies

      +

      Dependencies

      • None
      @@ -11262,12 +11849,12 @@

      Dependencies

      -

      Maintenance release

      -

      Main Changes

      +

      Maintenance release

      +

      Main Changes

      • First official release of STM32CubeF4 (STM32Cube for STM32F4 Series)
      -

      Contents

      +

      Contents

      @@ -11469,13 +12056,13 @@

      Contents

      Drivers
      -

      Known Limitations

      +

      Known Limitations

      • STM324x9I-EVAL, STM324xG-EVAL and STM32F429I-Discovery Demonstrations sources will be provided in V1.1.0 release planned very soon
      • TrueSTUDIO projects are not provided for few Examples and Applications (7 in total)
      • MDK-ARM projects are not provided for 2 Applications (2 in total)
      -

      Development Toolchains and Compilers

      +

      Development Toolchains and Compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain V6.70.3
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain v4.73 @@ -11484,7 +12071,7 @@

        Development Toolchains and Comp

    • Atollic TrueSTUDIO STM32 (TrueSTUDIO) toolchain v4.3.0
    -

    Supported Devices and EVAL boards

    +

    Supported Devices and EVAL boards

    • STM32F429xx/439xx devices and STM324x9I-EVAL board RevB
    • STM32F407xx/417xx devices and STM324xG-EVAL board RevC
    • @@ -11493,11 +12080,11 @@

      Supported Devices and EVAL boards<
    • STM32F429xx and STM32F429I-Discovery board RevB
    • STM32F401xE and STM32F4xx-Nucleo board RevC
    -

    Backward Compatibility

    +

    Backward Compatibility

    • None
    -

    Dependencies

    +

    Dependencies

    • None
    diff --git a/stm32cube/stm32f4xx/soc/stm32f412cx.h b/stm32cube/stm32f4xx/soc/stm32f412cx.h index 32b87399b..95178f413 100644 --- a/stm32cube/stm32f4xx/soc/stm32f412cx.h +++ b/stm32cube/stm32f4xx/soc/stm32f412cx.h @@ -8497,6 +8497,18 @@ typedef struct #define RCC_CFGR_MCO1PRE_1 (0x2UL << RCC_CFGR_MCO1PRE_Pos) /*!< 0x02000000 */ #define RCC_CFGR_MCO1PRE_2 (0x4UL << RCC_CFGR_MCO1PRE_Pos) /*!< 0x04000000 */ +#define RCC_CFGR_MCO2PRE_Pos (27U) +#define RCC_CFGR_MCO2PRE_Msk (0x7UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x38000000 */ +#define RCC_CFGR_MCO2PRE RCC_CFGR_MCO2PRE_Msk +#define RCC_CFGR_MCO2PRE_0 (0x1UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x08000000 */ +#define RCC_CFGR_MCO2PRE_1 (0x2UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x10000000 */ +#define RCC_CFGR_MCO2PRE_2 (0x4UL << RCC_CFGR_MCO2PRE_Pos) /*!< 0x20000000 */ + +#define RCC_CFGR_MCO2_Pos (30U) +#define RCC_CFGR_MCO2_Msk (0x3UL << RCC_CFGR_MCO2_Pos) /*!< 0xC0000000 */ +#define RCC_CFGR_MCO2 RCC_CFGR_MCO2_Msk +#define RCC_CFGR_MCO2_0 (0x1UL << RCC_CFGR_MCO2_Pos) /*!< 0x40000000 */ +#define RCC_CFGR_MCO2_1 (0x2UL << RCC_CFGR_MCO2_Pos) /*!< 0x80000000 */ /******************** Bit definition for RCC_CIR register *******************/ #define RCC_CIR_LSIRDYF_Pos (0U) diff --git a/stm32cube/stm32f4xx/soc/stm32f4xx.h b/stm32cube/stm32f4xx/soc/stm32f4xx.h index a5376a110..5bbe68ae4 100644 --- a/stm32cube/stm32f4xx/soc/stm32f4xx.h +++ b/stm32cube/stm32f4xx/soc/stm32f4xx.h @@ -105,11 +105,11 @@ extern "C" { #endif /* USE_HAL_DRIVER */ /** - * @brief CMSIS version number V2.6.9 + * @brief CMSIS version number V2.6.10 */ #define __STM32F4xx_CMSIS_VERSION_MAIN (0x02U) /*!< [31:24] main version */ #define __STM32F4xx_CMSIS_VERSION_SUB1 (0x06U) /*!< [23:16] sub1 version */ -#define __STM32F4xx_CMSIS_VERSION_SUB2 (0x09U) /*!< [15:8] sub2 version */ +#define __STM32F4xx_CMSIS_VERSION_SUB2 (0x0AU) /*!< [15:8] sub2 version */ #define __STM32F4xx_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32F4xx_CMSIS_VERSION ((__STM32F4xx_CMSIS_VERSION_MAIN << 24)\ |(__STM32F4xx_CMSIS_VERSION_SUB1 << 16)\ From 1549477714f39eec02ac9a72b4258c3b85aae71a Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 15:33:52 +0200 Subject: [PATCH 05/11] stm32cube: update stm32g4 to cube version V1.6.0 Update Cube version for STM32G4xx series on https://github.com/STMicroelectronics from version v1.5.2 to version v1.6.0 Signed-off-by: Guillaume Gautier --- stm32cube/stm32g4xx/README | 4 +- .../drivers/include/Legacy/stm32_hal_legacy.h | 499 +- .../stm32g4xx/drivers/include/stm32g4xx_hal.h | 2 + .../drivers/include/stm32g4xx_hal_adc.h | 2 +- .../drivers/include/stm32g4xx_hal_adc_ex.h | 14 +- .../drivers/include/stm32g4xx_hal_comp.h | 322 +- .../drivers/include/stm32g4xx_hal_cordic.h | 21 +- .../drivers/include/stm32g4xx_hal_cortex.h | 2 + .../drivers/include/stm32g4xx_hal_dac.h | 4 +- .../drivers/include/stm32g4xx_hal_dac_ex.h | 8 +- .../drivers/include/stm32g4xx_hal_fdcan.h | 4 +- .../drivers/include/stm32g4xx_hal_fmac.h | 12 +- .../drivers/include/stm32g4xx_hal_i2c_ex.h | 15 + .../drivers/include/stm32g4xx_hal_irda_ex.h | 221 +- .../drivers/include/stm32g4xx_hal_lptim.h | 4 +- .../drivers/include/stm32g4xx_hal_opamp.h | 6 +- .../drivers/include/stm32g4xx_hal_opamp_ex.h | 6 +- .../drivers/include/stm32g4xx_hal_pcd.h | 17 +- .../drivers/include/stm32g4xx_hal_pcd_ex.h | 1 - .../drivers/include/stm32g4xx_hal_rcc_ex.h | 30 +- .../drivers/include/stm32g4xx_hal_sai.h | 4 + .../drivers/include/stm32g4xx_hal_sai_ex.h | 4 + .../drivers/include/stm32g4xx_hal_smartcard.h | 52 + .../drivers/include/stm32g4xx_hal_smbus_ex.h | 4 + .../drivers/include/stm32g4xx_hal_uart.h | 5 +- .../drivers/include/stm32g4xx_hal_uart_ex.h | 284 +- .../drivers/include/stm32g4xx_hal_usart.h | 55 +- .../drivers/include/stm32g4xx_ll_adc.h | 2 +- .../drivers/include/stm32g4xx_ll_bus.h | 2 +- .../drivers/include/stm32g4xx_ll_cordic.h | 28 +- .../drivers/include/stm32g4xx_ll_fmac.h | 6 - .../drivers/include/stm32g4xx_ll_lpuart.h | 15 + .../drivers/include/stm32g4xx_ll_pwr.h | 2 + .../drivers/include/stm32g4xx_ll_rcc.h | 10 + .../drivers/include/stm32g4xx_ll_rng.h | 2 +- .../drivers/include/stm32g4xx_ll_system.h | 9 +- .../drivers/include/stm32g4xx_ll_ucpd.h | 12 +- .../drivers/include/stm32g4xx_ll_utils.h | 7 +- .../stm32g4xx/drivers/src/stm32g4xx_hal.c | 11 +- .../drivers/src/stm32g4xx_hal_comp.c | 2 +- .../drivers/src/stm32g4xx_hal_cordic.c | 2 +- .../drivers/src/stm32g4xx_hal_cortex.c | 82 +- .../drivers/src/stm32g4xx_hal_cryp.c | 12 +- .../drivers/src/stm32g4xx_hal_dac_ex.c | 15 +- .../stm32g4xx/drivers/src/stm32g4xx_hal_dma.c | 2 +- .../drivers/src/stm32g4xx_hal_flash_ex.c | 4 +- .../drivers/src/stm32g4xx_hal_fmac.c | 7 +- .../drivers/src/stm32g4xx_hal_gpio.c | 2 +- .../stm32g4xx/drivers/src/stm32g4xx_hal_i2c.c | 40 +- .../drivers/src/stm32g4xx_hal_opamp.c | 7 +- .../drivers/src/stm32g4xx_hal_opamp_ex.c | 2 + .../stm32g4xx/drivers/src/stm32g4xx_hal_pcd.c | 6 +- .../drivers/src/stm32g4xx_hal_pcd_ex.c | 2 - .../drivers/src/stm32g4xx_hal_pwr_ex.c | 8 +- .../drivers/src/stm32g4xx_hal_qspi.c | 12 + .../drivers/src/stm32g4xx_hal_rcc_ex.c | 43 +- .../stm32g4xx/drivers/src/stm32g4xx_hal_sai.c | 10 +- .../drivers/src/stm32g4xx_hal_sai_ex.c | 5 +- .../drivers/src/stm32g4xx_hal_smartcard.c | 2 +- .../drivers/src/stm32g4xx_hal_smbus_ex.c | 2 + .../drivers/src/stm32g4xx_hal_uart.c | 24 + .../drivers/src/stm32g4xx_hal_uart_ex.c | 2 +- .../drivers/src/stm32g4xx_hal_usart.c | 17 +- .../drivers/src/stm32g4xx_hal_usart_ex.c | 2 +- .../stm32g4xx/drivers/src/stm32g4xx_ll_adc.c | 4 +- .../stm32g4xx/drivers/src/stm32g4xx_ll_comp.c | 292 +- .../stm32g4xx/drivers/src/stm32g4xx_ll_dac.c | 12 +- .../stm32g4xx/drivers/src/stm32g4xx_ll_fmac.c | 2 - .../stm32g4xx/drivers/src/stm32g4xx_ll_i2c.c | 2 + .../stm32g4xx/drivers/src/stm32g4xx_ll_rcc.c | 30 +- .../stm32g4xx/drivers/src/stm32g4xx_ll_rng.c | 2 +- .../stm32g4xx/drivers/src/stm32g4xx_ll_ucpd.c | 2 +- .../drivers/src/stm32g4xx_ll_usart.c | 4 + stm32cube/stm32g4xx/release_note.html | 651 +- stm32cube/stm32g4xx/soc/stm32g414xx.h | 15817 ++++++++++++++++ stm32cube/stm32g4xx/soc/stm32g4xx.h | 10 +- 76 files changed, 18181 insertions(+), 667 deletions(-) create mode 100644 stm32cube/stm32g4xx/soc/stm32g414xx.h diff --git a/stm32cube/stm32g4xx/README b/stm32cube/stm32g4xx/README index 70f68d317..761bf4ced 100644 --- a/stm32cube/stm32g4xx/README +++ b/stm32cube/stm32g4xx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubeg4.html Status: - version v1.5.2 + version v1.6.0 Purpose: ST Microelectronics official MCU package for STM32G4 series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeG4 Commit: - fd05229e8a53bdec8478cb0760219c8789e947b0 + 98f52ec7cdbbbfe1650b351bde2efb037815886d Maintained-by: External diff --git a/stm32cube/stm32g4xx/drivers/include/Legacy/stm32_hal_legacy.h b/stm32cube/stm32g4xx/drivers/include/Legacy/stm32_hal_legacy.h index 757bfa3b3..f0204c4b0 100644 --- a/stm32cube/stm32g4xx/drivers/include/Legacy/stm32_hal_legacy.h +++ b/stm32cube/stm32g4xx/drivers/include/Legacy/stm32_hal_legacy.h @@ -103,7 +103,15 @@ extern "C" { #define ADC_CHANNEL_VBAT_DIV4 ADC_CHANNEL_VBAT #endif /* STM32H7 */ - +#if defined(STM32U5) +#define ADC_SAMPLETIME_5CYCLE ADC_SAMPLETIME_5CYCLES +#define ADC_SAMPLETIME_391CYCLES_5 ADC_SAMPLETIME_391CYCLES +#define ADC4_SAMPLETIME_160CYCLES_5 ADC4_SAMPLETIME_814CYCLES_5 +#endif /* STM32U5 */ + +#if defined(STM32H5) +#define ADC_CHANNEL_VCORE ADC_CHANNEL_VDDCORE +#endif /* STM32H5 */ /** * @} */ @@ -207,6 +215,9 @@ extern "C" { #endif +#if defined(STM32U5) +#define __HAL_COMP_COMP1_EXTI_CLEAR_RASING_FLAG __HAL_COMP_COMP1_EXTI_CLEAR_RISING_FLAG +#endif /** * @} @@ -216,6 +227,11 @@ extern "C" { * @{ */ #define __HAL_CORTEX_SYSTICKCLK_CONFIG HAL_SYSTICK_CLKSourceConfig +#if defined(STM32U5) +#define MPU_DEVICE_nGnRnE MPU_DEVICE_NGNRNE +#define MPU_DEVICE_nGnRE MPU_DEVICE_NGNRE +#define MPU_DEVICE_nGRE MPU_DEVICE_NGRE +#endif /* STM32U5 */ /** * @} */ @@ -223,10 +239,13 @@ extern "C" { /** @defgroup CRC_Aliases CRC API aliases * @{ */ +#if defined(STM32H5) || defined(STM32C0) +#else #define HAL_CRC_Input_Data_Reverse HAL_CRCEx_Input_Data_Reverse /*!< Aliased to HAL_CRCEx_Input_Data_Reverse for inter STM32 series compatibility */ #define HAL_CRC_Output_Data_Reverse HAL_CRCEx_Output_Data_Reverse /*!< Aliased to HAL_CRCEx_Output_Data_Reverse for inter STM32 series compatibility */ +#endif /** * @} */ @@ -256,12 +275,22 @@ extern "C" { #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE -#if defined(STM32G4) || defined(STM32H7) +#if defined(STM32G4) || defined(STM32H7) || defined (STM32U5) #define DAC_CHIPCONNECT_DISABLE DAC_CHIPCONNECT_EXTERNAL #define DAC_CHIPCONNECT_ENABLE DAC_CHIPCONNECT_INTERNAL #endif +#if defined(STM32U5) +#define DAC_TRIGGER_STOP_LPTIM1_OUT DAC_TRIGGER_STOP_LPTIM1_CH1 +#define DAC_TRIGGER_STOP_LPTIM3_OUT DAC_TRIGGER_STOP_LPTIM3_CH1 +#define DAC_TRIGGER_LPTIM1_OUT DAC_TRIGGER_LPTIM1_CH1 +#define DAC_TRIGGER_LPTIM3_OUT DAC_TRIGGER_LPTIM3_CH1 +#endif +#if defined(STM32H5) +#define DAC_TRIGGER_LPTIM1_OUT DAC_TRIGGER_LPTIM1_CH1 +#define DAC_TRIGGER_LPTIM2_OUT DAC_TRIGGER_LPTIM2_CH1 +#endif #if defined(STM32L1) || defined(STM32L4) || defined(STM32G0) || defined(STM32L5) || defined(STM32H7) || \ defined(STM32F4) || defined(STM32G4) @@ -408,6 +437,9 @@ extern "C" { #endif /* STM32H7 */ +#if defined(STM32U5) +#define GPDMA1_REQUEST_DCMI GPDMA1_REQUEST_DCMI_PSSI +#endif /* STM32U5 */ /** * @} */ @@ -487,7 +519,7 @@ extern "C" { #define OB_RDP_LEVEL0 OB_RDP_LEVEL_0 #define OB_RDP_LEVEL1 OB_RDP_LEVEL_1 #define OB_RDP_LEVEL2 OB_RDP_LEVEL_2 -#if defined(STM32G0) +#if defined(STM32G0) || defined(STM32C0) #define OB_BOOT_LOCK_DISABLE OB_BOOT_ENTRY_FORCED_NONE #define OB_BOOT_LOCK_ENABLE OB_BOOT_ENTRY_FORCED_FLASH #else @@ -504,6 +536,28 @@ extern "C" { #define FLASH_FLAG_WDW FLASH_FLAG_WBNE #define OB_WRP_SECTOR_All OB_WRP_SECTOR_ALL #endif /* STM32H7 */ +#if defined(STM32U5) +#define OB_USER_nRST_STOP OB_USER_NRST_STOP +#define OB_USER_nRST_STDBY OB_USER_NRST_STDBY +#define OB_USER_nRST_SHDW OB_USER_NRST_SHDW +#define OB_USER_nSWBOOT0 OB_USER_NSWBOOT0 +#define OB_USER_nBOOT0 OB_USER_NBOOT0 +#define OB_nBOOT0_RESET OB_NBOOT0_RESET +#define OB_nBOOT0_SET OB_NBOOT0_SET +#define OB_USER_SRAM134_RST OB_USER_SRAM_RST +#define OB_SRAM134_RST_ERASE OB_SRAM_RST_ERASE +#define OB_SRAM134_RST_NOT_ERASE OB_SRAM_RST_NOT_ERASE +#endif /* STM32U5 */ +#if defined(STM32U0) +#define OB_USER_nRST_STOP OB_USER_NRST_STOP +#define OB_USER_nRST_STDBY OB_USER_NRST_STDBY +#define OB_USER_nRST_SHDW OB_USER_NRST_SHDW +#define OB_USER_nBOOT_SEL OB_USER_NBOOT_SEL +#define OB_USER_nBOOT0 OB_USER_NBOOT0 +#define OB_USER_nBOOT1 OB_USER_NBOOT1 +#define OB_nBOOT0_RESET OB_NBOOT0_RESET +#define OB_nBOOT0_SET OB_NBOOT0_SET +#endif /* STM32U0 */ /** * @} @@ -547,6 +601,104 @@ extern "C" { #define HAL_SYSCFG_DisableIOAnalogSwitchVDD HAL_SYSCFG_DisableIOSwitchVDD #endif /* STM32G4 */ +#if defined(STM32H5) +#define SYSCFG_IT_FPU_IOC SBS_IT_FPU_IOC +#define SYSCFG_IT_FPU_DZC SBS_IT_FPU_DZC +#define SYSCFG_IT_FPU_UFC SBS_IT_FPU_UFC +#define SYSCFG_IT_FPU_OFC SBS_IT_FPU_OFC +#define SYSCFG_IT_FPU_IDC SBS_IT_FPU_IDC +#define SYSCFG_IT_FPU_IXC SBS_IT_FPU_IXC + +#define SYSCFG_BREAK_FLASH_ECC SBS_BREAK_FLASH_ECC +#define SYSCFG_BREAK_PVD SBS_BREAK_PVD +#define SYSCFG_BREAK_SRAM_ECC SBS_BREAK_SRAM_ECC +#define SYSCFG_BREAK_LOCKUP SBS_BREAK_LOCKUP + +#define SYSCFG_VREFBUF_VOLTAGE_SCALE0 VREFBUF_VOLTAGE_SCALE0 +#define SYSCFG_VREFBUF_VOLTAGE_SCALE1 VREFBUF_VOLTAGE_SCALE1 +#define SYSCFG_VREFBUF_VOLTAGE_SCALE2 VREFBUF_VOLTAGE_SCALE2 +#define SYSCFG_VREFBUF_VOLTAGE_SCALE3 VREFBUF_VOLTAGE_SCALE3 + +#define SYSCFG_VREFBUF_HIGH_IMPEDANCE_DISABLE VREFBUF_HIGH_IMPEDANCE_DISABLE +#define SYSCFG_VREFBUF_HIGH_IMPEDANCE_ENABLE VREFBUF_HIGH_IMPEDANCE_ENABLE + +#define SYSCFG_FASTMODEPLUS_PB6 SBS_FASTMODEPLUS_PB6 +#define SYSCFG_FASTMODEPLUS_PB7 SBS_FASTMODEPLUS_PB7 +#define SYSCFG_FASTMODEPLUS_PB8 SBS_FASTMODEPLUS_PB8 +#define SYSCFG_FASTMODEPLUS_PB9 SBS_FASTMODEPLUS_PB9 + +#define SYSCFG_ETH_MII SBS_ETH_MII +#define SYSCFG_ETH_RMII SBS_ETH_RMII +#define IS_SYSCFG_ETHERNET_CONFIG IS_SBS_ETHERNET_CONFIG + +#define SYSCFG_MEMORIES_ERASE_FLAG_IPMEE SBS_MEMORIES_ERASE_FLAG_IPMEE +#define SYSCFG_MEMORIES_ERASE_FLAG_MCLR SBS_MEMORIES_ERASE_FLAG_MCLR +#define IS_SYSCFG_MEMORIES_ERASE_FLAG IS_SBS_MEMORIES_ERASE_FLAG + +#define IS_SYSCFG_CODE_CONFIG IS_SBS_CODE_CONFIG + +#define SYSCFG_MPU_NSEC SBS_MPU_NSEC +#define SYSCFG_VTOR_NSEC SBS_VTOR_NSEC +#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) +#define SYSCFG_SAU SBS_SAU +#define SYSCFG_MPU_SEC SBS_MPU_SEC +#define SYSCFG_VTOR_AIRCR_SEC SBS_VTOR_AIRCR_SEC +#define SYSCFG_LOCK_ALL SBS_LOCK_ALL +#else +#define SYSCFG_LOCK_ALL SBS_LOCK_ALL +#endif /* __ARM_FEATURE_CMSE */ + +#define SYSCFG_CLK SBS_CLK +#define SYSCFG_CLASSB SBS_CLASSB +#define SYSCFG_FPU SBS_FPU +#define SYSCFG_ALL SBS_ALL + +#define SYSCFG_SEC SBS_SEC +#define SYSCFG_NSEC SBS_NSEC + +#define __HAL_SYSCFG_FPU_INTERRUPT_ENABLE __HAL_SBS_FPU_INTERRUPT_ENABLE +#define __HAL_SYSCFG_FPU_INTERRUPT_DISABLE __HAL_SBS_FPU_INTERRUPT_DISABLE + +#define __HAL_SYSCFG_BREAK_ECC_LOCK __HAL_SBS_BREAK_ECC_LOCK +#define __HAL_SYSCFG_BREAK_LOCKUP_LOCK __HAL_SBS_BREAK_LOCKUP_LOCK +#define __HAL_SYSCFG_BREAK_PVD_LOCK __HAL_SBS_BREAK_PVD_LOCK +#define __HAL_SYSCFG_BREAK_SRAM_ECC_LOCK __HAL_SBS_BREAK_SRAM_ECC_LOCK + +#define __HAL_SYSCFG_FASTMODEPLUS_ENABLE __HAL_SBS_FASTMODEPLUS_ENABLE +#define __HAL_SYSCFG_FASTMODEPLUS_DISABLE __HAL_SBS_FASTMODEPLUS_DISABLE + +#define __HAL_SYSCFG_GET_MEMORIES_ERASE_STATUS __HAL_SBS_GET_MEMORIES_ERASE_STATUS +#define __HAL_SYSCFG_CLEAR_MEMORIES_ERASE_STATUS __HAL_SBS_CLEAR_MEMORIES_ERASE_STATUS + +#define IS_SYSCFG_FPU_INTERRUPT IS_SBS_FPU_INTERRUPT +#define IS_SYSCFG_BREAK_CONFIG IS_SBS_BREAK_CONFIG +#define IS_SYSCFG_VREFBUF_VOLTAGE_SCALE IS_VREFBUF_VOLTAGE_SCALE +#define IS_SYSCFG_VREFBUF_HIGH_IMPEDANCE IS_VREFBUF_HIGH_IMPEDANCE +#define IS_SYSCFG_VREFBUF_TRIMMING IS_VREFBUF_TRIMMING +#define IS_SYSCFG_FASTMODEPLUS IS_SBS_FASTMODEPLUS +#define IS_SYSCFG_ITEMS_ATTRIBUTES IS_SBS_ITEMS_ATTRIBUTES +#define IS_SYSCFG_ATTRIBUTES IS_SBS_ATTRIBUTES +#define IS_SYSCFG_LOCK_ITEMS IS_SBS_LOCK_ITEMS + +#define HAL_SYSCFG_VREFBUF_VoltageScalingConfig HAL_VREFBUF_VoltageScalingConfig +#define HAL_SYSCFG_VREFBUF_HighImpedanceConfig HAL_VREFBUF_HighImpedanceConfig +#define HAL_SYSCFG_VREFBUF_TrimmingConfig HAL_VREFBUF_TrimmingConfig +#define HAL_SYSCFG_EnableVREFBUF HAL_EnableVREFBUF +#define HAL_SYSCFG_DisableVREFBUF HAL_DisableVREFBUF + +#define HAL_SYSCFG_EnableIOAnalogSwitchBooster HAL_SBS_EnableIOAnalogSwitchBooster +#define HAL_SYSCFG_DisableIOAnalogSwitchBooster HAL_SBS_DisableIOAnalogSwitchBooster +#define HAL_SYSCFG_ETHInterfaceSelect HAL_SBS_ETHInterfaceSelect + +#define HAL_SYSCFG_Lock HAL_SBS_Lock +#define HAL_SYSCFG_GetLock HAL_SBS_GetLock + +#if defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U) +#define HAL_SYSCFG_ConfigAttributes HAL_SBS_ConfigAttributes +#define HAL_SYSCFG_GetConfigAttributes HAL_SBS_GetConfigAttributes +#endif /* __ARM_FEATURE_CMSE */ + +#endif /* STM32H5 */ /** @@ -624,12 +776,13 @@ extern "C" { #define GPIO_AF1_LPTIM GPIO_AF1_LPTIM1 #define GPIO_AF2_LPTIM GPIO_AF2_LPTIM1 -#if defined(STM32L0) || defined(STM32L4) || defined(STM32F4) || defined(STM32F2) || defined(STM32F7) || defined(STM32G4) || defined(STM32H7) || defined(STM32WB) +#if defined(STM32L0) || defined(STM32L4) || defined(STM32F4) || defined(STM32F2) || defined(STM32F7) || \ + defined(STM32G4) || defined(STM32H7) || defined(STM32WB) || defined(STM32U5) #define GPIO_SPEED_LOW GPIO_SPEED_FREQ_LOW #define GPIO_SPEED_MEDIUM GPIO_SPEED_FREQ_MEDIUM #define GPIO_SPEED_FAST GPIO_SPEED_FREQ_HIGH #define GPIO_SPEED_HIGH GPIO_SPEED_FREQ_VERY_HIGH -#endif /* STM32L0 || STM32L4 || STM32F4 || STM32F2 || STM32F7 || STM32G4 || STM32H7 || STM32WB */ +#endif /* STM32L0 || STM32L4 || STM32F4 || STM32F2 || STM32F7 || STM32G4 || STM32H7 || STM32WB || STM32U5*/ #if defined(STM32L1) #define GPIO_SPEED_VERY_LOW GPIO_SPEED_FREQ_LOW @@ -646,6 +799,28 @@ extern "C" { #define GPIO_AF6_DFSDM GPIO_AF6_DFSDM1 +#if defined(STM32U5) || defined(STM32H5) +#define GPIO_AF0_RTC_50Hz GPIO_AF0_RTC_50HZ +#endif /* STM32U5 || STM32H5 */ +#if defined(STM32U5) +#define GPIO_AF0_S2DSTOP GPIO_AF0_SRDSTOP +#define GPIO_AF11_LPGPIO GPIO_AF11_LPGPIO1 +#endif /* STM32U5 */ + +#if defined(STM32WBA) +#define GPIO_AF11_RF_ANTSW0 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW1 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO1 GPIO_AF11_RF +#define GPIO_AF11_RF_IO2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO3 GPIO_AF11_RF +#define GPIO_AF11_RF_IO4 GPIO_AF11_RF +#define GPIO_AF11_RF_IO5 GPIO_AF11_RF +#define GPIO_AF11_RF_IO6 GPIO_AF11_RF +#define GPIO_AF11_RF_IO7 GPIO_AF11_RF +#define GPIO_AF11_RF_IO8 GPIO_AF11_RF +#define GPIO_AF11_RF_IO9 GPIO_AF11_RF +#endif /* STM32WBA */ /** * @} */ @@ -653,6 +828,27 @@ extern "C" { /** @defgroup HAL_GTZC_Aliased_Defines HAL GTZC Aliased Defines maintained for legacy purpose * @{ */ +#if defined(STM32U5) +#define GTZC_PERIPH_DCMI GTZC_PERIPH_DCMI_PSSI +#define GTZC_PERIPH_LTDC GTZC_PERIPH_LTDCUSB +#endif /* STM32U5 */ +#if defined(STM32H5) +#define GTZC_PERIPH_DAC12 GTZC_PERIPH_DAC1 +#define GTZC_PERIPH_ADC12 GTZC_PERIPH_ADC +#define GTZC_PERIPH_USBFS GTZC_PERIPH_USB +#endif /* STM32H5 */ +#if defined(STM32H5) || defined(STM32U5) +#define GTZC_MCPBB_NB_VCTR_REG_MAX GTZC_MPCBB_NB_VCTR_REG_MAX +#define GTZC_MCPBB_NB_LCK_VCTR_REG_MAX GTZC_MPCBB_NB_LCK_VCTR_REG_MAX +#define GTZC_MCPBB_SUPERBLOCK_UNLOCKED GTZC_MPCBB_SUPERBLOCK_UNLOCKED +#define GTZC_MCPBB_SUPERBLOCK_LOCKED GTZC_MPCBB_SUPERBLOCK_LOCKED +#define GTZC_MCPBB_BLOCK_NSEC GTZC_MPCBB_BLOCK_NSEC +#define GTZC_MCPBB_BLOCK_SEC GTZC_MPCBB_BLOCK_SEC +#define GTZC_MCPBB_BLOCK_NPRIV GTZC_MPCBB_BLOCK_NPRIV +#define GTZC_MCPBB_BLOCK_PRIV GTZC_MPCBB_BLOCK_PRIV +#define GTZC_MCPBB_LOCK_OFF GTZC_MPCBB_LOCK_OFF +#define GTZC_MCPBB_LOCK_ON GTZC_MPCBB_LOCK_ON +#endif /* STM32H5 || STM32U5 */ /** * @} */ @@ -900,6 +1096,11 @@ extern "C" { * @} */ +#if defined(STM32U5) +#define LPTIM_ISR_CC1 LPTIM_ISR_CC1IF +#define LPTIM_ISR_CC2 LPTIM_ISR_CC2IF +#define LPTIM_CHANNEL_ALL 0x00000000U +#endif /* STM32U5 */ /** * @} */ @@ -967,7 +1168,7 @@ extern "C" { #define OPAMP_PGACONNECT_VM0 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO0 #define OPAMP_PGACONNECT_VM1 OPAMP_PGA_CONNECT_INVERTINGINPUT_IO1 -#if defined(STM32L1) || defined(STM32L4) || defined(STM32L5) || defined(STM32H7) || defined(STM32G4) +#if defined(STM32L1) || defined(STM32L4) || defined(STM32L5) || defined(STM32H7) || defined(STM32G4) || defined(STM32U5) #define HAL_OPAMP_MSP_INIT_CB_ID HAL_OPAMP_MSPINIT_CB_ID #define HAL_OPAMP_MSP_DEINIT_CB_ID HAL_OPAMP_MSPDEINIT_CB_ID #endif @@ -1063,8 +1264,25 @@ extern "C" { #define RTC_TAMPERPIN_PA0 RTC_TAMPERPIN_POS1 #define RTC_TAMPERPIN_PI8 RTC_TAMPERPIN_POS1 - - +#if defined(STM32H5) || defined(STM32H7RS) +#define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE +#define TAMP_SECRETDEVICE_ERASE_BKP_SRAM TAMP_DEVICESECRETS_ERASE_BKPSRAM +#endif /* STM32H5 || STM32H7RS */ + +#if defined(STM32WBA) +#define TAMP_SECRETDEVICE_ERASE_NONE TAMP_DEVICESECRETS_ERASE_NONE +#define TAMP_SECRETDEVICE_ERASE_SRAM2 TAMP_DEVICESECRETS_ERASE_SRAM2 +#define TAMP_SECRETDEVICE_ERASE_RHUK TAMP_DEVICESECRETS_ERASE_RHUK +#define TAMP_SECRETDEVICE_ERASE_ICACHE TAMP_DEVICESECRETS_ERASE_ICACHE +#define TAMP_SECRETDEVICE_ERASE_SAES_AES_HASH TAMP_DEVICESECRETS_ERASE_SAES_AES_HASH +#define TAMP_SECRETDEVICE_ERASE_PKA_SRAM TAMP_DEVICESECRETS_ERASE_PKA_SRAM +#define TAMP_SECRETDEVICE_ERASE_ALL TAMP_DEVICESECRETS_ERASE_ALL +#endif /* STM32WBA */ + +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) +#define TAMP_SECRETDEVICE_ERASE_DISABLE TAMP_DEVICESECRETS_ERASE_NONE +#define TAMP_SECRETDEVICE_ERASE_ENABLE TAMP_SECRETDEVICE_ERASE_ALL +#endif /* STM32H5 || STM32WBA || STM32H7RS */ #if defined(STM32F7) #define RTC_TAMPCR_TAMPXE RTC_TAMPER_ENABLE_BITS_MASK @@ -1248,6 +1466,10 @@ extern "C" { #define TIM_TIM3_TI1_COMP1COMP2_OUT TIM_TIM3_TI1_COMP1_COMP2 #endif +#if defined(STM32U5) +#define OCREF_CLEAR_SELECT_Pos OCREF_CLEAR_SELECT_POS +#define OCREF_CLEAR_SELECT_Msk OCREF_CLEAR_SELECT_MSK +#endif /** * @} */ @@ -1398,7 +1620,7 @@ extern "C" { #define ETH_MAC_SMALL_FIFO_RW_ACTIVE 0x00000006U /* MAC small FIFO read / write controllers active */ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE 0x00000001U /* MAC MII receive protocol engine active */ -#define ETH_TxPacketConfig ETH_TxPacketConfig_t /* Transmit Packet Configuration structure definition */ +#define ETH_TxPacketConfig ETH_TxPacketConfigTypeDef /* Transmit Packet Configuration structure definition */ /** * @} @@ -1448,7 +1670,9 @@ extern "C" { */ #endif /* STM32L4 || STM32F7 || STM32F4 || STM32H7 */ -#if defined(STM32L4) || defined(STM32F7) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32H7) +#if defined(STM32L4) || defined(STM32F7) || defined(STM32F427xx) || defined(STM32F437xx) \ + || defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) \ + || defined(STM32H7) || defined(STM32U5) /** @defgroup DMA2D_Aliases DMA2D API Aliases * @{ */ @@ -1458,7 +1682,7 @@ extern "C" { * @} */ -#endif /* STM32L4 || STM32F7 || STM32F4 || STM32H7 */ +#endif /* STM32L4 || STM32F7 || STM32F4 || STM32H7 || STM32U5 */ /** @defgroup HAL_PPP_Aliased_Defines HAL PPP Aliased Defines maintained for legacy purpose * @{ @@ -1482,6 +1706,10 @@ extern "C" { * @{ */ +#if defined(STM32U5) +#define HAL_DCACHE_CleanInvalidateByAddr HAL_DCACHE_CleanInvalidByAddr +#define HAL_DCACHE_CleanInvalidateByAddr_IT HAL_DCACHE_CleanInvalidByAddr_IT +#endif /* STM32U5 */ /** * @} @@ -1604,7 +1832,7 @@ extern "C" { #define HAL_FMPI2CEx_AnalogFilter_Config HAL_FMPI2CEx_ConfigAnalogFilter #define HAL_FMPI2CEx_DigitalFilter_Config HAL_FMPI2CEx_ConfigDigitalFilter -#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) ((cmd == ENABLE)? \ +#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd) == ENABLE)? \ HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): \ HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) @@ -1692,6 +1920,92 @@ extern "C" { #define PWR_MODE_EVT PWR_PVD_MODE_NORMAL +#if defined (STM32U5) +#define PWR_SRAM1_PAGE1_STOP_RETENTION PWR_SRAM1_PAGE1_STOP +#define PWR_SRAM1_PAGE2_STOP_RETENTION PWR_SRAM1_PAGE2_STOP +#define PWR_SRAM1_PAGE3_STOP_RETENTION PWR_SRAM1_PAGE3_STOP +#define PWR_SRAM1_PAGE4_STOP_RETENTION PWR_SRAM1_PAGE4_STOP +#define PWR_SRAM1_PAGE5_STOP_RETENTION PWR_SRAM1_PAGE5_STOP +#define PWR_SRAM1_PAGE6_STOP_RETENTION PWR_SRAM1_PAGE6_STOP +#define PWR_SRAM1_PAGE7_STOP_RETENTION PWR_SRAM1_PAGE7_STOP +#define PWR_SRAM1_PAGE8_STOP_RETENTION PWR_SRAM1_PAGE8_STOP +#define PWR_SRAM1_PAGE9_STOP_RETENTION PWR_SRAM1_PAGE9_STOP +#define PWR_SRAM1_PAGE10_STOP_RETENTION PWR_SRAM1_PAGE10_STOP +#define PWR_SRAM1_PAGE11_STOP_RETENTION PWR_SRAM1_PAGE11_STOP +#define PWR_SRAM1_PAGE12_STOP_RETENTION PWR_SRAM1_PAGE12_STOP +#define PWR_SRAM1_FULL_STOP_RETENTION PWR_SRAM1_FULL_STOP + +#define PWR_SRAM2_PAGE1_STOP_RETENTION PWR_SRAM2_PAGE1_STOP +#define PWR_SRAM2_PAGE2_STOP_RETENTION PWR_SRAM2_PAGE2_STOP +#define PWR_SRAM2_FULL_STOP_RETENTION PWR_SRAM2_FULL_STOP + +#define PWR_SRAM3_PAGE1_STOP_RETENTION PWR_SRAM3_PAGE1_STOP +#define PWR_SRAM3_PAGE2_STOP_RETENTION PWR_SRAM3_PAGE2_STOP +#define PWR_SRAM3_PAGE3_STOP_RETENTION PWR_SRAM3_PAGE3_STOP +#define PWR_SRAM3_PAGE4_STOP_RETENTION PWR_SRAM3_PAGE4_STOP +#define PWR_SRAM3_PAGE5_STOP_RETENTION PWR_SRAM3_PAGE5_STOP +#define PWR_SRAM3_PAGE6_STOP_RETENTION PWR_SRAM3_PAGE6_STOP +#define PWR_SRAM3_PAGE7_STOP_RETENTION PWR_SRAM3_PAGE7_STOP +#define PWR_SRAM3_PAGE8_STOP_RETENTION PWR_SRAM3_PAGE8_STOP +#define PWR_SRAM3_PAGE9_STOP_RETENTION PWR_SRAM3_PAGE9_STOP +#define PWR_SRAM3_PAGE10_STOP_RETENTION PWR_SRAM3_PAGE10_STOP +#define PWR_SRAM3_PAGE11_STOP_RETENTION PWR_SRAM3_PAGE11_STOP +#define PWR_SRAM3_PAGE12_STOP_RETENTION PWR_SRAM3_PAGE12_STOP +#define PWR_SRAM3_PAGE13_STOP_RETENTION PWR_SRAM3_PAGE13_STOP +#define PWR_SRAM3_FULL_STOP_RETENTION PWR_SRAM3_FULL_STOP + +#define PWR_SRAM4_FULL_STOP_RETENTION PWR_SRAM4_FULL_STOP + +#define PWR_SRAM5_PAGE1_STOP_RETENTION PWR_SRAM5_PAGE1_STOP +#define PWR_SRAM5_PAGE2_STOP_RETENTION PWR_SRAM5_PAGE2_STOP +#define PWR_SRAM5_PAGE3_STOP_RETENTION PWR_SRAM5_PAGE3_STOP +#define PWR_SRAM5_PAGE4_STOP_RETENTION PWR_SRAM5_PAGE4_STOP +#define PWR_SRAM5_PAGE5_STOP_RETENTION PWR_SRAM5_PAGE5_STOP +#define PWR_SRAM5_PAGE6_STOP_RETENTION PWR_SRAM5_PAGE6_STOP +#define PWR_SRAM5_PAGE7_STOP_RETENTION PWR_SRAM5_PAGE7_STOP +#define PWR_SRAM5_PAGE8_STOP_RETENTION PWR_SRAM5_PAGE8_STOP +#define PWR_SRAM5_PAGE9_STOP_RETENTION PWR_SRAM5_PAGE9_STOP +#define PWR_SRAM5_PAGE10_STOP_RETENTION PWR_SRAM5_PAGE10_STOP +#define PWR_SRAM5_PAGE11_STOP_RETENTION PWR_SRAM5_PAGE11_STOP +#define PWR_SRAM5_PAGE12_STOP_RETENTION PWR_SRAM5_PAGE12_STOP +#define PWR_SRAM5_PAGE13_STOP_RETENTION PWR_SRAM5_PAGE13_STOP +#define PWR_SRAM5_FULL_STOP_RETENTION PWR_SRAM5_FULL_STOP + +#define PWR_SRAM6_PAGE1_STOP_RETENTION PWR_SRAM6_PAGE1_STOP +#define PWR_SRAM6_PAGE2_STOP_RETENTION PWR_SRAM6_PAGE2_STOP +#define PWR_SRAM6_PAGE3_STOP_RETENTION PWR_SRAM6_PAGE3_STOP +#define PWR_SRAM6_PAGE4_STOP_RETENTION PWR_SRAM6_PAGE4_STOP +#define PWR_SRAM6_PAGE5_STOP_RETENTION PWR_SRAM6_PAGE5_STOP +#define PWR_SRAM6_PAGE6_STOP_RETENTION PWR_SRAM6_PAGE6_STOP +#define PWR_SRAM6_PAGE7_STOP_RETENTION PWR_SRAM6_PAGE7_STOP +#define PWR_SRAM6_PAGE8_STOP_RETENTION PWR_SRAM6_PAGE8_STOP +#define PWR_SRAM6_FULL_STOP_RETENTION PWR_SRAM6_FULL_STOP + + +#define PWR_ICACHE_FULL_STOP_RETENTION PWR_ICACHE_FULL_STOP +#define PWR_DCACHE1_FULL_STOP_RETENTION PWR_DCACHE1_FULL_STOP +#define PWR_DCACHE2_FULL_STOP_RETENTION PWR_DCACHE2_FULL_STOP +#define PWR_DMA2DRAM_FULL_STOP_RETENTION PWR_DMA2DRAM_FULL_STOP +#define PWR_PERIPHRAM_FULL_STOP_RETENTION PWR_PERIPHRAM_FULL_STOP +#define PWR_PKA32RAM_FULL_STOP_RETENTION PWR_PKA32RAM_FULL_STOP +#define PWR_GRAPHICPRAM_FULL_STOP_RETENTION PWR_GRAPHICPRAM_FULL_STOP +#define PWR_DSIRAM_FULL_STOP_RETENTION PWR_DSIRAM_FULL_STOP +#define PWR_JPEGRAM_FULL_STOP_RETENTION PWR_JPEGRAM_FULL_STOP + + +#define PWR_SRAM2_PAGE1_STANDBY_RETENTION PWR_SRAM2_PAGE1_STANDBY +#define PWR_SRAM2_PAGE2_STANDBY_RETENTION PWR_SRAM2_PAGE2_STANDBY +#define PWR_SRAM2_FULL_STANDBY_RETENTION PWR_SRAM2_FULL_STANDBY + +#define PWR_SRAM1_FULL_RUN_RETENTION PWR_SRAM1_FULL_RUN +#define PWR_SRAM2_FULL_RUN_RETENTION PWR_SRAM2_FULL_RUN +#define PWR_SRAM3_FULL_RUN_RETENTION PWR_SRAM3_FULL_RUN +#define PWR_SRAM4_FULL_RUN_RETENTION PWR_SRAM4_FULL_RUN +#define PWR_SRAM5_FULL_RUN_RETENTION PWR_SRAM5_FULL_RUN +#define PWR_SRAM6_FULL_RUN_RETENTION PWR_SRAM6_FULL_RUN + +#define PWR_ALL_RAM_RUN_RETENTION_MASK PWR_ALL_RAM_RUN_MASK +#endif /** * @} @@ -1700,6 +2014,12 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Functions HAL RTC Aliased Functions maintained for legacy purpose * @{ */ +#if defined(STM32H5) || defined(STM32WBA) || defined(STM32H7RS) +#define HAL_RTCEx_SetBoothardwareKey HAL_RTCEx_LockBootHardwareKey +#define HAL_RTCEx_BKUPBlock_Enable HAL_RTCEx_BKUPBlock +#define HAL_RTCEx_BKUPBlock_Disable HAL_RTCEx_BKUPUnblock +#define HAL_RTCEx_Erase_SecretDev_Conf HAL_RTCEx_ConfigEraseDeviceSecrets +#endif /* STM32H5 || STM32WBA || STM32H7RS */ /** * @} @@ -2014,8 +2334,8 @@ extern "C" { #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F302xE) || defined(STM32F302xC) +#endif +#if defined(STM32F302xE) || defined(STM32F302xC) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_ENABLE_RISING_EDGE() : \ @@ -2048,8 +2368,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP4) ? __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP6_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) +#endif +#if defined(STM32F303xE) || defined(STM32F398xx) || defined(STM32F303xC) || defined(STM32F358xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP2) ? __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE() : \ ((__EXTILINE__) == COMP_EXTI_LINE_COMP3) ? __HAL_COMP_COMP3_EXTI_ENABLE_RISING_EDGE() : \ @@ -2106,8 +2426,8 @@ extern "C" { ((__FLAG__) == COMP_EXTI_LINE_COMP5) ? __HAL_COMP_COMP5_EXTI_CLEAR_FLAG() : \ ((__FLAG__) == COMP_EXTI_LINE_COMP6) ? __HAL_COMP_COMP6_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP7_EXTI_CLEAR_FLAG()) -# endif -# if defined(STM32F373xC) ||defined(STM32F378xx) +#endif +#if defined(STM32F373xC) ||defined(STM32F378xx) #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) #define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE() : \ @@ -2124,7 +2444,7 @@ extern "C" { __HAL_COMP_COMP2_EXTI_GET_FLAG()) #define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (((__FLAG__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \ __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()) -# endif +#endif #else #define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (((__EXTILINE__) == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \ __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()) @@ -2426,6 +2746,12 @@ extern "C" { #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET +#if defined(STM32C0) +#define __HAL_RCC_APB1_FORCE_RESET __HAL_RCC_APB1_GRP1_FORCE_RESET +#define __HAL_RCC_APB1_RELEASE_RESET __HAL_RCC_APB1_GRP1_RELEASE_RESET +#define __HAL_RCC_APB2_FORCE_RESET __HAL_RCC_APB1_GRP2_FORCE_RESET +#define __HAL_RCC_APB2_RELEASE_RESET __HAL_RCC_APB1_GRP2_RELEASE_RESET +#endif /* STM32C0 */ #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET @@ -3349,8 +3675,12 @@ extern "C" { #define RCC_MCOSOURCE_PLLCLK_NODIV RCC_MCO1SOURCE_PLLCLK #define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_MCO1SOURCE_PLLCLK_DIV2 +#if defined(STM32U0) +#define RCC_SYSCLKSOURCE_STATUS_PLLR RCC_SYSCLKSOURCE_STATUS_PLLCLK +#endif -#if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) +#if defined(STM32L4) || defined(STM32WB) || defined(STM32G0) || defined(STM32G4) || defined(STM32L5) || \ + defined(STM32WL) || defined(STM32C0) || defined(STM32U0) #define RCC_RTCCLKSOURCE_NO_CLK RCC_RTCCLKSOURCE_NONE #else #define RCC_RTCCLKSOURCE_NONE RCC_RTCCLKSOURCE_NO_CLK @@ -3452,8 +3782,10 @@ extern "C" { #define __HAL_RCC_GET_DFSDM_SOURCE __HAL_RCC_GET_DFSDM1_SOURCE #define RCC_DFSDM1CLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 #define RCC_SWPMI1CLKSOURCE_PCLK RCC_SWPMI1CLKSOURCE_PCLK1 +#if !defined(STM32U0) #define RCC_LPTIM1CLKSOURCE_PCLK RCC_LPTIM1CLKSOURCE_PCLK1 #define RCC_LPTIM2CLKSOURCE_PCLK RCC_LPTIM2CLKSOURCE_PCLK1 +#endif #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM1AUDIOCLKSOURCE_I2S1 #define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM1AUDIOCLKSOURCE_I2S2 @@ -3462,7 +3794,124 @@ extern "C" { #define RCC_DFSDM1CLKSOURCE_APB2 RCC_DFSDM1CLKSOURCE_PCLK2 #define RCC_DFSDM2CLKSOURCE_APB2 RCC_DFSDM2CLKSOURCE_PCLK2 #define RCC_FMPI2C1CLKSOURCE_APB RCC_FMPI2C1CLKSOURCE_PCLK1 - +#if defined(STM32U5) +#define MSIKPLLModeSEL RCC_MSIKPLL_MODE_SEL +#define MSISPLLModeSEL RCC_MSISPLL_MODE_SEL +#define __HAL_RCC_AHB21_CLK_DISABLE __HAL_RCC_AHB2_1_CLK_DISABLE +#define __HAL_RCC_AHB22_CLK_DISABLE __HAL_RCC_AHB2_2_CLK_DISABLE +#define __HAL_RCC_AHB1_CLK_Disable_Clear __HAL_RCC_AHB1_CLK_ENABLE +#define __HAL_RCC_AHB21_CLK_Disable_Clear __HAL_RCC_AHB2_1_CLK_ENABLE +#define __HAL_RCC_AHB22_CLK_Disable_Clear __HAL_RCC_AHB2_2_CLK_ENABLE +#define __HAL_RCC_AHB3_CLK_Disable_Clear __HAL_RCC_AHB3_CLK_ENABLE +#define __HAL_RCC_APB1_CLK_Disable_Clear __HAL_RCC_APB1_CLK_ENABLE +#define __HAL_RCC_APB2_CLK_Disable_Clear __HAL_RCC_APB2_CLK_ENABLE +#define __HAL_RCC_APB3_CLK_Disable_Clear __HAL_RCC_APB3_CLK_ENABLE +#define IS_RCC_MSIPLLModeSelection IS_RCC_MSIPLLMODE_SELECT +#define RCC_PERIPHCLK_CLK48 RCC_PERIPHCLK_ICLK +#define RCC_CLK48CLKSOURCE_HSI48 RCC_ICLK_CLKSOURCE_HSI48 +#define RCC_CLK48CLKSOURCE_PLL2 RCC_ICLK_CLKSOURCE_PLL2 +#define RCC_CLK48CLKSOURCE_PLL1 RCC_ICLK_CLKSOURCE_PLL1 +#define RCC_CLK48CLKSOURCE_MSIK RCC_ICLK_CLKSOURCE_MSIK +#define __HAL_RCC_ADC1_CLK_ENABLE __HAL_RCC_ADC12_CLK_ENABLE +#define __HAL_RCC_ADC1_CLK_DISABLE __HAL_RCC_ADC12_CLK_DISABLE +#define __HAL_RCC_ADC1_IS_CLK_ENABLED __HAL_RCC_ADC12_IS_CLK_ENABLED +#define __HAL_RCC_ADC1_IS_CLK_DISABLED __HAL_RCC_ADC12_IS_CLK_DISABLED +#define __HAL_RCC_ADC1_FORCE_RESET __HAL_RCC_ADC12_FORCE_RESET +#define __HAL_RCC_ADC1_RELEASE_RESET __HAL_RCC_ADC12_RELEASE_RESET +#define __HAL_RCC_ADC1_CLK_SLEEP_ENABLE __HAL_RCC_ADC12_CLK_SLEEP_ENABLE +#define __HAL_RCC_ADC1_CLK_SLEEP_DISABLE __HAL_RCC_ADC12_CLK_SLEEP_DISABLE +#define __HAL_RCC_GET_CLK48_SOURCE __HAL_RCC_GET_ICLK_SOURCE +#define __HAL_RCC_PLLFRACN_ENABLE __HAL_RCC_PLL_FRACN_ENABLE +#define __HAL_RCC_PLLFRACN_DISABLE __HAL_RCC_PLL_FRACN_DISABLE +#define __HAL_RCC_PLLFRACN_CONFIG __HAL_RCC_PLL_FRACN_CONFIG +#define IS_RCC_PLLFRACN_VALUE IS_RCC_PLL_FRACN_VALUE +#endif /* STM32U5 */ + +#if defined(STM32H5) +#define __HAL_RCC_PLLFRACN_ENABLE __HAL_RCC_PLL_FRACN_ENABLE +#define __HAL_RCC_PLLFRACN_DISABLE __HAL_RCC_PLL_FRACN_DISABLE +#define __HAL_RCC_PLLFRACN_CONFIG __HAL_RCC_PLL_FRACN_CONFIG +#define IS_RCC_PLLFRACN_VALUE IS_RCC_PLL_FRACN_VALUE + +#define RCC_PLLSOURCE_NONE RCC_PLL1_SOURCE_NONE +#define RCC_PLLSOURCE_HSI RCC_PLL1_SOURCE_HSI +#define RCC_PLLSOURCE_CSI RCC_PLL1_SOURCE_CSI +#define RCC_PLLSOURCE_HSE RCC_PLL1_SOURCE_HSE +#define RCC_PLLVCIRANGE_0 RCC_PLL1_VCIRANGE_0 +#define RCC_PLLVCIRANGE_1 RCC_PLL1_VCIRANGE_1 +#define RCC_PLLVCIRANGE_2 RCC_PLL1_VCIRANGE_2 +#define RCC_PLLVCIRANGE_3 RCC_PLL1_VCIRANGE_3 +#define RCC_PLL1VCOWIDE RCC_PLL1_VCORANGE_WIDE +#define RCC_PLL1VCOMEDIUM RCC_PLL1_VCORANGE_MEDIUM + +#define IS_RCC_PLLSOURCE IS_RCC_PLL1_SOURCE +#define IS_RCC_PLLRGE_VALUE IS_RCC_PLL1_VCIRGE_VALUE +#define IS_RCC_PLLVCORGE_VALUE IS_RCC_PLL1_VCORGE_VALUE +#define IS_RCC_PLLCLOCKOUT_VALUE IS_RCC_PLL1_CLOCKOUT_VALUE +#define IS_RCC_PLL_FRACN_VALUE IS_RCC_PLL1_FRACN_VALUE +#define IS_RCC_PLLM_VALUE IS_RCC_PLL1_DIVM_VALUE +#define IS_RCC_PLLN_VALUE IS_RCC_PLL1_MULN_VALUE +#define IS_RCC_PLLP_VALUE IS_RCC_PLL1_DIVP_VALUE +#define IS_RCC_PLLQ_VALUE IS_RCC_PLL1_DIVQ_VALUE +#define IS_RCC_PLLR_VALUE IS_RCC_PLL1_DIVR_VALUE + +#define __HAL_RCC_PLL_ENABLE __HAL_RCC_PLL1_ENABLE +#define __HAL_RCC_PLL_DISABLE __HAL_RCC_PLL1_DISABLE +#define __HAL_RCC_PLL_FRACN_ENABLE __HAL_RCC_PLL1_FRACN_ENABLE +#define __HAL_RCC_PLL_FRACN_DISABLE __HAL_RCC_PLL1_FRACN_DISABLE +#define __HAL_RCC_PLL_CONFIG __HAL_RCC_PLL1_CONFIG +#define __HAL_RCC_PLL_PLLSOURCE_CONFIG __HAL_RCC_PLL1_PLLSOURCE_CONFIG +#define __HAL_RCC_PLL_DIVM_CONFIG __HAL_RCC_PLL1_DIVM_CONFIG +#define __HAL_RCC_PLL_FRACN_CONFIG __HAL_RCC_PLL1_FRACN_CONFIG +#define __HAL_RCC_PLL_VCIRANGE __HAL_RCC_PLL1_VCIRANGE +#define __HAL_RCC_PLL_VCORANGE __HAL_RCC_PLL1_VCORANGE +#define __HAL_RCC_GET_PLL_OSCSOURCE __HAL_RCC_GET_PLL1_OSCSOURCE +#define __HAL_RCC_PLLCLKOUT_ENABLE __HAL_RCC_PLL1_CLKOUT_ENABLE +#define __HAL_RCC_PLLCLKOUT_DISABLE __HAL_RCC_PLL1_CLKOUT_DISABLE +#define __HAL_RCC_GET_PLLCLKOUT_CONFIG __HAL_RCC_GET_PLL1_CLKOUT_CONFIG + +#define __HAL_RCC_PLL2FRACN_ENABLE __HAL_RCC_PLL2_FRACN_ENABLE +#define __HAL_RCC_PLL2FRACN_DISABLE __HAL_RCC_PLL2_FRACN_DISABLE +#define __HAL_RCC_PLL2CLKOUT_ENABLE __HAL_RCC_PLL2_CLKOUT_ENABLE +#define __HAL_RCC_PLL2CLKOUT_DISABLE __HAL_RCC_PLL2_CLKOUT_DISABLE +#define __HAL_RCC_PLL2FRACN_CONFIG __HAL_RCC_PLL2_FRACN_CONFIG +#define __HAL_RCC_GET_PLL2CLKOUT_CONFIG __HAL_RCC_GET_PLL2_CLKOUT_CONFIG + +#define __HAL_RCC_PLL3FRACN_ENABLE __HAL_RCC_PLL3_FRACN_ENABLE +#define __HAL_RCC_PLL3FRACN_DISABLE __HAL_RCC_PLL3_FRACN_DISABLE +#define __HAL_RCC_PLL3CLKOUT_ENABLE __HAL_RCC_PLL3_CLKOUT_ENABLE +#define __HAL_RCC_PLL3CLKOUT_DISABLE __HAL_RCC_PLL3_CLKOUT_DISABLE +#define __HAL_RCC_PLL3FRACN_CONFIG __HAL_RCC_PLL3_FRACN_CONFIG +#define __HAL_RCC_GET_PLL3CLKOUT_CONFIG __HAL_RCC_GET_PLL3_CLKOUT_CONFIG + +#define RCC_PLL2VCIRANGE_0 RCC_PLL2_VCIRANGE_0 +#define RCC_PLL2VCIRANGE_1 RCC_PLL2_VCIRANGE_1 +#define RCC_PLL2VCIRANGE_2 RCC_PLL2_VCIRANGE_2 +#define RCC_PLL2VCIRANGE_3 RCC_PLL2_VCIRANGE_3 + +#define RCC_PLL2VCOWIDE RCC_PLL2_VCORANGE_WIDE +#define RCC_PLL2VCOMEDIUM RCC_PLL2_VCORANGE_MEDIUM + +#define RCC_PLL2SOURCE_NONE RCC_PLL2_SOURCE_NONE +#define RCC_PLL2SOURCE_HSI RCC_PLL2_SOURCE_HSI +#define RCC_PLL2SOURCE_CSI RCC_PLL2_SOURCE_CSI +#define RCC_PLL2SOURCE_HSE RCC_PLL2_SOURCE_HSE + +#define RCC_PLL3VCIRANGE_0 RCC_PLL3_VCIRANGE_0 +#define RCC_PLL3VCIRANGE_1 RCC_PLL3_VCIRANGE_1 +#define RCC_PLL3VCIRANGE_2 RCC_PLL3_VCIRANGE_2 +#define RCC_PLL3VCIRANGE_3 RCC_PLL3_VCIRANGE_3 + +#define RCC_PLL3VCOWIDE RCC_PLL3_VCORANGE_WIDE +#define RCC_PLL3VCOMEDIUM RCC_PLL3_VCORANGE_MEDIUM + +#define RCC_PLL3SOURCE_NONE RCC_PLL3_SOURCE_NONE +#define RCC_PLL3SOURCE_HSI RCC_PLL3_SOURCE_HSI +#define RCC_PLL3SOURCE_CSI RCC_PLL3_SOURCE_CSI +#define RCC_PLL3SOURCE_HSE RCC_PLL3_SOURCE_HSE + + +#endif /* STM32H5 */ /** * @} @@ -3480,7 +3929,9 @@ extern "C" { /** @defgroup HAL_RTC_Aliased_Macros HAL RTC Aliased Macros maintained for legacy purpose * @{ */ -#if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) +#if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || \ + defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || \ + defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) #else #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #endif @@ -3540,6 +3991,10 @@ extern "C" { #define __RTC_WRITEPROTECTION_ENABLE __HAL_RTC_WRITEPROTECTION_ENABLE #define __RTC_WRITEPROTECTION_DISABLE __HAL_RTC_WRITEPROTECTION_DISABLE +#if defined (STM32H5) +#define __HAL_RCC_RTCAPB_CLK_ENABLE __HAL_RCC_RTC_CLK_ENABLE +#define __HAL_RCC_RTCAPB_CLK_DISABLE __HAL_RCC_RTC_CLK_DISABLE +#endif /* STM32H5 */ /** * @} diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal.h index 5786f8a42..e67a2033b 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal.h @@ -601,7 +601,9 @@ void HAL_SYSCFG_DisableIOSwitchBooster(void); void HAL_SYSCFG_EnableIOSwitchVDD(void); void HAL_SYSCFG_DisableIOSwitchVDD(void); +#if defined(CCMSRAM_BASE) void HAL_SYSCFG_CCMSRAM_WriteProtectionEnable(uint32_t Page); +#endif /* CCMSRAM_BASE */ /** * @} diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc.h index 97bc1bbce..81622aae4 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc.h @@ -1305,7 +1305,7 @@ out-of-window sample to raise flag or interrupt */ ((__REGTRIG__) == ADC_EXTERNALTRIG_T8_CC1) || \ ((__REGTRIG__) == ADC_EXTERNALTRIG_EXT_IT2))) || \ ((__REGTRIG__) == ADC_SOFTWARE_START) ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_EXTTRIG(__HANDLE__, __REGTRIG__) (((__REGTRIG__) == ADC_EXTERNALTRIG_T1_TRGO) || \ ((__REGTRIG__) == ADC_EXTERNALTRIG_T1_TRGO2) || \ ((__REGTRIG__) == ADC_EXTERNALTRIG_T1_CC1) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc_ex.h index 7acf6e663..d893d33b6 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_adc_ex.h @@ -631,7 +631,7 @@ typedef struct : \ RESET \ ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) #define ADC_IS_INDEPENDENT(__HANDLE__) (RESET) #endif /* defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) */ @@ -790,7 +790,7 @@ typedef struct : \ ((__HANDLE_SLAVE__)->Instance = NULL) \ ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) /** * @brief Set handle instance of the ADC slave associated to the ADC master. * @param __HANDLE_MASTER__ ADC master handle. @@ -816,7 +816,7 @@ typedef struct #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define ADC_TEMPERATURE_SENSOR_INSTANCE(__HANDLE__) \ ((((__HANDLE__)->Instance) == ADC1) || (((__HANDLE__)->Instance) == ADC5)) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) #define ADC_TEMPERATURE_SENSOR_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) == ADC1) #endif /* defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) */ @@ -828,7 +828,7 @@ typedef struct #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define ADC_BATTERY_VOLTAGE_INSTANCE(__HANDLE__) \ ((((__HANDLE__)->Instance) != ADC2) || (((__HANDLE__)->Instance) != ADC4)) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) #define ADC_BATTERY_VOLTAGE_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) != ADC2) #elif defined(STM32G491xx) || defined(STM32G4A1xx) #define ADC_BATTERY_VOLTAGE_INSTANCE(__HANDLE__) (((__HANDLE__)->Instance) == ADC1) @@ -947,7 +947,7 @@ typedef struct ((__CHANNEL__) == ADC_CHANNEL_16) || \ ((__CHANNEL__) == ADC_CHANNEL_VBAT) || \ ((__CHANNEL__) == ADC_CHANNEL_VREFINT)))) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_0) || \ ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ @@ -1069,7 +1069,7 @@ typedef struct ((__CHANNEL__) == ADC_CHANNEL_13))) || \ ((((__HANDLE__)->Instance) == ADC3) && \ ((__CHANNEL__) == ADC_CHANNEL_15))) ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_DIFF_CHANNEL(__HANDLE__, __CHANNEL__) ( ( ((__CHANNEL__) == ADC_CHANNEL_1) || \ ((__CHANNEL__) == ADC_CHANNEL_2) || \ ((__CHANNEL__) == ADC_CHANNEL_3) || \ @@ -1239,7 +1239,7 @@ typedef struct ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T8_CC2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_EXT_IT3))) || \ ((__INJTRIG__) == ADC_INJECTED_SOFTWARE_START) ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_ADC_EXTTRIGINJEC(__HANDLE__, __INJTRIG__) (((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_TRGO2) || \ ((__INJTRIG__) == ADC_EXTERNALTRIGINJEC_T1_CC4) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_comp.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_comp.h index f575d605e..2aecfde90 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_comp.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_comp.h @@ -369,16 +369,16 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP1 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP1); \ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP1);\ +#define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP1); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP1); \ } while(0) /** * @brief Disable the COMP1 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ +#define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP1); \ LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP1);\ } while(0) @@ -453,17 +453,17 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP2 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP2);\ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP2);\ +#define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP2); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP2); \ } while(0) /** * @brief Disable the COMP2 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP2);\ +#define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP2); \ LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP2);\ } while(0) @@ -537,19 +537,19 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP3 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP3_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP3); \ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP3); \ - } while(0) +#define __HAL_COMP_COMP3_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP3); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP3); \ + } while(0) /** * @brief Disable the COMP3 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP3_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP3); \ - LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP3); \ - } while(0) +#define __HAL_COMP_COMP3_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP3); \ + LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP3);\ + } while(0) /** * @brief Enable the COMP3 EXTI line in interrupt mode. @@ -621,19 +621,19 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP4 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP4_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP4); \ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP4); \ - } while(0) +#define __HAL_COMP_COMP4_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP4); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP4); \ + } while(0) /** * @brief Disable the COMP4 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP4_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP4); \ - LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP4); \ - } while(0) +#define __HAL_COMP_COMP4_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP4); \ + LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP4);\ + } while(0) /** * @brief Enable the COMP4 EXTI line in interrupt mode. @@ -677,7 +677,7 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer */ #define __HAL_COMP_COMP4_EXTI_CLEAR_FLAG() LL_EXTI_ClearFlag_0_31(COMP_EXTI_LINE_COMP4) -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) /** * @brief Enable the COMP5 EXTI line rising edge trigger. * @retval None @@ -706,19 +706,19 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP5 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP5_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP5); \ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP5); \ - } while(0) +#define __HAL_COMP_COMP5_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP5); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP5); \ + } while(0) /** * @brief Disable the COMP5 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP5_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP5); \ - LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP5); \ - } while(0) +#define __HAL_COMP_COMP5_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP5); \ + LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP5);\ + } while(0) /** * @brief Enable the COMP5 EXTI line in interrupt mode. @@ -762,8 +762,8 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer */ #define __HAL_COMP_COMP5_EXTI_CLEAR_FLAG() LL_EXTI_ClearFlag_0_31(COMP_EXTI_LINE_COMP5) -#endif /* STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx*/ -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx*/ +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) /** * @brief Enable the COMP6 EXTI line rising edge trigger. * @retval None @@ -792,19 +792,19 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP6 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP6_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_32_63(COMP_EXTI_LINE_COMP6); \ - LL_EXTI_EnableFallingTrig_32_63(COMP_EXTI_LINE_COMP6); \ - } while(0) +#define __HAL_COMP_COMP6_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_32_63(COMP_EXTI_LINE_COMP6); \ + LL_EXTI_EnableFallingTrig_32_63(COMP_EXTI_LINE_COMP6); \ + } while(0) /** * @brief Disable the COMP6 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP6_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_DisableRisingTrig_32_63(COMP_EXTI_LINE_COMP6); \ - LL_EXTI_DisableFallingTrig_32_63(COMP_EXTI_LINE_COMP6); \ - } while(0) +#define __HAL_COMP_COMP6_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_DisableRisingTrig_32_63(COMP_EXTI_LINE_COMP6);\ + LL_EXTI_DisableFallingTrig_32_63(COMP_EXTI_LINE_COMP6);\ + } while(0) /** * @brief Enable the COMP6 EXTI line in interrupt mode. @@ -848,8 +848,8 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer */ #define __HAL_COMP_COMP6_EXTI_CLEAR_FLAG() LL_EXTI_ClearFlag_32_63(COMP_EXTI_LINE_COMP6) -#endif /* STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx*/ -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx*/ +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) /** * @brief Enable the COMP7 EXTI line rising edge trigger. * @retval None @@ -878,19 +878,19 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP7 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP7_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_32_63(COMP_EXTI_LINE_COMP7); \ - LL_EXTI_EnableFallingTrig_32_63(COMP_EXTI_LINE_COMP7); \ - } while(0) +#define __HAL_COMP_COMP7_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_32_63(COMP_EXTI_LINE_COMP7); \ + LL_EXTI_EnableFallingTrig_32_63(COMP_EXTI_LINE_COMP7); \ + } while(0) /** * @brief Disable the COMP7 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP7_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_DisableRisingTrig_32_63(COMP_EXTI_LINE_COMP7); \ - LL_EXTI_DisableFallingTrig_32_63(COMP_EXTI_LINE_COMP7); \ - } while(0) +#define __HAL_COMP_COMP7_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_DisableRisingTrig_32_63(COMP_EXTI_LINE_COMP7);\ + LL_EXTI_DisableFallingTrig_32_63(COMP_EXTI_LINE_COMP7);\ + } while(0) /** * @brief Enable the COMP7 EXTI line in interrupt mode. @@ -934,7 +934,7 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer */ #define __HAL_COMP_COMP7_EXTI_CLEAR_FLAG() LL_EXTI_ClearFlag_32_63(COMP_EXTI_LINE_COMP7) -#endif /* STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ /** * @} */ @@ -957,11 +957,11 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer #define COMP_EXTI_LINE_COMP2 (LL_EXTI_LINE_22) /*!< EXTI line 22 connected to COMP2 output. Note: For COMPx instance availability, please refer to datasheet */ #define COMP_EXTI_LINE_COMP3 (LL_EXTI_LINE_29) /*!< EXTI line 29 connected to COMP3 output. Note: For COMPx instance availability, please refer to datasheet */ #define COMP_EXTI_LINE_COMP4 (LL_EXTI_LINE_30) /*!< EXTI line 30 connected to COMP4 output. Note: For COMPx instance availability, please refer to datasheet */ -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define COMP_EXTI_LINE_COMP5 (LL_EXTI_LINE_31) /*!< EXTI line 31 connected to COMP5 output. Note: For COMPx instance availability, please refer to datasheet */ #define COMP_EXTI_LINE_COMP6 (LL_EXTI_LINE_32) /*!< EXTI line 32 connected to COMP6 output. Note: For COMPx instance availability, please refer to datasheet */ #define COMP_EXTI_LINE_COMP7 (LL_EXTI_LINE_33) /*!< EXTI line 33 connected to COMP7 output. Note: For COMPx instance availability, please refer to datasheet */ -#endif /* STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ /** * @} */ @@ -994,7 +994,7 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @param __INSTANCE__ specifies the COMP instance. * @retval value of @ref COMP_ExtiLine */ -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define COMP_GET_EXTI_LINE(__INSTANCE__) (((__INSTANCE__) == COMP1) ? COMP_EXTI_LINE_COMP1 \ :((__INSTANCE__) == COMP2) ? COMP_EXTI_LINE_COMP2 \ :((__INSTANCE__) == COMP3) ? COMP_EXTI_LINE_COMP3 \ @@ -1007,7 +1007,7 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer :((__INSTANCE__) == COMP2) ? COMP_EXTI_LINE_COMP2 \ :((__INSTANCE__) == COMP3) ? COMP_EXTI_LINE_COMP3 \ : COMP_EXTI_LINE_COMP4) -#endif /* STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ /** * @} */ @@ -1018,63 +1018,63 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer #define IS_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) (((__INPUT_PLUS__) == COMP_INPUT_PLUS_IO1) || \ ((__INPUT_PLUS__) == COMP_INPUT_PLUS_IO2)) -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) -#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2) ||\ +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2) || \ (((__COMP_INSTANCE__) == COMP1) && \ (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) || \ ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP2) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ ) || \ (((__COMP_INSTANCE__) == COMP3) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP4) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ ) || \ (((__COMP_INSTANCE__) == COMP5) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC4_CH1)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC4_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP6) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC2_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC4_CH2)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC2_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC4_CH2)) \ ) || \ (((__COMP_INSTANCE__) == COMP7) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC2_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC4_CH1)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC2_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC4_CH1)) \ )) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) -#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2) ||\ +#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2) || \ (((__COMP_INSTANCE__) == COMP1) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP2) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ ) || \ (((__COMP_INSTANCE__) == COMP3) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP4) && \ - (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ + (((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC3_CH2)) \ )) #endif @@ -1098,159 +1098,159 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer /* Better use IS_COMP_BLANKINGSRC_INSTANCE instead */ /* Macro kept for compatibility with other STM32 series */ #define IS_COMP_BLANKINGSRCE(__OUTPUT_BLANKING_SOURCE__) \ - ( ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP2) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP3) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP4) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP6) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP7) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP2) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP3) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP6) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP2) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP3) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP7) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC4_COMP4) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP2) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP3) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP4) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP6) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP7) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1_COMP4) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC2_COMP6) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC2_COMP7) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM20_OC5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ + (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP2) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP4) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP6) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP7) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP2) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP6) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP2) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP7) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC4_COMP4) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP2) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP4) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP6) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP7) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1_COMP4) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC2_COMP6) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC2_COMP7) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM20_OC5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ ) -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define IS_COMP_BLANKINGSRC_INSTANCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ - ((((__INSTANCE__) == COMP1) && \ + ((((__INSTANCE__) == COMP1) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ - || \ - (((__INSTANCE__) == COMP2) && \ + || \ + (((__INSTANCE__) == COMP2) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ - || \ - (((__INSTANCE__) == COMP3) && \ + || \ + (((__INSTANCE__) == COMP3) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ - || \ - (((__INSTANCE__) == COMP4) && \ + || \ + (((__INSTANCE__) == COMP4) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ - || \ - (((__INSTANCE__) == COMP5) && \ + || \ + (((__INSTANCE__) == COMP5) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP5) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP5) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP5) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP5))) \ - || \ - (((__INSTANCE__) == COMP6) && \ + || \ + (((__INSTANCE__) == COMP6) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP6) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP6) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP6) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC2_COMP6))) \ - || \ - (((__INSTANCE__) == COMP7) && \ + || \ + (((__INSTANCE__) == COMP7) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP7) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP7) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP7) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC2_COMP7))) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM20_OC5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM20_OC5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ ) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) #define IS_COMP_BLANKINGSRC_INSTANCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ - ((((__INSTANCE__) == COMP1) && \ + ((((__INSTANCE__) == COMP1) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ - || \ - (((__INSTANCE__) == COMP2) && \ + || \ + (((__INSTANCE__) == COMP2) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ - || \ - (((__INSTANCE__) == COMP3) && \ + || \ + (((__INSTANCE__) == COMP3) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ - || \ - (((__INSTANCE__) == COMP4) && \ + || \ + (((__INSTANCE__) == COMP4) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ ) #elif defined(STM32G491xx) || defined(STM32G4A1xx) #define IS_COMP_BLANKINGSRC_INSTANCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ - ((((__INSTANCE__) == COMP1) && \ + ((((__INSTANCE__) == COMP1) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ - || \ - (((__INSTANCE__) == COMP2) && \ + || \ + (((__INSTANCE__) == COMP2) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ - || \ - (((__INSTANCE__) == COMP3) && \ + || \ + (((__INSTANCE__) == COMP3) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ - || \ - (((__INSTANCE__) == COMP4) && \ + || \ + (((__INSTANCE__) == COMP4) && \ (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM20_OC5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM20_OC5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM4_OC3) \ ) -#endif /* STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ #define IS_COMP_TRIGGERMODE(__MODE__) (((__MODE__) == COMP_TRIGGERMODE_NONE) || \ ((__MODE__) == COMP_TRIGGERMODE_IT_RISING) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cordic.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cordic.h index 2f0684538..ddb7a7b0a 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cordic.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cordic.h @@ -149,7 +149,6 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p * @} */ - /* Exported constants --------------------------------------------------------*/ /** @defgroup CORDIC_Exported_Constants CORDIC Exported Constants * @{ @@ -166,6 +165,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p #if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1 #define HAL_CORDIC_ERROR_INVALID_CALLBACK ((uint32_t)0x00000010U) /*!< Invalid Callback error */ #endif /* USE_HAL_CORDIC_REGISTER_CALLBACKS */ + /** * @} */ @@ -183,6 +183,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p #define CORDIC_FUNCTION_HARCTANGENT ((uint32_t)(CORDIC_CSR_FUNC_2 | CORDIC_CSR_FUNC_1 | CORDIC_CSR_FUNC_0))/*!< Hyperbolic Arctangent */ #define CORDIC_FUNCTION_NATURALLOG ((uint32_t)(CORDIC_CSR_FUNC_3)) /*!< Natural Logarithm */ #define CORDIC_FUNCTION_SQUAREROOT ((uint32_t)(CORDIC_CSR_FUNC_3 | CORDIC_CSR_FUNC_0)) /*!< Square Root */ + /** * @} */ @@ -212,6 +213,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p #define CORDIC_PRECISION_15CYCLES ((uint32_t)(CORDIC_CSR_PRECISION_3\ | CORDIC_CSR_PRECISION_2 | CORDIC_CSR_PRECISION_1\ |CORDIC_CSR_PRECISION_0)) + /** * @} */ @@ -229,6 +231,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p #define CORDIC_SCALE_5 ((uint32_t)(CORDIC_CSR_SCALE_2 | CORDIC_CSR_SCALE_0)) #define CORDIC_SCALE_6 ((uint32_t)(CORDIC_CSR_SCALE_2 | CORDIC_CSR_SCALE_1)) #define CORDIC_SCALE_7 ((uint32_t)(CORDIC_CSR_SCALE_2 | CORDIC_CSR_SCALE_1 | CORDIC_CSR_SCALE_0)) + /** * @} */ @@ -237,6 +240,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p * @{ */ #define CORDIC_IT_IEN CORDIC_CSR_IEN /*!< Result ready interrupt enable */ + /** * @} */ @@ -245,6 +249,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p * @{ */ #define CORDIC_DMA_REN CORDIC_CSR_DMAREN /*!< DMA Read requests enable */ + /** * @} */ @@ -253,6 +258,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p * @{ */ #define CORDIC_DMA_WEN CORDIC_CSR_DMAWEN /*!< DMA Write channel enable */ + /** * @} */ @@ -288,6 +294,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p */ #define CORDIC_INSIZE_32BITS (0x00000000U) /*!< 32 bits input data size (Q1.31 format) */ #define CORDIC_INSIZE_16BITS CORDIC_CSR_ARGSIZE /*!< 16 bits input data size (Q1.15 format) */ + /** * @} */ @@ -297,6 +304,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p */ #define CORDIC_OUTSIZE_32BITS (0x00000000U) /*!< 32 bits output data size (Q1.31 format) */ #define CORDIC_OUTSIZE_16BITS CORDIC_CSR_RESSIZE /*!< 16 bits output data size (Q1.15 format) */ + /** * @} */ @@ -305,6 +313,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p * @{ */ #define CORDIC_FLAG_RRDY CORDIC_CSR_RRDY /*!< Result Ready Flag */ + /** * @} */ @@ -316,6 +325,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p #define CORDIC_DMA_DIR_IN ((uint32_t)0x00000001U) /*!< DMA direction : Input of CORDIC */ #define CORDIC_DMA_DIR_OUT ((uint32_t)0x00000002U) /*!< DMA direction : Output of CORDIC */ #define CORDIC_DMA_DIR_IN_OUT ((uint32_t)0x00000003U) /*!< DMA direction : Input and Output of CORDIC */ + /** * @} */ @@ -336,9 +346,9 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p */ #if USE_HAL_CORDIC_REGISTER_CALLBACKS == 1 #define __HAL_CORDIC_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->State = HAL_CORDIC_STATE_RESET; \ - (__HANDLE__)->MspInitCallback = NULL; \ - (__HANDLE__)->MspDeInitCallback = NULL; \ + (__HANDLE__)->State = HAL_CORDIC_STATE_RESET; \ + (__HANDLE__)->MspInitCallback = NULL; \ + (__HANDLE__)->MspDeInitCallback = NULL; \ } while(0) #else #define __HAL_CORDIC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CORDIC_STATE_RESET) @@ -416,7 +426,7 @@ typedef void (*pCORDIC_CallbackTypeDef)(CORDIC_HandleTypeDef *hcordic); /*!< p * @} */ -/* Private macros --------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ /** @defgroup CORDIC_Private_Macros CORDIC Private Macros * @{ */ @@ -584,6 +594,7 @@ void HAL_CORDIC_IRQHandler(CORDIC_HandleTypeDef *hcordic); /* Peripheral State functions *************************************************/ HAL_CORDIC_StateTypeDef HAL_CORDIC_GetState(const CORDIC_HandleTypeDef *hcordic); uint32_t HAL_CORDIC_GetError(const CORDIC_HandleTypeDef *hcordic); + /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cortex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cortex.h index ecb1ebccc..e02040564 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cortex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_cortex.h @@ -295,6 +295,8 @@ void HAL_SYSTICK_Callback(void); #if (__MPU_PRESENT == 1) void HAL_MPU_Enable(uint32_t MPU_Control); void HAL_MPU_Disable(void); +void HAL_MPU_EnableRegion(uint32_t RegionNumber); +void HAL_MPU_DisableRegion(uint32_t RegionNumber); void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #endif /* __MPU_PRESENT */ /** diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac.h index a331446b9..d196be0f0 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac.h @@ -499,7 +499,7 @@ typedef void (*pDAC_CallbackTypeDef)(DAC_HandleTypeDef *hdac); #define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) #define IS_DAC_CHANNEL(DACX, CHANNEL) \ (((DACX) == DAC2) ? \ ((CHANNEL) == DAC_CHANNEL_1) \ @@ -510,7 +510,7 @@ typedef void (*pDAC_CallbackTypeDef)(DAC_HandleTypeDef *hdac); #define IS_DAC_CHANNEL(DACX, CHANNEL) \ (((CHANNEL) == DAC_CHANNEL_1) || \ ((CHANNEL) == DAC_CHANNEL_2)) -#endif /* STM32G474xx || STM32G484xx || STM32G473xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx */ #define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ ((ALIGN) == DAC_ALIGN_12B_L) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac_ex.h index d042af1a6..bbc7f573a 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_dac_ex.h @@ -103,7 +103,7 @@ extern "C" { /** @defgroup DACEx_Private_Macros DACEx Private Macros * @{ */ -#if defined(STM32G474xx) || defined(STM32G484xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) #define IS_DAC_TRIGGER(DACX, TRIGGER) \ (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE) || \ @@ -153,9 +153,9 @@ extern "C" { : ((TRIGGER) == DAC_TRIGGER_T8_TRGO) \ ) \ ) -#endif /* STM32G474xx || STM32G484xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx */ -#if defined(STM32G474xx) || defined(STM32G484xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) #define IS_DAC_TRIGGER2(DACX, TRIGGER) \ (((TRIGGER) == DAC_TRIGGER_NONE) || \ ((TRIGGER) == DAC_TRIGGER_SOFTWARE) || \ @@ -201,7 +201,7 @@ extern "C" { :((TRIGGER) == DAC_TRIGGER_T8_TRGO) \ ) \ ) -#endif /* STM32G474xx || STM32G484xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx */ #define IS_DAC_HIGH_FREQUENCY_MODE(MODE) (((MODE) == DAC_HIGH_FREQUENCY_INTERFACE_MODE_DISABLE) || \ ((MODE) == DAC_HIGH_FREQUENCY_INTERFACE_MODE_ABOVE_80MHZ) || \ ((MODE) == DAC_HIGH_FREQUENCY_INTERFACE_MODE_ABOVE_160MHZ) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fdcan.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fdcan.h index e956f7f69..4e9bb25ad 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fdcan.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fdcan.h @@ -517,8 +517,8 @@ typedef void (*pFDCAN_ErrorStatusCallbackTypeDef)(FDCAN_HandleTypeDef *hfdcan, #define HAL_FDCAN_ERROR_PARAM ((uint32_t)0x00000020U) /*!< Parameter error */ #define HAL_FDCAN_ERROR_PENDING ((uint32_t)0x00000040U) /*!< Pending operation */ #define HAL_FDCAN_ERROR_RAM_ACCESS ((uint32_t)0x00000080U) /*!< Message RAM Access Failure */ -#define HAL_FDCAN_ERROR_FIFO_EMPTY ((uint32_t)0x00000100U) /*!< Put element in full FIFO */ -#define HAL_FDCAN_ERROR_FIFO_FULL ((uint32_t)0x00000200U) /*!< Get element from empty FIFO */ +#define HAL_FDCAN_ERROR_FIFO_EMPTY ((uint32_t)0x00000100U) /*!< Get element from empty FIFO */ +#define HAL_FDCAN_ERROR_FIFO_FULL ((uint32_t)0x00000200U) /*!< Put element in full FIFO */ #define HAL_FDCAN_ERROR_LOG_OVERFLOW FDCAN_IR_ELO /*!< Overflow of CAN Error Logging Counter */ #define HAL_FDCAN_ERROR_RAM_WDG FDCAN_IR_WDI /*!< Message RAM Watchdog event occurred */ #define HAL_FDCAN_ERROR_PROTOCOL_ARBT FDCAN_IR_PEA /*!< Protocol Error in Arbitration Phase (Nominal Bit Time is used) */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fmac.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fmac.h index ca8926986..48a94b612 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fmac.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_fmac.h @@ -243,10 +243,7 @@ typedef struct * @} */ - /* Exported constants --------------------------------------------------------*/ - - /** @defgroup FMAC_Exported_Constants FMAC Exported Constants * @{ */ @@ -357,7 +354,6 @@ typedef struct * @} */ - /* Exported variables --------------------------------------------------------*/ /** @defgroup FMAC_Exported_variables FMAC Exported variables * @{ @@ -499,7 +495,7 @@ typedef struct * @} */ -/* Private Macros-----------------------------------------------------------*/ +/* Private Macros-------------------------------------------------------------*/ /** @addtogroup FMAC_Private_Macros FMAC Private Macros * @{ */ @@ -578,9 +574,9 @@ typedef struct * @param __FUNCTION__ ID of the filter function. * @retval SET (__Q__ is a valid value) or RESET (__Q__ is invalid) */ -#define IS_FMAC_PARAM_Q(__FUNCTION__, __Q__) ( ((__FUNCTION__) == FMAC_FUNC_CONVO_FIR) || \ - (((__FUNCTION__) == FMAC_FUNC_IIR_DIRECT_FORM_1) && \ - (((__Q__) >= FMAC_PARAM_Q_MIN) && ((__Q__) <= FMAC_PARAM_Q_MAX))) ) +#define IS_FMAC_PARAM_Q(__FUNCTION__, __Q__) (((__FUNCTION__) == FMAC_FUNC_CONVO_FIR) || \ + (((__FUNCTION__) == FMAC_FUNC_IIR_DIRECT_FORM_1) && \ + (((__Q__) >= FMAC_PARAM_Q_MIN) && ((__Q__) <= FMAC_PARAM_Q_MAX)))) /** * @brief Verify the FMAC filter parameter R. diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_i2c_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_i2c_ex.h index 840beeaed..3042f9eb1 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_i2c_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_i2c_ex.h @@ -60,7 +60,11 @@ extern "C" { #define I2C_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_PB9_FMP /*!< Enable Fast Mode Plus on PB9 */ #define I2C_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C1_FMP /*!< Enable Fast Mode Plus on I2C1 pins */ #define I2C_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C2_FMP /*!< Enable Fast Mode Plus on I2C2 pins */ +#if defined(SYSCFG_CFGR1_I2C3_FMP) #define I2C_FASTMODEPLUS_I2C3 SYSCFG_CFGR1_I2C3_FMP /*!< Enable Fast Mode Plus on I2C3 pins */ +#else +#define I2C_FASTMODEPLUS_I2C3 (uint32_t)(0x00000400U | I2C_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus I2C3 not supported */ +#endif /* SYSCFG_CFGR1_I2C3_FMP */ #if defined(SYSCFG_CFGR1_I2C4_FMP) #define I2C_FASTMODEPLUS_I2C4 SYSCFG_CFGR1_I2C4_FMP /*!< Enable Fast Mode Plus on I2C4 pins */ #else @@ -138,6 +142,7 @@ void HAL_I2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus); #define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000FU) +#if defined (I2C3) #define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & I2C_FMP_NOT_SUPPORTED) != I2C_FMP_NOT_SUPPORTED) && \ ((((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ @@ -147,6 +152,16 @@ void HAL_I2CEx_DisableFastModePlus(uint32_t ConfigFastModePlus); (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C2)) == I2C_FASTMODEPLUS_I2C2) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C3)) == I2C_FASTMODEPLUS_I2C3) || \ (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C4)) == I2C_FASTMODEPLUS_I2C4))) +#else +#define IS_I2C_FASTMODEPLUS(__CONFIG__) ((((__CONFIG__) & I2C_FMP_NOT_SUPPORTED) != I2C_FMP_NOT_SUPPORTED) && \ + ((((__CONFIG__) & (I2C_FASTMODEPLUS_PB6)) == I2C_FASTMODEPLUS_PB6) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_PB7)) == I2C_FASTMODEPLUS_PB7) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_PB8)) == I2C_FASTMODEPLUS_PB8) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_PB9)) == I2C_FASTMODEPLUS_PB9) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C1)) == I2C_FASTMODEPLUS_I2C1) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C2)) == I2C_FASTMODEPLUS_I2C2) || \ + (((__CONFIG__) & (I2C_FASTMODEPLUS_I2C4)) == I2C_FASTMODEPLUS_I2C4))) +#endif /* I2C3 */ /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_irda_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_irda_ex.h index 24df2ebd4..c1f87f4f7 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_irda_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_irda_ex.h @@ -69,7 +69,99 @@ extern "C" { * @param __CLOCKSOURCE__ output variable. * @retval IRDA clocking source, written in __CLOCKSOURCE__. */ -#if defined(UART5) +#if defined(UART5) && !defined(USART3) +#define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == UART4) \ + { \ + switch(__HAL_RCC_GET_UART4_SOURCE()) \ + { \ + case RCC_UART4CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_UART4CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_UART4CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_UART4CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == UART5) \ + { \ + switch(__HAL_RCC_GET_UART5_SOURCE()) \ + { \ + case RCC_UART5CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_UART5CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_UART5CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_UART5CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#elif defined(UART5) && defined(USART3) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -182,7 +274,78 @@ extern "C" { (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) -#elif defined(UART4) +#elif defined(UART4) && !defined(USART3) +#define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == UART4) \ + { \ + switch(__HAL_RCC_GET_UART4_SOURCE()) \ + { \ + case RCC_UART4CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_UART4CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_UART4CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_UART4CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#elif defined(UART4) && defined(USART3) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -274,7 +437,7 @@ extern "C" { (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) -#else +#elif defined(USART3) #define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -345,7 +508,57 @@ extern "C" { (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) -#endif /* UART5 */ +#else +#define IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#endif /* UART5 && !USART3 */ /** @brief Compute the mask to apply to retrieve the received data * according to the word length and to the parity bits activation. diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_lptim.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_lptim.h index 6ceca1a25..82176c33d 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_lptim.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_lptim.h @@ -766,7 +766,7 @@ HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(const LPTIM_HandleTypeDef *hlptim); ((__POLARITY__) == LPTIM_CLOCKPOLARITY_FALLING) || \ ((__POLARITY__) == LPTIM_CLOCKPOLARITY_RISING_FALLING)) -#if defined(STM32G473xx) || defined(STM32G483xx) || defined(STM32G474xx) || defined(STM32G484xx) +#if defined(STM32G414xx) || defined(STM32G473xx) || defined(STM32G483xx) || defined(STM32G474xx) || defined(STM32G484xx) #define IS_LPTIM_TRG_SOURCE(__TRIG__) (((__TRIG__) == LPTIM_TRIGSOURCE_SOFTWARE) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_0) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_1) || \ @@ -793,7 +793,7 @@ HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(const LPTIM_HandleTypeDef *hlptim); ((__TRIG__) == LPTIM_TRIGSOURCE_7) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_8) || \ ((__TRIG__) == LPTIM_TRIGSOURCE_9)) -#endif /* STM32G473xx || STM32G483xx || STM32G474xx || STM32G484xx */ +#endif /* STM32G414xx || STM32G473xx || STM32G483xx || STM32G474xx || STM32G484xx */ #define IS_LPTIM_EXT_TRG_POLARITY(__POLARITY__) (((__POLARITY__) == LPTIM_ACTIVEEDGE_RISING ) || \ ((__POLARITY__) == LPTIM_ACTIVEEDGE_FALLING ) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp.h index a8849057a..e00b8280a 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp.h @@ -31,6 +31,8 @@ extern "C" { * @{ */ +#if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4) || defined (OPAMP5) || defined (OPAMP6) + /** @addtogroup OPAMP * @{ */ @@ -560,14 +562,14 @@ OPAMP_TrimmingValueTypeDef HAL_OPAMP_GetTrimOffset(OPAMP_HandleTypeDef *hopamp, * @} */ +#endif /* OPAMP1 || OPAMP2 || OPAMP3 || OPAMP4 || OPAMP5 || OPAMP6 */ + /** * @} */ - #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_OPAMP_H */ - diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp_ex.h index 4ec360118..72d48cf90 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_opamp_ex.h @@ -31,6 +31,8 @@ extern "C" { * @{ */ +#if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4) || defined (OPAMP5) || defined (OPAMP6) + /** @addtogroup OPAMPEx OPAMPEx * @{ */ @@ -71,15 +73,15 @@ HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPA * @} */ +#endif /* OPAMP1 || OPAMP2 || OPAMP3 || OPAMP4 || OPAMP5 || OPAMP6 */ + /** * @} */ - #ifdef __cplusplus } #endif #endif /* STM32G4xx_HAL_OPAMP_EX_H */ - diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd.h index 1aee8202d..52e06a94b 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd.h @@ -806,20 +806,17 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef const *hpcd); \ *(pdwReg) &= 0x3FFU; \ \ - if ((wCount) > 62U) \ + if ((wCount) == 0U) \ { \ - PCD_CALC_BLK32((pdwReg), (wCount), wNBlocks); \ + *(pdwReg) |= USB_CNTRX_BLSIZE; \ + } \ + else if ((wCount) <= 62U) \ + { \ + PCD_CALC_BLK2((pdwReg), (wCount), wNBlocks); \ } \ else \ { \ - if ((wCount) == 0U) \ - { \ - *(pdwReg) |= USB_CNTRX_BLSIZE; \ - } \ - else \ - { \ - PCD_CALC_BLK2((pdwReg), (wCount), wNBlocks); \ - } \ + PCD_CALC_BLK32((pdwReg), (wCount), wNBlocks); \ } \ } while(0) /* PCD_SET_EP_CNT_RX_REG */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd_ex.h index afb606d6f..3d85758a3 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_pcd_ex.h @@ -47,7 +47,6 @@ extern "C" { */ - HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, uint16_t ep_addr, uint16_t ep_kind, uint32_t pmaadress); diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_rcc_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_rcc_ex.h index 6cebf2779..10206ee17 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_rcc_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_rcc_ex.h @@ -53,9 +53,10 @@ typedef struct uint32_t Usart2ClockSelection; /*!< Specifies USART2 clock source. This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ - +#if defined(USART3) uint32_t Usart3ClockSelection; /*!< Specifies USART3 clock source. This parameter can be a value of @ref RCCEx_USART3_Clock_Source */ +#endif /* UART3 */ #if defined(UART4) uint32_t Uart4ClockSelection; /*!< Specifies UART4 clock source. @@ -353,6 +354,7 @@ typedef struct * @} */ +#if defined(SPI_I2S_SUPPORT) /** @defgroup RCCEx_I2S_Clock_Source I2S Clock Source * @{ */ @@ -363,6 +365,8 @@ typedef struct /** * @} */ +#endif /* SPI_I2S_SUPPORT */ + #if defined(FDCAN1) /** @defgroup RCCEx_FDCAN_Clock_Source FDCAN Clock Source * @{ @@ -827,6 +831,8 @@ typedef struct * * @retval None */ + +#if defined(SAI1) #define __HAL_RCC_SAI1_CONFIG(__SAI1_CLKSOURCE__)\ MODIFY_REG(RCC->CCIPR, RCC_CCIPR_SAI1SEL, (__SAI1_CLKSOURCE__)) @@ -839,7 +845,9 @@ typedef struct * */ #define __HAL_RCC_GET_SAI1_SOURCE() (READ_BIT(RCC->CCIPR, RCC_CCIPR_SAI1SEL)) +#endif /* SAI1 */ +#if defined(SPI_I2S_SUPPORT) /** * @brief Macro to configure the I2S clock source. * @param __I2S_CLKSOURCE__ defines the I2S clock source. This clock is derived @@ -864,6 +872,7 @@ typedef struct * */ #define __HAL_RCC_GET_I2S_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_I2S23SEL))) +#endif /* SPI_I2S_SUPPORT */ #if defined(FDCAN1) /** @@ -1404,7 +1413,6 @@ void HAL_RCCEx_CRS_ErrorCallback(uint32_t Error); (((__SELECTION__) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC)) #elif defined(STM32G431xx) || defined(STM32G441xx) - #define IS_RCC_PERIPHCLOCK(__SELECTION__) \ ((((__SELECTION__) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) || \ (((__SELECTION__) & RCC_PERIPHCLK_USART2) == RCC_PERIPHCLK_USART2) || \ @@ -1423,6 +1431,22 @@ void HAL_RCCEx_CRS_ErrorCallback(uint32_t Error); (((__SELECTION__) & RCC_PERIPHCLK_ADC12) == RCC_PERIPHCLK_ADC12) || \ (((__SELECTION__) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC)) +#elif defined(STM32G414xx) +#define IS_RCC_PERIPHCLOCK(__SELECTION__) \ + ((((__SELECTION__) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_USART2) == RCC_PERIPHCLK_USART2) || \ + (((__SELECTION__) & RCC_PERIPHCLK_UART4) == RCC_PERIPHCLK_UART4) || \ + (((__SELECTION__) & RCC_PERIPHCLK_UART5) == RCC_PERIPHCLK_UART5) || \ + (((__SELECTION__) & RCC_PERIPHCLK_LPUART1) == RCC_PERIPHCLK_LPUART1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_I2C2) == RCC_PERIPHCLK_I2C2) || \ + (((__SELECTION__) & RCC_PERIPHCLK_I2C3) == RCC_PERIPHCLK_I2C3) || \ + (((__SELECTION__) & RCC_PERIPHCLK_LPTIM1) == RCC_PERIPHCLK_LPTIM1) || \ + (((__SELECTION__) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) || \ + (((__SELECTION__) & RCC_PERIPHCLK_FDCAN) == RCC_PERIPHCLK_FDCAN) || \ + (((__SELECTION__) & RCC_PERIPHCLK_RNG) == RCC_PERIPHCLK_RNG) || \ + (((__SELECTION__) & RCC_PERIPHCLK_ADC12) == RCC_PERIPHCLK_ADC12) || \ + (((__SELECTION__) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC)) #elif defined(STM32GBK1CB) #define IS_RCC_PERIPHCLOCK(__SELECTION__) \ ((((__SELECTION__) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) || \ @@ -1514,11 +1538,13 @@ void HAL_RCCEx_CRS_ErrorCallback(uint32_t Error); ((__SOURCE__) == RCC_LPTIM1CLKSOURCE_HSI) || \ ((__SOURCE__) == RCC_LPTIM1CLKSOURCE_LSE)) +#if defined(SAI1) #define IS_RCC_SAI1CLKSOURCE(__SOURCE__) \ (((__SOURCE__) == RCC_SAI1CLKSOURCE_SYSCLK) || \ ((__SOURCE__) == RCC_SAI1CLKSOURCE_PLL) || \ ((__SOURCE__) == RCC_SAI1CLKSOURCE_EXT) || \ ((__SOURCE__) == RCC_SAI1CLKSOURCE_HSI)) +#endif /* SAI1 */ #define IS_RCC_I2SCLKSOURCE(__SOURCE__) \ (((__SOURCE__) == RCC_I2SCLKSOURCE_SYSCLK) || \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai.h index 771d4d623..d8311b2ad 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai.h @@ -31,6 +31,8 @@ extern "C" { * @{ */ +#if defined(SAI1) + /** @addtogroup SAI * @{ */ @@ -943,6 +945,8 @@ uint32_t HAL_SAI_GetError(const SAI_HandleTypeDef *hsai); * @} */ +#endif /* SAI1 */ + /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai_ex.h index 05771bea8..86a962563 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_sai_ex.h @@ -31,6 +31,8 @@ extern "C" { * @{ */ +#if defined(SAI1) + /** @addtogroup SAIEx * @{ */ @@ -92,6 +94,8 @@ HAL_StatusTypeDef HAL_SAIEx_ConfigPdmMicDelay(const SAI_HandleTypeDef *hsai, * @} */ +#endif /* SAI1 */ + /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smartcard.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smartcard.h index a2f700dd1..d765c0f4f 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smartcard.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smartcard.h @@ -859,6 +859,7 @@ typedef enum * @param __CLOCKSOURCE__ output variable. * @retval the SMARTCARD clocking source, written in __CLOCKSOURCE__. */ +#if defined(USART3) #define SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -929,6 +930,57 @@ typedef enum (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) +#else +#define SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#endif /* USART3 */ /** @brief Check the Baud rate range. * @note The maximum Baud Rate is derived from the maximum clock on G4 (150 MHz) diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smbus_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smbus_ex.h index 5043329ea..7ddf7706b 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smbus_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_smbus_ex.h @@ -51,7 +51,11 @@ extern "C" { #define SMBUS_FASTMODEPLUS_PB9 SYSCFG_CFGR1_I2C_PB9_FMP /*!< Enable Fast Mode Plus on PB9 */ #define SMBUS_FASTMODEPLUS_I2C1 SYSCFG_CFGR1_I2C1_FMP /*!< Enable Fast Mode Plus on I2C1 pins */ #define SMBUS_FASTMODEPLUS_I2C2 SYSCFG_CFGR1_I2C2_FMP /*!< Enable Fast Mode Plus on I2C2 pins */ +#if defined(SYSCFG_CFGR1_I2C3_FMP) #define SMBUS_FASTMODEPLUS_I2C3 SYSCFG_CFGR1_I2C3_FMP /*!< Enable Fast Mode Plus on I2C3 pins */ +#else +#define SMBUS_FASTMODEPLUS_I2C3 (uint32_t)(0x00000400U | SMBUS_FMP_NOT_SUPPORTED) /*!< Fast Mode Plus I2C3 not supported */ +#endif /* SYSCFG_CFGR1_I2C3_FMP */ #if defined(SYSCFG_CFGR1_I2C4_FMP) #define SMBUS_FASTMODEPLUS_I2C4 SYSCFG_CFGR1_I2C4_FMP /*!< Enable Fast Mode Plus on I2C4 pins */ #else diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart.h index bb06ee89f..2f308b333 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart.h @@ -1230,7 +1230,7 @@ typedef void (*pUART_RxEventCallbackTypeDef) /** @defgroup UART_Private_Macros UART Private Macros * @{ */ -/** @brief Get UART clok division factor from clock prescaler value. +/** @brief Get UART clock division factor from clock prescaler value. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval UART clock division factor */ @@ -1245,8 +1245,7 @@ typedef void (*pUART_RxEventCallbackTypeDef) ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV16) ? 16U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV32) ? 32U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV64) ? 64U : \ - ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : \ - ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV256) ? 256U : 1U) + ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : 256U) /** @brief BRR division operation to set BRR register with LPUART. * @param __PCLK__ LPUART clock. diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart_ex.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart_ex.h index 34c17155e..0c56e2790 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart_ex.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_uart_ex.h @@ -199,7 +199,7 @@ HAL_UART_RxEventTypeTypeDef HAL_UARTEx_GetRxEventType(const UART_HandleTypeDef * * @param __CLOCKSOURCE__ output variable. * @retval UART clocking source, written in __CLOCKSOURCE__. */ -#if defined(UART5) +#if defined(UART5) && defined(USART3) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -333,7 +333,120 @@ HAL_UART_RxEventTypeTypeDef HAL_UARTEx_GetRxEventType(const UART_HandleTypeDef * (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) -#elif defined(UART4) +#elif defined(UART5) && !defined(USART3) +#define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == UART4) \ + { \ + switch(__HAL_RCC_GET_UART4_SOURCE()) \ + { \ + case RCC_UART4CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_UART4CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_UART4CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_UART4CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == UART5) \ + { \ + switch(__HAL_RCC_GET_UART5_SOURCE()) \ + { \ + case RCC_UART5CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_UART5CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_UART5CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_UART5CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == LPUART1) \ + { \ + switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ + { \ + case RCC_LPUART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_LPUART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_LPUART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_LPUART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#elif defined(UART4) && defined(USART3) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -446,7 +559,99 @@ HAL_UART_RxEventTypeTypeDef HAL_UARTEx_GetRxEventType(const UART_HandleTypeDef * (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) -#else +#elif defined(UART4) && !defined(USART3) +#define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == UART4) \ + { \ + switch(__HAL_RCC_GET_UART4_SOURCE()) \ + { \ + case RCC_UART4CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_UART4CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_UART4CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_UART4CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == LPUART1) \ + { \ + switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ + { \ + case RCC_LPUART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_LPUART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_LPUART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_LPUART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#elif defined(USART3) #define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -538,7 +743,78 @@ HAL_UART_RxEventTypeTypeDef HAL_UARTEx_GetRxEventType(const UART_HandleTypeDef * (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0U) -#endif /* UART5 */ +#else +#define UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == LPUART1) \ + { \ + switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ + { \ + case RCC_LPUART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_LPUART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_LPUART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_LPUART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0U) +#endif /* UART5 && !USART3 */ /** @brief Report the UART mask to apply to retrieve the received data * according to the word length and to the parity bits activation. diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_usart.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_usart.h index 8e012b856..7c305b876 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_usart.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_hal_usart.h @@ -704,8 +704,7 @@ typedef void (*pUSART_CallbackTypeDef)(USART_HandleTypeDef *husart); /*!< poin ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV16) ? 16U : \ ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV32) ? 32U : \ ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV64) ? 64U : \ - ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV128) ? 128U : \ - ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV256) ? 256U : 1U) + ((__CLOCKPRESCALER__) == USART_PRESCALER_DIV128) ? 128U : 256U) /** @brief BRR division operation to set BRR register in 8-bit oversampling mode. * @param __PCLK__ USART clock. @@ -722,6 +721,7 @@ typedef void (*pUSART_CallbackTypeDef)(USART_HandleTypeDef *husart); /*!< poin * @param __CLOCKSOURCE__ output variable. * @retval the USART clocking source, written in __CLOCKSOURCE__. */ +#if defined(USART3) #define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ do { \ if((__HANDLE__)->Instance == USART1) \ @@ -792,6 +792,57 @@ typedef void (*pUSART_CallbackTypeDef)(USART_HandleTypeDef *husart); /*!< poin (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ } \ } while(0) +#else +#define USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#endif /* USART3 */ /** @brief Check USART Baud rate. * @param __BAUDRATE__ Baudrate specified by the user. diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_adc.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_adc.h index dc64ef1a4..5621f09d3 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_adc.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_adc.h @@ -2873,7 +2873,7 @@ Refer to device datasheet for ADC5 & OPAMP5 availability */ ) \ ) \ ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define __LL_ADC_IS_CHANNEL_INTERNAL_AVAILABLE(__ADC_INSTANCE__, __CHANNEL__) \ ((((__ADC_INSTANCE__) == ADC1) \ &&( \ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_bus.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_bus.h index a33634696..ffd3b7be6 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_bus.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_bus.h @@ -93,7 +93,7 @@ extern "C" { #define LL_AHB2_GRP1_PERIPH_GPIOE RCC_AHB2ENR_GPIOEEN #define LL_AHB2_GRP1_PERIPH_GPIOF RCC_AHB2ENR_GPIOFEN #define LL_AHB2_GRP1_PERIPH_GPIOG RCC_AHB2ENR_GPIOGEN -#define LL_AHB2_GRP1_PERIPH_CCM RCC_AHB2SMENR_CCMSMEN +#define LL_AHB2_GRP1_PERIPH_CCM RCC_AHB2SMENR_CCMSRAMSMEN #define LL_AHB2_GRP1_PERIPH_SRAM2 RCC_AHB2SMENR_SRAM2SMEN #define LL_AHB2_GRP1_PERIPH_ADC12 RCC_AHB2ENR_ADC12EN #if defined(ADC345_COMMON) diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_cordic.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_cordic.h index 8adb69beb..5abc53203 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_cordic.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_cordic.h @@ -131,12 +131,12 @@ extern "C" { /** @defgroup CORDIC_LL_EC_NBWRITE NBWRITE * @{ */ -#define LL_CORDIC_NBWRITE_1 (0x00000000U) /*!< One 32-bits write containing either only one - 32-bit data input (Q1.31 format), or two - 16-bit data input (Q1.15 format) packed - in one 32 bits Data */ -#define LL_CORDIC_NBWRITE_2 CORDIC_CSR_NARGS /*!< Two 32-bit write containing two 32-bits data input - (Q1.31 format) */ +#define LL_CORDIC_NBWRITE_1 (0x00000000U) /*!< One 32-bits write containing either only one + 32-bits data input (Q1.31 format), or two + 16-bits data input (Q1.15 format) packed + in one 32 bits Data */ +#define LL_CORDIC_NBWRITE_2 CORDIC_CSR_NARGS /*!< Two 32-bit write containing two 32-bits data input + (Q1.31 format) */ /** * @} */ @@ -144,12 +144,12 @@ extern "C" { /** @defgroup CORDIC_LL_EC_NBREAD NBREAD * @{ */ -#define LL_CORDIC_NBREAD_1 (0x00000000U) /*!< One 32-bits read containing either only one - 32-bit data output (Q1.31 format), or two - 16-bit data output (Q1.15 format) packed - in one 32 bits Data */ -#define LL_CORDIC_NBREAD_2 CORDIC_CSR_NRES /*!< Two 32-bit Data containing two 32-bits data output - (Q1.31 format) */ +#define LL_CORDIC_NBREAD_1 (0x00000000U) /*!< One 32-bits read containing either only one + 32-bits data output (Q1.31 format), or two + 16-bits data output (Q1.15 format) packed + in one 32 bits Data */ +#define LL_CORDIC_NBREAD_2 CORDIC_CSR_NRES /*!< Two 32-bit Data containing two 32-bits data output + (Q1.31 format) */ /** * @} */ @@ -218,9 +218,7 @@ extern "C" { * @} */ - /* Exported functions --------------------------------------------------------*/ - /** @defgroup CORDIC_LL_Exported_Functions CORDIC Exported Functions * @{ */ @@ -749,8 +747,6 @@ __STATIC_INLINE uint32_t LL_CORDIC_ReadData(const CORDIC_TypeDef *CORDICx) * @} */ - - #if defined(USE_FULL_LL_DRIVER) /** @defgroup CORDIC_LL_EF_Init Initialization and de-initialization functions * @{ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_fmac.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_fmac.h index 102cac0ff..63fac203e 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_fmac.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_fmac.h @@ -38,7 +38,6 @@ extern "C" { */ /* Exported types ------------------------------------------------------------*/ - /* Exported constants --------------------------------------------------------*/ /** @defgroup FMAC_LL_Exported_Constants FMAC Exported Constants * @{ @@ -147,9 +146,7 @@ extern "C" { * @} */ - /* Exported functions --------------------------------------------------------*/ - /** @defgroup FMAC_LL_Exported_Functions FMAC Exported Functions * @{ */ @@ -1033,8 +1030,6 @@ __STATIC_INLINE void LL_FMAC_ConfigFunc(FMAC_TypeDef *FMACx, uint8_t Start, uint * @} */ - - #if defined(USE_FULL_LL_DRIVER) /** @defgroup FMAC_LL_EF_Init Initialization and de-initialization functions * @{ @@ -1042,7 +1037,6 @@ __STATIC_INLINE void LL_FMAC_ConfigFunc(FMAC_TypeDef *FMACx, uint8_t Start, uint ErrorStatus LL_FMAC_Init(FMAC_TypeDef *FMACx); ErrorStatus LL_FMAC_DeInit(const FMAC_TypeDef *FMACx); - /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_lpuart.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_lpuart.h index e3f996ac1..0c9a89498 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_lpuart.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_lpuart.h @@ -2605,6 +2605,21 @@ __STATIC_INLINE void LL_LPUART_RequestRxDataFlush(USART_TypeDef *LPUARTx) SET_BIT(LPUARTx->RQR, (uint16_t)USART_RQR_RXFRQ); } +/** + * @brief Request a Transmit data FIFO flush + * @note TXFRQ bit is set to flush the whole FIFO when FIFO mode is enabled. This + * also sets the flag TXFE (TXFIFO empty bit in the LPUART_ISR register). + * @note Macro IS_UART_FIFO_INSTANCE(USARTx) can be used to check whether or not + * FIFO mode feature is supported by the USARTx instance. + * @rmtoll RQR TXFRQ LL_LPUART_RequestTxDataFlush + * @param LPUARTx LPUART Instance + * @retval None + */ +__STATIC_INLINE void LL_LPUART_RequestTxDataFlush(USART_TypeDef *LPUARTx) +{ + SET_BIT(LPUARTx->RQR, (uint16_t)USART_RQR_TXFRQ); +} + /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_pwr.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_pwr.h index e3c1bef8f..4a5a0c9c6 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_pwr.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_pwr.h @@ -783,6 +783,7 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnabledPUPDCfg(void) return ((temp == (PWR_CR3_APC))?1U:0U); } +#if defined(SRAM2_BASE) /** * @brief Enable SRAM2 content retention in Standby mode * @rmtoll CR3 RRS LL_PWR_EnableSRAM2Retention @@ -816,6 +817,7 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnabledSRAM2Retention(void) return ((temp == (PWR_CR3_RRS))?1U:0U); } +#endif /* SRAM2_BASE */ /** * @brief Enable the WakeUp PINx functionality * @rmtoll CR3 EWUP1 LL_PWR_EnableWakeUpPin\n diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rcc.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rcc.h index 9fef6c143..eb9d9f40e 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rcc.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rcc.h @@ -319,10 +319,12 @@ typedef struct #define LL_RCC_USART2_CLKSOURCE_SYSCLK ((RCC_CCIPR_USART2SEL << 16U) | RCC_CCIPR_USART2SEL_0) /*!< SYSCLK clock used as USART2 clock source */ #define LL_RCC_USART2_CLKSOURCE_HSI ((RCC_CCIPR_USART2SEL << 16U) | RCC_CCIPR_USART2SEL_1) /*!< HSI clock used as USART2 clock source */ #define LL_RCC_USART2_CLKSOURCE_LSE ((RCC_CCIPR_USART2SEL << 16U) | RCC_CCIPR_USART2SEL) /*!< LSE clock used as USART2 clock source */ +#if defined(RCC_CCIPR_USART3SEL) #define LL_RCC_USART3_CLKSOURCE_PCLK1 (RCC_CCIPR_USART3SEL << 16U) /*!< PCLK1 clock used as USART3 clock source */ #define LL_RCC_USART3_CLKSOURCE_SYSCLK ((RCC_CCIPR_USART3SEL << 16U) | RCC_CCIPR_USART3SEL_0) /*!< SYSCLK clock used as USART3 clock source */ #define LL_RCC_USART3_CLKSOURCE_HSI ((RCC_CCIPR_USART3SEL << 16U) | RCC_CCIPR_USART3SEL_1) /*!< HSI clock used as USART3 clock source */ #define LL_RCC_USART3_CLKSOURCE_LSE ((RCC_CCIPR_USART3SEL << 16U) | RCC_CCIPR_USART3SEL) /*!< LSE clock used as USART3 clock source */ +#endif /* RCC_CCIPR_USART3SEL */ /** * @} */ @@ -472,7 +474,9 @@ typedef struct */ #define LL_RCC_USART1_CLKSOURCE RCC_CCIPR_USART1SEL /*!< USART1 Clock source selection */ #define LL_RCC_USART2_CLKSOURCE RCC_CCIPR_USART2SEL /*!< USART2 Clock source selection */ +#if defined(RCC_CCIPR_USART3SEL) #define LL_RCC_USART3_CLKSOURCE RCC_CCIPR_USART3SEL /*!< USART3 Clock source selection */ +#endif /* RCC_CCIPR_USART3SEL */ /** * @} */ @@ -503,7 +507,9 @@ typedef struct */ #define LL_RCC_I2C1_CLKSOURCE (((uint32_t)RCC_OFFSET_CCIPR << 24U) | ((uint32_t)RCC_CCIPR_I2C1SEL_Pos << 16U) | (RCC_CCIPR_I2C1SEL >> RCC_CCIPR_I2C1SEL_Pos)) /*!< I2C1 Clock source selection */ #define LL_RCC_I2C2_CLKSOURCE (((uint32_t)RCC_OFFSET_CCIPR << 24U) | ((uint32_t)RCC_CCIPR_I2C2SEL_Pos << 16U) | (RCC_CCIPR_I2C2SEL >> RCC_CCIPR_I2C2SEL_Pos)) /*!< I2C2 Clock source selection */ +#if defined(RCC_CCIPR_I2C3SEL) #define LL_RCC_I2C3_CLKSOURCE (((uint32_t)RCC_OFFSET_CCIPR << 24U) | ((uint32_t)RCC_CCIPR_I2C3SEL_Pos << 16U) | (RCC_CCIPR_I2C3SEL >> RCC_CCIPR_I2C3SEL_Pos)) /*!< I2C3 Clock source selection */ +#endif /* RCC_CCIPR_I2C3SEL */ #if defined(RCC_CCIPR2_I2C4SEL) #define LL_RCC_I2C4_CLKSOURCE (((uint32_t)RCC_OFFSET_CCIPR2 << 24U) | ((uint32_t)RCC_CCIPR2_I2C4SEL_Pos << 16U) | (RCC_CCIPR2_I2C4SEL >> RCC_CCIPR2_I2C4SEL_Pos)) /*!< I2C4 Clock source selection */ #endif /* RCC_CCIPR2_I2C4SEL */ @@ -1602,6 +1608,7 @@ __STATIC_INLINE void LL_RCC_SetLPTIMClockSource(uint32_t LPTIMxSource) MODIFY_REG(RCC->CCIPR, RCC_CCIPR_LPTIM1SEL, LPTIMxSource); } +#if defined(SAI1) /** * @brief Configure SAIx clock source * @rmtoll CCIPR SAI1SEL LL_RCC_SetSAIClockSource @@ -1618,7 +1625,9 @@ __STATIC_INLINE void LL_RCC_SetSAIClockSource(uint32_t SAIxSource) { MODIFY_REG(RCC->CCIPR, RCC_CCIPR_SAI1SEL, SAIxSource); } +#endif /* SAI1 */ +#if defined(SPI_I2S_SUPPORT) /** * @brief Configure I2S clock source * @rmtoll CCIPR I2S23SEL LL_RCC_SetI2SClockSource @@ -1633,6 +1642,7 @@ __STATIC_INLINE void LL_RCC_SetI2SClockSource(uint32_t I2SxSource) { MODIFY_REG(RCC->CCIPR, RCC_CCIPR_I2S23SEL, I2SxSource); } +#endif /* SPI_I2S_SUPPORT */ #if defined(FDCAN1) /** diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rng.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rng.h index dce130661..90d95e545 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rng.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_rng.h @@ -369,7 +369,7 @@ __STATIC_INLINE uint32_t LL_RNG_ReadRandData32(const RNG_TypeDef *RNGx) /** @defgroup RNG_LL_EF_Init Initialization and de-initialization functions * @{ */ -ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, LL_RNG_InitTypeDef *RNG_InitStruct); +ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, const LL_RNG_InitTypeDef *RNG_InitStruct); void LL_RNG_StructInit(LL_RNG_InitTypeDef *RNG_InitStruct); ErrorStatus LL_RNG_DeInit(const RNG_TypeDef *RNGx); diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_system.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_system.h index 55abc5994..87b6f2f00 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_system.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_system.h @@ -187,6 +187,7 @@ extern "C" { /** @defgroup SYSTEM_LL_EC_CCMSRAMWRP SYSCFG CCMSRAM WRP * @{ */ +#if defined(CCMSRAM_BASE) #define LL_SYSCFG_CCMSRAMWRP_PAGE0 SYSCFG_SWPR_PAGE0 /*!< CCMSRAM Write protection page 0 */ #define LL_SYSCFG_CCMSRAMWRP_PAGE1 SYSCFG_SWPR_PAGE1 /*!< CCMSRAM Write protection page 1 */ #define LL_SYSCFG_CCMSRAMWRP_PAGE2 SYSCFG_SWPR_PAGE2 /*!< CCMSRAM Write protection page 2 */ @@ -197,6 +198,7 @@ extern "C" { #define LL_SYSCFG_CCMSRAMWRP_PAGE7 SYSCFG_SWPR_PAGE7 /*!< CCMSRAM Write protection page 7 */ #define LL_SYSCFG_CCMSRAMWRP_PAGE8 SYSCFG_SWPR_PAGE8 /*!< CCMSRAM Write protection page 8 */ #define LL_SYSCFG_CCMSRAMWRP_PAGE9 SYSCFG_SWPR_PAGE9 /*!< CCMSRAM Write protection page 9 */ +#endif /* CCMSRAM_BASE */ #if defined(SYSCFG_SWPR_PAGE10) #define LL_SYSCFG_CCMSRAMWRP_PAGE10 SYSCFG_SWPR_PAGE10 /*!< CCMSRAM Write protection page 10 */ #define LL_SYSCFG_CCMSRAMWRP_PAGE11 SYSCFG_SWPR_PAGE11 /*!< CCMSRAM Write protection page 11 */ @@ -261,7 +263,9 @@ extern "C" { #if defined(I2C2) #define LL_DBGMCU_APB1_GRP1_I2C2_STOP DBGMCU_APB1FZR1_DBG_I2C2_STOP /*!< The I2C2 SMBus timeout is frozen*/ #endif /* I2C2 */ +#if defined(I2C3) #define LL_DBGMCU_APB1_GRP1_I2C3_STOP DBGMCU_APB1FZR1_DBG_I2C3_STOP /*!< The I2C3 SMBus timeout is frozen*/ +#endif /* I2C3 */ #define LL_DBGMCU_APB1_GRP1_LPTIM1_STOP DBGMCU_APB1FZR1_DBG_LPTIM1_STOP /*!< The counter clock of LPTIM1 is stopped when the core is halted*/ /** * @} @@ -754,6 +758,7 @@ __STATIC_INLINE uint32_t LL_SYSCFG_GetEXTISource(uint32_t Line) return (uint32_t)(READ_BIT(SYSCFG->EXTICR[Line & 0x3U], (Line >> 16U)) >> (POSITION_VAL(Line >> 16U) & 0x1FU)); } +#if defined (CCMSRAM_BASE) /** * @brief Enable CCMSRAM Erase (starts a hardware CCMSRAM erase operation. This bit is * automatically cleared at the end of the CCMSRAM erase operation.) @@ -779,6 +784,7 @@ __STATIC_INLINE uint32_t LL_SYSCFG_IsCCMSRAMEraseOngoing(void) return ((READ_BIT(SYSCFG->SCSR, SYSCFG_SCSR_CCMBSY) == (SYSCFG_SCSR_CCMBSY)) ? 1UL : 0UL); } +#endif /* CCMSRAM_BASE */ /** * @brief Set connections to TIM1/8/15/16/17 Break inputs * @rmtoll SYSCFG_CFGR2 CLL LL_SYSCFG_SetTIMBreakInputs\n @@ -834,6 +840,7 @@ __STATIC_INLINE void LL_SYSCFG_ClearFlag_SP(void) SET_BIT(SYSCFG->CFGR2, SYSCFG_CFGR2_SPF); } +#if defined(CCMSRAM_BASE) /** * @brief Enable CCMSRAM page write protection * @note Write protection is cleared only by a system reset @@ -902,7 +909,7 @@ __STATIC_INLINE void LL_SYSCFG_UnlockCCMSRAMWRP(void) WRITE_REG(SYSCFG->SKR, 0xCA); WRITE_REG(SYSCFG->SKR, 0x53); } - +#endif /* CCMSRAM_BASE */ /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_ucpd.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_ucpd.h index 2cafeaa4c..0e90d7edc 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_ucpd.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_ucpd.h @@ -847,7 +847,7 @@ __STATIC_INLINE void LL_UCPD_EnableIT_RxOvr(UCPD_TypeDef *UCPDx) } /** - * @brief Enable Rx hard resrt interrupt + * @brief Enable Rx hard reset interrupt * @rmtoll IMR RXHRSTDETIE LL_UCPD_EnableIT_RxHRST * @param UCPDx UCPD Instance * @retval None @@ -1012,7 +1012,7 @@ __STATIC_INLINE void LL_UCPD_DisableIT_RxOvr(UCPD_TypeDef *UCPDx) } /** - * @brief Disable Rx hard resrt interrupt + * @brief Disable Rx hard reset interrupt * @rmtoll IMR RXHRSTDETIE LL_UCPD_DisableIT_RxHRST * @param UCPDx UCPD Instance * @retval None @@ -1177,7 +1177,7 @@ __STATIC_INLINE uint32_t LL_UCPD_IsEnableIT_RxOvr(UCPD_TypeDef const *const UCPD } /** - * @brief Check if Rx hard resrt interrupt enabled + * @brief Check if Rx hard reset interrupt enabled * @rmtoll IMR RXHRSTDETIE LL_UCPD_IsEnableIT_RxHRST * @param UCPDx UCPD Instance * @retval State of bit (1 or 0). @@ -1350,7 +1350,7 @@ __STATIC_INLINE void LL_UCPD_ClearFlag_RxOvr(UCPD_TypeDef *UCPDx) } /** - * @brief Clear Rx hard resrt interrupt + * @brief Clear Rx hard reset interrupt * @rmtoll ICR RXHRSTDETIE LL_UCPD_ClearFlag_RxHRST * @param UCPDx UCPD Instance * @retval None @@ -1501,7 +1501,7 @@ __STATIC_INLINE uint32_t LL_UCPD_IsActiveFlag_RxOvr(UCPD_TypeDef const *const UC } /** - * @brief Check if Rx hard resrt interrupt + * @brief Check if Rx hard reset interrupt * @rmtoll SR RXHRSTDET LL_UCPD_IsActiveFlag_RxHRST * @param UCPDx UCPD Instance * @retval None @@ -1833,7 +1833,7 @@ __STATIC_INLINE void LL_UCPD_SetRxOrdExt2(UCPD_TypeDef *UCPDx, uint32_t SOPExt) */ ErrorStatus LL_UCPD_DeInit(UCPD_TypeDef *UCPDx); -ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, LL_UCPD_InitTypeDef *UCPD_InitStruct); +ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, const LL_UCPD_InitTypeDef *UCPD_InitStruct); void LL_UCPD_StructInit(LL_UCPD_InitTypeDef *UCPD_InitStruct); /** diff --git a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_utils.h b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_utils.h index 60510db50..e8c955f10 100644 --- a/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_utils.h +++ b/stm32cube/stm32g4xx/drivers/include/stm32g4xx_ll_utils.h @@ -160,14 +160,13 @@ typedef struct */ #define LL_UTILS_PACKAGETYPE_LQFP64 0x00000000U /*!< LQFP64 package type */ #define LL_UTILS_PACKAGETYPE_WLCSP64 0x00000001U /*!< WLCSP64 package type */ -#if defined (STM32G431xx) || defined (STM32G441xx) || defined (STM32G471xx) || \ - defined (STM32G473xx) || defined (STM32G483xx) || defined (STM32G474xx) || \ - defined (STM32G484xx) +#if defined (STM32G431xx) || defined (STM32G414xx) || defined (STM32G441xx) || defined (STM32G471xx) || \ + defined (STM32G473xx) || defined (STM32G483xx) || defined (STM32G474xx) || defined (STM32G484xx) #define LL_UTILS_PACKAGETYPE_LQFP100_LQFP80 0x00000002U /*!< LQFP100 \ LQFP80 package type */ #define LL_UTILS_PACKAGETYPE_LQFP100 LL_UTILS_PACKAGETYPE_LQFP100_LQFP80 /*!< For backward compatibility */ #else #define LL_UTILS_PACKAGETYPE_LQFP100 0x00000002U /*!< LQFP100 package type */ -#endif /* STM32G431xx || STM32G441xx || STM32G471xx || STM32G473xx || STM32G483xx ||STM32G474xx || STM32G484xx */ +#endif /* STM32G431xx || STM32G414xx || STM32G441xx || STM32G471xx || STM32G473xx || STM32G483xx || STM32G474xx || STM32G484xx */ #define LL_UTILS_PACKAGETYPE_WLCSP81 0x00000005U /*!< WLCSP81 package type */ #define LL_UTILS_PACKAGETYPE_LQFP128_UFBGA121 0x00000007U /*!< LQFP128 \ UFBGA121 package type */ #define LL_UTILS_PACKAGETYPE_LQFP128 LL_UTILS_PACKAGETYPE_LQFP128_UFBGA121 /*!< For backward compatibility */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal.c index ebe1bdf5e..53d264a71 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal.c @@ -48,11 +48,11 @@ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** - * @brief STM32G4xx HAL Driver version number V1.2.3 + * @brief STM32G4xx HAL Driver version number V1.2.4 */ #define __STM32G4xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ #define __STM32G4xx_HAL_VERSION_SUB1 (0x02U) /*!< [23:16] sub1 version */ -#define __STM32G4xx_HAL_VERSION_SUB2 (0x03U) /*!< [15:8] sub2 version */ +#define __STM32G4xx_HAL_VERSION_SUB2 (0x04U) /*!< [15:8] sub2 version */ #define __STM32G4xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32G4xx_HAL_VERSION ((__STM32G4xx_HAL_VERSION_MAIN << 24U)\ |(__STM32G4xx_HAL_VERSION_SUB1 << 16U)\ @@ -594,7 +594,7 @@ void HAL_DBGMCU_DisableDBGStandbyMode(void) @endverbatim * @{ */ - +#if defined (CCMSRAM_BASE) /** * @brief Start a hardware CCMSRAM erase operation. * @note As long as CCMSRAM is not erased the CCMER bit will be set. @@ -609,6 +609,7 @@ void HAL_SYSCFG_CCMSRAMErase(void) /* Starts a hardware CCMSRAM erase operation*/ SET_BIT(SYSCFG->SCSR, SYSCFG_SCSR_CCMER); } +#endif /* CCMSRAM_BASE */ /** * @brief Enable the Internal FLASH Bank Swapping. @@ -767,7 +768,7 @@ void HAL_SYSCFG_DisableIOSwitchVDD(void) CLEAR_BIT(SYSCFG->CFGR1, SYSCFG_CFGR1_ANASWVDD); } - +#if defined(CCMSRAM_BASE) /** @brief CCMSRAM page write protection enable * @param Page: This parameter is a long 32bit value and can be a value of @ref SYSCFG_CCMSRAMWRP * @note write protection can only be disabled by a system reset @@ -779,7 +780,7 @@ void HAL_SYSCFG_CCMSRAM_WriteProtectionEnable(uint32_t Page) SET_BIT(SYSCFG->SWPR, (uint32_t)(Page)); } - +#endif /* CCMSRAM_BASE */ /** * @} diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_comp.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_comp.c index 1dc7f91da..796998dbe 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_comp.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_comp.c @@ -900,7 +900,7 @@ void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp) if (tmp_comp_exti_flag_set != 0UL) { - /* Clear COMP EXTI line pending bit */ + /* Clear COMP EXTI line pending bit */ #if defined(COMP7) if (tmp_comp_exti_flag_set == 2UL) { diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cordic.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cordic.c index b5cb44a7e..efb7a1cde 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cordic.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cordic.c @@ -164,12 +164,12 @@ static void CORDIC_ReadOutDataIncrementPtr(const CORDIC_HandleTypeDef *hcordic, static void CORDIC_DMAInCplt(DMA_HandleTypeDef *hdma); static void CORDIC_DMAOutCplt(DMA_HandleTypeDef *hdma); static void CORDIC_DMAError(DMA_HandleTypeDef *hdma); + /** * @} */ /* Exported functions --------------------------------------------------------*/ - /** @defgroup CORDIC_Exported_Functions CORDIC Exported Functions * @{ */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cortex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cortex.c index e83b9609d..d5896ee14 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cortex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cortex.c @@ -451,6 +451,37 @@ void HAL_MPU_Disable(void) MPU->CTRL = 0; } +/** + * @brief Enable the MPU Region. + * @retval None + */ +void HAL_MPU_EnableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Enable the Region */ + SET_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} + +/** + * @brief Disable the MPU Region. + * @retval None + */ +void HAL_MPU_DisableRegion(uint32_t RegionNumber) +{ + /* Check the parameters */ + assert_param(IS_MPU_REGION_NUMBER(RegionNumber)); + + /* Set the Region number */ + MPU->RNR = RegionNumber; + + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); +} /** * @brief Initialize and configure the Region and the memory to be protected. @@ -463,38 +494,31 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); - + assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); + assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); + assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); + assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); + assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); + assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); + assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); + assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; - if ((MPU_Init->Enable) != 0U) - { - /* Check the parameters */ - assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); - assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); - assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); - assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); - assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); - assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); - assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); - assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); - - MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | - ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | - ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | - ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | - ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | - ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | - ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | - ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | - ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); - } - else - { - MPU->RBAR = 0x00; - MPU->RASR = 0x00; - } + /* Disable the Region */ + CLEAR_BIT(MPU->RASR, MPU_RASR_ENABLE_Msk); + + /* Apply configuration */ + MPU->RBAR = MPU_Init->BaseAddress; + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | + ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | + ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | + ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | + ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | + ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | + ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } #endif /* __MPU_PRESENT */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cryp.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cryp.c index 19bbe46e9..233151128 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cryp.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_cryp.c @@ -928,8 +928,6 @@ void HAL_CRYP_ProcessSuspend(CRYP_HandleTypeDef *hcryp) hcryp->SuspendRequest = HAL_CRYP_SUSPEND; } - - /** * @brief CRYP processing suspension and peripheral internal parameters storage. * @param hcryp pointer to a CRYP_HandleTypeDef structure that contains @@ -1874,23 +1872,23 @@ void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp) uint32_t itflag = hcryp->Instance->SR; /* Check if error occurred */ - if ((itsource & CRYP_IT_ERRIE) != RESET) + if ((itsource & CRYP_IT_ERRIE) == CRYP_IT_ERRIE) { /* If write Error occurred */ - if ((itflag & CRYP_IT_WRERR) != RESET) + if ((itflag & CRYP_IT_WRERR) == CRYP_IT_WRERR) { hcryp->ErrorCode |= HAL_CRYP_ERROR_WRITE; } /* If read Error occurred */ - if ((itflag & CRYP_IT_RDERR) != RESET) + if ((itflag & CRYP_IT_RDERR) == CRYP_IT_RDERR) { hcryp->ErrorCode |= HAL_CRYP_ERROR_READ; } } - if ((itflag & CRYP_IT_CCF) != RESET) + if ((itflag & CRYP_IT_CCF) == CRYP_IT_CCF) { - if ((itsource & CRYP_IT_CCFIE) != RESET) + if ((itsource & CRYP_IT_CCFIE) == CRYP_IT_CCFIE) { /* Clear computation complete flag */ __HAL_CRYP_CLEAR_FLAG(hcryp, CRYP_CCF_CLEAR); diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dac_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dac_ex.c index e6627be90..e1d1e39a0 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dac_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dac_ex.c @@ -914,8 +914,8 @@ HAL_StatusTypeDef HAL_DACEx_SelfCalibrate(DAC_HandleTypeDef *hdac, DAC_ChannelCo /* Init trimming counter */ /* Medium value */ - trimmingvalue = 16UL; - delta = 8UL; + trimmingvalue = 0x10UL; + delta = 0x08UL; while (delta != 0UL) { /* Set candidate trimming */ @@ -961,8 +961,12 @@ HAL_StatusTypeDef HAL_DACEx_SelfCalibrate(DAC_HandleTypeDef *hdac, DAC_ChannelCo if ((hdac->Instance->SR & (DAC_SR_CAL_FLAG1 << (Channel & 0x10UL))) == 0UL) { - /* Trimming is actually one value more */ - trimmingvalue++; + /* Check trimming value below maximum */ + if (trimmingvalue < 0x1FU) + { + /* Trimming is actually one value more */ + trimmingvalue++; + } /* Set right trimming */ MODIFY_REG(hdac->Instance->CCR, (DAC_CCR_OTRIM1 << (Channel & 0x10UL)), (trimmingvalue << (Channel & 0x10UL))); } @@ -1041,8 +1045,7 @@ HAL_StatusTypeDef HAL_DACEx_SetUserTrimming(DAC_HandleTypeDef *hdac, DAC_Channel * * (1) On this STM32 series, parameter not available on all instances. * Refer to device datasheet for channels availability. - * @retval Trimming value : range: 0->31 - * + * @retval TrimmingValue Value between Min_Data=0x00 and Max_Data=0x1F */ uint32_t HAL_DACEx_GetTrimOffset(const DAC_HandleTypeDef *hdac, uint32_t Channel) { diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dma.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dma.c index 89abfc622..cc505efc6 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dma.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_dma.c @@ -1057,7 +1057,7 @@ static void DMA_CalcDMAMUXChannelBaseAndMask(DMA_HandleTypeDef *hdma) else { /* DMA2 */ -#if defined (STM32G471xx) || defined (STM32G473xx) || defined (STM32G474xx) || defined (STM32G483xx) || defined (STM32G484xx) || defined (STM32G491xx) || defined (STM32G4A1xx) +#if defined (STM32G471xx) || defined (STM32G473xx) || defined (STM32G474xx) || defined (STM32G414xx) || defined (STM32G483xx) || defined (STM32G484xx) || defined (STM32G491xx) || defined (STM32G4A1xx) DMAMUX1_ChannelBase = DMAMUX1_Channel8; #elif defined (STM32G431xx) || defined (STM32G441xx) || defined (STM32GBK1CB) DMAMUX1_ChannelBase = DMAMUX1_Channel6; diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_flash_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_flash_ex.c index 073eb3187..6e65fbef3 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_flash_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_flash_ex.c @@ -920,7 +920,7 @@ static HAL_StatusTypeDef FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserCon optr_reg_val |= (UserConfig & FLASH_OPTR_SRAM_PE); optr_reg_mask |= FLASH_OPTR_SRAM_PE; } - +#if defined(CCMSRAM_BASE) if ((UserType & OB_USER_CCMSRAM_RST) != 0U) { /* CCMSRAM_RST option byte should be modified */ @@ -930,7 +930,7 @@ static HAL_StatusTypeDef FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserCon optr_reg_val |= (UserConfig & FLASH_OPTR_CCMSRAM_RST); optr_reg_mask |= FLASH_OPTR_CCMSRAM_RST; } - +#endif /* CCMSRAM_BASE */ if ((UserType & OB_USER_nSWBOOT0) != 0U) { /* nSWBOOT0 option byte should be modified */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_fmac.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_fmac.c index db8f2617c..82207191f 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_fmac.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_fmac.c @@ -204,7 +204,6 @@ not defined, the callback registration feature is not available and weak callbacks are used. - @endverbatim * */ @@ -229,7 +228,6 @@ /** @defgroup FMAC_Private_Constants FMAC Private Constants * @{ */ - #define MAX_FILTER_DATA_SIZE_TO_HANDLE ((uint16_t) 0xFFU) #define MAX_PRELOAD_INDEX 0xFFU #define PRELOAD_ACCESS_DMA 0x00U @@ -322,7 +320,6 @@ /* Private variables ---------------------------------------------------------*/ /* Global variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ - static HAL_StatusTypeDef FMAC_Reset(FMAC_HandleTypeDef *hfmac); static void FMAC_ResetDataPointers(FMAC_HandleTypeDef *hfmac); static void FMAC_ResetOutputStateAndDataPointers(FMAC_HandleTypeDef *hfmac); @@ -348,7 +345,6 @@ static void FMAC_DMAFilterPreload(DMA_HandleTypeDef *hdma); static void FMAC_DMAError(DMA_HandleTypeDef *hdma); /* Functions Definition ------------------------------------------------------*/ - /** @defgroup FMAC_Exported_Functions FMAC Exported Functions * @{ */ @@ -2410,7 +2406,6 @@ static void FMAC_DMAFilterConfig(DMA_HandleTypeDef *hdma) #else HAL_FMAC_ErrorCallback(hfmac); #endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */ - } /** @@ -2516,11 +2511,11 @@ static void FMAC_DMAError(DMA_HandleTypeDef *hdma) HAL_FMAC_ErrorCallback(hfmac); #endif /* USE_HAL_FMAC_REGISTER_CALLBACKS */ } + /** * @} */ - /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_gpio.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_gpio.c index a802626cf..cd8876a04 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_gpio.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_gpio.c @@ -449,7 +449,7 @@ void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) * until the next reset. * @param GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family * @param GPIO_Pin specifies the port bits to be locked. - * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15). * @retval None */ HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_i2c.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_i2c.c index 59da55da7..787f4acb8 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_i2c.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_i2c.c @@ -90,7 +90,7 @@ add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. @@ -156,7 +156,7 @@ HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA() (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() @@ -214,7 +214,7 @@ add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. @@ -1407,14 +1407,6 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData /* Enable Address Acknowledge */ hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - /* Preload TX data if no stretch enable */ if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) { @@ -1428,6 +1420,18 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData hi2c->XferCount--; } + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + return HAL_ERROR; + } + /* Clear ADDR flag */ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); @@ -1439,6 +1443,10 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData { /* Disable Address Acknowledge */ hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + return HAL_ERROR; } @@ -1451,6 +1459,10 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData { /* Disable Address Acknowledge */ hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + return HAL_ERROR; } @@ -4552,7 +4564,7 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) } /** - * @brief Abort a master I2C IT or DMA process communication with Interrupt. + * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress Target device address: The device 7 bits address value @@ -4561,7 +4573,9 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) */ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) { - if (hi2c->Mode == HAL_I2C_MODE_MASTER) + HAL_I2C_ModeTypeDef tmp_mode = hi2c->Mode; + + if ((tmp_mode == HAL_I2C_MODE_MASTER) || (tmp_mode == HAL_I2C_MODE_MEM)) { /* Process Locked */ __HAL_LOCK(hi2c); diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp.c index a0cd1bae2..36fa2bf1e 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp.c @@ -231,7 +231,7 @@ /** @addtogroup STM32G4xx_HAL_Driver * @{ */ - +#if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4) || defined (OPAMP5) || defined (OPAMP6) #ifdef HAL_OPAMP_MODULE_ENABLED /** @defgroup OPAMP OPAMP @@ -1194,9 +1194,8 @@ HAL_StatusTypeDef HAL_OPAMP_UnRegisterCallback(OPAMP_HandleTypeDef *hopamp, HAL_ */ #endif /* HAL_OPAMP_MODULE_ENABLED */ +#endif /* OPAMP1 || OPAMP2 || OPAMP3 || OPAMP4 || OPAMP5 || OPAMP6 */ + /** * @} */ - - - diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp_ex.c index aff46af09..d4bfb2f46 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_opamp_ex.c @@ -30,6 +30,7 @@ * @{ */ +#if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4) || defined (OPAMP5) || defined (OPAMP6) #ifdef HAL_OPAMP_MODULE_ENABLED /** @defgroup OPAMPEx OPAMPEx @@ -740,6 +741,7 @@ HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPA */ #endif /* HAL_OPAMP_MODULE_ENABLED */ +#endif /* OPAMP1 || OPAMP2 || OPAMP3 || OPAMP4 || OPAMP5 || OPAMP6 */ /** * @} diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd.c index 8e93289f8..606551cec 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd.c @@ -1389,7 +1389,7 @@ HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address) 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; + HAL_StatusTypeDef ret = HAL_OK; PCD_EPTypeDef *ep; if ((ep_addr & 0x80U) == 0x80U) @@ -1404,7 +1404,7 @@ HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, } ep->num = ep_addr & EP_ADDR_MSK; - ep->maxpacket = ep_mps; + ep->maxpacket = (uint32_t)ep_mps & 0x7FFU; ep->type = ep_type; /* Set initial data PID. */ @@ -2227,13 +2227,11 @@ static HAL_StatusTypeDef HAL_PCD_EP_DB_Transmit(PCD_HandleTypeDef *hpcd, #endif /* (USE_USB_DOUBLE_BUFFER == 1U) */ - /** * @} */ #endif /* defined (USB) */ #endif /* HAL_PCD_MODULE_ENABLED */ - /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd_ex.c index cb53de693..96064ae4c 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pcd_ex.c @@ -242,7 +242,6 @@ void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd) } } - /** * @brief Activate LPM feature. * @param hpcd PCD handle @@ -279,7 +278,6 @@ HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd) } - /** * @brief Send LPM message to user layer callback. * @param hpcd PCD handle diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pwr_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pwr_ex.c index 5ec00b2e9..aad092537 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pwr_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_pwr_ex.c @@ -39,13 +39,13 @@ /* Private define ------------------------------------------------------------*/ -#if defined (STM32G471xx) || defined (STM32G473xx) || defined (STM32G474xx) || defined (STM32G483xx) || defined (STM32G484xx) +#if defined (STM32G471xx) || defined (STM32G473xx) || defined (STM32G414xx) || defined (STM32G474xx) || defined (STM32G483xx) || defined (STM32G484xx) #define PWR_PORTF_AVAILABLE_PINS 0x0000FFFFU /* PF0..PF15 */ #define PWR_PORTG_AVAILABLE_PINS 0x000007FFU /* PG0..PG10 */ #elif defined (STM32G431xx) || defined (STM32G441xx) || defined (STM32GBK1CB) || defined (STM32G491xx) || defined (STM32G4A1xx) #define PWR_PORTF_AVAILABLE_PINS 0x00000607U /* PF0..PF2 and PF9 and PF10 */ #define PWR_PORTG_AVAILABLE_PINS 0x00000400U /* PG10 */ -#endif +#endif /* STM32G471xx || STM32G473xx || STM32G414xx || STM32G474xx || STM32G483xx || STM32G484xx */ /** @defgroup PWR_Extended_Private_Defines PWR Extended Private Defines * @{ @@ -550,7 +550,7 @@ void HAL_PWREx_DisablePullUpPullDownConfig(void) } - +#if defined (SRAM2_BASE) /** * @brief Enable SRAM2 content retention in Standby mode. * @note When RRS bit is set, SRAM2 is powered by the low-power regulator in @@ -573,7 +573,7 @@ void HAL_PWREx_DisableSRAM2ContentRetention(void) { CLEAR_BIT(PWR->CR3, PWR_CR3_RRS); } - +#endif /* SRAM2_BASE */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_qspi.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_qspi.c index de89b25e2..a67c79e71 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_qspi.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_qspi.c @@ -2680,6 +2680,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->AlternateBytesSize | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | cmd->Instruction | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } else @@ -2707,6 +2710,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | cmd->Instruction | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } } @@ -2741,6 +2747,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) | cmd->AlternateBytesSize | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } else @@ -2770,6 +2779,9 @@ static void QSPI_Config(QSPI_HandleTypeDef *hqspi, QSPI_CommandTypeDef *cmd, uin cmd->DataMode | (cmd->DummyCycles << QUADSPI_CCR_DCYC_Pos) | cmd->AlternateByteMode | cmd->AddressMode | cmd->InstructionMode | FunctionalMode)); + + /* Clear AR register */ + CLEAR_REG(hqspi->Instance->AR); } } } diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_rcc_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_rcc_ex.c index 31c96550d..f08f8aa26 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_rcc_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_rcc_ex.c @@ -237,6 +237,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_USART2_CONFIG(PeriphClkInit->Usart2ClockSelection); } +#if defined(USART3) + /*-------------------------- USART3 clock source configuration -------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART3) == RCC_PERIPHCLK_USART3) { @@ -247,6 +249,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_USART3_CONFIG(PeriphClkInit->Usart3ClockSelection); } +#endif /* USART3 */ + #if defined(UART4) /*-------------------------- UART4 clock source configuration --------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_UART4) == RCC_PERIPHCLK_UART4) @@ -302,6 +306,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Configure the I2C2 clock source */ __HAL_RCC_I2C2_CONFIG(PeriphClkInit->I2c2ClockSelection); } +#if defined(I2C3) /*-------------------------- I2C3 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C3) == RCC_PERIPHCLK_I2C3) @@ -313,6 +318,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_I2C3_CONFIG(PeriphClkInit->I2c3ClockSelection); } +#endif /* I2C3 */ #if defined(I2C4) /*-------------------------- I2C4 clock source configuration ---------------------*/ @@ -337,6 +343,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_LPTIM1_CONFIG(PeriphClkInit->Lptim1ClockSelection); } +#if defined(SAI1) /*-------------------------- SAI1 clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_SAI1) == RCC_PERIPHCLK_SAI1) { @@ -353,6 +360,9 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } } +#endif /* SAI1 */ + +#if defined(SPI_I2S_SUPPORT) /*-------------------------- I2S clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S) == RCC_PERIPHCLK_I2S) { @@ -369,6 +379,8 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } } +#endif /* SPI_I2S_SUPPORT */ + #if defined(FDCAN1) /*-------------------------- FDCAN clock source configuration ---------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_FDCAN) == RCC_PERIPHCLK_FDCAN) @@ -496,6 +508,13 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | RCC_PERIPHCLK_ADC345 | \ RCC_PERIPHCLK_QSPI | \ RCC_PERIPHCLK_RTC; + +#elif defined(STM32G414xx) + + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_UART4 | RCC_PERIPHCLK_UART5 | \ + RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_I2S | RCC_PERIPHCLK_FDCAN | RCC_PERIPHCLK_RNG | \ + RCC_PERIPHCLK_ADC12 | RCC_PERIPHCLK_RTC; + #elif defined(STM32G491xx) || defined(STM32G4A1xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ @@ -526,6 +545,7 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) RCC_PERIPHCLK_LPTIM1 | RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2S | \ RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | \ RCC_PERIPHCLK_RTC; + #elif defined(STM32G431xx) || defined(STM32G441xx) PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_USART3 | RCC_PERIPHCLK_UART4 | \ @@ -541,15 +561,18 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC12 | \ RCC_PERIPHCLK_RTC; -#endif /* STM32G431xx */ +#endif /* STM32G474xx || STM32G484xx */ /* Get the USART1 clock source ---------------------------------------------*/ PeriphClkInit->Usart1ClockSelection = __HAL_RCC_GET_USART1_SOURCE(); /* Get the USART2 clock source ---------------------------------------------*/ PeriphClkInit->Usart2ClockSelection = __HAL_RCC_GET_USART2_SOURCE(); + +#if defined(USART3) /* Get the USART3 clock source ---------------------------------------------*/ PeriphClkInit->Usart3ClockSelection = __HAL_RCC_GET_USART3_SOURCE(); +#endif /* USART3 */ #if defined(UART4) /* Get the UART4 clock source ----------------------------------------------*/ @@ -570,8 +593,10 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) /* Get the I2C2 clock source ----------------------------------------------*/ PeriphClkInit->I2c2ClockSelection = __HAL_RCC_GET_I2C2_SOURCE(); +#if defined(I2C3) /* Get the I2C3 clock source -----------------------------------------------*/ PeriphClkInit->I2c3ClockSelection = __HAL_RCC_GET_I2C3_SOURCE(); +#endif /* I2C3 */ #if defined(I2C4) /* Get the I2C4 clock source -----------------------------------------------*/ @@ -581,11 +606,15 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) /* Get the LPTIM1 clock source ---------------------------------------------*/ PeriphClkInit->Lptim1ClockSelection = __HAL_RCC_GET_LPTIM1_SOURCE(); +#if defined(SAI1) /* Get the SAI1 clock source -----------------------------------------------*/ PeriphClkInit->Sai1ClockSelection = __HAL_RCC_GET_SAI1_SOURCE(); +#endif /* SAI1 */ +#if defined(SPI_I2S_SUPPORT) /* Get the I2S clock source -----------------------------------------------*/ PeriphClkInit->I2sClockSelection = __HAL_RCC_GET_I2S_SOURCE(); +#endif /* SPI_I2S_SUPPORT */ #if defined(FDCAN1) /* Get the FDCAN clock source -----------------------------------------------*/ @@ -772,6 +801,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; +#if defined(USART3) case RCC_PERIPHCLK_USART3: /* Get the current USART3 source */ srcclk = __HAL_RCC_GET_USART3_SOURCE(); @@ -798,6 +828,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* nothing to do: frequency already initialized to 0 */ } break; +#endif /* USART3 */ #if defined(UART4) case RCC_PERIPHCLK_UART4: @@ -930,6 +961,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; +#if defined(I2C3) + case RCC_PERIPHCLK_I2C3: /* Get the current I2C3 source */ srcclk = __HAL_RCC_GET_I2C3_SOURCE(); @@ -953,6 +986,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; +#endif /* I2C3 */ + #if defined(I2C4) case RCC_PERIPHCLK_I2C4: @@ -1007,6 +1042,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; +#if defined(SAI1) + case RCC_PERIPHCLK_SAI1: /* Get the current SAI1 source */ srcclk = __HAL_RCC_GET_SAI1_SOURCE(); @@ -1040,6 +1077,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } break; +#endif /* SAI1 */ + +#if defined(SPI_I2S_SUPPORT) case RCC_PERIPHCLK_I2S: /* Get the current I2Sx source */ srcclk = __HAL_RCC_GET_I2S_SOURCE(); @@ -1072,6 +1112,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* nothing to do: frequency already initialized to 0 */ } break; +#endif /* SPI_I2S_SUPPORT */ #if defined(FDCAN1) case RCC_PERIPHCLK_FDCAN: diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai.c index befbd56e1..96e06fee8 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai.c @@ -217,13 +217,14 @@ * @{ */ +#if defined(SAI1) +#ifdef HAL_SAI_MODULE_ENABLED + /** @defgroup SAI SAI * @brief SAI HAL module driver * @{ */ -#ifdef HAL_SAI_MODULE_ENABLED - /* Private typedef -----------------------------------------------------------*/ /** @defgroup SAI_Private_Typedefs SAI Private Typedefs * @{ @@ -2731,12 +2732,13 @@ static void SAI_DMAAbort(DMA_HandleTypeDef *hdma) * @} */ -#endif /* HAL_SAI_MODULE_ENABLED */ /** * @} */ +#endif /* HAL_SAI_MODULE_ENABLED */ +#endif /* SAI1 */ + /** * @} */ - diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai_ex.c index 78e90b682..20bdb0608 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_sai_ex.c @@ -26,6 +26,8 @@ /** @addtogroup STM32G4xx_HAL_Driver * @{ */ + +#if defined(SAI1) #ifdef HAL_SAI_MODULE_ENABLED /** @defgroup SAIEx SAIEx @@ -124,7 +126,8 @@ HAL_StatusTypeDef HAL_SAIEx_ConfigPdmMicDelay(const SAI_HandleTypeDef *hsai, */ #endif /* HAL_SAI_MODULE_ENABLED */ +#endif /* SAI1 */ + /** * @} */ - diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smartcard.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smartcard.c index 53aa44248..a3a83b1ad 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smartcard.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smartcard.c @@ -2406,7 +2406,7 @@ static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); tmpreg |= (uint32_t) hsmartcard->Init.TimeOutValue; } - MODIFY_REG(hsmartcard->Instance->RTOR, (USART_RTOR_RTO | USART_RTOR_BLEN), tmpreg); + WRITE_REG(hsmartcard->Instance->RTOR, tmpreg); /*-------------------------- USART BRR Configuration -----------------------*/ SMARTCARD_GETCLOCKSOURCE(hsmartcard, clocksource); diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smbus_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smbus_ex.c index b4404ab9c..b431d8ffa 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smbus_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_smbus_ex.c @@ -6,6 +6,8 @@ * This file provides firmware functions to manage the following * functionalities of SMBUS Extended peripheral: * + Extended features functions + * + WakeUp Mode Functions + * + FastModePlus Functions * ****************************************************************************** * @attention diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart.c index 2ca90c811..ba9df1e60 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart.c @@ -2425,6 +2425,28 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) HAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); #endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ } + else + { + /* If DMA is in Circular mode, Idle event is to be reported to user + even if occurring after a Transfer Complete event from DMA */ + if (nb_remaining_rx_data == huart->RxXferSize) + { + if (HAL_IS_BIT_SET(huart->hdmarx->Instance->CCR, DMA_CCR_CIRC)) + { + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Idle Event */ + huart->RxEventType = HAL_UART_RXEVENT_IDLE; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + } + } return; } else @@ -4466,6 +4488,7 @@ static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } + break; } } @@ -4630,6 +4653,7 @@ static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } + break; } } diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart_ex.c index 30fd99060..cdb0c9593 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_uart_ex.c @@ -576,7 +576,7 @@ HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart) /* Disable UART */ __HAL_UART_DISABLE(huart); - /* Enable FIFO mode */ + /* Disable FIFO mode */ CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); huart->FifoMode = UART_FIFOMODE_DISABLE; diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart.c index 96617bc65..a56ec7cfb 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart.c @@ -144,7 +144,7 @@ */ /** @defgroup USART USART - * @brief HAL USART Synchronous module driver + * @brief HAL USART Synchronous SPI module driver * @{ */ @@ -225,8 +225,8 @@ static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); =============================================================================== [..] 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: + in synchronous SPI master/slave mode. + (+) For the synchronous SPI mode only these parameters can be configured: (++) Baud Rate (++) Word Length (++) Stop Bit @@ -238,7 +238,7 @@ static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); (++) Receiver/transmitter modes [..] - The HAL_USART_Init() function follows the USART synchronous configuration + The HAL_USART_Init() function follows the USART synchronous SPI configuration procedure (details for the procedure are available in reference manual). @endverbatim @@ -316,7 +316,7 @@ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) return HAL_ERROR; } - /* In Synchronous mode, the following bits must be kept cleared: + /* In Synchronous SPI 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. */ @@ -657,11 +657,10 @@ HAL_StatusTypeDef HAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, HAL_ =============================================================================== ##### IO operation functions ##### =============================================================================== - [..] This subsection provides a set of functions allowing to manage the USART synchronous + [..] This subsection provides a set of functions allowing to manage the USART synchronous SPI data transfers. - [..] The USART supports master mode only: it cannot receive or send data related to an input - clock (SCLK is always an output). + [..] The USART Synchronous SPI supports master and slave modes (SCLK as output or input). [..] @@ -2908,7 +2907,7 @@ static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart) /* Clear and configure the USART Clock, CPOL, CPHA, LBCL STOP and SLVEN bits: * 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 (used in SPI master mode only) + * set LBCL bit according to husart->Init.CLKLastBit value (used in USART Synchronous SPI master mode only) * set STOP[13:12] bits according to husart->Init.StopBits value */ tmpreg = (uint32_t)(USART_CLOCK_ENABLE); tmpreg |= (uint32_t)husart->Init.CLKLastBit; diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart_ex.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart_ex.c index 2c0dabdea..dce468649 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart_ex.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_hal_usart_ex.c @@ -364,7 +364,7 @@ HAL_StatusTypeDef HAL_USARTEx_DisableFifoMode(USART_HandleTypeDef *husart) /* Disable USART */ __HAL_USART_DISABLE(husart); - /* Enable FIFO mode */ + /* Disable FIFO mode */ CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); husart->FifoMode = USART_FIFOMODE_DISABLE; diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_adc.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_adc.c index d49741c83..907fbb3d1 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_adc.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_adc.c @@ -250,7 +250,7 @@ ) \ ) \ ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \ (((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \ @@ -490,7 +490,7 @@ ) \ ) \ ) -#elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) +#elif defined(STM32G414xx) || defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) #define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \ (((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_comp.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_comp.c index 103e753ee..3c840a080 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_comp.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_comp.c @@ -52,47 +52,47 @@ /* Note: On this STM32 series, comparator input plus parameters are */ /* the same on all COMP instances. */ /* However, comparator instance kept as macro parameter for */ -/* compatibility with other STM32 families. */ +/* compatibility with other STM32 series. */ #define IS_LL_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) \ (((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO1) \ || ((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO2) \ ) -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO2) || \ - (((__COMP_INSTANCE__) == COMP1) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) || \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) || \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO1) || \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO2) || \ + (((__COMP_INSTANCE__) == COMP1) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ - ) || \ - (((__COMP_INSTANCE__) == COMP2) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ + ) || \ + (((__COMP_INSTANCE__) == COMP2) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ - ) || \ - (((__COMP_INSTANCE__) == COMP3) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ + ) || \ + (((__COMP_INSTANCE__) == COMP3) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ - ) || \ - (((__COMP_INSTANCE__) == COMP4) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ + ) || \ + (((__COMP_INSTANCE__) == COMP4) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ - ) || \ - (((__COMP_INSTANCE__) == COMP5) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ + ) || \ + (((__COMP_INSTANCE__) == COMP5) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH1)) \ - ) || \ - (((__COMP_INSTANCE__) == COMP6) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH1)) \ + ) || \ + (((__COMP_INSTANCE__) == COMP6) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC2_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH2)) \ - ) || \ - (((__COMP_INSTANCE__) == COMP7) && \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH2)) \ + ) || \ + (((__COMP_INSTANCE__) == COMP7) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC2_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH1)) \ - )) + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC4_CH1)) \ + )) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) || defined(STM32G491xx) || defined(STM32G4A1xx) #define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) || \ @@ -103,19 +103,19 @@ ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_IO2) || \ (((__COMP_INSTANCE__) == COMP1) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP2) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH2) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ ) || \ (((__COMP_INSTANCE__) == COMP3) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH1)) \ ) || \ (((__COMP_INSTANCE__) == COMP4) && \ (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC1_CH1) || \ - ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ + ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_DAC3_CH2)) \ )) #endif @@ -135,124 +135,124 @@ || ((__POLARITY__) == LL_COMP_OUTPUTPOL_INVERTED) \ ) -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) -#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ - ((((__INSTANCE__) == COMP1) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ - || \ - (((__INSTANCE__) == COMP2) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ - || \ - (((__INSTANCE__) == COMP3) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ - || \ - (((__INSTANCE__) == COMP4) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ - || \ - (((__INSTANCE__) == COMP5) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP5) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP5) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP5) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP5))) \ - || \ - (((__INSTANCE__) == COMP6) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP6) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP6) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP6) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC2_COMP6))) \ - || \ - (((__INSTANCE__) == COMP7) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP7) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP7) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP7) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC2_COMP7))) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM20_OC5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \ +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ + ((((__INSTANCE__) == COMP1) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ + || \ + (((__INSTANCE__) == COMP2) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ + || \ + (((__INSTANCE__) == COMP3) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ + || \ + (((__INSTANCE__) == COMP4) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ + || \ + (((__INSTANCE__) == COMP5) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP5) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP5) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP5) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP5))) \ + || \ + (((__INSTANCE__) == COMP6) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP6) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP6) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP6) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC2_COMP6))) \ + || \ + (((__INSTANCE__) == COMP7) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP7) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP7) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP7) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC2_COMP7))) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM20_OC5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \ ) #elif defined(STM32GBK1CB) || defined(STM32G431xx) || defined(STM32G441xx) || defined(STM32G471xx) -#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ - ((((__INSTANCE__) == COMP1) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ - || \ - (((__INSTANCE__) == COMP2) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ - || \ - (((__INSTANCE__) == COMP3) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ - || \ - (((__INSTANCE__) == COMP4) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \ +#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ + ((((__INSTANCE__) == COMP1) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ + || \ + (((__INSTANCE__) == COMP2) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ + || \ + (((__INSTANCE__) == COMP3) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ + || \ + (((__INSTANCE__) == COMP4) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \ ) #elif defined(STM32G491xx) || defined(STM32G4A1xx) -#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ - ((((__INSTANCE__) == COMP1) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ - || \ - (((__INSTANCE__) == COMP2) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ - || \ - (((__INSTANCE__) == COMP3) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ - || \ - (((__INSTANCE__) == COMP4) && \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ - ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM20_OC5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \ - || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \ +#define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__INSTANCE__, __OUTPUT_BLANKING_SOURCE__) \ + ((((__INSTANCE__) == COMP1) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP1) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP1))) \ + || \ + (((__INSTANCE__) == COMP2) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP2) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP2))) \ + || \ + (((__INSTANCE__) == COMP3) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC4_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC3_COMP3) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP3))) \ + || \ + (((__INSTANCE__) == COMP4) && \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM3_OC4_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM8_OC5_COMP4) || \ + ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1_COMP4))) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM20_OC5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM15_OC1) \ + || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM4_OC3) \ ) #endif /** diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_dac.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_dac.c index 0b21f6102..f47938f67 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_dac.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_dac.c @@ -45,7 +45,7 @@ /** @addtogroup DAC_LL_Private_Macros * @{ */ -#if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) #define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \ (((__DACX__) == DAC2) ? \ ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \ @@ -58,9 +58,9 @@ (((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \ || ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \ ) -#endif /* #if defined(STM32G474xx) || defined(STM32G484xx) || defined(STM32G473xx) || defined(STM32G483xx) */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx || STM32G473xx || STM32G483xx */ -#if defined(STM32G474xx) || defined(STM32G484xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) #define IS_LL_DAC_TRIGGER_SOURCE(__DACX__, __TRIGGER_SOURCE__) \ (((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \ @@ -96,9 +96,9 @@ || (((__DACX__) == DAC3) ? ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \ : ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO)) \ ) -#endif /* STM32G474xx || STM32G484xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx */ -#if defined(STM32G474xx) || defined(STM32G484xx) +#if defined(STM32G414xx) || defined(STM32G474xx) || defined(STM32G484xx) #define IS_LL_DAC_TRIGGER_SOURCE2(__DACX__, __TRIGGER_SOURCE__) \ (((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \ @@ -130,7 +130,7 @@ || (((__DACX__) == DAC3) ? ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM1_TRGO) \ : ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO)) \ ) -#endif /* STM32G474xx || STM32G484xx */ +#endif /* STM32G414xx || STM32G474xx || STM32G484xx */ #define IS_LL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \ (((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NONE) \ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_fmac.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_fmac.c index 4c523c0bd..f6c0f7080 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_fmac.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_fmac.c @@ -113,8 +113,6 @@ ErrorStatus LL_FMAC_DeInit(const FMAC_TypeDef *FMACx) return (status); } - - /** * @} */ diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_i2c.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_i2c.c index 8c165f93e..aff36edc3 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_i2c.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_i2c.c @@ -107,6 +107,7 @@ ErrorStatus LL_I2C_DeInit(const I2C_TypeDef *I2Cx) LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2); } +#if defined(I2C3) else if (I2Cx == I2C3) { /* Force reset of I2C clock */ @@ -115,6 +116,7 @@ ErrorStatus LL_I2C_DeInit(const I2C_TypeDef *I2Cx) /* Release reset of I2C clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C3); } +#endif /* I2C3 */ #if defined(I2C4) else if (I2Cx == I2C4) { diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rcc.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rcc.c index 61f08d545..d2b00dbf5 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rcc.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rcc.c @@ -38,9 +38,15 @@ /** @addtogroup RCC_LL_Private_Macros * @{ */ -#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \ - || ((__VALUE__) == LL_RCC_USART2_CLKSOURCE) \ - || ((__VALUE__) == LL_RCC_USART3_CLKSOURCE)) +#if defined(RCC_CCIPR_USART3SEL) +#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \ + || ((__VALUE__) == LL_RCC_USART2_CLKSOURCE) \ + || (__VALUE__) == LL_RCC_USART3_CLKSOURCE) +#else +#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \ + || ((__VALUE__) == LL_RCC_USART2_CLKSOURCE)) +#endif /* RCC_CCIPR_USART3SEL*/ + #if defined(RCC_CCIPR_UART5SEL) #define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_UART4_CLKSOURCE) \ || ((__VALUE__) == LL_RCC_UART5_CLKSOURCE)) @@ -55,15 +61,20 @@ || ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE) \ || ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE) \ || ((__VALUE__) == LL_RCC_I2C4_CLKSOURCE)) - -#else +#elif defined(RCC_CCIPR_I2C3SEL) #define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \ || ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE) \ || ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE)) +#else +#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \ + || ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE)) + #endif /* RCC_CCIPR2_I2C4SEL */ #define IS_LL_RCC_LPTIM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPTIM1_CLKSOURCE)) +#if defined(SAI1) #define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_SAI1_CLKSOURCE) +#endif /* SAI1 */ #define IS_LL_RCC_I2S_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_I2S_CLKSOURCE) @@ -297,6 +308,7 @@ uint32_t LL_RCC_GetUSARTClockFreq(uint32_t USARTxSource) } else { +#if defined(RCC_CCIPR_USART3SEL) if (USARTxSource == LL_RCC_USART3_CLKSOURCE) { /* USART3CLK clock frequency */ @@ -326,6 +338,7 @@ uint32_t LL_RCC_GetUSARTClockFreq(uint32_t USARTxSource) break; } } +#endif /* RCC_CCIPR_USART3SEL */ } return usart_frequency; } @@ -479,6 +492,7 @@ uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource) } else { +#if defined(RCC_CCIPR_I2C3SEL) if (I2CxSource == LL_RCC_I2C3_CLKSOURCE) { /* I2C3 CLK clock frequency */ @@ -501,6 +515,7 @@ uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource) break; } } +#endif /* RCC_CCIPR_I2C3SEL */ #if defined(RCC_CCIPR2_I2C4SEL) else { @@ -628,6 +643,7 @@ uint32_t LL_RCC_GetLPTIMClockFreq(uint32_t LPTIMxSource) return lptim_frequency; } +#if defined(SAI1) /** * @brief Return SAIx clock frequency * @param SAIxSource This parameter can be one of the following values: @@ -680,6 +696,9 @@ uint32_t LL_RCC_GetSAIClockFreq(uint32_t SAIxSource) return sai_frequency; } +#endif /* SAI1 */ + +#if defined(SPI_I2S_SUPPORT) /** * @brief Return I2Sx clock frequency * @param I2SxSource This parameter can be one of the following values: @@ -729,6 +748,7 @@ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) return i2s_frequency; } +#endif /* SPI_I2S_SUPPORT */ #if defined(FDCAN1) /** diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rng.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rng.c index 9fdfa6e5d..c43a23278 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rng.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_rng.c @@ -99,7 +99,7 @@ ErrorStatus LL_RNG_DeInit(const RNG_TypeDef *RNGx) * - SUCCESS: RNG registers are initialized according to RNG_InitStruct content * - ERROR: not applicable */ -ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, LL_RNG_InitTypeDef *RNG_InitStruct) +ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, const LL_RNG_InitTypeDef *RNG_InitStruct) { /* Check the parameters */ assert_param(IS_RNG_ALL_INSTANCE(RNGx)); diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_ucpd.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_ucpd.c index c6e5b2056..1d3d8418f 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_ucpd.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_ucpd.c @@ -112,7 +112,7 @@ ErrorStatus LL_UCPD_DeInit(UCPD_TypeDef *UCPDx) * the configuration information for the UCPD peripheral. * @retval An ErrorStatus enumeration value. (Return always SUCCESS) */ -ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, LL_UCPD_InitTypeDef *UCPD_InitStruct) +ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, const LL_UCPD_InitTypeDef *UCPD_InitStruct) { /* Check the ucpd Instance UCPDx*/ assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); diff --git a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_usart.c b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_usart.c index a3d396462..a0de805be 100644 --- a/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_usart.c +++ b/stm32cube/stm32g4xx/drivers/src/stm32g4xx_ll_usart.c @@ -159,6 +159,7 @@ ErrorStatus LL_USART_DeInit(const USART_TypeDef *USARTx) /* Release reset of USART clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2); } +#if defined(USART3) else if (USARTx == USART3) { /* Force reset of USART clock */ @@ -167,6 +168,7 @@ ErrorStatus LL_USART_DeInit(const USART_TypeDef *USARTx) /* Release reset of USART clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3); } +#endif /* USART3 */ #if defined(UART4) else if (USARTx == UART4) { @@ -267,10 +269,12 @@ ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, const LL_USART_InitTypeDef *USA { periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART2_CLKSOURCE); } +#if defined(USART3) else if (USARTx == USART3) { periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART3_CLKSOURCE); } +#endif /* USART3 */ #if defined(UART4) else if (USARTx == UART4) { diff --git a/stm32cube/stm32g4xx/release_note.html b/stm32cube/stm32g4xx/release_note.html index 6eeee81df..86232c636 100644 --- a/stm32cube/stm32g4xx/release_note.html +++ b/stm32cube/stm32g4xx/release_note.html @@ -5,11 +5,14 @@ Release Notes for STM32CubeG4 Firmware Package - Destination : 0xABAB0000) - Sign bit extension (Source : 0x0ABA ------> Destination : 0x00000ABA) - (Source : 0xFABA ------> Destination : 0xFFFFFABA) - (++) Truncation : - Truncate section from the source data single when the source data width is bigger than the - destination data width. - Left truncation (Source : 0xABABCDCD ------> Destination : 0xCDCD) - Right truncation (Source : 0xABABCDCD ------> Destination : 0xABAB) - (++) Pack/Unpack : - Pack a set of data when source data width is smaller than the destination data width. - Unpack a set of data when source data width is bigger than the destination data width. - Pack (Source : 0xAB, 0xCD ------> Destination : 0xABCD) - UnPack (Source : 0xABCD ------> Destination : 0xAB, 0xCD) - (++) Exchange : - Exchange data at byte and half-word on the destination and at byte level on the source. - Considering source and destination are both word type. Exchange operation can be as follows. - In examples below, one exchange setting is enabled at a time. - Source byte exchange only (Source : 0xAB12CD34 ------> Destination : 0xABCD1234) - Destination byte exchange only (Source : 0xAB12CD34 ------> Destination : 0x12AB34CD) - Destination half-word exchange only (Source : 0xAB12CD34 ------> Destination : 0xCD34AB12) - In addition, in case of double-word, Exchange data at word level on the destination is also - available. - Considering source and destination are both double-word type. - word exchange only (Source : 0xAB12CD34EF567890 ------> Destination : 0xEF567890AB12CD34) - - (+) Use HAL_DMAEx_ConfigDataHandling() to configure data handling features. Previous elementary explained - can be combined according to application needs. - (++) This API is complementary of normal transfers. - (++) This API must not be called for linked-list transfers as data handling information are configured at - node level. - - *** User sequence *** - [..] - To configure cleanly the DMA channel data handling, ensure to apply the following call sequence : - - (+) Linear transfer : - (++) HAL_DMA_Init() - (++) HAL_DMAEx_ConfigDataHandling() - (++) HAL_DMA_Start() - - *** Repeated Block *** - ====================== - [..] - When available, this feature is used when the data size is higher then 65535 bytes (Maximum block size) or for - scattering / gathering data. - (++) Gather data - Source Destination - 0xAA 0xAA - 0xBB 0xAA - 0xAA ==> 0xAA - 0xCC - 0xAA - (++) Scatter data - Source Destination - 0xAA 0xAA - 0xAA 0xBB - 0xAA ==> 0xAA - 0xBB - 0xAA - - (+) Use HAL_DMAEx_ConfigRepeatBlock() to configure data repeated block feature. Jump addresses and - incrementing or decrementing on source and destination can be combined to have the need application - behavior. - (++) This API is complementary of normal transfers. - (++) This API must not be called for linked-list transfers as repeated block information are configured at - node level. - (++) This API must be called only for DMA channel that supports repeated block feature. - - *** User sequence *** - [..] - To configure cleanly the DMA channel repeated block, ensure to apply the following call sequence : - - (+) Linear transfer : - (++) HAL_DMA_Init() - (++) HAL_DMAEx_ConfigRepeatBlock() - (++) HAL_DMA_Start() - - *** Trigger Configuration *** - ============================= - [..] - When application needs that DMA transfers are conditioned by internal or external events, the trigger feature can - do that. Trigger signals are a set of device signal that are linked to DMA trigger inputs that allows to start the - DMA transfers. - To setup a trigger transfers, three DMA channel parameters are needed: - - (+) Trigger mode - This parameter specifies the trig level. - (++) Block level - (++) Repeated block level - (++) Node level - (++) Single / Burst level - - (+) Trigger polarity - This parameter specifies the DMA trigger sensitivity (Rising or falling). - - (+) Trigger selection - This parameter specifies the DMA trigger hardware signal. - - (+) Use HAL_DMAEx_ConfigTrigger() to configure trigger feature. - (++) This API is complementary to normal transfers APIs. - (++) This API must not be called for linked-list transfers as trigger information are configured at - node level. - - *** User sequence *** - [..] - To configure cleanly the DMA channel trigger, ensure to apply the following call sequence : - (+) Linear transfer : - (++) HAL_DMA_Init() - (++) HAL_DMAEx_ConfigTrigger() - (++) HAL_DMA_Start() - - *** Suspend and resume operation *** - ==================================== - [..] - There are several cases when needs to suspend a DMA current transfer (Example: liberate bandwidth for more - priority DMA channel transfer). Suspending DMA channel (same as abort) is available in polling (blocking mode) and - interrupt (non-blocking mode) modes. When suspended, a DMA channel can be instantly resumed. - - (+) Use HAL_DMAEx_Suspend() to suspend an ongoing DMA channel transfer in polling mode (Blocking mode). - - (+) Use HAL_DMAEx_Suspend_IT() to suspend an ongoing DMA channel transfer in interrupt mode (Non-blocking - mode). - - (+) Use HAL_DMAEx_Resume() to resume a suspended DMA channel transfer execution. - - *** FIFO status *** - =================== - [..] - In several cases, the information of FIFO level is useful to inform at application level how to process remaining - data. When not empty, the DMA channel FIFO cannot be flashed only by reset. - - (+) Use HAL_DMAEx_GetFifoLevel() to get the DMA channel FIFO level (available beats in FIFO). - - @endverbatim - ********************************************************************************************************************** - */ - -/* Includes ----------------------------------------------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup DMAEx DMAEx - * @brief DMA Extended HAL module driver - * @{ - */ - -#ifdef HAL_DMA_MODULE_ENABLED - -/* Private types -----------------------------------------------------------------------------------------------------*/ -/* Private variables -------------------------------------------------------------------------------------------------*/ -/* Private Constants -------------------------------------------------------------------------------------------------*/ -/* Private macros ----------------------------------------------------------------------------------------------------*/ -/* Private function prototypes ---------------------------------------------------------------------------------------*/ -static void DMA_List_Init(DMA_HandleTypeDef const *const hdma); -static void DMA_List_BuildNode(DMA_NodeConfTypeDef const *const pNodeConfig, - DMA_NodeTypeDef *const pNode); -static void DMA_List_GetNodeConfig(DMA_NodeConfTypeDef *const pNodeConfig, - DMA_NodeTypeDef const *const pNode); -static uint32_t DMA_List_CheckNodesBaseAddresses(DMA_NodeTypeDef const *const pNode1, - DMA_NodeTypeDef const *const pNode2, - DMA_NodeTypeDef const *const pNode3); -static uint32_t DMA_List_CheckNodesTypes(DMA_NodeTypeDef const *const pNode1, - DMA_NodeTypeDef const *const pNode2, - DMA_NodeTypeDef const *const pNode3); -static void DMA_List_GetCLLRNodeInfo(DMA_NodeTypeDef const *const pNode, - uint32_t *const cllr_mask, - uint32_t *const cllr_offset); -static uint32_t DMA_List_FindNode(DMA_QListTypeDef const *const pQList, - DMA_NodeTypeDef const *const pNode, - DMA_NodeInQInfoTypeDef *const NodeInfo); -static void DMA_List_ResetQueueNodes(DMA_QListTypeDef const *const pQList, - DMA_NodeInQInfoTypeDef const *const NodeInfo); -static void DMA_List_FillNode(DMA_NodeTypeDef const *const pSrcNode, - DMA_NodeTypeDef *const pDestNode); -static void DMA_List_ConvertNodeToDynamic(uint32_t ContextNodeAddr, - uint32_t CurrentNodeAddr, - uint32_t RegisterNumber); -static void DMA_List_ConvertNodeToStatic(uint32_t ContextNodeAddr, - uint32_t CurrentNodeAddr, - uint32_t RegisterNumber); -static void DMA_List_UpdateDynamicQueueNodesCLLR(DMA_QListTypeDef const *const pQList, - uint32_t LastNode_IsCircular); -static void DMA_List_UpdateStaticQueueNodesCLLR(DMA_QListTypeDef const *const pQList, - uint32_t operation); -static void DMA_List_FormatNode(DMA_NodeTypeDef *const pNode, - uint32_t RegisterIdx, - uint32_t RegisterNumber, - uint32_t Format); -static void DMA_List_ClearUnusedFields(DMA_NodeTypeDef *const pNode, - uint32_t FirstUnusedField); -static void DMA_List_CleanQueue(DMA_QListTypeDef *const pQList); - -/* Exported functions ------------------------------------------------------------------------------------------------*/ - -/** @addtogroup DMAEx_Exported_Functions - * @{ - */ - -/** @addtogroup DMAEx_Exported_Functions_Group1 - * -@verbatim - ====================================================================================================================== - ##### Linked-List Initialization and De-Initialization Functions ##### - ====================================================================================================================== - [..] - This section provides functions allowing to initialize and de-initialize the DMA channel in linked-list mode. - [..] - (+) The HAL_DMAEx_List_Init() function follows the DMA channel linked-list mode configuration procedures as - described in reference manual. - (+) The HAL_DMAEx_List_DeInit() function allows to de-initialize the DMA channel in linked-list mode. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the DMA channel in linked-list mode according to the specified parameters in the - * DMA_InitLinkedListTypeDef and create the associated handle. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_Init(DMA_HandleTypeDef *const hdma) -{ - /* Get tick number */ - uint32_t tickstart = HAL_GetTick(); - - /* Check the DMA channel handle parameter */ - if (hdma == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); - assert_param(IS_DMA_PRIORITY(hdma->InitLinkedList.Priority)); - assert_param(IS_DMA_LINK_STEP_MODE(hdma->InitLinkedList.LinkStepMode)); - assert_param(IS_DMA_TCEM_LINKEDLIST_EVENT_MODE(hdma->InitLinkedList.TransferEventMode)); - assert_param(IS_DMA_LINKEDLIST_MODE(hdma->InitLinkedList.LinkedListMode)); - /* Check DMA channel instance */ - if ((IS_HPDMA_INSTANCE(hdma->Instance) != 0U) || (IS_GPDMA_INSTANCE(hdma->Instance) != 0U)) - { - assert_param(IS_DMA_LINK_ALLOCATED_PORT(hdma->InitLinkedList.LinkAllocatedPort)); - } - - /* Allocate lock resource */ - __HAL_UNLOCK(hdma); - - /* Change DMA peripheral state */ - hdma->State = HAL_DMA_STATE_BUSY; - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Check if the DMA channel is effectively disabled */ - while ((hdma->Instance->CCR & DMA_CCR_EN) != 0U) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) - { - /* Update error code */ - hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT; - - /* Change the DMA state */ - hdma->State = HAL_DMA_STATE_ERROR; - - return HAL_ERROR; - } - } - - /* Initialize the DMA channel registers */ - DMA_List_Init(hdma); - - /* Update DMA channel operation mode */ - hdma->Mode = hdma->InitLinkedList.LinkedListMode; - - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_NONE; - - /* Update the DMA channel state */ - hdma->State = HAL_DMA_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitialize the DMA channel when it is configured in linked-list mode. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_DeInit(DMA_HandleTypeDef *const hdma) -{ - /* Get tick number */ - uint32_t tickstart = HAL_GetTick(); - - /* Check the DMA peripheral handle parameter */ - if (hdma == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); - - /* Disable the selected DMA Channel */ - __HAL_DMA_DISABLE(hdma); - - /* Check if the DMA channel is effectively disabled */ - while ((hdma->Instance->CCR & DMA_CCR_EN) != 0U) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) - { - /* Update error code */ - hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT; - - /* Change the DMA state */ - hdma->State = HAL_DMA_STATE_ERROR; - - return HAL_ERROR; - } - } - - /* Reset DMA Channel registers */ - hdma->Instance->CCR = 0U; - hdma->Instance->CLBAR = 0U; - hdma->Instance->CTR1 = 0U; - hdma->Instance->CTR2 = 0U; - hdma->Instance->CBR1 = 0U; - hdma->Instance->CSAR = 0U; - hdma->Instance->CDAR = 0U; - hdma->Instance->CLLR = 0U; - - /* Reset 2D Addressing registers */ - if (IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance) != 0U) - { - hdma->Instance->CTR3 = 0U; - hdma->Instance->CBR2 = 0U; - } - - /* Clear all flags */ - __HAL_DMA_CLEAR_FLAG(hdma, (DMA_FLAG_TC | DMA_FLAG_HT | DMA_FLAG_DTE | DMA_FLAG_ULE | DMA_FLAG_USE | DMA_FLAG_SUSP | - DMA_FLAG_TO)); - - /* Clean all callbacks */ - hdma->XferCpltCallback = NULL; - hdma->XferHalfCpltCallback = NULL; - hdma->XferErrorCallback = NULL; - hdma->XferAbortCallback = NULL; - hdma->XferSuspendCallback = NULL; - - /* Check the linked-list queue */ - if (hdma->LinkedListQueue != NULL) - { - /* Update the queue state and error code */ - hdma->LinkedListQueue->State = HAL_DMA_QUEUE_STATE_READY; - hdma->LinkedListQueue->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Clean DMA queue */ - hdma->LinkedListQueue = NULL; - } - - /* Clean DMA parent */ - if (hdma->Parent != NULL) - { - hdma->Parent = NULL; - } - - /* Update DMA channel operation mode */ - hdma->Mode = DMA_NORMAL; - - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_NONE; - - /* Update the DMA channel state */ - hdma->State = HAL_DMA_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hdma); - - return HAL_OK; -} -/** - * @} - */ - -/** @addtogroup DMAEx_Exported_Functions_Group2 - * -@verbatim - ====================================================================================================================== - ##### Linked-List IO Operation Functions ##### - ====================================================================================================================== - [..] - This section provides functions allowing to : - (+) Configure to start DMA transfer in linked-list mode. - - [..] - (+) The HAL_DMAEx_List_Start() function allows to start the DMA channel transfer in linked-list mode (Blocking - mode). - (+) The HAL_DMAEx_List_Start_IT() function allows to start the DMA channel transfer in linked-list mode - (Non-blocking mode). - (++) It is mandatory to register a linked-list queue to be executed by a DMA channel before starting - transfer otherwise a HAL_ERROR will be returned. - -@endverbatim - * @{ - */ - -/** - * @brief Start the DMA channel transfer in linked-list mode (Blocking mode). - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_Start(DMA_HandleTypeDef *const hdma) -{ - HAL_DMA_StateTypeDef dma_state; - uint32_t ccr_value; - uint32_t cllr_mask; - - /* Check the DMA peripheral handle and the linked-list queue parameters */ - if ((hdma == NULL) || (hdma->LinkedListQueue == NULL)) - { - return HAL_ERROR; - } - - /* Check DMA channel state */ - dma_state = hdma->State; - ccr_value = hdma->Instance->CCR & DMA_CCR_LSM; - if ((dma_state == HAL_DMA_STATE_READY) || ((dma_state == HAL_DMA_STATE_BUSY) && (ccr_value != 0U))) - { - /* Check DMA channel state is ready */ - if (hdma->State == HAL_DMA_STATE_READY) - { - /* Process locked */ - __HAL_LOCK(hdma); - - /* Update the DMA channel and the queue states */ - hdma->State = HAL_DMA_STATE_BUSY; - hdma->LinkedListQueue->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the DMA channel and the queue error codes */ - hdma->ErrorCode = HAL_DMA_ERROR_NONE; - hdma->LinkedListQueue->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(hdma->LinkedListQueue->Head, &cllr_mask, NULL); - - /* Update DMA registers for linked-list transfer */ - hdma->Instance->CLBAR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLBAR_LBA); - hdma->Instance->CLLR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLLR_LA) | cllr_mask; - } - - /* Enable DMA channel */ - __HAL_DMA_ENABLE(hdma); - } - else - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Starts the DMA channel transfer in linked-list mode with interrupts enabled (Non-blocking mode). - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_Start_IT(DMA_HandleTypeDef *const hdma) -{ - HAL_DMA_StateTypeDef dma_state; - uint32_t ccr_value; - uint32_t cllr_mask; - - /* Check the DMA peripheral handle and the linked-list queue parameters */ - if ((hdma == NULL) || (hdma->LinkedListQueue == NULL)) - { - return HAL_ERROR; - } - - /* Check DMA channel state */ - dma_state = hdma->State; - ccr_value = hdma->Instance->CCR & DMA_CCR_LSM; - if ((dma_state == HAL_DMA_STATE_READY) || ((dma_state == HAL_DMA_STATE_BUSY) && (ccr_value != 0U))) - { - /* Check DMA channel state is ready */ - if (hdma->State == HAL_DMA_STATE_READY) - { - /* Process locked */ - __HAL_LOCK(hdma); - - /* Update the DMA channel and the queue states */ - hdma->State = HAL_DMA_STATE_BUSY; - hdma->LinkedListQueue->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the DMA channel and the queue error codes */ - hdma->ErrorCode = HAL_DMA_ERROR_NONE; - hdma->LinkedListQueue->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Enable common interrupts: Transfer Complete and Transfer Errors ITs */ - __HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_DTE | DMA_IT_ULE | DMA_IT_USE | DMA_IT_TO)); - - /* Check half transfer complete callback */ - if (hdma->XferHalfCpltCallback != NULL) - { - /* If half transfer complete callback is set, enable the corresponding IT */ - __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT); - } - - /* Check suspend callback */ - if (hdma->XferSuspendCallback != NULL) - { - /* If transfer suspend callback is set, enable the corresponding IT */ - __HAL_DMA_ENABLE_IT(hdma, DMA_IT_SUSP); - } - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(hdma->LinkedListQueue->Head, &cllr_mask, NULL); - - /* Update DMA registers for linked-list transfer */ - hdma->Instance->CLBAR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLBAR_LBA); - hdma->Instance->CLLR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLLR_LA) | cllr_mask; - } - - /* Enable DMA channel */ - __HAL_DMA_ENABLE(hdma); - } - else - { - /* Change the error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - return HAL_OK; -} -/** - * @} - */ - -/** @addtogroup DMAEx_Exported_Functions_Group3 - * -@verbatim - ====================================================================================================================== - ##### Linked-List Management Functions ##### - ====================================================================================================================== - [..] - This section provides functions allowing to : - (+) Build linked-list node. - (+) Get linked-list node configuration. - (+) Insert node to linked-list queue in any queue position. - (+) Remove any node from linked-list queue. - (+) Replace any node from linked-list queue. - (+) Reset linked-list queue. - (+) Insert linked-list queue in any queue position. - (+) Set circular mode configuration to linked-list queue. - (+) Clear circular mode configuration from linked-list queue. - (+) Convert static linked-list queue to dynamic format. - (+) Convert dynamic linked-list queue to static format. - (+) Link linked-list queue to DMA channel. - (+) Unlink linked-list queue from DMA channel. - - [..] - (+) The HAL_DMAEx_List_BuildNode() function allows to build linked-list node. - Node type can be : - (++) 2 dimensions addressing node. - (++) Linear addressing node. - - (+) The HAL_DMAEx_List_GetNodeConfig() function allows to get the linked-list node configuration from built node. - - (+) The HAL_DMAEx_List_InsertNode() function allows to insert built linked-list node to static linked-list queue - according to selected position. - - (+) The HAL_DMAEx_List_InsertNode_Head() and HAL_DMAEx_List_InsertNode_Tail() functions allow to insert built - linked-list node to the head (respectively the tail) of static linked-list queue. - - (+) The HAL_DMAEx_List_RemoveNode() function allows to remove selected built linked-list node from static - linked-list queue. - - (+) The HAL_DMAEx_List_RemoveNode_Head() and HAL_DMAEx_List_RemoveNode_Tail() functions allow to remove the head - (respectively the tail) built linked-list node from static linked-list queue. - - (+) The HAL_DMAEx_List_ReplaceNode() function allows to replace selected built linked-list node from static - linked-list queue. - - (+) The HAL_DMAEx_List_ReplaceNode_Head() and HAL_DMAEx_List_ReplaceNode_Tail() functions allow to replace the - head (respectively the tail) built linked-list node of static linked-list queue. - - (+) The HAL_DMAEx_List_ResetQ() function allows to reset static linked-list queue and unlink all built linked-list - nodes. - - (+) The HAL_DMAEx_List_InsertQ() function allows to insert static linked-list source queue to static linked-list - destination queue according to selected position. - - (+) The HAL_DMAEx_List_InsertQ_Head() and HAL_DMAEx_List_InsertQ_Tail() functions allow to insert static - linked-list source queue to the head (respectively the tail) of static linked-list destination queue. - - (+) The HAL_DMAEx_List_SetCircularModeConfig() function allows to link the last static linked-list queue node to - the selected first circular node. - - (+) The HAL_DMAEx_List_SetCircularMode() function allows to link the last static linked-list queue node to the - first static linked-list queue node. - - (+) The HAL_DMAEx_List_ClearCircularMode() function allows to unlink the last static linked-list queue node from - any first circular node position. - - (+) The HAL_DMAEx_List_ConvertQToDynamic() function allows to convert the static linked-list queue to dynamic - format. (Optimized queue execution) - - (+) The HAL_DMAEx_List_ConvertQToStatic() function allows to convert the dynamic linked-list queue to static - format. (Not optimized queue execution) - - (+) The HAL_DMAEx_List_LinkQ() function allows to link the (Dynamic / Static) linked-list queue to DMA channel to - be executed. - - (+) The HAL_DMAEx_List_UnLinkQ() function allows to unlink the (Dynamic / Static) linked-list queue from DMA - channel when execution is completed. - -@endverbatim - * @{ - */ - -/** - * @brief Build a DMA channel node according to the specified parameters in the DMA_NodeConfTypeDef. - * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the - * specified DMA linked-list Node. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @note The DMA linked-list node parameter address should be 32bit aligned and should not exceed the 64 KByte - * addressable space. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_BuildNode(DMA_NodeConfTypeDef const *const pNodeConfig, - DMA_NodeTypeDef *const pNode) -{ - /* Check the node configuration and physical node parameters */ - if ((pNodeConfig == NULL) || (pNode == NULL)) - { - return HAL_ERROR; - } - - /* Check node type parameter */ - assert_param(IS_DMA_NODE_TYPE(pNodeConfig->NodeType)); - - /* Check DMA channel basic transfer parameters */ - assert_param(IS_DMA_SOURCE_INC(pNodeConfig->Init.SrcInc)); - assert_param(IS_DMA_DESTINATION_INC(pNodeConfig->Init.DestInc)); - assert_param(IS_DMA_SOURCE_DATA_WIDTH(pNodeConfig->Init.SrcDataWidth)); - assert_param(IS_DMA_DESTINATION_DATA_WIDTH(pNodeConfig->Init.DestDataWidth)); - assert_param(IS_DMA_DATA_ALIGNMENT(pNodeConfig->DataHandlingConfig.DataAlignment)); - assert_param(IS_DMA_REQUEST(pNodeConfig->Init.Request)); - assert_param(IS_DMA_DIRECTION(pNodeConfig->Init.Direction)); - assert_param(IS_DMA_TCEM_EVENT_MODE(pNodeConfig->Init.TransferEventMode)); - assert_param(IS_DMA_BLOCK_HW_REQUEST(pNodeConfig->Init.BlkHWRequest)); - assert_param(IS_DMA_MODE(pNodeConfig->Init.Mode)); - - /* Check DMA channel parameters */ - if ((pNodeConfig->NodeType & (DMA_CHANNEL_TYPE_GPDMA | DMA_CHANNEL_TYPE_HPDMA)) != 0U) - { - assert_param(IS_DMA_BURST_LENGTH(pNodeConfig->Init.SrcBurstLength)); - assert_param(IS_DMA_BURST_LENGTH(pNodeConfig->Init.DestBurstLength)); - assert_param(IS_DMA_DATA_EXCHANGE(pNodeConfig->DataHandlingConfig.DataExchange)); - assert_param(IS_DMA_TRANSFER_ALLOCATED_PORT(pNodeConfig->Init.TransferAllocatedPort)); - } - - /* Check DMA channel trigger parameters */ - assert_param(IS_DMA_TRIGGER_POLARITY(pNodeConfig->TriggerConfig.TriggerPolarity)); - if (pNodeConfig->TriggerConfig.TriggerPolarity != DMA_TRIG_POLARITY_MASKED) - { - assert_param(IS_DMA_TRIGGER_MODE(pNodeConfig->TriggerConfig.TriggerMode)); - assert_param(IS_DMA_TRIGGER_SELECTION(pNodeConfig->TriggerConfig.TriggerSelection)); - } - - /* Check DMA channel repeated block parameters */ - if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - assert_param(IS_DMA_REPEAT_COUNT(pNodeConfig->RepeatBlockConfig.RepeatCount)); - assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.SrcAddrOffset)); - assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.DestAddrOffset)); - assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset)); - assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset)); - assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.SrcAddrOffset)); - assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.DestAddrOffset)); - assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset)); - assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset)); - } - - /* Build the DMA channel node */ - DMA_List_BuildNode(pNodeConfig, pNode); - - return HAL_OK; -} - -/** - * @brief Get a DMA channel node configuration. - * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the - * specified DMA linked-list Node. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_GetNodeConfig(DMA_NodeConfTypeDef *const pNodeConfig, - DMA_NodeTypeDef const *const pNode) -{ - /* Check the node configuration and physical node parameters */ - if ((pNodeConfig == NULL) || (pNode == NULL)) - { - return HAL_ERROR; - } - - /* Get the DMA channel node configuration */ - DMA_List_GetNodeConfig(pNodeConfig, pNode); - - return HAL_OK; -} - -/** - * @brief Insert new node in any queue position of linked-list queue according to selecting previous node. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pPrevNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list previous node registers - * configurations. - * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_InsertNode(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pPrevNode, - DMA_NodeTypeDef *const pNewNode) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the new node parameters */ - if ((pQList == NULL) || (pNewNode == NULL)) - { - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pPrevNode, pNewNode) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pQList->Head, pPrevNode, pNewNode) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); - - /* Empty queue */ - if (pQList->Head == NULL) - { - /* Add only new node to queue */ - if (pPrevNode == NULL) - { - pQList->Head = pNewNode; - pQList->NodeNumber = 1U; - } - /* Add previous node then new node to queue */ - else - { - pQList->Head = pPrevNode; - pPrevNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - pQList->NodeNumber = 2U; - } - } - /* Not empty queue */ - else - { - /* Add new node at the head of queue */ - if (pPrevNode == NULL) - { - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; - pQList->Head = pNewNode; - } - /* Add new node according to selected position */ - else - { - /* Find node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - if (DMA_List_FindNode(pQList, pPrevNode, &node_info) == 0U) - { - /* Selected node is the last queue node */ - if (node_info.currentnode_pos == pQList->NodeNumber) - { - /* Check if queue is circular */ - if (pQList->FirstCircularNode != NULL) - { - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; - } - - pPrevNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - } - /* Selected node is not the last queue node */ - else - { - pNewNode->LinkRegisters[cllr_offset] = pPrevNode->LinkRegisters[cllr_offset]; - pPrevNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - } - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; - - return HAL_ERROR; - } - } - - /* Increment queue node number */ - pQList->NodeNumber++; - } - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Insert new node at the head of linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_InsertNode_Head(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pNewNode) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - - /* Check the queue and the new node parameters */ - if ((pQList == NULL) || (pNewNode == NULL)) - { - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pNewNode, NULL) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pQList->Head, pNewNode, NULL) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Empty queue */ - if (pQList->Head == NULL) - { - pQList->Head = pNewNode; - } - /* Not empty queue */ - else - { - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); - - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; - pQList->Head = pNewNode; - } - - /* Increment queue node number */ - pQList->NodeNumber++; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Insert new node at the tail of linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_InsertNode_Tail(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pNewNode) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the new node parameters */ - if ((pQList == NULL) || (pNewNode == NULL)) - { - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pNewNode, NULL) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pQList->Head, pNewNode, NULL) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Empty queue */ - if (pQList->Head == NULL) - { - pQList->Head = pNewNode; - } - /* Not empty queue */ - else - { - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); - - /* Find node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Check if queue is circular */ - if (pQList->FirstCircularNode != NULL) - { - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; - } - - ((DMA_NodeTypeDef *)node_info.currentnode_addr)->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - } - - /* Increment queue node number */ - pQList->NodeNumber++; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Remove node from any linked-list queue position. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list previous node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_RemoveNode(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pNode) -{ - uint32_t previousnode_addr; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the node parameters */ - if ((pQList == NULL) || (pNode == NULL)) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNode, NULL, &cllr_offset); - - /* Find node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - if (DMA_List_FindNode(pQList, pNode, &node_info) == 0U) - { - /* Removed node is the head node */ - if (node_info.currentnode_pos == 1U) - { - /* Check if first circular node queue is the first node */ - if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)node_info.currentnode_addr)) - { - /* Find last queue node */ - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear last node link */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear first circular node */ - pQList->FirstCircularNode = NULL; - } - - /* Update the queue head node */ - pQList->Head = (DMA_NodeTypeDef *)(((uint32_t)pQList->Head & DMA_CLBAR_LBA) + - (pNode->LinkRegisters[cllr_offset] & DMA_CLLR_LA)); - /* Unlink node to be removed */ - pNode->LinkRegisters[cllr_offset] = 0U; - } - /* Removed node is the last node */ - else if (node_info.currentnode_pos == pQList->NodeNumber) - { - /* Clear CLLR for previous node */ - ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear CLLR for last node */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear first circular node */ - pQList->FirstCircularNode = NULL; - } - /* Removed node is in the middle */ - else - { - /* Store previous node address to be updated later */ - previousnode_addr = node_info.previousnode_addr; - - /* Check if first circular node queue is the current node */ - if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)node_info.currentnode_addr)) - { - /* Find last queue node */ - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear last node link */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear first circular node */ - pQList->FirstCircularNode = NULL; - } - - /* Link previous node */ - ((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[cllr_offset] = pNode->LinkRegisters[cllr_offset]; - - /* Unlink node to be removed */ - pNode->LinkRegisters[cllr_offset] = 0U; - } - - /* Decrement node number */ - pQList->NodeNumber--; - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; - - return HAL_ERROR; - } - - /* Check if queue is empty */ - if (pQList->NodeNumber == 0U) - { - /* Clean empty queue parameter */ - DMA_List_CleanQueue(pQList); - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - } - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Remove the head node from linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_RemoveNode_Head(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_offset; - uint32_t current_addr; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); - - /* Queue contains only one node */ - if (pQList->NodeNumber == 1U) - { - pQList->Head->LinkRegisters[cllr_offset] = 0U; - pQList->FirstCircularNode = 0U; - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - } - /* Queue contains more then one node */ - else - { - /* Check if first circular node queue is the first node */ - if (pQList->FirstCircularNode == pQList->Head) - { - /* Find last queue node */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear last node link */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear first circular node */ - pQList->FirstCircularNode = NULL; - } - - current_addr = pQList->Head->LinkRegisters[cllr_offset] & DMA_CLLR_LA; - pQList->Head->LinkRegisters[cllr_offset] = 0U; - pQList->Head = ((DMA_NodeTypeDef *)(current_addr + ((uint32_t)pQList->Head & DMA_CLBAR_LBA))); - } - - /* Decrement node number */ - pQList->NodeNumber--; - - /* Check if queue is empty */ - if (pQList->NodeNumber == 0U) - { - /* Clean empty queue parameter */ - DMA_List_CleanQueue(pQList); - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - } - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Remove the tail node from linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_RemoveNode_Tail(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); - - /* Queue contains only one node */ - if (pQList->NodeNumber == 1U) - { - pQList->Head->LinkRegisters[cllr_offset] = 0U; - pQList->FirstCircularNode = 0U; - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - } - /* Queue contains more then one node */ - else - { - /* Find node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear CLLR for previous node */ - ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear CLLR for last node */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Clear first circular node */ - pQList->FirstCircularNode = NULL; - } - - /* Decrement node number */ - pQList->NodeNumber--; - - /* Check if queue is empty */ - if (pQList->NodeNumber == 0U) - { - /* Clean empty queue parameter */ - DMA_List_CleanQueue(pQList); - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - } - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Replace node in linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pOldNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list old node registers - * configurations. - * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ReplaceNode(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pOldNode, - DMA_NodeTypeDef *const pNewNode) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the nodes parameters */ - if ((pQList == NULL) || (pOldNode == NULL) || (pNewNode == NULL)) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pOldNode, pNewNode) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pQList->Head, pOldNode, pNewNode) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); - - /* Find node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - if (DMA_List_FindNode(pQList, pOldNode, &node_info) == 0U) - { - /* Replaced node is the head node */ - if (node_info.currentnode_pos == 1U) - { - pNewNode->LinkRegisters[cllr_offset] = - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset]; - pQList->Head = pNewNode; - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Check if first circular node queue is the first node */ - if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)node_info.currentnode_addr)) - { - /* Find last queue node */ - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear last node link */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - - /* Set new node as first circular node */ - pQList->FirstCircularNode = pNewNode; - } - } - /* Replaced node is the last */ - else if (node_info.currentnode_pos == pQList->NodeNumber) - { - ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Check if first circular node queue is the last node */ - if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)(node_info.currentnode_addr))) - { - /* Link first circular node to new node */ - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - - /* Set new node as first circular node */ - pQList->FirstCircularNode = pNewNode; - } - /* Check if first circular node queue is not the last node */ - else if (pQList->FirstCircularNode != NULL) - { - /* Link first circular node to new node */ - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; - } - else - { - /* Prevent MISRA-C2012-Rule-15.7 */ - } - } - /* Replaced node is in the middle */ - else - { - ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - pNewNode->LinkRegisters[cllr_offset] = - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset]; - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Check if first circular node queue is the current node */ - if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)(node_info.currentnode_addr))) - { - /* Find last node and get its position in selected queue */ - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Link last queue node to new node */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - - /* Set new node as first circular node */ - pQList->FirstCircularNode = pNewNode; - } - } - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; - - return HAL_ERROR; - } - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Replace the head node of linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ReplaceNode_Head(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pNewNode) -{ - uint32_t cllr_offset; - uint32_t cllr_mask; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the new node parameters */ - if ((pQList == NULL) || (pNewNode == NULL)) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pNewNode, NULL) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pQList->Head, pNewNode, NULL) != 0U) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); - - /* Check if first circular node queue is the first node */ - if (pQList->FirstCircularNode == pQList->Head) - { - /* Find last queue node */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear last node link */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - - /* Set new node as first circular node */ - pQList->FirstCircularNode = pNewNode; - } - - /* Replace head node */ - pNewNode->LinkRegisters[cllr_offset] = pQList->Head->LinkRegisters[cllr_offset]; - pQList->Head->LinkRegisters[cllr_offset] = 0U; - pQList->Head = pNewNode; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Replace the tail node of linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers - * configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ReplaceNode_Tail(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pNewNode) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the new node parameters */ - if ((pQList == NULL) || (pNewNode == NULL)) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); - - /* Find last node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Link previous node to new node */ - ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - - /* Clear CLLR for current node */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Check if first circular node queue is the last node */ - if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)(node_info.currentnode_addr))) - { - /* Link first circular node to new node */ - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; - - /* Set new node as first circular node */ - pQList->FirstCircularNode = pNewNode; - } - /* Check if first circular node queue is not the last node */ - else if (pQList->FirstCircularNode != NULL) - { - /* Link first circular node to new node */ - pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; - } - else - { - /* Prevent MISRA-C2012-Rule-15.7 */ - } - - /* Check if queue contains one node */ - if (pQList->NodeNumber == 1U) - { - pQList->Head = pNewNode; - } - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Reset the linked-list queue and unlink queue nodes. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ResetQ(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check queue state */ - if (pQList->State == HAL_DMA_QUEUE_STATE_BUSY) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_BUSY; - - return HAL_ERROR; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Check the queue */ - if (pQList->Head != NULL) - { - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); - - /* Reset selected queue nodes */ - node_info.cllr_offset = cllr_offset; - DMA_List_ResetQueueNodes(pQList, &node_info); - } - - /* Reset head node address */ - pQList->Head = NULL; - - /* Reset node number */ - pQList->NodeNumber = 0U; - - /* Reset first circular node */ - pQList->FirstCircularNode = NULL; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_RESET; - - return HAL_OK; -} - -/** - * @brief Insert a source linked-list queue to a destination linked-list queue according to selecting previous node. - * @param pSrcQList : Pointer to a DMA_QListTypeDef structure that contains source queue information. - * @param pPrevNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list previous node registers - * configurations. - * @param pDestQList : Pointer to a DMA_QListTypeDef structure that contains destination queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_InsertQ(DMA_QListTypeDef *const pSrcQList, - DMA_NodeTypeDef const *const pPrevNode, - DMA_QListTypeDef *const pDestQList) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef src_q_node_info; - DMA_NodeInQInfoTypeDef dest_q_node_info; - - /* Check the source and destination queues and the previous node parameters */ - if ((pSrcQList == NULL) || (pDestQList == NULL)) - { - return HAL_ERROR; - } - - /* Check the source queue */ - if (pSrcQList->Head == NULL) - { - /* Update the queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check the source queue type */ - if (pSrcQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check the destination queue type */ - if (pDestQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check the source queue circularity */ - if (pSrcQList->FirstCircularNode != NULL) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pSrcQList->Head, pPrevNode, pDestQList->Head) != 0U) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pSrcQList->Head, pPrevNode, pDestQList->Head) != 0U) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the source queue state */ - pSrcQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the destination queue state */ - pDestQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pSrcQList->Head, &cllr_mask, &cllr_offset); - - /* Empty destination queue */ - if (pDestQList->Head == NULL) - { - pDestQList->Head = pSrcQList->Head; - pDestQList->NodeNumber = pSrcQList->NodeNumber; - } - /* Not empty destination queue */ - else - { - /* Previous node is empty */ - if (pPrevNode == NULL) - { - /* Find node and get its position in selected queue */ - src_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); - - /* Check if first circular node queue is the first node */ - if (pDestQList->FirstCircularNode == pDestQList->Head) - { - /* Find node and get its position in selected queue */ - dest_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pDestQList, NULL, &dest_q_node_info); - - /* Link destination queue tail node to new first circular node */ - ((DMA_NodeTypeDef *)dest_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = - ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; - - /* Set the head node of source queue as the first circular node */ - pDestQList->FirstCircularNode = pSrcQList->Head; - } - - /* Link the last node of source queue to the fist node of destination queue */ - ((DMA_NodeTypeDef *)(src_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pDestQList->Head & DMA_CLLR_LA) | cllr_mask; - pDestQList->Head = pSrcQList->Head; - pDestQList->NodeNumber += pSrcQList->NodeNumber; - } - /* Previous node is not empty */ - else - { - /* Find node and get its position in selected queue */ - dest_q_node_info.cllr_offset = cllr_offset; - if (DMA_List_FindNode(pDestQList, pPrevNode, &dest_q_node_info) == 0U) - { - /* Selected node is the last destination queue node */ - if (dest_q_node_info.currentnode_pos == pDestQList->NodeNumber) - { - /* Link the first node of source queue to the last node of destination queue */ - ((DMA_NodeTypeDef *)(dest_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; - pDestQList->NodeNumber += pSrcQList->NodeNumber; - - /* Check if first circular node queue is not empty */ - if (pDestQList->FirstCircularNode != NULL) - { - /* Find node and get its position in selected queue */ - src_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); - - /* Find first circular node */ - (void)DMA_List_FindNode(pDestQList, pDestQList->FirstCircularNode, &dest_q_node_info); - - /* Link last source queue node to first destination queue */ - ((DMA_NodeTypeDef *)src_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = - (dest_q_node_info.currentnode_addr & DMA_CLLR_LA) | cllr_mask; - } - } - /* Selected node is not the last destination queue node */ - else - { - /* Link the first node of source queue to the previous node of destination queue */ - ((DMA_NodeTypeDef *)(dest_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; - - /* Find node and get its position in selected queue */ - src_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); - - /* Link the last node of source queue to the next node of destination queue */ - ((DMA_NodeTypeDef *)(src_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - (dest_q_node_info.nextnode_addr & DMA_CLLR_LA) | cllr_mask; - - /* Update queues counter */ - pDestQList->NodeNumber += pSrcQList->NodeNumber; - } - } - else - { - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; - - return HAL_ERROR; - } - } - } - - /* Clean the source queue variable as it is obsolete */ - DMA_List_CleanQueue(pSrcQList); - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the destination queue state */ - pDestQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(src_q_node_info); - UNUSED(dest_q_node_info); - - return HAL_OK; -} - -/** - * @brief Insert a source linked-list queue at the head of destination queue. - * @param pSrcQList : Pointer to a DMA_QListTypeDef structure that contains source queue information. - * @param pDestQList : Pointer to a DMA_QListTypeDef structure that contains destination queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_InsertQ_Head(DMA_QListTypeDef *const pSrcQList, - DMA_QListTypeDef *const pDestQList) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef src_q_node_info; - DMA_NodeInQInfoTypeDef dest_q_node_info; - - /* Check the source and destination queues and the previous node parameters */ - if ((pSrcQList == NULL) || (pDestQList == NULL)) - { - return HAL_ERROR; - } - - /* Check the source queue */ - if (pSrcQList->Head == NULL) - { - /* Update the queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check the source queue type */ - if (pSrcQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check the destination queue type */ - if (pDestQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pSrcQList->Head, pDestQList->Head, NULL) != 0U) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pSrcQList->Head, pDestQList->Head, NULL) != 0U) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the source queue state */ - pSrcQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the destination queue state */ - pDestQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pSrcQList->Head, &cllr_mask, &cllr_offset); - - /* Empty destination queue */ - if (pDestQList->Head == NULL) - { - pDestQList->Head = pSrcQList->Head; - pDestQList->NodeNumber = pSrcQList->NodeNumber; - } - /* Not empty destination queue */ - else - { - /* Find node and get its position in selected queue */ - src_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); - - /* Check if first circular node queue is the first node */ - if (pDestQList->FirstCircularNode == pDestQList->Head) - { - /* Find node and get its position in selected queue */ - dest_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pDestQList, NULL, &dest_q_node_info); - - /* Link destination queue tail node to new first circular node */ - ((DMA_NodeTypeDef *)dest_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = - ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; - - /* Set the head node of source queue as the first circular node */ - pDestQList->FirstCircularNode = pSrcQList->Head; - } - - /* Link the last node of source queue to the fist node of destination queue */ - ((DMA_NodeTypeDef *)(src_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pDestQList->Head & DMA_CLLR_LA) | cllr_mask; - pDestQList->Head = pSrcQList->Head; - pDestQList->NodeNumber += pSrcQList->NodeNumber; - } - - /* Clean the source queue variable as it is obsolete */ - DMA_List_CleanQueue(pSrcQList); - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the destination queue state */ - pDestQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(src_q_node_info); - UNUSED(dest_q_node_info); - - return HAL_OK; -} - -/** - * @brief Insert a source linked-list queue at the tail of destination queue. - * @param pSrcQList : Pointer to a DMA_QListTypeDef structure that contains source queue information. - * @param pDestQList : Pointer to a DMA_QListTypeDef structure that contains destination queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_InsertQ_Tail(DMA_QListTypeDef *const pSrcQList, - DMA_QListTypeDef *const pDestQList) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef src_q_node_info; - DMA_NodeInQInfoTypeDef dest_q_node_info; - - /* Check the source and destination queues and the previous node parameters */ - if ((pSrcQList == NULL) || (pDestQList == NULL)) - { - return HAL_ERROR; - } - - /* Check the source queue */ - if (pSrcQList->Head == NULL) - { - /* Update the queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check the source queue type */ - if (pSrcQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check the destination queue type */ - if (pDestQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Check nodes base addresses */ - if (DMA_List_CheckNodesBaseAddresses(pSrcQList->Head, pDestQList->Head, NULL) != 0U) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; - - return HAL_ERROR; - } - - /* Check nodes types compatibility */ - if (DMA_List_CheckNodesTypes(pSrcQList->Head, pDestQList->Head, NULL) != 0U) - { - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the source queue state */ - pSrcQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the source queue error code */ - pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the destination queue state */ - pDestQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pSrcQList->Head, &cllr_mask, &cllr_offset); - - /* Empty destination queue */ - if (pDestQList->Head == NULL) - { - pDestQList->Head = pSrcQList->Head; - pDestQList->NodeNumber = pSrcQList->NodeNumber; - } - /* Not empty destination queue */ - else - { - /* Find node and get its position in selected queue */ - dest_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pDestQList, NULL, &dest_q_node_info); - - /* Update source queue last node CLLR to link it with destination first node */ - ((DMA_NodeTypeDef *)(dest_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; - pDestQList->NodeNumber += pSrcQList->NodeNumber; - - /* Check if first circular node queue is not empty */ - if (pDestQList->FirstCircularNode != NULL) - { - /* Find node and get its position in selected queue */ - src_q_node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); - - /* Find first circular node */ - (void)DMA_List_FindNode(pDestQList, pDestQList->FirstCircularNode, &dest_q_node_info); - - /* Link last source queue node to first destination queue */ - ((DMA_NodeTypeDef *)src_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = - (dest_q_node_info.currentnode_addr & DMA_CLLR_LA) | cllr_mask; - } - } - - /* Clean the source queue variable as it is obsolete */ - DMA_List_CleanQueue(pSrcQList); - - /* Update the destination queue error code */ - pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the destination queue state */ - pDestQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(src_q_node_info); - - return HAL_OK; -} - -/** - * @brief Set circular mode configuration for linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pFirstCircularNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list first circular node - * registers configurations. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_SetCircularModeConfig(DMA_QListTypeDef *const pQList, - DMA_NodeTypeDef *const pFirstCircularNode) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue and the first circular node parameters */ - if ((pQList == NULL) || (pFirstCircularNode == NULL)) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue circular mode */ - if (pQList->FirstCircularNode != NULL) - { - if (pQList->FirstCircularNode == pFirstCircularNode) - { - return HAL_OK; - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pFirstCircularNode, &cllr_mask, &cllr_offset); - - /* Find the first circular node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - if (DMA_List_FindNode(pQList, pFirstCircularNode, &node_info) == 0U) - { - /* Find the last queue node and get its position in selected queue */ - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Set circular mode */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pFirstCircularNode & DMA_CLLR_LA) | cllr_mask; - - /* Update first circular node in queue */ - pQList->FirstCircularNode = pFirstCircularNode; - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; - - return HAL_ERROR; - } - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Set circular mode for linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_SetCircularMode(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_mask; - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue circular mode */ - if (pQList->FirstCircularNode != NULL) - { - if (pQList->FirstCircularNode == pQList->Head) - { - return HAL_OK; - } - else - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, &cllr_mask, &cllr_offset); - - /* Find the last queue node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Set circular mode */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = - ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; - - /* Update linked-list circular state */ - pQList->FirstCircularNode = pQList->Head; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Clear circular mode for linked-list queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ClearCircularMode(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_offset; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check queue circular mode */ - if (pQList->FirstCircularNode == NULL) - { - return HAL_OK; - } - - /* Check queue type */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); - - /* Find the last queue node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - - /* Clear circular mode */ - ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; - - /* Update linked-list circular configuration */ - pQList->FirstCircularNode = NULL; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - /* Prevent MISRA-C2012-Rule-2.2_b */ - UNUSED(node_info); - - return HAL_OK; -} - -/** - * @brief Convert a linked-list queue to dynamic (Optimized DMA queue execution). - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ConvertQToDynamic(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_offset; - uint32_t currentnode_addr; - DMA_NodeTypeDef context_node; - DMA_NodeInQInfoTypeDef node_info; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check if queue is dynamic */ - if (pQList->Type == QUEUE_TYPE_DYNAMIC) - { - return HAL_OK; - } - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); - - /* Check queue circularity */ - if (pQList->FirstCircularNode != 0U) - { - /* Find the last queue node and get its position in selected queue */ - node_info.cllr_offset = cllr_offset; - (void)DMA_List_FindNode(pQList, NULL, &node_info); - } - - /* Set current node address */ - currentnode_addr = (uint32_t)pQList->Head; - - /* Store register value */ - DMA_List_FillNode(pQList->Head, &context_node); - - /* Convert all nodes to dyncamic (Bypass head node) */ - for (uint32_t node_count = 1U; node_count < pQList->NodeNumber; node_count++) - { - /* Update node address */ - MODIFY_REG(currentnode_addr, DMA_CLLR_LA, (context_node.LinkRegisters[cllr_offset] & DMA_CLLR_LA)); - - /* Bypass the first circular node when first circular node isn't the last queue node */ - if (((uint32_t)pQList->FirstCircularNode != 0U) && - ((uint32_t)pQList->FirstCircularNode != node_info.currentnode_addr) && - ((uint32_t)pQList->FirstCircularNode == currentnode_addr)) - { - /* Copy first circular node to context node */ - DMA_List_FillNode(pQList->FirstCircularNode, &context_node); - } - else - { - /* Convert current node to dynamic */ - DMA_List_ConvertNodeToDynamic((uint32_t)&context_node, currentnode_addr, (cllr_offset + 1U)); - } - } - - /* Check if first circular node is the last node queue */ - if (((uint32_t)pQList->FirstCircularNode != 0U) && - ((uint32_t)pQList->FirstCircularNode != node_info.currentnode_addr)) - { - /* Update all queue nodes CLLR */ - DMA_List_UpdateDynamicQueueNodesCLLR(pQList, LASTNODE_ISNOT_CIRCULAR); - } - else - { - /* Update all queue nodes CLLR */ - DMA_List_UpdateDynamicQueueNodesCLLR(pQList, LASTNODE_IS_CIRCULAR); - } - - /* Set queue type */ - pQList->Type = QUEUE_TYPE_DYNAMIC; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Convert a linked-list queue to static (Not optimized DMA queue execution). - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_ConvertQToStatic(DMA_QListTypeDef *const pQList) -{ - uint32_t cllr_offset; - uint32_t currentnode_addr; - DMA_NodeTypeDef context_node; - - /* Check the queue parameter */ - if (pQList == NULL) - { - return HAL_ERROR; - } - - /* Check the queue */ - if (pQList->Head == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; - - return HAL_ERROR; - } - - /* Check if queue is static */ - if (pQList->Type == QUEUE_TYPE_STATIC) - { - return HAL_OK; - } - - /* Set current node address */ - currentnode_addr = (uint32_t)pQList->Head; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_BUSY; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Get CLLR register mask and offset */ - DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); - - /* Set all CLLR queue nodes to their default positions */ - DMA_List_UpdateStaticQueueNodesCLLR(pQList, UPDATE_CLLR_POSITION); - - /* Convert all nodes to static (Bypass head node) */ - for (uint32_t node_count = 1U; node_count < pQList->NodeNumber; node_count++) - { - /* Update context node register values */ - DMA_List_FillNode((DMA_NodeTypeDef *)currentnode_addr, &context_node); - - /* Update node address */ - MODIFY_REG(currentnode_addr, DMA_CLLR_LA, (context_node.LinkRegisters[cllr_offset] & DMA_CLLR_LA)); - - /* Convert current node to static */ - DMA_List_ConvertNodeToStatic((uint32_t)&context_node, currentnode_addr, (cllr_offset + 1U)); - } - - /* Set all CLLR queue nodes to their default values */ - DMA_List_UpdateStaticQueueNodesCLLR(pQList, UPDATE_CLLR_VALUE); - - /* Set queue type */ - pQList->Type = QUEUE_TYPE_STATIC; - - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Update the queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Link linked-list queue to a DMA channel. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_LinkQ(DMA_HandleTypeDef *const hdma, - DMA_QListTypeDef *const pQList) -{ - HAL_DMA_StateTypeDef state; - - /* Check the DMA channel handle and the queue parameters */ - if ((hdma == NULL) || (pQList == NULL)) - { - return HAL_ERROR; - } - - /* Get DMA state */ - state = hdma->State; - - /* Check DMA channel state */ - if ((hdma->State == HAL_DMA_STATE_BUSY) || (state == HAL_DMA_STATE_SUSPEND)) - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - /* Check queue state */ - if (pQList->State == HAL_DMA_QUEUE_STATE_BUSY) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_BUSY; - - return HAL_ERROR; - } - - /* Check linearity compatibility */ - if ((IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance) == 0U) && - ((pQList->Head->NodeInfo & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR)) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_UNSUPPORTED; - - return HAL_ERROR; - } - - /* Check circularity compatibility */ - if (hdma->Mode == DMA_LINKEDLIST_CIRCULAR) - { - /* Check first circular node */ - if (pQList->FirstCircularNode == NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - } - else - { - /* Check first circular node */ - if (pQList->FirstCircularNode != NULL) - { - /* Update the queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; - - return HAL_ERROR; - } - } - - /* Register queue to DMA handle */ - hdma->LinkedListQueue = pQList; - - return HAL_OK; -} - -/** - * @brief Unlink linked-list queue from a DMA channel. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_List_UnLinkQ(DMA_HandleTypeDef *const hdma) -{ - HAL_DMA_StateTypeDef state; - - /* Check the DMA channel parameter */ - if (hdma == NULL) - { - return HAL_ERROR; - } - - /* Get DMA state */ - state = hdma->State; - - /* Check DMA channel state */ - if ((hdma->State == HAL_DMA_STATE_BUSY) || (state == HAL_DMA_STATE_SUSPEND)) - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - /* Clear queue information from DMA channel handle */ - hdma->LinkedListQueue = NULL; - - return HAL_OK; -} -/** - * @} - */ - -/** @addtogroup DMAEx_Exported_Functions_Group4 - * -@verbatim - ====================================================================================================================== - ##### Data handling, repeated block and trigger configuration functions ##### - ====================================================================================================================== - [..] - This section provides functions allowing to : - (+) Configure DMA channel data handling. - (+) Configure DMA channel repeated block. - (+) Configure DMA channel trigger. - - [..] - (+) The HAL_DMAEx_ConfigDataHandling() function allows to configure DMA channel data handling. - (++) GPDMA or HPDMA data handling : byte-based reordering, packing/unpacking, padding/truncation, - sign extension and left/right alignment. - - (+) The HAL_DMAEx_ConfigTrigger() function allows to configure DMA channel HW triggers. - - (+) The HAL_DMAEx_ConfigRepeatBlock() function allows to configure DMA channel repeated block. - (++) This feature is available only for channel that supports 2 dimensions addressing capability. - -@endverbatim - * @{ - */ - -/** - * @brief Configure the DMA channel data handling according to the specified parameters in the - * DMA_DataHandlingConfTypeDef. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA Channel. - * @param pConfigDataHandling : Pointer to a DMA_DataHandlingConfTypeDef structure that contains the data handling - * configuration. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_ConfigDataHandling(DMA_HandleTypeDef *const hdma, - DMA_DataHandlingConfTypeDef const *const pConfigDataHandling) -{ - /* Check the DMA peripheral handle and data handling parameters */ - if ((hdma == NULL) || (pConfigDataHandling == NULL)) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_DMA_DATA_ALIGNMENT(pConfigDataHandling->DataAlignment)); - assert_param(IS_DMA_DATA_EXCHANGE(pConfigDataHandling->DataExchange)); - - /* Check DMA channel state */ - if (hdma->State == HAL_DMA_STATE_READY) - { - MODIFY_REG(hdma->Instance->CTR1, (DMA_CTR1_DWX | DMA_CTR1_DHX | DMA_CTR1_DBX | DMA_CTR1_SBX | DMA_CTR1_PAM), - (pConfigDataHandling->DataAlignment | pConfigDataHandling->DataExchange)); - } - else - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Configure the DMA channel trigger according to the specified parameters in the DMA_TriggerConfTypeDef. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for - * the specified DMA Channel. - * @param pConfigTrigger : Pointer to a DMA_TriggerConfTypeDef structure that contains the trigger configuration. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_ConfigTrigger(DMA_HandleTypeDef *const hdma, - DMA_TriggerConfTypeDef const *const pConfigTrigger) -{ - /* Check the DMA peripheral handle and trigger parameters */ - if ((hdma == NULL) || (pConfigTrigger == NULL)) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); - assert_param(IS_DMA_TRIGGER_POLARITY(pConfigTrigger->TriggerPolarity)); - assert_param(IS_DMA_TRIGGER_MODE(pConfigTrigger->TriggerMode)); - assert_param(IS_DMA_TRIGGER_SELECTION(pConfigTrigger->TriggerSelection)); - - /* Check DMA channel state */ - if (hdma->State == HAL_DMA_STATE_READY) - { - MODIFY_REG(hdma->Instance->CTR2, (DMA_CTR2_TRIGPOL | DMA_CTR2_TRIGSEL | DMA_CTR2_TRIGM), - (pConfigTrigger->TriggerPolarity | pConfigTrigger->TriggerMode | - (pConfigTrigger->TriggerSelection << DMA_CTR2_TRIGSEL_Pos))); - } - else - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Configure the DMA channel repeated block according to the specified parameters in the - * DMA_RepeatBlockConfTypeDef. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA Channel. - * @param pConfigRepeatBlock : Pointer to a DMA_RepeatBlockConfTypeDef structure that contains the repeated block - * configuration. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_ConfigRepeatBlock(DMA_HandleTypeDef *const hdma, - DMA_RepeatBlockConfTypeDef const *const pConfigRepeatBlock) -{ - uint32_t tmpreg1; - uint32_t tmpreg2; - - /* Check the DMA peripheral handle and repeated block parameters */ - if ((hdma == NULL) || (pConfigRepeatBlock == NULL)) - { - return HAL_ERROR; - } - - /* Check parameters */ - assert_param(IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance)); - assert_param(IS_DMA_REPEAT_COUNT(pConfigRepeatBlock->RepeatCount)); - assert_param(IS_DMA_BURST_ADDR_OFFSET(pConfigRepeatBlock->SrcAddrOffset)); - assert_param(IS_DMA_BURST_ADDR_OFFSET(pConfigRepeatBlock->DestAddrOffset)); - assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pConfigRepeatBlock->BlkSrcAddrOffset)); - assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pConfigRepeatBlock->BlkDestAddrOffset)); - - /* Check DMA channel state */ - if (hdma->State == HAL_DMA_STATE_READY) - { - /* Store repeat block count */ - tmpreg1 = ((pConfigRepeatBlock->RepeatCount - 1U) << DMA_CBR1_BRC_Pos); - - /* Check the sign of single/burst destination address offset value */ - if (pConfigRepeatBlock->DestAddrOffset < 0) - { - /* Store single/burst destination address offset configuration (signed case) */ - tmpreg1 |= DMA_CBR1_DDEC; - tmpreg2 = (uint32_t)(- pConfigRepeatBlock->DestAddrOffset); - tmpreg2 = tmpreg2 << DMA_CTR3_DAO_Pos; - } - else - { - /* Store single/burst destination address offset configuration (unsigned case) */ - tmpreg2 = ((uint32_t)pConfigRepeatBlock->DestAddrOffset << DMA_CTR3_DAO_Pos); - } - - /* Check the sign of single/burst source address offset value */ - if (pConfigRepeatBlock->SrcAddrOffset < 0) - { - /* Store single/burst source address offset configuration (signed case) */ - tmpreg1 |= DMA_CBR1_SDEC; - tmpreg2 |= (uint32_t)(- pConfigRepeatBlock->SrcAddrOffset); - } - else - { - /* Store single/burst source address offset configuration (unsigned case) */ - tmpreg2 |= (uint32_t)pConfigRepeatBlock->SrcAddrOffset; - } - - /* Write DMA Channel Transfer Register 3 (CTR3) */ - WRITE_REG(hdma->Instance->CTR3, tmpreg2); - - /* Check the sign of block destination address offset value */ - if (pConfigRepeatBlock->BlkDestAddrOffset < 0) - { - /* Store block destination address offset configuration (signed case) */ - tmpreg1 |= DMA_CBR1_BRDDEC; - tmpreg2 = (uint32_t)(- pConfigRepeatBlock->BlkDestAddrOffset); - tmpreg2 = tmpreg2 << DMA_CBR2_BRDAO_Pos; - } - else - { - /* Store block destination address offset configuration (unsigned case) */ - tmpreg2 = ((uint32_t)pConfigRepeatBlock->BlkDestAddrOffset << DMA_CBR2_BRDAO_Pos); - } - - /* Check the sign of block source address offset value */ - if (pConfigRepeatBlock->BlkSrcAddrOffset < 0) - { - /* Store block source address offset configuration (signed case) */ - tmpreg1 |= DMA_CBR1_BRSDEC; - tmpreg2 |= (uint32_t)(- pConfigRepeatBlock->BlkSrcAddrOffset); - } - else - { - /* Store block source address offset configuration (unsigned case) */ - tmpreg2 |= (uint32_t)pConfigRepeatBlock->BlkSrcAddrOffset; - } - - /* Write DMA Channel block register 2 (CBR2) */ - WRITE_REG(hdma->Instance->CBR2, tmpreg2); - - /* Write DMA Channel block register 1 (CBR1) */ - WRITE_REG(hdma->Instance->CBR1, tmpreg1); - } - else - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_BUSY; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - - return HAL_OK; -} -/** - * @} - */ - -/** @addtogroup DMAEx_Exported_Functions_Group5 - * -@verbatim - ====================================================================================================================== - ##### Suspend and resume operation functions ##### - ====================================================================================================================== - [..] - This section provides functions allowing to : - (+) Suspend any ongoing DMA channel transfer. - (+) Resume any suspended DMA channel transfer. - - [..] - (+) The HAL_DMAEx_Suspend() function allows to suspend any ongoing DMA channel transfer in polling mode (Blocking - mode). - - (+) The HAL_DMAEx_Suspend_IT() function allows to suspend any ongoing DMA channel transfer in interrupt mode - (Non-blocking mode). - - (+) The HAL_DMAEx_Resume() function allows to resume any suspended DMA channel transfer. - -@endverbatim - * @{ - */ - -/** - * @brief Suspend any ongoing DMA channel transfer in polling mode (Blocking mode). - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA channel. - * @note After suspending a DMA channel, a check for wait until the DMA channel is effectively suspended is added. If - * a channel is suspended while a data transfer is ongoing, the current data will be transferred and the - * channel will be effectively suspended only after the transfer of this single/burst data is finished. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_Suspend(DMA_HandleTypeDef *const hdma) -{ - /* Get tick number */ - uint32_t tickstart = HAL_GetTick(); - - /* Check the DMA peripheral handle */ - if (hdma == NULL) - { - return HAL_ERROR; - } - - /* Check DMA channel state */ - if (hdma->State != HAL_DMA_STATE_BUSY) - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - else - { - /* Suspend the channel */ - hdma->Instance->CCR |= DMA_CCR_SUSP; - - /* Check if the DMA channel is suspended */ - while ((hdma->Instance->CSR & DMA_CSR_SUSPF) == 0U) - { - /* Check for the timeout */ - if ((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) - { - /* Update the DMA channel error code */ - hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT; - - /* Update the DMA channel state */ - hdma->State = HAL_DMA_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - } - - /* Update the DMA channel state */ - hdma->State = HAL_DMA_STATE_SUSPEND; - } - - return HAL_OK; -} - -/** - * @brief Suspend any ongoing DMA channel transfer in polling mode (Non-blocking mode). - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_Suspend_IT(DMA_HandleTypeDef *const hdma) -{ - /* Check the DMA peripheral handle parameter */ - if (hdma == NULL) - { - return HAL_ERROR; - } - - /* Check DMA channel state */ - if (hdma->State != HAL_DMA_STATE_BUSY) - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - else - { - /* Suspend the DMA channel and activate suspend interrupt */ - hdma->Instance->CCR |= (DMA_CCR_SUSP | DMA_CCR_SUSPIE); - } - - return HAL_OK; -} - -/** - * @brief Resume any suspended DMA channel transfer. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DMAEx_Resume(DMA_HandleTypeDef *const hdma) -{ - /* Check the DMA peripheral handle parameter */ - if (hdma == NULL) - { - return HAL_ERROR; - } - - /* Check DMA channel state */ - if (hdma->State != HAL_DMA_STATE_SUSPEND) - { - /* Update the DMA channel error code */ - hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; - - /* Process unlocked */ - __HAL_UNLOCK(hdma); - - return HAL_ERROR; - } - else - { - /* Resume the DMA channel */ - hdma->Instance->CCR &= (~DMA_CCR_SUSP); - - /* Clear the suspend flag */ - hdma->Instance->CFCR |= DMA_CFCR_SUSPF; - - /* Update the DMA channel state */ - hdma->State = HAL_DMA_STATE_BUSY; - } - - return HAL_OK; -} -/** - * @} - */ - -/** @addtogroup DMAEx_Exported_Functions_Group6 - * -@verbatim - ====================================================================================================================== - ##### Fifo status function ##### - ====================================================================================================================== - [..] - This section provides function allowing to get DMA channel FIFO level. - - [..] - (+) The HAL_DMAEx_GetFifoLevel() function allows to return the number of available write beats in the FIFO, in - units of the programmed destination data. - (++) This API is available only for DMA channels that supports FIFO. - -@endverbatim - * @{ - */ - -/** - * @brief Get and returns the DMA channel FIFO level. - * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval Returns the number of available beats in FIFO. - */ -uint32_t HAL_DMAEx_GetFifoLevel(DMA_HandleTypeDef const *const hdma) -{ - return ((hdma->Instance->CSR & DMA_CSR_FIFOL) >> DMA_CSR_FIFOL_Pos); -} -/** - * @} - */ - -/** - * @} - */ - -/* Private functions -------------------------------------------------------------------------------------------------*/ -/** @defgroup DMAEx_Private_Functions DMAEx Private Functions - * @brief DMAEx Private Functions - * @{ - */ - -/** - * @brief Initialize the DMA handle according to the specified parameters in the DMA_InitTypeDef. - * @param hdma : pointer to a DMA_HandleTypeDef structure that contains the configuration information for the - * specified DMA Channel. - * @retval None. - */ -static void DMA_List_Init(DMA_HandleTypeDef const *const hdma) -{ - uint32_t tmpreg; - - /* Prepare DMA Channel Control Register (CCR) value */ - tmpreg = hdma->InitLinkedList.Priority | hdma->InitLinkedList.LinkStepMode; - - /* Check DMA channel instance */ - if ((IS_HPDMA_INSTANCE(hdma->Instance) != 0U) || (IS_GPDMA_INSTANCE(hdma->Instance) != 0U)) - { - tmpreg |= hdma->InitLinkedList.LinkAllocatedPort; - } - - /* Write DMA Channel Control Register (CCR) */ - MODIFY_REG(hdma->Instance->CCR, DMA_CCR_PRIO | DMA_CCR_LAP | DMA_CCR_LSM, tmpreg); - - /* Write DMA Channel Control Register (CTR1) */ - WRITE_REG(hdma->Instance->CTR1, 0U); - - /* Write DMA Channel Control Register (CTR2) */ - WRITE_REG(hdma->Instance->CTR2, hdma->InitLinkedList.TransferEventMode); - - /* Write DMA Channel Control Register (CBR1) */ - WRITE_REG(hdma->Instance->CBR1, 0U); - - /* Write DMA Channel Control Register (CSAR) */ - WRITE_REG(hdma->Instance->CSAR, 0U); - - /* Write DMA Channel Control Register (CDAR) */ - WRITE_REG(hdma->Instance->CDAR, 0U); - - /* If 2D Addressing is supported by current channel */ - if (IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance) != 0U) - { - /* Write DMA Channel Control Register (CTR3) */ - WRITE_REG(hdma->Instance->CTR3, 0U); - - /* Write DMA Channel Control Register (CBR2) */ - WRITE_REG(hdma->Instance->CBR2, 0U); - } - - /* Write DMA Channel linked-list address register (CLLR) */ - WRITE_REG(hdma->Instance->CLLR, 0U); -} - -/** - * @brief Build a DMA channel node according to the specified parameters in the DMA_NodeConfTypeDef. - * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the - * specified DMA linked-list Node. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @retval None. - */ -static void DMA_List_BuildNode(DMA_NodeConfTypeDef const *const pNodeConfig, - DMA_NodeTypeDef *const pNode) -{ - int32_t blockoffset; - - /* Update CTR1 register value ***************************************************************************************/ - /* Prepare DMA channel transfer register (CTR1) value */ - pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] = pNodeConfig->Init.DestInc | - pNodeConfig->Init.DestDataWidth | - pNodeConfig->DataHandlingConfig.DataAlignment | - pNodeConfig->Init.SrcInc | - pNodeConfig->Init.SrcDataWidth; - - - /* Add parameters related to DMA configuration */ - if ((pNodeConfig->NodeType & (DMA_CHANNEL_TYPE_GPDMA | DMA_CHANNEL_TYPE_HPDMA)) != 0U) - { - /* Prepare DMA channel transfer register (CTR1) value */ - pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] |= - (pNodeConfig->Init.TransferAllocatedPort | pNodeConfig->DataHandlingConfig.DataExchange | - (((pNodeConfig->Init.DestBurstLength - 1U) << DMA_CTR1_DBL_1_Pos) & DMA_CTR1_DBL_1) | - (((pNodeConfig->Init.SrcBurstLength - 1U) << DMA_CTR1_SBL_1_Pos) & DMA_CTR1_SBL_1)); - } - /*********************************************************************************** CTR1 register value is updated */ - - - /* Update CTR2 register value ***************************************************************************************/ - /* Prepare DMA channel transfer register 2 (CTR2) value */ - pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] = pNodeConfig->Init.TransferEventMode | - (pNodeConfig->Init.Request & (DMA_CTR2_REQSEL | DMA_CTR2_SWREQ)); - - /* Check for memory to peripheral transfer */ - if ((pNodeConfig->Init.Direction) == DMA_MEMORY_TO_PERIPH) - { - /* Check for GPDMA OR HPDMA */ - if ((pNodeConfig->NodeType & (DMA_CHANNEL_TYPE_GPDMA | DMA_CHANNEL_TYPE_HPDMA)) != 0U) - { - pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= DMA_CTR2_DREQ; - } - } - /* Memory to memory transfer */ - else if ((pNodeConfig->Init.Direction) == DMA_MEMORY_TO_MEMORY) - { - pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= DMA_CTR2_SWREQ; - } - else - { - /* Prevent MISRA-C2012-Rule-15.7 */ - } - - /* Configure HW Peripheral flow control selection */ - pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= pNodeConfig->Init.Mode; - - /* Check if trigger feature is active */ - if (pNodeConfig->TriggerConfig.TriggerPolarity != DMA_TRIG_POLARITY_MASKED) - { - /* Prepare DMA channel transfer register 2 (CTR2) value */ - pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= - pNodeConfig->TriggerConfig.TriggerMode | pNodeConfig->TriggerConfig.TriggerPolarity | - ((pNodeConfig->TriggerConfig.TriggerSelection << DMA_CTR2_TRIGSEL_Pos) & DMA_CTR2_TRIGSEL); - } - /*********************************************************************************** CTR2 register value is updated */ - - - /* Update CBR1 register value ***************************************************************************************/ - /* Prepare DMA channel block register 1 (CBR1) value */ - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (pNodeConfig->DataSize & DMA_CBR1_BNDT); - - /* If 2D addressing is supported by the selected DMA channel */ - if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - /* Set the new CBR1 Register value */ - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= - (((pNodeConfig->RepeatBlockConfig.RepeatCount - 1U) << DMA_CBR1_BRC_Pos) & DMA_CBR1_BRC); - - /* If the source address offset is negative, set SDEC bit */ - if (pNodeConfig->RepeatBlockConfig.SrcAddrOffset < 0) - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_SDEC; - } - else - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_SDEC); - } - - /* If the destination address offset is negative, set DDEC bit */ - if (pNodeConfig->RepeatBlockConfig.DestAddrOffset < 0) - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_DDEC; - } - else - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_DDEC); - } - - /* If the repeated block source address offset is negative, set BRSEC bit */ - if (pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset < 0) - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_BRSDEC; - } - else - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_BRSDEC); - } - - /* if the repeated block destination address offset is negative, set BRDEC bit */ - if (pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset < 0) - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_BRDDEC; - } - else - { - pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_BRDDEC); - } - } - /*********************************************************************************** CBR1 register value is updated */ - - - /* Update CSAR register value ***************************************************************************************/ - pNode->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = pNodeConfig->SrcAddress; - /*********************************************************************************** CSAR register value is updated */ - - - /* Update CDAR register value ***************************************************************************************/ - pNode->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = pNodeConfig->DstAddress; - /*********************************************************************************** CDAR register value is updated */ - - /* Check if the selected channel is 2D addressing */ - if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - /* Update CTR3 register value *************************************************************************************/ - /* Write new CTR3 Register value : source address offset */ - if (pNodeConfig->RepeatBlockConfig.SrcAddrOffset < 0) - { - blockoffset = (- pNodeConfig->RepeatBlockConfig.SrcAddrOffset); - pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] = ((uint32_t)blockoffset & DMA_CTR3_SAO); - } - else - { - pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] = - ((uint32_t)pNodeConfig->RepeatBlockConfig.SrcAddrOffset & DMA_CTR3_SAO); - } - - /* Write new CTR3 Register value : destination address offset */ - if (pNodeConfig->RepeatBlockConfig.DestAddrOffset < 0) - { - blockoffset = (- pNodeConfig->RepeatBlockConfig.DestAddrOffset); - pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] |= (((uint32_t)blockoffset << DMA_CTR3_DAO_Pos) & DMA_CTR3_DAO); - } - else - { - pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] |= - (((uint32_t)pNodeConfig->RepeatBlockConfig.DestAddrOffset << DMA_CTR3_DAO_Pos) & DMA_CTR3_DAO); - } - /********************************************************************************* CTR3 register value is updated */ - - - /* Update CBR2 register value *************************************************************************************/ - /* Write new CBR2 Register value : repeated block source address offset */ - if (pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset < 0) - { - blockoffset = (- pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset); - pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] = ((uint32_t)blockoffset & DMA_CBR2_BRSAO); - } - else - { - pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] = - ((uint32_t)pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset & DMA_CBR2_BRSAO); - } - - /* Write new CBR2 Register value : repeated block destination address offset */ - if (pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset < 0) - { - blockoffset = (- pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset); - pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] |= - (((uint32_t)blockoffset & DMA_CBR2_BRSAO) << DMA_CBR2_BRDAO_Pos); - } - else - { - pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] |= - (((uint32_t)pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset << DMA_CBR2_BRDAO_Pos) & DMA_CBR2_BRDAO); - } - /********************************************************************************* CBR2 register value is updated */ - } - - - /* Update node information value ************************************************************************************/ - /* Set node information */ - pNode->NodeInfo = pNodeConfig->NodeType; - if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - pNode->NodeInfo |= (NODE_CLLR_2D_DEFAULT_OFFSET << NODE_CLLR_IDX_POS); - } - else - { - pNode->NodeInfo |= (NODE_CLLR_LINEAR_DEFAULT_OFFSET << NODE_CLLR_IDX_POS); - } - /******************************************************************************** Node information value is updated */ -} - -/** - * @brief Get a DMA channel node configuration. - * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the - * specified DMA linked-list Node. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @retval None. - */ -static void DMA_List_GetNodeConfig(DMA_NodeConfTypeDef *const pNodeConfig, - DMA_NodeTypeDef const *const pNode) -{ - uint16_t offset; - - /* Get node information *********************************************************************************************/ - pNodeConfig->NodeType = (pNode->NodeInfo & NODE_TYPE_MASK); - /*************************************************************************************** Node type value is updated */ - - - /* Get CTR1 fields values *******************************************************************************************/ - pNodeConfig->Init.SrcInc = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_SINC; - pNodeConfig->Init.DestInc = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DINC; - pNodeConfig->Init.SrcDataWidth = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_SDW_LOG2; - pNodeConfig->Init.DestDataWidth = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - pNodeConfig->Init.SrcBurstLength = ((pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & - DMA_CTR1_SBL_1) >> DMA_CTR1_SBL_1_Pos) + 1U; - pNodeConfig->Init.DestBurstLength = ((pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & - DMA_CTR1_DBL_1) >> DMA_CTR1_DBL_1_Pos) + 1U; - pNodeConfig->Init.TransferAllocatedPort = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & - (DMA_CTR1_SAP | DMA_CTR1_DAP); - pNodeConfig->DataHandlingConfig.DataExchange = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & - (DMA_CTR1_SBX | DMA_CTR1_DBX | DMA_CTR1_DHX | DMA_CTR1_DWX); - pNodeConfig->DataHandlingConfig.DataAlignment = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_PAM; - /*********************************************************************************** CTR1 fields values are updated */ - - - /* Get CTR2 fields values *******************************************************************************************/ - if ((pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_SWREQ) != 0U) - { - pNodeConfig->Init.Request = DMA_REQUEST_SW; - pNodeConfig->Init.Direction = DMA_MEMORY_TO_MEMORY; - } - else - { - pNodeConfig->Init.Request = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_REQSEL; - - if ((pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_DREQ) != 0U) - { - pNodeConfig->Init.Direction = DMA_MEMORY_TO_PERIPH; - } - else - { - pNodeConfig->Init.Direction = DMA_PERIPH_TO_MEMORY; - } - } - - pNodeConfig->Init.BlkHWRequest = (pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_BREQ); - pNodeConfig->TriggerConfig.TriggerMode = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_TRIGM; - pNodeConfig->TriggerConfig.TriggerPolarity = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_TRIGPOL; - pNodeConfig->TriggerConfig.TriggerSelection = (pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & - DMA_CTR2_TRIGSEL) >> DMA_CTR2_TRIGSEL_Pos; - pNodeConfig->Init.TransferEventMode = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_TCEM; - /*********************************************************************************** CTR2 fields values are updated */ - - - /* Get CBR1 fields **************************************************************************************************/ - pNodeConfig->DataSize = pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BNDT; - - if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - pNodeConfig->RepeatBlockConfig.RepeatCount = - ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BRC) >> DMA_CBR1_BRC_Pos) + 1U; - } - else - { - pNodeConfig->RepeatBlockConfig.RepeatCount = 1U; - } - /*********************************************************************************** CBR1 fields values are updated */ - - - /* Get CSAR field ***************************************************************************************************/ - pNodeConfig->SrcAddress = pNode->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET]; - /************************************************************************************** CSAR field value is updated */ - - - /* Get CDAR field ***************************************************************************************************/ - pNodeConfig->DstAddress = pNode->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET]; - /************************************************************************************** CDAR field value is updated */ - - /* Check if the selected channel is 2D addressing */ - if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - /* Get CTR3 field *************************************************************************************************/ - offset = (uint16_t)(pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] & DMA_CTR3_SAO); - pNodeConfig->RepeatBlockConfig.SrcAddrOffset = (int32_t)offset; - - offset = (uint16_t)((pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] & DMA_CTR3_DAO) >> DMA_CTR3_DAO_Pos); - pNodeConfig->RepeatBlockConfig.DestAddrOffset = (int32_t)offset; - - if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_SDEC) != 0U) - { - pNodeConfig->RepeatBlockConfig.SrcAddrOffset *= (-1); - } - - if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_DDEC) != 0U) - { - pNodeConfig->RepeatBlockConfig.DestAddrOffset *= (-1); - } - /************************************************************************************ CTR3 field value is updated */ - - - /* Get CBR2 fields ************************************************************************************************/ - offset = (uint16_t)(pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] & DMA_CBR2_BRSAO); - pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset = (int32_t)offset; - - offset = (uint16_t)((pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] & DMA_CBR2_BRDAO) >> DMA_CBR2_BRDAO_Pos); - pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset = (int32_t)offset; - - if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BRSDEC) != 0U) - { - pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset *= (-1); - } - - if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BRDDEC) != 0U) - { - pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset *= (-1); - } - /************************************************************************************ CBR2 field value is updated */ - } - else - { - /* Get CTR3 field *************************************************************************************************/ - pNodeConfig->RepeatBlockConfig.SrcAddrOffset = 0; - pNodeConfig->RepeatBlockConfig.DestAddrOffset = 0; - /************************************************************************************ CTR3 field value is updated */ - - - /* Get CBR2 fields ************************************************************************************************/ - pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset = 0; - pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset = 0; - /************************************************************************************ CBR2 field value is updated */ - } -} - -/** - * @brief Check nodes base addresses compatibility. - * @param pNode1 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 1 registers configurations. - * @param pNode2 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 2 registers configurations. - * @param pNode3 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 3 registers configurations. - * @retval Return 0 when nodes addresses are compatible, 1 otherwise. - */ -static uint32_t DMA_List_CheckNodesBaseAddresses(DMA_NodeTypeDef const *const pNode1, - DMA_NodeTypeDef const *const pNode2, - DMA_NodeTypeDef const *const pNode3) -{ - uint32_t temp = (((uint32_t)pNode1 | (uint32_t)pNode2 | (uint32_t)pNode3) & DMA_CLBAR_LBA); - uint32_t ref = 0U; - - /* Check node 1 address */ - if ((uint32_t)pNode1 != 0U) - { - ref = (uint32_t)pNode1; - } - /* Check node 2 address */ - else if ((uint32_t)pNode2 != 0U) - { - ref = (uint32_t)pNode2; - } - /* Check node 3 address */ - else if ((uint32_t)pNode3 != 0U) - { - ref = (uint32_t)pNode3; - } - else - { - /* Prevent MISRA-C2012-Rule-15.7 */ - } - - /* Check addresses compatibility */ - if (temp != ((uint32_t)ref & DMA_CLBAR_LBA)) - { - return 1U; - } - - return 0U; -} - -/** - * @brief Check nodes types compatibility. - * @param pNode1 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 1 registers configurations. - * @param pNode2 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 2 registers configurations. - * @param pNode3 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 3 registers configurations. - * @retval Return 0 when nodes types are compatible, otherwise nodes types are not compatible. - */ -static uint32_t DMA_List_CheckNodesTypes(DMA_NodeTypeDef const *const pNode1, - DMA_NodeTypeDef const *const pNode2, - DMA_NodeTypeDef const *const pNode3) -{ - uint32_t ref = 0U; - - /* Check node 1 parameter */ - if (pNode1 != NULL) - { - ref = pNode1->NodeInfo & NODE_TYPE_MASK; - } - /* Check node 2 parameter */ - else if (pNode2 != NULL) - { - ref = pNode2->NodeInfo & NODE_TYPE_MASK; - } - /* Check node 3 parameter */ - else if (pNode3 != NULL) - { - ref = pNode3->NodeInfo & NODE_TYPE_MASK; - } - else - { - /* Prevent MISRA-C2012-Rule-15.7 */ - } - - /* Check node 2 parameter */ - if (pNode2 != NULL) - { - /* Check node type compatibility */ - if (ref != (pNode2->NodeInfo & NODE_TYPE_MASK)) - { - return 2U; - } - } - - /* Check node 3 parameter */ - if (pNode3 != NULL) - { - /* Check node type compatibility */ - if (ref != (pNode3->NodeInfo & NODE_TYPE_MASK)) - { - return 3U; - } - } - - return 0U; -} - -/** - * @brief Check nodes types compatibility. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @param cllr_mask : Pointer to CLLR register mask value. - * @param cllr_offset : Pointer to CLLR register offset value. - * @retval None. - */ -static void DMA_List_GetCLLRNodeInfo(DMA_NodeTypeDef const *const pNode, - uint32_t *const cllr_mask, - uint32_t *const cllr_offset) -{ - /* Check node type */ - if ((pNode->NodeInfo & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) - { - /* Update CLLR register mask value */ - if (cllr_mask != NULL) - { - *cllr_mask = DMA_CLLR_UT1 | DMA_CLLR_UT2 | DMA_CLLR_UB1 | DMA_CLLR_USA | DMA_CLLR_UDA | DMA_CLLR_UT3 | - DMA_CLLR_UB2 | DMA_CLLR_ULL; - } - - /* Update CLLR register offset */ - if (cllr_offset != NULL) - { - *cllr_offset = NODE_CLLR_2D_DEFAULT_OFFSET; - } - } - /* Update CLLR and register number for linear addressing node */ - else - { - /* Update CLLR register mask value */ - if (cllr_mask != NULL) - { - *cllr_mask = DMA_CLLR_UT1 | DMA_CLLR_UT2 | DMA_CLLR_UB1 | DMA_CLLR_USA | DMA_CLLR_UDA | DMA_CLLR_ULL; - } - - /* Update CLLR register offset */ - if (cllr_offset != NULL) - { - *cllr_offset = NODE_CLLR_LINEAR_DEFAULT_OFFSET; - } - } -} - -/** - * @brief Find node in queue. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers configurations. - * @param NodeInfo : Pointer to a DMA_NodeInQInfoTypeDef structure that contains node linked to queue information. - * @retval Return 0 when node is found in selected queue, otherwise node is not found. - */ -static uint32_t DMA_List_FindNode(DMA_QListTypeDef const *const pQList, - DMA_NodeTypeDef const *const pNode, - DMA_NodeInQInfoTypeDef *const NodeInfo) -{ - uint32_t node_idx = 0U; - uint32_t currentnode_address = 0U; - uint32_t previousnode_address = 0U; - uint32_t cllr_offset = NodeInfo->cllr_offset; - - /* Find last node in queue */ - if (pNode == NULL) - { - /* Check that previous node is linked to the selected queue */ - while (node_idx < pQList->NodeNumber) - { - /* Get head node address */ - if (node_idx == 0U) - { - currentnode_address = (uint32_t)pQList->Head & DMA_CLLR_LA; - } - /* Calculate nodes addresses */ - else - { - previousnode_address = currentnode_address; - currentnode_address = - ((DMA_NodeTypeDef *)(currentnode_address + - ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] & DMA_CLLR_LA; - } - - /* Increment node index */ - node_idx++; - } - } - /* Find selected node node in queue */ - else - { - /* Check that previous node is linked to the selected queue */ - while ((node_idx < pQList->NodeNumber) && (currentnode_address != ((uint32_t)pNode & DMA_CLLR_LA))) - { - /* Get head node address */ - if (node_idx == 0U) - { - currentnode_address = (uint32_t)pQList->Head & DMA_CLLR_LA; - } - /* Calculate nodes addresses */ - else - { - previousnode_address = currentnode_address; - currentnode_address = - ((DMA_NodeTypeDef *)(currentnode_address + - ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] & DMA_CLLR_LA; - } - - /* Increment node index */ - node_idx++; - } - } - - /* Check stored address */ - if (pNode != NULL) - { - if (currentnode_address != ((uint32_t)pNode & DMA_CLLR_LA)) - { - return 1U; - } - } - - /* Update current node position */ - NodeInfo->currentnode_pos = node_idx; - - /* Update previous node address */ - NodeInfo->previousnode_addr = previousnode_address | ((uint32_t)pQList->Head & DMA_CLBAR_LBA); - - /* Update current node address */ - NodeInfo->currentnode_addr = currentnode_address | ((uint32_t)pQList->Head & DMA_CLBAR_LBA); - - /* Update next node address */ - if (((DMA_NodeTypeDef *)NodeInfo->currentnode_addr)->LinkRegisters[cllr_offset] != 0U) - { - NodeInfo->nextnode_addr = (((DMA_NodeTypeDef *)NodeInfo->currentnode_addr)->LinkRegisters[cllr_offset] & - DMA_CLLR_LA) | ((uint32_t)pQList->Head & DMA_CLBAR_LBA); - } - - return 0U; -} - -/** - * @brief Reset queue nodes. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param NodeInfo : Pointer to a DMA_NodeInQInfoTypeDef structure that contains node linked to queue information. - * @retval None. - */ -static void DMA_List_ResetQueueNodes(DMA_QListTypeDef const *const pQList, - DMA_NodeInQInfoTypeDef const *const NodeInfo) -{ - uint32_t node_idx = 0U; - uint32_t currentnode_address = 0U; - uint32_t previousnode_address; - uint32_t cllr_offset = NodeInfo->cllr_offset; - - /* Check that previous node is linked to the selected queue */ - while (node_idx < pQList->NodeNumber) - { - /* Get head node address */ - if (node_idx == 0U) - { - previousnode_address = (uint32_t)pQList->Head & DMA_CLLR_LA; - currentnode_address = (pQList->Head->LinkRegisters[cllr_offset] & DMA_CLLR_LA); - } - /* Calculate nodes addresses */ - else - { - previousnode_address = currentnode_address; - currentnode_address = - ((DMA_NodeTypeDef *)(currentnode_address + - ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] & DMA_CLLR_LA; - } - - /* Reset node */ - ((DMA_NodeTypeDef *)(previousnode_address + - ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] = 0U; - - /* Increment node index */ - node_idx++; - } -} - -/** - * @brief Fill source node registers values by destination nodes registers values. - * @param pSrcNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list source node registers - * configurations. - * @param pDestNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list destination node registers - * configurations. - * @retval None. - */ -static void DMA_List_FillNode(DMA_NodeTypeDef const *const pSrcNode, - DMA_NodeTypeDef *const pDestNode) -{ - /* Repeat for all register nodes */ - for (uint32_t reg_idx = 0U; reg_idx < NODE_MAXIMUM_SIZE; reg_idx++) - { - pDestNode->LinkRegisters[reg_idx] = pSrcNode->LinkRegisters[reg_idx]; - } - - /* Fill node information */ - pDestNode->NodeInfo = pSrcNode->NodeInfo; -} - -/** - * @brief Convert node to dynamic. - * @param ContextNodeAddr : The context node address. - * @param CurrentNodeAddr : The current node address to be converted. - * @param RegisterNumber : The register number to be converted. - * @retval None. - */ -static void DMA_List_ConvertNodeToDynamic(uint32_t ContextNodeAddr, - uint32_t CurrentNodeAddr, - uint32_t RegisterNumber) -{ - uint32_t currentnode_reg_counter = 0U; - uint32_t contextnode_reg_counter = 0U; - uint32_t cllr_idx = RegisterNumber - 1U; - DMA_NodeTypeDef *context_node = (DMA_NodeTypeDef *)ContextNodeAddr; - DMA_NodeTypeDef *current_node = (DMA_NodeTypeDef *)CurrentNodeAddr; - uint32_t update_link[NODE_MAXIMUM_SIZE] = {DMA_CLLR_UT1, DMA_CLLR_UT2, DMA_CLLR_UB1, DMA_CLLR_USA, - DMA_CLLR_UDA, DMA_CLLR_UT3, DMA_CLLR_UB2, DMA_CLLR_ULL - }; - - /* Update ULL position according to register number */ - update_link[cllr_idx] = update_link[NODE_MAXIMUM_SIZE - 1U]; - - /* Repeat for all node registers */ - while (contextnode_reg_counter != RegisterNumber) - { - /* Check if register values are equal (exception for CSAR, CDAR and CLLR registers) */ - if ((context_node->LinkRegisters[contextnode_reg_counter] == - current_node->LinkRegisters[currentnode_reg_counter]) && - (contextnode_reg_counter != NODE_CSAR_DEFAULT_OFFSET) && - (contextnode_reg_counter != NODE_CDAR_DEFAULT_OFFSET) && - (contextnode_reg_counter != (RegisterNumber - 1U))) - { - /* Format the node according to unused registers */ - DMA_List_FormatNode(current_node, currentnode_reg_counter, RegisterNumber, NODE_DYNAMIC_FORMAT); - - /* Update CLLR index */ - cllr_idx --; - - /* Update CLLR fields */ - current_node->LinkRegisters[cllr_idx] &= ~update_link[contextnode_reg_counter]; - } - else - { - /* Update context node register fields with new values */ - context_node->LinkRegisters[contextnode_reg_counter] = current_node->LinkRegisters[currentnode_reg_counter]; - - /* Update CLLR fields */ - current_node->LinkRegisters[cllr_idx] |= update_link[contextnode_reg_counter]; - - /* Increment current node number register counter */ - currentnode_reg_counter++; - } - - /* Increment context node number register counter */ - contextnode_reg_counter++; - } - - /* Update node information */ - MODIFY_REG(current_node->NodeInfo, NODE_CLLR_IDX, ((currentnode_reg_counter - 1U) << NODE_CLLR_IDX_POS)); - - /* Clear unused node fields */ - DMA_List_ClearUnusedFields(current_node, currentnode_reg_counter); -} - -/** - * @brief Convert node to static. - * @param ContextNodeAddr : The context node address. - * @param CurrentNodeAddr : The current node address to be converted. - * @param RegisterNumber : The register number to be converted. - * @retval None. - */ -static void DMA_List_ConvertNodeToStatic(uint32_t ContextNodeAddr, - uint32_t CurrentNodeAddr, - uint32_t RegisterNumber) -{ - uint32_t contextnode_reg_counter = 0U; - uint32_t cllr_idx; - uint32_t cllr_mask; - const DMA_NodeTypeDef *context_node = (DMA_NodeTypeDef *)ContextNodeAddr; - DMA_NodeTypeDef *current_node = (DMA_NodeTypeDef *)CurrentNodeAddr; - uint32_t update_link[NODE_MAXIMUM_SIZE] = {DMA_CLLR_UT1, DMA_CLLR_UT2, DMA_CLLR_UB1, DMA_CLLR_USA, - DMA_CLLR_UDA, DMA_CLLR_UT3, DMA_CLLR_UB2, DMA_CLLR_ULL - }; - - /* Update ULL position according to register number */ - update_link[RegisterNumber - 1U] = update_link[NODE_MAXIMUM_SIZE - 1U]; - - /* Get context node CLLR information */ - cllr_idx = (context_node->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; - cllr_mask = context_node->LinkRegisters[cllr_idx]; - - /* Repeat for all node registers */ - while (contextnode_reg_counter != RegisterNumber) - { - /* Check if node field is dynamic */ - if ((cllr_mask & update_link[contextnode_reg_counter]) == 0U) - { - /* Format the node according to unused registers */ - DMA_List_FormatNode(current_node, contextnode_reg_counter, RegisterNumber, NODE_STATIC_FORMAT); - - /* Update node field */ - current_node->LinkRegisters[contextnode_reg_counter] = context_node->LinkRegisters[contextnode_reg_counter]; - } - - /* Increment context node number register counter */ - contextnode_reg_counter++; - } - - /* Update node information */ - MODIFY_REG(current_node->NodeInfo, NODE_CLLR_IDX, ((RegisterNumber - 1U) << NODE_CLLR_IDX_POS)); -} - -/** - * @brief Format the node according to unused registers. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @param RegisterIdx : The first register index to be formatted. - * @param RegisterNumber : The number of node registers. - * @param Format : The format type. - * @retval None. - */ -static void DMA_List_FormatNode(DMA_NodeTypeDef *const pNode, - uint32_t RegisterIdx, - uint32_t RegisterNumber, - uint32_t Format) -{ - if (Format == NODE_DYNAMIC_FORMAT) - { - /* Repeat for all registers to be formatted */ - for (uint32_t reg_idx = RegisterIdx; reg_idx < (RegisterNumber - 1U); reg_idx++) - { - pNode->LinkRegisters[reg_idx] = pNode->LinkRegisters[reg_idx + 1U]; - } - } - else - { - /* Repeat for all registers to be formatted */ - for (uint32_t reg_idx = (RegisterNumber - 2U); reg_idx > RegisterIdx; reg_idx--) - { - pNode->LinkRegisters[reg_idx] = pNode->LinkRegisters[reg_idx - 1U]; - } - } -} - -/** - * @brief Clear unused register fields. - * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers - * configurations. - * @param FirstUnusedField : The first unused field to be cleared. - * @retval None. - */ -static void DMA_List_ClearUnusedFields(DMA_NodeTypeDef *const pNode, - uint32_t FirstUnusedField) -{ - /* Repeat for all unused fields */ - for (uint32_t reg_idx = FirstUnusedField; reg_idx < NODE_MAXIMUM_SIZE; reg_idx++) - { - pNode->LinkRegisters[reg_idx] = 0U; - } -} - -/** - * @brief Update CLLR for all dynamic queue nodes. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param LastNode_IsCircular : The first circular node is the last queue node or not. - * @retval None. - */ -static void DMA_List_UpdateDynamicQueueNodesCLLR(DMA_QListTypeDef const *const pQList, - uint32_t LastNode_IsCircular) -{ - uint32_t previous_cllr_offset; - uint32_t current_cllr_offset = 0U; - uint32_t previousnode_addr; - uint32_t currentnode_addr = (uint32_t)pQList->Head; - uint32_t cllr_mask; - uint32_t node_idx = 0U; - - /* Repeat for all register nodes */ - while (node_idx < pQList->NodeNumber) - { - /* Get head node address */ - if (node_idx == 0U) - { - /* Get current node information */ - current_cllr_offset = (((DMA_NodeTypeDef *)currentnode_addr)->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; - } - /* Calculate nodes addresses */ - else - { - /* Get previous node information */ - previousnode_addr = currentnode_addr; - previous_cllr_offset = current_cllr_offset; - - /* Get current node information */ - currentnode_addr = (((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[previous_cllr_offset] & DMA_CLLR_LA) + - ((uint32_t)pQList->Head & DMA_CLBAR_LBA); - current_cllr_offset = (((DMA_NodeTypeDef *)currentnode_addr)->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; - - /* Calculate CLLR register value to be updated */ - cllr_mask = (((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] & ~DMA_CLLR_LA) | - (((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[previous_cllr_offset] & DMA_CLLR_LA); - - /* Set new CLLR value to previous node */ - ((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[previous_cllr_offset] = cllr_mask; - } - - /* Increment node index */ - node_idx++; - } - - /* Check queue circularity */ - if (pQList->FirstCircularNode != 0U) - { - /* First circular queue is not last queue node */ - if (LastNode_IsCircular == 0U) - { - /* Get CLLR node information */ - DMA_List_GetCLLRNodeInfo(((DMA_NodeTypeDef *)currentnode_addr), &cllr_mask, NULL); - - /* Update CLLR register for last circular node */ - ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] = - ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; - } - /* First circular queue is last queue node */ - else - { - /* Disable CLLR updating */ - ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] &= ~DMA_CLLR_ULL; - } - } - else - { - /* Clear CLLR register for last node */ - ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] = 0U; - } -} - -/** - * @brief Update CLLR for all static queue nodes. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @param operation : The operation type. - * @retval None. - */ -static void DMA_List_UpdateStaticQueueNodesCLLR(DMA_QListTypeDef const *const pQList, - uint32_t operation) -{ - uint32_t currentnode_addr = (uint32_t)pQList->Head; - uint32_t current_cllr_offset = ((uint32_t)pQList->Head->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; - uint32_t cllr_default_offset; - uint32_t cllr_default_mask; - uint32_t cllr_mask; - uint32_t node_idx = 0U; - - /* Get CLLR node information */ - DMA_List_GetCLLRNodeInfo(pQList->Head, &cllr_default_mask, &cllr_default_offset); - - /* Repeat for all register nodes (Bypass last queue node) */ - while (node_idx < pQList->NodeNumber) - { - if (operation == UPDATE_CLLR_POSITION) - { - /* Get CLLR value */ - cllr_mask = ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset]; - } - else - { - /* Calculate CLLR value */ - cllr_mask = (((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] & DMA_CLLR_LA) | - cllr_default_mask; - } - - /* Set new CLLR value to default position */ - if ((node_idx == (pQList->NodeNumber - 1U)) && (pQList->FirstCircularNode == NULL)) - { - ((DMA_NodeTypeDef *)(currentnode_addr))->LinkRegisters[cllr_default_offset] = 0U; - } - else - { - ((DMA_NodeTypeDef *)(currentnode_addr))->LinkRegisters[cllr_default_offset] = cllr_mask; - } - - /* Update current node address with next node address */ - currentnode_addr = (currentnode_addr & DMA_CLBAR_LBA) | (cllr_mask & DMA_CLLR_LA); - - /* Update current CLLR offset with next CLLR offset */ - current_cllr_offset = (((DMA_NodeTypeDef *)currentnode_addr)->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; - - /* Increment node index */ - node_idx++; - } -} - -/** - * @brief Clean linked-list queue variable. - * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. - * @retval None. - */ -static void DMA_List_CleanQueue(DMA_QListTypeDef *const pQList) -{ - /* Clear head node */ - pQList->Head = NULL; - - /* Clear first circular queue node */ - pQList->FirstCircularNode = NULL; - - /* Reset node number */ - pQList->NodeNumber = 0U; - - /* Reset queue state */ - pQList->State = HAL_DMA_QUEUE_STATE_RESET; - - /* Reset queue error code */ - pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; - - /* Reset queue type */ - pQList->Type = QUEUE_TYPE_STATIC; -} -/** - * @} - */ - -#endif /* HAL_DMA_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ********************************************************************************************************************** + * @file stm32h7rsxx_hal_dma_ex.c + * @author MCD Application Team + * @brief DMA Extension HAL module driver + * This file provides firmware functions to manage the following functionalities of the DMA extension + * peripheral: + * + Linked-List Initialization and De-Initialization Functions + * + Linked-List I/O Operation Functions + * + Linked-List Management Functions + * + Data Handling, Repeated Block and Trigger Configuration Functions + * + Suspend and Resume Operation Functions + * + FIFO Status Function + * + ********************************************************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ********************************************************************************************************************** + @verbatim + ====================================================================================================================== + ##### How to use this driver ##### + ====================================================================================================================== + [..] + Alternatively to the normal programming mode, a DMA channel can be programmed by a list of transfers, known as + linked-list (list of Node items). Each node is defined by its data structure. + Each node specifies a standalone DMA channel. + When enabled, the DMA channel fetch the first linked-list node from SRAM (known as head node). When executed, the + next linked list node will be fetched and executed. This operation is repeated until the end of the whole + linked-list queue. Optionally, the linked-list can be linear where the last linked-list queue node is not linked + to another queue node or circular where the last linked-list node is linked to any linked-list queue node. + + (+) Linear linked-list: + The DMA channel fetch and execute all DMA linked-list queue from first node (head node) to last node + (tail node) ones. When the last node is completed, the DMA channel remains in idle state and another + transfer can be lunched. + + (+) Circular linked-list: + The DMA channel fetch and execute all DMA linked-list queue from first node (head node) to last node (tail + node). When last node is executed, the DMA channel fetches the first circular node another time and repeat + the same sequence in an infinite loop (Circular transfer). To stop the DMA channel, an abort operation is + required. This linked-list mode replaces the legacy circular transfers. + + [..] + In order to reduce linked-list queue executing time and power consumption, the DMA channel supports executing the + dynamic linked-list format. In fact, the DMA supports the execution of 2 types of linked-list formats : static and + dynamic. + + (+) Static linked-list: + The static linked-list format refers to the full linked-list node where all DMA channel parameters are + fetched and executed independently of the redundancy of information. + + (+) Dynamic linked-list: + The dynamic linked-list format refer to the customized linked-list node where only DMA channel necessary + parameters are fetched and executed (Example: data size = 20 on previous node, and data size = 20 on the + current node => No need to update it). + + For linked-list transfers, the DMA channel can execute the linked-list queue node by node. This feature is named + link step mode. When activated, enabling the DMA channel first time allows to fetch the head node from memory + then it stops. Then, another DMA channel enable is needed to execute the node. After that, keeping enabling the + DMA channel is needed to execute each node until the end of linked-list queue. When the linked-list queue is + circular, enabling the DMA channel in an infinite loop is required to keep the DMA channel running. This feature + is useful for debug purpose or asynchronously executing queue nodes. + + [..] + Each DMA channel transfer (normal or linked-list), is highly configurable according to DMA channel instance + integrated in devices. These configuration can be : + + (+) Repeated block configuration : + If the feature is supported, the DMA channel can performs a repeated block transfers. Named also 2 + dimension addressing transfers, this feature can transfer n iteration of programmed block transfer (Block + transfer is the legacy data size). Additional to the repeat count of a block, DMA channel addresses can + jump after at burst and block level. The jump length is a programmable parameter defined by DMA user. + (++) Jump at burst level : + The DMA channel keep an empty area, between each 2 consecutive bursts transmitted. + (++) Jump at block level : + The DMA channel keep an empty area, between each 2 consecutive blocks transmitted. + + (+) Trigger : + The DMA channel transfers can be conditioned by hardware signals edges (rising or falling) named hardware + triggers. Trigger condition can be applied at : + (++) Single/Burst level : + Each single/burst data transmission is conditioned by a signal trigger hit. + (++) Block level : + Each block data transmission is conditioned by a signal trigger hit. + (++) Repeated block level : + Each repeated block data transmission is conditioned by a signal trigger hit. + (++) Node level : + Each node execution is conditioned by a signal trigger hit. + The DMA channel can report a trigger overrun when detects more than 2 trigger signal edges before + executing the current transfer. + + (+) Data handling : + The data handling feature is a FIFO capability that can be : + (++) Padding pattern : + Padding selected pattern (zero padding or sign extension) when the source data width is smaller + than the destination data width at single level. + (++) Truncation : + Truncate section from the source data single when the source data width is bigger than the + destination data width. + (++) Pack/Unpack : + Pack a set of data when source data width is smaller than the destination data width. + Unpack a set of data when source data width is bigger than the destination data width. + (++) Exchange : + Exchange data at byte, half-word and word on the destination and at byte level on the source. + + [..] + Each DMA channel transfer (normal or linked-list) when it is active, can be suspended and resumed at run time + application. When trying to suspend an ongoing transfer, the DMA channel isn't suspended instantly but complete + the current ongoing single/burst then it stops. + When the DMA channel is suspended, the current transfer can be resumed instantly. + + [..] + The DMA channel that supports FIFO, can report in real time the number of beats remains on destination (Output) + FIFO level. + + *** Linked-List Initialization and De-Initialization operation *** + ================================================================== + [..] + Differently from normal transfers, DMA channel initialization and de-initialization need less parameters as the + remaining transfer parameters are defined by linked-list nodes. + + (+) Use HAL_DMAEx_List_Init() to initialize a DMA channel in linked-list mode according to programmed fields. + When called, the DMA channel will be ready to execute linked-list queues. + + (+) Use HAL_DMAEx_List_DeInit() to de-initialize a DMA channel in linked-list mode. + When called, the DMA channel will be in reset. It is mandatory to reinitialize it for next transfer. + + *** Linked-List I/O Operation *** + ================================= + [..] + (+) Use HAL_DMAEx_List_Start() to start a DMA transfer in linked-list mode after the configuration of + linked-list queue base address and offset in polling mode (Blocking mode). + + (+) Use HAL_DMAEx_List_Start_IT() to start a DMA transfer in linked-list mode after the configuration of + linked-list queue base address and offset in interrupt mode (Non-blocking mode). + + *** Linked-List Management *** + ============================== + [..] + The linked-list management is a software processing independently of DMA channel hardware. It allows to reset, + build, create, insert, remove, replace, circularize, convert both nodes and queue in order to perform DMA + channel transfers in linked-list mode. + Linked-list APIs and types are adapted to reduce memory footprint. + + *** Linked-list nodes building *** + [..] + At node level, the operations that can be done are building a new linked-list node or get a linked-list node + information from a built node. The linked-list nodes have two forms according to 2 dimensions addressing + capability. The linear addressing nodes contains the information of all DMA channel features except the 2 + dimension addressing features and the 2 dimensions addressing nodes contain the information of all available + features. + + (+) Use HAL_DMAEx_List_BuildNode() to build the DMA linked-list node according to the specified parameters. + Build operation allow to convert the specified parameter in values known by the DMA channel and place them + in memory. + Placing DMA linked-list in SRAM must be done in accordance to product specification to ensure that the + link access port can access to the specified SRAM. + (++) The DMA linked-list node parameter address should be 32bit aligned and should not exceed the 64 KByte + addressable space. + + (+) Use HAL_DMAEx_List_GetNodeConfig() to get the specified configuration parameter on building node. + This API can be used when need to change few parameter to build new node. + + *** Inserting nodes to linked-list queue *** + [..] + In order to build a sequence of DMA transaction with different configuration, we need to insert built node at + linked-list queue (node present an elementary DMA transaction) in linked-list queue on any position to have the + full flexibility of ordering nodes or extend the sequence of queue transactions. + + (+) Use HAL_DMAEx_List_InsertNode() to insert new built node in any queue position of linked-list queue + according to selecting previous node. When calling this API with previous node parameter is NULL, the + inserted node will be placed at the head of the linked-list queue. + (++) This API must be used after HAL_DMAEx_List_BuildNode() otherwise an error will be returned. + (++) This API must be called for static queues format. + (++) This API shall be avoided when adding new node at the head or the tail of queue (overhead of + footprint and performance : use HAL_DMAEx_List_InsertNode_Head() or HAL_DMAEx_List_InsertNode_Tail() + instead). + + (+) Use HAL_DMAEx_List_InsertNode_Head() to insert new built node at the head of linked-list queue. The head + node will not be overwritten but will be the second queue node. + (++) This API must be used after HAL_DMAEx_List_BuildNode() otherwise an error will be returned. + (++) This API must be called for static queues format. + + (+) Use HAL_DMAEx_List_InsertNode_Tail() to insert new built node at the tail of linked-list queue. The tail + node will not be overwritten but will be the penultimate queue node. + (++) This API must be used after HAL_DMAEx_List_BuildNode() otherwise an error will be returned. + (++) This API must be called for static queues format. + + *** Removing nodes from linked-list queue *** + [..] + There is some cases when removing a node from linked-list queue is needed (need to remove an elementary DMA + transaction). Removing node allows to unlink a node from DMA linked-list queue (NOT DELETED), so the removed node + can be reused for another queue or to be added to the same queue without need to rebuild it in next step. + + (+) Use HAL_DMAEx_List_RemoveNode() to remove any yet built and inserted node from linked-list queue according + to selected node. + (++) This API must be called for static queues format. + (++) This API shall be avoided when removing the head or the tail of linked-list queue (overhead of + footprint and performance : use HAL_DMAEx_List_RemoveNode_Head() or HAL_DMAEx_List_RemoveNode_Tail() + instead). + + (+) Use HAL_DMAEx_List_RemoveNode_Head() to remove the head node from linked-list queue. + (++) This API must be called for static queues format. + + (+) Use HAL_DMAEx_List_RemoveNode_Tail() to remove the tail node from linked-list queue. + (++) This API must be called for static queues format. + + *** Replacing nodes on linked-list queue *** + [..] + There is some cases when replacing a node from linked-list queue is needed (need to replace an elementary DMA + transfer, by another one that have not the same configuration). Replacing node allows to unlink the node to be + replaced from DMA linked-list queue (NOT DELETED) and link instead a new node. So the replaced node can be reused + for another queue or to be added to the same queue without need to rebuild it in next step and the new node cannot + be reused except when remove it or replaced in next step. + + (+) Use HAL_DMAEx_List_ReplaceNode() to replace any yet built and inserted node on linked-list queue according + to selected node. + (++) This API must be called for static queues format. + (++) This API shall be avoided when replacing the head or the tail linked-list queue (overhead of + footprint and performance : use HAL_DMAEx_List_ReplaceNode_Head() or + HAL_DMAEx_List_ReplaceNode_Tail() instead). + + (+) Use HAL_DMAEx_List_ReplaceNode_Head() to replace the head node of linked-list queue. + (++) This API must be called for static queues format. + + (+) Use HAL_DMAEx_List_ReplaceNode_Tail() to replace the tail node from linked-list queue. + (++) This API must be called for static queues format. + + *** Reset linked-list queue *** + [..] + After finishing using a linked-list queue, it can be reset and cleared and it's content nodes will be + unlinked (NOT DELETED) and reused on another queue. + + (+) Use HAL_DMAEx_List_ResetQ() to reset a linked-list queue and unlink all it's content nodes. + (++) This API must be called for ready state queues. + (++) This API must be called for static queues format. + + *** Inserting linked-list queue *** + [..] + To ensure the flexibility of building linked-list queue by their targeted functionalities (Example: 3 nodes for + action 1 and 5 nodes for action 2), it is possible to build a queue for action 1 that contains action 1 nodes and + a queue for action 2 that contains action 2 nodes then concatenating the 2 queues. So, there are some cases where + the management of linked-list at queue granularity is needed. + + (+) Use HAL_DMAEx_List_InsertQ() to insert source linked-list queue to a destination linked-list queue + according to selecting previous node. + (++) This API must be called for static queues format. + (++) This API shall be avoided when inserting source linked-list queue at the head or the tail of + destination queue (overhead of footprint and performance : use HAL_DMAEx_List_InsertQ_Head() or + HAL_DMAEx_List_InsertQ_Tail() instead). + + (+) Use HAL_DMAEx_List_InsertQ_Head() to insert a source linked-list queue at the head of linked-list + destination queue. + (++) This API must be called for static queues format. + + (+) Use HAL_DMAEx_List_InsertQ_Tail() to insert a source linked-list queue at the tail of linked-list + destination queue. + (++) This API must be called for static queues format. + + *** Circularizing linked-list queue *** + [..] + In order to perform tasks in infinite loop with DMA channel, it is possible to circularize the linked-list queues. + Circularizing queue allows to link last linked-list queue node to any previous node of the same queue (This node + is named first circular queue). When the first circular node is the head node, all linked-list queue nodes will be + executed in infinite loop. When the first circular node is not the head nodes, all precedent nodes are executed + once and all remaining nodes are executed in an infinite loop. + + (+) Use HAL_DMAEx_List_SetCircularModeConfig() to circularize the linked-list queue according to first + circular node selected. + (++) This API must be called for static queues format. + (++) This API shall be avoided when first circular node is the head linked-list queue node (overhead of + footprint and performance : use HAL_DMAEx_List_SetCircularMode() instead). + + (+) Use HAL_DMAEx_List_SetCircularMode() to circularize the linked-list queue with linking last queue node + with first queue node. + (++) This API must be called for static queues format. + + (+) Use HAL_DMAEx_List_ClearCircularMode() to clear any linked-list queue circular configuration. + (++) This API must be called for static queues format. + + + *** Converting linked-list queue *** + [..] + To have the best DMA channel linked-list queue execution, it is recommended to convert yet build linked-list queue + to dynamic format (Static is the default format). When linked-list queue becomes dynamic, all queue nodes are + optimized and only changed parameters will be updated between nodes. So, the DMA will fetch only changes + parameters instead of the whole node. + + (+) Use HAL_DMAEx_List_ConvertQToDynamic() to convert a linked-list queue to dynamic format. + (++) This API must be called for ready state queues. + (++) This API must be called for static queues format. + (++) This API must be called as the last API before starting the DMA channel in linked-list mode. + + (+) Use HAL_DMAEx_List_ConvertQToStatic() to convert a linked-list queue to static format. + (++) This API must be called for ready state queues. + (++) This API must be called for dynamic queues format. + (++) This API must be called as the first API after the full execution of linked-list queue when the + execution mode is linear (not circular) if it is dynamic and a linked-list queue management is + needed. + (++) This API must be called as the first API after the aborting the execution of the current linked-list + queue when the execution mode is linear (not circular) if it is dynamic and a linked-list queue + management is needed. + + [..] + When converting a circular queue to dynamic format and when the first circular node is the last queue node, it is + recommended to duplicate the last circular node in order to ensure the full optimization when calling + HAL_DMAEx_List_ConvertQToDynamic() API. In this case, updated information are only addresses which allow to reduce + 4 words of update for linear nodes per node execution and 6 words update for 2 dimensions addressing nodes per + node execution. + + + *** Linking linked-list queue to DMA channel *** + [..] + In order to have the possibility of the creation of an infinity queues (limited by available memory size), the + building of linked-list queue is fully independent from DMA channels. It is possible to build all needed queues if + their size is less then available memory at startup time, then linking each time when needed a linked-list queue + to an idle DMA channel. + + (+) Use HAL_DMAEx_List_LinkQ() to link a ready linked-list queue to ready DMA channel. + (++) This API supports the two format of linked-list (Static and dynamic). + (++) This API must be called for ready state queues and DMA channels. + + (+) Use HAL_DMAEx_List_ConvertQToStatic() to unlink a ready linked-list queue to ready DMA channel. + (++) This API supports the two format of linked-list (Static and dynamic). + (++) This API must be called for ready state queues and DMA channels. + + *** User sequence *** + [..] + To use cleanly the DMA linked-list library, ensure to apply the following call sequences : + + (+) Linear transfer : + Linked-list queue building + (++) HAL_DMAEx_List_BuildNode() + (++) HAL_DMAEx_List_InsertNode_Tail() + . + . + . + (++) HAL_DMAEx_List_BuildNode() + (++) HAL_DMAEx_List_InsertNode_Tail() + (++) HAL_DMAEx_List_ConvertQToDynamic() + Linked-list queue execution + (++) HAL_DMAEx_List_Init() + (++) HAL_DMAEx_List_LinkQ() + (++) HAL_DMAEx_List_Start() / HAL_DMAEx_List_Start_IT() + (++) HAL_DMAEx_List_UnLinkQ() + (++) HAL_DMAEx_List_DeInit() + + (+) Circular transfer : + Linked-list queue building + (++) HAL_DMAEx_List_BuildNode() + (++) HAL_DMAEx_List_InsertNode_Tail() + . + . + . + (++) HAL_DMAEx_List_BuildNode() + (++) HAL_DMAEx_List_InsertNode_Tail() + (++) HAL_DMAEx_List_SetCircularModeConfig() / HAL_DMAEx_List_SetCircularMode() + (++) HAL_DMAEx_List_ConvertQToDynamic() + Linked-list queue execution + (++) HAL_DMAEx_List_Init() + (++) HAL_DMAEx_List_LinkQ() + (++) HAL_DMAEx_List_Start() / HAL_DMAEx_List_Start_IT() + (++) HAL_DMA_Abort() / HAL_DMA_Abort_IT() + (++) HAL_DMAEx_List_UnLinkQ() + (++) HAL_DMAEx_List_DeInit() + + + *** Data Handling *** + ===================== + [..] + In order to avoid some CPU data processing in several cases, the DMA channel provides some features related to + FIFO capabilities titled data handling. + (++) Padding pattern + Padding selected pattern (zero padding or sign extension) when the source data width is smaller + than the destination data width at single level. + Zero padding (Source : 0xABAB ------> Destination : 0xABAB0000) + Sign bit extension (Source : 0x0ABA ------> Destination : 0x00000ABA) + (Source : 0xFABA ------> Destination : 0xFFFFFABA) + (++) Truncation : + Truncate section from the source data single when the source data width is bigger than the + destination data width. + Left truncation (Source : 0xABABCDCD ------> Destination : 0xCDCD) + Right truncation (Source : 0xABABCDCD ------> Destination : 0xABAB) + (++) Pack/Unpack : + Pack a set of data when source data width is smaller than the destination data width. + Unpack a set of data when source data width is bigger than the destination data width. + Pack (Source : 0xAB, 0xCD ------> Destination : 0xABCD) + UnPack (Source : 0xABCD ------> Destination : 0xAB, 0xCD) + (++) Exchange : + Exchange data at byte and half-word on the destination and at byte level on the source. + Considering source and destination are both word type. Exchange operation can be as follows. + In examples below, one exchange setting is enabled at a time. + Source byte exchange only (Source : 0xAB12CD34 ------> Destination : 0xABCD1234) + Destination byte exchange only (Source : 0xAB12CD34 ------> Destination : 0x12AB34CD) + Destination half-word exchange only (Source : 0xAB12CD34 ------> Destination : 0xCD34AB12) + In addition, in case of double-word, Exchange data at word level on the destination is also + available. + Considering source and destination are both double-word type. + word exchange only (Source : 0xAB12CD34EF567890 ------> Destination : 0xEF567890AB12CD34) + + (+) Use HAL_DMAEx_ConfigDataHandling() to configure data handling features. Previous elementary explained + can be combined according to application needs. + (++) This API is complementary of normal transfers. + (++) This API must not be called for linked-list transfers as data handling information are configured at + node level. + + *** User sequence *** + [..] + To configure cleanly the DMA channel data handling, ensure to apply the following call sequence : + + (+) Linear transfer : + (++) HAL_DMA_Init() + (++) HAL_DMAEx_ConfigDataHandling() + (++) HAL_DMA_Start() + + *** Repeated Block *** + ====================== + [..] + When available, this feature is used when the data size is higher then 65535 bytes (Maximum block size) or for + scattering / gathering data. + (++) Gather data + Source Destination + 0xAA 0xAA + 0xBB 0xAA + 0xAA ==> 0xAA + 0xCC + 0xAA + (++) Scatter data + Source Destination + 0xAA 0xAA + 0xAA 0xBB + 0xAA ==> 0xAA + 0xBB + 0xAA + + (+) Use HAL_DMAEx_ConfigRepeatBlock() to configure data repeated block feature. Jump addresses and + incrementing or decrementing on source and destination can be combined to have the need application + behavior. + (++) This API is complementary of normal transfers. + (++) This API must not be called for linked-list transfers as repeated block information are configured at + node level. + (++) This API must be called only for DMA channel that supports repeated block feature. + + *** User sequence *** + [..] + To configure cleanly the DMA channel repeated block, ensure to apply the following call sequence : + + (+) Linear transfer : + (++) HAL_DMA_Init() + (++) HAL_DMAEx_ConfigRepeatBlock() + (++) HAL_DMA_Start() + + *** Trigger Configuration *** + ============================= + [..] + When application needs that DMA transfers are conditioned by internal or external events, the trigger feature can + do that. Trigger signals are a set of device signal that are linked to DMA trigger inputs that allows to start the + DMA transfers. + To setup a trigger transfers, three DMA channel parameters are needed: + + (+) Trigger mode + This parameter specifies the trig level. + (++) Block level + (++) Repeated block level + (++) Node level + (++) Single / Burst level + + (+) Trigger polarity + This parameter specifies the DMA trigger sensitivity (Rising or falling). + + (+) Trigger selection + This parameter specifies the DMA trigger hardware signal. + + (+) Use HAL_DMAEx_ConfigTrigger() to configure trigger feature. + (++) This API is complementary to normal transfers APIs. + (++) This API must not be called for linked-list transfers as trigger information are configured at + node level. + + *** User sequence *** + [..] + To configure cleanly the DMA channel trigger, ensure to apply the following call sequence : + (+) Linear transfer : + (++) HAL_DMA_Init() + (++) HAL_DMAEx_ConfigTrigger() + (++) HAL_DMA_Start() + + *** Suspend and resume operation *** + ==================================== + [..] + There are several cases when needs to suspend a DMA current transfer (Example: liberate bandwidth for more + priority DMA channel transfer). Suspending DMA channel (same as abort) is available in polling (blocking mode) and + interrupt (non-blocking mode) modes. When suspended, a DMA channel can be instantly resumed. + + (+) Use HAL_DMAEx_Suspend() to suspend an ongoing DMA channel transfer in polling mode (Blocking mode). + + (+) Use HAL_DMAEx_Suspend_IT() to suspend an ongoing DMA channel transfer in interrupt mode (Non-blocking + mode). + + (+) Use HAL_DMAEx_Resume() to resume a suspended DMA channel transfer execution. + + *** FIFO status *** + =================== + [..] + In several cases, the information of FIFO level is useful to inform at application level how to process remaining + data. When not empty, the DMA channel FIFO cannot be flashed only by reset. + + (+) Use HAL_DMAEx_GetFifoLevel() to get the DMA channel FIFO level (available beats in FIFO). + + @endverbatim + ********************************************************************************************************************** + */ + +/* Includes ----------------------------------------------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup DMAEx DMAEx + * @brief DMA Extended HAL module driver + * @{ + */ + +#ifdef HAL_DMA_MODULE_ENABLED + +/* Private types -----------------------------------------------------------------------------------------------------*/ +/* Private variables -------------------------------------------------------------------------------------------------*/ +/* Private Constants -------------------------------------------------------------------------------------------------*/ +/* Private macros ----------------------------------------------------------------------------------------------------*/ +/* Private function prototypes ---------------------------------------------------------------------------------------*/ +static void DMA_List_Init(DMA_HandleTypeDef const *const hdma); +static void DMA_List_BuildNode(DMA_NodeConfTypeDef const *const pNodeConfig, + DMA_NodeTypeDef *const pNode); +static void DMA_List_GetNodeConfig(DMA_NodeConfTypeDef *const pNodeConfig, + DMA_NodeTypeDef const *const pNode); +static uint32_t DMA_List_CheckNodesBaseAddresses(DMA_NodeTypeDef const *const pNode1, + DMA_NodeTypeDef const *const pNode2, + DMA_NodeTypeDef const *const pNode3); +static uint32_t DMA_List_CheckNodesTypes(DMA_NodeTypeDef const *const pNode1, + DMA_NodeTypeDef const *const pNode2, + DMA_NodeTypeDef const *const pNode3); +static void DMA_List_GetCLLRNodeInfo(DMA_NodeTypeDef const *const pNode, + uint32_t *const cllr_mask, + uint32_t *const cllr_offset); +static uint32_t DMA_List_FindNode(DMA_QListTypeDef const *const pQList, + DMA_NodeTypeDef const *const pNode, + DMA_NodeInQInfoTypeDef *const NodeInfo); +static void DMA_List_ResetQueueNodes(DMA_QListTypeDef const *const pQList, + DMA_NodeInQInfoTypeDef const *const NodeInfo); +static void DMA_List_FillNode(DMA_NodeTypeDef const *const pSrcNode, + DMA_NodeTypeDef *const pDestNode); +static void DMA_List_ConvertNodeToDynamic(uint32_t ContextNodeAddr, + uint32_t CurrentNodeAddr, + uint32_t RegisterNumber); +static void DMA_List_ConvertNodeToStatic(uint32_t ContextNodeAddr, + uint32_t CurrentNodeAddr, + uint32_t RegisterNumber); +static void DMA_List_UpdateDynamicQueueNodesCLLR(DMA_QListTypeDef const *const pQList, + uint32_t LastNode_IsCircular); +static void DMA_List_UpdateStaticQueueNodesCLLR(DMA_QListTypeDef const *const pQList, + uint32_t operation); +static void DMA_List_FormatNode(DMA_NodeTypeDef *const pNode, + uint32_t RegisterIdx, + uint32_t RegisterNumber, + uint32_t Format); +static void DMA_List_ClearUnusedFields(DMA_NodeTypeDef *const pNode, + uint32_t FirstUnusedField); +static void DMA_List_CleanQueue(DMA_QListTypeDef *const pQList); + +/* Exported functions ------------------------------------------------------------------------------------------------*/ + +/** @addtogroup DMAEx_Exported_Functions + * @{ + */ + +/** @addtogroup DMAEx_Exported_Functions_Group1 + * +@verbatim + ====================================================================================================================== + ##### Linked-List Initialization and De-Initialization Functions ##### + ====================================================================================================================== + [..] + This section provides functions allowing to initialize and de-initialize the DMA channel in linked-list mode. + [..] + (+) The HAL_DMAEx_List_Init() function follows the DMA channel linked-list mode configuration procedures as + described in reference manual. + (+) The HAL_DMAEx_List_DeInit() function allows to de-initialize the DMA channel in linked-list mode. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the DMA channel in linked-list mode according to the specified parameters in the + * DMA_InitLinkedListTypeDef and create the associated handle. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_Init(DMA_HandleTypeDef *const hdma) +{ + /* Get tick number */ + uint32_t tickstart = HAL_GetTick(); + + /* Check the DMA channel handle parameter */ + if (hdma == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); + assert_param(IS_DMA_PRIORITY(hdma->InitLinkedList.Priority)); + assert_param(IS_DMA_LINK_STEP_MODE(hdma->InitLinkedList.LinkStepMode)); + assert_param(IS_DMA_TCEM_LINKEDLIST_EVENT_MODE(hdma->InitLinkedList.TransferEventMode)); + assert_param(IS_DMA_LINKEDLIST_MODE(hdma->InitLinkedList.LinkedListMode)); + /* Check DMA channel instance */ + if ((IS_HPDMA_INSTANCE(hdma->Instance) != 0U) || (IS_GPDMA_INSTANCE(hdma->Instance) != 0U)) + { + assert_param(IS_DMA_LINK_ALLOCATED_PORT(hdma->InitLinkedList.LinkAllocatedPort)); + } + + /* Allocate lock resource */ + __HAL_UNLOCK(hdma); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Check if the DMA channel is effectively disabled */ + while ((hdma->Instance->CCR & DMA_CCR_EN) != 0U) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; + + return HAL_ERROR; + } + } + + /* Initialize the DMA channel registers */ + DMA_List_Init(hdma); + + /* Update DMA channel operation mode */ + hdma->Mode = hdma->InitLinkedList.LinkedListMode; + + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + + /* Update the DMA channel state */ + hdma->State = HAL_DMA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitialize the DMA channel when it is configured in linked-list mode. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_DeInit(DMA_HandleTypeDef *const hdma) +{ + /* Get tick number */ + uint32_t tickstart = HAL_GetTick(); + + /* Check the DMA peripheral handle parameter */ + if (hdma == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); + + /* Disable the selected DMA Channel */ + __HAL_DMA_DISABLE(hdma); + + /* Check if the DMA channel is effectively disabled */ + while ((hdma->Instance->CCR & DMA_CCR_EN) != 0U) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; + + return HAL_ERROR; + } + } + + /* Reset DMA Channel registers */ + hdma->Instance->CCR = 0U; + hdma->Instance->CLBAR = 0U; + hdma->Instance->CTR1 = 0U; + hdma->Instance->CTR2 = 0U; + hdma->Instance->CBR1 = 0U; + hdma->Instance->CSAR = 0U; + hdma->Instance->CDAR = 0U; + hdma->Instance->CLLR = 0U; + + /* Reset 2D Addressing registers */ + if (IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance) != 0U) + { + hdma->Instance->CTR3 = 0U; + hdma->Instance->CBR2 = 0U; + } + + /* Clear all flags */ + __HAL_DMA_CLEAR_FLAG(hdma, (DMA_FLAG_TC | DMA_FLAG_HT | DMA_FLAG_DTE | DMA_FLAG_ULE | DMA_FLAG_USE | DMA_FLAG_SUSP | + DMA_FLAG_TO)); + + /* Clean all callbacks */ + hdma->XferCpltCallback = NULL; + hdma->XferHalfCpltCallback = NULL; + hdma->XferErrorCallback = NULL; + hdma->XferAbortCallback = NULL; + hdma->XferSuspendCallback = NULL; + + /* Check the linked-list queue */ + if (hdma->LinkedListQueue != NULL) + { + /* Update the queue state and error code */ + hdma->LinkedListQueue->State = HAL_DMA_QUEUE_STATE_READY; + hdma->LinkedListQueue->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Clean DMA queue */ + hdma->LinkedListQueue = NULL; + } + + /* Clean DMA parent */ + if (hdma->Parent != NULL) + { + hdma->Parent = NULL; + } + + /* Update DMA channel operation mode */ + hdma->Mode = DMA_NORMAL; + + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + + /* Update the DMA channel state */ + hdma->State = HAL_DMA_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hdma); + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup DMAEx_Exported_Functions_Group2 + * +@verbatim + ====================================================================================================================== + ##### Linked-List IO Operation Functions ##### + ====================================================================================================================== + [..] + This section provides functions allowing to : + (+) Configure to start DMA transfer in linked-list mode. + + [..] + (+) The HAL_DMAEx_List_Start() function allows to start the DMA channel transfer in linked-list mode (Blocking + mode). + (+) The HAL_DMAEx_List_Start_IT() function allows to start the DMA channel transfer in linked-list mode + (Non-blocking mode). + (++) It is mandatory to register a linked-list queue to be executed by a DMA channel before starting + transfer otherwise a HAL_ERROR will be returned. + +@endverbatim + * @{ + */ + +/** + * @brief Start the DMA channel transfer in linked-list mode (Blocking mode). + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_Start(DMA_HandleTypeDef *const hdma) +{ + HAL_DMA_StateTypeDef dma_state; + uint32_t ccr_value; + uint32_t cllr_mask; + + /* Check the DMA peripheral handle and the linked-list queue parameters */ + if ((hdma == NULL) || (hdma->LinkedListQueue == NULL)) + { + return HAL_ERROR; + } + + /* Check DMA channel state */ + dma_state = hdma->State; + ccr_value = hdma->Instance->CCR & DMA_CCR_LSM; + if ((dma_state == HAL_DMA_STATE_READY) || ((dma_state == HAL_DMA_STATE_BUSY) && (ccr_value != 0U))) + { + /* Check DMA channel state is ready */ + if (hdma->State == HAL_DMA_STATE_READY) + { + /* Process locked */ + __HAL_LOCK(hdma); + + /* Update the DMA channel and the queue states */ + hdma->State = HAL_DMA_STATE_BUSY; + hdma->LinkedListQueue->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the DMA channel and the queue error codes */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + hdma->LinkedListQueue->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(hdma->LinkedListQueue->Head, &cllr_mask, NULL); + + /* Update DMA registers for linked-list transfer */ + hdma->Instance->CLBAR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLBAR_LBA); + hdma->Instance->CLLR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLLR_LA) | cllr_mask; + } + + /* Enable DMA channel */ + __HAL_DMA_ENABLE(hdma); + } + else + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Starts the DMA channel transfer in linked-list mode with interrupts enabled (Non-blocking mode). + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_Start_IT(DMA_HandleTypeDef *const hdma) +{ + HAL_DMA_StateTypeDef dma_state; + uint32_t ccr_value; + uint32_t cllr_mask; + + /* Check the DMA peripheral handle and the linked-list queue parameters */ + if ((hdma == NULL) || (hdma->LinkedListQueue == NULL)) + { + return HAL_ERROR; + } + + /* Check DMA channel state */ + dma_state = hdma->State; + ccr_value = hdma->Instance->CCR & DMA_CCR_LSM; + if ((dma_state == HAL_DMA_STATE_READY) || ((dma_state == HAL_DMA_STATE_BUSY) && (ccr_value != 0U))) + { + /* Check DMA channel state is ready */ + if (hdma->State == HAL_DMA_STATE_READY) + { + /* Process locked */ + __HAL_LOCK(hdma); + + /* Update the DMA channel and the queue states */ + hdma->State = HAL_DMA_STATE_BUSY; + hdma->LinkedListQueue->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the DMA channel and the queue error codes */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + hdma->LinkedListQueue->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Enable common interrupts: Transfer Complete and Transfer Errors ITs */ + __HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_DTE | DMA_IT_ULE | DMA_IT_USE | DMA_IT_TO)); + + /* Check half transfer complete callback */ + if (hdma->XferHalfCpltCallback != NULL) + { + /* If half transfer complete callback is set, enable the corresponding IT */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT); + } + + /* Check suspend callback */ + if (hdma->XferSuspendCallback != NULL) + { + /* If transfer suspend callback is set, enable the corresponding IT */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_SUSP); + } + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(hdma->LinkedListQueue->Head, &cllr_mask, NULL); + + /* Update DMA registers for linked-list transfer */ + hdma->Instance->CLBAR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLBAR_LBA); + hdma->Instance->CLLR = ((uint32_t)hdma->LinkedListQueue->Head & DMA_CLLR_LA) | cllr_mask; + } + + /* Enable DMA channel */ + __HAL_DMA_ENABLE(hdma); + } + else + { + /* Change the error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup DMAEx_Exported_Functions_Group3 + * +@verbatim + ====================================================================================================================== + ##### Linked-List Management Functions ##### + ====================================================================================================================== + [..] + This section provides functions allowing to : + (+) Build linked-list node. + (+) Get linked-list node configuration. + (+) Insert node to linked-list queue in any queue position. + (+) Remove any node from linked-list queue. + (+) Replace any node from linked-list queue. + (+) Reset linked-list queue. + (+) Insert linked-list queue in any queue position. + (+) Set circular mode configuration to linked-list queue. + (+) Clear circular mode configuration from linked-list queue. + (+) Convert static linked-list queue to dynamic format. + (+) Convert dynamic linked-list queue to static format. + (+) Link linked-list queue to DMA channel. + (+) Unlink linked-list queue from DMA channel. + + [..] + (+) The HAL_DMAEx_List_BuildNode() function allows to build linked-list node. + Node type can be : + (++) 2 dimensions addressing node. + (++) Linear addressing node. + + (+) The HAL_DMAEx_List_GetNodeConfig() function allows to get the linked-list node configuration from built node. + + (+) The HAL_DMAEx_List_InsertNode() function allows to insert built linked-list node to static linked-list queue + according to selected position. + + (+) The HAL_DMAEx_List_InsertNode_Head() and HAL_DMAEx_List_InsertNode_Tail() functions allow to insert built + linked-list node to the head (respectively the tail) of static linked-list queue. + + (+) The HAL_DMAEx_List_RemoveNode() function allows to remove selected built linked-list node from static + linked-list queue. + + (+) The HAL_DMAEx_List_RemoveNode_Head() and HAL_DMAEx_List_RemoveNode_Tail() functions allow to remove the head + (respectively the tail) built linked-list node from static linked-list queue. + + (+) The HAL_DMAEx_List_ReplaceNode() function allows to replace selected built linked-list node from static + linked-list queue. + + (+) The HAL_DMAEx_List_ReplaceNode_Head() and HAL_DMAEx_List_ReplaceNode_Tail() functions allow to replace the + head (respectively the tail) built linked-list node of static linked-list queue. + + (+) The HAL_DMAEx_List_ResetQ() function allows to reset static linked-list queue and unlink all built linked-list + nodes. + + (+) The HAL_DMAEx_List_InsertQ() function allows to insert static linked-list source queue to static linked-list + destination queue according to selected position. + + (+) The HAL_DMAEx_List_InsertQ_Head() and HAL_DMAEx_List_InsertQ_Tail() functions allow to insert static + linked-list source queue to the head (respectively the tail) of static linked-list destination queue. + + (+) The HAL_DMAEx_List_SetCircularModeConfig() function allows to link the last static linked-list queue node to + the selected first circular node. + + (+) The HAL_DMAEx_List_SetCircularMode() function allows to link the last static linked-list queue node to the + first static linked-list queue node. + + (+) The HAL_DMAEx_List_ClearCircularMode() function allows to unlink the last static linked-list queue node from + any first circular node position. + + (+) The HAL_DMAEx_List_ConvertQToDynamic() function allows to convert the static linked-list queue to dynamic + format. (Optimized queue execution) + + (+) The HAL_DMAEx_List_ConvertQToStatic() function allows to convert the dynamic linked-list queue to static + format. (Not optimized queue execution) + + (+) The HAL_DMAEx_List_LinkQ() function allows to link the (Dynamic / Static) linked-list queue to DMA channel to + be executed. + + (+) The HAL_DMAEx_List_UnLinkQ() function allows to unlink the (Dynamic / Static) linked-list queue from DMA + channel when execution is completed. + +@endverbatim + * @{ + */ + +/** + * @brief Build a DMA channel node according to the specified parameters in the DMA_NodeConfTypeDef. + * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the + * specified DMA linked-list Node. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @note The DMA linked-list node parameter address should be 32bit aligned and should not exceed the 64 KByte + * addressable space. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_BuildNode(DMA_NodeConfTypeDef const *const pNodeConfig, + DMA_NodeTypeDef *const pNode) +{ + /* Check the node configuration and physical node parameters */ + if ((pNodeConfig == NULL) || (pNode == NULL)) + { + return HAL_ERROR; + } + + /* Check node type parameter */ + assert_param(IS_DMA_NODE_TYPE(pNodeConfig->NodeType)); + + /* Check DMA channel basic transfer parameters */ + assert_param(IS_DMA_SOURCE_INC(pNodeConfig->Init.SrcInc)); + assert_param(IS_DMA_DESTINATION_INC(pNodeConfig->Init.DestInc)); + assert_param(IS_DMA_SOURCE_DATA_WIDTH(pNodeConfig->Init.SrcDataWidth)); + assert_param(IS_DMA_DESTINATION_DATA_WIDTH(pNodeConfig->Init.DestDataWidth)); + assert_param(IS_DMA_DATA_ALIGNMENT(pNodeConfig->DataHandlingConfig.DataAlignment)); + assert_param(IS_DMA_REQUEST(pNodeConfig->Init.Request)); + assert_param(IS_DMA_DIRECTION(pNodeConfig->Init.Direction)); + assert_param(IS_DMA_TCEM_EVENT_MODE(pNodeConfig->Init.TransferEventMode)); + assert_param(IS_DMA_BLOCK_HW_REQUEST(pNodeConfig->Init.BlkHWRequest)); + assert_param(IS_DMA_MODE(pNodeConfig->Init.Mode)); + + /* Check DMA channel parameters */ + if ((pNodeConfig->NodeType & (DMA_CHANNEL_TYPE_GPDMA | DMA_CHANNEL_TYPE_HPDMA)) != 0U) + { + assert_param(IS_DMA_BURST_LENGTH(pNodeConfig->Init.SrcBurstLength)); + assert_param(IS_DMA_BURST_LENGTH(pNodeConfig->Init.DestBurstLength)); + assert_param(IS_DMA_DATA_EXCHANGE(pNodeConfig->DataHandlingConfig.DataExchange)); + assert_param(IS_DMA_TRANSFER_ALLOCATED_PORT(pNodeConfig->Init.TransferAllocatedPort)); + } + + /* Check DMA channel trigger parameters */ + assert_param(IS_DMA_TRIGGER_POLARITY(pNodeConfig->TriggerConfig.TriggerPolarity)); + if (pNodeConfig->TriggerConfig.TriggerPolarity != DMA_TRIG_POLARITY_MASKED) + { + assert_param(IS_DMA_TRIGGER_MODE(pNodeConfig->TriggerConfig.TriggerMode)); + assert_param(IS_DMA_TRIGGER_SELECTION(pNodeConfig->TriggerConfig.TriggerSelection)); + } + + /* Check DMA channel repeated block parameters */ + if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + assert_param(IS_DMA_REPEAT_COUNT(pNodeConfig->RepeatBlockConfig.RepeatCount)); + assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.SrcAddrOffset)); + assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.DestAddrOffset)); + assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset)); + assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset)); + assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.SrcAddrOffset)); + assert_param(IS_DMA_BURST_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.DestAddrOffset)); + assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset)); + assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset)); + } + + /* Build the DMA channel node */ + DMA_List_BuildNode(pNodeConfig, pNode); + + return HAL_OK; +} + +/** + * @brief Get a DMA channel node configuration. + * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the + * specified DMA linked-list Node. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_GetNodeConfig(DMA_NodeConfTypeDef *const pNodeConfig, + DMA_NodeTypeDef const *const pNode) +{ + /* Check the node configuration and physical node parameters */ + if ((pNodeConfig == NULL) || (pNode == NULL)) + { + return HAL_ERROR; + } + + /* Get the DMA channel node configuration */ + DMA_List_GetNodeConfig(pNodeConfig, pNode); + + return HAL_OK; +} + +/** + * @brief Insert new node in any queue position of linked-list queue according to selecting previous node. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pPrevNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list previous node registers + * configurations. + * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_InsertNode(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pPrevNode, + DMA_NodeTypeDef *const pNewNode) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the new node parameters */ + if ((pQList == NULL) || (pNewNode == NULL)) + { + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pPrevNode, pNewNode) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pQList->Head, pPrevNode, pNewNode) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); + + /* Empty queue */ + if (pQList->Head == NULL) + { + /* Add only new node to queue */ + if (pPrevNode == NULL) + { + pQList->Head = pNewNode; + pQList->NodeNumber = 1U; + } + /* Add previous node then new node to queue */ + else + { + pQList->Head = pPrevNode; + pPrevNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + pQList->NodeNumber = 2U; + } + } + /* Not empty queue */ + else + { + /* Add new node at the head of queue */ + if (pPrevNode == NULL) + { + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; + pQList->Head = pNewNode; + } + /* Add new node according to selected position */ + else + { + /* Find node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + if (DMA_List_FindNode(pQList, pPrevNode, &node_info) == 0U) + { + /* Selected node is the last queue node */ + if (node_info.currentnode_pos == pQList->NodeNumber) + { + /* Check if queue is circular */ + if (pQList->FirstCircularNode != NULL) + { + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; + } + + pPrevNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + } + /* Selected node is not the last queue node */ + else + { + pNewNode->LinkRegisters[cllr_offset] = pPrevNode->LinkRegisters[cllr_offset]; + pPrevNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + } + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; + + return HAL_ERROR; + } + } + + /* Increment queue node number */ + pQList->NodeNumber++; + } + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Insert new node at the head of linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_InsertNode_Head(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pNewNode) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + + /* Check the queue and the new node parameters */ + if ((pQList == NULL) || (pNewNode == NULL)) + { + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pNewNode, NULL) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pQList->Head, pNewNode, NULL) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Empty queue */ + if (pQList->Head == NULL) + { + pQList->Head = pNewNode; + } + /* Not empty queue */ + else + { + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); + + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; + pQList->Head = pNewNode; + } + + /* Increment queue node number */ + pQList->NodeNumber++; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Insert new node at the tail of linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_InsertNode_Tail(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pNewNode) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the new node parameters */ + if ((pQList == NULL) || (pNewNode == NULL)) + { + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pNewNode, NULL) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pQList->Head, pNewNode, NULL) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Empty queue */ + if (pQList->Head == NULL) + { + pQList->Head = pNewNode; + } + /* Not empty queue */ + else + { + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); + + /* Find node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Check if queue is circular */ + if (pQList->FirstCircularNode != NULL) + { + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; + } + + ((DMA_NodeTypeDef *)node_info.currentnode_addr)->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + } + + /* Increment queue node number */ + pQList->NodeNumber++; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Remove node from any linked-list queue position. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list previous node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_RemoveNode(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pNode) +{ + uint32_t previousnode_addr; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the node parameters */ + if ((pQList == NULL) || (pNode == NULL)) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNode, NULL, &cllr_offset); + + /* Find node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + if (DMA_List_FindNode(pQList, pNode, &node_info) == 0U) + { + /* Removed node is the head node */ + if (node_info.currentnode_pos == 1U) + { + /* Check if first circular node queue is the first node */ + if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)node_info.currentnode_addr)) + { + /* Find last queue node */ + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear last node link */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear first circular node */ + pQList->FirstCircularNode = NULL; + } + + /* Update the queue head node */ + pQList->Head = (DMA_NodeTypeDef *)(((uint32_t)pQList->Head & DMA_CLBAR_LBA) + + (pNode->LinkRegisters[cllr_offset] & DMA_CLLR_LA)); + /* Unlink node to be removed */ + pNode->LinkRegisters[cllr_offset] = 0U; + } + /* Removed node is the last node */ + else if (node_info.currentnode_pos == pQList->NodeNumber) + { + /* Clear CLLR for previous node */ + ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear CLLR for last node */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear first circular node */ + pQList->FirstCircularNode = NULL; + } + /* Removed node is in the middle */ + else + { + /* Store previous node address to be updated later */ + previousnode_addr = node_info.previousnode_addr; + + /* Check if first circular node queue is the current node */ + if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)node_info.currentnode_addr)) + { + /* Find last queue node */ + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear last node link */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear first circular node */ + pQList->FirstCircularNode = NULL; + } + + /* Link previous node */ + ((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[cllr_offset] = pNode->LinkRegisters[cllr_offset]; + + /* Unlink node to be removed */ + pNode->LinkRegisters[cllr_offset] = 0U; + } + + /* Decrement node number */ + pQList->NodeNumber--; + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; + + return HAL_ERROR; + } + + /* Check if queue is empty */ + if (pQList->NodeNumber == 0U) + { + /* Clean empty queue parameter */ + DMA_List_CleanQueue(pQList); + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + } + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Remove the head node from linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_RemoveNode_Head(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_offset; + uint32_t current_addr; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); + + /* Queue contains only one node */ + if (pQList->NodeNumber == 1U) + { + pQList->Head->LinkRegisters[cllr_offset] = 0U; + pQList->FirstCircularNode = 0U; + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + } + /* Queue contains more then one node */ + else + { + /* Check if first circular node queue is the first node */ + if (pQList->FirstCircularNode == pQList->Head) + { + /* Find last queue node */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear last node link */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear first circular node */ + pQList->FirstCircularNode = NULL; + } + + current_addr = pQList->Head->LinkRegisters[cllr_offset] & DMA_CLLR_LA; + pQList->Head->LinkRegisters[cllr_offset] = 0U; + pQList->Head = ((DMA_NodeTypeDef *)(current_addr + ((uint32_t)pQList->Head & DMA_CLBAR_LBA))); + } + + /* Decrement node number */ + pQList->NodeNumber--; + + /* Check if queue is empty */ + if (pQList->NodeNumber == 0U) + { + /* Clean empty queue parameter */ + DMA_List_CleanQueue(pQList); + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + } + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Remove the tail node from linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_RemoveNode_Tail(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); + + /* Queue contains only one node */ + if (pQList->NodeNumber == 1U) + { + pQList->Head->LinkRegisters[cllr_offset] = 0U; + pQList->FirstCircularNode = 0U; + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + } + /* Queue contains more then one node */ + else + { + /* Find node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear CLLR for previous node */ + ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear CLLR for last node */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Clear first circular node */ + pQList->FirstCircularNode = NULL; + } + + /* Decrement node number */ + pQList->NodeNumber--; + + /* Check if queue is empty */ + if (pQList->NodeNumber == 0U) + { + /* Clean empty queue parameter */ + DMA_List_CleanQueue(pQList); + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + } + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Replace node in linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pOldNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list old node registers + * configurations. + * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ReplaceNode(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pOldNode, + DMA_NodeTypeDef *const pNewNode) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the nodes parameters */ + if ((pQList == NULL) || (pOldNode == NULL) || (pNewNode == NULL)) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pOldNode, pNewNode) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pQList->Head, pOldNode, pNewNode) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); + + /* Find node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + if (DMA_List_FindNode(pQList, pOldNode, &node_info) == 0U) + { + /* Replaced node is the head node */ + if (node_info.currentnode_pos == 1U) + { + pNewNode->LinkRegisters[cllr_offset] = + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset]; + pQList->Head = pNewNode; + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Check if first circular node queue is the first node */ + if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)node_info.currentnode_addr)) + { + /* Find last queue node */ + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear last node link */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + + /* Set new node as first circular node */ + pQList->FirstCircularNode = pNewNode; + } + } + /* Replaced node is the last */ + else if (node_info.currentnode_pos == pQList->NodeNumber) + { + ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Check if first circular node queue is the last node */ + if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)(node_info.currentnode_addr))) + { + /* Link first circular node to new node */ + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + + /* Set new node as first circular node */ + pQList->FirstCircularNode = pNewNode; + } + /* Check if first circular node queue is not the last node */ + else if (pQList->FirstCircularNode != NULL) + { + /* Link first circular node to new node */ + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; + } + else + { + /* Prevent MISRA-C2012-Rule-15.7 */ + } + } + /* Replaced node is in the middle */ + else + { + ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + pNewNode->LinkRegisters[cllr_offset] = + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset]; + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Check if first circular node queue is the current node */ + if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)(node_info.currentnode_addr))) + { + /* Find last node and get its position in selected queue */ + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Link last queue node to new node */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + + /* Set new node as first circular node */ + pQList->FirstCircularNode = pNewNode; + } + } + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; + + return HAL_ERROR; + } + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Replace the head node of linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ReplaceNode_Head(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pNewNode) +{ + uint32_t cllr_offset; + uint32_t cllr_mask; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the new node parameters */ + if ((pQList == NULL) || (pNewNode == NULL)) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pQList->Head, pNewNode, NULL) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pQList->Head, pNewNode, NULL) != 0U) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); + + /* Check if first circular node queue is the first node */ + if (pQList->FirstCircularNode == pQList->Head) + { + /* Find last queue node */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear last node link */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + + /* Set new node as first circular node */ + pQList->FirstCircularNode = pNewNode; + } + + /* Replace head node */ + pNewNode->LinkRegisters[cllr_offset] = pQList->Head->LinkRegisters[cllr_offset]; + pQList->Head->LinkRegisters[cllr_offset] = 0U; + pQList->Head = pNewNode; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Replace the tail node of linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pNewNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list new node registers + * configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ReplaceNode_Tail(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pNewNode) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the new node parameters */ + if ((pQList == NULL) || (pNewNode == NULL)) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pNewNode, &cllr_mask, &cllr_offset); + + /* Find last node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Link previous node to new node */ + ((DMA_NodeTypeDef *)(node_info.previousnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + + /* Clear CLLR for current node */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Check if first circular node queue is the last node */ + if (pQList->FirstCircularNode == ((DMA_NodeTypeDef *)(node_info.currentnode_addr))) + { + /* Link first circular node to new node */ + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pNewNode & DMA_CLLR_LA) | cllr_mask; + + /* Set new node as first circular node */ + pQList->FirstCircularNode = pNewNode; + } + /* Check if first circular node queue is not the last node */ + else if (pQList->FirstCircularNode != NULL) + { + /* Link first circular node to new node */ + pNewNode->LinkRegisters[cllr_offset] = ((uint32_t)pQList->FirstCircularNode & DMA_CLLR_LA) | cllr_mask; + } + else + { + /* Prevent MISRA-C2012-Rule-15.7 */ + } + + /* Check if queue contains one node */ + if (pQList->NodeNumber == 1U) + { + pQList->Head = pNewNode; + } + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Reset the linked-list queue and unlink queue nodes. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ResetQ(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check queue state */ + if (pQList->State == HAL_DMA_QUEUE_STATE_BUSY) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_BUSY; + + return HAL_ERROR; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Check the queue */ + if (pQList->Head != NULL) + { + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); + + /* Reset selected queue nodes */ + node_info.cllr_offset = cllr_offset; + DMA_List_ResetQueueNodes(pQList, &node_info); + } + + /* Reset head node address */ + pQList->Head = NULL; + + /* Reset node number */ + pQList->NodeNumber = 0U; + + /* Reset first circular node */ + pQList->FirstCircularNode = NULL; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Insert a source linked-list queue to a destination linked-list queue according to selecting previous node. + * @param pSrcQList : Pointer to a DMA_QListTypeDef structure that contains source queue information. + * @param pPrevNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list previous node registers + * configurations. + * @param pDestQList : Pointer to a DMA_QListTypeDef structure that contains destination queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_InsertQ(DMA_QListTypeDef *const pSrcQList, + DMA_NodeTypeDef const *const pPrevNode, + DMA_QListTypeDef *const pDestQList) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef src_q_node_info; + DMA_NodeInQInfoTypeDef dest_q_node_info; + + /* Check the source and destination queues and the previous node parameters */ + if ((pSrcQList == NULL) || (pDestQList == NULL)) + { + return HAL_ERROR; + } + + /* Check the source queue */ + if (pSrcQList->Head == NULL) + { + /* Update the queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check the source queue type */ + if (pSrcQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check the destination queue type */ + if (pDestQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check the source queue circularity */ + if (pSrcQList->FirstCircularNode != NULL) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pSrcQList->Head, pPrevNode, pDestQList->Head) != 0U) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pSrcQList->Head, pPrevNode, pDestQList->Head) != 0U) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the source queue state */ + pSrcQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the destination queue state */ + pDestQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pSrcQList->Head, &cllr_mask, &cllr_offset); + + /* Empty destination queue */ + if (pDestQList->Head == NULL) + { + pDestQList->Head = pSrcQList->Head; + pDestQList->NodeNumber = pSrcQList->NodeNumber; + } + /* Not empty destination queue */ + else + { + /* Previous node is empty */ + if (pPrevNode == NULL) + { + /* Find node and get its position in selected queue */ + src_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); + + /* Check if first circular node queue is the first node */ + if (pDestQList->FirstCircularNode == pDestQList->Head) + { + /* Find node and get its position in selected queue */ + dest_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pDestQList, NULL, &dest_q_node_info); + + /* Link destination queue tail node to new first circular node */ + ((DMA_NodeTypeDef *)dest_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = + ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; + + /* Set the head node of source queue as the first circular node */ + pDestQList->FirstCircularNode = pSrcQList->Head; + } + + /* Link the last node of source queue to the fist node of destination queue */ + ((DMA_NodeTypeDef *)(src_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pDestQList->Head & DMA_CLLR_LA) | cllr_mask; + pDestQList->Head = pSrcQList->Head; + pDestQList->NodeNumber += pSrcQList->NodeNumber; + } + /* Previous node is not empty */ + else + { + /* Find node and get its position in selected queue */ + dest_q_node_info.cllr_offset = cllr_offset; + if (DMA_List_FindNode(pDestQList, pPrevNode, &dest_q_node_info) == 0U) + { + /* Selected node is the last destination queue node */ + if (dest_q_node_info.currentnode_pos == pDestQList->NodeNumber) + { + /* Link the first node of source queue to the last node of destination queue */ + ((DMA_NodeTypeDef *)(dest_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; + pDestQList->NodeNumber += pSrcQList->NodeNumber; + + /* Check if first circular node queue is not empty */ + if (pDestQList->FirstCircularNode != NULL) + { + /* Find node and get its position in selected queue */ + src_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); + + /* Find first circular node */ + (void)DMA_List_FindNode(pDestQList, pDestQList->FirstCircularNode, &dest_q_node_info); + + /* Link last source queue node to first destination queue */ + ((DMA_NodeTypeDef *)src_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = + (dest_q_node_info.currentnode_addr & DMA_CLLR_LA) | cllr_mask; + } + } + /* Selected node is not the last destination queue node */ + else + { + /* Link the first node of source queue to the previous node of destination queue */ + ((DMA_NodeTypeDef *)(dest_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; + + /* Find node and get its position in selected queue */ + src_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); + + /* Link the last node of source queue to the next node of destination queue */ + ((DMA_NodeTypeDef *)(src_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + (dest_q_node_info.nextnode_addr & DMA_CLLR_LA) | cllr_mask; + + /* Update queues counter */ + pDestQList->NodeNumber += pSrcQList->NodeNumber; + } + } + else + { + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; + + return HAL_ERROR; + } + } + } + + /* Clean the source queue variable as it is obsolete */ + DMA_List_CleanQueue(pSrcQList); + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the destination queue state */ + pDestQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(src_q_node_info); + UNUSED(dest_q_node_info); + + return HAL_OK; +} + +/** + * @brief Insert a source linked-list queue at the head of destination queue. + * @param pSrcQList : Pointer to a DMA_QListTypeDef structure that contains source queue information. + * @param pDestQList : Pointer to a DMA_QListTypeDef structure that contains destination queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_InsertQ_Head(DMA_QListTypeDef *const pSrcQList, + DMA_QListTypeDef *const pDestQList) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef src_q_node_info; + DMA_NodeInQInfoTypeDef dest_q_node_info; + + /* Check the source and destination queues and the previous node parameters */ + if ((pSrcQList == NULL) || (pDestQList == NULL)) + { + return HAL_ERROR; + } + + /* Check the source queue */ + if (pSrcQList->Head == NULL) + { + /* Update the queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check the source queue type */ + if (pSrcQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check the destination queue type */ + if (pDestQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pSrcQList->Head, pDestQList->Head, NULL) != 0U) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pSrcQList->Head, pDestQList->Head, NULL) != 0U) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the source queue state */ + pSrcQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the destination queue state */ + pDestQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pSrcQList->Head, &cllr_mask, &cllr_offset); + + /* Empty destination queue */ + if (pDestQList->Head == NULL) + { + pDestQList->Head = pSrcQList->Head; + pDestQList->NodeNumber = pSrcQList->NodeNumber; + } + /* Not empty destination queue */ + else + { + /* Find node and get its position in selected queue */ + src_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); + + /* Check if first circular node queue is the first node */ + if (pDestQList->FirstCircularNode == pDestQList->Head) + { + /* Find node and get its position in selected queue */ + dest_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pDestQList, NULL, &dest_q_node_info); + + /* Link destination queue tail node to new first circular node */ + ((DMA_NodeTypeDef *)dest_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = + ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; + + /* Set the head node of source queue as the first circular node */ + pDestQList->FirstCircularNode = pSrcQList->Head; + } + + /* Link the last node of source queue to the fist node of destination queue */ + ((DMA_NodeTypeDef *)(src_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pDestQList->Head & DMA_CLLR_LA) | cllr_mask; + pDestQList->Head = pSrcQList->Head; + pDestQList->NodeNumber += pSrcQList->NodeNumber; + } + + /* Clean the source queue variable as it is obsolete */ + DMA_List_CleanQueue(pSrcQList); + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the destination queue state */ + pDestQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(src_q_node_info); + UNUSED(dest_q_node_info); + + return HAL_OK; +} + +/** + * @brief Insert a source linked-list queue at the tail of destination queue. + * @param pSrcQList : Pointer to a DMA_QListTypeDef structure that contains source queue information. + * @param pDestQList : Pointer to a DMA_QListTypeDef structure that contains destination queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_InsertQ_Tail(DMA_QListTypeDef *const pSrcQList, + DMA_QListTypeDef *const pDestQList) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef src_q_node_info; + DMA_NodeInQInfoTypeDef dest_q_node_info; + + /* Check the source and destination queues and the previous node parameters */ + if ((pSrcQList == NULL) || (pDestQList == NULL)) + { + return HAL_ERROR; + } + + /* Check the source queue */ + if (pSrcQList->Head == NULL) + { + /* Update the queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check the source queue type */ + if (pSrcQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check the destination queue type */ + if (pDestQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Check nodes base addresses */ + if (DMA_List_CheckNodesBaseAddresses(pSrcQList->Head, pDestQList->Head, NULL) != 0U) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_OUTOFRANGE; + + return HAL_ERROR; + } + + /* Check nodes types compatibility */ + if (DMA_List_CheckNodesTypes(pSrcQList->Head, pDestQList->Head, NULL) != 0U) + { + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the source queue state */ + pSrcQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the source queue error code */ + pSrcQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the destination queue state */ + pDestQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pSrcQList->Head, &cllr_mask, &cllr_offset); + + /* Empty destination queue */ + if (pDestQList->Head == NULL) + { + pDestQList->Head = pSrcQList->Head; + pDestQList->NodeNumber = pSrcQList->NodeNumber; + } + /* Not empty destination queue */ + else + { + /* Find node and get its position in selected queue */ + dest_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pDestQList, NULL, &dest_q_node_info); + + /* Update source queue last node CLLR to link it with destination first node */ + ((DMA_NodeTypeDef *)(dest_q_node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pSrcQList->Head & DMA_CLLR_LA) | cllr_mask; + pDestQList->NodeNumber += pSrcQList->NodeNumber; + + /* Check if first circular node queue is not empty */ + if (pDestQList->FirstCircularNode != NULL) + { + /* Find node and get its position in selected queue */ + src_q_node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pSrcQList, NULL, &src_q_node_info); + + /* Find first circular node */ + (void)DMA_List_FindNode(pDestQList, pDestQList->FirstCircularNode, &dest_q_node_info); + + /* Link last source queue node to first destination queue */ + ((DMA_NodeTypeDef *)src_q_node_info.currentnode_addr)->LinkRegisters[cllr_offset] = + (dest_q_node_info.currentnode_addr & DMA_CLLR_LA) | cllr_mask; + } + } + + /* Clean the source queue variable as it is obsolete */ + DMA_List_CleanQueue(pSrcQList); + + /* Update the destination queue error code */ + pDestQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the destination queue state */ + pDestQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(src_q_node_info); + + return HAL_OK; +} + +/** + * @brief Set circular mode configuration for linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pFirstCircularNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list first circular node + * registers configurations. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_SetCircularModeConfig(DMA_QListTypeDef *const pQList, + DMA_NodeTypeDef *const pFirstCircularNode) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue and the first circular node parameters */ + if ((pQList == NULL) || (pFirstCircularNode == NULL)) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue circular mode */ + if (pQList->FirstCircularNode != NULL) + { + if (pQList->FirstCircularNode == pFirstCircularNode) + { + return HAL_OK; + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pFirstCircularNode, &cllr_mask, &cllr_offset); + + /* Find the first circular node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + if (DMA_List_FindNode(pQList, pFirstCircularNode, &node_info) == 0U) + { + /* Find the last queue node and get its position in selected queue */ + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Set circular mode */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pFirstCircularNode & DMA_CLLR_LA) | cllr_mask; + + /* Update first circular node in queue */ + pQList->FirstCircularNode = pFirstCircularNode; + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NOTFOUND; + + return HAL_ERROR; + } + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Set circular mode for linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_SetCircularMode(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_mask; + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue circular mode */ + if (pQList->FirstCircularNode != NULL) + { + if (pQList->FirstCircularNode == pQList->Head) + { + return HAL_OK; + } + else + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, &cllr_mask, &cllr_offset); + + /* Find the last queue node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Set circular mode */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = + ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; + + /* Update linked-list circular state */ + pQList->FirstCircularNode = pQList->Head; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Clear circular mode for linked-list queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ClearCircularMode(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_offset; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check queue circular mode */ + if (pQList->FirstCircularNode == NULL) + { + return HAL_OK; + } + + /* Check queue type */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); + + /* Find the last queue node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + + /* Clear circular mode */ + ((DMA_NodeTypeDef *)(node_info.currentnode_addr))->LinkRegisters[cllr_offset] = 0U; + + /* Update linked-list circular configuration */ + pQList->FirstCircularNode = NULL; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + /* Prevent MISRA-C2012-Rule-2.2_b */ + UNUSED(node_info); + + return HAL_OK; +} + +/** + * @brief Convert a linked-list queue to dynamic (Optimized DMA queue execution). + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ConvertQToDynamic(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_offset; + uint32_t currentnode_addr; + DMA_NodeTypeDef context_node; + DMA_NodeInQInfoTypeDef node_info; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check if queue is dynamic */ + if (pQList->Type == QUEUE_TYPE_DYNAMIC) + { + return HAL_OK; + } + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); + + /* Check queue circularity */ + if (pQList->FirstCircularNode != 0U) + { + /* Find the last queue node and get its position in selected queue */ + node_info.cllr_offset = cllr_offset; + (void)DMA_List_FindNode(pQList, NULL, &node_info); + } + + /* Set current node address */ + currentnode_addr = (uint32_t)pQList->Head; + + /* Store register value */ + DMA_List_FillNode(pQList->Head, &context_node); + + /* Convert all nodes to dyncamic (Bypass head node) */ + for (uint32_t node_count = 1U; node_count < pQList->NodeNumber; node_count++) + { + /* Update node address */ + MODIFY_REG(currentnode_addr, DMA_CLLR_LA, (context_node.LinkRegisters[cllr_offset] & DMA_CLLR_LA)); + + /* Bypass the first circular node when first circular node isn't the last queue node */ + if (((uint32_t)pQList->FirstCircularNode != 0U) && + ((uint32_t)pQList->FirstCircularNode != node_info.currentnode_addr) && + ((uint32_t)pQList->FirstCircularNode == currentnode_addr)) + { + /* Copy first circular node to context node */ + DMA_List_FillNode(pQList->FirstCircularNode, &context_node); + } + else + { + /* Convert current node to dynamic */ + DMA_List_ConvertNodeToDynamic((uint32_t)&context_node, currentnode_addr, (cllr_offset + 1U)); + } + } + + /* Check if first circular node is the last node queue */ + if (((uint32_t)pQList->FirstCircularNode != 0U) && + ((uint32_t)pQList->FirstCircularNode != node_info.currentnode_addr)) + { + /* Update all queue nodes CLLR */ + DMA_List_UpdateDynamicQueueNodesCLLR(pQList, LASTNODE_ISNOT_CIRCULAR); + } + else + { + /* Update all queue nodes CLLR */ + DMA_List_UpdateDynamicQueueNodesCLLR(pQList, LASTNODE_IS_CIRCULAR); + } + + /* Set queue type */ + pQList->Type = QUEUE_TYPE_DYNAMIC; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Convert a linked-list queue to static (Not optimized DMA queue execution). + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_ConvertQToStatic(DMA_QListTypeDef *const pQList) +{ + uint32_t cllr_offset; + uint32_t currentnode_addr; + DMA_NodeTypeDef context_node; + + /* Check the queue parameter */ + if (pQList == NULL) + { + return HAL_ERROR; + } + + /* Check the queue */ + if (pQList->Head == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_EMPTY; + + return HAL_ERROR; + } + + /* Check if queue is static */ + if (pQList->Type == QUEUE_TYPE_STATIC) + { + return HAL_OK; + } + + /* Set current node address */ + currentnode_addr = (uint32_t)pQList->Head; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_BUSY; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Get CLLR register mask and offset */ + DMA_List_GetCLLRNodeInfo(pQList->Head, NULL, &cllr_offset); + + /* Set all CLLR queue nodes to their default positions */ + DMA_List_UpdateStaticQueueNodesCLLR(pQList, UPDATE_CLLR_POSITION); + + /* Convert all nodes to static (Bypass head node) */ + for (uint32_t node_count = 1U; node_count < pQList->NodeNumber; node_count++) + { + /* Update context node register values */ + DMA_List_FillNode((DMA_NodeTypeDef *)currentnode_addr, &context_node); + + /* Update node address */ + MODIFY_REG(currentnode_addr, DMA_CLLR_LA, (context_node.LinkRegisters[cllr_offset] & DMA_CLLR_LA)); + + /* Convert current node to static */ + DMA_List_ConvertNodeToStatic((uint32_t)&context_node, currentnode_addr, (cllr_offset + 1U)); + } + + /* Set all CLLR queue nodes to their default values */ + DMA_List_UpdateStaticQueueNodesCLLR(pQList, UPDATE_CLLR_VALUE); + + /* Set queue type */ + pQList->Type = QUEUE_TYPE_STATIC; + + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Update the queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Link linked-list queue to a DMA channel. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_LinkQ(DMA_HandleTypeDef *const hdma, + DMA_QListTypeDef *const pQList) +{ + HAL_DMA_StateTypeDef state; + + /* Check the DMA channel handle and the queue parameters */ + if ((hdma == NULL) || (pQList == NULL)) + { + return HAL_ERROR; + } + + /* Get DMA state */ + state = hdma->State; + + /* Check DMA channel state */ + if ((hdma->State == HAL_DMA_STATE_BUSY) || (state == HAL_DMA_STATE_SUSPEND)) + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + /* Check queue state */ + if (pQList->State == HAL_DMA_QUEUE_STATE_BUSY) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_BUSY; + + return HAL_ERROR; + } + + /* Check linearity compatibility */ + if ((IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance) == 0U) && + ((pQList->Head->NodeInfo & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR)) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_UNSUPPORTED; + + return HAL_ERROR; + } + + /* Check circularity compatibility */ + if (hdma->Mode == DMA_LINKEDLIST_CIRCULAR) + { + /* Check first circular node */ + if (pQList->FirstCircularNode == NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + } + else + { + /* Check first circular node */ + if (pQList->FirstCircularNode != NULL) + { + /* Update the queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_INVALIDTYPE; + + return HAL_ERROR; + } + } + + /* Register queue to DMA handle */ + hdma->LinkedListQueue = pQList; + + return HAL_OK; +} + +/** + * @brief Unlink linked-list queue from a DMA channel. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_List_UnLinkQ(DMA_HandleTypeDef *const hdma) +{ + HAL_DMA_StateTypeDef state; + + /* Check the DMA channel parameter */ + if (hdma == NULL) + { + return HAL_ERROR; + } + + /* Get DMA state */ + state = hdma->State; + + /* Check DMA channel state */ + if ((hdma->State == HAL_DMA_STATE_BUSY) || (state == HAL_DMA_STATE_SUSPEND)) + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + /* Clear queue information from DMA channel handle */ + hdma->LinkedListQueue = NULL; + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup DMAEx_Exported_Functions_Group4 + * +@verbatim + ====================================================================================================================== + ##### Data handling, repeated block and trigger configuration functions ##### + ====================================================================================================================== + [..] + This section provides functions allowing to : + (+) Configure DMA channel data handling. + (+) Configure DMA channel repeated block. + (+) Configure DMA channel trigger. + + [..] + (+) The HAL_DMAEx_ConfigDataHandling() function allows to configure DMA channel data handling. + (++) GPDMA or HPDMA data handling : byte-based reordering, packing/unpacking, padding/truncation, + sign extension and left/right alignment. + + (+) The HAL_DMAEx_ConfigTrigger() function allows to configure DMA channel HW triggers. + + (+) The HAL_DMAEx_ConfigRepeatBlock() function allows to configure DMA channel repeated block. + (++) This feature is available only for channel that supports 2 dimensions addressing capability. + +@endverbatim + * @{ + */ + +/** + * @brief Configure the DMA channel data handling according to the specified parameters in the + * DMA_DataHandlingConfTypeDef. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA Channel. + * @param pConfigDataHandling : Pointer to a DMA_DataHandlingConfTypeDef structure that contains the data handling + * configuration. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_ConfigDataHandling(DMA_HandleTypeDef *const hdma, + DMA_DataHandlingConfTypeDef const *const pConfigDataHandling) +{ + /* Check the DMA peripheral handle and data handling parameters */ + if ((hdma == NULL) || (pConfigDataHandling == NULL)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_DATA_ALIGNMENT(pConfigDataHandling->DataAlignment)); + assert_param(IS_DMA_DATA_EXCHANGE(pConfigDataHandling->DataExchange)); + + /* Check DMA channel state */ + if (hdma->State == HAL_DMA_STATE_READY) + { + MODIFY_REG(hdma->Instance->CTR1, (DMA_CTR1_DWX | DMA_CTR1_DHX | DMA_CTR1_DBX | DMA_CTR1_SBX | DMA_CTR1_PAM), + (pConfigDataHandling->DataAlignment | pConfigDataHandling->DataExchange)); + } + else + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Configure the DMA channel trigger according to the specified parameters in the DMA_TriggerConfTypeDef. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for + * the specified DMA Channel. + * @param pConfigTrigger : Pointer to a DMA_TriggerConfTypeDef structure that contains the trigger configuration. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_ConfigTrigger(DMA_HandleTypeDef *const hdma, + DMA_TriggerConfTypeDef const *const pConfigTrigger) +{ + /* Check the DMA peripheral handle and trigger parameters */ + if ((hdma == NULL) || (pConfigTrigger == NULL)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); + assert_param(IS_DMA_TRIGGER_POLARITY(pConfigTrigger->TriggerPolarity)); + assert_param(IS_DMA_TRIGGER_MODE(pConfigTrigger->TriggerMode)); + assert_param(IS_DMA_TRIGGER_SELECTION(pConfigTrigger->TriggerSelection)); + + /* Check DMA channel state */ + if (hdma->State == HAL_DMA_STATE_READY) + { + MODIFY_REG(hdma->Instance->CTR2, (DMA_CTR2_TRIGPOL | DMA_CTR2_TRIGSEL | DMA_CTR2_TRIGM), + (pConfigTrigger->TriggerPolarity | pConfigTrigger->TriggerMode | + (pConfigTrigger->TriggerSelection << DMA_CTR2_TRIGSEL_Pos))); + } + else + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Configure the DMA channel repeated block according to the specified parameters in the + * DMA_RepeatBlockConfTypeDef. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA Channel. + * @param pConfigRepeatBlock : Pointer to a DMA_RepeatBlockConfTypeDef structure that contains the repeated block + * configuration. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_ConfigRepeatBlock(DMA_HandleTypeDef *const hdma, + DMA_RepeatBlockConfTypeDef const *const pConfigRepeatBlock) +{ + uint32_t tmpreg1; + uint32_t tmpreg2; + + /* Check the DMA peripheral handle and repeated block parameters */ + if ((hdma == NULL) || (pConfigRepeatBlock == NULL)) + { + return HAL_ERROR; + } + + /* Check parameters */ + assert_param(IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance)); + assert_param(IS_DMA_REPEAT_COUNT(pConfigRepeatBlock->RepeatCount)); + assert_param(IS_DMA_BURST_ADDR_OFFSET(pConfigRepeatBlock->SrcAddrOffset)); + assert_param(IS_DMA_BURST_ADDR_OFFSET(pConfigRepeatBlock->DestAddrOffset)); + assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pConfigRepeatBlock->BlkSrcAddrOffset)); + assert_param(IS_DMA_BLOCK_ADDR_OFFSET(pConfigRepeatBlock->BlkDestAddrOffset)); + + /* Check DMA channel state */ + if (hdma->State == HAL_DMA_STATE_READY) + { + /* Store repeat block count */ + tmpreg1 = ((pConfigRepeatBlock->RepeatCount - 1U) << DMA_CBR1_BRC_Pos); + + /* Check the sign of single/burst destination address offset value */ + if (pConfigRepeatBlock->DestAddrOffset < 0) + { + /* Store single/burst destination address offset configuration (signed case) */ + tmpreg1 |= DMA_CBR1_DDEC; + tmpreg2 = (uint32_t)(- pConfigRepeatBlock->DestAddrOffset); + tmpreg2 = tmpreg2 << DMA_CTR3_DAO_Pos; + } + else + { + /* Store single/burst destination address offset configuration (unsigned case) */ + tmpreg2 = ((uint32_t)pConfigRepeatBlock->DestAddrOffset << DMA_CTR3_DAO_Pos); + } + + /* Check the sign of single/burst source address offset value */ + if (pConfigRepeatBlock->SrcAddrOffset < 0) + { + /* Store single/burst source address offset configuration (signed case) */ + tmpreg1 |= DMA_CBR1_SDEC; + tmpreg2 |= (uint32_t)(- pConfigRepeatBlock->SrcAddrOffset); + } + else + { + /* Store single/burst source address offset configuration (unsigned case) */ + tmpreg2 |= (uint32_t)pConfigRepeatBlock->SrcAddrOffset; + } + + /* Write DMA Channel Transfer Register 3 (CTR3) */ + WRITE_REG(hdma->Instance->CTR3, tmpreg2); + + /* Check the sign of block destination address offset value */ + if (pConfigRepeatBlock->BlkDestAddrOffset < 0) + { + /* Store block destination address offset configuration (signed case) */ + tmpreg1 |= DMA_CBR1_BRDDEC; + tmpreg2 = (uint32_t)(- pConfigRepeatBlock->BlkDestAddrOffset); + tmpreg2 = tmpreg2 << DMA_CBR2_BRDAO_Pos; + } + else + { + /* Store block destination address offset configuration (unsigned case) */ + tmpreg2 = ((uint32_t)pConfigRepeatBlock->BlkDestAddrOffset << DMA_CBR2_BRDAO_Pos); + } + + /* Check the sign of block source address offset value */ + if (pConfigRepeatBlock->BlkSrcAddrOffset < 0) + { + /* Store block source address offset configuration (signed case) */ + tmpreg1 |= DMA_CBR1_BRSDEC; + tmpreg2 |= (uint32_t)(- pConfigRepeatBlock->BlkSrcAddrOffset); + } + else + { + /* Store block source address offset configuration (unsigned case) */ + tmpreg2 |= (uint32_t)pConfigRepeatBlock->BlkSrcAddrOffset; + } + + /* Write DMA Channel block register 2 (CBR2) */ + WRITE_REG(hdma->Instance->CBR2, tmpreg2); + + /* Write DMA Channel block register 1 (CBR1) */ + WRITE_REG(hdma->Instance->CBR1, tmpreg1); + } + else + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_BUSY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup DMAEx_Exported_Functions_Group5 + * +@verbatim + ====================================================================================================================== + ##### Suspend and resume operation functions ##### + ====================================================================================================================== + [..] + This section provides functions allowing to : + (+) Suspend any ongoing DMA channel transfer. + (+) Resume any suspended DMA channel transfer. + + [..] + (+) The HAL_DMAEx_Suspend() function allows to suspend any ongoing DMA channel transfer in polling mode (Blocking + mode). + + (+) The HAL_DMAEx_Suspend_IT() function allows to suspend any ongoing DMA channel transfer in interrupt mode + (Non-blocking mode). + + (+) The HAL_DMAEx_Resume() function allows to resume any suspended DMA channel transfer. + +@endverbatim + * @{ + */ + +/** + * @brief Suspend any ongoing DMA channel transfer in polling mode (Blocking mode). + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA channel. + * @note After suspending a DMA channel, a check for wait until the DMA channel is effectively suspended is added. If + * a channel is suspended while a data transfer is ongoing, the current data will be transferred and the + * channel will be effectively suspended only after the transfer of this single/burst data is finished. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_Suspend(DMA_HandleTypeDef *const hdma) +{ + /* Get tick number */ + uint32_t tickstart = HAL_GetTick(); + + /* Check the DMA peripheral handle */ + if (hdma == NULL) + { + return HAL_ERROR; + } + + /* Check DMA channel state */ + if (hdma->State != HAL_DMA_STATE_BUSY) + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + else + { + /* Suspend the channel */ + hdma->Instance->CCR |= DMA_CCR_SUSP; + + /* Check if the DMA channel is suspended */ + while ((hdma->Instance->CSR & DMA_CSR_SUSPF) == 0U) + { + /* Check for the timeout */ + if ((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) + { + /* Update the DMA channel error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT; + + /* Update the DMA channel state */ + hdma->State = HAL_DMA_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + } + + /* Update the DMA channel state */ + hdma->State = HAL_DMA_STATE_SUSPEND; + } + + return HAL_OK; +} + +/** + * @brief Suspend any ongoing DMA channel transfer in polling mode (Non-blocking mode). + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_Suspend_IT(DMA_HandleTypeDef *const hdma) +{ + /* Check the DMA peripheral handle parameter */ + if (hdma == NULL) + { + return HAL_ERROR; + } + + /* Check DMA channel state */ + if (hdma->State != HAL_DMA_STATE_BUSY) + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + else + { + /* Suspend the DMA channel and activate suspend interrupt */ + hdma->Instance->CCR |= (DMA_CCR_SUSP | DMA_CCR_SUSPIE); + } + + return HAL_OK; +} + +/** + * @brief Resume any suspended DMA channel transfer. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DMAEx_Resume(DMA_HandleTypeDef *const hdma) +{ + /* Check the DMA peripheral handle parameter */ + if (hdma == NULL) + { + return HAL_ERROR; + } + + /* Check DMA channel state */ + if (hdma->State != HAL_DMA_STATE_SUSPEND) + { + /* Update the DMA channel error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + else + { + /* Resume the DMA channel */ + hdma->Instance->CCR &= (~DMA_CCR_SUSP); + + /* Clear the suspend flag */ + hdma->Instance->CFCR |= DMA_CFCR_SUSPF; + + /* Update the DMA channel state */ + hdma->State = HAL_DMA_STATE_BUSY; + } + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup DMAEx_Exported_Functions_Group6 + * +@verbatim + ====================================================================================================================== + ##### Fifo status function ##### + ====================================================================================================================== + [..] + This section provides function allowing to get DMA channel FIFO level. + + [..] + (+) The HAL_DMAEx_GetFifoLevel() function allows to return the number of available write beats in the FIFO, in + units of the programmed destination data. + (++) This API is available only for DMA channels that supports FIFO. + +@endverbatim + * @{ + */ + +/** + * @brief Get and returns the DMA channel FIFO level. + * @param hdma : Pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval Returns the number of available beats in FIFO. + */ +uint32_t HAL_DMAEx_GetFifoLevel(DMA_HandleTypeDef const *const hdma) +{ + return ((hdma->Instance->CSR & DMA_CSR_FIFOL) >> DMA_CSR_FIFOL_Pos); +} +/** + * @} + */ + +/** + * @} + */ + +/* Private functions -------------------------------------------------------------------------------------------------*/ +/** @defgroup DMAEx_Private_Functions DMAEx Private Functions + * @brief DMAEx Private Functions + * @{ + */ + +/** + * @brief Initialize the DMA handle according to the specified parameters in the DMA_InitTypeDef. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains the configuration information for the + * specified DMA Channel. + * @retval None. + */ +static void DMA_List_Init(DMA_HandleTypeDef const *const hdma) +{ + uint32_t tmpreg; + + /* Prepare DMA Channel Control Register (CCR) value */ + tmpreg = hdma->InitLinkedList.Priority | hdma->InitLinkedList.LinkStepMode; + + /* Check DMA channel instance */ + if ((IS_HPDMA_INSTANCE(hdma->Instance) != 0U) || (IS_GPDMA_INSTANCE(hdma->Instance) != 0U)) + { + tmpreg |= hdma->InitLinkedList.LinkAllocatedPort; + } + + /* Write DMA Channel Control Register (CCR) */ + MODIFY_REG(hdma->Instance->CCR, DMA_CCR_PRIO | DMA_CCR_LAP | DMA_CCR_LSM, tmpreg); + + /* Write DMA Channel Control Register (CTR1) */ + WRITE_REG(hdma->Instance->CTR1, 0U); + + /* Write DMA Channel Control Register (CTR2) */ + WRITE_REG(hdma->Instance->CTR2, hdma->InitLinkedList.TransferEventMode); + + /* Write DMA Channel Control Register (CBR1) */ + WRITE_REG(hdma->Instance->CBR1, 0U); + + /* Write DMA Channel Control Register (CSAR) */ + WRITE_REG(hdma->Instance->CSAR, 0U); + + /* Write DMA Channel Control Register (CDAR) */ + WRITE_REG(hdma->Instance->CDAR, 0U); + + /* If 2D Addressing is supported by current channel */ + if (IS_DMA_2D_ADDRESSING_INSTANCE(hdma->Instance) != 0U) + { + /* Write DMA Channel Control Register (CTR3) */ + WRITE_REG(hdma->Instance->CTR3, 0U); + + /* Write DMA Channel Control Register (CBR2) */ + WRITE_REG(hdma->Instance->CBR2, 0U); + } + + /* Write DMA Channel linked-list address register (CLLR) */ + WRITE_REG(hdma->Instance->CLLR, 0U); +} + +/** + * @brief Build a DMA channel node according to the specified parameters in the DMA_NodeConfTypeDef. + * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the + * specified DMA linked-list Node. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @retval None. + */ +static void DMA_List_BuildNode(DMA_NodeConfTypeDef const *const pNodeConfig, + DMA_NodeTypeDef *const pNode) +{ + int32_t blockoffset; + + /* Update CTR1 register value ***************************************************************************************/ + /* Prepare DMA channel transfer register (CTR1) value */ + pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] = pNodeConfig->Init.DestInc | + pNodeConfig->Init.DestDataWidth | + pNodeConfig->DataHandlingConfig.DataAlignment | + pNodeConfig->Init.SrcInc | + pNodeConfig->Init.SrcDataWidth; + + + /* Add parameters related to DMA configuration */ + if ((pNodeConfig->NodeType & (DMA_CHANNEL_TYPE_GPDMA | DMA_CHANNEL_TYPE_HPDMA)) != 0U) + { + /* Prepare DMA channel transfer register (CTR1) value */ + pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] |= + (pNodeConfig->Init.TransferAllocatedPort | pNodeConfig->DataHandlingConfig.DataExchange | + (((pNodeConfig->Init.DestBurstLength - 1U) << DMA_CTR1_DBL_1_Pos) & DMA_CTR1_DBL_1) | + (((pNodeConfig->Init.SrcBurstLength - 1U) << DMA_CTR1_SBL_1_Pos) & DMA_CTR1_SBL_1)); + } + /*********************************************************************************** CTR1 register value is updated */ + + + /* Update CTR2 register value ***************************************************************************************/ + /* Prepare DMA channel transfer register 2 (CTR2) value */ + pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] = pNodeConfig->Init.TransferEventMode | + (pNodeConfig->Init.Request & (DMA_CTR2_REQSEL | DMA_CTR2_SWREQ)); + + /* Check for memory to peripheral transfer */ + if ((pNodeConfig->Init.Direction) == DMA_MEMORY_TO_PERIPH) + { + /* Check for GPDMA OR HPDMA */ + if ((pNodeConfig->NodeType & (DMA_CHANNEL_TYPE_GPDMA | DMA_CHANNEL_TYPE_HPDMA)) != 0U) + { + pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= DMA_CTR2_DREQ; + } + } + /* Memory to memory transfer */ + else if ((pNodeConfig->Init.Direction) == DMA_MEMORY_TO_MEMORY) + { + pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= DMA_CTR2_SWREQ; + } + else + { + /* Prevent MISRA-C2012-Rule-15.7 */ + } + + /* Configure HW Peripheral flow control selection */ + pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= pNodeConfig->Init.Mode; + + /* Check if trigger feature is active */ + if (pNodeConfig->TriggerConfig.TriggerPolarity != DMA_TRIG_POLARITY_MASKED) + { + /* Prepare DMA channel transfer register 2 (CTR2) value */ + pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] |= + pNodeConfig->TriggerConfig.TriggerMode | pNodeConfig->TriggerConfig.TriggerPolarity | + ((pNodeConfig->TriggerConfig.TriggerSelection << DMA_CTR2_TRIGSEL_Pos) & DMA_CTR2_TRIGSEL); + } + /*********************************************************************************** CTR2 register value is updated */ + + + /* Update CBR1 register value ***************************************************************************************/ + /* Prepare DMA channel block register 1 (CBR1) value */ + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (pNodeConfig->DataSize & DMA_CBR1_BNDT); + + /* If 2D addressing is supported by the selected DMA channel */ + if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + /* Set the new CBR1 Register value */ + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= + (((pNodeConfig->RepeatBlockConfig.RepeatCount - 1U) << DMA_CBR1_BRC_Pos) & DMA_CBR1_BRC); + + /* If the source address offset is negative, set SDEC bit */ + if (pNodeConfig->RepeatBlockConfig.SrcAddrOffset < 0) + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_SDEC; + } + else + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_SDEC); + } + + /* If the destination address offset is negative, set DDEC bit */ + if (pNodeConfig->RepeatBlockConfig.DestAddrOffset < 0) + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_DDEC; + } + else + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_DDEC); + } + + /* If the repeated block source address offset is negative, set BRSEC bit */ + if (pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset < 0) + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_BRSDEC; + } + else + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_BRSDEC); + } + + /* if the repeated block destination address offset is negative, set BRDEC bit */ + if (pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset < 0) + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] |= DMA_CBR1_BRDDEC; + } + else + { + pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] &= (~DMA_CBR1_BRDDEC); + } + } + /*********************************************************************************** CBR1 register value is updated */ + + + /* Update CSAR register value ***************************************************************************************/ + pNode->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = pNodeConfig->SrcAddress; + /*********************************************************************************** CSAR register value is updated */ + + + /* Update CDAR register value ***************************************************************************************/ + pNode->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = pNodeConfig->DstAddress; + /*********************************************************************************** CDAR register value is updated */ + + /* Check if the selected channel is 2D addressing */ + if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + /* Update CTR3 register value *************************************************************************************/ + /* Write new CTR3 Register value : source address offset */ + if (pNodeConfig->RepeatBlockConfig.SrcAddrOffset < 0) + { + blockoffset = (- pNodeConfig->RepeatBlockConfig.SrcAddrOffset); + pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] = ((uint32_t)blockoffset & DMA_CTR3_SAO); + } + else + { + pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] = + ((uint32_t)pNodeConfig->RepeatBlockConfig.SrcAddrOffset & DMA_CTR3_SAO); + } + + /* Write new CTR3 Register value : destination address offset */ + if (pNodeConfig->RepeatBlockConfig.DestAddrOffset < 0) + { + blockoffset = (- pNodeConfig->RepeatBlockConfig.DestAddrOffset); + pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] |= (((uint32_t)blockoffset << DMA_CTR3_DAO_Pos) & DMA_CTR3_DAO); + } + else + { + pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] |= + (((uint32_t)pNodeConfig->RepeatBlockConfig.DestAddrOffset << DMA_CTR3_DAO_Pos) & DMA_CTR3_DAO); + } + /********************************************************************************* CTR3 register value is updated */ + + + /* Update CBR2 register value *************************************************************************************/ + /* Write new CBR2 Register value : repeated block source address offset */ + if (pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset < 0) + { + blockoffset = (- pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset); + pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] = ((uint32_t)blockoffset & DMA_CBR2_BRSAO); + } + else + { + pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] = + ((uint32_t)pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset & DMA_CBR2_BRSAO); + } + + /* Write new CBR2 Register value : repeated block destination address offset */ + if (pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset < 0) + { + blockoffset = (- pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset); + pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] |= + (((uint32_t)blockoffset & DMA_CBR2_BRSAO) << DMA_CBR2_BRDAO_Pos); + } + else + { + pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] |= + (((uint32_t)pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset << DMA_CBR2_BRDAO_Pos) & DMA_CBR2_BRDAO); + } + /********************************************************************************* CBR2 register value is updated */ + } + + + /* Update node information value ************************************************************************************/ + /* Set node information */ + pNode->NodeInfo = pNodeConfig->NodeType; + if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + pNode->NodeInfo |= (NODE_CLLR_2D_DEFAULT_OFFSET << NODE_CLLR_IDX_POS); + } + else + { + pNode->NodeInfo |= (NODE_CLLR_LINEAR_DEFAULT_OFFSET << NODE_CLLR_IDX_POS); + } + /******************************************************************************** Node information value is updated */ +} + +/** + * @brief Get a DMA channel node configuration. + * @param pNodeConfig : Pointer to a DMA_NodeConfTypeDef structure that contains the configuration information for the + * specified DMA linked-list Node. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @retval None. + */ +static void DMA_List_GetNodeConfig(DMA_NodeConfTypeDef *const pNodeConfig, + DMA_NodeTypeDef const *const pNode) +{ + uint16_t offset; + + /* Get node information *********************************************************************************************/ + pNodeConfig->NodeType = (pNode->NodeInfo & NODE_TYPE_MASK); + /*************************************************************************************** Node type value is updated */ + + + /* Get CTR1 fields values *******************************************************************************************/ + pNodeConfig->Init.SrcInc = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_SINC; + pNodeConfig->Init.DestInc = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DINC; + pNodeConfig->Init.SrcDataWidth = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_SDW_LOG2; + pNodeConfig->Init.DestDataWidth = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + pNodeConfig->Init.SrcBurstLength = ((pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & + DMA_CTR1_SBL_1) >> DMA_CTR1_SBL_1_Pos) + 1U; + pNodeConfig->Init.DestBurstLength = ((pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & + DMA_CTR1_DBL_1) >> DMA_CTR1_DBL_1_Pos) + 1U; + pNodeConfig->Init.TransferAllocatedPort = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & + (DMA_CTR1_SAP | DMA_CTR1_DAP); + pNodeConfig->DataHandlingConfig.DataExchange = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & + (DMA_CTR1_SBX | DMA_CTR1_DBX | DMA_CTR1_DHX | DMA_CTR1_DWX); + pNodeConfig->DataHandlingConfig.DataAlignment = pNode->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_PAM; + /*********************************************************************************** CTR1 fields values are updated */ + + + /* Get CTR2 fields values *******************************************************************************************/ + if ((pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_SWREQ) != 0U) + { + pNodeConfig->Init.Request = DMA_REQUEST_SW; + pNodeConfig->Init.Direction = DMA_MEMORY_TO_MEMORY; + } + else + { + pNodeConfig->Init.Request = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_REQSEL; + + if ((pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_DREQ) != 0U) + { + pNodeConfig->Init.Direction = DMA_MEMORY_TO_PERIPH; + } + else + { + pNodeConfig->Init.Direction = DMA_PERIPH_TO_MEMORY; + } + } + + pNodeConfig->Init.BlkHWRequest = (pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_BREQ); + pNodeConfig->TriggerConfig.TriggerMode = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_TRIGM; + pNodeConfig->TriggerConfig.TriggerPolarity = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_TRIGPOL; + pNodeConfig->TriggerConfig.TriggerSelection = (pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & + DMA_CTR2_TRIGSEL) >> DMA_CTR2_TRIGSEL_Pos; + pNodeConfig->Init.TransferEventMode = pNode->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET] & DMA_CTR2_TCEM; + /*********************************************************************************** CTR2 fields values are updated */ + + + /* Get CBR1 fields **************************************************************************************************/ + pNodeConfig->DataSize = pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BNDT; + + if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + pNodeConfig->RepeatBlockConfig.RepeatCount = + ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BRC) >> DMA_CBR1_BRC_Pos) + 1U; + } + else + { + pNodeConfig->RepeatBlockConfig.RepeatCount = 1U; + } + /*********************************************************************************** CBR1 fields values are updated */ + + + /* Get CSAR field ***************************************************************************************************/ + pNodeConfig->SrcAddress = pNode->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET]; + /************************************************************************************** CSAR field value is updated */ + + + /* Get CDAR field ***************************************************************************************************/ + pNodeConfig->DstAddress = pNode->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET]; + /************************************************************************************** CDAR field value is updated */ + + /* Check if the selected channel is 2D addressing */ + if ((pNodeConfig->NodeType & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + /* Get CTR3 field *************************************************************************************************/ + offset = (uint16_t)(pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] & DMA_CTR3_SAO); + pNodeConfig->RepeatBlockConfig.SrcAddrOffset = (int32_t)offset; + + offset = (uint16_t)((pNode->LinkRegisters[NODE_CTR3_DEFAULT_OFFSET] & DMA_CTR3_DAO) >> DMA_CTR3_DAO_Pos); + pNodeConfig->RepeatBlockConfig.DestAddrOffset = (int32_t)offset; + + if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_SDEC) != 0U) + { + pNodeConfig->RepeatBlockConfig.SrcAddrOffset *= (-1); + } + + if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_DDEC) != 0U) + { + pNodeConfig->RepeatBlockConfig.DestAddrOffset *= (-1); + } + /************************************************************************************ CTR3 field value is updated */ + + + /* Get CBR2 fields ************************************************************************************************/ + offset = (uint16_t)(pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] & DMA_CBR2_BRSAO); + pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset = (int32_t)offset; + + offset = (uint16_t)((pNode->LinkRegisters[NODE_CBR2_DEFAULT_OFFSET] & DMA_CBR2_BRDAO) >> DMA_CBR2_BRDAO_Pos); + pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset = (int32_t)offset; + + if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BRSDEC) != 0U) + { + pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset *= (-1); + } + + if ((pNode->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] & DMA_CBR1_BRDDEC) != 0U) + { + pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset *= (-1); + } + /************************************************************************************ CBR2 field value is updated */ + } + else + { + /* Get CTR3 field *************************************************************************************************/ + pNodeConfig->RepeatBlockConfig.SrcAddrOffset = 0; + pNodeConfig->RepeatBlockConfig.DestAddrOffset = 0; + /************************************************************************************ CTR3 field value is updated */ + + + /* Get CBR2 fields ************************************************************************************************/ + pNodeConfig->RepeatBlockConfig.BlkSrcAddrOffset = 0; + pNodeConfig->RepeatBlockConfig.BlkDestAddrOffset = 0; + /************************************************************************************ CBR2 field value is updated */ + } +} + +/** + * @brief Check nodes base addresses compatibility. + * @param pNode1 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 1 registers configurations. + * @param pNode2 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 2 registers configurations. + * @param pNode3 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 3 registers configurations. + * @retval Return 0 when nodes addresses are compatible, 1 otherwise. + */ +static uint32_t DMA_List_CheckNodesBaseAddresses(DMA_NodeTypeDef const *const pNode1, + DMA_NodeTypeDef const *const pNode2, + DMA_NodeTypeDef const *const pNode3) +{ + uint32_t temp = (((uint32_t)pNode1 | (uint32_t)pNode2 | (uint32_t)pNode3) & DMA_CLBAR_LBA); + uint32_t ref = 0U; + + /* Check node 1 address */ + if ((uint32_t)pNode1 != 0U) + { + ref = (uint32_t)pNode1; + } + /* Check node 2 address */ + else if ((uint32_t)pNode2 != 0U) + { + ref = (uint32_t)pNode2; + } + /* Check node 3 address */ + else if ((uint32_t)pNode3 != 0U) + { + ref = (uint32_t)pNode3; + } + else + { + /* Prevent MISRA-C2012-Rule-15.7 */ + } + + /* Check addresses compatibility */ + if (temp != ((uint32_t)ref & DMA_CLBAR_LBA)) + { + return 1U; + } + + return 0U; +} + +/** + * @brief Check nodes types compatibility. + * @param pNode1 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 1 registers configurations. + * @param pNode2 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 2 registers configurations. + * @param pNode3 : Pointer to a DMA_NodeTypeDef structure that contains linked-list node 3 registers configurations. + * @retval Return 0 when nodes types are compatible, otherwise nodes types are not compatible. + */ +static uint32_t DMA_List_CheckNodesTypes(DMA_NodeTypeDef const *const pNode1, + DMA_NodeTypeDef const *const pNode2, + DMA_NodeTypeDef const *const pNode3) +{ + uint32_t ref = 0U; + + /* Check node 1 parameter */ + if (pNode1 != NULL) + { + ref = pNode1->NodeInfo & NODE_TYPE_MASK; + } + /* Check node 2 parameter */ + else if (pNode2 != NULL) + { + ref = pNode2->NodeInfo & NODE_TYPE_MASK; + } + /* Check node 3 parameter */ + else if (pNode3 != NULL) + { + ref = pNode3->NodeInfo & NODE_TYPE_MASK; + } + else + { + /* Prevent MISRA-C2012-Rule-15.7 */ + } + + /* Check node 2 parameter */ + if (pNode2 != NULL) + { + /* Check node type compatibility */ + if (ref != (pNode2->NodeInfo & NODE_TYPE_MASK)) + { + return 2U; + } + } + + /* Check node 3 parameter */ + if (pNode3 != NULL) + { + /* Check node type compatibility */ + if (ref != (pNode3->NodeInfo & NODE_TYPE_MASK)) + { + return 3U; + } + } + + return 0U; +} + +/** + * @brief Check nodes types compatibility. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @param cllr_mask : Pointer to CLLR register mask value. + * @param cllr_offset : Pointer to CLLR register offset value. + * @retval None. + */ +static void DMA_List_GetCLLRNodeInfo(DMA_NodeTypeDef const *const pNode, + uint32_t *const cllr_mask, + uint32_t *const cllr_offset) +{ + /* Check node type */ + if ((pNode->NodeInfo & DMA_CHANNEL_TYPE_2D_ADDR) == DMA_CHANNEL_TYPE_2D_ADDR) + { + /* Update CLLR register mask value */ + if (cllr_mask != NULL) + { + *cllr_mask = DMA_CLLR_UT1 | DMA_CLLR_UT2 | DMA_CLLR_UB1 | DMA_CLLR_USA | DMA_CLLR_UDA | DMA_CLLR_UT3 | + DMA_CLLR_UB2 | DMA_CLLR_ULL; + } + + /* Update CLLR register offset */ + if (cllr_offset != NULL) + { + *cllr_offset = NODE_CLLR_2D_DEFAULT_OFFSET; + } + } + /* Update CLLR and register number for linear addressing node */ + else + { + /* Update CLLR register mask value */ + if (cllr_mask != NULL) + { + *cllr_mask = DMA_CLLR_UT1 | DMA_CLLR_UT2 | DMA_CLLR_UB1 | DMA_CLLR_USA | DMA_CLLR_UDA | DMA_CLLR_ULL; + } + + /* Update CLLR register offset */ + if (cllr_offset != NULL) + { + *cllr_offset = NODE_CLLR_LINEAR_DEFAULT_OFFSET; + } + } +} + +/** + * @brief Find node in queue. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers configurations. + * @param NodeInfo : Pointer to a DMA_NodeInQInfoTypeDef structure that contains node linked to queue information. + * @retval Return 0 when node is found in selected queue, otherwise node is not found. + */ +static uint32_t DMA_List_FindNode(DMA_QListTypeDef const *const pQList, + DMA_NodeTypeDef const *const pNode, + DMA_NodeInQInfoTypeDef *const NodeInfo) +{ + uint32_t node_idx = 0U; + uint32_t currentnode_address = 0U; + uint32_t previousnode_address = 0U; + uint32_t cllr_offset = NodeInfo->cllr_offset; + + /* Find last node in queue */ + if (pNode == NULL) + { + /* Check that previous node is linked to the selected queue */ + while (node_idx < pQList->NodeNumber) + { + /* Get head node address */ + if (node_idx == 0U) + { + currentnode_address = (uint32_t)pQList->Head & DMA_CLLR_LA; + } + /* Calculate nodes addresses */ + else + { + previousnode_address = currentnode_address; + currentnode_address = + ((DMA_NodeTypeDef *)(currentnode_address + + ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] & DMA_CLLR_LA; + } + + /* Increment node index */ + node_idx++; + } + } + /* Find selected node node in queue */ + else + { + /* Check that previous node is linked to the selected queue */ + while ((node_idx < pQList->NodeNumber) && (currentnode_address != ((uint32_t)pNode & DMA_CLLR_LA))) + { + /* Get head node address */ + if (node_idx == 0U) + { + currentnode_address = (uint32_t)pQList->Head & DMA_CLLR_LA; + } + /* Calculate nodes addresses */ + else + { + previousnode_address = currentnode_address; + currentnode_address = + ((DMA_NodeTypeDef *)(currentnode_address + + ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] & DMA_CLLR_LA; + } + + /* Increment node index */ + node_idx++; + } + } + + /* Check stored address */ + if (pNode != NULL) + { + if (currentnode_address != ((uint32_t)pNode & DMA_CLLR_LA)) + { + return 1U; + } + } + + /* Update current node position */ + NodeInfo->currentnode_pos = node_idx; + + /* Update previous node address */ + NodeInfo->previousnode_addr = previousnode_address | ((uint32_t)pQList->Head & DMA_CLBAR_LBA); + + /* Update current node address */ + NodeInfo->currentnode_addr = currentnode_address | ((uint32_t)pQList->Head & DMA_CLBAR_LBA); + + /* Update next node address */ + if (((DMA_NodeTypeDef *)NodeInfo->currentnode_addr)->LinkRegisters[cllr_offset] != 0U) + { + NodeInfo->nextnode_addr = (((DMA_NodeTypeDef *)NodeInfo->currentnode_addr)->LinkRegisters[cllr_offset] & + DMA_CLLR_LA) | ((uint32_t)pQList->Head & DMA_CLBAR_LBA); + } + + return 0U; +} + +/** + * @brief Reset queue nodes. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param NodeInfo : Pointer to a DMA_NodeInQInfoTypeDef structure that contains node linked to queue information. + * @retval None. + */ +static void DMA_List_ResetQueueNodes(DMA_QListTypeDef const *const pQList, + DMA_NodeInQInfoTypeDef const *const NodeInfo) +{ + uint32_t node_idx = 0U; + uint32_t currentnode_address = 0U; + uint32_t previousnode_address; + uint32_t cllr_offset = NodeInfo->cllr_offset; + + /* Check that previous node is linked to the selected queue */ + while (node_idx < pQList->NodeNumber) + { + /* Get head node address */ + if (node_idx == 0U) + { + previousnode_address = (uint32_t)pQList->Head & DMA_CLLR_LA; + currentnode_address = (pQList->Head->LinkRegisters[cllr_offset] & DMA_CLLR_LA); + } + /* Calculate nodes addresses */ + else + { + previousnode_address = currentnode_address; + currentnode_address = + ((DMA_NodeTypeDef *)(currentnode_address + + ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] & DMA_CLLR_LA; + } + + /* Reset node */ + ((DMA_NodeTypeDef *)(previousnode_address + + ((uint32_t)pQList->Head & DMA_CLBAR_LBA)))->LinkRegisters[cllr_offset] = 0U; + + /* Increment node index */ + node_idx++; + } +} + +/** + * @brief Fill source node registers values by destination nodes registers values. + * @param pSrcNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list source node registers + * configurations. + * @param pDestNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list destination node registers + * configurations. + * @retval None. + */ +static void DMA_List_FillNode(DMA_NodeTypeDef const *const pSrcNode, + DMA_NodeTypeDef *const pDestNode) +{ + /* Repeat for all register nodes */ + for (uint32_t reg_idx = 0U; reg_idx < NODE_MAXIMUM_SIZE; reg_idx++) + { + pDestNode->LinkRegisters[reg_idx] = pSrcNode->LinkRegisters[reg_idx]; + } + + /* Fill node information */ + pDestNode->NodeInfo = pSrcNode->NodeInfo; +} + +/** + * @brief Convert node to dynamic. + * @param ContextNodeAddr : The context node address. + * @param CurrentNodeAddr : The current node address to be converted. + * @param RegisterNumber : The register number to be converted. + * @retval None. + */ +static void DMA_List_ConvertNodeToDynamic(uint32_t ContextNodeAddr, + uint32_t CurrentNodeAddr, + uint32_t RegisterNumber) +{ + uint32_t currentnode_reg_counter = 0U; + uint32_t contextnode_reg_counter = 0U; + uint32_t cllr_idx = RegisterNumber - 1U; + DMA_NodeTypeDef *context_node = (DMA_NodeTypeDef *)ContextNodeAddr; + DMA_NodeTypeDef *current_node = (DMA_NodeTypeDef *)CurrentNodeAddr; + uint32_t update_link[NODE_MAXIMUM_SIZE] = {DMA_CLLR_UT1, DMA_CLLR_UT2, DMA_CLLR_UB1, DMA_CLLR_USA, + DMA_CLLR_UDA, DMA_CLLR_UT3, DMA_CLLR_UB2, DMA_CLLR_ULL + }; + + /* Update ULL position according to register number */ + update_link[cllr_idx] = update_link[NODE_MAXIMUM_SIZE - 1U]; + + /* Repeat for all node registers */ + while (contextnode_reg_counter != RegisterNumber) + { + /* Check if register values are equal (exception for CSAR, CDAR and CLLR registers) */ + if ((context_node->LinkRegisters[contextnode_reg_counter] == + current_node->LinkRegisters[currentnode_reg_counter]) && + (contextnode_reg_counter != NODE_CSAR_DEFAULT_OFFSET) && + (contextnode_reg_counter != NODE_CDAR_DEFAULT_OFFSET) && + (contextnode_reg_counter != (RegisterNumber - 1U))) + { + /* Format the node according to unused registers */ + DMA_List_FormatNode(current_node, currentnode_reg_counter, RegisterNumber, NODE_DYNAMIC_FORMAT); + + /* Update CLLR index */ + cllr_idx --; + + /* Update CLLR fields */ + current_node->LinkRegisters[cllr_idx] &= ~update_link[contextnode_reg_counter]; + } + else + { + /* Update context node register fields with new values */ + context_node->LinkRegisters[contextnode_reg_counter] = current_node->LinkRegisters[currentnode_reg_counter]; + + /* Update CLLR fields */ + current_node->LinkRegisters[cllr_idx] |= update_link[contextnode_reg_counter]; + + /* Increment current node number register counter */ + currentnode_reg_counter++; + } + + /* Increment context node number register counter */ + contextnode_reg_counter++; + } + + /* Update node information */ + MODIFY_REG(current_node->NodeInfo, NODE_CLLR_IDX, ((currentnode_reg_counter - 1U) << NODE_CLLR_IDX_POS)); + + /* Clear unused node fields */ + DMA_List_ClearUnusedFields(current_node, currentnode_reg_counter); +} + +/** + * @brief Convert node to static. + * @param ContextNodeAddr : The context node address. + * @param CurrentNodeAddr : The current node address to be converted. + * @param RegisterNumber : The register number to be converted. + * @retval None. + */ +static void DMA_List_ConvertNodeToStatic(uint32_t ContextNodeAddr, + uint32_t CurrentNodeAddr, + uint32_t RegisterNumber) +{ + uint32_t contextnode_reg_counter = 0U; + uint32_t cllr_idx; + uint32_t cllr_mask; + const DMA_NodeTypeDef *context_node = (DMA_NodeTypeDef *)ContextNodeAddr; + DMA_NodeTypeDef *current_node = (DMA_NodeTypeDef *)CurrentNodeAddr; + uint32_t update_link[NODE_MAXIMUM_SIZE] = {DMA_CLLR_UT1, DMA_CLLR_UT2, DMA_CLLR_UB1, DMA_CLLR_USA, + DMA_CLLR_UDA, DMA_CLLR_UT3, DMA_CLLR_UB2, DMA_CLLR_ULL + }; + + /* Update ULL position according to register number */ + update_link[RegisterNumber - 1U] = update_link[NODE_MAXIMUM_SIZE - 1U]; + + /* Get context node CLLR information */ + cllr_idx = (context_node->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; + cllr_mask = context_node->LinkRegisters[cllr_idx]; + + /* Repeat for all node registers */ + while (contextnode_reg_counter != RegisterNumber) + { + /* Check if node field is dynamic */ + if ((cllr_mask & update_link[contextnode_reg_counter]) == 0U) + { + /* Format the node according to unused registers */ + DMA_List_FormatNode(current_node, contextnode_reg_counter, RegisterNumber, NODE_STATIC_FORMAT); + + /* Update node field */ + current_node->LinkRegisters[contextnode_reg_counter] = context_node->LinkRegisters[contextnode_reg_counter]; + } + + /* Increment context node number register counter */ + contextnode_reg_counter++; + } + + /* Update node information */ + MODIFY_REG(current_node->NodeInfo, NODE_CLLR_IDX, ((RegisterNumber - 1U) << NODE_CLLR_IDX_POS)); +} + +/** + * @brief Format the node according to unused registers. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @param RegisterIdx : The first register index to be formatted. + * @param RegisterNumber : The number of node registers. + * @param Format : The format type. + * @retval None. + */ +static void DMA_List_FormatNode(DMA_NodeTypeDef *const pNode, + uint32_t RegisterIdx, + uint32_t RegisterNumber, + uint32_t Format) +{ + if (Format == NODE_DYNAMIC_FORMAT) + { + /* Repeat for all registers to be formatted */ + for (uint32_t reg_idx = RegisterIdx; reg_idx < (RegisterNumber - 1U); reg_idx++) + { + pNode->LinkRegisters[reg_idx] = pNode->LinkRegisters[reg_idx + 1U]; + } + } + else + { + /* Repeat for all registers to be formatted */ + for (uint32_t reg_idx = (RegisterNumber - 2U); reg_idx > RegisterIdx; reg_idx--) + { + pNode->LinkRegisters[reg_idx] = pNode->LinkRegisters[reg_idx - 1U]; + } + } +} + +/** + * @brief Clear unused register fields. + * @param pNode : Pointer to a DMA_NodeTypeDef structure that contains linked-list node registers + * configurations. + * @param FirstUnusedField : The first unused field to be cleared. + * @retval None. + */ +static void DMA_List_ClearUnusedFields(DMA_NodeTypeDef *const pNode, + uint32_t FirstUnusedField) +{ + /* Repeat for all unused fields */ + for (uint32_t reg_idx = FirstUnusedField; reg_idx < NODE_MAXIMUM_SIZE; reg_idx++) + { + pNode->LinkRegisters[reg_idx] = 0U; + } +} + +/** + * @brief Update CLLR for all dynamic queue nodes. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param LastNode_IsCircular : The first circular node is the last queue node or not. + * @retval None. + */ +static void DMA_List_UpdateDynamicQueueNodesCLLR(DMA_QListTypeDef const *const pQList, + uint32_t LastNode_IsCircular) +{ + uint32_t previous_cllr_offset; + uint32_t current_cllr_offset = 0U; + uint32_t previousnode_addr; + uint32_t currentnode_addr = (uint32_t)pQList->Head; + uint32_t cllr_mask; + uint32_t node_idx = 0U; + + /* Repeat for all register nodes */ + while (node_idx < pQList->NodeNumber) + { + /* Get head node address */ + if (node_idx == 0U) + { + /* Get current node information */ + current_cllr_offset = (((DMA_NodeTypeDef *)currentnode_addr)->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; + } + /* Calculate nodes addresses */ + else + { + /* Get previous node information */ + previousnode_addr = currentnode_addr; + previous_cllr_offset = current_cllr_offset; + + /* Get current node information */ + currentnode_addr = (((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[previous_cllr_offset] & DMA_CLLR_LA) + + ((uint32_t)pQList->Head & DMA_CLBAR_LBA); + current_cllr_offset = (((DMA_NodeTypeDef *)currentnode_addr)->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; + + /* Calculate CLLR register value to be updated */ + cllr_mask = (((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] & ~DMA_CLLR_LA) | + (((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[previous_cllr_offset] & DMA_CLLR_LA); + + /* Set new CLLR value to previous node */ + ((DMA_NodeTypeDef *)(previousnode_addr))->LinkRegisters[previous_cllr_offset] = cllr_mask; + } + + /* Increment node index */ + node_idx++; + } + + /* Check queue circularity */ + if (pQList->FirstCircularNode != 0U) + { + /* First circular queue is not last queue node */ + if (LastNode_IsCircular == 0U) + { + /* Get CLLR node information */ + DMA_List_GetCLLRNodeInfo(((DMA_NodeTypeDef *)currentnode_addr), &cllr_mask, NULL); + + /* Update CLLR register for last circular node */ + ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] = + ((uint32_t)pQList->Head & DMA_CLLR_LA) | cllr_mask; + } + /* First circular queue is last queue node */ + else + { + /* Disable CLLR updating */ + ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] &= ~DMA_CLLR_ULL; + } + } + else + { + /* Clear CLLR register for last node */ + ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] = 0U; + } +} + +/** + * @brief Update CLLR for all static queue nodes. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @param operation : The operation type. + * @retval None. + */ +static void DMA_List_UpdateStaticQueueNodesCLLR(DMA_QListTypeDef const *const pQList, + uint32_t operation) +{ + uint32_t currentnode_addr = (uint32_t)pQList->Head; + uint32_t current_cllr_offset = ((uint32_t)pQList->Head->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; + uint32_t cllr_default_offset; + uint32_t cllr_default_mask; + uint32_t cllr_mask; + uint32_t node_idx = 0U; + + /* Get CLLR node information */ + DMA_List_GetCLLRNodeInfo(pQList->Head, &cllr_default_mask, &cllr_default_offset); + + /* Repeat for all register nodes (Bypass last queue node) */ + while (node_idx < pQList->NodeNumber) + { + if (operation == UPDATE_CLLR_POSITION) + { + /* Get CLLR value */ + cllr_mask = ((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset]; + } + else + { + /* Calculate CLLR value */ + cllr_mask = (((DMA_NodeTypeDef *)currentnode_addr)->LinkRegisters[current_cllr_offset] & DMA_CLLR_LA) | + cllr_default_mask; + } + + /* Set new CLLR value to default position */ + if ((node_idx == (pQList->NodeNumber - 1U)) && (pQList->FirstCircularNode == NULL)) + { + ((DMA_NodeTypeDef *)(currentnode_addr))->LinkRegisters[cllr_default_offset] = 0U; + } + else + { + ((DMA_NodeTypeDef *)(currentnode_addr))->LinkRegisters[cllr_default_offset] = cllr_mask; + } + + /* Update current node address with next node address */ + currentnode_addr = (currentnode_addr & DMA_CLBAR_LBA) | (cllr_mask & DMA_CLLR_LA); + + /* Update current CLLR offset with next CLLR offset */ + current_cllr_offset = (((DMA_NodeTypeDef *)currentnode_addr)->NodeInfo & NODE_CLLR_IDX) >> NODE_CLLR_IDX_POS; + + /* Increment node index */ + node_idx++; + } +} + +/** + * @brief Clean linked-list queue variable. + * @param pQList : Pointer to a DMA_QListTypeDef structure that contains queue information. + * @retval None. + */ +static void DMA_List_CleanQueue(DMA_QListTypeDef *const pQList) +{ + /* Clear head node */ + pQList->Head = NULL; + + /* Clear first circular queue node */ + pQList->FirstCircularNode = NULL; + + /* Reset node number */ + pQList->NodeNumber = 0U; + + /* Reset queue state */ + pQList->State = HAL_DMA_QUEUE_STATE_RESET; + + /* Reset queue error code */ + pQList->ErrorCode = HAL_DMA_QUEUE_ERROR_NONE; + + /* Reset queue type */ + pQList->Type = QUEUE_TYPE_STATIC; +} +/** + * @} + */ + +#endif /* HAL_DMA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_dts.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_dts.c index b4fb8e9d5..660fbd52d 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_dts.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_dts.c @@ -1,1087 +1,1087 @@ -/** - ********************************************************************************************************************** - * @file stm32h7rsxx_hal_dts.c - * @author MCD Application Team - * @brief DTS HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the DTS peripheral: - * + Initialization and de-initialization functions - * + Start/Stop operation functions in polling mode. - * + Start/Stop operation functions in interrupt mode. - * + Peripheral Control functions - * + Peripheral State functions - * - ********************************************************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ********************************************************************************************************************** - @verbatim - ====================================================================================================================== - ##### DTS Peripheral features ##### - ====================================================================================================================== - - [..] - The STM32h7rsxx device family integrate one DTS sensor interface that converts the temperature into a square wave - which frequency is proportional to the temperature. - - (+) Temperature window comparator feature: - The DTS allows defining the high and low threshold that will be used for temperature comparison. - If the temperature data is equal or higher than the high threshold, or equal or lower than the low threshold, - an interrupt is generated and the corresponding flag. - - (+) Synchronous interrupts: - A global interrupt output line is available on the DTS block. The interrupt can be generated - at the end of measurement and/or when the measurement result is equal/higher or equal/lower than - a predefined threshold. - - (+) Asynchronous wakeup: - The DTS block provides an asynchronous interrupt line. It is used only when the LSE is selected as reference - clock. This line can generate a signal that wakes up the system from Sleep and stop mode at the end of - measurement and/or when the measurement result is equal/higher or equal/lower than a - predefined threshold. - - (+) Trigger inputs: - The temperature measurement can be triggered either by software or by an external event - as well as lowpower timer. - - (+) Measurement modes: - (++) Quick measure : measure without a calibration when a high precision is not required. - (++) Slow measure : measure with a calibration used when a high precision is required. - - (+) Sampling time: - The sampling time can be used to increase temperature measurement precision. - - (+) Prescaler: - When a calibration is ongoing, the counter clock must be slower than 1 MHz. This is - achieved by the PCLK clock prescaler embedded in the temperature sensor. - - (+) Operating Modes: - - (++) PCLK only : The temperature sensor registers can be accessed. The interface can consequently be - reconfigured and the measurement sequence is performed using PCLK clock. - - (++) PCLK and LSE : The temperature sensor registers can be accessed. The interface can consequently be - reconfigured and the measurement sequence is performed using the LSE clock. - - (++) LSE only : The registers cannot be accessed. The measurement can be performed using the LSE - clock This mode is used to exit from Sleep and stop mode by using hardware triggers - and the asynchronous interrupt line. - (+) Calibration: - The temperature sensor must run the calibration prior to any frequency measurement. The calibration is - performed automatically when the temperature measurement is triggered except for quick measurement mode. - - (+) Low power modes: - (++) Sleep mode: only works in LSE mode. - (++) Stop mode: only works in LSE mode. - - ====================================================================================================================== - ##### How to use this driver ##### - ====================================================================================================================== - [..] - This driver provides functions to configure and program the DTS instances of STM32H7RSxx devices. - - To use the DTS, perform the following steps: - - (+) Initialize the DTS low level resources by implementing the HAL_DTS_MspInit(): - - (++) If required enable the DTS interrupt by configuring and enabling EXTI line in Interrupt mode After that - enable the DTS interrupt vector using HAL_NVIC_EnableIRQ() function. - - (+) Configure the DTS using HAL_DTS_Init() function: - - (++) Select the quick measure option - (++) Select the reference clock. - (++) Select the trigger input. - (++) Select the sampling time. - (++) Select the high speed clock ratio divider. - (++) Select the low threshold - (++) Select the high threshold - - - (+) Use HAL_DTS_Start() to enable and start the DTS sensor in polling mode. - - (+) Use HAL_DTS_Start_IT() to enable and start the DTS sensor in interrupt mode. - - (+) Use HAL_DTS_GetTemperature() to get temperature from DTS. - - (+) Use HAL_DTS_Stop() to disable and stop the DTS sensor in polling mode. - - (+) Use HAL_DTS_Stop_IT() to disable and stop the DTS sensor in interrupt mode. - - (+) De-initialize the DTS using HAL_DTS_DeInit() function. - - *** Callback and interrupts *** - ============================================= - [..] - When the compilation flag USE_HAL_DTS_REGISTER_CALLBACKS is set to 0 or not defined, the callback registration - feature is not available and all callbacks are set to the corresponding weak functions. - - (+) Implement the weak function HAL_DTS_EndCallback() to get a callback at the end of the temperature measurement. - (+) Implement the weak function HAL_DTS_HighCallback() to get a callback when the temperature - exceed the high threshold. - (+) Implement the weak function HAL_DTS_LowCallback() to get a callback when the temperature - go down the low threshold. - (+) Implement the weak function HAL_DTS_AsyncEndCallback() to get a callback at the end - of an asynchronous temperature measurement. - (+) Implement the weak function HAL_DTS_AsyncHighCallback() to get a callback when the temperature - exceed the high threshold in an asynchronous measurement. - (+) Implement the weak function HAL_DTS_AsyncLowCallback() to get a callback when the temperature - go down the low threshold in an asynchronous measurement. - - [..] - The compilation flag USE_HAL_DTS_REGISTER_CALLBACKS, when set to 1, allows the user to configure dynamically - the driver callbacks. - - *** State *** - ============================================= - [..] - The driver permits to get in run time the status of the peripheral. - - (+) Use HAL_DTS_GetState() to get the state of the DTS. - - @endverbatim - ********************************************************************************************************************** - */ - -/* Includes ----------------------------------------------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_DTS_MODULE_ENABLED - -/** @defgroup DTS DTS - * @brief DTS HAL module driver - * @{ - */ - -/* Private typedef ---------------------------------------------------------------------------------------------------*/ -/* Private define ----------------------------------------------------------------------------------------------------*/ -/** @addtogroup DTS_Private_Constants - * @{ - */ - -/* @brief Delay for DTS startup time - * @note Delay required to get ready for DTS Block. - * @note Unit: ms - */ -#define DTS_DELAY_STARTUP (1UL) - -/* @brief DTS measure ready flag time out value. - * @note Maximal measurement time is when LSE is selected as ref_clock and - * maximal sampling time is used, taking calibration into account this - * is equivalent to ~620 us. Use 5 ms as arbitrary timeout - * @note Unit: ms - */ -#define TS_TIMEOUT_MS (5UL) - -/* @brief DTS factory temperatures - * @note Unit: degree Celsius - */ -#define DTS_FACTORY_TEMPERATURE1 (30UL) -#define DTS_FACTORY_TEMPERATURE2 (130UL) - -/** - * @} - */ - -/* Private macro -----------------------------------------------------------------------------------------------------*/ -/* Private variables -------------------------------------------------------------------------------------------------*/ -/* Private function prototypes ---------------------------------------------------------------------------------------*/ -/* Exported functions ------------------------------------------------------------------------------------------------*/ -/** @defgroup DTS_Exported_Functions DTS Exported Functions - * @{ - */ - -/** @defgroup DTS_Exported_Functions_Group1 Initialization/de-initialization functions - * @brief Initialization and de-initialization functions. - * -@verbatim - ======================================================================================================================= - ##### Initialization and de-initialization functions ##### - ======================================================================================================================= - [..] This section provides functions to initialize and de-initialize DTS - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the DTS according to the specified - * parameters in the DTS_InitTypeDef and initialize the associated handle. - * @param hdts DTS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_Init(DTS_HandleTypeDef *hdts) -{ - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_DTS_ALL_INSTANCE(hdts->Instance)); - assert_param(IS_DTS_QUICKMEAS(hdts->Init.QuickMeasure)); - assert_param(IS_DTS_REFCLK(hdts->Init.RefClock)); - assert_param(IS_DTS_TRIGGERINPUT(hdts->Init.TriggerInput)); - assert_param(IS_DTS_SAMPLINGTIME(hdts->Init.SamplingTime)); - assert_param(IS_DTS_THRESHOLD(hdts->Init.HighThreshold)); - assert_param(IS_DTS_THRESHOLD(hdts->Init.LowThreshold)); - - if (hdts->State == HAL_DTS_STATE_RESET) - { -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - /* Reset the DTS callback to the legacy weak callbacks */ - hdts->EndCallback = HAL_DTS_EndCallback; /* End measure Callback */ - hdts->LowCallback = HAL_DTS_LowCallback; /* low threshold Callback */ - hdts->HighCallback = HAL_DTS_HighCallback; /* high threshold Callback */ - hdts->AsyncEndCallback = HAL_DTS_AsyncEndCallback; /* Asynchronous end of measure Callback */ - hdts->AsyncLowCallback = HAL_DTS_AsyncLowCallback; /* Asynchronous low threshold Callback */ - hdts->AsyncHighCallback = HAL_DTS_AsyncHighCallback; /* Asynchronous high threshold Callback */ - - if (hdts->MspInitCallback == NULL) - { - hdts->MspInitCallback = HAL_DTS_MspInit; - } - - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - hdts->MspInitCallback(hdts); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - HAL_DTS_MspInit(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } - - /* Change the DTS state */ - hdts->State = HAL_DTS_STATE_BUSY; - - /* Check ramp coefficient */ - if (hdts->Instance->RAMPVALR == 0UL) - { - return HAL_ERROR; - } - - /* Check factory calibration temperature */ - if (hdts->Instance->T0VALR1 == 0UL) - { - return HAL_ERROR; - } - - /* Check Quick Measure option is enabled or disabled */ - if (hdts->Init.QuickMeasure == DTS_QUICKMEAS_DISABLE) - { - /* Check Reference clock selection */ - if (hdts->Init.RefClock == DTS_REFCLKSEL_PCLK) - { - assert_param(IS_DTS_DIVIDER_RATIO_NUMBER(hdts->Init.Divider)); - } - /* Quick measurement mode disabled */ - CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_Q_MEAS_OPT); - } - else - { - /* DTS_QUICKMEAS_ENABLE shall be used only when the LSE clock is - selected as reference clock */ - if (hdts->Init.RefClock != DTS_REFCLKSEL_LSE) - { - return HAL_ERROR; - } - - /* Quick measurement mode enabled - no calibration needed */ - SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_Q_MEAS_OPT); - } - - /* set the DTS clk source */ - if (hdts->Init.RefClock == DTS_REFCLKSEL_LSE) - { - SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_REFCLK_SEL); - } - else - { - CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_REFCLK_SEL); - } - - MODIFY_REG(hdts->Instance->CFGR1, DTS_CFGR1_HSREF_CLK_DIV, (hdts->Init.Divider << DTS_CFGR1_HSREF_CLK_DIV_Pos)); - MODIFY_REG(hdts->Instance->CFGR1, DTS_CFGR1_TS1_SMP_TIME, hdts->Init.SamplingTime); - MODIFY_REG(hdts->Instance->CFGR1, DTS_CFGR1_TS1_INTRIG_SEL, hdts->Init.TriggerInput); - MODIFY_REG(hdts->Instance->ITR1, DTS_ITR1_TS1_HITTHD, (hdts->Init.HighThreshold << DTS_ITR1_TS1_HITTHD_Pos)); - MODIFY_REG(hdts->Instance->ITR1, DTS_ITR1_TS1_LITTHD, hdts->Init.LowThreshold); - - /* Change the DTS state */ - hdts->State = HAL_DTS_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitialize the DTS peripheral. - * @note Deinitialization cannot be performed if the DTS configuration is locked. - * To unlock the configuration, perform a system reset. - * @param hdts DTS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_DeInit(DTS_HandleTypeDef *hdts) -{ - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_ERROR; - } - - /* Check the parameter */ - assert_param(IS_DTS_ALL_INSTANCE(hdts->Instance)); - - /* Set DTS_CFGR register to reset value */ - CLEAR_REG(hdts->Instance->CFGR1); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - if (hdts->MspDeInitCallback == NULL) - { - hdts->MspDeInitCallback = HAL_DTS_MspDeInit; - } - - /* DeInit the low level hardware: CLOCK, NVIC.*/ - hdts->MspDeInitCallback(hdts); -#else - /* DeInit the low level hardware: CLOCK, NVIC.*/ - HAL_DTS_MspDeInit(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - - hdts->State = HAL_DTS_STATE_RESET; - - return HAL_OK; -} - -/** - * @brief Initialize the DTS MSP. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_MspInit(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitialize the DTS MSP. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_MspDeInit(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a user DTS callback to be used instead of the weak predefined callback. - * @param hdts DTS handle. - * @param CallbackID ID of the callback to be registered. - * This parameter can be one of the following values: - * @arg @ref HAL_DTS_MEAS_COMPLETE_CB_ID measure complete callback ID. - * @arg @ref HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID asynchronous measure complete callback ID. - * @arg @ref HAL_DTS_LOW_THRESHOLD_CB_ID low threshold detection callback ID. - * @arg @ref HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID asynchronous low threshold detection callback ID. - * @arg @ref HAL_DTS_HIGH_THRESHOLD_CB_ID high threshold detection callback ID. - * @arg @ref HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID asynchronous high threshold detection callback ID. - * @arg @ref HAL_DTS_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_DTS_MSPDEINIT_CB_ID MSP de-init callback ID. - * @param pCallback pointer to the callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DTS_RegisterCallback(DTS_HandleTypeDef *hdts, - HAL_DTS_CallbackIDTypeDef CallbackID, - pDTS_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pCallback == NULL) - { - /* Update status */ - status = HAL_ERROR; - } - else - { - if (hdts->State == HAL_DTS_STATE_READY) - { - switch (CallbackID) - { - case HAL_DTS_MEAS_COMPLETE_CB_ID : - hdts->EndCallback = pCallback; - break; - case HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID : - hdts->AsyncEndCallback = pCallback; - break; - case HAL_DTS_LOW_THRESHOLD_CB_ID : - hdts->LowCallback = pCallback; - break; - case HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID : - hdts->AsyncLowCallback = pCallback; - break; - case HAL_DTS_HIGH_THRESHOLD_CB_ID : - hdts->HighCallback = pCallback; - break; - case HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID : - hdts->AsyncHighCallback = pCallback; - break; - case HAL_DTS_MSPINIT_CB_ID : - hdts->MspInitCallback = pCallback; - break; - case HAL_DTS_MSPDEINIT_CB_ID : - hdts->MspDeInitCallback = pCallback; - break; - default : - /* Update status */ - status = HAL_ERROR; - break; - } - } - else if (hdts->State == HAL_DTS_STATE_RESET) - { - switch (CallbackID) - { - case HAL_DTS_MSPINIT_CB_ID : - hdts->MspInitCallback = pCallback; - break; - case HAL_DTS_MSPDEINIT_CB_ID : - hdts->MspDeInitCallback = pCallback; - break; - default : - /* Update status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Unregister a user DTS callback. - * DTS callback is redirected to the weak predefined callback. - * @param hdts DTS handle. - * @param CallbackID ID of the callback to be unregistered. - * This parameter can be one of the following values: - * @arg @ref HAL_DTS_MEAS_COMPLETE_CB_ID measure complete callback ID. - * @arg @ref HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID asynchronous measure complete callback ID. - * @arg @ref HAL_DTS_LOW_THRESHOLD_CB_ID low threshold detection callback ID. - * @arg @ref HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID asynchronous low threshold detection callback ID. - * @arg @ref HAL_DTS_HIGH_THRESHOLD_CB_ID high threshold detection callback ID. - * @arg @ref HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID asynchronous high threshold detection callback ID. - * @arg @ref HAL_DTS_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_DTS_MSPDEINIT_CB_ID MSP de-init callback ID. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_DTS_UnRegisterCallback(DTS_HandleTypeDef *hdts, - HAL_DTS_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hdts->State == HAL_DTS_STATE_READY) - { - switch (CallbackID) - { - case HAL_DTS_MEAS_COMPLETE_CB_ID : - hdts->EndCallback = HAL_DTS_EndCallback; - break; - case HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID : - hdts->AsyncEndCallback = HAL_DTS_AsyncEndCallback; - break; - case HAL_DTS_LOW_THRESHOLD_CB_ID : - hdts->LowCallback = HAL_DTS_LowCallback; - break; - case HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID : - hdts->AsyncLowCallback = HAL_DTS_AsyncLowCallback; - break; - case HAL_DTS_HIGH_THRESHOLD_CB_ID : - hdts->HighCallback = HAL_DTS_HighCallback; - break; - case HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID : - hdts->AsyncHighCallback = HAL_DTS_AsyncHighCallback; - break; - case HAL_DTS_MSPINIT_CB_ID : - hdts->MspInitCallback = HAL_DTS_MspInit; - break; - case HAL_DTS_MSPDEINIT_CB_ID : - hdts->MspDeInitCallback = HAL_DTS_MspDeInit; - break; - default : - /* Update status */ - status = HAL_ERROR; - break; - } - } - else if (hdts->State == HAL_DTS_STATE_RESET) - { - switch (CallbackID) - { - case HAL_DTS_MSPINIT_CB_ID : - hdts->MspInitCallback = HAL_DTS_MspInit; - break; - case HAL_DTS_MSPDEINIT_CB_ID : - hdts->MspDeInitCallback = HAL_DTS_MspDeInit; - break; - default : - /* Update status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update status */ - status = HAL_ERROR; - } - - /* Return function status */ - return status; -} -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup DTS_Exported_Functions_Group2 Start-Stop operation functions - * @brief Start-Stop operation functions. - * -@verbatim - ======================================================================================================================= - ##### DTS Start Stop operation functions ##### - ======================================================================================================================= - [..] This section provides functions allowing to: - (+) Start a DTS Sensor without interrupt. - (+) Stop a DTS Sensor without interrupt. - (+) Start a DTS Sensor with interrupt generation. - (+) Stop a DTS Sensor with interrupt generation. - -@endverbatim - * @{ - */ - -/** - * @brief Start the DTS sensor. - * @param hdts DTS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_Start(DTS_HandleTypeDef *hdts) -{ - uint32_t Ref_Time; - - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_ERROR; - } - - if (hdts->State == HAL_DTS_STATE_READY) - { - hdts->State = HAL_DTS_STATE_BUSY; - - /* Enable DTS sensor */ - __HAL_DTS_ENABLE(hdts); - - /* Get Start Tick*/ - Ref_Time = HAL_GetTick(); - - /* Wait till TS1_RDY flag is set */ - while (__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_RDY) == RESET) - { - if ((HAL_GetTick() - Ref_Time) > DTS_DELAY_STARTUP) - { - return HAL_TIMEOUT; - } - } - - if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) - { - /* Start continuous measures */ - SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); - - /* Ensure start is taken into account */ - HAL_Delay(TS_TIMEOUT_MS); - } - - hdts->State = HAL_DTS_STATE_READY; - } - else - { - return HAL_BUSY; - } - - return HAL_OK; -} - -/** - * @brief Stop the DTS Sensor. - * @param hdts DTS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_Stop(DTS_HandleTypeDef *hdts) -{ - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_ERROR; - } - - if (hdts->State == HAL_DTS_STATE_READY) - { - hdts->State = HAL_DTS_STATE_BUSY; - - if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) - { - CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); - } - - /* Disable the selected DTS sensor */ - __HAL_DTS_DISABLE(hdts); - - hdts->State = HAL_DTS_STATE_READY; - } - else - { - return HAL_BUSY; - } - - return HAL_OK; -} - -/** - * @brief Enable the interrupt(s) and start the DTS sensor - * @param hdts DTS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_Start_IT(DTS_HandleTypeDef *hdts) -{ - uint32_t Ref_Time; - - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_ERROR; - } - - if (hdts->State == HAL_DTS_STATE_READY) - { - hdts->State = HAL_DTS_STATE_BUSY; - - /* On Asynchronous mode enable the asynchronous IT */ - if (hdts->Init.RefClock == DTS_REFCLKSEL_LSE) - { - __HAL_DTS_ENABLE_IT(hdts, DTS_IT_TS1_AITE | DTS_IT_TS1_AITL | DTS_IT_TS1_AITH); - } - else - { - /* Enable the IT(s) */ - __HAL_DTS_ENABLE_IT(hdts, DTS_IT_TS1_ITE | DTS_IT_TS1_ITL | DTS_IT_TS1_ITH); - } - - /* Enable the selected DTS sensor */ - __HAL_DTS_ENABLE(hdts); - - /* Get Start Tick*/ - Ref_Time = HAL_GetTick(); - - /* Wait till TS1_RDY flag is set */ - while (__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_RDY) == RESET) - { - if ((HAL_GetTick() - Ref_Time) > DTS_DELAY_STARTUP) - { - return HAL_TIMEOUT; - } - } - - if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) - { - /* Start continuous measures */ - SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); - - /* Ensure start is taken into account */ - HAL_Delay(TS_TIMEOUT_MS); - } - - hdts->State = HAL_DTS_STATE_READY; - } - else - { - return HAL_BUSY; - } - - return HAL_OK; -} - -/** - * @brief Disable the interrupt(s) and stop the DTS sensor. - * @param hdts DTS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_Stop_IT(DTS_HandleTypeDef *hdts) -{ - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_ERROR; - } - - if (hdts->State == HAL_DTS_STATE_READY) - { - hdts->State = HAL_DTS_STATE_BUSY; - - /* On Asynchronous mode disable the asynchronous IT */ - if (hdts->Init.RefClock == DTS_REFCLKSEL_LSE) - { - __HAL_DTS_DISABLE_IT(hdts, DTS_IT_TS1_AITE | DTS_IT_TS1_AITL | DTS_IT_TS1_AITH); - } - else - { - /* Disable the IT(s) */ - __HAL_DTS_DISABLE_IT(hdts, DTS_IT_TS1_ITE | DTS_IT_TS1_ITL | DTS_IT_TS1_ITH); - } - - if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) - { - CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); - } - - /* Disable the selected DTS sensor */ - __HAL_DTS_DISABLE(hdts); - - hdts->State = HAL_DTS_STATE_READY; - } - else - { - return HAL_BUSY; - } - - return HAL_OK; -} - -/** - * @brief Get temperature from DTS - * @param hdts DTS handle - * @param Temperature Temperature in deg C - * @note This function retrieves latest available measure - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DTS_GetTemperature(DTS_HandleTypeDef *hdts, int32_t *Temperature) -{ - uint32_t freq_meas; - uint32_t samples; - uint32_t t0_temp; - uint32_t t0_freq; - uint32_t ramp_coeff; - - if (hdts->State == HAL_DTS_STATE_READY) - { - hdts->State = HAL_DTS_STATE_BUSY; - - /* Get the total number of samples */ - samples = (hdts->Instance->DR & DTS_DR_TS1_MFREQ); - - if ((hdts->Init.SamplingTime == 0UL) || (samples == 0UL)) - { - hdts->State = HAL_DTS_STATE_READY; - return HAL_ERROR; - } - - if ((hdts->Init.RefClock) == DTS_REFCLKSEL_LSE) - { - /* Measured frequency On Hz */ - freq_meas = (LSE_VALUE * samples) / (hdts->Init.SamplingTime >> DTS_CFGR1_TS1_SMP_TIME_Pos); - } - else - { - /* Measured frequency On Hz */ - freq_meas = (HAL_RCC_GetPCLK1Freq() * (hdts->Init.SamplingTime >> DTS_CFGR1_TS1_SMP_TIME_Pos)) / samples; - } - - /* Read factory settings */ - t0_temp = hdts->Instance->T0VALR1 >> DTS_T0VALR1_TS1_T0_Pos; - - if (t0_temp == 0UL) - { - t0_temp = DTS_FACTORY_TEMPERATURE1; /* 30 deg C */ - } - else if (t0_temp == 1UL) - { - t0_temp = DTS_FACTORY_TEMPERATURE2; /* 130 deg C */ - } - else - { - hdts->State = HAL_DTS_STATE_READY; - return HAL_ERROR; - } - - t0_freq = (hdts->Instance->T0VALR1 & DTS_T0VALR1_TS1_FMT0) * 100UL; /* Hz */ - - ramp_coeff = hdts->Instance->RAMPVALR & DTS_RAMPVALR_TS1_RAMP_COEFF; /* deg C/Hz */ - - if (ramp_coeff == 0UL) - { - hdts->State = HAL_DTS_STATE_READY; - return HAL_ERROR; - } - - /* Figure out the temperature deg C */ - *Temperature = (int32_t)t0_temp + (((int32_t)freq_meas - (int32_t)t0_freq) / (int32_t)ramp_coeff); - - hdts->State = HAL_DTS_STATE_READY; - } - else - { - return HAL_BUSY; - } - - return HAL_OK; -} - -/** - * @brief DTS sensor IRQ Handler. - * @param hdts DTS handle - * @retval None - */ -void HAL_DTS_IRQHandler(DTS_HandleTypeDef *hdts) -{ - /* Check end of measure Asynchronous IT */ - if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_AITE)) != RESET) - { - __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_AITE); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - hdts->AsyncEndCallback(hdts); -#else - HAL_DTS_AsyncEndCallback(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } - - /* Check low threshold Asynchronous IT */ - if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_AITL)) != RESET) - { - __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_AITL); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - hdts->AsyncLowCallback(hdts); -#else - HAL_DTS_AsyncLowCallback(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } - - /* Check high threshold Asynchronous IT */ - if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_AITH)) != RESET) - { - __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_AITH); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - hdts->AsyncHighCallback(hdts); -#else - HAL_DTS_AsyncHighCallback(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } - - /* Check end of measure IT */ - if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_ITE)) != RESET) - { - __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_ITE); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - hdts->EndCallback(hdts); -#else - HAL_DTS_EndCallback(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } - - /* Check low threshold IT */ - if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_ITL)) != RESET) - { - __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_ITL); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - hdts->LowCallback(hdts); -#else - HAL_DTS_LowCallback(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } - - /* Check high threshold IT */ - if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_ITH)) != RESET) - { - __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_ITH); - -#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) - hdts->HighCallback(hdts); -#else - HAL_DTS_HighCallback(hdts); -#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DTS Sensor End measure callback. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_EndCallback(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_EndCallback should be implemented in the user file - */ -} - -/** - * @brief DTS Sensor low threshold measure callback. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_LowCallback(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_LowCallback should be implemented in the user file - */ -} - -/** - * @brief DTS Sensor high threshold measure callback. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_HighCallback(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_HighCallback should be implemented in the user file - */ -} - -/** - * @brief DTS Sensor asynchronous end measure callback. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_AsyncEndCallback(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_AsyncEndCallback should be implemented in the user file - */ -} - -/** - * @brief DTS Sensor asynchronous low threshold measure callback. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_AsyncLowCallback(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_AsyncLowCallback should be implemented in the user file - */ -} - -/** - * @brief DTS Sensor asynchronous high threshold measure callback. - * @param hdts DTS handle - * @retval None - */ -__weak void HAL_DTS_AsyncHighCallback(DTS_HandleTypeDef *hdts) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hdts); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_DTS_AsyncHighCallback should be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup DTS_Exported_Functions_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. - -@endverbatim - * @{ - */ - -/** - * @brief Return the DTS handle state. - * @param hdts DTS handle - * @retval HAL state - */ -HAL_DTS_StateTypeDef HAL_DTS_GetState(const DTS_HandleTypeDef *hdts) -{ - /* Check the DTS handle allocation */ - if (hdts == NULL) - { - return HAL_DTS_STATE_RESET; - } - - /* Return DTS handle state */ - return hdts->State; -} -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_DTS_MODULE_ENABLED */ - -/** - * @} - */ +/** + ********************************************************************************************************************** + * @file stm32h7rsxx_hal_dts.c + * @author MCD Application Team + * @brief DTS HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the DTS peripheral: + * + Initialization and de-initialization functions + * + Start/Stop operation functions in polling mode. + * + Start/Stop operation functions in interrupt mode. + * + Peripheral Control functions + * + Peripheral State functions + * + ********************************************************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ********************************************************************************************************************** + @verbatim + ====================================================================================================================== + ##### DTS Peripheral features ##### + ====================================================================================================================== + + [..] + The STM32h7rsxx device family integrate one DTS sensor interface that converts the temperature into a square wave + which frequency is proportional to the temperature. + + (+) Temperature window comparator feature: + The DTS allows defining the high and low threshold that will be used for temperature comparison. + If the temperature data is equal or higher than the high threshold, or equal or lower than the low threshold, + an interrupt is generated and the corresponding flag. + + (+) Synchronous interrupts: + A global interrupt output line is available on the DTS block. The interrupt can be generated + at the end of measurement and/or when the measurement result is equal/higher or equal/lower than + a predefined threshold. + + (+) Asynchronous wakeup: + The DTS block provides an asynchronous interrupt line. It is used only when the LSE is selected as reference + clock. This line can generate a signal that wakes up the system from Sleep and stop mode at the end of + measurement and/or when the measurement result is equal/higher or equal/lower than a + predefined threshold. + + (+) Trigger inputs: + The temperature measurement can be triggered either by software or by an external event + as well as lowpower timer. + + (+) Measurement modes: + (++) Quick measure : measure without a calibration when a high precision is not required. + (++) Slow measure : measure with a calibration used when a high precision is required. + + (+) Sampling time: + The sampling time can be used to increase temperature measurement precision. + + (+) Prescaler: + When a calibration is ongoing, the counter clock must be slower than 1 MHz. This is + achieved by the PCLK clock prescaler embedded in the temperature sensor. + + (+) Operating Modes: + + (++) PCLK only : The temperature sensor registers can be accessed. The interface can consequently be + reconfigured and the measurement sequence is performed using PCLK clock. + + (++) PCLK and LSE : The temperature sensor registers can be accessed. The interface can consequently be + reconfigured and the measurement sequence is performed using the LSE clock. + + (++) LSE only : The registers cannot be accessed. The measurement can be performed using the LSE + clock This mode is used to exit from Sleep and stop mode by using hardware triggers + and the asynchronous interrupt line. + (+) Calibration: + The temperature sensor must run the calibration prior to any frequency measurement. The calibration is + performed automatically when the temperature measurement is triggered except for quick measurement mode. + + (+) Low power modes: + (++) Sleep mode: only works in LSE mode. + (++) Stop mode: only works in LSE mode. + + ====================================================================================================================== + ##### How to use this driver ##### + ====================================================================================================================== + [..] + This driver provides functions to configure and program the DTS instances of STM32H7RSxx devices. + + To use the DTS, perform the following steps: + + (+) Initialize the DTS low level resources by implementing the HAL_DTS_MspInit(): + + (++) If required enable the DTS interrupt by configuring and enabling EXTI line in Interrupt mode After that + enable the DTS interrupt vector using HAL_NVIC_EnableIRQ() function. + + (+) Configure the DTS using HAL_DTS_Init() function: + + (++) Select the quick measure option + (++) Select the reference clock. + (++) Select the trigger input. + (++) Select the sampling time. + (++) Select the high speed clock ratio divider. + (++) Select the low threshold + (++) Select the high threshold + + + (+) Use HAL_DTS_Start() to enable and start the DTS sensor in polling mode. + + (+) Use HAL_DTS_Start_IT() to enable and start the DTS sensor in interrupt mode. + + (+) Use HAL_DTS_GetTemperature() to get temperature from DTS. + + (+) Use HAL_DTS_Stop() to disable and stop the DTS sensor in polling mode. + + (+) Use HAL_DTS_Stop_IT() to disable and stop the DTS sensor in interrupt mode. + + (+) De-initialize the DTS using HAL_DTS_DeInit() function. + + *** Callback and interrupts *** + ============================================= + [..] + When the compilation flag USE_HAL_DTS_REGISTER_CALLBACKS is set to 0 or not defined, the callback registration + feature is not available and all callbacks are set to the corresponding weak functions. + + (+) Implement the weak function HAL_DTS_EndCallback() to get a callback at the end of the temperature measurement. + (+) Implement the weak function HAL_DTS_HighCallback() to get a callback when the temperature + exceed the high threshold. + (+) Implement the weak function HAL_DTS_LowCallback() to get a callback when the temperature + go down the low threshold. + (+) Implement the weak function HAL_DTS_AsyncEndCallback() to get a callback at the end + of an asynchronous temperature measurement. + (+) Implement the weak function HAL_DTS_AsyncHighCallback() to get a callback when the temperature + exceed the high threshold in an asynchronous measurement. + (+) Implement the weak function HAL_DTS_AsyncLowCallback() to get a callback when the temperature + go down the low threshold in an asynchronous measurement. + + [..] + The compilation flag USE_HAL_DTS_REGISTER_CALLBACKS, when set to 1, allows the user to configure dynamically + the driver callbacks. + + *** State *** + ============================================= + [..] + The driver permits to get in run time the status of the peripheral. + + (+) Use HAL_DTS_GetState() to get the state of the DTS. + + @endverbatim + ********************************************************************************************************************** + */ + +/* Includes ----------------------------------------------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_DTS_MODULE_ENABLED + +/** @defgroup DTS DTS + * @brief DTS HAL module driver + * @{ + */ + +/* Private typedef ---------------------------------------------------------------------------------------------------*/ +/* Private define ----------------------------------------------------------------------------------------------------*/ +/** @addtogroup DTS_Private_Constants + * @{ + */ + +/* @brief Delay for DTS startup time + * @note Delay required to get ready for DTS Block. + * @note Unit: ms + */ +#define DTS_DELAY_STARTUP (1UL) + +/* @brief DTS measure ready flag time out value. + * @note Maximal measurement time is when LSE is selected as ref_clock and + * maximal sampling time is used, taking calibration into account this + * is equivalent to ~620 us. Use 5 ms as arbitrary timeout + * @note Unit: ms + */ +#define TS_TIMEOUT_MS (5UL) + +/* @brief DTS factory temperatures + * @note Unit: degree Celsius + */ +#define DTS_FACTORY_TEMPERATURE1 (30UL) +#define DTS_FACTORY_TEMPERATURE2 (130UL) + +/** + * @} + */ + +/* Private macro -----------------------------------------------------------------------------------------------------*/ +/* Private variables -------------------------------------------------------------------------------------------------*/ +/* Private function prototypes ---------------------------------------------------------------------------------------*/ +/* Exported functions ------------------------------------------------------------------------------------------------*/ +/** @defgroup DTS_Exported_Functions DTS Exported Functions + * @{ + */ + +/** @defgroup DTS_Exported_Functions_Group1 Initialization/de-initialization functions + * @brief Initialization and de-initialization functions. + * +@verbatim + ======================================================================================================================= + ##### Initialization and de-initialization functions ##### + ======================================================================================================================= + [..] This section provides functions to initialize and de-initialize DTS + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the DTS according to the specified + * parameters in the DTS_InitTypeDef and initialize the associated handle. + * @param hdts DTS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_Init(DTS_HandleTypeDef *hdts) +{ + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DTS_ALL_INSTANCE(hdts->Instance)); + assert_param(IS_DTS_QUICKMEAS(hdts->Init.QuickMeasure)); + assert_param(IS_DTS_REFCLK(hdts->Init.RefClock)); + assert_param(IS_DTS_TRIGGERINPUT(hdts->Init.TriggerInput)); + assert_param(IS_DTS_SAMPLINGTIME(hdts->Init.SamplingTime)); + assert_param(IS_DTS_THRESHOLD(hdts->Init.HighThreshold)); + assert_param(IS_DTS_THRESHOLD(hdts->Init.LowThreshold)); + + if (hdts->State == HAL_DTS_STATE_RESET) + { +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + /* Reset the DTS callback to the legacy weak callbacks */ + hdts->EndCallback = HAL_DTS_EndCallback; /* End measure Callback */ + hdts->LowCallback = HAL_DTS_LowCallback; /* low threshold Callback */ + hdts->HighCallback = HAL_DTS_HighCallback; /* high threshold Callback */ + hdts->AsyncEndCallback = HAL_DTS_AsyncEndCallback; /* Asynchronous end of measure Callback */ + hdts->AsyncLowCallback = HAL_DTS_AsyncLowCallback; /* Asynchronous low threshold Callback */ + hdts->AsyncHighCallback = HAL_DTS_AsyncHighCallback; /* Asynchronous high threshold Callback */ + + if (hdts->MspInitCallback == NULL) + { + hdts->MspInitCallback = HAL_DTS_MspInit; + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + hdts->MspInitCallback(hdts); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_DTS_MspInit(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } + + /* Change the DTS state */ + hdts->State = HAL_DTS_STATE_BUSY; + + /* Check ramp coefficient */ + if (hdts->Instance->RAMPVALR == 0UL) + { + return HAL_ERROR; + } + + /* Check factory calibration temperature */ + if (hdts->Instance->T0VALR1 == 0UL) + { + return HAL_ERROR; + } + + /* Check Quick Measure option is enabled or disabled */ + if (hdts->Init.QuickMeasure == DTS_QUICKMEAS_DISABLE) + { + /* Check Reference clock selection */ + if (hdts->Init.RefClock == DTS_REFCLKSEL_PCLK) + { + assert_param(IS_DTS_DIVIDER_RATIO_NUMBER(hdts->Init.Divider)); + } + /* Quick measurement mode disabled */ + CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_Q_MEAS_OPT); + } + else + { + /* DTS_QUICKMEAS_ENABLE shall be used only when the LSE clock is + selected as reference clock */ + if (hdts->Init.RefClock != DTS_REFCLKSEL_LSE) + { + return HAL_ERROR; + } + + /* Quick measurement mode enabled - no calibration needed */ + SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_Q_MEAS_OPT); + } + + /* set the DTS clk source */ + if (hdts->Init.RefClock == DTS_REFCLKSEL_LSE) + { + SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_REFCLK_SEL); + } + else + { + CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_REFCLK_SEL); + } + + MODIFY_REG(hdts->Instance->CFGR1, DTS_CFGR1_HSREF_CLK_DIV, (hdts->Init.Divider << DTS_CFGR1_HSREF_CLK_DIV_Pos)); + MODIFY_REG(hdts->Instance->CFGR1, DTS_CFGR1_TS1_SMP_TIME, hdts->Init.SamplingTime); + MODIFY_REG(hdts->Instance->CFGR1, DTS_CFGR1_TS1_INTRIG_SEL, hdts->Init.TriggerInput); + MODIFY_REG(hdts->Instance->ITR1, DTS_ITR1_TS1_HITTHD, (hdts->Init.HighThreshold << DTS_ITR1_TS1_HITTHD_Pos)); + MODIFY_REG(hdts->Instance->ITR1, DTS_ITR1_TS1_LITTHD, hdts->Init.LowThreshold); + + /* Change the DTS state */ + hdts->State = HAL_DTS_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitialize the DTS peripheral. + * @note Deinitialization cannot be performed if the DTS configuration is locked. + * To unlock the configuration, perform a system reset. + * @param hdts DTS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_DeInit(DTS_HandleTypeDef *hdts) +{ + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_ERROR; + } + + /* Check the parameter */ + assert_param(IS_DTS_ALL_INSTANCE(hdts->Instance)); + + /* Set DTS_CFGR register to reset value */ + CLEAR_REG(hdts->Instance->CFGR1); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + if (hdts->MspDeInitCallback == NULL) + { + hdts->MspDeInitCallback = HAL_DTS_MspDeInit; + } + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + hdts->MspDeInitCallback(hdts); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_DTS_MspDeInit(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + + hdts->State = HAL_DTS_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initialize the DTS MSP. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_MspInit(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the DTS MSP. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_MspDeInit(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a user DTS callback to be used instead of the weak predefined callback. + * @param hdts DTS handle. + * @param CallbackID ID of the callback to be registered. + * This parameter can be one of the following values: + * @arg @ref HAL_DTS_MEAS_COMPLETE_CB_ID measure complete callback ID. + * @arg @ref HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID asynchronous measure complete callback ID. + * @arg @ref HAL_DTS_LOW_THRESHOLD_CB_ID low threshold detection callback ID. + * @arg @ref HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID asynchronous low threshold detection callback ID. + * @arg @ref HAL_DTS_HIGH_THRESHOLD_CB_ID high threshold detection callback ID. + * @arg @ref HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID asynchronous high threshold detection callback ID. + * @arg @ref HAL_DTS_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_DTS_MSPDEINIT_CB_ID MSP de-init callback ID. + * @param pCallback pointer to the callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DTS_RegisterCallback(DTS_HandleTypeDef *hdts, + HAL_DTS_CallbackIDTypeDef CallbackID, + pDTS_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pCallback == NULL) + { + /* Update status */ + status = HAL_ERROR; + } + else + { + if (hdts->State == HAL_DTS_STATE_READY) + { + switch (CallbackID) + { + case HAL_DTS_MEAS_COMPLETE_CB_ID : + hdts->EndCallback = pCallback; + break; + case HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID : + hdts->AsyncEndCallback = pCallback; + break; + case HAL_DTS_LOW_THRESHOLD_CB_ID : + hdts->LowCallback = pCallback; + break; + case HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID : + hdts->AsyncLowCallback = pCallback; + break; + case HAL_DTS_HIGH_THRESHOLD_CB_ID : + hdts->HighCallback = pCallback; + break; + case HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID : + hdts->AsyncHighCallback = pCallback; + break; + case HAL_DTS_MSPINIT_CB_ID : + hdts->MspInitCallback = pCallback; + break; + case HAL_DTS_MSPDEINIT_CB_ID : + hdts->MspDeInitCallback = pCallback; + break; + default : + /* Update status */ + status = HAL_ERROR; + break; + } + } + else if (hdts->State == HAL_DTS_STATE_RESET) + { + switch (CallbackID) + { + case HAL_DTS_MSPINIT_CB_ID : + hdts->MspInitCallback = pCallback; + break; + case HAL_DTS_MSPDEINIT_CB_ID : + hdts->MspDeInitCallback = pCallback; + break; + default : + /* Update status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Unregister a user DTS callback. + * DTS callback is redirected to the weak predefined callback. + * @param hdts DTS handle. + * @param CallbackID ID of the callback to be unregistered. + * This parameter can be one of the following values: + * @arg @ref HAL_DTS_MEAS_COMPLETE_CB_ID measure complete callback ID. + * @arg @ref HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID asynchronous measure complete callback ID. + * @arg @ref HAL_DTS_LOW_THRESHOLD_CB_ID low threshold detection callback ID. + * @arg @ref HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID asynchronous low threshold detection callback ID. + * @arg @ref HAL_DTS_HIGH_THRESHOLD_CB_ID high threshold detection callback ID. + * @arg @ref HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID asynchronous high threshold detection callback ID. + * @arg @ref HAL_DTS_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_DTS_MSPDEINIT_CB_ID MSP de-init callback ID. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_DTS_UnRegisterCallback(DTS_HandleTypeDef *hdts, + HAL_DTS_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hdts->State == HAL_DTS_STATE_READY) + { + switch (CallbackID) + { + case HAL_DTS_MEAS_COMPLETE_CB_ID : + hdts->EndCallback = HAL_DTS_EndCallback; + break; + case HAL_DTS_ASYNC_MEAS_COMPLETE_CB_ID : + hdts->AsyncEndCallback = HAL_DTS_AsyncEndCallback; + break; + case HAL_DTS_LOW_THRESHOLD_CB_ID : + hdts->LowCallback = HAL_DTS_LowCallback; + break; + case HAL_DTS_ASYNC_LOW_THRESHOLD_CB_ID : + hdts->AsyncLowCallback = HAL_DTS_AsyncLowCallback; + break; + case HAL_DTS_HIGH_THRESHOLD_CB_ID : + hdts->HighCallback = HAL_DTS_HighCallback; + break; + case HAL_DTS_ASYNC_HIGH_THRESHOLD_CB_ID : + hdts->AsyncHighCallback = HAL_DTS_AsyncHighCallback; + break; + case HAL_DTS_MSPINIT_CB_ID : + hdts->MspInitCallback = HAL_DTS_MspInit; + break; + case HAL_DTS_MSPDEINIT_CB_ID : + hdts->MspDeInitCallback = HAL_DTS_MspDeInit; + break; + default : + /* Update status */ + status = HAL_ERROR; + break; + } + } + else if (hdts->State == HAL_DTS_STATE_RESET) + { + switch (CallbackID) + { + case HAL_DTS_MSPINIT_CB_ID : + hdts->MspInitCallback = HAL_DTS_MspInit; + break; + case HAL_DTS_MSPDEINIT_CB_ID : + hdts->MspDeInitCallback = HAL_DTS_MspDeInit; + break; + default : + /* Update status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update status */ + status = HAL_ERROR; + } + + /* Return function status */ + return status; +} +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup DTS_Exported_Functions_Group2 Start-Stop operation functions + * @brief Start-Stop operation functions. + * +@verbatim + ======================================================================================================================= + ##### DTS Start Stop operation functions ##### + ======================================================================================================================= + [..] This section provides functions allowing to: + (+) Start a DTS Sensor without interrupt. + (+) Stop a DTS Sensor without interrupt. + (+) Start a DTS Sensor with interrupt generation. + (+) Stop a DTS Sensor with interrupt generation. + +@endverbatim + * @{ + */ + +/** + * @brief Start the DTS sensor. + * @param hdts DTS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_Start(DTS_HandleTypeDef *hdts) +{ + uint32_t Ref_Time; + + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_ERROR; + } + + if (hdts->State == HAL_DTS_STATE_READY) + { + hdts->State = HAL_DTS_STATE_BUSY; + + /* Enable DTS sensor */ + __HAL_DTS_ENABLE(hdts); + + /* Get Start Tick*/ + Ref_Time = HAL_GetTick(); + + /* Wait till TS1_RDY flag is set */ + while (__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_RDY) == RESET) + { + if ((HAL_GetTick() - Ref_Time) > DTS_DELAY_STARTUP) + { + return HAL_TIMEOUT; + } + } + + if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) + { + /* Start continuous measures */ + SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); + + /* Ensure start is taken into account */ + HAL_Delay(TS_TIMEOUT_MS); + } + + hdts->State = HAL_DTS_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Stop the DTS Sensor. + * @param hdts DTS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_Stop(DTS_HandleTypeDef *hdts) +{ + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_ERROR; + } + + if (hdts->State == HAL_DTS_STATE_READY) + { + hdts->State = HAL_DTS_STATE_BUSY; + + if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) + { + CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); + } + + /* Disable the selected DTS sensor */ + __HAL_DTS_DISABLE(hdts); + + hdts->State = HAL_DTS_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Enable the interrupt(s) and start the DTS sensor + * @param hdts DTS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_Start_IT(DTS_HandleTypeDef *hdts) +{ + uint32_t Ref_Time; + + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_ERROR; + } + + if (hdts->State == HAL_DTS_STATE_READY) + { + hdts->State = HAL_DTS_STATE_BUSY; + + /* On Asynchronous mode enable the asynchronous IT */ + if (hdts->Init.RefClock == DTS_REFCLKSEL_LSE) + { + __HAL_DTS_ENABLE_IT(hdts, DTS_IT_TS1_AITE | DTS_IT_TS1_AITL | DTS_IT_TS1_AITH); + } + else + { + /* Enable the IT(s) */ + __HAL_DTS_ENABLE_IT(hdts, DTS_IT_TS1_ITE | DTS_IT_TS1_ITL | DTS_IT_TS1_ITH); + } + + /* Enable the selected DTS sensor */ + __HAL_DTS_ENABLE(hdts); + + /* Get Start Tick*/ + Ref_Time = HAL_GetTick(); + + /* Wait till TS1_RDY flag is set */ + while (__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_RDY) == RESET) + { + if ((HAL_GetTick() - Ref_Time) > DTS_DELAY_STARTUP) + { + return HAL_TIMEOUT; + } + } + + if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) + { + /* Start continuous measures */ + SET_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); + + /* Ensure start is taken into account */ + HAL_Delay(TS_TIMEOUT_MS); + } + + hdts->State = HAL_DTS_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Disable the interrupt(s) and stop the DTS sensor. + * @param hdts DTS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_Stop_IT(DTS_HandleTypeDef *hdts) +{ + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_ERROR; + } + + if (hdts->State == HAL_DTS_STATE_READY) + { + hdts->State = HAL_DTS_STATE_BUSY; + + /* On Asynchronous mode disable the asynchronous IT */ + if (hdts->Init.RefClock == DTS_REFCLKSEL_LSE) + { + __HAL_DTS_DISABLE_IT(hdts, DTS_IT_TS1_AITE | DTS_IT_TS1_AITL | DTS_IT_TS1_AITH); + } + else + { + /* Disable the IT(s) */ + __HAL_DTS_DISABLE_IT(hdts, DTS_IT_TS1_ITE | DTS_IT_TS1_ITL | DTS_IT_TS1_ITH); + } + + if (__HAL_DTS_GET_TRIGGER(hdts) == DTS_TRIGGER_HW_NONE) + { + CLEAR_BIT(hdts->Instance->CFGR1, DTS_CFGR1_TS1_START); + } + + /* Disable the selected DTS sensor */ + __HAL_DTS_DISABLE(hdts); + + hdts->State = HAL_DTS_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Get temperature from DTS + * @param hdts DTS handle + * @param Temperature Temperature in deg C + * @note This function retrieves latest available measure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DTS_GetTemperature(DTS_HandleTypeDef *hdts, int32_t *Temperature) +{ + uint32_t freq_meas; + uint32_t samples; + uint32_t t0_temp; + uint32_t t0_freq; + uint32_t ramp_coeff; + + if (hdts->State == HAL_DTS_STATE_READY) + { + hdts->State = HAL_DTS_STATE_BUSY; + + /* Get the total number of samples */ + samples = (hdts->Instance->DR & DTS_DR_TS1_MFREQ); + + if ((hdts->Init.SamplingTime == 0UL) || (samples == 0UL)) + { + hdts->State = HAL_DTS_STATE_READY; + return HAL_ERROR; + } + + if ((hdts->Init.RefClock) == DTS_REFCLKSEL_LSE) + { + /* Measured frequency On Hz */ + freq_meas = (LSE_VALUE * samples) / (hdts->Init.SamplingTime >> DTS_CFGR1_TS1_SMP_TIME_Pos); + } + else + { + /* Measured frequency On Hz */ + freq_meas = (HAL_RCC_GetPCLK1Freq() * (hdts->Init.SamplingTime >> DTS_CFGR1_TS1_SMP_TIME_Pos)) / samples; + } + + /* Read factory settings */ + t0_temp = hdts->Instance->T0VALR1 >> DTS_T0VALR1_TS1_T0_Pos; + + if (t0_temp == 0UL) + { + t0_temp = DTS_FACTORY_TEMPERATURE1; /* 30 deg C */ + } + else if (t0_temp == 1UL) + { + t0_temp = DTS_FACTORY_TEMPERATURE2; /* 130 deg C */ + } + else + { + hdts->State = HAL_DTS_STATE_READY; + return HAL_ERROR; + } + + t0_freq = (hdts->Instance->T0VALR1 & DTS_T0VALR1_TS1_FMT0) * 100UL; /* Hz */ + + ramp_coeff = hdts->Instance->RAMPVALR & DTS_RAMPVALR_TS1_RAMP_COEFF; /* deg C/Hz */ + + if (ramp_coeff == 0UL) + { + hdts->State = HAL_DTS_STATE_READY; + return HAL_ERROR; + } + + /* Figure out the temperature deg C */ + *Temperature = (int32_t)t0_temp + (((int32_t)freq_meas - (int32_t)t0_freq) / (int32_t)ramp_coeff); + + hdts->State = HAL_DTS_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief DTS sensor IRQ Handler. + * @param hdts DTS handle + * @retval None + */ +void HAL_DTS_IRQHandler(DTS_HandleTypeDef *hdts) +{ + /* Check end of measure Asynchronous IT */ + if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_AITE)) != RESET) + { + __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_AITE); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + hdts->AsyncEndCallback(hdts); +#else + HAL_DTS_AsyncEndCallback(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } + + /* Check low threshold Asynchronous IT */ + if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_AITL)) != RESET) + { + __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_AITL); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + hdts->AsyncLowCallback(hdts); +#else + HAL_DTS_AsyncLowCallback(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } + + /* Check high threshold Asynchronous IT */ + if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_AITH)) != RESET) + { + __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_AITH); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + hdts->AsyncHighCallback(hdts); +#else + HAL_DTS_AsyncHighCallback(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } + + /* Check end of measure IT */ + if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_ITE)) != RESET) + { + __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_ITE); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + hdts->EndCallback(hdts); +#else + HAL_DTS_EndCallback(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } + + /* Check low threshold IT */ + if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_ITL)) != RESET) + { + __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_ITL); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + hdts->LowCallback(hdts); +#else + HAL_DTS_LowCallback(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } + + /* Check high threshold IT */ + if ((__HAL_DTS_GET_FLAG(hdts, DTS_FLAG_TS1_ITH)) != RESET) + { + __HAL_DTS_CLEAR_FLAG(hdts, DTS_FLAG_TS1_ITH); + +#if (USE_HAL_DTS_REGISTER_CALLBACKS == 1U) + hdts->HighCallback(hdts); +#else + HAL_DTS_HighCallback(hdts); +#endif /* USE_HAL_DTS_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DTS Sensor End measure callback. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_EndCallback(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_EndCallback should be implemented in the user file + */ +} + +/** + * @brief DTS Sensor low threshold measure callback. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_LowCallback(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_LowCallback should be implemented in the user file + */ +} + +/** + * @brief DTS Sensor high threshold measure callback. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_HighCallback(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_HighCallback should be implemented in the user file + */ +} + +/** + * @brief DTS Sensor asynchronous end measure callback. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_AsyncEndCallback(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_AsyncEndCallback should be implemented in the user file + */ +} + +/** + * @brief DTS Sensor asynchronous low threshold measure callback. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_AsyncLowCallback(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_AsyncLowCallback should be implemented in the user file + */ +} + +/** + * @brief DTS Sensor asynchronous high threshold measure callback. + * @param hdts DTS handle + * @retval None + */ +__weak void HAL_DTS_AsyncHighCallback(DTS_HandleTypeDef *hdts) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdts); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_DTS_AsyncHighCallback should be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DTS_Exported_Functions_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. + +@endverbatim + * @{ + */ + +/** + * @brief Return the DTS handle state. + * @param hdts DTS handle + * @retval HAL state + */ +HAL_DTS_StateTypeDef HAL_DTS_GetState(const DTS_HandleTypeDef *hdts) +{ + /* Check the DTS handle allocation */ + if (hdts == NULL) + { + return HAL_DTS_STATE_RESET; + } + + /* Return DTS handle state */ + return hdts->State; +} +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_DTS_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_eth_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_eth_ex.c index 9987ab2c9..5754ead38 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_eth_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_eth_ex.c @@ -1,660 +1,660 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_eth_ex.c - * @author MCD Application Team - * @brief ETH HAL Extended module driver. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_ETH_MODULE_ENABLED - -#if defined(ETH) - -/** @defgroup ETHEx ETHEx - * @brief ETH HAL Extended module driver - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup ETHEx_Private_Constants ETHEx Private Constants - * @{ - */ -#define ETH_MACL4CR_MASK (ETH_MACL3L4CR_L4PEN | ETH_MACL3L4CR_L4SPM | \ - ETH_MACL3L4CR_L4SPIM | ETH_MACL3L4CR_L4DPM | \ - ETH_MACL3L4CR_L4DPIM) - -#define ETH_MACL3CR_MASK (ETH_MACL3L4CR_L3PEN | ETH_MACL3L4CR_L3SAM | \ - ETH_MACL3L4CR_L3SAIM | ETH_MACL3L4CR_L3DAM | \ - ETH_MACL3L4CR_L3DAIM | ETH_MACL3L4CR_L3HSBM | \ - ETH_MACL3L4CR_L3HDBM) - -#define ETH_MACRXVLAN_MASK (ETH_MACVTR_EIVLRXS | ETH_MACVTR_EIVLS | \ - ETH_MACVTR_ERIVLT | ETH_MACVTR_EDVLP | \ - ETH_MACVTR_VTHM | ETH_MACVTR_EVLRXS | \ - ETH_MACVTR_EVLS | ETH_MACVTR_DOVLTC | \ - ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL | \ - ETH_MACVTR_VTIM | ETH_MACVTR_ETV) - -#define ETH_MACTXVLAN_MASK (ETH_MACVIR_VLTI | ETH_MACVIR_CSVL | \ - ETH_MACVIR_VLP | ETH_MACVIR_VLC) - -#define ETH_MAC_L4_SRSP_MASK 0x0000FFFFU -#define ETH_MAC_L4_DSTP_MASK 0xFFFF0000U -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions ---------------------------------------------------------*/ -/** @defgroup ETHEx_Exported_Functions ETH Extended Exported Functions - * @{ - */ - -/** @defgroup ETHEx_Exported_Functions_Group1 Extended features functions - * @brief Extended features functions - * -@verbatim - =============================================================================== - ##### Extended features functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure ARP offload module - (+) Configure L3 and L4 filters - (+) Configure Extended VLAN features - (+) Configure Energy Efficient Ethernet module - -@endverbatim - * @{ - */ - -/** - * @brief Enables ARP Offload. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None - */ - -void HAL_ETHEx_EnableARPOffload(ETH_HandleTypeDef *heth) -{ - SET_BIT(heth->Instance->MACCR, ETH_MACCR_ARP); -} - -/** - * @brief Disables ARP Offload. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None - */ -void HAL_ETHEx_DisableARPOffload(ETH_HandleTypeDef *heth) -{ - CLEAR_BIT(heth->Instance->MACCR, ETH_MACCR_ARP); -} - -/** - * @brief Set the ARP Match IP address - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param IpAddress: IP Address to be matched for incoming ARP requests - * @retval None - */ -void HAL_ETHEx_SetARPAddressMatch(ETH_HandleTypeDef *heth, uint32_t IpAddress) -{ - WRITE_REG(heth->Instance->MACARPAR, IpAddress); -} - -/** - * @brief Configures the L4 Filter, this function allow to: - * set the layer 4 protocol to be matched (TCP or UDP) - * enable/disable L4 source/destination port perfect/inverse match. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param Filter: L4 filter to configured, this parameter must be one of the following - * ETH_L4_FILTER_0 - * ETH_L4_FILTER_1 - * @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure - * that contains L4 filter configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_ETHEx_SetL4FilterConfig(ETH_HandleTypeDef *heth, uint32_t Filter, - const ETH_L4FilterConfigTypeDef *pL4FilterConfig) -{ - if (pL4FilterConfig == NULL) - { - return HAL_ERROR; - } - - if (Filter == ETH_L4_FILTER_0) - { - /* Write configuration to MACL3L4C0R register */ - MODIFY_REG(heth->Instance->MACL3L4C0R, ETH_MACL4CR_MASK, (pL4FilterConfig->Protocol | - pL4FilterConfig->SrcPortFilterMatch | - pL4FilterConfig->DestPortFilterMatch)); - - /* Write configuration to MACL4A0R register */ - WRITE_REG(heth->Instance->MACL4A0R, (pL4FilterConfig->SourcePort | (pL4FilterConfig->DestinationPort << 16))); - - } - else /* Filter == ETH_L4_FILTER_1 */ - { - /* Write configuration to MACL3L4C1R register */ - MODIFY_REG(heth->Instance->MACL3L4C1R, ETH_MACL4CR_MASK, (pL4FilterConfig->Protocol | - pL4FilterConfig->SrcPortFilterMatch | - pL4FilterConfig->DestPortFilterMatch)); - - /* Write configuration to MACL4A1R register */ - WRITE_REG(heth->Instance->MACL4A1R, (pL4FilterConfig->SourcePort | (pL4FilterConfig->DestinationPort << 16))); - } - - /* Enable L4 filter */ - SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); - - return HAL_OK; -} - -/** - * @brief Configures the L4 Filter, this function allow to: - * set the layer 4 protocol to be matched (TCP or UDP) - * enable/disable L4 source/destination port perfect/inverse match. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param Filter: L4 filter to configured, this parameter must be one of the following - * ETH_L4_FILTER_0 - * ETH_L4_FILTER_1 - * @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure - * that contains L4 filter configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_ETHEx_GetL4FilterConfig(const ETH_HandleTypeDef *heth, uint32_t Filter, - ETH_L4FilterConfigTypeDef *pL4FilterConfig) -{ - if (pL4FilterConfig == NULL) - { - return HAL_ERROR; - } - - if (Filter == ETH_L4_FILTER_0) - { - /* Get configuration from MACL3L4C0R register */ - pL4FilterConfig->Protocol = READ_BIT(heth->Instance->MACL3L4C0R, ETH_MACL3L4CR_L4PEN); - pL4FilterConfig->DestPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C0R, - (ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM)); - pL4FilterConfig->SrcPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C0R, - (ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM)); - - /* Get configuration from MACL4A0R register */ - pL4FilterConfig->DestinationPort = (READ_BIT(heth->Instance->MACL4A0R, ETH_MAC_L4_DSTP_MASK) >> 16); - pL4FilterConfig->SourcePort = READ_BIT(heth->Instance->MACL4A0R, ETH_MAC_L4_SRSP_MASK); - } - else /* Filter == ETH_L4_FILTER_1 */ - { - /* Get configuration from MACL3L4C1R register */ - pL4FilterConfig->Protocol = READ_BIT(heth->Instance->MACL3L4C1R, ETH_MACL3L4CR_L4PEN); - pL4FilterConfig->DestPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C1R, - (ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM)); - pL4FilterConfig->SrcPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C1R, - (ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM)); - - /* Get configuration from MACL4A1R register */ - pL4FilterConfig->DestinationPort = (READ_BIT(heth->Instance->MACL4A1R, ETH_MAC_L4_DSTP_MASK) >> 16); - pL4FilterConfig->SourcePort = READ_BIT(heth->Instance->MACL4A1R, ETH_MAC_L4_SRSP_MASK); - } - - return HAL_OK; -} - -/** - * @brief Configures the L3 Filter, this function allow to: - * set the layer 3 protocol to be matched (IPv4 or IPv6) - * enable/disable L3 source/destination port perfect/inverse match. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param Filter: L3 filter to configured, this parameter must be one of the following - * ETH_L3_FILTER_0 - * ETH_L3_FILTER_1 - * @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure - * that contains L3 filter configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_ETHEx_SetL3FilterConfig(ETH_HandleTypeDef *heth, uint32_t Filter, - const ETH_L3FilterConfigTypeDef *pL3FilterConfig) -{ - if (pL3FilterConfig == NULL) - { - return HAL_ERROR; - } - - if (Filter == ETH_L3_FILTER_0) - { - /* Write configuration to MACL3L4C0R register */ - MODIFY_REG(heth->Instance->MACL3L4C0R, ETH_MACL3CR_MASK, (pL3FilterConfig->Protocol | - pL3FilterConfig->SrcAddrFilterMatch | - pL3FilterConfig->DestAddrFilterMatch | - (pL3FilterConfig->SrcAddrHigherBitsMatch << 6) | - (pL3FilterConfig->DestAddrHigherBitsMatch << 11))); - } - else /* Filter == ETH_L3_FILTER_1 */ - { - /* Write configuration to MACL3L4C1R register */ - MODIFY_REG(heth->Instance->MACL3L4C1R, ETH_MACL3CR_MASK, (pL3FilterConfig->Protocol | - pL3FilterConfig->SrcAddrFilterMatch | - pL3FilterConfig->DestAddrFilterMatch | - (pL3FilterConfig->SrcAddrHigherBitsMatch << 6) | - (pL3FilterConfig->DestAddrHigherBitsMatch << 11))); - } - - if (Filter == ETH_L3_FILTER_0) - { - /* Check if IPv6 protocol is selected */ - if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) - { - /* Set the IPv6 address match */ - /* Set Bits[31:0] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip6Addr[0]); - /* Set Bits[63:32] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip6Addr[1]); - /* update Bits[95:64] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A2R0R, pL3FilterConfig->Ip6Addr[2]); - /* update Bits[127:96] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A3R0R, pL3FilterConfig->Ip6Addr[3]); - } - else /* IPv4 protocol is selected */ - { - /* Set the IPv4 source address match */ - WRITE_REG(heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip4SrcAddr); - /* Set the IPv4 destination address match */ - WRITE_REG(heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip4DestAddr); - } - } - else /* Filter == ETH_L3_FILTER_1 */ - { - /* Check if IPv6 protocol is selected */ - if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) - { - /* Set the IPv6 address match */ - /* Set Bits[31:0] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip6Addr[0]); - /* Set Bits[63:32] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[1]); - /* update Bits[95:64] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[2]); - /* update Bits[127:96] of 128-bit IP addr */ - WRITE_REG(heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[3]); - } - else /* IPv4 protocol is selected */ - { - /* Set the IPv4 source address match */ - WRITE_REG(heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4SrcAddr); - /* Set the IPv4 destination address match */ - WRITE_REG(heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4DestAddr); - - } - } - - /* Enable L3 filter */ - SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); - - return HAL_OK; -} - -/** - * @brief Configures the L3 Filter, this function allow to: - * set the layer 3 protocol to be matched (IPv4 or IPv6) - * enable/disable L3 source/destination port perfect/inverse match. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param Filter: L3 filter to configured, this parameter must be one of the following - * ETH_L3_FILTER_0 - * ETH_L3_FILTER_1 - * @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure - * that will contain the L3 filter configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_ETHEx_GetL3FilterConfig(const ETH_HandleTypeDef *heth, uint32_t Filter, - ETH_L3FilterConfigTypeDef *pL3FilterConfig) -{ - if (pL3FilterConfig == NULL) - { - return HAL_ERROR; - } - pL3FilterConfig->Protocol = READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), - ETH_MACL3L4CR_L3PEN); - pL3FilterConfig->SrcAddrFilterMatch = READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), - (ETH_MACL3L4CR_L3SAM | ETH_MACL3L4CR_L3SAIM)); - pL3FilterConfig->DestAddrFilterMatch = READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), - (ETH_MACL3L4CR_L3DAM | ETH_MACL3L4CR_L3DAIM)); - pL3FilterConfig->SrcAddrHigherBitsMatch = (READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), - ETH_MACL3L4CR_L3HSBM) >> 6); - pL3FilterConfig->DestAddrHigherBitsMatch = (READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), - ETH_MACL3L4CR_L3HDBM) >> 11); - - if (Filter == ETH_L3_FILTER_0) - { - if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) - { - WRITE_REG(pL3FilterConfig->Ip6Addr[0], heth->Instance->MACL3A0R0R); - WRITE_REG(pL3FilterConfig->Ip6Addr[1], heth->Instance->MACL3A1R0R); - WRITE_REG(pL3FilterConfig->Ip6Addr[2], heth->Instance->MACL3A2R0R); - WRITE_REG(pL3FilterConfig->Ip6Addr[3], heth->Instance->MACL3A3R0R); - } - else - { - WRITE_REG(pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R0R); - WRITE_REG(pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R0R); - } - } - else /* ETH_L3_FILTER_1 */ - { - if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) - { - WRITE_REG(pL3FilterConfig->Ip6Addr[0], heth->Instance->MACL3A0R1R); - WRITE_REG(pL3FilterConfig->Ip6Addr[1], heth->Instance->MACL3A1R1R); - WRITE_REG(pL3FilterConfig->Ip6Addr[2], heth->Instance->MACL3A2R1R); - WRITE_REG(pL3FilterConfig->Ip6Addr[3], heth->Instance->MACL3A3R1R); - } - else - { - WRITE_REG(pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R1R); - WRITE_REG(pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R1R); - } - } - - return HAL_OK; -} - -/** - * @brief Enables L3 and L4 filtering process. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None. - */ -void HAL_ETHEx_EnableL3L4Filtering(ETH_HandleTypeDef *heth) -{ - /* Enable L3/L4 filter */ - SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); -} - -/** - * @brief Disables L3 and L4 filtering process. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None. - */ -void HAL_ETHEx_DisableL3L4Filtering(ETH_HandleTypeDef *heth) -{ - /* Disable L3/L4 filter */ - CLEAR_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); -} - -/** - * @brief Get the VLAN Configuration for Receive Packets. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure - * that will contain the VLAN filter configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_ETHEx_GetRxVLANConfig(const ETH_HandleTypeDef *heth, ETH_RxVLANConfigTypeDef *pVlanConfig) -{ - if (pVlanConfig == NULL) - { - return HAL_ERROR; - } - - pVlanConfig->InnerVLANTagInStatus = ((READ_BIT(heth->Instance->MACVTR, - ETH_MACVTR_EIVLRXS) >> 31) == 0U) ? DISABLE : ENABLE; - pVlanConfig->StripInnerVLANTag = READ_BIT(heth->Instance->MACVTR, ETH_MACVTR_EIVLS); - pVlanConfig->InnerVLANTag = ((READ_BIT(heth->Instance->MACVTR, - ETH_MACVTR_ERIVLT) >> 27) == 0U) ? DISABLE : ENABLE; - pVlanConfig->DoubleVLANProcessing = ((READ_BIT(heth->Instance->MACVTR, - ETH_MACVTR_EDVLP) >> 26) == 0U) ? DISABLE : ENABLE; - pVlanConfig->VLANTagHashTableMatch = ((READ_BIT(heth->Instance->MACVTR, - ETH_MACVTR_VTHM) >> 25) == 0U) ? DISABLE : ENABLE; - pVlanConfig->VLANTagInStatus = ((READ_BIT(heth->Instance->MACVTR, - ETH_MACVTR_EVLRXS) >> 24) == 0U) ? DISABLE : ENABLE; - pVlanConfig->StripVLANTag = READ_BIT(heth->Instance->MACVTR, ETH_MACVTR_EVLS); - pVlanConfig->VLANTypeCheck = READ_BIT(heth->Instance->MACVTR, - (ETH_MACVTR_DOVLTC | ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL)); - pVlanConfig->VLANTagInverceMatch = ((READ_BIT(heth->Instance->MACVTR, ETH_MACVTR_VTIM) >> 17) == 0U) - ? DISABLE : ENABLE; - - return HAL_OK; -} - -/** - * @brief Set the VLAN Configuration for Receive Packets. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure - * that contains VLAN filter configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_ETHEx_SetRxVLANConfig(ETH_HandleTypeDef *heth, ETH_RxVLANConfigTypeDef *pVlanConfig) -{ - if (pVlanConfig == NULL) - { - return HAL_ERROR; - } - - /* Write config to MACVTR */ - MODIFY_REG(heth->Instance->MACVTR, ETH_MACRXVLAN_MASK, (((uint32_t)pVlanConfig->InnerVLANTagInStatus << 31) | - pVlanConfig->StripInnerVLANTag | - ((uint32_t)pVlanConfig->InnerVLANTag << 27) | - ((uint32_t)pVlanConfig->DoubleVLANProcessing << 26) | - ((uint32_t)pVlanConfig->VLANTagHashTableMatch << 25) | - ((uint32_t)pVlanConfig->VLANTagInStatus << 24) | - pVlanConfig->StripVLANTag | - pVlanConfig->VLANTypeCheck | - ((uint32_t)pVlanConfig->VLANTagInverceMatch << 17))); - - return HAL_OK; -} - -/** - * @brief Set the VLAN Hash Table - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param VLANHashTable: VLAN hash table 16 bit value - * @retval None - */ -void HAL_ETHEx_SetVLANHashTable(ETH_HandleTypeDef *heth, uint32_t VLANHashTable) -{ - MODIFY_REG(heth->Instance->MACVHTR, ETH_MACVHTR_VLHT, VLANHashTable); -} - -/** - * @brief Get the VLAN Configuration for Transmit Packets. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param VLANTag: Selects the vlan tag, this parameter must be one of the following - * ETH_OUTER_TX_VLANTAG - * ETH_INNER_TX_VLANTAG - * @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure - * that will contain the Tx VLAN filter configuration. - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_ETHEx_GetTxVLANConfig(const ETH_HandleTypeDef *heth, uint32_t VLANTag, - ETH_TxVLANConfigTypeDef *pVlanConfig) -{ - if (pVlanConfig == NULL) - { - return HAL_ERROR; - } - - if (VLANTag == ETH_INNER_TX_VLANTAG) - { - pVlanConfig->SourceTxDesc = ((READ_BIT(heth->Instance->MACIVIR, ETH_MACVIR_VLTI) >> 20) == 0U) ? DISABLE : ENABLE; - pVlanConfig->SVLANType = ((READ_BIT(heth->Instance->MACIVIR, ETH_MACVIR_CSVL) >> 19) == 0U) ? DISABLE : ENABLE; - pVlanConfig->VLANTagControl = READ_BIT(heth->Instance->MACIVIR, (ETH_MACVIR_VLP | ETH_MACVIR_VLC)); - } - else - { - pVlanConfig->SourceTxDesc = ((READ_BIT(heth->Instance->MACVIR, ETH_MACVIR_VLTI) >> 20) == 0U) ? DISABLE : ENABLE; - pVlanConfig->SVLANType = ((READ_BIT(heth->Instance->MACVIR, ETH_MACVIR_CSVL) >> 19) == 0U) ? DISABLE : ENABLE; - pVlanConfig->VLANTagControl = READ_BIT(heth->Instance->MACVIR, (ETH_MACVIR_VLP | ETH_MACVIR_VLC)); - } - - return HAL_OK;; -} - -/** - * @brief Set the VLAN Configuration for Transmit Packets. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param VLANTag: Selects the vlan tag, this parameter must be one of the following - * ETH_OUTER_TX_VLANTAG - * ETH_INNER_TX_VLANTAG - * @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure - * that contains Tx VLAN filter configuration. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_ETHEx_SetTxVLANConfig(ETH_HandleTypeDef *heth, uint32_t VLANTag, - const ETH_TxVLANConfigTypeDef *pVlanConfig) -{ - if (VLANTag == ETH_INNER_TX_VLANTAG) - { - MODIFY_REG(heth->Instance->MACIVIR, ETH_MACTXVLAN_MASK, (((uint32_t)pVlanConfig->SourceTxDesc << 20) | - ((uint32_t)pVlanConfig->SVLANType << 19) | - pVlanConfig->VLANTagControl)); - /* Enable Double VLAN processing */ - SET_BIT(heth->Instance->MACVTR, ETH_MACVTR_EDVLP); - } - else - { - MODIFY_REG(heth->Instance->MACVIR, ETH_MACTXVLAN_MASK, (((uint32_t)pVlanConfig->SourceTxDesc << 20) | - ((uint32_t)pVlanConfig->SVLANType << 19) | - pVlanConfig->VLANTagControl)); - } - - return HAL_OK; -} - -/** - * @brief Set the VLAN Tag Identifier for Transmit Packets. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param VLANTag: Selects the vlan tag, this parameter must be one of the following - * ETH_OUTER_TX_VLANTAG - * ETH_INNER_TX_VLANTAG - * @param VLANIdentifier: VLAN Identifier 16 bit value - * @retval None - */ -void HAL_ETHEx_SetTxVLANIdentifier(ETH_HandleTypeDef *heth, uint32_t VLANTag, uint32_t VLANIdentifier) -{ - if (VLANTag == ETH_INNER_TX_VLANTAG) - { - MODIFY_REG(heth->Instance->MACIVIR, ETH_MACVIR_VLT, VLANIdentifier); - } - else - { - MODIFY_REG(heth->Instance->MACVIR, ETH_MACVIR_VLT, VLANIdentifier); - } -} - -/** - * @brief Enables the VLAN Tag Filtering process. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None. - */ -void HAL_ETHEx_EnableVLANProcessing(ETH_HandleTypeDef *heth) -{ - /* Enable VLAN processing */ - SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_VTFE); -} - -/** - * @brief Disables the VLAN Tag Filtering process. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None. - */ -void HAL_ETHEx_DisableVLANProcessing(ETH_HandleTypeDef *heth) -{ - /* Disable VLAN processing */ - CLEAR_BIT(heth->Instance->MACPFR, ETH_MACPFR_VTFE); -} - -/** - * @brief Enters the Low Power Idle (LPI) mode - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @param TxAutomate: Enable/Disable automate enter/exit LPI mode. - * @param TxClockStop: Enable/Disable Tx clock stop in LPI mode. - * @retval None - */ -void HAL_ETHEx_EnterLPIMode(ETH_HandleTypeDef *heth, FunctionalState TxAutomate, FunctionalState TxClockStop) -{ - /* Enable LPI Interrupts */ - __HAL_ETH_MAC_ENABLE_IT(heth, ETH_MACIER_LPIIE); - - /* Write to LPI Control register: Enter low power mode */ - MODIFY_REG(heth->Instance->MACLCSR, (ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE), - (((uint32_t)TxAutomate << 19) | - ((uint32_t)TxClockStop << 21) | - ETH_MACLCSR_LPIEN)); -} - -/** - * @brief Exits the Low Power Idle (LPI) mode. - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval None - */ -void HAL_ETHEx_ExitLPIMode(ETH_HandleTypeDef *heth) -{ - /* Clear the LPI Config and exit low power mode */ - CLEAR_BIT(heth->Instance->MACLCSR, (ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE)); - - /* Enable LPI Interrupts */ - __HAL_ETH_MAC_DISABLE_IT(heth, ETH_MACIER_LPIIE); -} - -/** - * @brief Returns the ETH MAC LPI event - * @param heth: pointer to a ETH_HandleTypeDef structure that contains - * the configuration information for ETHERNET module - * @retval ETH MAC WakeUp event - */ -uint32_t HAL_ETHEx_GetMACLPIEvent(const ETH_HandleTypeDef *heth) -{ - return heth->MACLPIEvent; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* ETH */ - -#endif /* HAL_ETH_MODULE_ENABLED */ -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_eth_ex.c + * @author MCD Application Team + * @brief ETH HAL Extended module driver. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_ETH_MODULE_ENABLED + +#if defined(ETH) + +/** @defgroup ETHEx ETHEx + * @brief ETH HAL Extended module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup ETHEx_Private_Constants ETHEx Private Constants + * @{ + */ +#define ETH_MACL4CR_MASK (ETH_MACL3L4CR_L4PEN | ETH_MACL3L4CR_L4SPM | \ + ETH_MACL3L4CR_L4SPIM | ETH_MACL3L4CR_L4DPM | \ + ETH_MACL3L4CR_L4DPIM) + +#define ETH_MACL3CR_MASK (ETH_MACL3L4CR_L3PEN | ETH_MACL3L4CR_L3SAM | \ + ETH_MACL3L4CR_L3SAIM | ETH_MACL3L4CR_L3DAM | \ + ETH_MACL3L4CR_L3DAIM | ETH_MACL3L4CR_L3HSBM | \ + ETH_MACL3L4CR_L3HDBM) + +#define ETH_MACRXVLAN_MASK (ETH_MACVTR_EIVLRXS | ETH_MACVTR_EIVLS | \ + ETH_MACVTR_ERIVLT | ETH_MACVTR_EDVLP | \ + ETH_MACVTR_VTHM | ETH_MACVTR_EVLRXS | \ + ETH_MACVTR_EVLS | ETH_MACVTR_DOVLTC | \ + ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL | \ + ETH_MACVTR_VTIM | ETH_MACVTR_ETV) + +#define ETH_MACTXVLAN_MASK (ETH_MACVIR_VLTI | ETH_MACVIR_CSVL | \ + ETH_MACVIR_VLP | ETH_MACVIR_VLC) + +#define ETH_MAC_L4_SRSP_MASK 0x0000FFFFU +#define ETH_MAC_L4_DSTP_MASK 0xFFFF0000U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions ---------------------------------------------------------*/ +/** @defgroup ETHEx_Exported_Functions ETH Extended Exported Functions + * @{ + */ + +/** @defgroup ETHEx_Exported_Functions_Group1 Extended features functions + * @brief Extended features functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure ARP offload module + (+) Configure L3 and L4 filters + (+) Configure Extended VLAN features + (+) Configure Energy Efficient Ethernet module + +@endverbatim + * @{ + */ + +/** + * @brief Enables ARP Offload. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ + +void HAL_ETHEx_EnableARPOffload(ETH_HandleTypeDef *heth) +{ + SET_BIT(heth->Instance->MACCR, ETH_MACCR_ARP); +} + +/** + * @brief Disables ARP Offload. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +void HAL_ETHEx_DisableARPOffload(ETH_HandleTypeDef *heth) +{ + CLEAR_BIT(heth->Instance->MACCR, ETH_MACCR_ARP); +} + +/** + * @brief Set the ARP Match IP address + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param IpAddress: IP Address to be matched for incoming ARP requests + * @retval None + */ +void HAL_ETHEx_SetARPAddressMatch(ETH_HandleTypeDef *heth, uint32_t IpAddress) +{ + WRITE_REG(heth->Instance->MACARPAR, IpAddress); +} + +/** + * @brief Configures the L4 Filter, this function allow to: + * set the layer 4 protocol to be matched (TCP or UDP) + * enable/disable L4 source/destination port perfect/inverse match. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param Filter: L4 filter to configured, this parameter must be one of the following + * ETH_L4_FILTER_0 + * ETH_L4_FILTER_1 + * @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure + * that contains L4 filter configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ETHEx_SetL4FilterConfig(ETH_HandleTypeDef *heth, uint32_t Filter, + const ETH_L4FilterConfigTypeDef *pL4FilterConfig) +{ + if (pL4FilterConfig == NULL) + { + return HAL_ERROR; + } + + if (Filter == ETH_L4_FILTER_0) + { + /* Write configuration to MACL3L4C0R register */ + MODIFY_REG(heth->Instance->MACL3L4C0R, ETH_MACL4CR_MASK, (pL4FilterConfig->Protocol | + pL4FilterConfig->SrcPortFilterMatch | + pL4FilterConfig->DestPortFilterMatch)); + + /* Write configuration to MACL4A0R register */ + WRITE_REG(heth->Instance->MACL4A0R, (pL4FilterConfig->SourcePort | (pL4FilterConfig->DestinationPort << 16))); + + } + else /* Filter == ETH_L4_FILTER_1 */ + { + /* Write configuration to MACL3L4C1R register */ + MODIFY_REG(heth->Instance->MACL3L4C1R, ETH_MACL4CR_MASK, (pL4FilterConfig->Protocol | + pL4FilterConfig->SrcPortFilterMatch | + pL4FilterConfig->DestPortFilterMatch)); + + /* Write configuration to MACL4A1R register */ + WRITE_REG(heth->Instance->MACL4A1R, (pL4FilterConfig->SourcePort | (pL4FilterConfig->DestinationPort << 16))); + } + + /* Enable L4 filter */ + SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); + + return HAL_OK; +} + +/** + * @brief Configures the L4 Filter, this function allow to: + * set the layer 4 protocol to be matched (TCP or UDP) + * enable/disable L4 source/destination port perfect/inverse match. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param Filter: L4 filter to configured, this parameter must be one of the following + * ETH_L4_FILTER_0 + * ETH_L4_FILTER_1 + * @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure + * that contains L4 filter configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ETHEx_GetL4FilterConfig(const ETH_HandleTypeDef *heth, uint32_t Filter, + ETH_L4FilterConfigTypeDef *pL4FilterConfig) +{ + if (pL4FilterConfig == NULL) + { + return HAL_ERROR; + } + + if (Filter == ETH_L4_FILTER_0) + { + /* Get configuration from MACL3L4C0R register */ + pL4FilterConfig->Protocol = READ_BIT(heth->Instance->MACL3L4C0R, ETH_MACL3L4CR_L4PEN); + pL4FilterConfig->DestPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C0R, + (ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM)); + pL4FilterConfig->SrcPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C0R, + (ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM)); + + /* Get configuration from MACL4A0R register */ + pL4FilterConfig->DestinationPort = (READ_BIT(heth->Instance->MACL4A0R, ETH_MAC_L4_DSTP_MASK) >> 16); + pL4FilterConfig->SourcePort = READ_BIT(heth->Instance->MACL4A0R, ETH_MAC_L4_SRSP_MASK); + } + else /* Filter == ETH_L4_FILTER_1 */ + { + /* Get configuration from MACL3L4C1R register */ + pL4FilterConfig->Protocol = READ_BIT(heth->Instance->MACL3L4C1R, ETH_MACL3L4CR_L4PEN); + pL4FilterConfig->DestPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C1R, + (ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM)); + pL4FilterConfig->SrcPortFilterMatch = READ_BIT(heth->Instance->MACL3L4C1R, + (ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM)); + + /* Get configuration from MACL4A1R register */ + pL4FilterConfig->DestinationPort = (READ_BIT(heth->Instance->MACL4A1R, ETH_MAC_L4_DSTP_MASK) >> 16); + pL4FilterConfig->SourcePort = READ_BIT(heth->Instance->MACL4A1R, ETH_MAC_L4_SRSP_MASK); + } + + return HAL_OK; +} + +/** + * @brief Configures the L3 Filter, this function allow to: + * set the layer 3 protocol to be matched (IPv4 or IPv6) + * enable/disable L3 source/destination port perfect/inverse match. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param Filter: L3 filter to configured, this parameter must be one of the following + * ETH_L3_FILTER_0 + * ETH_L3_FILTER_1 + * @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure + * that contains L3 filter configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ETHEx_SetL3FilterConfig(ETH_HandleTypeDef *heth, uint32_t Filter, + const ETH_L3FilterConfigTypeDef *pL3FilterConfig) +{ + if (pL3FilterConfig == NULL) + { + return HAL_ERROR; + } + + if (Filter == ETH_L3_FILTER_0) + { + /* Write configuration to MACL3L4C0R register */ + MODIFY_REG(heth->Instance->MACL3L4C0R, ETH_MACL3CR_MASK, (pL3FilterConfig->Protocol | + pL3FilterConfig->SrcAddrFilterMatch | + pL3FilterConfig->DestAddrFilterMatch | + (pL3FilterConfig->SrcAddrHigherBitsMatch << 6) | + (pL3FilterConfig->DestAddrHigherBitsMatch << 11))); + } + else /* Filter == ETH_L3_FILTER_1 */ + { + /* Write configuration to MACL3L4C1R register */ + MODIFY_REG(heth->Instance->MACL3L4C1R, ETH_MACL3CR_MASK, (pL3FilterConfig->Protocol | + pL3FilterConfig->SrcAddrFilterMatch | + pL3FilterConfig->DestAddrFilterMatch | + (pL3FilterConfig->SrcAddrHigherBitsMatch << 6) | + (pL3FilterConfig->DestAddrHigherBitsMatch << 11))); + } + + if (Filter == ETH_L3_FILTER_0) + { + /* Check if IPv6 protocol is selected */ + if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) + { + /* Set the IPv6 address match */ + /* Set Bits[31:0] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip6Addr[0]); + /* Set Bits[63:32] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip6Addr[1]); + /* update Bits[95:64] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A2R0R, pL3FilterConfig->Ip6Addr[2]); + /* update Bits[127:96] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A3R0R, pL3FilterConfig->Ip6Addr[3]); + } + else /* IPv4 protocol is selected */ + { + /* Set the IPv4 source address match */ + WRITE_REG(heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip4SrcAddr); + /* Set the IPv4 destination address match */ + WRITE_REG(heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip4DestAddr); + } + } + else /* Filter == ETH_L3_FILTER_1 */ + { + /* Check if IPv6 protocol is selected */ + if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) + { + /* Set the IPv6 address match */ + /* Set Bits[31:0] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip6Addr[0]); + /* Set Bits[63:32] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[1]); + /* update Bits[95:64] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[2]); + /* update Bits[127:96] of 128-bit IP addr */ + WRITE_REG(heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[3]); + } + else /* IPv4 protocol is selected */ + { + /* Set the IPv4 source address match */ + WRITE_REG(heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4SrcAddr); + /* Set the IPv4 destination address match */ + WRITE_REG(heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4DestAddr); + + } + } + + /* Enable L3 filter */ + SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); + + return HAL_OK; +} + +/** + * @brief Configures the L3 Filter, this function allow to: + * set the layer 3 protocol to be matched (IPv4 or IPv6) + * enable/disable L3 source/destination port perfect/inverse match. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param Filter: L3 filter to configured, this parameter must be one of the following + * ETH_L3_FILTER_0 + * ETH_L3_FILTER_1 + * @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure + * that will contain the L3 filter configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ETHEx_GetL3FilterConfig(const ETH_HandleTypeDef *heth, uint32_t Filter, + ETH_L3FilterConfigTypeDef *pL3FilterConfig) +{ + if (pL3FilterConfig == NULL) + { + return HAL_ERROR; + } + pL3FilterConfig->Protocol = READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), + ETH_MACL3L4CR_L3PEN); + pL3FilterConfig->SrcAddrFilterMatch = READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), + (ETH_MACL3L4CR_L3SAM | ETH_MACL3L4CR_L3SAIM)); + pL3FilterConfig->DestAddrFilterMatch = READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), + (ETH_MACL3L4CR_L3DAM | ETH_MACL3L4CR_L3DAIM)); + pL3FilterConfig->SrcAddrHigherBitsMatch = (READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), + ETH_MACL3L4CR_L3HSBM) >> 6); + pL3FilterConfig->DestAddrHigherBitsMatch = (READ_BIT(*((__IO uint32_t *)(&(heth->Instance->MACL3L4C0R) + Filter)), + ETH_MACL3L4CR_L3HDBM) >> 11); + + if (Filter == ETH_L3_FILTER_0) + { + if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) + { + WRITE_REG(pL3FilterConfig->Ip6Addr[0], heth->Instance->MACL3A0R0R); + WRITE_REG(pL3FilterConfig->Ip6Addr[1], heth->Instance->MACL3A1R0R); + WRITE_REG(pL3FilterConfig->Ip6Addr[2], heth->Instance->MACL3A2R0R); + WRITE_REG(pL3FilterConfig->Ip6Addr[3], heth->Instance->MACL3A3R0R); + } + else + { + WRITE_REG(pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R0R); + WRITE_REG(pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R0R); + } + } + else /* ETH_L3_FILTER_1 */ + { + if (pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH) + { + WRITE_REG(pL3FilterConfig->Ip6Addr[0], heth->Instance->MACL3A0R1R); + WRITE_REG(pL3FilterConfig->Ip6Addr[1], heth->Instance->MACL3A1R1R); + WRITE_REG(pL3FilterConfig->Ip6Addr[2], heth->Instance->MACL3A2R1R); + WRITE_REG(pL3FilterConfig->Ip6Addr[3], heth->Instance->MACL3A3R1R); + } + else + { + WRITE_REG(pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R1R); + WRITE_REG(pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R1R); + } + } + + return HAL_OK; +} + +/** + * @brief Enables L3 and L4 filtering process. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None. + */ +void HAL_ETHEx_EnableL3L4Filtering(ETH_HandleTypeDef *heth) +{ + /* Enable L3/L4 filter */ + SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); +} + +/** + * @brief Disables L3 and L4 filtering process. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None. + */ +void HAL_ETHEx_DisableL3L4Filtering(ETH_HandleTypeDef *heth) +{ + /* Disable L3/L4 filter */ + CLEAR_BIT(heth->Instance->MACPFR, ETH_MACPFR_IPFE); +} + +/** + * @brief Get the VLAN Configuration for Receive Packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure + * that will contain the VLAN filter configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ETHEx_GetRxVLANConfig(const ETH_HandleTypeDef *heth, ETH_RxVLANConfigTypeDef *pVlanConfig) +{ + if (pVlanConfig == NULL) + { + return HAL_ERROR; + } + + pVlanConfig->InnerVLANTagInStatus = ((READ_BIT(heth->Instance->MACVTR, + ETH_MACVTR_EIVLRXS) >> 31) == 0U) ? DISABLE : ENABLE; + pVlanConfig->StripInnerVLANTag = READ_BIT(heth->Instance->MACVTR, ETH_MACVTR_EIVLS); + pVlanConfig->InnerVLANTag = ((READ_BIT(heth->Instance->MACVTR, + ETH_MACVTR_ERIVLT) >> 27) == 0U) ? DISABLE : ENABLE; + pVlanConfig->DoubleVLANProcessing = ((READ_BIT(heth->Instance->MACVTR, + ETH_MACVTR_EDVLP) >> 26) == 0U) ? DISABLE : ENABLE; + pVlanConfig->VLANTagHashTableMatch = ((READ_BIT(heth->Instance->MACVTR, + ETH_MACVTR_VTHM) >> 25) == 0U) ? DISABLE : ENABLE; + pVlanConfig->VLANTagInStatus = ((READ_BIT(heth->Instance->MACVTR, + ETH_MACVTR_EVLRXS) >> 24) == 0U) ? DISABLE : ENABLE; + pVlanConfig->StripVLANTag = READ_BIT(heth->Instance->MACVTR, ETH_MACVTR_EVLS); + pVlanConfig->VLANTypeCheck = READ_BIT(heth->Instance->MACVTR, + (ETH_MACVTR_DOVLTC | ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL)); + pVlanConfig->VLANTagInverceMatch = ((READ_BIT(heth->Instance->MACVTR, ETH_MACVTR_VTIM) >> 17) == 0U) + ? DISABLE : ENABLE; + + return HAL_OK; +} + +/** + * @brief Set the VLAN Configuration for Receive Packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure + * that contains VLAN filter configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ETHEx_SetRxVLANConfig(ETH_HandleTypeDef *heth, ETH_RxVLANConfigTypeDef *pVlanConfig) +{ + if (pVlanConfig == NULL) + { + return HAL_ERROR; + } + + /* Write config to MACVTR */ + MODIFY_REG(heth->Instance->MACVTR, ETH_MACRXVLAN_MASK, (((uint32_t)pVlanConfig->InnerVLANTagInStatus << 31) | + pVlanConfig->StripInnerVLANTag | + ((uint32_t)pVlanConfig->InnerVLANTag << 27) | + ((uint32_t)pVlanConfig->DoubleVLANProcessing << 26) | + ((uint32_t)pVlanConfig->VLANTagHashTableMatch << 25) | + ((uint32_t)pVlanConfig->VLANTagInStatus << 24) | + pVlanConfig->StripVLANTag | + pVlanConfig->VLANTypeCheck | + ((uint32_t)pVlanConfig->VLANTagInverceMatch << 17))); + + return HAL_OK; +} + +/** + * @brief Set the VLAN Hash Table + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param VLANHashTable: VLAN hash table 16 bit value + * @retval None + */ +void HAL_ETHEx_SetVLANHashTable(ETH_HandleTypeDef *heth, uint32_t VLANHashTable) +{ + MODIFY_REG(heth->Instance->MACVHTR, ETH_MACVHTR_VLHT, VLANHashTable); +} + +/** + * @brief Get the VLAN Configuration for Transmit Packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param VLANTag: Selects the vlan tag, this parameter must be one of the following + * ETH_OUTER_TX_VLANTAG + * ETH_INNER_TX_VLANTAG + * @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure + * that will contain the Tx VLAN filter configuration. + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_ETHEx_GetTxVLANConfig(const ETH_HandleTypeDef *heth, uint32_t VLANTag, + ETH_TxVLANConfigTypeDef *pVlanConfig) +{ + if (pVlanConfig == NULL) + { + return HAL_ERROR; + } + + if (VLANTag == ETH_INNER_TX_VLANTAG) + { + pVlanConfig->SourceTxDesc = ((READ_BIT(heth->Instance->MACIVIR, ETH_MACVIR_VLTI) >> 20) == 0U) ? DISABLE : ENABLE; + pVlanConfig->SVLANType = ((READ_BIT(heth->Instance->MACIVIR, ETH_MACVIR_CSVL) >> 19) == 0U) ? DISABLE : ENABLE; + pVlanConfig->VLANTagControl = READ_BIT(heth->Instance->MACIVIR, (ETH_MACVIR_VLP | ETH_MACVIR_VLC)); + } + else + { + pVlanConfig->SourceTxDesc = ((READ_BIT(heth->Instance->MACVIR, ETH_MACVIR_VLTI) >> 20) == 0U) ? DISABLE : ENABLE; + pVlanConfig->SVLANType = ((READ_BIT(heth->Instance->MACVIR, ETH_MACVIR_CSVL) >> 19) == 0U) ? DISABLE : ENABLE; + pVlanConfig->VLANTagControl = READ_BIT(heth->Instance->MACVIR, (ETH_MACVIR_VLP | ETH_MACVIR_VLC)); + } + + return HAL_OK;; +} + +/** + * @brief Set the VLAN Configuration for Transmit Packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param VLANTag: Selects the vlan tag, this parameter must be one of the following + * ETH_OUTER_TX_VLANTAG + * ETH_INNER_TX_VLANTAG + * @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure + * that contains Tx VLAN filter configuration. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_ETHEx_SetTxVLANConfig(ETH_HandleTypeDef *heth, uint32_t VLANTag, + const ETH_TxVLANConfigTypeDef *pVlanConfig) +{ + if (VLANTag == ETH_INNER_TX_VLANTAG) + { + MODIFY_REG(heth->Instance->MACIVIR, ETH_MACTXVLAN_MASK, (((uint32_t)pVlanConfig->SourceTxDesc << 20) | + ((uint32_t)pVlanConfig->SVLANType << 19) | + pVlanConfig->VLANTagControl)); + /* Enable Double VLAN processing */ + SET_BIT(heth->Instance->MACVTR, ETH_MACVTR_EDVLP); + } + else + { + MODIFY_REG(heth->Instance->MACVIR, ETH_MACTXVLAN_MASK, (((uint32_t)pVlanConfig->SourceTxDesc << 20) | + ((uint32_t)pVlanConfig->SVLANType << 19) | + pVlanConfig->VLANTagControl)); + } + + return HAL_OK; +} + +/** + * @brief Set the VLAN Tag Identifier for Transmit Packets. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param VLANTag: Selects the vlan tag, this parameter must be one of the following + * ETH_OUTER_TX_VLANTAG + * ETH_INNER_TX_VLANTAG + * @param VLANIdentifier: VLAN Identifier 16 bit value + * @retval None + */ +void HAL_ETHEx_SetTxVLANIdentifier(ETH_HandleTypeDef *heth, uint32_t VLANTag, uint32_t VLANIdentifier) +{ + if (VLANTag == ETH_INNER_TX_VLANTAG) + { + MODIFY_REG(heth->Instance->MACIVIR, ETH_MACVIR_VLT, VLANIdentifier); + } + else + { + MODIFY_REG(heth->Instance->MACVIR, ETH_MACVIR_VLT, VLANIdentifier); + } +} + +/** + * @brief Enables the VLAN Tag Filtering process. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None. + */ +void HAL_ETHEx_EnableVLANProcessing(ETH_HandleTypeDef *heth) +{ + /* Enable VLAN processing */ + SET_BIT(heth->Instance->MACPFR, ETH_MACPFR_VTFE); +} + +/** + * @brief Disables the VLAN Tag Filtering process. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None. + */ +void HAL_ETHEx_DisableVLANProcessing(ETH_HandleTypeDef *heth) +{ + /* Disable VLAN processing */ + CLEAR_BIT(heth->Instance->MACPFR, ETH_MACPFR_VTFE); +} + +/** + * @brief Enters the Low Power Idle (LPI) mode + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @param TxAutomate: Enable/Disable automate enter/exit LPI mode. + * @param TxClockStop: Enable/Disable Tx clock stop in LPI mode. + * @retval None + */ +void HAL_ETHEx_EnterLPIMode(ETH_HandleTypeDef *heth, FunctionalState TxAutomate, FunctionalState TxClockStop) +{ + /* Enable LPI Interrupts */ + __HAL_ETH_MAC_ENABLE_IT(heth, ETH_MACIER_LPIIE); + + /* Write to LPI Control register: Enter low power mode */ + MODIFY_REG(heth->Instance->MACLCSR, (ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE), + (((uint32_t)TxAutomate << 19) | + ((uint32_t)TxClockStop << 21) | + ETH_MACLCSR_LPIEN)); +} + +/** + * @brief Exits the Low Power Idle (LPI) mode. + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval None + */ +void HAL_ETHEx_ExitLPIMode(ETH_HandleTypeDef *heth) +{ + /* Clear the LPI Config and exit low power mode */ + CLEAR_BIT(heth->Instance->MACLCSR, (ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE)); + + /* Enable LPI Interrupts */ + __HAL_ETH_MAC_DISABLE_IT(heth, ETH_MACIER_LPIIE); +} + +/** + * @brief Returns the ETH MAC LPI event + * @param heth: pointer to a ETH_HandleTypeDef structure that contains + * the configuration information for ETHERNET module + * @retval ETH MAC WakeUp event + */ +uint32_t HAL_ETHEx_GetMACLPIEvent(const ETH_HandleTypeDef *heth) +{ + return heth->MACLPIEvent; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* ETH */ + +#endif /* HAL_ETH_MODULE_ENABLED */ +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_exti.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_exti.c index 5d1a41ae0..00a48f56c 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_exti.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_exti.c @@ -1,639 +1,638 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_exti.c - * @author MCD Application Team - * @brief EXTI HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the General Purpose Input/Output (EXTI) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### EXTI Peripheral features ##### - ============================================================================== - [..] - (+) Each Exti line can be configured within this driver. - - (+) Exti line can be configured in 3 different modes - (++) Interrupt - (++) Event - (++) Both of them - - (+) Configurable Exti lines can be configured with 3 different triggers - (++) Rising - (++) Falling - (++) Both of them - - (+) When set in interrupt mode, configurable Exti lines have two different - interrupts pending registers which allow to distinguish which transition - occurs: - (++) Rising edge pending interrupt - (++) Falling - - (+) Exti lines 0 to 15 are linked to gpio pin number 0 to 15. Gpio port can - be selected through multiplexer. - - ##### How to use this driver ##### - ============================================================================== - [..] - - (#) Configure the EXTI line using HAL_EXTI_SetConfigLine(). - (++) Choose the interrupt line number by setting "Line" member from - EXTI_ConfigTypeDef structure. - (++) Configure the interrupt and/or event mode using "Mode" member from - EXTI_ConfigTypeDef structure. - (++) For configurable lines, configure rising and/or falling trigger - "Trigger" member from EXTI_ConfigTypeDef structure. - (++) For Exti lines linked to gpio, choose gpio port using "GPIOSel" - member from GPIO_InitTypeDef structure. - - (#) Get current Exti configuration of a dedicated line using - HAL_EXTI_GetConfigLine(). - (++) Provide exiting handle as parameter. - (++) Provide pointer on EXTI_ConfigTypeDef structure as second parameter. - - (#) Clear Exti configuration of a dedicated line using HAL_EXTI_GetConfigLine(). - (++) Provide exiting handle as parameter. - - (#) Register callback to treat Exti interrupts using HAL_EXTI_RegisterCallback(). - (++) Provide exiting handle as first parameter. - (++) Provide which callback will be registered using one value from - EXTI_CallbackIDTypeDef. - (++) Provide callback function pointer. - - (#) Get interrupt pending bit using HAL_EXTI_GetPending(). - - (#) Clear interrupt pending bit using HAL_EXTI_GetPending(). - - (#) Generate software interrupt using HAL_EXTI_GenerateSWI(). - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @addtogroup EXTI - * @{ - */ - -#ifdef HAL_EXTI_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private defines ------------------------------------------------------------*/ -/** @defgroup EXTI_Private_Constants EXTI Private Constants - * @{ - */ -#define EXTI_MODE_OFFSET 0x04u /* 0x10: Offset between MCU IMRx/EMRx registers */ -#define EXTI_CONFIG_OFFSET 0x08u /* 0x20: Offset between MCU Rising/Falling configuration registers */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup EXTI_Exported_Functions - * @{ - */ - -/** @addtogroup EXTI_Exported_Functions_Group1 - * @brief Configuration functions - * -@verbatim - =============================================================================== - ##### Configuration functions ##### - =============================================================================== - -@endverbatim - * @{ - */ - -/** - * @brief Set configuration of a dedicated Exti line. - * @param hexti Exti handle. - * @param pExtiConfig Pointer on EXTI configuration to be set. - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_EXTI_SetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) -{ - __IO uint32_t *regaddr; - uint32_t regval; - uint32_t linepos; - uint32_t maskline; - uint32_t offset; - - /* Check null pointer */ - if ((hexti == NULL) || (pExtiConfig == NULL)) - { - return HAL_ERROR; - } - - /* Check parameters */ - assert_param(IS_EXTI_LINE(pExtiConfig->Line)); - assert_param(IS_EXTI_MODE(pExtiConfig->Mode)); - - /* Assign line number to handle */ - hexti->Line = pExtiConfig->Line; - - /* Compute line register offset and line mask */ - offset = ((pExtiConfig->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - linepos = (pExtiConfig->Line & EXTI_PIN_MASK); - maskline = (1uL << linepos); - - /* Configure triggers for configurable lines */ - if ((pExtiConfig->Line & EXTI_CONFIG) != 0x00u) - { - assert_param(IS_EXTI_TRIGGER(pExtiConfig->Trigger)); - - /* Configure rising trigger */ - regaddr = (__IO uint32_t *)(&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); - regval = *regaddr; - - /* Mask or set line */ - if ((pExtiConfig->Trigger & EXTI_TRIGGER_RISING) != 0x00u) - { - regval |= maskline; - } - else - { - regval &= ~maskline; - } - - /* Store rising trigger mode */ - *regaddr = regval; - - /* Configure falling trigger */ - regaddr = (__IO uint32_t *)(&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); - regval = *regaddr; - - /* Mask or set line */ - if ((pExtiConfig->Trigger & EXTI_TRIGGER_FALLING) != 0x00u) - { - regval |= maskline; - } - else - { - regval &= ~maskline; - } - - /* Store falling trigger mode */ - *regaddr = regval; - - /* Configure gpio port selection in case of gpio exti line */ - if ((pExtiConfig->Line & EXTI_GPIO) == EXTI_GPIO) - { - assert_param(IS_EXTI_GPIO_PORT(pExtiConfig->GPIOSel)); - assert_param(IS_EXTI_GPIO_PIN(linepos)); - - regval = SBS->EXTICR[linepos >> 2u]; - regval &= ~(SBS_EXTICR1_PC_EXTI0 << (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))); - regval |= (pExtiConfig->GPIOSel << (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))); - SBS->EXTICR[linepos >> 2u] = regval; - } - } - - /* Configure interrupt mode : read current mode */ - regaddr = (__IO uint32_t *)(&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); - regval = *regaddr; - - /* Mask or set line */ - if ((pExtiConfig->Mode & EXTI_MODE_INTERRUPT) != 0x00u) - { - regval |= maskline; - } - else - { - regval &= ~maskline; - } - - /* Store interrupt mode */ - *regaddr = regval; - - /* The event mode cannot be configured if the line does not support it */ - assert_param(((pExtiConfig->Line & EXTI_EVENT) == EXTI_EVENT) || ((pExtiConfig->Mode & EXTI_MODE_EVENT) != EXTI_MODE_EVENT)); - - /* Configure event mode : read current mode */ - regaddr = (__IO uint32_t *)(&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); - regval = *regaddr; - - /* Mask or set line */ - if ((pExtiConfig->Mode & EXTI_MODE_EVENT) != 0x00u) - { - regval |= maskline; - } - else - { - regval &= ~maskline; - } - - /* Store event mode */ - *regaddr = regval; - - return HAL_OK; -} - - -/** - * @brief Get configuration of a dedicated Exti line. - * @param hexti Exti handle. - * @param pExtiConfig Pointer on structure to store Exti configuration. - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_EXTI_GetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) -{ - const __IO uint32_t *regaddr; - uint32_t regval; - uint32_t linepos; - uint32_t maskline; - uint32_t offset; - - /* Check null pointer */ - if ((hexti == NULL) || (pExtiConfig == NULL)) - { - return HAL_ERROR; - } - - /* Check the parameter */ - assert_param(IS_EXTI_LINE(hexti->Line)); - - /* Store handle line number to configuration structure */ - pExtiConfig->Line = hexti->Line; - - /* Compute line register offset and line mask */ - offset = ((pExtiConfig->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - linepos = (pExtiConfig->Line & EXTI_PIN_MASK); - maskline = (1uL << linepos); - - /* 1] Get core mode : interrupt */ - regaddr = (__IO uint32_t *)(&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); - regval = *regaddr; - - /* Check if selected line is enable */ - if ((regval & maskline) != 0x00u) - { - pExtiConfig->Mode = EXTI_MODE_INTERRUPT; - } - else - { - pExtiConfig->Mode = EXTI_MODE_NONE; - } - - /* Get event mode */ - regaddr = (__IO uint32_t *)(&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); - regval = *regaddr; - - /* Check if selected line is enable */ - if ((regval & maskline) != 0x00u) - { - pExtiConfig->Mode |= EXTI_MODE_EVENT; - } - - /* 2] Get trigger for configurable lines : rising */ - if ((pExtiConfig->Line & EXTI_CONFIG) != 0x00u) - { - regaddr = (__IO uint32_t *)(&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); - regval = *regaddr; - - /* Check if configuration of selected line is enable */ - if ((regval & maskline) != 0x00u) - { - pExtiConfig->Trigger = EXTI_TRIGGER_RISING; - } - else - { - pExtiConfig->Trigger = EXTI_TRIGGER_NONE; - } - - /* Get falling configuration */ - regaddr = (__IO uint32_t *)(&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); - regval = *regaddr; - - /* Check if configuration of selected line is enable */ - if ((regval & maskline) != 0x00u) - { - pExtiConfig->Trigger |= EXTI_TRIGGER_FALLING; - } - - /* Get Gpio port selection for gpio lines */ - if ((pExtiConfig->Line & EXTI_GPIO) == EXTI_GPIO) - { - assert_param(IS_EXTI_GPIO_PIN(linepos)); - - regval = SBS->EXTICR[linepos >> 2u]; - pExtiConfig->GPIOSel = (regval >> (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))) & SBS_EXTICR1_PC_EXTI0; - } - else - { - pExtiConfig->GPIOSel = 0x00u; - } - } - else - { - pExtiConfig->Trigger = EXTI_TRIGGER_NONE; - pExtiConfig->GPIOSel = 0x00u; - } - - return HAL_OK; -} - - -/** - * @brief Clear whole configuration of a dedicated Exti line. - * @param hexti Exti handle. - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_EXTI_ClearConfigLine(const EXTI_HandleTypeDef *hexti) -{ - __IO uint32_t *regaddr; - uint32_t regval; - uint32_t linepos; - uint32_t maskline; - uint32_t offset; - - /* Check null pointer */ - if (hexti == NULL) - { - return HAL_ERROR; - } - - /* Check the parameter */ - assert_param(IS_EXTI_LINE(hexti->Line)); - - /* compute line register offset and line mask */ - offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - linepos = (hexti->Line & EXTI_PIN_MASK); - maskline = (1uL << linepos); - - /* 1] Clear interrupt mode */ - regaddr = (__IO uint32_t *)(&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); - regval = (*regaddr & ~maskline); - *regaddr = regval; - - /* 2] Clear event mode */ - regaddr = (__IO uint32_t *)(&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); - regval = (*regaddr & ~maskline); - *regaddr = regval; - - /* 3] Clear triggers in case of configurable lines */ - if ((hexti->Line & EXTI_CONFIG) != 0x00u) - { - regaddr = (__IO uint32_t *)(&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); - regval = (*regaddr & ~maskline); - *regaddr = regval; - - regaddr = (__IO uint32_t *)(&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); - regval = (*regaddr & ~maskline); - *regaddr = regval; - - /* Get Gpio port selection for gpio lines */ - if ((hexti->Line & EXTI_GPIO) == EXTI_GPIO) - { - assert_param(IS_EXTI_GPIO_PIN(linepos)); - - regval = SBS->EXTICR[linepos >> 2u]; - regval &= ~(SBS_EXTICR1_PC_EXTI0 << (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))); - SBS->EXTICR[linepos >> 2u] = regval; - } - } - - return HAL_OK; -} - - -/** - * @brief Register callback for a dedicated Exti line. - * @param hexti Exti handle. - * @param CallbackID User callback identifier. - * This parameter can be one of @arg @ref EXTI_CallbackIDTypeDef values. - * @param pPendingCbfn function pointer to be stored as callback. - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_EXTI_RegisterCallback(EXTI_HandleTypeDef *hexti, EXTI_CallbackIDTypeDef CallbackID, void (*pPendingCbfn)(void)) -{ - HAL_StatusTypeDef status = HAL_OK; - - switch (CallbackID) - { - case HAL_EXTI_COMMON_CB_ID: - hexti->PendingCallback = pPendingCbfn; - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} - - -/** - * @brief Store line number as handle private field. - * @param hexti Exti handle. - * @param ExtiLine Exti line number. - * This parameter can be from 0 to @ref EXTI_LINE_NB. - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_EXTI_GetHandle(EXTI_HandleTypeDef *hexti, uint32_t ExtiLine) -{ - /* Check the parameters */ - assert_param(IS_EXTI_LINE(ExtiLine)); - - /* Check null pointer */ - if (hexti == NULL) - { - return HAL_ERROR; - } - else - { - /* Store line number as handle private field */ - hexti->Line = ExtiLine; - - return HAL_OK; - } -} - - -/** - * @} - */ - -/** @addtogroup EXTI_Exported_Functions_Group2 - * @brief EXTI IO functions. - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - -@endverbatim - * @{ - */ - -/** - * @brief Handle EXTI interrupt request. - * @param hexti Exti handle. - * @retval none. - */ -void HAL_EXTI_IRQHandler(const EXTI_HandleTypeDef *hexti) -{ - __IO uint32_t *regaddr; - uint32_t regval; - uint32_t maskline; - uint32_t offset; - - /* Compute line register offset and line mask */ - offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); - - /* Get pending bit */ - regaddr = (__IO uint32_t *)(&EXTI->PR1 + (EXTI_MODE_OFFSET * offset)); - regval = (*regaddr & maskline); - - if (regval != 0x00u) - { - /* Clear pending bit */ - *regaddr = maskline; - - /* Call callback */ - if (hexti->PendingCallback != NULL) - { - hexti->PendingCallback(); - } - } -} - - -/** - * @brief Get interrupt pending bit of a dedicated line. - * @param hexti Exti handle. - * @param Edge Specify which pending edge as to be checked. - * This parameter can be one of the following values: - * @arg @ref EXTI_TRIGGER_RISING_FALLING - * This parameter is kept for compatibility with other series. - * @retval 1 if interrupt is pending else 0. - */ -uint32_t HAL_EXTI_GetPending(const EXTI_HandleTypeDef *hexti, uint32_t Edge) -{ - const __IO uint32_t *regaddr; - uint32_t regval; - uint32_t linepos; - uint32_t maskline; - uint32_t offset; - - /* Check parameters */ - assert_param(IS_EXTI_LINE(hexti->Line)); - assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); - - /* Prevent unused argument(s) compilation warning */ - UNUSED(Edge); - - /* Compute line register offset and line mask */ - offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - linepos = (hexti->Line & EXTI_PIN_MASK); - maskline = (1uL << linepos); - - /* Get pending bit */ - regaddr = (__IO uint32_t *)(&EXTI->PR1 + (EXTI_MODE_OFFSET * offset)); - - /* return 1 if bit is set else 0 */ - regval = ((*regaddr & maskline) >> linepos); - return regval; -} - - -/** - * @brief Clear interrupt pending bit of a dedicated line. - * @param hexti Exti handle. - * @param Edge Specify which pending edge as to be clear. - * This parameter can be one of the following values: - * @arg @ref EXTI_TRIGGER_RISING_FALLING - * This parameter is kept for compatibility with other series. - * @retval None. - */ -void HAL_EXTI_ClearPending(const EXTI_HandleTypeDef *hexti, uint32_t Edge) -{ - __IO uint32_t *regaddr; - uint32_t maskline; - uint32_t offset; - - /* Check parameters */ - assert_param(IS_EXTI_LINE(hexti->Line)); - assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); - - /* Prevent unused argument(s) compilation warning */ - UNUSED(Edge); - - /* compute line register offset and line mask */ - offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); - - /* Get pending register address */ - regaddr = (__IO uint32_t *)(&EXTI->PR1 + (EXTI_MODE_OFFSET * offset)); - - /* Clear Pending bit */ - *regaddr = maskline; -} - - -/** - * @brief Generate a software interrupt for a dedicated line. - * @param hexti Exti handle. - * @retval None. - */ -void HAL_EXTI_GenerateSWI(const EXTI_HandleTypeDef *hexti) -{ - __IO uint32_t *regaddr; - uint32_t maskline; - uint32_t offset; - - /* Check parameters */ - assert_param(IS_EXTI_LINE(hexti->Line)); - assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); - - /* compute line register offset and line mask */ - offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); - maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); - - regaddr = (__IO uint32_t *)(&EXTI->SWIER1 + (EXTI_CONFIG_OFFSET * offset)); - *regaddr = maskline; -} - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_EXTI_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_exti.c + * @author MCD Application Team + * @brief EXTI HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the General Purpose Input/Output (EXTI) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### EXTI Peripheral features ##### + ============================================================================== + [..] + (+) Each Exti line can be configured within this driver. + + (+) Exti line can be configured in 3 different modes + (++) Interrupt + (++) Event + (++) Both of them + + (+) Configurable Exti lines can be configured with 3 different triggers + (++) Rising + (++) Falling + (++) Both of them + + (+) When set in interrupt mode, configurable Exti lines have two different + interrupts pending registers which allow to distinguish which transition + occurs: + (++) Rising edge pending interrupt + (++) Falling + + (+) Exti lines 0 to 15 are linked to gpio pin number 0 to 15. Gpio port can + be selected through multiplexer. + + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Configure the EXTI line using HAL_EXTI_SetConfigLine(). + (++) Choose the interrupt line number by setting "Line" member from + EXTI_ConfigTypeDef structure. + (++) Configure the interrupt and/or event mode using "Mode" member from + EXTI_ConfigTypeDef structure. + (++) For configurable lines, configure rising and/or falling trigger + "Trigger" member from EXTI_ConfigTypeDef structure. + (++) For Exti lines linked to gpio, choose gpio port using "GPIOSel" + member from GPIO_InitTypeDef structure. + + (#) Get current Exti configuration of a dedicated line using + HAL_EXTI_GetConfigLine(). + (++) Provide exiting handle as parameter. + (++) Provide pointer on EXTI_ConfigTypeDef structure as second parameter. + + (#) Clear Exti configuration of a dedicated line using HAL_EXTI_GetConfigLine(). + (++) Provide exiting handle as parameter. + + (#) Register callback to treat Exti interrupts using HAL_EXTI_RegisterCallback(). + (++) Provide exiting handle as first parameter. + (++) Provide which callback will be registered using one value from + EXTI_CallbackIDTypeDef. + (++) Provide callback function pointer. + + (#) Get interrupt pending bit using HAL_EXTI_GetPending(). + + (#) Clear interrupt pending bit using HAL_EXTI_GetPending(). + + (#) Generate software interrupt using HAL_EXTI_GenerateSWI(). + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @addtogroup EXTI + * @{ + */ + +#ifdef HAL_EXTI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines ------------------------------------------------------------*/ +/** @defgroup EXTI_Private_Constants EXTI Private Constants + * @{ + */ +#define EXTI_MODE_OFFSET 0x04u /* 0x10: Offset between MCU IMRx/EMRx registers */ +#define EXTI_CONFIG_OFFSET 0x08u /* 0x20: Offset between MCU Rising/Falling configuration registers */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup EXTI_Exported_Functions + * @{ + */ + +/** @addtogroup EXTI_Exported_Functions_Group1 + * @brief Configuration functions + * +@verbatim + =============================================================================== + ##### Configuration functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Set configuration of a dedicated Exti line. + * @param hexti Exti handle. + * @param pExtiConfig Pointer on EXTI configuration to be set. + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_EXTI_SetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) +{ + __IO uint32_t *regaddr; + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + uint32_t offset; + + /* Check null pointer */ + if ((hexti == NULL) || (pExtiConfig == NULL)) + { + return HAL_ERROR; + } + + /* Check parameters */ + assert_param(IS_EXTI_LINE(pExtiConfig->Line)); + assert_param(IS_EXTI_MODE(pExtiConfig->Mode)); + + /* Assign line number to handle */ + hexti->Line = pExtiConfig->Line; + + /* Compute line register offset and line mask */ + offset = ((pExtiConfig->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + linepos = (pExtiConfig->Line & EXTI_PIN_MASK); + maskline = (1uL << linepos); + + /* Configure triggers for configurable lines */ + if ((pExtiConfig->Line & EXTI_CONFIG) != 0x00u) + { + assert_param(IS_EXTI_TRIGGER(pExtiConfig->Trigger)); + + /* Configure rising trigger */ + regaddr = (__IO uint32_t *)(&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); + regval = *regaddr; + + /* Mask or set line */ + if ((pExtiConfig->Trigger & EXTI_TRIGGER_RISING) != 0x00u) + { + regval |= maskline; + } + else + { + regval &= ~maskline; + } + + /* Store rising trigger mode */ + *regaddr = regval; + + /* Configure falling trigger */ + regaddr = (__IO uint32_t *)(&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); + regval = *regaddr; + + /* Mask or set line */ + if ((pExtiConfig->Trigger & EXTI_TRIGGER_FALLING) != 0x00u) + { + regval |= maskline; + } + else + { + regval &= ~maskline; + } + + /* Store falling trigger mode */ + *regaddr = regval; + + /* Configure gpio port selection in case of gpio exti line */ + if ((pExtiConfig->Line & EXTI_GPIO) == EXTI_GPIO) + { + assert_param(IS_EXTI_GPIO_PORT(pExtiConfig->GPIOSel)); + assert_param(IS_EXTI_GPIO_PIN(linepos)); + + regval = SBS->EXTICR[linepos >> 2u]; + regval &= ~(SBS_EXTICR1_PC_EXTI0 << (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))); + regval |= (pExtiConfig->GPIOSel << (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))); + SBS->EXTICR[linepos >> 2u] = regval; + } + } + + /* Configure interrupt mode : read current mode */ + regaddr = (__IO uint32_t *)(&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); + regval = *regaddr; + + /* Mask or set line */ + if ((pExtiConfig->Mode & EXTI_MODE_INTERRUPT) != 0x00u) + { + regval |= maskline; + } + else + { + regval &= ~maskline; + } + + /* Store interrupt mode */ + *regaddr = regval; + + /* The event mode cannot be configured if the line does not support it */ + assert_param(((pExtiConfig->Line & EXTI_EVENT) == EXTI_EVENT) || ((pExtiConfig->Mode & EXTI_MODE_EVENT) != EXTI_MODE_EVENT)); + + /* Configure event mode : read current mode */ + regaddr = (__IO uint32_t *)(&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); + regval = *regaddr; + + /* Mask or set line */ + if ((pExtiConfig->Mode & EXTI_MODE_EVENT) != 0x00u) + { + regval |= maskline; + } + else + { + regval &= ~maskline; + } + + /* Store event mode */ + *regaddr = regval; + + return HAL_OK; +} + + +/** + * @brief Get configuration of a dedicated Exti line. + * @param hexti Exti handle. + * @param pExtiConfig Pointer on structure to store Exti configuration. + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_EXTI_GetConfigLine(EXTI_HandleTypeDef *hexti, EXTI_ConfigTypeDef *pExtiConfig) +{ + const __IO uint32_t *regaddr; + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + uint32_t offset; + + /* Check null pointer */ + if ((hexti == NULL) || (pExtiConfig == NULL)) + { + return HAL_ERROR; + } + + /* Check the parameter */ + assert_param(IS_EXTI_LINE(hexti->Line)); + + /* Store handle line number to configuration structure */ + pExtiConfig->Line = hexti->Line; + + /* Compute line register offset and line mask */ + offset = ((pExtiConfig->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + linepos = (pExtiConfig->Line & EXTI_PIN_MASK); + maskline = (1uL << linepos); + + /* 1] Get core mode : interrupt */ + regaddr = (__IO uint32_t *)(&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); + regval = *regaddr; + + /* Check if selected line is enable */ + if ((regval & maskline) != 0x00u) + { + pExtiConfig->Mode = EXTI_MODE_INTERRUPT; + } + else + { + pExtiConfig->Mode = EXTI_MODE_NONE; + } + + /* Get event mode */ + regaddr = (__IO uint32_t *)(&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); + regval = *regaddr; + + /* Check if selected line is enable */ + if ((regval & maskline) != 0x00u) + { + pExtiConfig->Mode |= EXTI_MODE_EVENT; + } + + /* 2] Get trigger for configurable lines : rising */ + if ((pExtiConfig->Line & EXTI_CONFIG) != 0x00u) + { + regaddr = (__IO uint32_t *)(&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); + regval = *regaddr; + + /* Check if configuration of selected line is enable */ + if ((regval & maskline) != 0x00u) + { + pExtiConfig->Trigger = EXTI_TRIGGER_RISING; + } + else + { + pExtiConfig->Trigger = EXTI_TRIGGER_NONE; + } + + /* Get falling configuration */ + regaddr = (__IO uint32_t *)(&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); + regval = *regaddr; + + /* Check if configuration of selected line is enable */ + if ((regval & maskline) != 0x00u) + { + pExtiConfig->Trigger |= EXTI_TRIGGER_FALLING; + } + + /* Get Gpio port selection for gpio lines */ + if ((pExtiConfig->Line & EXTI_GPIO) == EXTI_GPIO) + { + assert_param(IS_EXTI_GPIO_PIN(linepos)); + + regval = SBS->EXTICR[linepos >> 2u]; + pExtiConfig->GPIOSel = (regval >> (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))) & SBS_EXTICR1_PC_EXTI0; + } + else + { + pExtiConfig->GPIOSel = 0x00u; + } + } + else + { + pExtiConfig->Trigger = EXTI_TRIGGER_NONE; + pExtiConfig->GPIOSel = 0x00u; + } + + return HAL_OK; +} + + +/** + * @brief Clear whole configuration of a dedicated Exti line. + * @param hexti Exti handle. + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_EXTI_ClearConfigLine(const EXTI_HandleTypeDef *hexti) +{ + __IO uint32_t *regaddr; + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + uint32_t offset; + + /* Check null pointer */ + if (hexti == NULL) + { + return HAL_ERROR; + } + + /* Check the parameter */ + assert_param(IS_EXTI_LINE(hexti->Line)); + + /* compute line register offset and line mask */ + offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + linepos = (hexti->Line & EXTI_PIN_MASK); + maskline = (1uL << linepos); + + /* 1] Clear interrupt mode */ + regaddr = (__IO uint32_t *)(&EXTI->IMR1 + (EXTI_MODE_OFFSET * offset)); + regval = (*regaddr & ~maskline); + *regaddr = regval; + + /* 2] Clear event mode */ + regaddr = (__IO uint32_t *)(&EXTI->EMR1 + (EXTI_MODE_OFFSET * offset)); + regval = (*regaddr & ~maskline); + *regaddr = regval; + + /* 3] Clear triggers in case of configurable lines */ + if ((hexti->Line & EXTI_CONFIG) != 0x00u) + { + regaddr = (__IO uint32_t *)(&EXTI->RTSR1 + (EXTI_CONFIG_OFFSET * offset)); + regval = (*regaddr & ~maskline); + *regaddr = regval; + + regaddr = (__IO uint32_t *)(&EXTI->FTSR1 + (EXTI_CONFIG_OFFSET * offset)); + regval = (*regaddr & ~maskline); + *regaddr = regval; + + /* Get Gpio port selection for gpio lines */ + if ((hexti->Line & EXTI_GPIO) == EXTI_GPIO) + { + assert_param(IS_EXTI_GPIO_PIN(linepos)); + + regval = SBS->EXTICR[linepos >> 2u]; + regval &= ~(SBS_EXTICR1_PC_EXTI0 << (SBS_EXTICR1_PC_EXTI1_Pos * (linepos & 0x03u))); + SBS->EXTICR[linepos >> 2u] = regval; + } + } + + return HAL_OK; +} + + +/** + * @brief Register callback for a dedicated Exti line. + * @param hexti Exti handle. + * @param CallbackID User callback identifier. + * This parameter can be one of @arg @ref EXTI_CallbackIDTypeDef values. + * @param pPendingCbfn function pointer to be stored as callback. + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_EXTI_RegisterCallback(EXTI_HandleTypeDef *hexti, EXTI_CallbackIDTypeDef CallbackID, void (*pPendingCbfn)(void)) +{ + HAL_StatusTypeDef status = HAL_OK; + + switch (CallbackID) + { + case HAL_EXTI_COMMON_CB_ID: + hexti->PendingCallback = pPendingCbfn; + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} + + +/** + * @brief Store line number as handle private field. + * @param hexti Exti handle. + * @param ExtiLine Exti line number. + * This parameter can be from 0 to @ref EXTI_LINE_NB. + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_EXTI_GetHandle(EXTI_HandleTypeDef *hexti, uint32_t ExtiLine) +{ + /* Check the parameters */ + assert_param(IS_EXTI_LINE(ExtiLine)); + + /* Check null pointer */ + if (hexti == NULL) + { + return HAL_ERROR; + } + else + { + /* Store line number as handle private field */ + hexti->Line = ExtiLine; + + return HAL_OK; + } +} + + +/** + * @} + */ + +/** @addtogroup EXTI_Exported_Functions_Group2 + * @brief EXTI IO functions. + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Handle EXTI interrupt request. + * @param hexti Exti handle. + * @retval none. + */ +void HAL_EXTI_IRQHandler(const EXTI_HandleTypeDef *hexti) +{ + __IO uint32_t *regaddr; + uint32_t regval; + uint32_t maskline; + uint32_t offset; + + /* Compute line register offset and line mask */ + offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); + + /* Get pending bit */ + regaddr = (__IO uint32_t *)(&EXTI->PR1 + (EXTI_MODE_OFFSET * offset)); + regval = (*regaddr & maskline); + + if (regval != 0x00u) + { + /* Clear pending bit */ + *regaddr = maskline; + + /* Call callback */ + if (hexti->PendingCallback != NULL) + { + hexti->PendingCallback(); + } + } +} + + +/** + * @brief Get interrupt pending bit of a dedicated line. + * @param hexti Exti handle. + * @param Edge Specify which pending edge as to be checked. + * This parameter can be one of the following values: + * @arg @ref EXTI_TRIGGER_RISING_FALLING + * This parameter is kept for compatibility with other series. + * @retval 1 if interrupt is pending else 0. + */ +uint32_t HAL_EXTI_GetPending(const EXTI_HandleTypeDef *hexti, uint32_t Edge) +{ + const __IO uint32_t *regaddr; + uint32_t regval; + uint32_t linepos; + uint32_t maskline; + uint32_t offset; + + /* Check parameters */ + assert_param(IS_EXTI_LINE(hexti->Line)); + assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(Edge); + + /* Compute line register offset and line mask */ + offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + linepos = (hexti->Line & EXTI_PIN_MASK); + maskline = (1uL << linepos); + + /* Get pending bit */ + regaddr = (__IO uint32_t *)(&EXTI->PR1 + (EXTI_MODE_OFFSET * offset)); + + /* return 1 if bit is set else 0 */ + regval = ((*regaddr & maskline) >> linepos); + return regval; +} + + +/** + * @brief Clear interrupt pending bit of a dedicated line. + * @param hexti Exti handle. + * @param Edge Specify which pending edge as to be clear. + * This parameter can be one of the following values: + * @arg @ref EXTI_TRIGGER_RISING_FALLING + * This parameter is kept for compatibility with other series. + * @retval None. + */ +void HAL_EXTI_ClearPending(const EXTI_HandleTypeDef *hexti, uint32_t Edge) +{ + __IO uint32_t *regaddr; + uint32_t maskline; + uint32_t offset; + + /* Check parameters */ + assert_param(IS_EXTI_LINE(hexti->Line)); + assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(Edge); + + /* compute line register offset and line mask */ + offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); + + /* Get pending register address */ + regaddr = (__IO uint32_t *)(&EXTI->PR1 + (EXTI_MODE_OFFSET * offset)); + + /* Clear Pending bit */ + *regaddr = maskline; +} + + +/** + * @brief Generate a software interrupt for a dedicated line. + * @param hexti Exti handle. + * @retval None. + */ +void HAL_EXTI_GenerateSWI(const EXTI_HandleTypeDef *hexti) +{ + __IO uint32_t *regaddr; + uint32_t maskline; + uint32_t offset; + + /* Check parameters */ + assert_param(IS_EXTI_LINE(hexti->Line)); + assert_param(IS_EXTI_CONFIG_LINE(hexti->Line)); + + /* compute line register offset and line mask */ + offset = ((hexti->Line & EXTI_REG_MASK) >> EXTI_REG_SHIFT); + maskline = (1uL << (hexti->Line & EXTI_PIN_MASK)); + + regaddr = (__IO uint32_t *)(&EXTI->SWIER1 + (EXTI_CONFIG_OFFSET * offset)); + *regaddr = maskline; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_EXTI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_fdcan.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_fdcan.c index 800fed828..0e3ce4ed6 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_fdcan.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_fdcan.c @@ -1,3538 +1,3538 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_fdcan.c - * @author MCD Application Team - * @brief FDCAN HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Flexible DataRate Controller Area Network - * (FDCAN) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral Configuration and Control functions - * + Peripheral State and Error functions - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Initialize the FDCAN peripheral using HAL_FDCAN_Init function. - - (#) If needed , configure the reception filters and optional features using - the following configuration functions: - (++) HAL_FDCAN_ConfigFilter - (++) HAL_FDCAN_ConfigGlobalFilter - (++) HAL_FDCAN_ConfigExtendedIdMask - (++) HAL_FDCAN_ConfigRxFifoOverwrite - (++) HAL_FDCAN_ConfigRamWatchdog - (++) HAL_FDCAN_ConfigTimestampCounter - (++) HAL_FDCAN_EnableTimestampCounter - (++) HAL_FDCAN_DisableTimestampCounter - (++) HAL_FDCAN_ConfigTimeoutCounter - (++) HAL_FDCAN_EnableTimeoutCounter - (++) HAL_FDCAN_DisableTimeoutCounter - (++) HAL_FDCAN_ConfigTxDelayCompensation - (++) HAL_FDCAN_EnableTxDelayCompensation - (++) HAL_FDCAN_DisableTxDelayCompensation - (++) HAL_FDCAN_EnableISOMode - (++) HAL_FDCAN_DisableISOMode - (++) HAL_FDCAN_EnableEdgeFiltering - (++) HAL_FDCAN_DisableEdgeFiltering - - (#) Start the FDCAN module using HAL_FDCAN_Start function. At this level - the node is active on the bus: it can send and receive messages. - - (#) The following Tx control functions can only be called when the FDCAN - module is started: - (++) HAL_FDCAN_AddMessageToTxFifoQ - (++) HAL_FDCAN_AbortTxRequest - - (#) After having submitted a Tx request in Tx Fifo or Queue, it is possible to - get Tx buffer location used to place the Tx request thanks to - HAL_FDCAN_GetLatestTxFifoQRequestBuffer API. - It is then possible to abort later on the corresponding Tx Request using - HAL_FDCAN_AbortTxRequest API. - - (#) When a message is received into the FDCAN message RAM, it can be - retrieved using the HAL_FDCAN_GetRxMessage function. - - (#) Calling the HAL_FDCAN_Stop function stops the FDCAN module by entering - it to initialization mode and re-enabling access to configuration - registers through the configuration functions listed here above. - - (#) All other control functions can be called any time after initialization - phase, no matter if the FDCAN module is started or stopped. - - *** Polling mode operation *** - ============================== - [..] - (#) Reception and transmission states can be monitored via the following - functions: - (++) HAL_FDCAN_IsTxBufferMessagePending - (++) HAL_FDCAN_GetRxFifoFillLevel - (++) HAL_FDCAN_GetTxFifoFreeLevel - - *** Interrupt mode operation *** - ================================ - [..] - (#) There are two interrupt lines: line 0 and 1. - By default, all interrupts are assigned to line 0. Interrupt lines - can be configured using HAL_FDCAN_ConfigInterruptLines function. - - (#) Notifications are activated using HAL_FDCAN_ActivateNotification - function. Then, the process can be controlled through one of the - available user callbacks: HAL_FDCAN_xxxCallback. - - *** Callback registration *** - ============================================= - - The compilation define USE_HAL_FDCAN_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Function HAL_FDCAN_RegisterCallback() or HAL_FDCAN_RegisterXXXCallback() - to register an interrupt callback. - - Function HAL_FDCAN_RegisterCallback() allows to register following callbacks: - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) HighPriorityMessageCallback : High Priority Message Callback. - (+) TimestampWraparoundCallback : Timestamp Wraparound Callback. - (+) TimeoutOccurredCallback : Timeout Occurred Callback. - (+) ErrorCallback : Error Callback. - (+) MspInitCallback : FDCAN MspInit. - (+) MspDeInitCallback : FDCAN MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - For specific callbacks TxEventFifoCallback, RxFifo0Callback, RxFifo1Callback, - TxBufferCompleteCallback, TxBufferAbortCallback and ErrorStatusCallback use dedicated - register callbacks: respectively HAL_FDCAN_RegisterTxEventFifoCallback(), - HAL_FDCAN_RegisterRxFifo0Callback(), HAL_FDCAN_RegisterRxFifo1Callback(), - HAL_FDCAN_RegisterTxBufferCompleteCallback(), HAL_FDCAN_RegisterTxBufferAbortCallback() - and HAL_FDCAN_RegisterErrorStatusCallback(). - - Use function HAL_FDCAN_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_FDCAN_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) HighPriorityMessageCallback : High Priority Message Callback. - (+) TimestampWraparoundCallback : Timestamp Wraparound Callback. - (+) TimeoutOccurredCallback : Timeout Occurred Callback. - (+) ErrorCallback : Error Callback. - (+) MspInitCallback : FDCAN MspInit. - (+) MspDeInitCallback : FDCAN MspDeInit. - - For specific callbacks TxEventFifoCallback, RxFifo0Callback, RxFifo1Callback, - TxBufferCompleteCallback and TxBufferAbortCallback, use dedicated - unregister callbacks: respectively HAL_FDCAN_UnRegisterTxEventFifoCallback(), - HAL_FDCAN_UnRegisterRxFifo0Callback(), HAL_FDCAN_UnRegisterRxFifo1Callback(), - HAL_FDCAN_UnRegisterTxBufferCompleteCallback(), HAL_FDCAN_UnRegisterTxBufferAbortCallback() - and HAL_FDCAN_UnRegisterErrorStatusCallback(). - - By default, after the HAL_FDCAN_Init() and when the state is HAL_FDCAN_STATE_RESET, - all callbacks are set to the corresponding weak functions: - examples HAL_FDCAN_ErrorCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak function in the HAL_FDCAN_Init()/ HAL_FDCAN_DeInit() only when - these callbacks are null (not registered beforehand). - if not, MspInit or MspDeInit are not null, the HAL_FDCAN_Init()/ HAL_FDCAN_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in HAL_FDCAN_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_FDCAN_STATE_READY or HAL_FDCAN_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_FDCAN_RegisterCallback() before calling HAL_FDCAN_DeInit() - or HAL_FDCAN_Init() function. - - When The compilation define USE_HAL_FDCAN_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -#if defined(FDCAN1) - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup FDCAN FDCAN - * @brief FDCAN HAL module driver - * @{ - */ - -#ifdef HAL_FDCAN_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup FDCAN_Private_Constants - * @{ - */ -#define FDCAN_TIMEOUT_VALUE 10U - -#define FDCAN_TX_EVENT_FIFO_MASK (FDCAN_IR_TEFL | FDCAN_IR_TEFF | FDCAN_IR_TEFN) -#define FDCAN_RX_FIFO0_MASK (FDCAN_IR_RF0L | FDCAN_IR_RF0F | FDCAN_IR_RF0N) -#define FDCAN_RX_FIFO1_MASK (FDCAN_IR_RF1L | FDCAN_IR_RF1F | FDCAN_IR_RF1N) -#define FDCAN_ERROR_MASK (FDCAN_IR_ELO | FDCAN_IR_WDI | FDCAN_IR_PEA | FDCAN_IR_PED | FDCAN_IR_ARA) -#define FDCAN_ERROR_STATUS_MASK (FDCAN_IR_EP | FDCAN_IR_EW | FDCAN_IR_BO) - -#define FDCAN_ELEMENT_MASK_STDID ((uint32_t)0x1FFC0000U) /* Standard Identifier */ -#define FDCAN_ELEMENT_MASK_EXTID ((uint32_t)0x1FFFFFFFU) /* Extended Identifier */ -#define FDCAN_ELEMENT_MASK_RTR ((uint32_t)0x20000000U) /* Remote Transmission Request */ -#define FDCAN_ELEMENT_MASK_XTD ((uint32_t)0x40000000U) /* Extended Identifier */ -#define FDCAN_ELEMENT_MASK_ESI ((uint32_t)0x80000000U) /* Error State Indicator */ -#define FDCAN_ELEMENT_MASK_TS ((uint32_t)0x0000FFFFU) /* Timestamp */ -#define FDCAN_ELEMENT_MASK_DLC ((uint32_t)0x000F0000U) /* Data Length Code */ -#define FDCAN_ELEMENT_MASK_BRS ((uint32_t)0x00100000U) /* Bit Rate Switch */ -#define FDCAN_ELEMENT_MASK_FDF ((uint32_t)0x00200000U) /* FD Format */ -#define FDCAN_ELEMENT_MASK_EFC ((uint32_t)0x00800000U) /* Event FIFO Control */ -#define FDCAN_ELEMENT_MASK_MM ((uint32_t)0xFF000000U) /* Message Marker */ -#define FDCAN_ELEMENT_MASK_FIDX ((uint32_t)0x7F000000U) /* Filter Index */ -#define FDCAN_ELEMENT_MASK_ANMF ((uint32_t)0x80000000U) /* Accepted Non-matching Frame */ -#define FDCAN_ELEMENT_MASK_ET ((uint32_t)0x00C00000U) /* Event type */ - -#define SRAMCAN_FLS_NBR (28U) /* Max. Filter List Standard Number */ -#define SRAMCAN_FLE_NBR ( 8U) /* Max. Filter List Extended Number */ -#define SRAMCAN_RF0_NBR ( 3U) /* RX FIFO 0 Elements Number */ -#define SRAMCAN_RF1_NBR ( 3U) /* RX FIFO 1 Elements Number */ -#define SRAMCAN_TEF_NBR ( 3U) /* TX Event FIFO Elements Number */ -#define SRAMCAN_TFQ_NBR ( 3U) /* TX FIFO/Queue Elements Number */ - -#define SRAMCAN_FLS_SIZE ( 1U * 4U) /* Filter Standard Element Size in bytes */ -#define SRAMCAN_FLE_SIZE ( 2U * 4U) /* Filter Extended Element Size in bytes */ -#define SRAMCAN_RF0_SIZE (18U * 4U) /* RX FIFO 0 Elements Size in bytes */ -#define SRAMCAN_RF1_SIZE (18U * 4U) /* RX FIFO 1 Elements Size in bytes */ -#define SRAMCAN_TEF_SIZE ( 2U * 4U) /* TX Event FIFO Elements Size in bytes */ -#define SRAMCAN_TFQ_SIZE (18U * 4U) /* TX FIFO/Queue Elements Size in bytes */ - -#define SRAMCAN_FLSSA ((uint32_t)0) /* Filter List Standard Start - Address */ -#define SRAMCAN_FLESA ((uint32_t)(SRAMCAN_FLSSA + (SRAMCAN_FLS_NBR * SRAMCAN_FLS_SIZE))) /* Filter List Extended Start - Address */ -#define SRAMCAN_RF0SA ((uint32_t)(SRAMCAN_FLESA + (SRAMCAN_FLE_NBR * SRAMCAN_FLE_SIZE))) /* Rx FIFO 0 Start Address */ -#define SRAMCAN_RF1SA ((uint32_t)(SRAMCAN_RF0SA + (SRAMCAN_RF0_NBR * SRAMCAN_RF0_SIZE))) /* Rx FIFO 1 Start Address */ -#define SRAMCAN_TEFSA ((uint32_t)(SRAMCAN_RF1SA + (SRAMCAN_RF1_NBR * SRAMCAN_RF1_SIZE))) /* Tx Event FIFO Start - Address */ -#define SRAMCAN_TFQSA ((uint32_t)(SRAMCAN_TEFSA + (SRAMCAN_TEF_NBR * SRAMCAN_TEF_SIZE))) /* Tx FIFO/Queue Start - Address */ -#define SRAMCAN_SIZE ((uint32_t)(SRAMCAN_TFQSA + (SRAMCAN_TFQ_NBR * SRAMCAN_TFQ_SIZE))) /* Message RAM size */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @addtogroup FDCAN_Private_Variables - * @{ - */ -static const uint8_t DLCtoBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}; -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup FDCAN_Private_Functions_Prototypes - * @{ - */ -static void FDCAN_CalcultateRamBlockAddresses(FDCAN_HandleTypeDef *hfdcan); -static void FDCAN_CopyMessageToRAM(const FDCAN_HandleTypeDef *hfdcan, const FDCAN_TxHeaderTypeDef *pTxHeader, - const uint8_t *pTxData, uint32_t BufferIndex); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup FDCAN_Exported_Functions FDCAN Exported Functions - * @{ - */ - -/** @defgroup FDCAN_Exported_Functions_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 FDCAN. - (+) De-initialize the FDCAN. - (+) Enter FDCAN peripheral in power down mode. - (+) Exit power down mode. - (+) Register callbacks. - (+) Unregister callbacks. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the FDCAN peripheral according to the specified - * parameters in the FDCAN_InitTypeDef structure. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_Init(FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t tickstart; - - /* Check FDCAN handle */ - if (hfdcan == NULL) - { - return HAL_ERROR; - } - - /* Check function parameters */ - assert_param(IS_FDCAN_ALL_INSTANCE(hfdcan->Instance)); - if (hfdcan->Instance == FDCAN1) - { - assert_param(IS_FDCAN_CKDIV(hfdcan->Init.ClockDivider)); - } - assert_param(IS_FDCAN_FRAME_FORMAT(hfdcan->Init.FrameFormat)); - assert_param(IS_FDCAN_MODE(hfdcan->Init.Mode)); - assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.AutoRetransmission)); - assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.TransmitPause)); - assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.ProtocolException)); - assert_param(IS_FDCAN_NOMINAL_PRESCALER(hfdcan->Init.NominalPrescaler)); - assert_param(IS_FDCAN_NOMINAL_SJW(hfdcan->Init.NominalSyncJumpWidth)); - assert_param(IS_FDCAN_NOMINAL_TSEG1(hfdcan->Init.NominalTimeSeg1)); - assert_param(IS_FDCAN_NOMINAL_TSEG2(hfdcan->Init.NominalTimeSeg2)); - if (hfdcan->Init.FrameFormat == FDCAN_FRAME_FD_BRS) - { - assert_param(IS_FDCAN_DATA_PRESCALER(hfdcan->Init.DataPrescaler)); - assert_param(IS_FDCAN_DATA_SJW(hfdcan->Init.DataSyncJumpWidth)); - assert_param(IS_FDCAN_DATA_TSEG1(hfdcan->Init.DataTimeSeg1)); - assert_param(IS_FDCAN_DATA_TSEG2(hfdcan->Init.DataTimeSeg2)); - } - assert_param(IS_FDCAN_MAX_VALUE(hfdcan->Init.StdFiltersNbr, SRAMCAN_FLS_NBR)); - assert_param(IS_FDCAN_MAX_VALUE(hfdcan->Init.ExtFiltersNbr, SRAMCAN_FLE_NBR)); - assert_param(IS_FDCAN_TX_FIFO_QUEUE_MODE(hfdcan->Init.TxFifoQueueMode)); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - if (hfdcan->State == HAL_FDCAN_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hfdcan->Lock = HAL_UNLOCKED; - - /* Reset callbacks to legacy functions */ - hfdcan->TxEventFifoCallback = HAL_FDCAN_TxEventFifoCallback; /* TxEventFifoCallback */ - hfdcan->RxFifo0Callback = HAL_FDCAN_RxFifo0Callback; /* RxFifo0Callback */ - hfdcan->RxFifo1Callback = HAL_FDCAN_RxFifo1Callback; /* RxFifo1Callback */ - hfdcan->TxFifoEmptyCallback = HAL_FDCAN_TxFifoEmptyCallback; /* TxFifoEmptyCallback */ - hfdcan->TxBufferCompleteCallback = HAL_FDCAN_TxBufferCompleteCallback; /* TxBufferCompleteCallback */ - hfdcan->TxBufferAbortCallback = HAL_FDCAN_TxBufferAbortCallback; /* TxBufferAbortCallback */ - hfdcan->HighPriorityMessageCallback = HAL_FDCAN_HighPriorityMessageCallback; /* HighPriorityMessageCallback */ - hfdcan->TimestampWraparoundCallback = HAL_FDCAN_TimestampWraparoundCallback; /* TimestampWraparoundCallback */ - hfdcan->TimeoutOccurredCallback = HAL_FDCAN_TimeoutOccurredCallback; /* TimeoutOccurredCallback */ - hfdcan->ErrorCallback = HAL_FDCAN_ErrorCallback; /* ErrorCallback */ - hfdcan->ErrorStatusCallback = HAL_FDCAN_ErrorStatusCallback; /* ErrorStatusCallback */ - - if (hfdcan->MspInitCallback == NULL) - { - hfdcan->MspInitCallback = HAL_FDCAN_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware: CLOCK, NVIC */ - hfdcan->MspInitCallback(hfdcan); - } -#else - if (hfdcan->State == HAL_FDCAN_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hfdcan->Lock = HAL_UNLOCKED; - - /* Init the low level hardware: CLOCK, NVIC */ - HAL_FDCAN_MspInit(hfdcan); - } -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - - /* Exit from Sleep mode */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Check Sleep mode acknowledge */ - while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA) - { - if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_ERROR; - - return HAL_ERROR; - } - } - - /* Request initialisation */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until the INIT bit into CCCR register is set */ - while ((hfdcan->Instance->CCCR & FDCAN_CCCR_INIT) == 0U) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_ERROR; - - return HAL_ERROR; - } - } - - /* Enable configuration change */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CCE); - - /* Check FDCAN instance */ - if (hfdcan->Instance == FDCAN1) - { - /* Configure Clock divider */ - FDCAN_CONFIG->CKDIV = hfdcan->Init.ClockDivider; - } - - /* Set the no automatic retransmission */ - if (hfdcan->Init.AutoRetransmission == ENABLE) - { - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_DAR); - } - else - { - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_DAR); - } - - /* Set the transmit pause feature */ - if (hfdcan->Init.TransmitPause == ENABLE) - { - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TXP); - } - else - { - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TXP); - } - - /* Set the Protocol Exception Handling */ - if (hfdcan->Init.ProtocolException == ENABLE) - { - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_PXHD); - } - else - { - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_PXHD); - } - - /* Set FDCAN Frame Format */ - MODIFY_REG(hfdcan->Instance->CCCR, FDCAN_FRAME_FD_BRS, hfdcan->Init.FrameFormat); - - /* Reset FDCAN Operation Mode */ - CLEAR_BIT(hfdcan->Instance->CCCR, (FDCAN_CCCR_TEST | FDCAN_CCCR_MON | FDCAN_CCCR_ASM)); - CLEAR_BIT(hfdcan->Instance->TEST, FDCAN_TEST_LBCK); - - /* Set FDCAN Operating Mode: - | Normal | Restricted | Bus | Internal | External - | | Operation | Monitoring | LoopBack | LoopBack - CCCR.TEST | 0 | 0 | 0 | 1 | 1 - CCCR.MON | 0 | 0 | 1 | 1 | 0 - TEST.LBCK | 0 | 0 | 0 | 1 | 1 - CCCR.ASM | 0 | 1 | 0 | 0 | 0 - */ - if (hfdcan->Init.Mode == FDCAN_MODE_RESTRICTED_OPERATION) - { - /* Enable Restricted Operation mode */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_ASM); - } - else if (hfdcan->Init.Mode != FDCAN_MODE_NORMAL) - { - if (hfdcan->Init.Mode != FDCAN_MODE_BUS_MONITORING) - { - /* Enable write access to TEST register */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TEST); - - /* Enable LoopBack mode */ - SET_BIT(hfdcan->Instance->TEST, FDCAN_TEST_LBCK); - - if (hfdcan->Init.Mode == FDCAN_MODE_INTERNAL_LOOPBACK) - { - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_MON); - } - } - else - { - /* Enable bus monitoring mode */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_MON); - } - } - else - { - /* Nothing to do: normal mode */ - } - - /* Set the nominal bit timing register */ - hfdcan->Instance->NBTP = ((((uint32_t)hfdcan->Init.NominalSyncJumpWidth - 1U) << FDCAN_NBTP_NSJW_Pos) | \ - (((uint32_t)hfdcan->Init.NominalTimeSeg1 - 1U) << FDCAN_NBTP_NTSEG1_Pos) | \ - (((uint32_t)hfdcan->Init.NominalTimeSeg2 - 1U) << FDCAN_NBTP_NTSEG2_Pos) | \ - (((uint32_t)hfdcan->Init.NominalPrescaler - 1U) << FDCAN_NBTP_NBRP_Pos)); - - /* If FD operation with BRS is selected, set the data bit timing register */ - if (hfdcan->Init.FrameFormat == FDCAN_FRAME_FD_BRS) - { - hfdcan->Instance->DBTP = ((((uint32_t)hfdcan->Init.DataSyncJumpWidth - 1U) << FDCAN_DBTP_DSJW_Pos) | \ - (((uint32_t)hfdcan->Init.DataTimeSeg1 - 1U) << FDCAN_DBTP_DTSEG1_Pos) | \ - (((uint32_t)hfdcan->Init.DataTimeSeg2 - 1U) << FDCAN_DBTP_DTSEG2_Pos) | \ - (((uint32_t)hfdcan->Init.DataPrescaler - 1U) << FDCAN_DBTP_DBRP_Pos)); - } - - /* Select between Tx FIFO and Tx Queue operation modes */ - SET_BIT(hfdcan->Instance->TXBC, hfdcan->Init.TxFifoQueueMode); - - /* Calculate each RAM block address */ - FDCAN_CalcultateRamBlockAddresses(hfdcan); - - /* Initialize the Latest Tx request buffer index */ - hfdcan->LatestTxFifoQRequest = 0U; - - /* Initialize the error code */ - hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE; - - /* Initialize the FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Deinitializes the FDCAN peripheral registers to their default reset values. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DeInit(FDCAN_HandleTypeDef *hfdcan) -{ - /* Check FDCAN handle */ - if (hfdcan == NULL) - { - return HAL_ERROR; - } - - /* Check function parameters */ - assert_param(IS_FDCAN_ALL_INSTANCE(hfdcan->Instance)); - - /* Stop the FDCAN module: return value is voluntary ignored */ - (void)HAL_FDCAN_Stop(hfdcan); - - /* Disable Interrupt lines */ - CLEAR_BIT(hfdcan->Instance->ILE, (FDCAN_INTERRUPT_LINE0 | FDCAN_INTERRUPT_LINE1)); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - if (hfdcan->MspDeInitCallback == NULL) - { - hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: CLOCK, NVIC */ - hfdcan->MspDeInitCallback(hfdcan); -#else - /* DeInit the low level hardware: CLOCK, NVIC */ - HAL_FDCAN_MspDeInit(hfdcan); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - - /* Reset the FDCAN ErrorCode */ - hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_RESET; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Initializes the FDCAN MSP. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_MspInit(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitializes the FDCAN MSP. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_MspDeInit(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_MspDeInit could be implemented in the user file - */ -} - -/** - * @brief Enter FDCAN peripheral in sleep mode. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_EnterPowerDownMode(FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t tickstart; - - /* Request clock stop */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until FDCAN is ready for power down */ - while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == 0U) - { - if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_ERROR; - - return HAL_ERROR; - } - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Exit power down mode. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ExitPowerDownMode(FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t tickstart; - - /* Reset clock stop request */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until FDCAN exits sleep mode */ - while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA) - { - if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_ERROR; - - return HAL_ERROR; - } - } - - /* Enter normal operation */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); - - /* Return function status */ - return HAL_OK; -} - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 -/** - * @brief Register a FDCAN CallBack. - * To be used instead of the weak predefined callback - * @param hfdcan pointer to a FDCAN_HandleTypeDef structure that contains - * the configuration information for FDCAN module - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_FDCAN_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty callback ID - * @arg @ref HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID High priority message callback ID - * @arg @ref HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID Timestamp wraparound callback ID - * @arg @ref HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID Timeout occurred callback ID - * @arg @ref HAL_FDCAN_ERROR_CALLBACK_CB_ID Error callback ID - * @arg @ref HAL_FDCAN_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_FDCAN_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID, - void (* pCallback)(FDCAN_HandleTypeDef *_hFDCAN)) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - switch (CallbackID) - { - case HAL_FDCAN_TX_FIFO_EMPTY_CB_ID : - hfdcan->TxFifoEmptyCallback = pCallback; - break; - - case HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID : - hfdcan->HighPriorityMessageCallback = pCallback; - break; - - case HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID : - hfdcan->TimestampWraparoundCallback = pCallback; - break; - - case HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID : - hfdcan->TimeoutOccurredCallback = pCallback; - break; - - case HAL_FDCAN_ERROR_CALLBACK_CB_ID : - hfdcan->ErrorCallback = pCallback; - break; - - case HAL_FDCAN_MSPINIT_CB_ID : - hfdcan->MspInitCallback = pCallback; - break; - - case HAL_FDCAN_MSPDEINIT_CB_ID : - hfdcan->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hfdcan->State == HAL_FDCAN_STATE_RESET) - { - switch (CallbackID) - { - case HAL_FDCAN_MSPINIT_CB_ID : - hfdcan->MspInitCallback = pCallback; - break; - - case HAL_FDCAN_MSPDEINIT_CB_ID : - hfdcan->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a FDCAN CallBack. - * FDCAN callback is redirected to the weak predefined callback - * @param hfdcan pointer to a FDCAN_HandleTypeDef structure that contains - * the configuration information for FDCAN module - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_FDCAN_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty callback ID - * @arg @ref HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID High priority message callback ID - * @arg @ref HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID Timestamp wraparound callback ID - * @arg @ref HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID Timeout occurred callback ID - * @arg @ref HAL_FDCAN_ERROR_CALLBACK_CB_ID Error callback ID - * @arg @ref HAL_FDCAN_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_FDCAN_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - switch (CallbackID) - { - case HAL_FDCAN_TX_FIFO_EMPTY_CB_ID : - hfdcan->TxFifoEmptyCallback = HAL_FDCAN_TxFifoEmptyCallback; - break; - - case HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID : - hfdcan->HighPriorityMessageCallback = HAL_FDCAN_HighPriorityMessageCallback; - break; - - case HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID : - hfdcan->TimestampWraparoundCallback = HAL_FDCAN_TimestampWraparoundCallback; - break; - - case HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID : - hfdcan->TimeoutOccurredCallback = HAL_FDCAN_TimeoutOccurredCallback; - break; - - case HAL_FDCAN_ERROR_CALLBACK_CB_ID : - hfdcan->ErrorCallback = HAL_FDCAN_ErrorCallback; - break; - - case HAL_FDCAN_MSPINIT_CB_ID : - hfdcan->MspInitCallback = HAL_FDCAN_MspInit; - break; - - case HAL_FDCAN_MSPDEINIT_CB_ID : - hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; - break; - - default : - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hfdcan->State == HAL_FDCAN_STATE_RESET) - { - switch (CallbackID) - { - case HAL_FDCAN_MSPINIT_CB_ID : - hfdcan->MspInitCallback = HAL_FDCAN_MspInit; - break; - - case HAL_FDCAN_MSPDEINIT_CB_ID : - hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; - break; - - default : - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register Tx Event Fifo FDCAN Callback - * To be used instead of the weak HAL_FDCAN_TxEventFifoCallback() predefined callback - * @param hfdcan FDCAN handle - * @param pCallback pointer to the Tx Event Fifo Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, - pFDCAN_TxEventFifoCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->TxEventFifoCallback = pCallback; - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Tx Event Fifo FDCAN Callback - * Tx Event Fifo FDCAN Callback is redirected to the weak HAL_FDCAN_TxEventFifoCallback() predefined callback - * @param hfdcan FDCAN handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->TxEventFifoCallback = HAL_FDCAN_TxEventFifoCallback; /* Legacy weak TxEventFifoCallback */ - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register Rx Fifo 0 FDCAN Callback - * To be used instead of the weak HAL_FDCAN_RxFifo0Callback() predefined callback - * @param hfdcan FDCAN handle - * @param pCallback pointer to the Rx Fifo 0 Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, - pFDCAN_RxFifo0CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->RxFifo0Callback = pCallback; - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Rx Fifo 0 FDCAN Callback - * Rx Fifo 0 FDCAN Callback is redirected to the weak HAL_FDCAN_RxFifo0Callback() predefined callback - * @param hfdcan FDCAN handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->RxFifo0Callback = HAL_FDCAN_RxFifo0Callback; /* Legacy weak RxFifo0Callback */ - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register Rx Fifo 1 FDCAN Callback - * To be used instead of the weak HAL_FDCAN_RxFifo1Callback() predefined callback - * @param hfdcan FDCAN handle - * @param pCallback pointer to the Rx Fifo 1 Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, - pFDCAN_RxFifo1CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->RxFifo1Callback = pCallback; - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Rx Fifo 1 FDCAN Callback - * Rx Fifo 1 FDCAN Callback is redirected to the weak HAL_FDCAN_RxFifo1Callback() predefined callback - * @param hfdcan FDCAN handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->RxFifo1Callback = HAL_FDCAN_RxFifo1Callback; /* Legacy weak RxFifo1Callback */ - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register Tx Buffer Complete FDCAN Callback - * To be used instead of the weak HAL_FDCAN_TxBufferCompleteCallback() predefined callback - * @param hfdcan FDCAN handle - * @param pCallback pointer to the Tx Buffer Complete Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, - pFDCAN_TxBufferCompleteCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->TxBufferCompleteCallback = pCallback; - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Tx Buffer Complete FDCAN Callback - * Tx Buffer Complete FDCAN Callback is redirected to - * the weak HAL_FDCAN_TxBufferCompleteCallback() predefined callback - * @param hfdcan FDCAN handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->TxBufferCompleteCallback = HAL_FDCAN_TxBufferCompleteCallback; /* Legacy weak TxBufferCompleteCallback */ - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register Tx Buffer Abort FDCAN Callback - * To be used instead of the weak HAL_FDCAN_TxBufferAbortCallback() predefined callback - * @param hfdcan FDCAN handle - * @param pCallback pointer to the Tx Buffer Abort Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, - pFDCAN_TxBufferAbortCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->TxBufferAbortCallback = pCallback; - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Tx Buffer Abort FDCAN Callback - * Tx Buffer Abort FDCAN Callback is redirected to - * the weak HAL_FDCAN_TxBufferAbortCallback() predefined callback - * @param hfdcan FDCAN handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->TxBufferAbortCallback = HAL_FDCAN_TxBufferAbortCallback; /* Legacy weak TxBufferAbortCallback */ - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register Error Status FDCAN Callback - * To be used instead of the weak HAL_FDCAN_ErrorStatusCallback() predefined callback - * @param hfdcan FDCAN handle - * @param pCallback pointer to the Error Status Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_RegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, - pFDCAN_ErrorStatusCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->ErrorStatusCallback = pCallback; - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Error Status FDCAN Callback - * Error Status FDCAN Callback is redirected to the weak HAL_FDCAN_ErrorStatusCallback() predefined callback - * @param hfdcan FDCAN handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_UnRegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - hfdcan->ErrorStatusCallback = HAL_FDCAN_ErrorStatusCallback; /* Legacy weak ErrorStatusCallback */ - } - else - { - /* Update the error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup FDCAN_Exported_Functions_Group2 Configuration functions - * @brief FDCAN Configuration functions. - * -@verbatim - ============================================================================== - ##### Configuration functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) HAL_FDCAN_ConfigFilter : Configure the FDCAN reception filters - (+) HAL_FDCAN_ConfigGlobalFilter : Configure the FDCAN global filter - (+) HAL_FDCAN_ConfigExtendedIdMask : Configure the extended ID mask - (+) HAL_FDCAN_ConfigRxFifoOverwrite : Configure the Rx FIFO operation mode - (+) HAL_FDCAN_ConfigRamWatchdog : Configure the RAM watchdog - (+) HAL_FDCAN_ConfigTimestampCounter : Configure the timestamp counter - (+) HAL_FDCAN_EnableTimestampCounter : Enable the timestamp counter - (+) HAL_FDCAN_DisableTimestampCounter : Disable the timestamp counter - (+) HAL_FDCAN_GetTimestampCounter : Get the timestamp counter value - (+) HAL_FDCAN_ResetTimestampCounter : Reset the timestamp counter to zero - (+) HAL_FDCAN_ConfigTimeoutCounter : Configure the timeout counter - (+) HAL_FDCAN_EnableTimeoutCounter : Enable the timeout counter - (+) HAL_FDCAN_DisableTimeoutCounter : Disable the timeout counter - (+) HAL_FDCAN_GetTimeoutCounter : Get the timeout counter value - (+) HAL_FDCAN_ResetTimeoutCounter : Reset the timeout counter to its start value - (+) HAL_FDCAN_ConfigTxDelayCompensation : Configure the transmitter delay compensation - (+) HAL_FDCAN_EnableTxDelayCompensation : Enable the transmitter delay compensation - (+) HAL_FDCAN_DisableTxDelayCompensation : Disable the transmitter delay compensation - (+) HAL_FDCAN_EnableISOMode : Enable ISO 11898-1 protocol mode - (+) HAL_FDCAN_DisableISOMode : Disable ISO 11898-1 protocol mode - (+) HAL_FDCAN_EnableEdgeFiltering : Enable edge filtering during bus integration - (+) HAL_FDCAN_DisableEdgeFiltering : Disable edge filtering during bus integration - -@endverbatim - * @{ - */ - -/** - * @brief Configure the FDCAN reception filter according to the specified - * parameters in the FDCAN_FilterTypeDef structure. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param sFilterConfig pointer to an FDCAN_FilterTypeDef structure that - * contains the filter configuration information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigFilter(FDCAN_HandleTypeDef *hfdcan, const FDCAN_FilterTypeDef *sFilterConfig) -{ - uint32_t FilterElementW1; - uint32_t FilterElementW2; - uint32_t *FilterAddress; - HAL_FDCAN_StateTypeDef state = hfdcan->State; - - if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) - { - /* Check function parameters */ - assert_param(IS_FDCAN_ID_TYPE(sFilterConfig->IdType)); - assert_param(IS_FDCAN_FILTER_CFG(sFilterConfig->FilterConfig)); - - if (sFilterConfig->IdType == FDCAN_STANDARD_ID) - { - /* Check function parameters */ - assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterIndex, (hfdcan->Init.StdFiltersNbr - 1U))); - assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID1, 0x7FFU)); - assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID2, 0x7FFU)); - assert_param(IS_FDCAN_STD_FILTER_TYPE(sFilterConfig->FilterType)); - - /* Build filter element */ - FilterElementW1 = ((sFilterConfig->FilterType << 30U) | - (sFilterConfig->FilterConfig << 27U) | - (sFilterConfig->FilterID1 << 16U) | - sFilterConfig->FilterID2); - - /* Calculate filter address */ - FilterAddress = (uint32_t *)(hfdcan->msgRam.StandardFilterSA + (sFilterConfig->FilterIndex * SRAMCAN_FLS_SIZE)); - - /* Write filter element to the message RAM */ - *FilterAddress = FilterElementW1; - } - else /* sFilterConfig->IdType == FDCAN_EXTENDED_ID */ - { - /* Check function parameters */ - assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterIndex, (hfdcan->Init.ExtFiltersNbr - 1U))); - assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID1, 0x1FFFFFFFU)); - assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID2, 0x1FFFFFFFU)); - assert_param(IS_FDCAN_EXT_FILTER_TYPE(sFilterConfig->FilterType)); - - /* Build first word of filter element */ - FilterElementW1 = ((sFilterConfig->FilterConfig << 29U) | sFilterConfig->FilterID1); - - /* Build second word of filter element */ - FilterElementW2 = ((sFilterConfig->FilterType << 30U) | sFilterConfig->FilterID2); - - /* Calculate filter address */ - FilterAddress = (uint32_t *)(hfdcan->msgRam.ExtendedFilterSA + (sFilterConfig->FilterIndex * SRAMCAN_FLE_SIZE)); - - /* Write filter element to the message RAM */ - *FilterAddress = FilterElementW1; - FilterAddress++; - *FilterAddress = FilterElementW2; - } - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; - - return HAL_ERROR; - } -} - -/** - * @brief Configure the FDCAN global filter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param NonMatchingStd Defines how received messages with 11-bit IDs that - * do not match any element of the filter list are treated. - * This parameter can be a value of @arg FDCAN_Non_Matching_Frames. - * @param NonMatchingExt Defines how received messages with 29-bit IDs that - * do not match any element of the filter list are treated. - * This parameter can be a value of @arg FDCAN_Non_Matching_Frames. - * @param RejectRemoteStd Filter or reject all the remote 11-bit IDs frames. - * This parameter can be a value of @arg FDCAN_Reject_Remote_Frames. - * @param RejectRemoteExt Filter or reject all the remote 29-bit IDs frames. - * This parameter can be a value of @arg FDCAN_Reject_Remote_Frames. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigGlobalFilter(FDCAN_HandleTypeDef *hfdcan, - uint32_t NonMatchingStd, - uint32_t NonMatchingExt, - uint32_t RejectRemoteStd, - uint32_t RejectRemoteExt) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_NON_MATCHING(NonMatchingStd)); - assert_param(IS_FDCAN_NON_MATCHING(NonMatchingExt)); - assert_param(IS_FDCAN_REJECT_REMOTE(RejectRemoteStd)); - assert_param(IS_FDCAN_REJECT_REMOTE(RejectRemoteExt)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Configure global filter */ - MODIFY_REG(hfdcan->Instance->RXGFC, (FDCAN_RXGFC_ANFS | - FDCAN_RXGFC_ANFE | - FDCAN_RXGFC_RRFS | - FDCAN_RXGFC_RRFE), - ((NonMatchingStd << FDCAN_RXGFC_ANFS_Pos) | - (NonMatchingExt << FDCAN_RXGFC_ANFE_Pos) | - (RejectRemoteStd << FDCAN_RXGFC_RRFS_Pos) | - (RejectRemoteExt << FDCAN_RXGFC_RRFE_Pos))); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Configure the extended ID mask. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param Mask Extended ID Mask. - * This parameter must be a number between 0 and 0x1FFFFFFF. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigExtendedIdMask(FDCAN_HandleTypeDef *hfdcan, uint32_t Mask) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_MAX_VALUE(Mask, 0x1FFFFFFFU)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Configure the extended ID mask */ - hfdcan->Instance->XIDAM = Mask; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Configure the Rx FIFO operation mode. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param RxFifo Rx FIFO. - * This parameter can be one of the following values: - * @arg FDCAN_RX_FIFO0: Rx FIFO 0 - * @arg FDCAN_RX_FIFO1: Rx FIFO 1 - * @param OperationMode operation mode. - * This parameter can be a value of @arg FDCAN_Rx_FIFO_operation_mode. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigRxFifoOverwrite(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo, uint32_t OperationMode) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_RX_FIFO(RxFifo)); - assert_param(IS_FDCAN_RX_FIFO_MODE(OperationMode)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - if (RxFifo == FDCAN_RX_FIFO0) - { - /* Select FIFO 0 Operation Mode */ - MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_F0OM, (OperationMode << FDCAN_RXGFC_F0OM_Pos)); - } - else /* RxFifo == FDCAN_RX_FIFO1 */ - { - /* Select FIFO 1 Operation Mode */ - MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_F1OM, (OperationMode << FDCAN_RXGFC_F1OM_Pos)); - } - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Configure the RAM watchdog. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param CounterStartValue Start value of the Message RAM Watchdog Counter, - * This parameter must be a number between 0x00 and 0xFF, - * with the reset value of 0x00 the counter is disabled. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigRamWatchdog(FDCAN_HandleTypeDef *hfdcan, uint32_t CounterStartValue) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_MAX_VALUE(CounterStartValue, 0xFFU)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Configure the RAM watchdog counter start value */ - MODIFY_REG(hfdcan->Instance->RWD, FDCAN_RWD_WDC, CounterStartValue); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Configure the timestamp counter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param TimestampPrescaler Timestamp Counter Prescaler. - * This parameter can be a value of @arg FDCAN_Timestamp_Prescaler. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampPrescaler) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_TIMESTAMP_PRESCALER(TimestampPrescaler)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Configure prescaler */ - MODIFY_REG(hfdcan->Instance->TSCC, FDCAN_TSCC_TCP, TimestampPrescaler); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Enable the timestamp counter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param TimestampOperation Timestamp counter operation. - * This parameter can be a value of @arg FDCAN_Timestamp. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_EnableTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampOperation) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_TIMESTAMP(TimestampOperation)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Enable timestamp counter */ - MODIFY_REG(hfdcan->Instance->TSCC, FDCAN_TSCC_TSS, TimestampOperation); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Disable the timestamp counter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DisableTimestampCounter(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Disable timestamp counter */ - CLEAR_BIT(hfdcan->Instance->TSCC, FDCAN_TSCC_TSS); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Get the timestamp counter value. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval Timestamp counter value - */ -uint16_t HAL_FDCAN_GetTimestampCounter(const FDCAN_HandleTypeDef *hfdcan) -{ - return (uint16_t)(hfdcan->Instance->TSCV); -} - -/** - * @brief Reset the timestamp counter to zero. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ResetTimestampCounter(FDCAN_HandleTypeDef *hfdcan) -{ - if ((hfdcan->Instance->TSCC & FDCAN_TSCC_TSS) != FDCAN_TIMESTAMP_EXTERNAL) - { - /* Reset timestamp counter. - Actually any write operation to TSCV clears the counter */ - CLEAR_REG(hfdcan->Instance->TSCV); - } - else - { - /* Update error code. - Unable to reset external counter */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_SUPPORTED; - - return HAL_ERROR; - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Configure the timeout counter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param TimeoutOperation Timeout counter operation. - * This parameter can be a value of @arg FDCAN_Timeout_Operation. - * @param TimeoutPeriod Start value of the timeout down-counter. - * This parameter must be a number between 0x0000 and 0xFFFF - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigTimeoutCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimeoutOperation, - uint32_t TimeoutPeriod) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_TIMEOUT(TimeoutOperation)); - assert_param(IS_FDCAN_MAX_VALUE(TimeoutPeriod, 0xFFFFU)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Select timeout operation and configure period */ - MODIFY_REG(hfdcan->Instance->TOCC, - (FDCAN_TOCC_TOS | FDCAN_TOCC_TOP), (TimeoutOperation | (TimeoutPeriod << FDCAN_TOCC_TOP_Pos))); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Enable the timeout counter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_EnableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Enable timeout counter */ - SET_BIT(hfdcan->Instance->TOCC, FDCAN_TOCC_ETOC); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Disable the timeout counter. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DisableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Disable timeout counter */ - CLEAR_BIT(hfdcan->Instance->TOCC, FDCAN_TOCC_ETOC); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Get the timeout counter value. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval Timeout counter value - */ -uint16_t HAL_FDCAN_GetTimeoutCounter(const FDCAN_HandleTypeDef *hfdcan) -{ - return (uint16_t)(hfdcan->Instance->TOCV); -} - -/** - * @brief Reset the timeout counter to its start value. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ResetTimeoutCounter(FDCAN_HandleTypeDef *hfdcan) -{ - if ((hfdcan->Instance->TOCC & FDCAN_TOCC_TOS) == FDCAN_TIMEOUT_CONTINUOUS) - { - /* Reset timeout counter to start value */ - CLEAR_REG(hfdcan->Instance->TOCV); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code. - Unable to reset counter: controlled only by FIFO empty state */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_SUPPORTED; - - return HAL_ERROR; - } -} - -/** - * @brief Configure the transmitter delay compensation. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param TdcOffset Transmitter Delay Compensation Offset. - * This parameter must be a number between 0x00 and 0x7F. - * @param TdcFilter Transmitter Delay Compensation Filter Window Length. - * This parameter must be a number between 0x00 and 0x7F. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan, uint32_t TdcOffset, - uint32_t TdcFilter) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_MAX_VALUE(TdcOffset, 0x7FU)); - assert_param(IS_FDCAN_MAX_VALUE(TdcFilter, 0x7FU)); - - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Configure TDC offset and filter window */ - hfdcan->Instance->TDCR = ((TdcFilter << FDCAN_TDCR_TDCF_Pos) | (TdcOffset << FDCAN_TDCR_TDCO_Pos)); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Enable the transmitter delay compensation. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_EnableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Enable transmitter delay compensation */ - SET_BIT(hfdcan->Instance->DBTP, FDCAN_DBTP_TDC); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Disable the transmitter delay compensation. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DisableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Disable transmitter delay compensation */ - CLEAR_BIT(hfdcan->Instance->DBTP, FDCAN_DBTP_TDC); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Enable ISO 11898-1 protocol mode. - * CAN FD frame format is according to ISO 11898-1 standard. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_EnableISOMode(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Disable Non ISO protocol mode */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_NISO); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Disable ISO 11898-1 protocol mode. - * CAN FD frame format is according to Bosch CAN FD specification V1.0. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DisableISOMode(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Enable Non ISO protocol mode */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_NISO); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Enable edge filtering during bus integration. - * Two consecutive dominant tq are required to detect an edge for hard synchronization. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_EnableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Enable edge filtering */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_EFBI); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Disable edge filtering during bus integration. - * One dominant tq is required to detect an edge for hard synchronization. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DisableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Disable edge filtering */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_EFBI); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @} - */ - -/** @defgroup FDCAN_Exported_Functions_Group3 Control functions - * @brief Control functions - * -@verbatim - ============================================================================== - ##### Control functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) HAL_FDCAN_Start : Start the FDCAN module - (+) HAL_FDCAN_Stop : Stop the FDCAN module and enable access to configuration registers - (+) HAL_FDCAN_AddMessageToTxFifoQ : Add a message to the Tx FIFO/Queue and activate the corresponding - transmission request - (+) HAL_FDCAN_GetLatestTxFifoQRequestBuffer : Get Tx buffer index of latest Tx FIFO/Queue request - (+) HAL_FDCAN_AbortTxRequest : Abort transmission request - (+) HAL_FDCAN_GetRxMessage : Get an FDCAN frame from the Rx FIFO zone into the message RAM - (+) HAL_FDCAN_GetTxEvent : Get an FDCAN Tx event from the Tx Event FIFO zone - into the message RAM - (+) HAL_FDCAN_GetHighPriorityMessageStatus : Get high priority message status - (+) HAL_FDCAN_GetProtocolStatus : Get protocol status - (+) HAL_FDCAN_GetErrorCounters : Get error counter values - (+) HAL_FDCAN_IsTxBufferMessagePending : Check if a transmission request is pending - on the selected Tx buffer - (+) HAL_FDCAN_GetRxFifoFillLevel : Return Rx FIFO fill level - (+) HAL_FDCAN_GetTxFifoFreeLevel : Return Tx FIFO free level - (+) HAL_FDCAN_IsRestrictedOperationMode : Check if the FDCAN peripheral entered Restricted Operation Mode - (+) HAL_FDCAN_ExitRestrictedOperationMode : Exit Restricted Operation Mode - -@endverbatim - * @{ - */ - -/** - * @brief Start the FDCAN module. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_Start(FDCAN_HandleTypeDef *hfdcan) -{ - if (hfdcan->State == HAL_FDCAN_STATE_READY) - { - /* Change FDCAN peripheral state */ - hfdcan->State = HAL_FDCAN_STATE_BUSY; - - /* Request leave initialisation */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); - - /* Reset the FDCAN ErrorCode */ - hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; - - return HAL_ERROR; - } -} - -/** - * @brief Stop the FDCAN module and enable access to configuration registers. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_Stop(FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t Counter = 0U; - - if (hfdcan->State == HAL_FDCAN_STATE_BUSY) - { - /* Request initialisation */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); - - /* Wait until the INIT bit into CCCR register is set */ - while ((hfdcan->Instance->CCCR & FDCAN_CCCR_INIT) == 0U) - { - /* Check for the Timeout */ - if (Counter > FDCAN_TIMEOUT_VALUE) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_ERROR; - - return HAL_ERROR; - } - - /* Increment counter */ - Counter++; - } - - /* Reset counter */ - Counter = 0U; - - /* Exit from Sleep mode */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); - - /* Wait until FDCAN exits sleep mode */ - while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA) - { - /* Check for the Timeout */ - if (Counter > FDCAN_TIMEOUT_VALUE) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; - - /* Change FDCAN state */ - hfdcan->State = HAL_FDCAN_STATE_ERROR; - - return HAL_ERROR; - } - - /* Increment counter */ - Counter++; - } - - /* Enable configuration change */ - SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CCE); - - /* Reset Latest Tx FIFO/Queue Request Buffer Index */ - hfdcan->LatestTxFifoQRequest = 0U; - - /* Change FDCAN peripheral state */ - hfdcan->State = HAL_FDCAN_STATE_READY; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; - - return HAL_ERROR; - } -} - -/** - * @brief Add a message to the Tx FIFO/Queue and activate the corresponding transmission request - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param pTxHeader pointer to a FDCAN_TxHeaderTypeDef structure. - * @param pTxData pointer to a buffer containing the payload of the Tx frame. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_AddMessageToTxFifoQ(FDCAN_HandleTypeDef *hfdcan, const FDCAN_TxHeaderTypeDef *pTxHeader, - const uint8_t *pTxData) -{ - uint32_t PutIndex; - - /* Check function parameters */ - assert_param(IS_FDCAN_ID_TYPE(pTxHeader->IdType)); - if (pTxHeader->IdType == FDCAN_STANDARD_ID) - { - assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->Identifier, 0x7FFU)); - } - else /* pTxHeader->IdType == FDCAN_EXTENDED_ID */ - { - assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->Identifier, 0x1FFFFFFFU)); - } - assert_param(IS_FDCAN_FRAME_TYPE(pTxHeader->TxFrameType)); - assert_param(IS_FDCAN_DLC(pTxHeader->DataLength)); - assert_param(IS_FDCAN_ESI(pTxHeader->ErrorStateIndicator)); - assert_param(IS_FDCAN_BRS(pTxHeader->BitRateSwitch)); - assert_param(IS_FDCAN_FDF(pTxHeader->FDFormat)); - assert_param(IS_FDCAN_EFC(pTxHeader->TxEventFifoControl)); - assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->MessageMarker, 0xFFU)); - - if (hfdcan->State == HAL_FDCAN_STATE_BUSY) - { - /* Check that the Tx FIFO/Queue is not full */ - if ((hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFQF) != 0U) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_FULL; - - return HAL_ERROR; - } - else - { - /* Retrieve the Tx FIFO PutIndex */ - PutIndex = ((hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFQPI) >> FDCAN_TXFQS_TFQPI_Pos); - - /* Add the message to the Tx FIFO/Queue */ - FDCAN_CopyMessageToRAM(hfdcan, pTxHeader, pTxData, PutIndex); - - /* Activate the corresponding transmission request */ - hfdcan->Instance->TXBAR = ((uint32_t)1 << PutIndex); - - /* Store the Latest Tx FIFO/Queue Request Buffer Index */ - hfdcan->LatestTxFifoQRequest = ((uint32_t)1 << PutIndex); - } - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; - - return HAL_ERROR; - } -} - -/** - * @brief Get Tx buffer index of latest Tx FIFO/Queue request - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval Tx buffer index of last Tx FIFO/Queue request - * - Any value of @arg FDCAN_Tx_location if Tx request has been submitted. - * - 0 if no Tx FIFO/Queue request have been submitted. - */ -uint32_t HAL_FDCAN_GetLatestTxFifoQRequestBuffer(const FDCAN_HandleTypeDef *hfdcan) -{ - /* Return Last Tx FIFO/Queue Request Buffer */ - return hfdcan->LatestTxFifoQRequest; -} - -/** - * @brief Abort transmission request - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param BufferIndex buffer index. - * This parameter can be any combination of @arg FDCAN_Tx_location. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_AbortTxRequest(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndex) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_TX_LOCATION_LIST(BufferIndex)); - - if (hfdcan->State == HAL_FDCAN_STATE_BUSY) - { - /* Add cancellation request */ - hfdcan->Instance->TXBCR = BufferIndex; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; - - return HAL_ERROR; - } -} - -/** - * @brief Get an FDCAN frame from the Rx FIFO zone into the message RAM. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param RxLocation Location of the received message to be read. - * This parameter can be a value of @arg FDCAN_Rx_location. - * @param pRxHeader pointer to a FDCAN_RxHeaderTypeDef structure. - * @param pRxData pointer to a buffer where the payload of the Rx frame will be stored. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_GetRxMessage(FDCAN_HandleTypeDef *hfdcan, uint32_t RxLocation, - FDCAN_RxHeaderTypeDef *pRxHeader, uint8_t *pRxData) -{ - uint32_t *RxAddress; - uint8_t *pData; - uint32_t ByteCounter; - uint32_t GetIndex = 0; - HAL_FDCAN_StateTypeDef state = hfdcan->State; - - /* Check function parameters */ - assert_param(IS_FDCAN_RX_FIFO(RxLocation)); - - if (state == HAL_FDCAN_STATE_BUSY) - { - if (RxLocation == FDCAN_RX_FIFO0) /* Rx element is assigned to the Rx FIFO 0 */ - { - /* Check that the Rx FIFO 0 is not empty */ - if ((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0FL) == 0U) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY; - - return HAL_ERROR; - } - else - { - /* Check that the Rx FIFO 0 is full & overwrite mode is on */ - if (((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0F) >> FDCAN_RXF0S_F0F_Pos) == 1U) - { - if (((hfdcan->Instance->RXGFC & FDCAN_RXGFC_F0OM) >> FDCAN_RXGFC_F0OM_Pos) == FDCAN_RX_FIFO_OVERWRITE) - { - /* When overwrite status is on discard first message in FIFO */ - GetIndex = 1U; - } - } - - /* Calculate Rx FIFO 0 element index */ - GetIndex += ((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0GI) >> FDCAN_RXF0S_F0GI_Pos); - - /* Calculate Rx FIFO 0 element address */ - RxAddress = (uint32_t *)(hfdcan->msgRam.RxFIFO0SA + (GetIndex * SRAMCAN_RF0_SIZE)); - } - } - else /* Rx element is assigned to the Rx FIFO 1 */ - { - /* Check that the Rx FIFO 1 is not empty */ - if ((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1FL) == 0U) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY; - - return HAL_ERROR; - } - else - { - /* Check that the Rx FIFO 1 is full & overwrite mode is on */ - if (((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1F) >> FDCAN_RXF1S_F1F_Pos) == 1U) - { - if (((hfdcan->Instance->RXGFC & FDCAN_RXGFC_F1OM) >> FDCAN_RXGFC_F1OM_Pos) == FDCAN_RX_FIFO_OVERWRITE) - { - /* When overwrite status is on discard first message in FIFO */ - GetIndex = 1U; - } - } - - /* Calculate Rx FIFO 1 element index */ - GetIndex += ((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1GI) >> FDCAN_RXF1S_F1GI_Pos); - /* Calculate Rx FIFO 1 element address */ - RxAddress = (uint32_t *)(hfdcan->msgRam.RxFIFO1SA + (GetIndex * SRAMCAN_RF1_SIZE)); - } - } - - /* Retrieve IdType */ - pRxHeader->IdType = *RxAddress & FDCAN_ELEMENT_MASK_XTD; - - /* Retrieve Identifier */ - if (pRxHeader->IdType == FDCAN_STANDARD_ID) /* Standard ID element */ - { - pRxHeader->Identifier = ((*RxAddress & FDCAN_ELEMENT_MASK_STDID) >> 18U); - } - else /* Extended ID element */ - { - pRxHeader->Identifier = (*RxAddress & FDCAN_ELEMENT_MASK_EXTID); - } - - /* Retrieve RxFrameType */ - pRxHeader->RxFrameType = (*RxAddress & FDCAN_ELEMENT_MASK_RTR); - - /* Retrieve ErrorStateIndicator */ - pRxHeader->ErrorStateIndicator = (*RxAddress & FDCAN_ELEMENT_MASK_ESI); - - /* Increment RxAddress pointer to second word of Rx FIFO element */ - RxAddress++; - - /* Retrieve RxTimestamp */ - pRxHeader->RxTimestamp = (*RxAddress & FDCAN_ELEMENT_MASK_TS); - - /* Retrieve DataLength */ - pRxHeader->DataLength = ((*RxAddress & FDCAN_ELEMENT_MASK_DLC) >> 16U); - - /* Retrieve BitRateSwitch */ - pRxHeader->BitRateSwitch = (*RxAddress & FDCAN_ELEMENT_MASK_BRS); - - /* Retrieve FDFormat */ - pRxHeader->FDFormat = (*RxAddress & FDCAN_ELEMENT_MASK_FDF); - - /* Retrieve FilterIndex */ - pRxHeader->FilterIndex = ((*RxAddress & FDCAN_ELEMENT_MASK_FIDX) >> 24U); - - /* Retrieve NonMatchingFrame */ - pRxHeader->IsFilterMatchingFrame = ((*RxAddress & FDCAN_ELEMENT_MASK_ANMF) >> 31U); - - /* Increment RxAddress pointer to payload of Rx FIFO element */ - RxAddress++; - - /* Retrieve Rx payload */ - pData = (uint8_t *)RxAddress; - for (ByteCounter = 0; ByteCounter < DLCtoBytes[pRxHeader->DataLength]; ByteCounter++) - { - pRxData[ByteCounter] = pData[ByteCounter]; - } - - if (RxLocation == FDCAN_RX_FIFO0) /* Rx element is assigned to the Rx FIFO 0 */ - { - /* Acknowledge the Rx FIFO 0 that the oldest element is read so that it increments the GetIndex */ - hfdcan->Instance->RXF0A = GetIndex; - } - else /* Rx element is assigned to the Rx FIFO 1 */ - { - /* Acknowledge the Rx FIFO 1 that the oldest element is read so that it increments the GetIndex */ - hfdcan->Instance->RXF1A = GetIndex; - } - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; - - return HAL_ERROR; - } -} - -/** - * @brief Get an FDCAN Tx event from the Tx Event FIFO zone into the message RAM. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param pTxEvent pointer to a FDCAN_TxEventFifoTypeDef structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_GetTxEvent(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxEventFifoTypeDef *pTxEvent) -{ - uint32_t *TxEventAddress; - uint32_t GetIndex; - HAL_FDCAN_StateTypeDef state = hfdcan->State; - - if (state == HAL_FDCAN_STATE_BUSY) - { - /* Check that the Tx event FIFO is not empty */ - if ((hfdcan->Instance->TXEFS & FDCAN_TXEFS_EFFL) == 0U) - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY; - - return HAL_ERROR; - } - - /* Calculate Tx event FIFO element address */ - GetIndex = ((hfdcan->Instance->TXEFS & FDCAN_TXEFS_EFGI) >> FDCAN_TXEFS_EFGI_Pos); - TxEventAddress = (uint32_t *)(hfdcan->msgRam.TxEventFIFOSA + (GetIndex * SRAMCAN_TEF_SIZE)); - - /* Retrieve IdType */ - pTxEvent->IdType = *TxEventAddress & FDCAN_ELEMENT_MASK_XTD; - - /* Retrieve Identifier */ - if (pTxEvent->IdType == FDCAN_STANDARD_ID) /* Standard ID element */ - { - pTxEvent->Identifier = ((*TxEventAddress & FDCAN_ELEMENT_MASK_STDID) >> 18U); - } - else /* Extended ID element */ - { - pTxEvent->Identifier = (*TxEventAddress & FDCAN_ELEMENT_MASK_EXTID); - } - - /* Retrieve TxFrameType */ - pTxEvent->TxFrameType = (*TxEventAddress & FDCAN_ELEMENT_MASK_RTR); - - /* Retrieve ErrorStateIndicator */ - pTxEvent->ErrorStateIndicator = (*TxEventAddress & FDCAN_ELEMENT_MASK_ESI); - - /* Increment TxEventAddress pointer to second word of Tx Event FIFO element */ - TxEventAddress++; - - /* Retrieve TxTimestamp */ - pTxEvent->TxTimestamp = (*TxEventAddress & FDCAN_ELEMENT_MASK_TS); - - /* Retrieve DataLength */ - pTxEvent->DataLength = ((*TxEventAddress & FDCAN_ELEMENT_MASK_DLC) >> 16U); - - /* Retrieve BitRateSwitch */ - pTxEvent->BitRateSwitch = (*TxEventAddress & FDCAN_ELEMENT_MASK_BRS); - - /* Retrieve FDFormat */ - pTxEvent->FDFormat = (*TxEventAddress & FDCAN_ELEMENT_MASK_FDF); - - /* Retrieve EventType */ - pTxEvent->EventType = (*TxEventAddress & FDCAN_ELEMENT_MASK_ET); - - /* Retrieve MessageMarker */ - pTxEvent->MessageMarker = ((*TxEventAddress & FDCAN_ELEMENT_MASK_MM) >> 24U); - - /* Acknowledge the Tx Event FIFO that the oldest element is read so that it increments the GetIndex */ - hfdcan->Instance->TXEFA = GetIndex; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; - - return HAL_ERROR; - } -} - -/** - * @brief Get high priority message status. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param HpMsgStatus pointer to an FDCAN_HpMsgStatusTypeDef structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_GetHighPriorityMessageStatus(const FDCAN_HandleTypeDef *hfdcan, - FDCAN_HpMsgStatusTypeDef *HpMsgStatus) -{ - HpMsgStatus->FilterList = ((hfdcan->Instance->HPMS & FDCAN_HPMS_FLST) >> FDCAN_HPMS_FLST_Pos); - HpMsgStatus->FilterIndex = ((hfdcan->Instance->HPMS & FDCAN_HPMS_FIDX) >> FDCAN_HPMS_FIDX_Pos); - HpMsgStatus->MessageStorage = (hfdcan->Instance->HPMS & FDCAN_HPMS_MSI); - HpMsgStatus->MessageIndex = (hfdcan->Instance->HPMS & FDCAN_HPMS_BIDX); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Get protocol status. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param ProtocolStatus pointer to an FDCAN_ProtocolStatusTypeDef structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_GetProtocolStatus(const FDCAN_HandleTypeDef *hfdcan, - FDCAN_ProtocolStatusTypeDef *ProtocolStatus) -{ - uint32_t StatusReg; - - /* Read the protocol status register */ - StatusReg = READ_REG(hfdcan->Instance->PSR); - - /* Fill the protocol status structure */ - ProtocolStatus->LastErrorCode = (StatusReg & FDCAN_PSR_LEC); - ProtocolStatus->DataLastErrorCode = ((StatusReg & FDCAN_PSR_DLEC) >> FDCAN_PSR_DLEC_Pos); - ProtocolStatus->Activity = (StatusReg & FDCAN_PSR_ACT); - ProtocolStatus->ErrorPassive = ((StatusReg & FDCAN_PSR_EP) >> FDCAN_PSR_EP_Pos); - ProtocolStatus->Warning = ((StatusReg & FDCAN_PSR_EW) >> FDCAN_PSR_EW_Pos); - ProtocolStatus->BusOff = ((StatusReg & FDCAN_PSR_BO) >> FDCAN_PSR_BO_Pos); - ProtocolStatus->RxESIflag = ((StatusReg & FDCAN_PSR_RESI) >> FDCAN_PSR_RESI_Pos); - ProtocolStatus->RxBRSflag = ((StatusReg & FDCAN_PSR_RBRS) >> FDCAN_PSR_RBRS_Pos); - ProtocolStatus->RxFDFflag = ((StatusReg & FDCAN_PSR_REDL) >> FDCAN_PSR_REDL_Pos); - ProtocolStatus->ProtocolException = ((StatusReg & FDCAN_PSR_PXE) >> FDCAN_PSR_PXE_Pos); - ProtocolStatus->TDCvalue = ((StatusReg & FDCAN_PSR_TDCV) >> FDCAN_PSR_TDCV_Pos); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Get error counter values. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param ErrorCounters pointer to an FDCAN_ErrorCountersTypeDef structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_GetErrorCounters(const FDCAN_HandleTypeDef *hfdcan, - FDCAN_ErrorCountersTypeDef *ErrorCounters) -{ - uint32_t CountersReg; - - /* Read the error counters register */ - CountersReg = READ_REG(hfdcan->Instance->ECR); - - /* Fill the error counters structure */ - ErrorCounters->TxErrorCnt = ((CountersReg & FDCAN_ECR_TEC) >> FDCAN_ECR_TEC_Pos); - ErrorCounters->RxErrorCnt = ((CountersReg & FDCAN_ECR_REC) >> FDCAN_ECR_REC_Pos); - ErrorCounters->RxErrorPassive = ((CountersReg & FDCAN_ECR_RP) >> FDCAN_ECR_RP_Pos); - ErrorCounters->ErrorLogging = ((CountersReg & FDCAN_ECR_CEL) >> FDCAN_ECR_CEL_Pos); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Check if a transmission request is pending on the selected Tx buffer. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param TxBufferIndex Tx buffer index. - * This parameter can be any combination of @arg FDCAN_Tx_location. - * @retval Status - * - 0 : No pending transmission request on TxBufferIndex list. - * - 1 : Pending transmission request on TxBufferIndex. - */ -uint32_t HAL_FDCAN_IsTxBufferMessagePending(const FDCAN_HandleTypeDef *hfdcan, uint32_t TxBufferIndex) -{ - /* Check function parameters */ - assert_param(IS_FDCAN_TX_LOCATION_LIST(TxBufferIndex)); - - /* Check pending transmission request on the selected buffer */ - if ((hfdcan->Instance->TXBRP & TxBufferIndex) == 0U) - { - return 0; - } - return 1; -} - -/** - * @brief Return Rx FIFO fill level. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param RxFifo Rx FIFO. - * This parameter can be one of the following values: - * @arg FDCAN_RX_FIFO0: Rx FIFO 0 - * @arg FDCAN_RX_FIFO1: Rx FIFO 1 - * @retval Rx FIFO fill level. - */ -uint32_t HAL_FDCAN_GetRxFifoFillLevel(const FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo) -{ - uint32_t FillLevel; - - /* Check function parameters */ - assert_param(IS_FDCAN_RX_FIFO(RxFifo)); - - if (RxFifo == FDCAN_RX_FIFO0) - { - FillLevel = hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0FL; - } - else /* RxFifo == FDCAN_RX_FIFO1 */ - { - FillLevel = hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1FL; - } - - /* Return Rx FIFO fill level */ - return FillLevel; -} - -/** - * @brief Return Tx FIFO free level: number of consecutive free Tx FIFO - * elements starting from Tx FIFO GetIndex. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval Tx FIFO free level. - */ -uint32_t HAL_FDCAN_GetTxFifoFreeLevel(const FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t FreeLevel; - - FreeLevel = hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFFL; - - /* Return Tx FIFO free level */ - return FreeLevel; -} - -/** - * @brief Check if the FDCAN peripheral entered Restricted Operation Mode. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval Status - * - 0 : Normal FDCAN operation. - * - 1 : Restricted Operation Mode active. - */ -uint32_t HAL_FDCAN_IsRestrictedOperationMode(const FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t OperationMode; - - /* Get Operation Mode */ - OperationMode = ((hfdcan->Instance->CCCR & FDCAN_CCCR_ASM) >> FDCAN_CCCR_ASM_Pos); - - return OperationMode; -} - -/** - * @brief Exit Restricted Operation Mode. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ExitRestrictedOperationMode(FDCAN_HandleTypeDef *hfdcan) -{ - HAL_FDCAN_StateTypeDef state = hfdcan->State; - - if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) - { - /* Exit Restricted Operation mode */ - CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_ASM); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; - - return HAL_ERROR; - } -} - -/** - * @} - */ - -/** @defgroup FDCAN_Exported_Functions_Group4 Interrupts management - * @brief Interrupts management - * -@verbatim - ============================================================================== - ##### Interrupts management ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) HAL_FDCAN_ConfigInterruptLines : Assign interrupts to either Interrupt line 0 or 1 - (+) HAL_FDCAN_ActivateNotification : Enable interrupts - (+) HAL_FDCAN_DeactivateNotification : Disable interrupts - (+) HAL_FDCAN_IRQHandler : Handles FDCAN interrupt request - -@endverbatim - * @{ - */ - -/** - * @brief Assign interrupts to either Interrupt line 0 or 1. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param ITList indicates which interrupts group will be assigned to the selected interrupt line. - * This parameter can be any combination of @arg FDCAN_Interrupts_Group. - * @param InterruptLine Interrupt line. - * This parameter can be a value of @arg FDCAN_Interrupt_Line. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ConfigInterruptLines(FDCAN_HandleTypeDef *hfdcan, uint32_t ITList, uint32_t InterruptLine) -{ - HAL_FDCAN_StateTypeDef state = hfdcan->State; - - /* Check function parameters */ - assert_param(IS_FDCAN_IT_GROUP(ITList)); - assert_param(IS_FDCAN_IT_LINE(InterruptLine)); - - if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) - { - /* Assign list of interrupts to the selected line */ - if (InterruptLine == FDCAN_INTERRUPT_LINE0) - { - CLEAR_BIT(hfdcan->Instance->ILS, ITList); - } - else /* InterruptLine == FDCAN_INTERRUPT_LINE1 */ - { - SET_BIT(hfdcan->Instance->ILS, ITList); - } - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; - - return HAL_ERROR; - } -} - -/** - * @brief Enable interrupts. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param ActiveITs indicates which interrupts will be enabled. - * This parameter can be any combination of @arg FDCAN_Interrupts. - * @param BufferIndexes Tx Buffer Indexes. - * This parameter can be any combination of @arg FDCAN_Tx_location. - * This parameter is ignored if ActiveITs does not include one of the following: - * - FDCAN_IT_TX_COMPLETE - * - FDCAN_IT_TX_ABORT_COMPLETE - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_ActivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t ActiveITs, - uint32_t BufferIndexes) -{ - HAL_FDCAN_StateTypeDef state = hfdcan->State; - uint32_t ITs_lines_selection; - - /* Check function parameters */ - assert_param(IS_FDCAN_IT(ActiveITs)); - if ((ActiveITs & (FDCAN_IT_TX_COMPLETE | FDCAN_IT_TX_ABORT_COMPLETE)) != 0U) - { - assert_param(IS_FDCAN_TX_LOCATION_LIST(BufferIndexes)); - } - - if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) - { - /* Get interrupts line selection */ - ITs_lines_selection = hfdcan->Instance->ILS; - - /* Enable Interrupt lines */ - if ((((ActiveITs & FDCAN_IT_LIST_RX_FIFO0) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) == 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_RX_FIFO1) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) == 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_SMSG) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) == 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) == 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_MISC) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) == 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) == 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) == 0U))) - { - /* Enable Interrupt line 0 */ - SET_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE0); - } - if ((((ActiveITs & FDCAN_IT_LIST_RX_FIFO0) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) != 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_RX_FIFO1) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) != 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_SMSG) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) != 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) != 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_MISC) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) != 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) != 0U)) || \ - (((ActiveITs & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) != 0U))) - { - /* Enable Interrupt line 1 */ - SET_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE1); - } - - if ((ActiveITs & FDCAN_IT_TX_COMPLETE) != 0U) - { - /* Enable Tx Buffer Transmission Interrupt to set TC flag in IR register, - but interrupt will only occur if TC is enabled in IE register */ - SET_BIT(hfdcan->Instance->TXBTIE, BufferIndexes); - } - - if ((ActiveITs & FDCAN_IT_TX_ABORT_COMPLETE) != 0U) - { - /* Enable Tx Buffer Cancellation Finished Interrupt to set TCF flag in IR register, - but interrupt will only occur if TCF is enabled in IE register */ - SET_BIT(hfdcan->Instance->TXBCIE, BufferIndexes); - } - - /* Enable the selected interrupts */ - __HAL_FDCAN_ENABLE_IT(hfdcan, ActiveITs); - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; - - return HAL_ERROR; - } -} - -/** - * @brief Disable interrupts. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param InactiveITs indicates which interrupts will be disabled. - * This parameter can be any combination of @arg FDCAN_Interrupts. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_FDCAN_DeactivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t InactiveITs) -{ - HAL_FDCAN_StateTypeDef state = hfdcan->State; - uint32_t ITs_enabled; - uint32_t ITs_lines_selection; - - /* Check function parameters */ - assert_param(IS_FDCAN_IT(InactiveITs)); - - if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) - { - /* Disable the selected interrupts */ - __HAL_FDCAN_DISABLE_IT(hfdcan, InactiveITs); - - if ((InactiveITs & FDCAN_IT_TX_COMPLETE) != 0U) - { - /* Disable Tx Buffer Transmission Interrupts */ - CLEAR_REG(hfdcan->Instance->TXBTIE); - } - - if ((InactiveITs & FDCAN_IT_TX_ABORT_COMPLETE) != 0U) - { - /* Disable Tx Buffer Cancellation Finished Interrupt */ - CLEAR_REG(hfdcan->Instance->TXBCIE); - } - - /* Get interrupts enabled and interrupts line selection */ - ITs_enabled = hfdcan->Instance->IE; - ITs_lines_selection = hfdcan->Instance->ILS; - - /* Check if some interrupts are still enabled on interrupt line 0 */ - if ((((ITs_enabled & FDCAN_IT_LIST_RX_FIFO0) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) == 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_RX_FIFO1) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) == 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_SMSG) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) == 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) == 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_MISC) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) == 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) == 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) == 0U))) - { - /* Do nothing */ - } - else /* no more interrupts enabled on interrupt line 0 */ - { - /* Disable interrupt line 0 */ - CLEAR_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE0); - } - - /* Check if some interrupts are still enabled on interrupt line 1 */ - if ((((ITs_enabled & FDCAN_IT_LIST_RX_FIFO0) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) != 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_RX_FIFO1) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) != 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_SMSG) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) != 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) != 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_MISC) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) != 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) != 0U)) || \ - (((ITs_enabled & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) - && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) != 0U))) - { - /* Do nothing */ - } - else /* no more interrupts enabled on interrupt line 1 */ - { - /* Disable interrupt line 1 */ - CLEAR_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE1); - } - - /* Return function status */ - return HAL_OK; - } - else - { - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; - - return HAL_ERROR; - } -} - -/** - * @brief Handles FDCAN interrupt request. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL status - */ -void HAL_FDCAN_IRQHandler(FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t TxEventFifoITs; - uint32_t RxFifo0ITs; - uint32_t RxFifo1ITs; - uint32_t Errors; - uint32_t ErrorStatusITs; - uint32_t TransmittedBuffers; - uint32_t AbortedBuffers; - uint32_t itsource; - uint32_t itflag; - - TxEventFifoITs = hfdcan->Instance->IR & FDCAN_TX_EVENT_FIFO_MASK; - TxEventFifoITs &= hfdcan->Instance->IE; - RxFifo0ITs = hfdcan->Instance->IR & FDCAN_RX_FIFO0_MASK; - RxFifo0ITs &= hfdcan->Instance->IE; - RxFifo1ITs = hfdcan->Instance->IR & FDCAN_RX_FIFO1_MASK; - RxFifo1ITs &= hfdcan->Instance->IE; - Errors = hfdcan->Instance->IR & FDCAN_ERROR_MASK; - Errors &= hfdcan->Instance->IE; - ErrorStatusITs = hfdcan->Instance->IR & FDCAN_ERROR_STATUS_MASK; - ErrorStatusITs &= hfdcan->Instance->IE; - itsource = hfdcan->Instance->IE; - itflag = hfdcan->Instance->IR; - - /* High Priority Message interrupt management *******************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_RX_HIGH_PRIORITY_MSG) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_RX_HIGH_PRIORITY_MSG) != RESET) - { - /* Clear the High Priority Message flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_RX_HIGH_PRIORITY_MSG); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->HighPriorityMessageCallback(hfdcan); -#else - /* High Priority Message Callback */ - HAL_FDCAN_HighPriorityMessageCallback(hfdcan); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - } - - /* Transmission Abort interrupt management **********************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TX_ABORT_COMPLETE) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TX_ABORT_COMPLETE) != RESET) - { - /* List of aborted monitored buffers */ - AbortedBuffers = hfdcan->Instance->TXBCF; - AbortedBuffers &= hfdcan->Instance->TXBCIE; - - /* Clear the Transmission Cancellation flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_ABORT_COMPLETE); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->TxBufferAbortCallback(hfdcan, AbortedBuffers); -#else - /* Transmission Cancellation Callback */ - HAL_FDCAN_TxBufferAbortCallback(hfdcan, AbortedBuffers); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - } - - /* Tx event FIFO interrupts management **************************************/ - if (TxEventFifoITs != 0U) - { - /* Clear the Tx Event FIFO flags */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, TxEventFifoITs); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->TxEventFifoCallback(hfdcan, TxEventFifoITs); -#else - /* Tx Event FIFO Callback */ - HAL_FDCAN_TxEventFifoCallback(hfdcan, TxEventFifoITs); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - - /* Rx FIFO 0 interrupts management ******************************************/ - if (RxFifo0ITs != 0U) - { - /* Clear the Rx FIFO 0 flags */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, RxFifo0ITs); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->RxFifo0Callback(hfdcan, RxFifo0ITs); -#else - /* Rx FIFO 0 Callback */ - HAL_FDCAN_RxFifo0Callback(hfdcan, RxFifo0ITs); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - - /* Rx FIFO 1 interrupts management ******************************************/ - if (RxFifo1ITs != 0U) - { - /* Clear the Rx FIFO 1 flags */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, RxFifo1ITs); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->RxFifo1Callback(hfdcan, RxFifo1ITs); -#else - /* Rx FIFO 1 Callback */ - HAL_FDCAN_RxFifo1Callback(hfdcan, RxFifo1ITs); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - - /* Tx FIFO empty interrupt management ***************************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TX_FIFO_EMPTY) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TX_FIFO_EMPTY) != RESET) - { - /* Clear the Tx FIFO empty flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_FIFO_EMPTY); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->TxFifoEmptyCallback(hfdcan); -#else - /* Tx FIFO empty Callback */ - HAL_FDCAN_TxFifoEmptyCallback(hfdcan); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - } - - /* Transmission Complete interrupt management *******************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TX_COMPLETE) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TX_COMPLETE) != RESET) - { - /* List of transmitted monitored buffers */ - TransmittedBuffers = hfdcan->Instance->TXBTO; - TransmittedBuffers &= hfdcan->Instance->TXBTIE; - - /* Clear the Transmission Complete flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_COMPLETE); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->TxBufferCompleteCallback(hfdcan, TransmittedBuffers); -#else - /* Transmission Complete Callback */ - HAL_FDCAN_TxBufferCompleteCallback(hfdcan, TransmittedBuffers); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - } - - /* Timestamp Wraparound interrupt management ********************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TIMESTAMP_WRAPAROUND) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TIMESTAMP_WRAPAROUND) != RESET) - { - /* Clear the Timestamp Wraparound flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TIMESTAMP_WRAPAROUND); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->TimestampWraparoundCallback(hfdcan); -#else - /* Timestamp Wraparound Callback */ - HAL_FDCAN_TimestampWraparoundCallback(hfdcan); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - } - - /* Timeout Occurred interrupt management ************************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TIMEOUT_OCCURRED) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TIMEOUT_OCCURRED) != RESET) - { - /* Clear the Timeout Occurred flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TIMEOUT_OCCURRED); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->TimeoutOccurredCallback(hfdcan); -#else - /* Timeout Occurred Callback */ - HAL_FDCAN_TimeoutOccurredCallback(hfdcan); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - } - - /* Message RAM access failure interrupt management **************************/ - if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_RAM_ACCESS_FAILURE) != RESET) - { - if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_RAM_ACCESS_FAILURE) != RESET) - { - /* Clear the Message RAM access failure flag */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_RAM_ACCESS_FAILURE); - - /* Update error code */ - hfdcan->ErrorCode |= HAL_FDCAN_ERROR_RAM_ACCESS; - } - } - - /* Error Status interrupts management ***************************************/ - if (ErrorStatusITs != 0U) - { - /* Clear the Error flags */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, ErrorStatusITs); - -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->ErrorStatusCallback(hfdcan, ErrorStatusITs); -#else - /* Error Status Callback */ - HAL_FDCAN_ErrorStatusCallback(hfdcan, ErrorStatusITs); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } - - /* Error interrupts management **********************************************/ - if (Errors != 0U) - { - /* Clear the Error flags */ - __HAL_FDCAN_CLEAR_FLAG(hfdcan, Errors); - - /* Update error code */ - hfdcan->ErrorCode |= Errors; - } - - if (hfdcan->ErrorCode != HAL_FDCAN_ERROR_NONE) - { -#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 - /* Call registered callback*/ - hfdcan->ErrorCallback(hfdcan); -#else - /* Error Callback */ - HAL_FDCAN_ErrorCallback(hfdcan); -#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ - } -} - -/** - * @} - */ - -/** @defgroup FDCAN_Exported_Functions_Group5 Callback functions - * @brief FDCAN Callback functions - * -@verbatim - ============================================================================== - ##### Callback functions ##### - ============================================================================== - [..] - This subsection provides the following callback functions: - (+) HAL_FDCAN_TxEventFifoCallback - (+) HAL_FDCAN_RxFifo0Callback - (+) HAL_FDCAN_RxFifo1Callback - (+) HAL_FDCAN_TxFifoEmptyCallback - (+) HAL_FDCAN_TxBufferCompleteCallback - (+) HAL_FDCAN_TxBufferAbortCallback - (+) HAL_FDCAN_HighPriorityMessageCallback - (+) HAL_FDCAN_TimestampWraparoundCallback - (+) HAL_FDCAN_TimeoutOccurredCallback - (+) HAL_FDCAN_ErrorCallback - (+) HAL_FDCAN_ErrorStatusCallback - -@endverbatim - * @{ - */ - -/** - * @brief Tx Event callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param TxEventFifoITs indicates which Tx Event FIFO interrupts are signaled. - * This parameter can be any combination of @arg FDCAN_Tx_Event_Fifo_Interrupts. - * @retval None - */ -__weak void HAL_FDCAN_TxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t TxEventFifoITs) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - UNUSED(TxEventFifoITs); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_TxEventFifoCallback could be implemented in the user file - */ -} - -/** - * @brief Rx FIFO 0 callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param RxFifo0ITs indicates which Rx FIFO 0 interrupts are signaled. - * This parameter can be any combination of @arg FDCAN_Rx_Fifo0_Interrupts. - * @retval None - */ -__weak void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - UNUSED(RxFifo0ITs); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_RxFifo0Callback could be implemented in the user file - */ -} - -/** - * @brief Rx FIFO 1 callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param RxFifo1ITs indicates which Rx FIFO 1 interrupts are signaled. - * This parameter can be any combination of @arg FDCAN_Rx_Fifo1_Interrupts. - * @retval None - */ -__weak void HAL_FDCAN_RxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - UNUSED(RxFifo1ITs); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_RxFifo1Callback could be implemented in the user file - */ -} - -/** - * @brief Tx FIFO Empty callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_TxFifoEmptyCallback(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_TxFifoEmptyCallback could be implemented in the user file - */ -} - -/** - * @brief Transmission Complete callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param BufferIndexes Indexes of the transmitted buffers. - * This parameter can be any combination of @arg FDCAN_Tx_location. - * @retval None - */ -__weak void HAL_FDCAN_TxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - UNUSED(BufferIndexes); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_TxBufferCompleteCallback could be implemented in the user file - */ -} - -/** - * @brief Transmission Cancellation callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param BufferIndexes Indexes of the aborted buffers. - * This parameter can be any combination of @arg FDCAN_Tx_location. - * @retval None - */ -__weak void HAL_FDCAN_TxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - UNUSED(BufferIndexes); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_TxBufferAbortCallback could be implemented in the user file - */ -} - -/** - * @brief Timestamp Wraparound callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_TimestampWraparoundCallback(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_TimestampWraparoundCallback could be implemented in the user file - */ -} - -/** - * @brief Timeout Occurred callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_TimeoutOccurredCallback(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_TimeoutOccurredCallback could be implemented in the user file - */ -} - -/** - * @brief High Priority Message callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_HighPriorityMessageCallback(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_HighPriorityMessageCallback could be implemented in the user file - */ -} - -/** - * @brief Error callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval None - */ -__weak void HAL_FDCAN_ErrorCallback(FDCAN_HandleTypeDef *hfdcan) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief Error status callback. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param ErrorStatusITs indicates which Error Status interrupts are signaled. - * This parameter can be any combination of @arg FDCAN_Error_Status_Interrupts. - * @retval None - */ -__weak void HAL_FDCAN_ErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hfdcan); - UNUSED(ErrorStatusITs); - - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_FDCAN_ErrorStatusCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup FDCAN_Exported_Functions_Group6 Peripheral State functions - * @brief FDCAN Peripheral State functions - * -@verbatim - ============================================================================== - ##### Peripheral State functions ##### - ============================================================================== - [..] - This subsection provides functions allowing to : - (+) HAL_FDCAN_GetState() : Return the FDCAN state. - (+) HAL_FDCAN_GetError() : Return the FDCAN error code if any. - -@endverbatim - * @{ - */ -/** - * @brief Return the FDCAN state - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval HAL state - */ -HAL_FDCAN_StateTypeDef HAL_FDCAN_GetState(const FDCAN_HandleTypeDef *hfdcan) -{ - /* Return FDCAN state */ - return hfdcan->State; -} - -/** - * @brief Return the FDCAN error code - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval FDCAN Error Code - */ -uint32_t HAL_FDCAN_GetError(const FDCAN_HandleTypeDef *hfdcan) -{ - /* Return FDCAN error code */ - return hfdcan->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup FDCAN_Private_Functions FDCAN Private Functions - * @{ - */ - -/** - * @brief Calculate each RAM block start address and size - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @retval none - */ -static void FDCAN_CalcultateRamBlockAddresses(FDCAN_HandleTypeDef *hfdcan) -{ - uint32_t RAMcounter; - uint32_t SramCanInstanceBase = SRAMCAN_BASE; - - if (hfdcan->Instance == FDCAN2) - { - SramCanInstanceBase += SRAMCAN_SIZE; - } - - /* Standard filter list start address */ - hfdcan->msgRam.StandardFilterSA = SramCanInstanceBase + SRAMCAN_FLSSA; - - /* Standard filter elements number */ - MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_LSS, (hfdcan->Init.StdFiltersNbr << FDCAN_RXGFC_LSS_Pos)); - - /* Extended filter list start address */ - hfdcan->msgRam.ExtendedFilterSA = SramCanInstanceBase + SRAMCAN_FLESA; - - /* Extended filter elements number */ - MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_LSE, (hfdcan->Init.ExtFiltersNbr << FDCAN_RXGFC_LSE_Pos)); - - /* Rx FIFO 0 start address */ - hfdcan->msgRam.RxFIFO0SA = SramCanInstanceBase + SRAMCAN_RF0SA; - - /* Rx FIFO 1 start address */ - hfdcan->msgRam.RxFIFO1SA = SramCanInstanceBase + SRAMCAN_RF1SA; - - /* Tx event FIFO start address */ - hfdcan->msgRam.TxEventFIFOSA = SramCanInstanceBase + SRAMCAN_TEFSA; - - /* Tx FIFO/queue start address */ - hfdcan->msgRam.TxFIFOQSA = SramCanInstanceBase + SRAMCAN_TFQSA; - - /* Flush the allocated Message RAM area */ - for (RAMcounter = SramCanInstanceBase; RAMcounter < (SramCanInstanceBase + SRAMCAN_SIZE); RAMcounter += 4U) - { - *(uint32_t *)(RAMcounter) = 0x00000000U; - } -} - -/** - * @brief Copy Tx message to the message RAM. - * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains - * the configuration information for the specified FDCAN. - * @param pTxHeader pointer to a FDCAN_TxHeaderTypeDef structure. - * @param pTxData pointer to a buffer containing the payload of the Tx frame. - * @param BufferIndex index of the buffer to be configured. - * @retval none - */ -static void FDCAN_CopyMessageToRAM(const FDCAN_HandleTypeDef *hfdcan, const FDCAN_TxHeaderTypeDef *pTxHeader, - const uint8_t *pTxData, uint32_t BufferIndex) -{ - uint32_t TxElementW1; - uint32_t TxElementW2; - uint32_t *TxAddress; - uint32_t ByteCounter; - - /* Build first word of Tx header element */ - if (pTxHeader->IdType == FDCAN_STANDARD_ID) - { - TxElementW1 = (pTxHeader->ErrorStateIndicator | - FDCAN_STANDARD_ID | - pTxHeader->TxFrameType | - (pTxHeader->Identifier << 18U)); - } - else /* pTxHeader->IdType == FDCAN_EXTENDED_ID */ - { - TxElementW1 = (pTxHeader->ErrorStateIndicator | - FDCAN_EXTENDED_ID | - pTxHeader->TxFrameType | - pTxHeader->Identifier); - } - - /* Build second word of Tx header element */ - TxElementW2 = ((pTxHeader->MessageMarker << 24U) | - pTxHeader->TxEventFifoControl | - pTxHeader->FDFormat | - pTxHeader->BitRateSwitch | - (pTxHeader->DataLength << 16U)); - - /* Calculate Tx element address */ - TxAddress = (uint32_t *)(hfdcan->msgRam.TxFIFOQSA + (BufferIndex * SRAMCAN_TFQ_SIZE)); - - /* Write Tx element header to the message RAM */ - *TxAddress = TxElementW1; - TxAddress++; - *TxAddress = TxElementW2; - TxAddress++; - - /* Write Tx payload to the message RAM */ - for (ByteCounter = 0; ByteCounter < DLCtoBytes[pTxHeader->DataLength]; ByteCounter += 4U) - { - *TxAddress = (((uint32_t)pTxData[ByteCounter + 3U] << 24U) | - ((uint32_t)pTxData[ByteCounter + 2U] << 16U) | - ((uint32_t)pTxData[ByteCounter + 1U] << 8U) | - (uint32_t)pTxData[ByteCounter]); - TxAddress++; - } -} - -/** - * @} - */ -#endif /* HAL_FDCAN_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - -#endif /* FDCAN1 */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_fdcan.c + * @author MCD Application Team + * @brief FDCAN HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Flexible DataRate Controller Area Network + * (FDCAN) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Configuration and Control functions + * + Peripheral State and Error functions + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the FDCAN peripheral using HAL_FDCAN_Init function. + + (#) If needed , configure the reception filters and optional features using + the following configuration functions: + (++) HAL_FDCAN_ConfigFilter + (++) HAL_FDCAN_ConfigGlobalFilter + (++) HAL_FDCAN_ConfigExtendedIdMask + (++) HAL_FDCAN_ConfigRxFifoOverwrite + (++) HAL_FDCAN_ConfigRamWatchdog + (++) HAL_FDCAN_ConfigTimestampCounter + (++) HAL_FDCAN_EnableTimestampCounter + (++) HAL_FDCAN_DisableTimestampCounter + (++) HAL_FDCAN_ConfigTimeoutCounter + (++) HAL_FDCAN_EnableTimeoutCounter + (++) HAL_FDCAN_DisableTimeoutCounter + (++) HAL_FDCAN_ConfigTxDelayCompensation + (++) HAL_FDCAN_EnableTxDelayCompensation + (++) HAL_FDCAN_DisableTxDelayCompensation + (++) HAL_FDCAN_EnableISOMode + (++) HAL_FDCAN_DisableISOMode + (++) HAL_FDCAN_EnableEdgeFiltering + (++) HAL_FDCAN_DisableEdgeFiltering + + (#) Start the FDCAN module using HAL_FDCAN_Start function. At this level + the node is active on the bus: it can send and receive messages. + + (#) The following Tx control functions can only be called when the FDCAN + module is started: + (++) HAL_FDCAN_AddMessageToTxFifoQ + (++) HAL_FDCAN_AbortTxRequest + + (#) After having submitted a Tx request in Tx Fifo or Queue, it is possible to + get Tx buffer location used to place the Tx request thanks to + HAL_FDCAN_GetLatestTxFifoQRequestBuffer API. + It is then possible to abort later on the corresponding Tx Request using + HAL_FDCAN_AbortTxRequest API. + + (#) When a message is received into the FDCAN message RAM, it can be + retrieved using the HAL_FDCAN_GetRxMessage function. + + (#) Calling the HAL_FDCAN_Stop function stops the FDCAN module by entering + it to initialization mode and re-enabling access to configuration + registers through the configuration functions listed here above. + + (#) All other control functions can be called any time after initialization + phase, no matter if the FDCAN module is started or stopped. + + *** Polling mode operation *** + ============================== + [..] + (#) Reception and transmission states can be monitored via the following + functions: + (++) HAL_FDCAN_IsTxBufferMessagePending + (++) HAL_FDCAN_GetRxFifoFillLevel + (++) HAL_FDCAN_GetTxFifoFreeLevel + + *** Interrupt mode operation *** + ================================ + [..] + (#) There are two interrupt lines: line 0 and 1. + By default, all interrupts are assigned to line 0. Interrupt lines + can be configured using HAL_FDCAN_ConfigInterruptLines function. + + (#) Notifications are activated using HAL_FDCAN_ActivateNotification + function. Then, the process can be controlled through one of the + available user callbacks: HAL_FDCAN_xxxCallback. + + *** Callback registration *** + ============================================= + + The compilation define USE_HAL_FDCAN_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function HAL_FDCAN_RegisterCallback() or HAL_FDCAN_RegisterXXXCallback() + to register an interrupt callback. + + Function HAL_FDCAN_RegisterCallback() allows to register following callbacks: + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) HighPriorityMessageCallback : High Priority Message Callback. + (+) TimestampWraparoundCallback : Timestamp Wraparound Callback. + (+) TimeoutOccurredCallback : Timeout Occurred Callback. + (+) ErrorCallback : Error Callback. + (+) MspInitCallback : FDCAN MspInit. + (+) MspDeInitCallback : FDCAN MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + For specific callbacks TxEventFifoCallback, RxFifo0Callback, RxFifo1Callback, + TxBufferCompleteCallback, TxBufferAbortCallback and ErrorStatusCallback use dedicated + register callbacks: respectively HAL_FDCAN_RegisterTxEventFifoCallback(), + HAL_FDCAN_RegisterRxFifo0Callback(), HAL_FDCAN_RegisterRxFifo1Callback(), + HAL_FDCAN_RegisterTxBufferCompleteCallback(), HAL_FDCAN_RegisterTxBufferAbortCallback() + and HAL_FDCAN_RegisterErrorStatusCallback(). + + Use function HAL_FDCAN_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_FDCAN_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) HighPriorityMessageCallback : High Priority Message Callback. + (+) TimestampWraparoundCallback : Timestamp Wraparound Callback. + (+) TimeoutOccurredCallback : Timeout Occurred Callback. + (+) ErrorCallback : Error Callback. + (+) MspInitCallback : FDCAN MspInit. + (+) MspDeInitCallback : FDCAN MspDeInit. + + For specific callbacks TxEventFifoCallback, RxFifo0Callback, RxFifo1Callback, + TxBufferCompleteCallback and TxBufferAbortCallback, use dedicated + unregister callbacks: respectively HAL_FDCAN_UnRegisterTxEventFifoCallback(), + HAL_FDCAN_UnRegisterRxFifo0Callback(), HAL_FDCAN_UnRegisterRxFifo1Callback(), + HAL_FDCAN_UnRegisterTxBufferCompleteCallback(), HAL_FDCAN_UnRegisterTxBufferAbortCallback() + and HAL_FDCAN_UnRegisterErrorStatusCallback(). + + By default, after the HAL_FDCAN_Init() and when the state is HAL_FDCAN_STATE_RESET, + all callbacks are set to the corresponding weak functions: + examples HAL_FDCAN_ErrorCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the HAL_FDCAN_Init()/ HAL_FDCAN_DeInit() only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the HAL_FDCAN_Init()/ HAL_FDCAN_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in HAL_FDCAN_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_FDCAN_STATE_READY or HAL_FDCAN_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_FDCAN_RegisterCallback() before calling HAL_FDCAN_DeInit() + or HAL_FDCAN_Init() function. + + When The compilation define USE_HAL_FDCAN_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +#if defined(FDCAN1) + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup FDCAN FDCAN + * @brief FDCAN HAL module driver + * @{ + */ + +#ifdef HAL_FDCAN_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup FDCAN_Private_Constants + * @{ + */ +#define FDCAN_TIMEOUT_VALUE 10U + +#define FDCAN_TX_EVENT_FIFO_MASK (FDCAN_IR_TEFL | FDCAN_IR_TEFF | FDCAN_IR_TEFN) +#define FDCAN_RX_FIFO0_MASK (FDCAN_IR_RF0L | FDCAN_IR_RF0F | FDCAN_IR_RF0N) +#define FDCAN_RX_FIFO1_MASK (FDCAN_IR_RF1L | FDCAN_IR_RF1F | FDCAN_IR_RF1N) +#define FDCAN_ERROR_MASK (FDCAN_IR_ELO | FDCAN_IR_WDI | FDCAN_IR_PEA | FDCAN_IR_PED | FDCAN_IR_ARA) +#define FDCAN_ERROR_STATUS_MASK (FDCAN_IR_EP | FDCAN_IR_EW | FDCAN_IR_BO) + +#define FDCAN_ELEMENT_MASK_STDID ((uint32_t)0x1FFC0000U) /* Standard Identifier */ +#define FDCAN_ELEMENT_MASK_EXTID ((uint32_t)0x1FFFFFFFU) /* Extended Identifier */ +#define FDCAN_ELEMENT_MASK_RTR ((uint32_t)0x20000000U) /* Remote Transmission Request */ +#define FDCAN_ELEMENT_MASK_XTD ((uint32_t)0x40000000U) /* Extended Identifier */ +#define FDCAN_ELEMENT_MASK_ESI ((uint32_t)0x80000000U) /* Error State Indicator */ +#define FDCAN_ELEMENT_MASK_TS ((uint32_t)0x0000FFFFU) /* Timestamp */ +#define FDCAN_ELEMENT_MASK_DLC ((uint32_t)0x000F0000U) /* Data Length Code */ +#define FDCAN_ELEMENT_MASK_BRS ((uint32_t)0x00100000U) /* Bit Rate Switch */ +#define FDCAN_ELEMENT_MASK_FDF ((uint32_t)0x00200000U) /* FD Format */ +#define FDCAN_ELEMENT_MASK_EFC ((uint32_t)0x00800000U) /* Event FIFO Control */ +#define FDCAN_ELEMENT_MASK_MM ((uint32_t)0xFF000000U) /* Message Marker */ +#define FDCAN_ELEMENT_MASK_FIDX ((uint32_t)0x7F000000U) /* Filter Index */ +#define FDCAN_ELEMENT_MASK_ANMF ((uint32_t)0x80000000U) /* Accepted Non-matching Frame */ +#define FDCAN_ELEMENT_MASK_ET ((uint32_t)0x00C00000U) /* Event type */ + +#define SRAMCAN_FLS_NBR (28U) /* Max. Filter List Standard Number */ +#define SRAMCAN_FLE_NBR ( 8U) /* Max. Filter List Extended Number */ +#define SRAMCAN_RF0_NBR ( 3U) /* RX FIFO 0 Elements Number */ +#define SRAMCAN_RF1_NBR ( 3U) /* RX FIFO 1 Elements Number */ +#define SRAMCAN_TEF_NBR ( 3U) /* TX Event FIFO Elements Number */ +#define SRAMCAN_TFQ_NBR ( 3U) /* TX FIFO/Queue Elements Number */ + +#define SRAMCAN_FLS_SIZE ( 1U * 4U) /* Filter Standard Element Size in bytes */ +#define SRAMCAN_FLE_SIZE ( 2U * 4U) /* Filter Extended Element Size in bytes */ +#define SRAMCAN_RF0_SIZE (18U * 4U) /* RX FIFO 0 Elements Size in bytes */ +#define SRAMCAN_RF1_SIZE (18U * 4U) /* RX FIFO 1 Elements Size in bytes */ +#define SRAMCAN_TEF_SIZE ( 2U * 4U) /* TX Event FIFO Elements Size in bytes */ +#define SRAMCAN_TFQ_SIZE (18U * 4U) /* TX FIFO/Queue Elements Size in bytes */ + +#define SRAMCAN_FLSSA ((uint32_t)0) /* Filter List Standard Start + Address */ +#define SRAMCAN_FLESA ((uint32_t)(SRAMCAN_FLSSA + (SRAMCAN_FLS_NBR * SRAMCAN_FLS_SIZE))) /* Filter List Extended Start + Address */ +#define SRAMCAN_RF0SA ((uint32_t)(SRAMCAN_FLESA + (SRAMCAN_FLE_NBR * SRAMCAN_FLE_SIZE))) /* Rx FIFO 0 Start Address */ +#define SRAMCAN_RF1SA ((uint32_t)(SRAMCAN_RF0SA + (SRAMCAN_RF0_NBR * SRAMCAN_RF0_SIZE))) /* Rx FIFO 1 Start Address */ +#define SRAMCAN_TEFSA ((uint32_t)(SRAMCAN_RF1SA + (SRAMCAN_RF1_NBR * SRAMCAN_RF1_SIZE))) /* Tx Event FIFO Start + Address */ +#define SRAMCAN_TFQSA ((uint32_t)(SRAMCAN_TEFSA + (SRAMCAN_TEF_NBR * SRAMCAN_TEF_SIZE))) /* Tx FIFO/Queue Start + Address */ +#define SRAMCAN_SIZE ((uint32_t)(SRAMCAN_TFQSA + (SRAMCAN_TFQ_NBR * SRAMCAN_TFQ_SIZE))) /* Message RAM size */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup FDCAN_Private_Variables + * @{ + */ +static const uint8_t DLCtoBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64}; +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup FDCAN_Private_Functions_Prototypes + * @{ + */ +static void FDCAN_CalcultateRamBlockAddresses(FDCAN_HandleTypeDef *hfdcan); +static void FDCAN_CopyMessageToRAM(const FDCAN_HandleTypeDef *hfdcan, const FDCAN_TxHeaderTypeDef *pTxHeader, + const uint8_t *pTxData, uint32_t BufferIndex); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup FDCAN_Exported_Functions FDCAN Exported Functions + * @{ + */ + +/** @defgroup FDCAN_Exported_Functions_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 FDCAN. + (+) De-initialize the FDCAN. + (+) Enter FDCAN peripheral in power down mode. + (+) Exit power down mode. + (+) Register callbacks. + (+) Unregister callbacks. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the FDCAN peripheral according to the specified + * parameters in the FDCAN_InitTypeDef structure. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_Init(FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t tickstart; + + /* Check FDCAN handle */ + if (hfdcan == NULL) + { + return HAL_ERROR; + } + + /* Check function parameters */ + assert_param(IS_FDCAN_ALL_INSTANCE(hfdcan->Instance)); + if (hfdcan->Instance == FDCAN1) + { + assert_param(IS_FDCAN_CKDIV(hfdcan->Init.ClockDivider)); + } + assert_param(IS_FDCAN_FRAME_FORMAT(hfdcan->Init.FrameFormat)); + assert_param(IS_FDCAN_MODE(hfdcan->Init.Mode)); + assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.AutoRetransmission)); + assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.TransmitPause)); + assert_param(IS_FUNCTIONAL_STATE(hfdcan->Init.ProtocolException)); + assert_param(IS_FDCAN_NOMINAL_PRESCALER(hfdcan->Init.NominalPrescaler)); + assert_param(IS_FDCAN_NOMINAL_SJW(hfdcan->Init.NominalSyncJumpWidth)); + assert_param(IS_FDCAN_NOMINAL_TSEG1(hfdcan->Init.NominalTimeSeg1)); + assert_param(IS_FDCAN_NOMINAL_TSEG2(hfdcan->Init.NominalTimeSeg2)); + if (hfdcan->Init.FrameFormat == FDCAN_FRAME_FD_BRS) + { + assert_param(IS_FDCAN_DATA_PRESCALER(hfdcan->Init.DataPrescaler)); + assert_param(IS_FDCAN_DATA_SJW(hfdcan->Init.DataSyncJumpWidth)); + assert_param(IS_FDCAN_DATA_TSEG1(hfdcan->Init.DataTimeSeg1)); + assert_param(IS_FDCAN_DATA_TSEG2(hfdcan->Init.DataTimeSeg2)); + } + assert_param(IS_FDCAN_MAX_VALUE(hfdcan->Init.StdFiltersNbr, SRAMCAN_FLS_NBR)); + assert_param(IS_FDCAN_MAX_VALUE(hfdcan->Init.ExtFiltersNbr, SRAMCAN_FLE_NBR)); + assert_param(IS_FDCAN_TX_FIFO_QUEUE_MODE(hfdcan->Init.TxFifoQueueMode)); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + if (hfdcan->State == HAL_FDCAN_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hfdcan->Lock = HAL_UNLOCKED; + + /* Reset callbacks to legacy functions */ + hfdcan->TxEventFifoCallback = HAL_FDCAN_TxEventFifoCallback; /* TxEventFifoCallback */ + hfdcan->RxFifo0Callback = HAL_FDCAN_RxFifo0Callback; /* RxFifo0Callback */ + hfdcan->RxFifo1Callback = HAL_FDCAN_RxFifo1Callback; /* RxFifo1Callback */ + hfdcan->TxFifoEmptyCallback = HAL_FDCAN_TxFifoEmptyCallback; /* TxFifoEmptyCallback */ + hfdcan->TxBufferCompleteCallback = HAL_FDCAN_TxBufferCompleteCallback; /* TxBufferCompleteCallback */ + hfdcan->TxBufferAbortCallback = HAL_FDCAN_TxBufferAbortCallback; /* TxBufferAbortCallback */ + hfdcan->HighPriorityMessageCallback = HAL_FDCAN_HighPriorityMessageCallback; /* HighPriorityMessageCallback */ + hfdcan->TimestampWraparoundCallback = HAL_FDCAN_TimestampWraparoundCallback; /* TimestampWraparoundCallback */ + hfdcan->TimeoutOccurredCallback = HAL_FDCAN_TimeoutOccurredCallback; /* TimeoutOccurredCallback */ + hfdcan->ErrorCallback = HAL_FDCAN_ErrorCallback; /* ErrorCallback */ + hfdcan->ErrorStatusCallback = HAL_FDCAN_ErrorStatusCallback; /* ErrorStatusCallback */ + + if (hfdcan->MspInitCallback == NULL) + { + hfdcan->MspInitCallback = HAL_FDCAN_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware: CLOCK, NVIC */ + hfdcan->MspInitCallback(hfdcan); + } +#else + if (hfdcan->State == HAL_FDCAN_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hfdcan->Lock = HAL_UNLOCKED; + + /* Init the low level hardware: CLOCK, NVIC */ + HAL_FDCAN_MspInit(hfdcan); + } +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + + /* Exit from Sleep mode */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Check Sleep mode acknowledge */ + while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA) + { + if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_ERROR; + + return HAL_ERROR; + } + } + + /* Request initialisation */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until the INIT bit into CCCR register is set */ + while ((hfdcan->Instance->CCCR & FDCAN_CCCR_INIT) == 0U) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_ERROR; + + return HAL_ERROR; + } + } + + /* Enable configuration change */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CCE); + + /* Check FDCAN instance */ + if (hfdcan->Instance == FDCAN1) + { + /* Configure Clock divider */ + FDCAN_CONFIG->CKDIV = hfdcan->Init.ClockDivider; + } + + /* Set the no automatic retransmission */ + if (hfdcan->Init.AutoRetransmission == ENABLE) + { + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_DAR); + } + else + { + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_DAR); + } + + /* Set the transmit pause feature */ + if (hfdcan->Init.TransmitPause == ENABLE) + { + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TXP); + } + else + { + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TXP); + } + + /* Set the Protocol Exception Handling */ + if (hfdcan->Init.ProtocolException == ENABLE) + { + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_PXHD); + } + else + { + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_PXHD); + } + + /* Set FDCAN Frame Format */ + MODIFY_REG(hfdcan->Instance->CCCR, FDCAN_FRAME_FD_BRS, hfdcan->Init.FrameFormat); + + /* Reset FDCAN Operation Mode */ + CLEAR_BIT(hfdcan->Instance->CCCR, (FDCAN_CCCR_TEST | FDCAN_CCCR_MON | FDCAN_CCCR_ASM)); + CLEAR_BIT(hfdcan->Instance->TEST, FDCAN_TEST_LBCK); + + /* Set FDCAN Operating Mode: + | Normal | Restricted | Bus | Internal | External + | | Operation | Monitoring | LoopBack | LoopBack + CCCR.TEST | 0 | 0 | 0 | 1 | 1 + CCCR.MON | 0 | 0 | 1 | 1 | 0 + TEST.LBCK | 0 | 0 | 0 | 1 | 1 + CCCR.ASM | 0 | 1 | 0 | 0 | 0 + */ + if (hfdcan->Init.Mode == FDCAN_MODE_RESTRICTED_OPERATION) + { + /* Enable Restricted Operation mode */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_ASM); + } + else if (hfdcan->Init.Mode != FDCAN_MODE_NORMAL) + { + if (hfdcan->Init.Mode != FDCAN_MODE_BUS_MONITORING) + { + /* Enable write access to TEST register */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_TEST); + + /* Enable LoopBack mode */ + SET_BIT(hfdcan->Instance->TEST, FDCAN_TEST_LBCK); + + if (hfdcan->Init.Mode == FDCAN_MODE_INTERNAL_LOOPBACK) + { + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_MON); + } + } + else + { + /* Enable bus monitoring mode */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_MON); + } + } + else + { + /* Nothing to do: normal mode */ + } + + /* Set the nominal bit timing register */ + hfdcan->Instance->NBTP = ((((uint32_t)hfdcan->Init.NominalSyncJumpWidth - 1U) << FDCAN_NBTP_NSJW_Pos) | \ + (((uint32_t)hfdcan->Init.NominalTimeSeg1 - 1U) << FDCAN_NBTP_NTSEG1_Pos) | \ + (((uint32_t)hfdcan->Init.NominalTimeSeg2 - 1U) << FDCAN_NBTP_NTSEG2_Pos) | \ + (((uint32_t)hfdcan->Init.NominalPrescaler - 1U) << FDCAN_NBTP_NBRP_Pos)); + + /* If FD operation with BRS is selected, set the data bit timing register */ + if (hfdcan->Init.FrameFormat == FDCAN_FRAME_FD_BRS) + { + hfdcan->Instance->DBTP = ((((uint32_t)hfdcan->Init.DataSyncJumpWidth - 1U) << FDCAN_DBTP_DSJW_Pos) | \ + (((uint32_t)hfdcan->Init.DataTimeSeg1 - 1U) << FDCAN_DBTP_DTSEG1_Pos) | \ + (((uint32_t)hfdcan->Init.DataTimeSeg2 - 1U) << FDCAN_DBTP_DTSEG2_Pos) | \ + (((uint32_t)hfdcan->Init.DataPrescaler - 1U) << FDCAN_DBTP_DBRP_Pos)); + } + + /* Select between Tx FIFO and Tx Queue operation modes */ + SET_BIT(hfdcan->Instance->TXBC, hfdcan->Init.TxFifoQueueMode); + + /* Calculate each RAM block address */ + FDCAN_CalcultateRamBlockAddresses(hfdcan); + + /* Initialize the Latest Tx request buffer index */ + hfdcan->LatestTxFifoQRequest = 0U; + + /* Initialize the error code */ + hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE; + + /* Initialize the FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitializes the FDCAN peripheral registers to their default reset values. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DeInit(FDCAN_HandleTypeDef *hfdcan) +{ + /* Check FDCAN handle */ + if (hfdcan == NULL) + { + return HAL_ERROR; + } + + /* Check function parameters */ + assert_param(IS_FDCAN_ALL_INSTANCE(hfdcan->Instance)); + + /* Stop the FDCAN module: return value is voluntary ignored */ + (void)HAL_FDCAN_Stop(hfdcan); + + /* Disable Interrupt lines */ + CLEAR_BIT(hfdcan->Instance->ILE, (FDCAN_INTERRUPT_LINE0 | FDCAN_INTERRUPT_LINE1)); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + if (hfdcan->MspDeInitCallback == NULL) + { + hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: CLOCK, NVIC */ + hfdcan->MspDeInitCallback(hfdcan); +#else + /* DeInit the low level hardware: CLOCK, NVIC */ + HAL_FDCAN_MspDeInit(hfdcan); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + + /* Reset the FDCAN ErrorCode */ + hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_RESET; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the FDCAN MSP. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_MspInit(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the FDCAN MSP. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_MspDeInit(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Enter FDCAN peripheral in sleep mode. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_EnterPowerDownMode(FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t tickstart; + + /* Request clock stop */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until FDCAN is ready for power down */ + while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == 0U) + { + if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_ERROR; + + return HAL_ERROR; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Exit power down mode. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ExitPowerDownMode(FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t tickstart; + + /* Reset clock stop request */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until FDCAN exits sleep mode */ + while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA) + { + if ((HAL_GetTick() - tickstart) > FDCAN_TIMEOUT_VALUE) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_ERROR; + + return HAL_ERROR; + } + } + + /* Enter normal operation */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); + + /* Return function status */ + return HAL_OK; +} + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 +/** + * @brief Register a FDCAN CallBack. + * To be used instead of the weak predefined callback + * @param hfdcan pointer to a FDCAN_HandleTypeDef structure that contains + * the configuration information for FDCAN module + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_FDCAN_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty callback ID + * @arg @ref HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID High priority message callback ID + * @arg @ref HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID Timestamp wraparound callback ID + * @arg @ref HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID Timeout occurred callback ID + * @arg @ref HAL_FDCAN_ERROR_CALLBACK_CB_ID Error callback ID + * @arg @ref HAL_FDCAN_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_FDCAN_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID, + void (* pCallback)(FDCAN_HandleTypeDef *_hFDCAN)) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + switch (CallbackID) + { + case HAL_FDCAN_TX_FIFO_EMPTY_CB_ID : + hfdcan->TxFifoEmptyCallback = pCallback; + break; + + case HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID : + hfdcan->HighPriorityMessageCallback = pCallback; + break; + + case HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID : + hfdcan->TimestampWraparoundCallback = pCallback; + break; + + case HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID : + hfdcan->TimeoutOccurredCallback = pCallback; + break; + + case HAL_FDCAN_ERROR_CALLBACK_CB_ID : + hfdcan->ErrorCallback = pCallback; + break; + + case HAL_FDCAN_MSPINIT_CB_ID : + hfdcan->MspInitCallback = pCallback; + break; + + case HAL_FDCAN_MSPDEINIT_CB_ID : + hfdcan->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hfdcan->State == HAL_FDCAN_STATE_RESET) + { + switch (CallbackID) + { + case HAL_FDCAN_MSPINIT_CB_ID : + hfdcan->MspInitCallback = pCallback; + break; + + case HAL_FDCAN_MSPDEINIT_CB_ID : + hfdcan->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a FDCAN CallBack. + * FDCAN callback is redirected to the weak predefined callback + * @param hfdcan pointer to a FDCAN_HandleTypeDef structure that contains + * the configuration information for FDCAN module + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_FDCAN_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty callback ID + * @arg @ref HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID High priority message callback ID + * @arg @ref HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID Timestamp wraparound callback ID + * @arg @ref HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID Timeout occurred callback ID + * @arg @ref HAL_FDCAN_ERROR_CALLBACK_CB_ID Error callback ID + * @arg @ref HAL_FDCAN_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_FDCAN_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterCallback(FDCAN_HandleTypeDef *hfdcan, HAL_FDCAN_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + switch (CallbackID) + { + case HAL_FDCAN_TX_FIFO_EMPTY_CB_ID : + hfdcan->TxFifoEmptyCallback = HAL_FDCAN_TxFifoEmptyCallback; + break; + + case HAL_FDCAN_HIGH_PRIO_MESSAGE_CB_ID : + hfdcan->HighPriorityMessageCallback = HAL_FDCAN_HighPriorityMessageCallback; + break; + + case HAL_FDCAN_TIMESTAMP_WRAPAROUND_CB_ID : + hfdcan->TimestampWraparoundCallback = HAL_FDCAN_TimestampWraparoundCallback; + break; + + case HAL_FDCAN_TIMEOUT_OCCURRED_CB_ID : + hfdcan->TimeoutOccurredCallback = HAL_FDCAN_TimeoutOccurredCallback; + break; + + case HAL_FDCAN_ERROR_CALLBACK_CB_ID : + hfdcan->ErrorCallback = HAL_FDCAN_ErrorCallback; + break; + + case HAL_FDCAN_MSPINIT_CB_ID : + hfdcan->MspInitCallback = HAL_FDCAN_MspInit; + break; + + case HAL_FDCAN_MSPDEINIT_CB_ID : + hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; + break; + + default : + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hfdcan->State == HAL_FDCAN_STATE_RESET) + { + switch (CallbackID) + { + case HAL_FDCAN_MSPINIT_CB_ID : + hfdcan->MspInitCallback = HAL_FDCAN_MspInit; + break; + + case HAL_FDCAN_MSPDEINIT_CB_ID : + hfdcan->MspDeInitCallback = HAL_FDCAN_MspDeInit; + break; + + default : + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register Tx Event Fifo FDCAN Callback + * To be used instead of the weak HAL_FDCAN_TxEventFifoCallback() predefined callback + * @param hfdcan FDCAN handle + * @param pCallback pointer to the Tx Event Fifo Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, + pFDCAN_TxEventFifoCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->TxEventFifoCallback = pCallback; + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Tx Event Fifo FDCAN Callback + * Tx Event Fifo FDCAN Callback is redirected to the weak HAL_FDCAN_TxEventFifoCallback() predefined callback + * @param hfdcan FDCAN handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->TxEventFifoCallback = HAL_FDCAN_TxEventFifoCallback; /* Legacy weak TxEventFifoCallback */ + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register Rx Fifo 0 FDCAN Callback + * To be used instead of the weak HAL_FDCAN_RxFifo0Callback() predefined callback + * @param hfdcan FDCAN handle + * @param pCallback pointer to the Rx Fifo 0 Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, + pFDCAN_RxFifo0CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->RxFifo0Callback = pCallback; + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Rx Fifo 0 FDCAN Callback + * Rx Fifo 0 FDCAN Callback is redirected to the weak HAL_FDCAN_RxFifo0Callback() predefined callback + * @param hfdcan FDCAN handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo0Callback(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->RxFifo0Callback = HAL_FDCAN_RxFifo0Callback; /* Legacy weak RxFifo0Callback */ + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register Rx Fifo 1 FDCAN Callback + * To be used instead of the weak HAL_FDCAN_RxFifo1Callback() predefined callback + * @param hfdcan FDCAN handle + * @param pCallback pointer to the Rx Fifo 1 Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, + pFDCAN_RxFifo1CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->RxFifo1Callback = pCallback; + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Rx Fifo 1 FDCAN Callback + * Rx Fifo 1 FDCAN Callback is redirected to the weak HAL_FDCAN_RxFifo1Callback() predefined callback + * @param hfdcan FDCAN handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterRxFifo1Callback(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->RxFifo1Callback = HAL_FDCAN_RxFifo1Callback; /* Legacy weak RxFifo1Callback */ + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register Tx Buffer Complete FDCAN Callback + * To be used instead of the weak HAL_FDCAN_TxBufferCompleteCallback() predefined callback + * @param hfdcan FDCAN handle + * @param pCallback pointer to the Tx Buffer Complete Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, + pFDCAN_TxBufferCompleteCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->TxBufferCompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Tx Buffer Complete FDCAN Callback + * Tx Buffer Complete FDCAN Callback is redirected to + * the weak HAL_FDCAN_TxBufferCompleteCallback() predefined callback + * @param hfdcan FDCAN handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->TxBufferCompleteCallback = HAL_FDCAN_TxBufferCompleteCallback; /* Legacy weak TxBufferCompleteCallback */ + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register Tx Buffer Abort FDCAN Callback + * To be used instead of the weak HAL_FDCAN_TxBufferAbortCallback() predefined callback + * @param hfdcan FDCAN handle + * @param pCallback pointer to the Tx Buffer Abort Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, + pFDCAN_TxBufferAbortCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->TxBufferAbortCallback = pCallback; + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Tx Buffer Abort FDCAN Callback + * Tx Buffer Abort FDCAN Callback is redirected to + * the weak HAL_FDCAN_TxBufferAbortCallback() predefined callback + * @param hfdcan FDCAN handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterTxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->TxBufferAbortCallback = HAL_FDCAN_TxBufferAbortCallback; /* Legacy weak TxBufferAbortCallback */ + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register Error Status FDCAN Callback + * To be used instead of the weak HAL_FDCAN_ErrorStatusCallback() predefined callback + * @param hfdcan FDCAN handle + * @param pCallback pointer to the Error Status Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_RegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, + pFDCAN_ErrorStatusCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->ErrorStatusCallback = pCallback; + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Error Status FDCAN Callback + * Error Status FDCAN Callback is redirected to the weak HAL_FDCAN_ErrorStatusCallback() predefined callback + * @param hfdcan FDCAN handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_UnRegisterErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + hfdcan->ErrorStatusCallback = HAL_FDCAN_ErrorStatusCallback; /* Legacy weak ErrorStatusCallback */ + } + else + { + /* Update the error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup FDCAN_Exported_Functions_Group2 Configuration functions + * @brief FDCAN Configuration functions. + * +@verbatim + ============================================================================== + ##### Configuration functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) HAL_FDCAN_ConfigFilter : Configure the FDCAN reception filters + (+) HAL_FDCAN_ConfigGlobalFilter : Configure the FDCAN global filter + (+) HAL_FDCAN_ConfigExtendedIdMask : Configure the extended ID mask + (+) HAL_FDCAN_ConfigRxFifoOverwrite : Configure the Rx FIFO operation mode + (+) HAL_FDCAN_ConfigRamWatchdog : Configure the RAM watchdog + (+) HAL_FDCAN_ConfigTimestampCounter : Configure the timestamp counter + (+) HAL_FDCAN_EnableTimestampCounter : Enable the timestamp counter + (+) HAL_FDCAN_DisableTimestampCounter : Disable the timestamp counter + (+) HAL_FDCAN_GetTimestampCounter : Get the timestamp counter value + (+) HAL_FDCAN_ResetTimestampCounter : Reset the timestamp counter to zero + (+) HAL_FDCAN_ConfigTimeoutCounter : Configure the timeout counter + (+) HAL_FDCAN_EnableTimeoutCounter : Enable the timeout counter + (+) HAL_FDCAN_DisableTimeoutCounter : Disable the timeout counter + (+) HAL_FDCAN_GetTimeoutCounter : Get the timeout counter value + (+) HAL_FDCAN_ResetTimeoutCounter : Reset the timeout counter to its start value + (+) HAL_FDCAN_ConfigTxDelayCompensation : Configure the transmitter delay compensation + (+) HAL_FDCAN_EnableTxDelayCompensation : Enable the transmitter delay compensation + (+) HAL_FDCAN_DisableTxDelayCompensation : Disable the transmitter delay compensation + (+) HAL_FDCAN_EnableISOMode : Enable ISO 11898-1 protocol mode + (+) HAL_FDCAN_DisableISOMode : Disable ISO 11898-1 protocol mode + (+) HAL_FDCAN_EnableEdgeFiltering : Enable edge filtering during bus integration + (+) HAL_FDCAN_DisableEdgeFiltering : Disable edge filtering during bus integration + +@endverbatim + * @{ + */ + +/** + * @brief Configure the FDCAN reception filter according to the specified + * parameters in the FDCAN_FilterTypeDef structure. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param sFilterConfig pointer to an FDCAN_FilterTypeDef structure that + * contains the filter configuration information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigFilter(FDCAN_HandleTypeDef *hfdcan, const FDCAN_FilterTypeDef *sFilterConfig) +{ + uint32_t FilterElementW1; + uint32_t FilterElementW2; + uint32_t *FilterAddress; + HAL_FDCAN_StateTypeDef state = hfdcan->State; + + if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) + { + /* Check function parameters */ + assert_param(IS_FDCAN_ID_TYPE(sFilterConfig->IdType)); + assert_param(IS_FDCAN_FILTER_CFG(sFilterConfig->FilterConfig)); + + if (sFilterConfig->IdType == FDCAN_STANDARD_ID) + { + /* Check function parameters */ + assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterIndex, (hfdcan->Init.StdFiltersNbr - 1U))); + assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID1, 0x7FFU)); + assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID2, 0x7FFU)); + assert_param(IS_FDCAN_STD_FILTER_TYPE(sFilterConfig->FilterType)); + + /* Build filter element */ + FilterElementW1 = ((sFilterConfig->FilterType << 30U) | + (sFilterConfig->FilterConfig << 27U) | + (sFilterConfig->FilterID1 << 16U) | + sFilterConfig->FilterID2); + + /* Calculate filter address */ + FilterAddress = (uint32_t *)(hfdcan->msgRam.StandardFilterSA + (sFilterConfig->FilterIndex * SRAMCAN_FLS_SIZE)); + + /* Write filter element to the message RAM */ + *FilterAddress = FilterElementW1; + } + else /* sFilterConfig->IdType == FDCAN_EXTENDED_ID */ + { + /* Check function parameters */ + assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterIndex, (hfdcan->Init.ExtFiltersNbr - 1U))); + assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID1, 0x1FFFFFFFU)); + assert_param(IS_FDCAN_MAX_VALUE(sFilterConfig->FilterID2, 0x1FFFFFFFU)); + assert_param(IS_FDCAN_EXT_FILTER_TYPE(sFilterConfig->FilterType)); + + /* Build first word of filter element */ + FilterElementW1 = ((sFilterConfig->FilterConfig << 29U) | sFilterConfig->FilterID1); + + /* Build second word of filter element */ + FilterElementW2 = ((sFilterConfig->FilterType << 30U) | sFilterConfig->FilterID2); + + /* Calculate filter address */ + FilterAddress = (uint32_t *)(hfdcan->msgRam.ExtendedFilterSA + (sFilterConfig->FilterIndex * SRAMCAN_FLE_SIZE)); + + /* Write filter element to the message RAM */ + *FilterAddress = FilterElementW1; + FilterAddress++; + *FilterAddress = FilterElementW2; + } + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; + + return HAL_ERROR; + } +} + +/** + * @brief Configure the FDCAN global filter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param NonMatchingStd Defines how received messages with 11-bit IDs that + * do not match any element of the filter list are treated. + * This parameter can be a value of @arg FDCAN_Non_Matching_Frames. + * @param NonMatchingExt Defines how received messages with 29-bit IDs that + * do not match any element of the filter list are treated. + * This parameter can be a value of @arg FDCAN_Non_Matching_Frames. + * @param RejectRemoteStd Filter or reject all the remote 11-bit IDs frames. + * This parameter can be a value of @arg FDCAN_Reject_Remote_Frames. + * @param RejectRemoteExt Filter or reject all the remote 29-bit IDs frames. + * This parameter can be a value of @arg FDCAN_Reject_Remote_Frames. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigGlobalFilter(FDCAN_HandleTypeDef *hfdcan, + uint32_t NonMatchingStd, + uint32_t NonMatchingExt, + uint32_t RejectRemoteStd, + uint32_t RejectRemoteExt) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_NON_MATCHING(NonMatchingStd)); + assert_param(IS_FDCAN_NON_MATCHING(NonMatchingExt)); + assert_param(IS_FDCAN_REJECT_REMOTE(RejectRemoteStd)); + assert_param(IS_FDCAN_REJECT_REMOTE(RejectRemoteExt)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Configure global filter */ + MODIFY_REG(hfdcan->Instance->RXGFC, (FDCAN_RXGFC_ANFS | + FDCAN_RXGFC_ANFE | + FDCAN_RXGFC_RRFS | + FDCAN_RXGFC_RRFE), + ((NonMatchingStd << FDCAN_RXGFC_ANFS_Pos) | + (NonMatchingExt << FDCAN_RXGFC_ANFE_Pos) | + (RejectRemoteStd << FDCAN_RXGFC_RRFS_Pos) | + (RejectRemoteExt << FDCAN_RXGFC_RRFE_Pos))); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Configure the extended ID mask. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param Mask Extended ID Mask. + * This parameter must be a number between 0 and 0x1FFFFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigExtendedIdMask(FDCAN_HandleTypeDef *hfdcan, uint32_t Mask) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_MAX_VALUE(Mask, 0x1FFFFFFFU)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Configure the extended ID mask */ + hfdcan->Instance->XIDAM = Mask; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Configure the Rx FIFO operation mode. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param RxFifo Rx FIFO. + * This parameter can be one of the following values: + * @arg FDCAN_RX_FIFO0: Rx FIFO 0 + * @arg FDCAN_RX_FIFO1: Rx FIFO 1 + * @param OperationMode operation mode. + * This parameter can be a value of @arg FDCAN_Rx_FIFO_operation_mode. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigRxFifoOverwrite(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo, uint32_t OperationMode) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_RX_FIFO(RxFifo)); + assert_param(IS_FDCAN_RX_FIFO_MODE(OperationMode)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + if (RxFifo == FDCAN_RX_FIFO0) + { + /* Select FIFO 0 Operation Mode */ + MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_F0OM, (OperationMode << FDCAN_RXGFC_F0OM_Pos)); + } + else /* RxFifo == FDCAN_RX_FIFO1 */ + { + /* Select FIFO 1 Operation Mode */ + MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_F1OM, (OperationMode << FDCAN_RXGFC_F1OM_Pos)); + } + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Configure the RAM watchdog. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param CounterStartValue Start value of the Message RAM Watchdog Counter, + * This parameter must be a number between 0x00 and 0xFF, + * with the reset value of 0x00 the counter is disabled. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigRamWatchdog(FDCAN_HandleTypeDef *hfdcan, uint32_t CounterStartValue) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_MAX_VALUE(CounterStartValue, 0xFFU)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Configure the RAM watchdog counter start value */ + MODIFY_REG(hfdcan->Instance->RWD, FDCAN_RWD_WDC, CounterStartValue); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Configure the timestamp counter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param TimestampPrescaler Timestamp Counter Prescaler. + * This parameter can be a value of @arg FDCAN_Timestamp_Prescaler. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampPrescaler) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_TIMESTAMP_PRESCALER(TimestampPrescaler)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Configure prescaler */ + MODIFY_REG(hfdcan->Instance->TSCC, FDCAN_TSCC_TCP, TimestampPrescaler); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Enable the timestamp counter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param TimestampOperation Timestamp counter operation. + * This parameter can be a value of @arg FDCAN_Timestamp. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_EnableTimestampCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimestampOperation) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_TIMESTAMP(TimestampOperation)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Enable timestamp counter */ + MODIFY_REG(hfdcan->Instance->TSCC, FDCAN_TSCC_TSS, TimestampOperation); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Disable the timestamp counter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DisableTimestampCounter(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Disable timestamp counter */ + CLEAR_BIT(hfdcan->Instance->TSCC, FDCAN_TSCC_TSS); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Get the timestamp counter value. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval Timestamp counter value + */ +uint16_t HAL_FDCAN_GetTimestampCounter(const FDCAN_HandleTypeDef *hfdcan) +{ + return (uint16_t)(hfdcan->Instance->TSCV); +} + +/** + * @brief Reset the timestamp counter to zero. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ResetTimestampCounter(FDCAN_HandleTypeDef *hfdcan) +{ + if ((hfdcan->Instance->TSCC & FDCAN_TSCC_TSS) != FDCAN_TIMESTAMP_EXTERNAL) + { + /* Reset timestamp counter. + Actually any write operation to TSCV clears the counter */ + CLEAR_REG(hfdcan->Instance->TSCV); + } + else + { + /* Update error code. + Unable to reset external counter */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_SUPPORTED; + + return HAL_ERROR; + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configure the timeout counter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param TimeoutOperation Timeout counter operation. + * This parameter can be a value of @arg FDCAN_Timeout_Operation. + * @param TimeoutPeriod Start value of the timeout down-counter. + * This parameter must be a number between 0x0000 and 0xFFFF + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigTimeoutCounter(FDCAN_HandleTypeDef *hfdcan, uint32_t TimeoutOperation, + uint32_t TimeoutPeriod) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_TIMEOUT(TimeoutOperation)); + assert_param(IS_FDCAN_MAX_VALUE(TimeoutPeriod, 0xFFFFU)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Select timeout operation and configure period */ + MODIFY_REG(hfdcan->Instance->TOCC, + (FDCAN_TOCC_TOS | FDCAN_TOCC_TOP), (TimeoutOperation | (TimeoutPeriod << FDCAN_TOCC_TOP_Pos))); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Enable the timeout counter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_EnableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Enable timeout counter */ + SET_BIT(hfdcan->Instance->TOCC, FDCAN_TOCC_ETOC); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Disable the timeout counter. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DisableTimeoutCounter(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Disable timeout counter */ + CLEAR_BIT(hfdcan->Instance->TOCC, FDCAN_TOCC_ETOC); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Get the timeout counter value. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval Timeout counter value + */ +uint16_t HAL_FDCAN_GetTimeoutCounter(const FDCAN_HandleTypeDef *hfdcan) +{ + return (uint16_t)(hfdcan->Instance->TOCV); +} + +/** + * @brief Reset the timeout counter to its start value. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ResetTimeoutCounter(FDCAN_HandleTypeDef *hfdcan) +{ + if ((hfdcan->Instance->TOCC & FDCAN_TOCC_TOS) == FDCAN_TIMEOUT_CONTINUOUS) + { + /* Reset timeout counter to start value */ + CLEAR_REG(hfdcan->Instance->TOCV); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code. + Unable to reset counter: controlled only by FIFO empty state */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_SUPPORTED; + + return HAL_ERROR; + } +} + +/** + * @brief Configure the transmitter delay compensation. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param TdcOffset Transmitter Delay Compensation Offset. + * This parameter must be a number between 0x00 and 0x7F. + * @param TdcFilter Transmitter Delay Compensation Filter Window Length. + * This parameter must be a number between 0x00 and 0x7F. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan, uint32_t TdcOffset, + uint32_t TdcFilter) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_MAX_VALUE(TdcOffset, 0x7FU)); + assert_param(IS_FDCAN_MAX_VALUE(TdcFilter, 0x7FU)); + + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Configure TDC offset and filter window */ + hfdcan->Instance->TDCR = ((TdcFilter << FDCAN_TDCR_TDCF_Pos) | (TdcOffset << FDCAN_TDCR_TDCO_Pos)); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Enable the transmitter delay compensation. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_EnableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Enable transmitter delay compensation */ + SET_BIT(hfdcan->Instance->DBTP, FDCAN_DBTP_TDC); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Disable the transmitter delay compensation. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DisableTxDelayCompensation(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Disable transmitter delay compensation */ + CLEAR_BIT(hfdcan->Instance->DBTP, FDCAN_DBTP_TDC); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Enable ISO 11898-1 protocol mode. + * CAN FD frame format is according to ISO 11898-1 standard. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_EnableISOMode(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Disable Non ISO protocol mode */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_NISO); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Disable ISO 11898-1 protocol mode. + * CAN FD frame format is according to Bosch CAN FD specification V1.0. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DisableISOMode(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Enable Non ISO protocol mode */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_NISO); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Enable edge filtering during bus integration. + * Two consecutive dominant tq are required to detect an edge for hard synchronization. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_EnableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Enable edge filtering */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_EFBI); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Disable edge filtering during bus integration. + * One dominant tq is required to detect an edge for hard synchronization. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DisableEdgeFiltering(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Disable edge filtering */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_EFBI); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @} + */ + +/** @defgroup FDCAN_Exported_Functions_Group3 Control functions + * @brief Control functions + * +@verbatim + ============================================================================== + ##### Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) HAL_FDCAN_Start : Start the FDCAN module + (+) HAL_FDCAN_Stop : Stop the FDCAN module and enable access to configuration registers + (+) HAL_FDCAN_AddMessageToTxFifoQ : Add a message to the Tx FIFO/Queue and activate the corresponding + transmission request + (+) HAL_FDCAN_GetLatestTxFifoQRequestBuffer : Get Tx buffer index of latest Tx FIFO/Queue request + (+) HAL_FDCAN_AbortTxRequest : Abort transmission request + (+) HAL_FDCAN_GetRxMessage : Get an FDCAN frame from the Rx FIFO zone into the message RAM + (+) HAL_FDCAN_GetTxEvent : Get an FDCAN Tx event from the Tx Event FIFO zone + into the message RAM + (+) HAL_FDCAN_GetHighPriorityMessageStatus : Get high priority message status + (+) HAL_FDCAN_GetProtocolStatus : Get protocol status + (+) HAL_FDCAN_GetErrorCounters : Get error counter values + (+) HAL_FDCAN_IsTxBufferMessagePending : Check if a transmission request is pending + on the selected Tx buffer + (+) HAL_FDCAN_GetRxFifoFillLevel : Return Rx FIFO fill level + (+) HAL_FDCAN_GetTxFifoFreeLevel : Return Tx FIFO free level + (+) HAL_FDCAN_IsRestrictedOperationMode : Check if the FDCAN peripheral entered Restricted Operation Mode + (+) HAL_FDCAN_ExitRestrictedOperationMode : Exit Restricted Operation Mode + +@endverbatim + * @{ + */ + +/** + * @brief Start the FDCAN module. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_Start(FDCAN_HandleTypeDef *hfdcan) +{ + if (hfdcan->State == HAL_FDCAN_STATE_READY) + { + /* Change FDCAN peripheral state */ + hfdcan->State = HAL_FDCAN_STATE_BUSY; + + /* Request leave initialisation */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); + + /* Reset the FDCAN ErrorCode */ + hfdcan->ErrorCode = HAL_FDCAN_ERROR_NONE; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_READY; + + return HAL_ERROR; + } +} + +/** + * @brief Stop the FDCAN module and enable access to configuration registers. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_Stop(FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t Counter = 0U; + + if (hfdcan->State == HAL_FDCAN_STATE_BUSY) + { + /* Request initialisation */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_INIT); + + /* Wait until the INIT bit into CCCR register is set */ + while ((hfdcan->Instance->CCCR & FDCAN_CCCR_INIT) == 0U) + { + /* Check for the Timeout */ + if (Counter > FDCAN_TIMEOUT_VALUE) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_ERROR; + + return HAL_ERROR; + } + + /* Increment counter */ + Counter++; + } + + /* Reset counter */ + Counter = 0U; + + /* Exit from Sleep mode */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CSR); + + /* Wait until FDCAN exits sleep mode */ + while ((hfdcan->Instance->CCCR & FDCAN_CCCR_CSA) == FDCAN_CCCR_CSA) + { + /* Check for the Timeout */ + if (Counter > FDCAN_TIMEOUT_VALUE) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_TIMEOUT; + + /* Change FDCAN state */ + hfdcan->State = HAL_FDCAN_STATE_ERROR; + + return HAL_ERROR; + } + + /* Increment counter */ + Counter++; + } + + /* Enable configuration change */ + SET_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_CCE); + + /* Reset Latest Tx FIFO/Queue Request Buffer Index */ + hfdcan->LatestTxFifoQRequest = 0U; + + /* Change FDCAN peripheral state */ + hfdcan->State = HAL_FDCAN_STATE_READY; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; + + return HAL_ERROR; + } +} + +/** + * @brief Add a message to the Tx FIFO/Queue and activate the corresponding transmission request + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param pTxHeader pointer to a FDCAN_TxHeaderTypeDef structure. + * @param pTxData pointer to a buffer containing the payload of the Tx frame. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_AddMessageToTxFifoQ(FDCAN_HandleTypeDef *hfdcan, const FDCAN_TxHeaderTypeDef *pTxHeader, + const uint8_t *pTxData) +{ + uint32_t PutIndex; + + /* Check function parameters */ + assert_param(IS_FDCAN_ID_TYPE(pTxHeader->IdType)); + if (pTxHeader->IdType == FDCAN_STANDARD_ID) + { + assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->Identifier, 0x7FFU)); + } + else /* pTxHeader->IdType == FDCAN_EXTENDED_ID */ + { + assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->Identifier, 0x1FFFFFFFU)); + } + assert_param(IS_FDCAN_FRAME_TYPE(pTxHeader->TxFrameType)); + assert_param(IS_FDCAN_DLC(pTxHeader->DataLength)); + assert_param(IS_FDCAN_ESI(pTxHeader->ErrorStateIndicator)); + assert_param(IS_FDCAN_BRS(pTxHeader->BitRateSwitch)); + assert_param(IS_FDCAN_FDF(pTxHeader->FDFormat)); + assert_param(IS_FDCAN_EFC(pTxHeader->TxEventFifoControl)); + assert_param(IS_FDCAN_MAX_VALUE(pTxHeader->MessageMarker, 0xFFU)); + + if (hfdcan->State == HAL_FDCAN_STATE_BUSY) + { + /* Check that the Tx FIFO/Queue is not full */ + if ((hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFQF) != 0U) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_FULL; + + return HAL_ERROR; + } + else + { + /* Retrieve the Tx FIFO PutIndex */ + PutIndex = ((hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFQPI) >> FDCAN_TXFQS_TFQPI_Pos); + + /* Add the message to the Tx FIFO/Queue */ + FDCAN_CopyMessageToRAM(hfdcan, pTxHeader, pTxData, PutIndex); + + /* Activate the corresponding transmission request */ + hfdcan->Instance->TXBAR = ((uint32_t)1 << PutIndex); + + /* Store the Latest Tx FIFO/Queue Request Buffer Index */ + hfdcan->LatestTxFifoQRequest = ((uint32_t)1 << PutIndex); + } + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; + + return HAL_ERROR; + } +} + +/** + * @brief Get Tx buffer index of latest Tx FIFO/Queue request + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval Tx buffer index of last Tx FIFO/Queue request + * - Any value of @arg FDCAN_Tx_location if Tx request has been submitted. + * - 0 if no Tx FIFO/Queue request have been submitted. + */ +uint32_t HAL_FDCAN_GetLatestTxFifoQRequestBuffer(const FDCAN_HandleTypeDef *hfdcan) +{ + /* Return Last Tx FIFO/Queue Request Buffer */ + return hfdcan->LatestTxFifoQRequest; +} + +/** + * @brief Abort transmission request + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param BufferIndex buffer index. + * This parameter can be any combination of @arg FDCAN_Tx_location. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_AbortTxRequest(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndex) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_TX_LOCATION_LIST(BufferIndex)); + + if (hfdcan->State == HAL_FDCAN_STATE_BUSY) + { + /* Add cancellation request */ + hfdcan->Instance->TXBCR = BufferIndex; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; + + return HAL_ERROR; + } +} + +/** + * @brief Get an FDCAN frame from the Rx FIFO zone into the message RAM. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param RxLocation Location of the received message to be read. + * This parameter can be a value of @arg FDCAN_Rx_location. + * @param pRxHeader pointer to a FDCAN_RxHeaderTypeDef structure. + * @param pRxData pointer to a buffer where the payload of the Rx frame will be stored. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_GetRxMessage(FDCAN_HandleTypeDef *hfdcan, uint32_t RxLocation, + FDCAN_RxHeaderTypeDef *pRxHeader, uint8_t *pRxData) +{ + uint32_t *RxAddress; + uint8_t *pData; + uint32_t ByteCounter; + uint32_t GetIndex = 0; + HAL_FDCAN_StateTypeDef state = hfdcan->State; + + /* Check function parameters */ + assert_param(IS_FDCAN_RX_FIFO(RxLocation)); + + if (state == HAL_FDCAN_STATE_BUSY) + { + if (RxLocation == FDCAN_RX_FIFO0) /* Rx element is assigned to the Rx FIFO 0 */ + { + /* Check that the Rx FIFO 0 is not empty */ + if ((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0FL) == 0U) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY; + + return HAL_ERROR; + } + else + { + /* Check that the Rx FIFO 0 is full & overwrite mode is on */ + if (((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0F) >> FDCAN_RXF0S_F0F_Pos) == 1U) + { + if (((hfdcan->Instance->RXGFC & FDCAN_RXGFC_F0OM) >> FDCAN_RXGFC_F0OM_Pos) == FDCAN_RX_FIFO_OVERWRITE) + { + /* When overwrite status is on discard first message in FIFO */ + GetIndex = 1U; + } + } + + /* Calculate Rx FIFO 0 element index */ + GetIndex += ((hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0GI) >> FDCAN_RXF0S_F0GI_Pos); + + /* Calculate Rx FIFO 0 element address */ + RxAddress = (uint32_t *)(hfdcan->msgRam.RxFIFO0SA + (GetIndex * SRAMCAN_RF0_SIZE)); + } + } + else /* Rx element is assigned to the Rx FIFO 1 */ + { + /* Check that the Rx FIFO 1 is not empty */ + if ((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1FL) == 0U) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY; + + return HAL_ERROR; + } + else + { + /* Check that the Rx FIFO 1 is full & overwrite mode is on */ + if (((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1F) >> FDCAN_RXF1S_F1F_Pos) == 1U) + { + if (((hfdcan->Instance->RXGFC & FDCAN_RXGFC_F1OM) >> FDCAN_RXGFC_F1OM_Pos) == FDCAN_RX_FIFO_OVERWRITE) + { + /* When overwrite status is on discard first message in FIFO */ + GetIndex = 1U; + } + } + + /* Calculate Rx FIFO 1 element index */ + GetIndex += ((hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1GI) >> FDCAN_RXF1S_F1GI_Pos); + /* Calculate Rx FIFO 1 element address */ + RxAddress = (uint32_t *)(hfdcan->msgRam.RxFIFO1SA + (GetIndex * SRAMCAN_RF1_SIZE)); + } + } + + /* Retrieve IdType */ + pRxHeader->IdType = *RxAddress & FDCAN_ELEMENT_MASK_XTD; + + /* Retrieve Identifier */ + if (pRxHeader->IdType == FDCAN_STANDARD_ID) /* Standard ID element */ + { + pRxHeader->Identifier = ((*RxAddress & FDCAN_ELEMENT_MASK_STDID) >> 18U); + } + else /* Extended ID element */ + { + pRxHeader->Identifier = (*RxAddress & FDCAN_ELEMENT_MASK_EXTID); + } + + /* Retrieve RxFrameType */ + pRxHeader->RxFrameType = (*RxAddress & FDCAN_ELEMENT_MASK_RTR); + + /* Retrieve ErrorStateIndicator */ + pRxHeader->ErrorStateIndicator = (*RxAddress & FDCAN_ELEMENT_MASK_ESI); + + /* Increment RxAddress pointer to second word of Rx FIFO element */ + RxAddress++; + + /* Retrieve RxTimestamp */ + pRxHeader->RxTimestamp = (*RxAddress & FDCAN_ELEMENT_MASK_TS); + + /* Retrieve DataLength */ + pRxHeader->DataLength = ((*RxAddress & FDCAN_ELEMENT_MASK_DLC) >> 16U); + + /* Retrieve BitRateSwitch */ + pRxHeader->BitRateSwitch = (*RxAddress & FDCAN_ELEMENT_MASK_BRS); + + /* Retrieve FDFormat */ + pRxHeader->FDFormat = (*RxAddress & FDCAN_ELEMENT_MASK_FDF); + + /* Retrieve FilterIndex */ + pRxHeader->FilterIndex = ((*RxAddress & FDCAN_ELEMENT_MASK_FIDX) >> 24U); + + /* Retrieve NonMatchingFrame */ + pRxHeader->IsFilterMatchingFrame = ((*RxAddress & FDCAN_ELEMENT_MASK_ANMF) >> 31U); + + /* Increment RxAddress pointer to payload of Rx FIFO element */ + RxAddress++; + + /* Retrieve Rx payload */ + pData = (uint8_t *)RxAddress; + for (ByteCounter = 0; ByteCounter < DLCtoBytes[pRxHeader->DataLength]; ByteCounter++) + { + pRxData[ByteCounter] = pData[ByteCounter]; + } + + if (RxLocation == FDCAN_RX_FIFO0) /* Rx element is assigned to the Rx FIFO 0 */ + { + /* Acknowledge the Rx FIFO 0 that the oldest element is read so that it increments the GetIndex */ + hfdcan->Instance->RXF0A = GetIndex; + } + else /* Rx element is assigned to the Rx FIFO 1 */ + { + /* Acknowledge the Rx FIFO 1 that the oldest element is read so that it increments the GetIndex */ + hfdcan->Instance->RXF1A = GetIndex; + } + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; + + return HAL_ERROR; + } +} + +/** + * @brief Get an FDCAN Tx event from the Tx Event FIFO zone into the message RAM. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param pTxEvent pointer to a FDCAN_TxEventFifoTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_GetTxEvent(FDCAN_HandleTypeDef *hfdcan, FDCAN_TxEventFifoTypeDef *pTxEvent) +{ + uint32_t *TxEventAddress; + uint32_t GetIndex; + HAL_FDCAN_StateTypeDef state = hfdcan->State; + + if (state == HAL_FDCAN_STATE_BUSY) + { + /* Check that the Tx event FIFO is not empty */ + if ((hfdcan->Instance->TXEFS & FDCAN_TXEFS_EFFL) == 0U) + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_FIFO_EMPTY; + + return HAL_ERROR; + } + + /* Calculate Tx event FIFO element address */ + GetIndex = ((hfdcan->Instance->TXEFS & FDCAN_TXEFS_EFGI) >> FDCAN_TXEFS_EFGI_Pos); + TxEventAddress = (uint32_t *)(hfdcan->msgRam.TxEventFIFOSA + (GetIndex * SRAMCAN_TEF_SIZE)); + + /* Retrieve IdType */ + pTxEvent->IdType = *TxEventAddress & FDCAN_ELEMENT_MASK_XTD; + + /* Retrieve Identifier */ + if (pTxEvent->IdType == FDCAN_STANDARD_ID) /* Standard ID element */ + { + pTxEvent->Identifier = ((*TxEventAddress & FDCAN_ELEMENT_MASK_STDID) >> 18U); + } + else /* Extended ID element */ + { + pTxEvent->Identifier = (*TxEventAddress & FDCAN_ELEMENT_MASK_EXTID); + } + + /* Retrieve TxFrameType */ + pTxEvent->TxFrameType = (*TxEventAddress & FDCAN_ELEMENT_MASK_RTR); + + /* Retrieve ErrorStateIndicator */ + pTxEvent->ErrorStateIndicator = (*TxEventAddress & FDCAN_ELEMENT_MASK_ESI); + + /* Increment TxEventAddress pointer to second word of Tx Event FIFO element */ + TxEventAddress++; + + /* Retrieve TxTimestamp */ + pTxEvent->TxTimestamp = (*TxEventAddress & FDCAN_ELEMENT_MASK_TS); + + /* Retrieve DataLength */ + pTxEvent->DataLength = ((*TxEventAddress & FDCAN_ELEMENT_MASK_DLC) >> 16U); + + /* Retrieve BitRateSwitch */ + pTxEvent->BitRateSwitch = (*TxEventAddress & FDCAN_ELEMENT_MASK_BRS); + + /* Retrieve FDFormat */ + pTxEvent->FDFormat = (*TxEventAddress & FDCAN_ELEMENT_MASK_FDF); + + /* Retrieve EventType */ + pTxEvent->EventType = (*TxEventAddress & FDCAN_ELEMENT_MASK_ET); + + /* Retrieve MessageMarker */ + pTxEvent->MessageMarker = ((*TxEventAddress & FDCAN_ELEMENT_MASK_MM) >> 24U); + + /* Acknowledge the Tx Event FIFO that the oldest element is read so that it increments the GetIndex */ + hfdcan->Instance->TXEFA = GetIndex; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_STARTED; + + return HAL_ERROR; + } +} + +/** + * @brief Get high priority message status. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param HpMsgStatus pointer to an FDCAN_HpMsgStatusTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_GetHighPriorityMessageStatus(const FDCAN_HandleTypeDef *hfdcan, + FDCAN_HpMsgStatusTypeDef *HpMsgStatus) +{ + HpMsgStatus->FilterList = ((hfdcan->Instance->HPMS & FDCAN_HPMS_FLST) >> FDCAN_HPMS_FLST_Pos); + HpMsgStatus->FilterIndex = ((hfdcan->Instance->HPMS & FDCAN_HPMS_FIDX) >> FDCAN_HPMS_FIDX_Pos); + HpMsgStatus->MessageStorage = (hfdcan->Instance->HPMS & FDCAN_HPMS_MSI); + HpMsgStatus->MessageIndex = (hfdcan->Instance->HPMS & FDCAN_HPMS_BIDX); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Get protocol status. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param ProtocolStatus pointer to an FDCAN_ProtocolStatusTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_GetProtocolStatus(const FDCAN_HandleTypeDef *hfdcan, + FDCAN_ProtocolStatusTypeDef *ProtocolStatus) +{ + uint32_t StatusReg; + + /* Read the protocol status register */ + StatusReg = READ_REG(hfdcan->Instance->PSR); + + /* Fill the protocol status structure */ + ProtocolStatus->LastErrorCode = (StatusReg & FDCAN_PSR_LEC); + ProtocolStatus->DataLastErrorCode = ((StatusReg & FDCAN_PSR_DLEC) >> FDCAN_PSR_DLEC_Pos); + ProtocolStatus->Activity = (StatusReg & FDCAN_PSR_ACT); + ProtocolStatus->ErrorPassive = ((StatusReg & FDCAN_PSR_EP) >> FDCAN_PSR_EP_Pos); + ProtocolStatus->Warning = ((StatusReg & FDCAN_PSR_EW) >> FDCAN_PSR_EW_Pos); + ProtocolStatus->BusOff = ((StatusReg & FDCAN_PSR_BO) >> FDCAN_PSR_BO_Pos); + ProtocolStatus->RxESIflag = ((StatusReg & FDCAN_PSR_RESI) >> FDCAN_PSR_RESI_Pos); + ProtocolStatus->RxBRSflag = ((StatusReg & FDCAN_PSR_RBRS) >> FDCAN_PSR_RBRS_Pos); + ProtocolStatus->RxFDFflag = ((StatusReg & FDCAN_PSR_REDL) >> FDCAN_PSR_REDL_Pos); + ProtocolStatus->ProtocolException = ((StatusReg & FDCAN_PSR_PXE) >> FDCAN_PSR_PXE_Pos); + ProtocolStatus->TDCvalue = ((StatusReg & FDCAN_PSR_TDCV) >> FDCAN_PSR_TDCV_Pos); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Get error counter values. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param ErrorCounters pointer to an FDCAN_ErrorCountersTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_GetErrorCounters(const FDCAN_HandleTypeDef *hfdcan, + FDCAN_ErrorCountersTypeDef *ErrorCounters) +{ + uint32_t CountersReg; + + /* Read the error counters register */ + CountersReg = READ_REG(hfdcan->Instance->ECR); + + /* Fill the error counters structure */ + ErrorCounters->TxErrorCnt = ((CountersReg & FDCAN_ECR_TEC) >> FDCAN_ECR_TEC_Pos); + ErrorCounters->RxErrorCnt = ((CountersReg & FDCAN_ECR_REC) >> FDCAN_ECR_REC_Pos); + ErrorCounters->RxErrorPassive = ((CountersReg & FDCAN_ECR_RP) >> FDCAN_ECR_RP_Pos); + ErrorCounters->ErrorLogging = ((CountersReg & FDCAN_ECR_CEL) >> FDCAN_ECR_CEL_Pos); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Check if a transmission request is pending on the selected Tx buffer. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param TxBufferIndex Tx buffer index. + * This parameter can be any combination of @arg FDCAN_Tx_location. + * @retval Status + * - 0 : No pending transmission request on TxBufferIndex list. + * - 1 : Pending transmission request on TxBufferIndex. + */ +uint32_t HAL_FDCAN_IsTxBufferMessagePending(const FDCAN_HandleTypeDef *hfdcan, uint32_t TxBufferIndex) +{ + /* Check function parameters */ + assert_param(IS_FDCAN_TX_LOCATION_LIST(TxBufferIndex)); + + /* Check pending transmission request on the selected buffer */ + if ((hfdcan->Instance->TXBRP & TxBufferIndex) == 0U) + { + return 0; + } + return 1; +} + +/** + * @brief Return Rx FIFO fill level. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param RxFifo Rx FIFO. + * This parameter can be one of the following values: + * @arg FDCAN_RX_FIFO0: Rx FIFO 0 + * @arg FDCAN_RX_FIFO1: Rx FIFO 1 + * @retval Rx FIFO fill level. + */ +uint32_t HAL_FDCAN_GetRxFifoFillLevel(const FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo) +{ + uint32_t FillLevel; + + /* Check function parameters */ + assert_param(IS_FDCAN_RX_FIFO(RxFifo)); + + if (RxFifo == FDCAN_RX_FIFO0) + { + FillLevel = hfdcan->Instance->RXF0S & FDCAN_RXF0S_F0FL; + } + else /* RxFifo == FDCAN_RX_FIFO1 */ + { + FillLevel = hfdcan->Instance->RXF1S & FDCAN_RXF1S_F1FL; + } + + /* Return Rx FIFO fill level */ + return FillLevel; +} + +/** + * @brief Return Tx FIFO free level: number of consecutive free Tx FIFO + * elements starting from Tx FIFO GetIndex. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval Tx FIFO free level. + */ +uint32_t HAL_FDCAN_GetTxFifoFreeLevel(const FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t FreeLevel; + + FreeLevel = hfdcan->Instance->TXFQS & FDCAN_TXFQS_TFFL; + + /* Return Tx FIFO free level */ + return FreeLevel; +} + +/** + * @brief Check if the FDCAN peripheral entered Restricted Operation Mode. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval Status + * - 0 : Normal FDCAN operation. + * - 1 : Restricted Operation Mode active. + */ +uint32_t HAL_FDCAN_IsRestrictedOperationMode(const FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t OperationMode; + + /* Get Operation Mode */ + OperationMode = ((hfdcan->Instance->CCCR & FDCAN_CCCR_ASM) >> FDCAN_CCCR_ASM_Pos); + + return OperationMode; +} + +/** + * @brief Exit Restricted Operation Mode. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ExitRestrictedOperationMode(FDCAN_HandleTypeDef *hfdcan) +{ + HAL_FDCAN_StateTypeDef state = hfdcan->State; + + if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) + { + /* Exit Restricted Operation mode */ + CLEAR_BIT(hfdcan->Instance->CCCR, FDCAN_CCCR_ASM); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; + + return HAL_ERROR; + } +} + +/** + * @} + */ + +/** @defgroup FDCAN_Exported_Functions_Group4 Interrupts management + * @brief Interrupts management + * +@verbatim + ============================================================================== + ##### Interrupts management ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) HAL_FDCAN_ConfigInterruptLines : Assign interrupts to either Interrupt line 0 or 1 + (+) HAL_FDCAN_ActivateNotification : Enable interrupts + (+) HAL_FDCAN_DeactivateNotification : Disable interrupts + (+) HAL_FDCAN_IRQHandler : Handles FDCAN interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Assign interrupts to either Interrupt line 0 or 1. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param ITList indicates which interrupts group will be assigned to the selected interrupt line. + * This parameter can be any combination of @arg FDCAN_Interrupts_Group. + * @param InterruptLine Interrupt line. + * This parameter can be a value of @arg FDCAN_Interrupt_Line. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ConfigInterruptLines(FDCAN_HandleTypeDef *hfdcan, uint32_t ITList, uint32_t InterruptLine) +{ + HAL_FDCAN_StateTypeDef state = hfdcan->State; + + /* Check function parameters */ + assert_param(IS_FDCAN_IT_GROUP(ITList)); + assert_param(IS_FDCAN_IT_LINE(InterruptLine)); + + if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) + { + /* Assign list of interrupts to the selected line */ + if (InterruptLine == FDCAN_INTERRUPT_LINE0) + { + CLEAR_BIT(hfdcan->Instance->ILS, ITList); + } + else /* InterruptLine == FDCAN_INTERRUPT_LINE1 */ + { + SET_BIT(hfdcan->Instance->ILS, ITList); + } + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; + + return HAL_ERROR; + } +} + +/** + * @brief Enable interrupts. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param ActiveITs indicates which interrupts will be enabled. + * This parameter can be any combination of @arg FDCAN_Interrupts. + * @param BufferIndexes Tx Buffer Indexes. + * This parameter can be any combination of @arg FDCAN_Tx_location. + * This parameter is ignored if ActiveITs does not include one of the following: + * - FDCAN_IT_TX_COMPLETE + * - FDCAN_IT_TX_ABORT_COMPLETE + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_ActivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t ActiveITs, + uint32_t BufferIndexes) +{ + HAL_FDCAN_StateTypeDef state = hfdcan->State; + uint32_t ITs_lines_selection; + + /* Check function parameters */ + assert_param(IS_FDCAN_IT(ActiveITs)); + if ((ActiveITs & (FDCAN_IT_TX_COMPLETE | FDCAN_IT_TX_ABORT_COMPLETE)) != 0U) + { + assert_param(IS_FDCAN_TX_LOCATION_LIST(BufferIndexes)); + } + + if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) + { + /* Get interrupts line selection */ + ITs_lines_selection = hfdcan->Instance->ILS; + + /* Enable Interrupt lines */ + if ((((ActiveITs & FDCAN_IT_LIST_RX_FIFO0) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) == 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_RX_FIFO1) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) == 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_SMSG) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) == 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) == 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_MISC) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) == 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) == 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) == 0U))) + { + /* Enable Interrupt line 0 */ + SET_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE0); + } + if ((((ActiveITs & FDCAN_IT_LIST_RX_FIFO0) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) != 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_RX_FIFO1) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) != 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_SMSG) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) != 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) != 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_MISC) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) != 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) != 0U)) || \ + (((ActiveITs & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) != 0U))) + { + /* Enable Interrupt line 1 */ + SET_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE1); + } + + if ((ActiveITs & FDCAN_IT_TX_COMPLETE) != 0U) + { + /* Enable Tx Buffer Transmission Interrupt to set TC flag in IR register, + but interrupt will only occur if TC is enabled in IE register */ + SET_BIT(hfdcan->Instance->TXBTIE, BufferIndexes); + } + + if ((ActiveITs & FDCAN_IT_TX_ABORT_COMPLETE) != 0U) + { + /* Enable Tx Buffer Cancellation Finished Interrupt to set TCF flag in IR register, + but interrupt will only occur if TCF is enabled in IE register */ + SET_BIT(hfdcan->Instance->TXBCIE, BufferIndexes); + } + + /* Enable the selected interrupts */ + __HAL_FDCAN_ENABLE_IT(hfdcan, ActiveITs); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; + + return HAL_ERROR; + } +} + +/** + * @brief Disable interrupts. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param InactiveITs indicates which interrupts will be disabled. + * This parameter can be any combination of @arg FDCAN_Interrupts. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FDCAN_DeactivateNotification(FDCAN_HandleTypeDef *hfdcan, uint32_t InactiveITs) +{ + HAL_FDCAN_StateTypeDef state = hfdcan->State; + uint32_t ITs_enabled; + uint32_t ITs_lines_selection; + + /* Check function parameters */ + assert_param(IS_FDCAN_IT(InactiveITs)); + + if ((state == HAL_FDCAN_STATE_READY) || (state == HAL_FDCAN_STATE_BUSY)) + { + /* Disable the selected interrupts */ + __HAL_FDCAN_DISABLE_IT(hfdcan, InactiveITs); + + if ((InactiveITs & FDCAN_IT_TX_COMPLETE) != 0U) + { + /* Disable Tx Buffer Transmission Interrupts */ + CLEAR_REG(hfdcan->Instance->TXBTIE); + } + + if ((InactiveITs & FDCAN_IT_TX_ABORT_COMPLETE) != 0U) + { + /* Disable Tx Buffer Cancellation Finished Interrupt */ + CLEAR_REG(hfdcan->Instance->TXBCIE); + } + + /* Get interrupts enabled and interrupts line selection */ + ITs_enabled = hfdcan->Instance->IE; + ITs_lines_selection = hfdcan->Instance->ILS; + + /* Check if some interrupts are still enabled on interrupt line 0 */ + if ((((ITs_enabled & FDCAN_IT_LIST_RX_FIFO0) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) == 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_RX_FIFO1) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) == 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_SMSG) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) == 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) == 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_MISC) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) == 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) == 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) == 0U))) + { + /* Do nothing */ + } + else /* no more interrupts enabled on interrupt line 0 */ + { + /* Disable interrupt line 0 */ + CLEAR_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE0); + } + + /* Check if some interrupts are still enabled on interrupt line 1 */ + if ((((ITs_enabled & FDCAN_IT_LIST_RX_FIFO0) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO0) != 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_RX_FIFO1) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_RX_FIFO1) != 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_SMSG) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_SMSG) != 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_TX_FIFO_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_TX_FIFO_ERROR) != 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_MISC) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_MISC) != 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_BIT_LINE_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_BIT_LINE_ERROR) != 0U)) || \ + (((ITs_enabled & FDCAN_IT_LIST_PROTOCOL_ERROR) != 0U) + && (((ITs_lines_selection) & FDCAN_IT_GROUP_PROTOCOL_ERROR) != 0U))) + { + /* Do nothing */ + } + else /* no more interrupts enabled on interrupt line 1 */ + { + /* Disable interrupt line 1 */ + CLEAR_BIT(hfdcan->Instance->ILE, FDCAN_INTERRUPT_LINE1); + } + + /* Return function status */ + return HAL_OK; + } + else + { + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_NOT_INITIALIZED; + + return HAL_ERROR; + } +} + +/** + * @brief Handles FDCAN interrupt request. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL status + */ +void HAL_FDCAN_IRQHandler(FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t TxEventFifoITs; + uint32_t RxFifo0ITs; + uint32_t RxFifo1ITs; + uint32_t Errors; + uint32_t ErrorStatusITs; + uint32_t TransmittedBuffers; + uint32_t AbortedBuffers; + uint32_t itsource; + uint32_t itflag; + + TxEventFifoITs = hfdcan->Instance->IR & FDCAN_TX_EVENT_FIFO_MASK; + TxEventFifoITs &= hfdcan->Instance->IE; + RxFifo0ITs = hfdcan->Instance->IR & FDCAN_RX_FIFO0_MASK; + RxFifo0ITs &= hfdcan->Instance->IE; + RxFifo1ITs = hfdcan->Instance->IR & FDCAN_RX_FIFO1_MASK; + RxFifo1ITs &= hfdcan->Instance->IE; + Errors = hfdcan->Instance->IR & FDCAN_ERROR_MASK; + Errors &= hfdcan->Instance->IE; + ErrorStatusITs = hfdcan->Instance->IR & FDCAN_ERROR_STATUS_MASK; + ErrorStatusITs &= hfdcan->Instance->IE; + itsource = hfdcan->Instance->IE; + itflag = hfdcan->Instance->IR; + + /* High Priority Message interrupt management *******************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_RX_HIGH_PRIORITY_MSG) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_RX_HIGH_PRIORITY_MSG) != RESET) + { + /* Clear the High Priority Message flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_RX_HIGH_PRIORITY_MSG); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->HighPriorityMessageCallback(hfdcan); +#else + /* High Priority Message Callback */ + HAL_FDCAN_HighPriorityMessageCallback(hfdcan); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + } + + /* Transmission Abort interrupt management **********************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TX_ABORT_COMPLETE) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TX_ABORT_COMPLETE) != RESET) + { + /* List of aborted monitored buffers */ + AbortedBuffers = hfdcan->Instance->TXBCF; + AbortedBuffers &= hfdcan->Instance->TXBCIE; + + /* Clear the Transmission Cancellation flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_ABORT_COMPLETE); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->TxBufferAbortCallback(hfdcan, AbortedBuffers); +#else + /* Transmission Cancellation Callback */ + HAL_FDCAN_TxBufferAbortCallback(hfdcan, AbortedBuffers); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + } + + /* Tx event FIFO interrupts management **************************************/ + if (TxEventFifoITs != 0U) + { + /* Clear the Tx Event FIFO flags */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, TxEventFifoITs); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->TxEventFifoCallback(hfdcan, TxEventFifoITs); +#else + /* Tx Event FIFO Callback */ + HAL_FDCAN_TxEventFifoCallback(hfdcan, TxEventFifoITs); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + + /* Rx FIFO 0 interrupts management ******************************************/ + if (RxFifo0ITs != 0U) + { + /* Clear the Rx FIFO 0 flags */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, RxFifo0ITs); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->RxFifo0Callback(hfdcan, RxFifo0ITs); +#else + /* Rx FIFO 0 Callback */ + HAL_FDCAN_RxFifo0Callback(hfdcan, RxFifo0ITs); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + + /* Rx FIFO 1 interrupts management ******************************************/ + if (RxFifo1ITs != 0U) + { + /* Clear the Rx FIFO 1 flags */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, RxFifo1ITs); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->RxFifo1Callback(hfdcan, RxFifo1ITs); +#else + /* Rx FIFO 1 Callback */ + HAL_FDCAN_RxFifo1Callback(hfdcan, RxFifo1ITs); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + + /* Tx FIFO empty interrupt management ***************************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TX_FIFO_EMPTY) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TX_FIFO_EMPTY) != RESET) + { + /* Clear the Tx FIFO empty flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_FIFO_EMPTY); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->TxFifoEmptyCallback(hfdcan); +#else + /* Tx FIFO empty Callback */ + HAL_FDCAN_TxFifoEmptyCallback(hfdcan); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + } + + /* Transmission Complete interrupt management *******************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TX_COMPLETE) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TX_COMPLETE) != RESET) + { + /* List of transmitted monitored buffers */ + TransmittedBuffers = hfdcan->Instance->TXBTO; + TransmittedBuffers &= hfdcan->Instance->TXBTIE; + + /* Clear the Transmission Complete flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TX_COMPLETE); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->TxBufferCompleteCallback(hfdcan, TransmittedBuffers); +#else + /* Transmission Complete Callback */ + HAL_FDCAN_TxBufferCompleteCallback(hfdcan, TransmittedBuffers); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + } + + /* Timestamp Wraparound interrupt management ********************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TIMESTAMP_WRAPAROUND) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TIMESTAMP_WRAPAROUND) != RESET) + { + /* Clear the Timestamp Wraparound flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TIMESTAMP_WRAPAROUND); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->TimestampWraparoundCallback(hfdcan); +#else + /* Timestamp Wraparound Callback */ + HAL_FDCAN_TimestampWraparoundCallback(hfdcan); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + } + + /* Timeout Occurred interrupt management ************************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_TIMEOUT_OCCURRED) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_TIMEOUT_OCCURRED) != RESET) + { + /* Clear the Timeout Occurred flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_TIMEOUT_OCCURRED); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->TimeoutOccurredCallback(hfdcan); +#else + /* Timeout Occurred Callback */ + HAL_FDCAN_TimeoutOccurredCallback(hfdcan); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + } + + /* Message RAM access failure interrupt management **************************/ + if (FDCAN_CHECK_FLAG(itflag, FDCAN_FLAG_RAM_ACCESS_FAILURE) != RESET) + { + if (FDCAN_CHECK_IT_SOURCE(itsource, FDCAN_IT_RAM_ACCESS_FAILURE) != RESET) + { + /* Clear the Message RAM access failure flag */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, FDCAN_FLAG_RAM_ACCESS_FAILURE); + + /* Update error code */ + hfdcan->ErrorCode |= HAL_FDCAN_ERROR_RAM_ACCESS; + } + } + + /* Error Status interrupts management ***************************************/ + if (ErrorStatusITs != 0U) + { + /* Clear the Error flags */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, ErrorStatusITs); + +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->ErrorStatusCallback(hfdcan, ErrorStatusITs); +#else + /* Error Status Callback */ + HAL_FDCAN_ErrorStatusCallback(hfdcan, ErrorStatusITs); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } + + /* Error interrupts management **********************************************/ + if (Errors != 0U) + { + /* Clear the Error flags */ + __HAL_FDCAN_CLEAR_FLAG(hfdcan, Errors); + + /* Update error code */ + hfdcan->ErrorCode |= Errors; + } + + if (hfdcan->ErrorCode != HAL_FDCAN_ERROR_NONE) + { +#if USE_HAL_FDCAN_REGISTER_CALLBACKS == 1 + /* Call registered callback*/ + hfdcan->ErrorCallback(hfdcan); +#else + /* Error Callback */ + HAL_FDCAN_ErrorCallback(hfdcan); +#endif /* USE_HAL_FDCAN_REGISTER_CALLBACKS */ + } +} + +/** + * @} + */ + +/** @defgroup FDCAN_Exported_Functions_Group5 Callback functions + * @brief FDCAN Callback functions + * +@verbatim + ============================================================================== + ##### Callback functions ##### + ============================================================================== + [..] + This subsection provides the following callback functions: + (+) HAL_FDCAN_TxEventFifoCallback + (+) HAL_FDCAN_RxFifo0Callback + (+) HAL_FDCAN_RxFifo1Callback + (+) HAL_FDCAN_TxFifoEmptyCallback + (+) HAL_FDCAN_TxBufferCompleteCallback + (+) HAL_FDCAN_TxBufferAbortCallback + (+) HAL_FDCAN_HighPriorityMessageCallback + (+) HAL_FDCAN_TimestampWraparoundCallback + (+) HAL_FDCAN_TimeoutOccurredCallback + (+) HAL_FDCAN_ErrorCallback + (+) HAL_FDCAN_ErrorStatusCallback + +@endverbatim + * @{ + */ + +/** + * @brief Tx Event callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param TxEventFifoITs indicates which Tx Event FIFO interrupts are signaled. + * This parameter can be any combination of @arg FDCAN_Tx_Event_Fifo_Interrupts. + * @retval None + */ +__weak void HAL_FDCAN_TxEventFifoCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t TxEventFifoITs) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + UNUSED(TxEventFifoITs); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_TxEventFifoCallback could be implemented in the user file + */ +} + +/** + * @brief Rx FIFO 0 callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param RxFifo0ITs indicates which Rx FIFO 0 interrupts are signaled. + * This parameter can be any combination of @arg FDCAN_Rx_Fifo0_Interrupts. + * @retval None + */ +__weak void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + UNUSED(RxFifo0ITs); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_RxFifo0Callback could be implemented in the user file + */ +} + +/** + * @brief Rx FIFO 1 callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param RxFifo1ITs indicates which Rx FIFO 1 interrupts are signaled. + * This parameter can be any combination of @arg FDCAN_Rx_Fifo1_Interrupts. + * @retval None + */ +__weak void HAL_FDCAN_RxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + UNUSED(RxFifo1ITs); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_RxFifo1Callback could be implemented in the user file + */ +} + +/** + * @brief Tx FIFO Empty callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_TxFifoEmptyCallback(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_TxFifoEmptyCallback could be implemented in the user file + */ +} + +/** + * @brief Transmission Complete callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param BufferIndexes Indexes of the transmitted buffers. + * This parameter can be any combination of @arg FDCAN_Tx_location. + * @retval None + */ +__weak void HAL_FDCAN_TxBufferCompleteCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + UNUSED(BufferIndexes); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_TxBufferCompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Transmission Cancellation callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param BufferIndexes Indexes of the aborted buffers. + * This parameter can be any combination of @arg FDCAN_Tx_location. + * @retval None + */ +__weak void HAL_FDCAN_TxBufferAbortCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t BufferIndexes) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + UNUSED(BufferIndexes); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_TxBufferAbortCallback could be implemented in the user file + */ +} + +/** + * @brief Timestamp Wraparound callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_TimestampWraparoundCallback(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_TimestampWraparoundCallback could be implemented in the user file + */ +} + +/** + * @brief Timeout Occurred callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_TimeoutOccurredCallback(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_TimeoutOccurredCallback could be implemented in the user file + */ +} + +/** + * @brief High Priority Message callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_HighPriorityMessageCallback(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_HighPriorityMessageCallback could be implemented in the user file + */ +} + +/** + * @brief Error callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval None + */ +__weak void HAL_FDCAN_ErrorCallback(FDCAN_HandleTypeDef *hfdcan) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Error status callback. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param ErrorStatusITs indicates which Error Status interrupts are signaled. + * This parameter can be any combination of @arg FDCAN_Error_Status_Interrupts. + * @retval None + */ +__weak void HAL_FDCAN_ErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hfdcan); + UNUSED(ErrorStatusITs); + + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_FDCAN_ErrorStatusCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup FDCAN_Exported_Functions_Group6 Peripheral State functions + * @brief FDCAN Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to : + (+) HAL_FDCAN_GetState() : Return the FDCAN state. + (+) HAL_FDCAN_GetError() : Return the FDCAN error code if any. + +@endverbatim + * @{ + */ +/** + * @brief Return the FDCAN state + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval HAL state + */ +HAL_FDCAN_StateTypeDef HAL_FDCAN_GetState(const FDCAN_HandleTypeDef *hfdcan) +{ + /* Return FDCAN state */ + return hfdcan->State; +} + +/** + * @brief Return the FDCAN error code + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval FDCAN Error Code + */ +uint32_t HAL_FDCAN_GetError(const FDCAN_HandleTypeDef *hfdcan) +{ + /* Return FDCAN error code */ + return hfdcan->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup FDCAN_Private_Functions FDCAN Private Functions + * @{ + */ + +/** + * @brief Calculate each RAM block start address and size + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @retval none + */ +static void FDCAN_CalcultateRamBlockAddresses(FDCAN_HandleTypeDef *hfdcan) +{ + uint32_t RAMcounter; + uint32_t SramCanInstanceBase = SRAMCAN_BASE; + + if (hfdcan->Instance == FDCAN2) + { + SramCanInstanceBase += SRAMCAN_SIZE; + } + + /* Standard filter list start address */ + hfdcan->msgRam.StandardFilterSA = SramCanInstanceBase + SRAMCAN_FLSSA; + + /* Standard filter elements number */ + MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_LSS, (hfdcan->Init.StdFiltersNbr << FDCAN_RXGFC_LSS_Pos)); + + /* Extended filter list start address */ + hfdcan->msgRam.ExtendedFilterSA = SramCanInstanceBase + SRAMCAN_FLESA; + + /* Extended filter elements number */ + MODIFY_REG(hfdcan->Instance->RXGFC, FDCAN_RXGFC_LSE, (hfdcan->Init.ExtFiltersNbr << FDCAN_RXGFC_LSE_Pos)); + + /* Rx FIFO 0 start address */ + hfdcan->msgRam.RxFIFO0SA = SramCanInstanceBase + SRAMCAN_RF0SA; + + /* Rx FIFO 1 start address */ + hfdcan->msgRam.RxFIFO1SA = SramCanInstanceBase + SRAMCAN_RF1SA; + + /* Tx event FIFO start address */ + hfdcan->msgRam.TxEventFIFOSA = SramCanInstanceBase + SRAMCAN_TEFSA; + + /* Tx FIFO/queue start address */ + hfdcan->msgRam.TxFIFOQSA = SramCanInstanceBase + SRAMCAN_TFQSA; + + /* Flush the allocated Message RAM area */ + for (RAMcounter = SramCanInstanceBase; RAMcounter < (SramCanInstanceBase + SRAMCAN_SIZE); RAMcounter += 4U) + { + *(uint32_t *)(RAMcounter) = 0x00000000U; + } +} + +/** + * @brief Copy Tx message to the message RAM. + * @param hfdcan pointer to an FDCAN_HandleTypeDef structure that contains + * the configuration information for the specified FDCAN. + * @param pTxHeader pointer to a FDCAN_TxHeaderTypeDef structure. + * @param pTxData pointer to a buffer containing the payload of the Tx frame. + * @param BufferIndex index of the buffer to be configured. + * @retval none + */ +static void FDCAN_CopyMessageToRAM(const FDCAN_HandleTypeDef *hfdcan, const FDCAN_TxHeaderTypeDef *pTxHeader, + const uint8_t *pTxData, uint32_t BufferIndex) +{ + uint32_t TxElementW1; + uint32_t TxElementW2; + uint32_t *TxAddress; + uint32_t ByteCounter; + + /* Build first word of Tx header element */ + if (pTxHeader->IdType == FDCAN_STANDARD_ID) + { + TxElementW1 = (pTxHeader->ErrorStateIndicator | + FDCAN_STANDARD_ID | + pTxHeader->TxFrameType | + (pTxHeader->Identifier << 18U)); + } + else /* pTxHeader->IdType == FDCAN_EXTENDED_ID */ + { + TxElementW1 = (pTxHeader->ErrorStateIndicator | + FDCAN_EXTENDED_ID | + pTxHeader->TxFrameType | + pTxHeader->Identifier); + } + + /* Build second word of Tx header element */ + TxElementW2 = ((pTxHeader->MessageMarker << 24U) | + pTxHeader->TxEventFifoControl | + pTxHeader->FDFormat | + pTxHeader->BitRateSwitch | + (pTxHeader->DataLength << 16U)); + + /* Calculate Tx element address */ + TxAddress = (uint32_t *)(hfdcan->msgRam.TxFIFOQSA + (BufferIndex * SRAMCAN_TFQ_SIZE)); + + /* Write Tx element header to the message RAM */ + *TxAddress = TxElementW1; + TxAddress++; + *TxAddress = TxElementW2; + TxAddress++; + + /* Write Tx payload to the message RAM */ + for (ByteCounter = 0; ByteCounter < DLCtoBytes[pTxHeader->DataLength]; ByteCounter += 4U) + { + *TxAddress = (((uint32_t)pTxData[ByteCounter + 3U] << 24U) | + ((uint32_t)pTxData[ByteCounter + 2U] << 16U) | + ((uint32_t)pTxData[ByteCounter + 1U] << 8U) | + (uint32_t)pTxData[ByteCounter]); + TxAddress++; + } +} + +/** + * @} + */ +#endif /* HAL_FDCAN_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +#endif /* FDCAN1 */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash.c index 732100462..5e67cc487 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash.c @@ -1,969 +1,962 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_flash.c - * @author MCD Application Team - * @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 C-Bus 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 implements the TrustZone security features (TZ) supported - by ARM Cortex-M33 core (CM33). - - [..] The FLASH main features are: - (+) Flash memory read operations - (+) Flash memory program/erase operations - (+) Read / write protections - (+) Option bytes programming - (+) TrustZone aware - (+) Watermark-based area protection including PCROP and secure hide area - (+) Block-based page protection - (+) Error code correction (ECC) : Data in flash are 137-bits word - (9 bits added per quad-word) - - ##### How to use this driver ##### - ============================================================================== - [..] - This driver provides functions and macros to configure and program the FLASH - memory of all STM32H7RSxx devices. - - (#) Flash Memory IO Programming functions: - (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and - HAL_FLASH_Lock() functions - (++) Program functions: quad-words and burst program (8 quad-words) - (++) There are 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() - (++) Callback functions are called when the flash operations are finished : - HAL_FLASH_EndOfOperationCallback() when everything is ok, otherwise - HAL_FLASH_OperationErrorCallback() - (++) Get error flag status by calling HAL_GetError() - - (#) Option bytes management functions : - (++) Lock and Unlock the option bytes using HAL_FLASH_OB_Unlock() and - HAL_FLASH_OB_Lock() functions - (++) Launch the reload of the option bytes using HAL_FLASH_Launch() function. - In this case, a reset is generated - - [..] - In addition to these functions, this driver includes a set of macros allowing - to handle the following operations: - (+) Set the latency - (+) Enable/Disable the Flash power-down during low-power run and sleep modes - (+) Enable/Disable the Flash interrupts - (+) Monitor the Flash flags status - - @endverbatim - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup FLASH FLASH - * @brief FLASH HAL module driver - * @{ - */ - -#ifdef HAL_FLASH_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private defines -----------------------------------------------------------*/ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup FLASH_Private_Variables FLASH Private Variables - * @{ - */ -/** - * @brief Variable used for Program/Erase sectors under interruption - */ -FLASH_ProcessTypeDef pFlash = {.Lock = HAL_UNLOCKED, \ - .ErrorCode = HAL_FLASH_ERROR_NONE, \ - .ProcedureOnGoing = 0U, \ - .Address = 0U, \ - .Sector = 0U, \ - .NbSectorsToErase = 0U - }; -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup FLASH_Private_Functions FLASH Private Functions - * @{ - */ -static void FLASH_Program_Byte(uint32_t Address, uint32_t DataAddress); -static void FLASH_Program_HalfWord(uint32_t Address, uint32_t DataAddress); -static void FLASH_Program_Word(uint32_t Address, uint32_t DataAddress); -static void FLASH_Program_DoubleWord(uint32_t Address, uint32_t DataAddress); -static void FLASH_Program_QuadWord(uint32_t Address, uint32_t DataAddress); -static void FLASH_Program_OTPHalfWord(uint32_t Address, uint32_t DataAddress); -static void FLASH_Program_OTPWord(uint32_t Address, uint32_t DataAddress); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup FLASH_Exported_Functions FLASH Exported Functions - * @{ - */ - -/** @defgroup FLASH_Exported_Functions_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 a data 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 DataAddress specifies the address of data to be programmed. - * - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint32_t DataAddress) -{ - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status == HAL_OK) - { - switch (TypeProgram) - { - case FLASH_TYPEPROGRAM_BYTE: - /* Program a byte (8-bit) at a specified address */ - FLASH_Program_Byte(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_HALFWORD: - /* Program a half-word (16-bit) at a specified address */ - FLASH_Program_HalfWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_WORD: - /* Program a word (32-bit) at a specified address */ - FLASH_Program_Word(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_DOUBLEWORD: - /* Program a double-word (64-bit) at a specified address */ - FLASH_Program_DoubleWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_QUADWORD: - /* Program a quad-word (128-bit) at a specified address */ - FLASH_Program_QuadWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_OTP_HALFWORD: - /* Program a half-word (16-bit) at a OTP address */ - FLASH_Program_OTPHalfWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_OTP_WORD: - /* Program a word (32-bit) at a OTP address */ - FLASH_Program_OTPWord(Address, DataAddress); - break; - - default: - status = HAL_ERROR; - break; - } - - if (status != HAL_ERROR) - { - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - /* If the program operation is completed, disable the PG (and FW Bit in non quad-word mode) */ - CLEAR_BIT(FLASH->CR, (TypeProgram & ~(FLASH_WORD_SIZE_MASK))); - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - - /* return status */ - return status; -} - -/** - * @brief Program a data 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 DataAddress specifies the address of data to be programmed - * - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint32_t DataAddress) -{ - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status != HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - } - else - { - /* Set internal variables used by the IRQ handler */ - pFlash.ProcedureOnGoing = TypeProgram; - pFlash.Address = Address; - - /* Enable End of Operation and Error interrupts */ - SET_BIT(FLASH->IER, (FLASH_IT_EOP | FLASH_IT_WRPERR | FLASH_IT_PGSERR | FLASH_IT_STRBERR | FLASH_IT_INCERR)); - - switch (TypeProgram) - { - case FLASH_TYPEPROGRAM_BYTE: - /* Program a byte (8-bit) at a specified address */ - FLASH_Program_Byte(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_HALFWORD: - /* Program a half-word (16-bit) at a specified address */ - FLASH_Program_HalfWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_WORD: - /* Program a word (32-bit) at a specified address */ - FLASH_Program_Word(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_DOUBLEWORD: - /* Program a double-word (64-bit) at a specified address */ - FLASH_Program_DoubleWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_QUADWORD: - /* Program a quad-word (128-bit) at a specified address */ - FLASH_Program_QuadWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_OTP_HALFWORD: - /* Program a half-word (16-bit) at a OTP address */ - FLASH_Program_OTPHalfWord(Address, DataAddress); - break; - - case FLASH_TYPEPROGRAM_OTP_WORD: - /* Program a word (32-bit) at a OTP address */ - FLASH_Program_OTPWord(Address, DataAddress); - break; - - default: - status = HAL_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - break; - } - } - - return status; -} - -/** - * @brief Handle FLASH interrupt request. - * @retval None - */ -void HAL_FLASH_IRQHandler(void) -{ - uint32_t param = 0U; - uint32_t error; - - /* Save Flash errors */ - error = FLASH->ISR & FLASH_FLAG_ISR_ERRORS; - error |= (FLASH->OPTISR & FLASH_FLAG_OPTISR_ERRORS); - - /* Set parameter of the callback */ - if (pFlash.ProcedureOnGoing == FLASH_TYPEERASE_SECTORS) - { - param = pFlash.Sector; - } - else if ((pFlash.ProcedureOnGoing & FLASH_CR_PG) != 0U) - { - param = pFlash.Address; - } - else - { - /* Empty statement (to be compliant MISRA 15.7) */ - } - - /* Clear operation bit on the on-going procedure */ - CLEAR_BIT(FLASH->CR, (pFlash.ProcedureOnGoing & ~(FLASH_WORD_SIZE_MASK))); - - /* Check FLASH operation error flags */ - if (error != 0U) - { - /* Save the error code */ - pFlash.ErrorCode |= error; - - /* Clear error programming flags */ - FLASH->ICR = (error & FLASH_FLAG_ISR_ERRORS); - FLASH->OPTICR = (error & FLASH_FLAG_OPTISR_ERRORS); - - /* Stop the procedure ongoing */ - pFlash.ProcedureOnGoing = 0U; - - /* FLASH error interrupt user callback */ - HAL_FLASH_OperationErrorCallback(param); - } - - /* Check FLASH End of Operation flag */ - if ((FLASH->ISR & FLASH_FLAG_EOP) != 0U) - { - /* Clear FLASH End of Operation pending bit */ - FLASH->ICR = FLASH_FLAG_EOP; - - if (pFlash.ProcedureOnGoing == FLASH_TYPEERASE_SECTORS) - { - /* Nb of sectors to erase can be decreased */ - pFlash.NbSectorsToErase--; - - /* Check if there are still sectors to erase */ - if (pFlash.NbSectorsToErase != 0U) - { - /* Increment sector number */ - pFlash.Sector++; - FLASH_SectorErase(pFlash.Sector); - } - else - { - /* No more sectors to Erase */ - pFlash.ProcedureOnGoing = 0U; - param = 0xFFFFFFFFU; - } - } - else - { - /*Clear the procedure ongoing*/ - pFlash.ProcedureOnGoing = 0U; - } - - /* FLASH EOP interrupt user callback */ - HAL_FLASH_EndOfOperationCallback(param); - } - - if (pFlash.ProcedureOnGoing == 0U) - { - /* Disable End of Operation and Error interrupts */ - CLEAR_BIT(FLASH->IER, (FLASH_IT_EOP | FLASH_IT_WRPERR | FLASH_IT_PGSERR | FLASH_IT_STRBERR | FLASH_IT_INCERR)); - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - } - - /* Check ECC Correction Error */ - if ((FLASH->IER & FLASH_IT_SNECCERR) != 0U) - { - if ((FLASH->ISR & FLASH_FLAG_SNECCERR) != 0U) - { - /* Call User callback */ - HAL_FLASHEx_EccCorrectionCallback(); - - /* Clear ECC correction flag in order to allow new ECC error record */ - FLASH->ICR = FLASH_FLAG_SNECCERR; - } - } - - /* Check ECC Detection Error */ - if ((FLASH->IER & FLASH_IT_DBECCERR) != 0U) - { - if ((FLASH->ISR & FLASH_FLAG_DBECCERR) != 0U) - { - /* Call User callback */ - HAL_FLASHEx_EccDetectionCallback(); - - /* Clear ECC detection flag in order to allow new ECC error record */ - FLASH->ICR = FLASH_FLAG_DBECCERR; - } - } -} - -/** - * @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 - * Sector 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 - * Sector 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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_Exported_Functions_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. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASH_Unlock(void) -{ - if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) - { - /* Authorize the FLASH Registers access */ - WRITE_REG(FLASH->KEYR, FLASH_KEY1); - WRITE_REG(FLASH->KEYR, FLASH_KEY2); - - /* verify Flash is unlocked */ - if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Lock the FLASH control register access. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASH_Lock(void) -{ - /* Set the LOCK Bit to lock the FLASH Registers access */ - SET_BIT(FLASH->CR, FLASH_CR_LOCK); - - /* verify Flash is locked */ - if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) - { - return HAL_OK; - } - - return HAL_ERROR; -} - -/** - * @brief Unlock the FLASH Option Bytes Registers access. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) -{ - if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK) != 0U) - { - /* Authorizes the Option Byte register programming */ - WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1); - WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2); - - /* Verify that the Option Bytes are unlocked */ - if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK) != 0U) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Lock the FLASH Option Bytes Registers access. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) -{ - /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */ - SET_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK); - - /* Verify that the Option Bytes are locked */ - if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK) != 0U) - { - return HAL_OK; - } - - return HAL_ERROR; -} - -/** - * @} - */ - -/** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief Peripheral Errors functions - * -@verbatim - =============================================================================== - ##### Peripheral Errors functions ##### - =============================================================================== - [..] - This subsection permits to get in run-time Errors of the FLASH peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Get the specific FLASH error flag. - * @retval FLASH_ErrorCode The returned value can be: - * @arg HAL_FLASH_ERROR_NONE: No error set - * @arg HAL_FLASH_ERROR_WRP: FLASH Write protection error - * @arg HAL_FLASH_ERROR_PGS: FLASH Programming sequence error - * @arg HAL_FLASH_ERROR_STRB: FLASH Strobe error - * @arg HAL_FLASH_ERROR_INC: FLASH Inconsistency error - * @arg HAL_FLASH_ERROR_RDS: FLASH Read security error - * @arg HAL_FLASH_ERROR_SNECC: FLASH ECC single error - * @arg HAL_FLASH_ERROR_DBECC: FLASH ECC double error - * @arg HAL_FLASH_ERROR_CRC: FLASH CRC error - * @arg HAL_FLASH_ERROR_KDR: FLASH Key data register error - * @arg HAL_FLASH_ERROR_OBC: FLASH Options byte change error - */ -uint32_t HAL_FLASH_GetError(void) -{ - return pFlash.ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ - -/** @addtogroup FLASH_Private_Functions - * @{ - */ - -/** - * @brief Wait for a FLASH operation to complete. - * @param Timeout maximum flash operation timeout - * @retval 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; - uint32_t error; - - while ((FLASH->SR & FLASH_SR_QW) != 0U) - { - if (Timeout != HAL_MAX_DELAY) - { - if (HAL_GetTick() >= timeout) - { - return HAL_TIMEOUT; - } - } - } - - /* Check FLASH operation error flags */ - error = (FLASH->ISR & FLASH_FLAG_ISR_ERRORS); - error |= (FLASH->OPTISR & FLASH_FLAG_OPTISR_ERRORS); - - if (error != 0U) - { - /*Save the error code*/ - pFlash.ErrorCode |= error; - - /* Clear error programming flags */ - FLASH->ICR = (error & FLASH_FLAG_ISR_ERRORS); - FLASH->OPTICR = (error & FLASH_FLAG_OPTISR_ERRORS); - - return HAL_ERROR; - } - - /* Check FLASH End of Operation flag */ - if ((FLASH->ISR & FLASH_FLAG_EOP) != 0U) - { - /* Clear FLASH End of Operation pending bit */ - FLASH->ICR = FLASH_FLAG_EOP; - } - - /* If there is no error flag set */ - return HAL_OK; -} - -/** - * @brief Program a byte (8-bit) at a specified address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_Byte(uint32_t Address, uint32_t DataAddress) -{ - uint8_t *dest_addr = (uint8_t *)Address; - uint8_t *src_addr = (uint8_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); - - /* Set PG bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the byte */ - *dest_addr = *src_addr; - - __ISB(); - __DSB(); - - /* Set FW bit */ - SET_BIT(FLASH->CR, FLASH_CR_FW); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @brief Program a half-word (16-bit) at a specified address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_HalfWord(uint32_t Address, uint32_t DataAddress) -{ - uint16_t *dest_addr = (uint16_t *)Address; - uint16_t *src_addr = (uint16_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); - - /* Set PG bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the half-word */ - *dest_addr = *src_addr; - - __ISB(); - __DSB(); - - /* Set FW bit */ - SET_BIT(FLASH->CR, FLASH_CR_FW); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @brief Program a word (32-bit) at a specified address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_Word(uint32_t Address, uint32_t DataAddress) -{ - uint8_t index = 2; - uint16_t *dest_addr = (uint16_t *)Address; - uint16_t *src_addr = (uint16_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); - - /* Set PG bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the word */ - do - { - *dest_addr = *src_addr; - dest_addr++; - src_addr++; - index--; - } while (index != 0U); - - __ISB(); - __DSB(); - - /* Set FW bit */ - SET_BIT(FLASH->CR, FLASH_CR_FW); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @brief Program a double-word (64-bit) at a specified address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_DoubleWord(uint32_t Address, uint32_t DataAddress) -{ - uint8_t index = 4; - uint16_t *dest_addr = (uint16_t *)Address; - uint16_t *src_addr = (uint16_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); - - /* Set PG bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the double-word */ - do - { - *dest_addr = *src_addr; - dest_addr++; - src_addr++; - index--; - } while (index != 0U); - - __ISB(); - __DSB(); - - /* Set FW bit */ - SET_BIT(FLASH->CR, FLASH_CR_FW); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @brief Program a quad-word (128-bit) at a specified address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_QuadWord(uint32_t Address, uint32_t DataAddress) -{ - uint8_t index = 8; - uint16_t *dest_addr = (uint16_t *)Address; - uint16_t *src_addr = (uint16_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); - - /* Set PG bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the quad-word */ - do - { - *dest_addr = *src_addr; - dest_addr++; - src_addr++; - index--; - } while (index != 0U); - - __ISB(); - __DSB(); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @brief Program a half-word (16-bit) at a OTP address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_OTPHalfWord(uint32_t Address, uint32_t DataAddress) -{ - uint16_t *dest_addr = (uint16_t *)Address; - uint16_t *src_addr = (uint16_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_OTP_ADDRESS(Address)); - - /* Set PG_OTP bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG_OTP); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the half-word */ - *dest_addr = *src_addr; - - __ISB(); - __DSB(); - - /* Set FW bit */ - SET_BIT(FLASH->CR, FLASH_CR_FW); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @brief Program a word (32-bit) at a OTP address. - * @param Address specifies the address to be programmed. - * @param DataAddress specifies the address of data to be programmed. - * @retval None - */ -static void FLASH_Program_OTPWord(uint32_t Address, uint32_t DataAddress) -{ - uint8_t index = 2; - uint16_t *dest_addr = (uint16_t *)Address; - uint16_t *src_addr = (uint16_t *)DataAddress; - uint32_t primask_bit; - - /* Check the parameters */ - assert_param(IS_FLASH_OTP_ADDRESS(Address)); - - /* Set PG_OTP bit */ - SET_BIT(FLASH->CR, FLASH_CR_PG_OTP); - - /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ - primask_bit = __get_PRIMASK(); - __disable_irq(); - - /* Program the word */ - do - { - *dest_addr = *src_addr; - dest_addr++; - src_addr++; - index--; - } while (index != 0U); - - __ISB(); - __DSB(); - - /* Set FW bit */ - SET_BIT(FLASH->CR, FLASH_CR_FW); - - /* Exit critical section: restore previous priority mask */ - __set_PRIMASK(primask_bit); -} - -/** - * @} - */ - -#endif /* HAL_FLASH_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_flash.c + * @author MCD Application Team + * @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 C-Bus accesses to the Flash memory. + It implements the erase and program Flash memory operations and the read + and write protection mechanisms. + + [..] The FLASH main features are: + (+) Flash memory read operations + (+) Flash memory program/erase operations + (+) Read / write protections + (+) Option bytes programming + (+) Error code correction (ECC) : Data in flash are 137-bits word + (9 bits added per quad-word) + + ##### How to use this driver ##### + ============================================================================== + [..] + This driver provides functions and macros to configure and program the FLASH + memory of all STM32H7RSxx devices. + + (#) Flash Memory IO Programming functions: + (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and + HAL_FLASH_Lock() functions + (++) Program functions: bytes, half-words, words, double-words and quad-words + (++) There are 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() + (++) Callback functions are called when the flash operations are finished : + HAL_FLASH_EndOfOperationCallback() when everything is ok, otherwise + HAL_FLASH_OperationErrorCallback() + (++) Get error flag status by calling HAL_GetError() + + (#) Option bytes management functions : + (++) Lock and Unlock the option bytes using HAL_FLASH_OB_Unlock() and + HAL_FLASH_OB_Lock() functions + (++) Launch the reload of the option bytes using HAL_FLASH_Launch() function. + In this case, a reset is generated + + [..] + In addition to these functions, this driver includes a set of macros allowing + to handle the following operations: + (+) Set the latency + (+) Enable/Disable the Flash interrupts + (+) Monitor the Flash flags status + + @endverbatim + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup FLASH FLASH + * @brief FLASH HAL module driver + * @{ + */ + +#ifdef HAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup FLASH_Private_Variables FLASH Private Variables + * @{ + */ +/** + * @brief Variable used for Program/Erase sectors under interruption + */ +FLASH_ProcessTypeDef pFlash = {.Lock = HAL_UNLOCKED, \ + .ErrorCode = HAL_FLASH_ERROR_NONE, \ + .ProcedureOnGoing = 0U, \ + .Address = 0U, \ + .Sector = 0U, \ + .NbSectorsToErase = 0U + }; +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup FLASH_Private_Functions FLASH Private Functions + * @{ + */ +static void FLASH_Program_Byte(uint32_t Address, uint32_t DataAddress); +static void FLASH_Program_HalfWord(uint32_t Address, uint32_t DataAddress); +static void FLASH_Program_Word(uint32_t Address, uint32_t DataAddress); +static void FLASH_Program_DoubleWord(uint32_t Address, uint32_t DataAddress); +static void FLASH_Program_QuadWord(uint32_t Address, uint32_t DataAddress); +static void FLASH_Program_OTPHalfWord(uint32_t Address, uint32_t DataAddress); +static void FLASH_Program_OTPWord(uint32_t Address, uint32_t DataAddress); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Functions FLASH Exported Functions + * @{ + */ + +/** @defgroup FLASH_Exported_Functions_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 a data 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 DataAddress specifies the address of data to be programmed. + * + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint32_t DataAddress) +{ + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + switch (TypeProgram) + { + case FLASH_TYPEPROGRAM_BYTE: + /* Program a byte (8-bit) at a specified address */ + FLASH_Program_Byte(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_HALFWORD: + /* Program a half-word (16-bit) at a specified address */ + FLASH_Program_HalfWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_WORD: + /* Program a word (32-bit) at a specified address */ + FLASH_Program_Word(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_DOUBLEWORD: + /* Program a double-word (64-bit) at a specified address */ + FLASH_Program_DoubleWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_QUADWORD: + /* Program a quad-word (128-bit) at a specified address */ + FLASH_Program_QuadWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_OTP_HALFWORD: + /* Program a half-word (16-bit) at a OTP address */ + FLASH_Program_OTPHalfWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_OTP_WORD: + /* Program a word (32-bit) at a OTP address */ + FLASH_Program_OTPWord(Address, DataAddress); + break; + + default: + status = HAL_ERROR; + break; + } + + if (status != HAL_ERROR) + { + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + /* If the program operation is completed, disable the PG (and FW Bit in non quad-word mode) */ + CLEAR_BIT(FLASH->CR, (TypeProgram & ~(FLASH_WORD_SIZE_MASK))); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + /* return status */ + return status; +} + +/** + * @brief Program a data 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 DataAddress specifies the address of data to be programmed + * + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint32_t DataAddress) +{ + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status != HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + } + else + { + /* Set internal variables used by the IRQ handler */ + pFlash.ProcedureOnGoing = TypeProgram; + pFlash.Address = Address; + + /* Enable End of Operation and Error interrupts */ + SET_BIT(FLASH->IER, (FLASH_IT_EOP | FLASH_IT_WRPERR | FLASH_IT_PGSERR | FLASH_IT_STRBERR | FLASH_IT_INCERR)); + + switch (TypeProgram) + { + case FLASH_TYPEPROGRAM_BYTE: + /* Program a byte (8-bit) at a specified address */ + FLASH_Program_Byte(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_HALFWORD: + /* Program a half-word (16-bit) at a specified address */ + FLASH_Program_HalfWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_WORD: + /* Program a word (32-bit) at a specified address */ + FLASH_Program_Word(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_DOUBLEWORD: + /* Program a double-word (64-bit) at a specified address */ + FLASH_Program_DoubleWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_QUADWORD: + /* Program a quad-word (128-bit) at a specified address */ + FLASH_Program_QuadWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_OTP_HALFWORD: + /* Program a half-word (16-bit) at a OTP address */ + FLASH_Program_OTPHalfWord(Address, DataAddress); + break; + + case FLASH_TYPEPROGRAM_OTP_WORD: + /* Program a word (32-bit) at a OTP address */ + FLASH_Program_OTPWord(Address, DataAddress); + break; + + default: + status = HAL_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + break; + } + } + + return status; +} + +/** + * @brief Handle FLASH interrupt request. + * @retval None + */ +void HAL_FLASH_IRQHandler(void) +{ + uint32_t param = 0U; + uint32_t error; + + /* Save Flash errors */ + error = FLASH->ISR & FLASH_FLAG_ISR_ERRORS; + error |= (FLASH->OPTISR & FLASH_FLAG_OPTISR_ERRORS); + + /* Set parameter of the callback */ + if (pFlash.ProcedureOnGoing == FLASH_TYPEERASE_SECTORS) + { + param = pFlash.Sector; + } + else if ((pFlash.ProcedureOnGoing & FLASH_CR_PG) != 0U) + { + param = pFlash.Address; + } + else + { + /* Empty statement (to be compliant MISRA 15.7) */ + } + + /* Clear operation bit on the on-going procedure */ + CLEAR_BIT(FLASH->CR, (pFlash.ProcedureOnGoing & ~(FLASH_WORD_SIZE_MASK))); + + /* Check FLASH operation error flags */ + if (error != 0U) + { + /* Save the error code */ + pFlash.ErrorCode |= error; + + /* Clear error programming flags */ + FLASH->ICR = (error & FLASH_FLAG_ISR_ERRORS); + FLASH->OPTICR = (error & FLASH_FLAG_OPTISR_ERRORS); + + /* Stop the procedure ongoing */ + pFlash.ProcedureOnGoing = 0U; + + /* FLASH error interrupt user callback */ + HAL_FLASH_OperationErrorCallback(param); + } + + /* Check FLASH End of Operation flag */ + if ((FLASH->ISR & FLASH_FLAG_EOP) != 0U) + { + /* Clear FLASH End of Operation pending bit */ + FLASH->ICR = FLASH_FLAG_EOP; + + if (pFlash.ProcedureOnGoing == FLASH_TYPEERASE_SECTORS) + { + /* Nb of sectors to erase can be decreased */ + pFlash.NbSectorsToErase--; + + /* Check if there are still sectors to erase */ + if (pFlash.NbSectorsToErase != 0U) + { + /* Increment sector number */ + pFlash.Sector++; + FLASH_SectorErase(pFlash.Sector); + } + else + { + /* No more sectors to Erase */ + pFlash.ProcedureOnGoing = 0U; + param = 0xFFFFFFFFU; + } + } + else + { + /*Clear the procedure ongoing*/ + pFlash.ProcedureOnGoing = 0U; + } + + /* FLASH EOP interrupt user callback */ + HAL_FLASH_EndOfOperationCallback(param); + } + + if (pFlash.ProcedureOnGoing == 0U) + { + /* Disable End of Operation and Error interrupts */ + CLEAR_BIT(FLASH->IER, (FLASH_IT_EOP | FLASH_IT_WRPERR | FLASH_IT_PGSERR | FLASH_IT_STRBERR | FLASH_IT_INCERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + } + + /* Check ECC Correction Error */ + if ((FLASH->IER & FLASH_IT_SNECCERR) != 0U) + { + if ((FLASH->ISR & FLASH_FLAG_SNECCERR) != 0U) + { + /* Call User callback */ + HAL_FLASHEx_EccCorrectionCallback(); + + /* Clear ECC correction flag in order to allow new ECC error record */ + FLASH->ICR = FLASH_FLAG_SNECCERR; + } + } + + /* Check ECC Detection Error */ + if ((FLASH->IER & FLASH_IT_DBECCERR) != 0U) + { + if ((FLASH->ISR & FLASH_FLAG_DBECCERR) != 0U) + { + /* Call User callback */ + HAL_FLASHEx_EccDetectionCallback(); + + /* Clear ECC detection flag in order to allow new ECC error record */ + FLASH->ICR = FLASH_FLAG_DBECCERR; + } + } +} + +/** + * @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 + * Sector 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 + * Sector 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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_Exported_Functions_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. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Unlock(void) +{ + if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) + { + /* Authorize the FLASH Registers access */ + WRITE_REG(FLASH->KEYR, FLASH_KEY1); + WRITE_REG(FLASH->KEYR, FLASH_KEY2); + + /* verify Flash is unlocked */ + if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Lock the FLASH control register access. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Lock(void) +{ + /* Set the LOCK Bit to lock the FLASH Registers access */ + SET_BIT(FLASH->CR, FLASH_CR_LOCK); + + /* verify Flash is locked */ + if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U) + { + return HAL_OK; + } + + return HAL_ERROR; +} + +/** + * @brief Unlock the FLASH Option Bytes Registers access. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) +{ + if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK) != 0U) + { + /* Authorizes the Option Byte register programming */ + WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1); + WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2); + + /* Verify that the Option Bytes are unlocked */ + if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK) != 0U) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Lock the FLASH Option Bytes Registers access. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) +{ + /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */ + SET_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK); + + /* Verify that the Option Bytes are locked */ + if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_OPTLOCK) != 0U) + { + return HAL_OK; + } + + return HAL_ERROR; +} + +/** + * @} + */ + +/** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief Peripheral Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral Errors functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time Errors of the FLASH peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Get the specific FLASH error flag. + * @retval FLASH_ErrorCode The returned value can be: + * @arg HAL_FLASH_ERROR_NONE: No error set + * @arg HAL_FLASH_ERROR_WRP: FLASH Write protection error + * @arg HAL_FLASH_ERROR_PGS: FLASH Programming sequence error + * @arg HAL_FLASH_ERROR_STRB: FLASH Strobe error + * @arg HAL_FLASH_ERROR_INC: FLASH Inconsistency error + * @arg HAL_FLASH_ERROR_RDS: FLASH Read security error + * @arg HAL_FLASH_ERROR_SNECC: FLASH ECC single error + * @arg HAL_FLASH_ERROR_DBECC: FLASH ECC double error + * @arg HAL_FLASH_ERROR_CRC: FLASH CRC error + * @arg HAL_FLASH_ERROR_KDR: FLASH Key data register error + * @arg HAL_FLASH_ERROR_OBC: FLASH Options byte change error + */ +uint32_t HAL_FLASH_GetError(void) +{ + return pFlash.ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +/** @addtogroup FLASH_Private_Functions + * @{ + */ + +/** + * @brief Wait for a FLASH operation to complete. + * @param Timeout maximum flash operation timeout + * @retval 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; + uint32_t error; + + while ((FLASH->SR & FLASH_SR_QW) != 0U) + { + if (Timeout != HAL_MAX_DELAY) + { + if (HAL_GetTick() >= timeout) + { + return HAL_TIMEOUT; + } + } + } + + /* Check FLASH operation error flags */ + error = (FLASH->ISR & FLASH_FLAG_ISR_ERRORS); + error |= (FLASH->OPTISR & FLASH_FLAG_OPTISR_ERRORS); + + if (error != 0U) + { + /*Save the error code*/ + pFlash.ErrorCode |= error; + + /* Clear error programming flags */ + FLASH->ICR = (error & FLASH_FLAG_ISR_ERRORS); + FLASH->OPTICR = (error & FLASH_FLAG_OPTISR_ERRORS); + + return HAL_ERROR; + } + + /* Check FLASH End of Operation flag */ + if ((FLASH->ISR & FLASH_FLAG_EOP) != 0U) + { + /* Clear FLASH End of Operation pending bit */ + FLASH->ICR = FLASH_FLAG_EOP; + } + + /* If there is no error flag set */ + return HAL_OK; +} + +/** + * @brief Program a byte (8-bit) at a specified address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_Byte(uint32_t Address, uint32_t DataAddress) +{ + uint8_t *dest_addr = (uint8_t *)Address; + uint8_t *src_addr = (uint8_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); + + /* Set PG bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the byte */ + *dest_addr = *src_addr; + + __ISB(); + __DSB(); + + /* Set FW bit */ + SET_BIT(FLASH->CR, FLASH_CR_FW); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @brief Program a half-word (16-bit) at a specified address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_HalfWord(uint32_t Address, uint32_t DataAddress) +{ + uint16_t *dest_addr = (uint16_t *)Address; + uint16_t *src_addr = (uint16_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); + + /* Set PG bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the half-word */ + *dest_addr = *src_addr; + + __ISB(); + __DSB(); + + /* Set FW bit */ + SET_BIT(FLASH->CR, FLASH_CR_FW); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @brief Program a word (32-bit) at a specified address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_Word(uint32_t Address, uint32_t DataAddress) +{ + uint8_t index = 2; + uint16_t *dest_addr = (uint16_t *)Address; + uint16_t *src_addr = (uint16_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); + + /* Set PG bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the word */ + do + { + *dest_addr = *src_addr; + dest_addr++; + src_addr++; + index--; + } while (index != 0U); + + __ISB(); + __DSB(); + + /* Set FW bit */ + SET_BIT(FLASH->CR, FLASH_CR_FW); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @brief Program a double-word (64-bit) at a specified address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_DoubleWord(uint32_t Address, uint32_t DataAddress) +{ + uint8_t index = 4; + uint16_t *dest_addr = (uint16_t *)Address; + uint16_t *src_addr = (uint16_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); + + /* Set PG bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the double-word */ + do + { + *dest_addr = *src_addr; + dest_addr++; + src_addr++; + index--; + } while (index != 0U); + + __ISB(); + __DSB(); + + /* Set FW bit */ + SET_BIT(FLASH->CR, FLASH_CR_FW); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @brief Program a quad-word (128-bit) at a specified address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_QuadWord(uint32_t Address, uint32_t DataAddress) +{ + uint8_t index = 8; + uint16_t *dest_addr = (uint16_t *)Address; + uint16_t *src_addr = (uint16_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(Address)); + + /* Set PG bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the quad-word */ + do + { + *dest_addr = *src_addr; + dest_addr++; + src_addr++; + index--; + } while (index != 0U); + + __ISB(); + __DSB(); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @brief Program a half-word (16-bit) at a OTP address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_OTPHalfWord(uint32_t Address, uint32_t DataAddress) +{ + uint16_t *dest_addr = (uint16_t *)Address; + uint16_t *src_addr = (uint16_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_OTP_ADDRESS(Address)); + + /* Set PG_OTP bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG_OTP); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the half-word */ + *dest_addr = *src_addr; + + __ISB(); + __DSB(); + + /* Set FW bit */ + SET_BIT(FLASH->CR, FLASH_CR_FW); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @brief Program a word (32-bit) at a OTP address. + * @param Address specifies the address to be programmed. + * @param DataAddress specifies the address of data to be programmed. + * @retval None + */ +static void FLASH_Program_OTPWord(uint32_t Address, uint32_t DataAddress) +{ + uint8_t index = 2; + uint16_t *dest_addr = (uint16_t *)Address; + uint16_t *src_addr = (uint16_t *)DataAddress; + uint32_t primask_bit; + + /* Check the parameters */ + assert_param(IS_FLASH_OTP_ADDRESS(Address)); + + /* Set PG_OTP bit */ + SET_BIT(FLASH->CR, FLASH_CR_PG_OTP); + + /* Enter critical section: Disable interrupts to avoid any interruption during the loop */ + primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* Program the word */ + do + { + *dest_addr = *src_addr; + dest_addr++; + src_addr++; + index--; + } while (index != 0U); + + __ISB(); + __DSB(); + + /* Set FW bit */ + SET_BIT(FLASH->CR, FLASH_CR_FW); + + /* Exit critical section: restore previous priority mask */ + __set_PRIMASK(primask_bit); +} + +/** + * @} + */ + +#endif /* HAL_FLASH_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash_ex.c index 5737414b5..16ab51f37 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_flash_ex.c @@ -1,1306 +1,1322 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_flash_ex.c - * @author MCD Application Team - * @brief Extended FLASH HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the FLASH extended peripheral: - * + Extended programming operations functions - * - @verbatim - ============================================================================== - ##### Flash Extended features ##### - ============================================================================== - - [..] Comparing to other previous devices, the FLASH interface for STM32H7RSxx - 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 - (+) Watermark-based secure area including PCROP and secure hide areas - (+) Block-based secure pages - - ##### How to use this driver ##### - ============================================================================== - [..] This driver provides functions to configure and program the FLASH memory - of all STM32H7RSxx devices. It includes: - (#) Flash Memory Erase functions: - (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and - HAL_FLASH_Lock() functions - (++) Erase function: page Erase and Bank/Mass Erase - (++) There are two modes of erase : - (+++) Polling Mode using HAL_FLASHEx_Erase() - (+++) Interrupt Mode using HAL_FLASHEx_Erase_IT() - - (#) Option Bytes Programming function: Use HAL_FLASHEx_OBProgram() to: - (++) Configure the write protection for each area - (++) Set the Read protection Level - (++) Program the user Option Bytes - (++) Configure the watermark security for each area including PCROP and secure hide areas - (++) Configure the boot lock (BOOT_LOCK) - (++) Configure the Boot addresses - - (#) Get Option Bytes Configuration function: Use HAL_FLASHEx_OBGetConfig() to: - (++) Get the value of a write protection area - (++) Know if the read protection is activated - (++) Get the value of the user Option Bytes - (++) Get the configuration of a watermark security area including PCROP and secure hide areas - (++) Get the boot lock (BOOT_LOCK) configuration - (++) Get the value of a boot address - - (#) Block-based secure / privilege area configuration function: Use HAL_FLASHEx_ConfigBBAttributes() - (++) Bit-field allowing to secure or un-secure each page - (++) Bit-field allowing to privilege or un-privilege each page - - (#) Get the block-based secure / privilege area configuration function: Use HAL_FLASHEx_GetBBSec() - (++) Return the configuration of the block-based security and privilege for all the pages - - (#) Activation of the secure hide area function: Use HAL_FLASHEx_EnableSecHideProtection() - (++) Deny the access to the secure hide area - - (#) Privilege mode configuration function: Use HAL_FLASHEx_ConfigPrivMode() - (++) FLASH register can be protected against non-privilege accesses - - (#) Get the privilege mode configuration function: Use HAL_FLASHEx_GetPrivMode() - (++) Return if the FLASH registers are protected against non-privilege accesses - - (#) Security inversion configuration function: Use HAL_FLASHEx_ConfigSecInversion() - (++) FLASH secure state can be override - - (#) Get the security inversion configuration function: Use HAL_FLASHEx_GetSecInversion() - (++) Return if FLASH secure state is override - - (#) Enable bank low-power mode function: Use HAL_FLASHEx_EnablePowerDown() - (++) Enable low-power mode for Flash Bank 1 and/or Bank 2 - - (#) Enable low-power read mode function: Use HAL_FLASHEx_ConfigLowPowerRead() - (++) Enable low-power read mode for Flash memory - - (#) Get the low-power read mode configuration function: Use HAL_FLASHEx_GetLowPowerRead() - (++) Return if FLASH is in low-power read mode or normal read mode - - (#) Get Flash operation function: Use HAL_FLASHEx_GetOperation() - (++) Return information about the on-going Flash operation. After a - system reset, return information about the interrupted Flash operation, if any. - - @endverbatim - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup FLASHEx FLASHEx - * @brief FLASH Extended HAL module driver - * @{ - */ - -#ifdef HAL_FLASH_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -#define SYSTEM_FLASH_SIZE 0x00020000UL /*!< System Flash size : 128 KB */ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup FLASHEx_Private_Functions FLASHEx Private Functions - * @{ - */ -static void FLASH_MassErase(void); - -static void FLASH_OB_WRPConfig(uint32_t WRPState, uint32_t WRPSector); -static void FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig1, uint32_t UserConfig2); -static void FLASH_OB_HDPConfig(uint32_t HDPStartPage, uint32_t HDPEndPage); -static void FLASH_OB_NVConfig(uint32_t NVState); - -static void FLASH_OB_GetWRP(uint32_t *WRPState, uint32_t *WRPSector); -static void FLASH_OB_GetUser(uint32_t *UserConfig1, uint32_t *UserConfig2); -static void FLASH_OB_GetHDP(uint32_t *HDPStartPage, uint32_t *HDPEndPage); -static uint32_t FLASH_OB_GetNV(void); -static uint32_t FLASH_OB_GetRoT(void); -static uint32_t FLASH_OB_GetEpoch(void); - -static void FLASH_CRC_AddSector(uint32_t Sector); -static void FLASH_CRC_SelectAddress(uint32_t CRCStartAddr, uint32_t CRCEndAddr); -static HAL_StatusTypeDef FLASH_CRC_WaitForLastOperation(uint32_t Timeout); -/** - * @} - */ - -/* Exported functions -------------------------------------------------------*/ -/** @defgroup FLASHEx_Exported_Functions FLASH Extended Exported Functions - * @{ - */ - -/** @defgroup FLASHEx_Exported_Functions_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 Extended 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 Status - */ -HAL_StatusTypeDef HAL_FLASHEx_Erase(const FLASH_EraseInitTypeDef *pEraseInit, uint32_t *SectorError) -{ - HAL_StatusTypeDef status; - uint32_t sector_index; - - /* Check the parameters */ - assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status == HAL_OK) - { - if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) - { - /* Mass erase to be done */ - FLASH_MassErase(); - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - } - else - { - /*Initialization of SectorError variable*/ - *SectorError = 0xFFFFFFFFU; - - for (sector_index = pEraseInit->Sector; sector_index < (pEraseInit->Sector + pEraseInit->NbSectors); - sector_index++) - { - FLASH_SectorErase(sector_index); - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status != HAL_OK) - { - /* In case of error, stop erase procedure and return the faulty sector */ - *SectorError = sector_index; - break; - } - } - } - - /* If the erase operation is completed, disable the associated bits */ - CLEAR_BIT(FLASH->CR, (pEraseInit->TypeErase | FLASH_CR_SSN)); - } - - /* 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 Status - */ -HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(const FLASH_EraseInitTypeDef *pEraseInit) -{ - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status != HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - } - else - { - /* Set internal variables used by the IRQ handler */ - pFlash.ProcedureOnGoing = pEraseInit->TypeErase; - - /* Enable End of Operation and Error interrupts */ - SET_BIT(FLASH->IER, (FLASH_IT_EOP | FLASH_IT_WRPERR | FLASH_IT_PGSERR | FLASH_IT_STRBERR | FLASH_IT_INCERR)); - - if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) - { - /* Mass erase to be done */ - FLASH_MassErase(); - } - else - { - /* Erase by sector to be done */ - pFlash.NbSectorsToErase = pEraseInit->NbSectors; - pFlash.Sector = pEraseInit->Sector; - - /* Erase first sector and wait for IT */ - FLASH_SectorErase(pEraseInit->Sector); - } - } - - return status; -} - -/** - * @brief Program Option bytes. - * @param pOBInit pointer to an FLASH_OBInitStruct structure that - * contains the configuration information for the programming. - * - * @note To configure any option bytes, the option lock bit OPTLOCK must be - * cleared with the call of HAL_FLASH_OB_Unlock() function. - * @note New option bytes configuration will be taken into account in two cases: - * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() - * - after a power reset (BOR reset or exit from Standby/Shutdown modes) - * - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASHEx_OBProgram(const FLASH_OBProgramInitTypeDef *pOBInit) -{ - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_OPTIONBYTE(pOBInit->OptionType)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if ((status == HAL_OK) && (pOBInit->OptionType != 0U)) - { - /* Set PG_OPT Bit */ - SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - - /* Write protection configuration */ - if ((pOBInit->OptionType & OPTIONBYTE_WRP) != 0U) - { - /* Configure of Write protection on the selected area */ - FLASH_OB_WRPConfig(pOBInit->WRPState, pOBInit->WRPSector); - } - - /* User Configuration */ - if ((pOBInit->OptionType & OPTIONBYTE_USER) != 0U) - { - /* Configure the user option bytes */ - FLASH_OB_UserConfig(pOBInit->USERType, pOBInit->USERConfig1, pOBInit->USERConfig2); - } - - /* HDP configuration */ - if ((pOBInit->OptionType & OPTIONBYTE_HDP) != 0U) - { - /* Configure the HDP Protection */ - FLASH_OB_HDPConfig(pOBInit->HDPStartPage, pOBInit->HDPEndPage); - } - - /* Non-volatile state configuration */ - if ((pOBInit->OptionType & OPTIONBYTE_NV) != 0U) - { - /* Configure the non-volatile state */ - FLASH_OB_NVConfig(pOBInit->NVState); - } - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - /* Clear PG_OPT Bit */ - CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - } - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - - return status; -} - -/** - * @brief Get the Option bytes configuration. - * @param pOBInit pointer to an FLASH_OBInitStruct structure that contains the - * configuration information. - * @note The fields pOBInit->WRPArea, pOBInit->WMSecConfig and pOBInit->BootAddrConfig - * should indicate which area/address is requested for the WRP, WM Security or - * Boot Address, else no information will be returned - * - * @retval None - */ -void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) -{ - /* Get write protection on the selected area */ - FLASH_OB_GetWRP(&(pOBInit->WRPState), &(pOBInit->WRPSector)); - - /* Get the user option bytes */ - FLASH_OB_GetUser(&(pOBInit->USERConfig1), &(pOBInit->USERConfig2)); - - /* Get the HDP Protection */ - FLASH_OB_GetHDP(&(pOBInit->HDPStartPage), &(pOBInit->HDPEndPage)); - - /* Get the non-volatile state */ - pOBInit->NVState = FLASH_OB_GetNV(); - - /* Get the Root-Of-Trust configuration */ - pOBInit->ROTConfig = FLASH_OB_GetRoT(); - - /* Get the epoch */ - pOBInit->EPOCH = FLASH_OB_GetEpoch(); -} - -/** - * @} - */ - -/** @defgroup FLASHEx_Exported_Functions_Group2 Extended CRC operation functions - * @brief Extended CRC operation functions - * -@verbatim - =============================================================================== - ##### Extended CRC operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the Extended FLASH - CRC Operations. - -@endverbatim - * @{ - */ -/** - * @brief Configure the OTP Lock. - * - * @note To configure the OTP Lock options, the option lock bit OPTLOCK must be - * cleared with the call of the HAL_FLASH_OB_Unlock() function. - * - * @param OTPLBlock Specifies the block(s) to be OTP locked (used for OPTIONBYTE_OTPL). - * The value of this parameter depend on device used within the same series - * - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASHEx_OTPLockConfig(uint32_t OTPLBlock) -{ - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_OB_OTP_BLOCK(OTPLBlock)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status == HAL_OK) - { - /* Set the bit for the OTP programmation */ - SET_BIT(FLASH->CR, FLASH_CR_PG_OTP); - - /* Set PG_OPT Bit */ - SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - - /* Configure the write protected area */ - MODIFY_REG(FLASH->OTPLSRP, FLASH_OTPLSRP_OTPL, (OTPLBlock & FLASH_OTPLSRP_OTPL)); - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - /* Clear PG_OPT Bit */ - CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - - /* Clear the bit for the OTP programmation */ - CLEAR_BIT(FLASH->CR, FLASH_CR_PG_OTP); - } - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - - return status; -} - -/** - * @brief Return the FLASH OTP Lock Option Bytes value. - * - * @retval Status of the OTP Lock - */ -uint32_t HAL_FLASHEx_GetOTPLock(void) -{ - return (FLASH->OTPLSR & FLASH_OTPLSR_OTPL); -} - -/** - * @brief Configure the Keys. - * - * @note To configure the Keys options, the option lock bit OPTLOCK must be - * cleared with the call of the HAL_FLASH_OB_Unlock() function. - * - * @param pKeyConfig Key(s) to be configured. - * - * @param pKey Address of the key - * - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASHEx_KeyConfig(const FLASH_KeyConfigTypeDef *pKeyConfig, const uint32_t *pKey) -{ - uint32_t index; - uint32_t index_max; - const uint32_t *pdata; - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_KEY_INDEX(pKeyConfig->Index)); - assert_param(IS_KEY_SIZE(pKeyConfig->Size)); - assert_param(IS_KEY_HDPL_LEVEL(pKeyConfig->HDPLLevel)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status == HAL_OK) - { - /* Set PG_OPT Bit */ - SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - - switch (pKeyConfig->Size) - { - case FLASH_KEY_32_BITS : - index_max = 1U; - break; - - case FLASH_KEY_64_BITS : - index_max = 2U; - break; - - case FLASH_KEY_128_BITS : - index_max = 4U; - break; - - case FLASH_KEY_256_BITS : - index_max = 8U; - break; - - default: - /* This case should not occur */ - index_max = 0U; - break; - } - - pdata = pKey; - for (index = 0U; index < index_max; index++) - { - FLASH->OBKDR[index] = pdata[index]; - } - - MODIFY_REG(FLASH->OBKCR, (FLASH_OBKCR_OBKINDEX | FLASH_OBKCR_NEXTKL | FLASH_OBKCR_OBKSIZE), - (pKeyConfig->Index | pKeyConfig->HDPLLevel | pKeyConfig->Size)); - - SET_BIT(FLASH->OBKCR, (FLASH_OBKCR_KEYSTART | FLASH_OBKCR_KEYPROG)); - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - CLEAR_BIT(FLASH->OBKCR, FLASH_OBKCR_KEYPROG); - - /* Clear PG_OPT Bit */ - CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - } - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - - return status; -} - -/** - * @brief Load and optionally return the FLASH Option Bytes Key value. - * - * @param pKeyConfig Configuration of the key to be loaded and optionally returned - * - * @param pKey Address to return the FLASH Option Bytes Key value if not NULL. - * - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASHEx_GetKey(const FLASH_KeyConfigTypeDef *pKeyConfig, uint32_t *pKey) -{ - uint32_t index; - uint32_t *pdata; - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_KEY_INDEX(pKeyConfig->Index)); - assert_param(IS_KEY_HDPL_LEVEL(pKeyConfig->HDPLLevel)); - - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status == HAL_OK) - { - /* Set PG_OPT Bit */ - SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - - /* Configure index and HDPL level */ - MODIFY_REG(FLASH->OBKCR, (FLASH_OBKCR_OBKINDEX | FLASH_OBKCR_NEXTKL | FLASH_OBKCR_OBKSIZE | FLASH_OBKCR_KEYPROG), - (pKeyConfig->Index | pKeyConfig->HDPLLevel)); - - /* Set the start bit to get the key value */ - SET_BIT(FLASH->OBKCR, FLASH_OBKCR_KEYSTART); - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if ((status == HAL_OK) && (pKey != NULL)) - { - pdata = pKey; - for (index = 0U; index < 8U; index++) - { - *pdata = FLASH->OBKDR[index]; - pdata++; - } - } - - /* Clear PG_OPT Bit */ - CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); - } - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - - return status; -} - -/** - * @brief Perform a CRC computation on the specified FLASH memory area - * @param pCRCInit pointer to an FLASH_CRCInitTypeDef structure that - * contains the configuration information for the CRC computation. - * @param CRC_Result pointer to CRC result - * @note CRC computation uses CRC-32 (Ethernet) polynomial 0x4C11DB7 - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_FLASHEx_ComputeCRC(const FLASH_CRCInitTypeDef *pCRCInit, uint32_t *CRC_Result) -{ - HAL_StatusTypeDef status; - uint32_t sector_index; - - /* Check the parameters */ - assert_param(IS_FLASH_TYPE_CRC(pCRCInit->TypeCRC)); - assert_param(IS_FLASH_BURST_SIZE_CRC(pCRCInit->BurstSize)); - - /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); - - if (status == HAL_OK) - { - /* Process Locked */ - __HAL_LOCK(&pFlash); - - /* Reset error code */ - pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; - - /* Enable CRC feature */ - SET_BIT(FLASH->CR, FLASH_CR_CRC_EN); - - /* Clear CRC flags in Status Register: CRC end of calculation and CRC read error */ - FLASH->ICR = (FLASH_ICR_CRCRDERRF | FLASH_ICR_CRCENDF); - - /* Clear current CRC result and program burst size */ - MODIFY_REG(FLASH->CRCCR, (FLASH_CRCCR_CLEAN_CRC | FLASH_CRCCR_CRC_BURST), - (FLASH_CRCCR_CLEAN_CRC | pCRCInit->BurstSize)); - - if (pCRCInit->TypeCRC == FLASH_CRC_SECTORS) - { - /* Select CRC by sector and clear sectors list */ - SET_BIT(FLASH->CRCCR, (FLASH_CRCCR_CRC_BY_SECT | FLASH_CRCCR_CLEAN_SECT)); - - /* Select CRC sectors */ - for (sector_index = pCRCInit->Sector; sector_index < (pCRCInit->NbSectors + pCRCInit->Sector); sector_index++) - { - FLASH_CRC_AddSector(sector_index); - } - } - else if (pCRCInit->TypeCRC == FLASH_CRC_BANK) - { - /* Select CRC by sector and all sectors */ - SET_BIT(FLASH->CRCCR, (FLASH_CRCCR_CRC_BY_SECT | FLASH_CRCCR_ALL_SECT)); - } - else - { - /* Select CRC by address */ - CLEAR_BIT(FLASH->CRCCR, FLASH_CRCCR_CRC_BY_SECT); - - /* Select CRC start and end addresses */ - FLASH_CRC_SelectAddress(pCRCInit->CRCStartAddr, pCRCInit->CRCEndAddr); - } - - /* Start the CRC calculation */ - SET_BIT(FLASH->CRCCR, FLASH_CRCCR_START_CRC); - - /* Wait on CRC busy flag */ - status = FLASH_CRC_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); - - /* Return CRC result */ - (*CRC_Result) = FLASH->CRCDATAR; - - /* Disable CRC feature */ - CLEAR_BIT(FLASH->CR, FLASH_CR_CRC_EN); - - /* Clear CRC flags */ - FLASH->ICR = (FLASH_ICR_CRCRDERRF | FLASH_ICR_CRCENDF); - - /* Process Unlocked */ - __HAL_UNLOCK(&pFlash); - } - - return status; -} - -/** - * @} - */ - -/** @defgroup FLASHEx_Exported_Functions_Group3 Extended ECC operation functions - * @brief Extended ECC operation functions - * -@verbatim - =============================================================================== - ##### Extended ECC operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the Extended FLASH - ECC Operations. - -@endverbatim - * @{ - */ -/** - * @brief Enable ECC correction interrupt - * @retval None - */ -void HAL_FLASHEx_EnableEccCorrectionInterrupt(void) -{ - __HAL_FLASH_ENABLE_IT(FLASH_IT_SNECCERR); -} - -/** - * @brief Disable ECC correction interrupt - * @retval None - */ -void HAL_FLASHEx_DisableEccCorrectionInterrupt(void) -{ - __HAL_FLASH_DISABLE_IT(FLASH_IT_SNECCERR); -} - -/** - * @brief Enable ECC detection interrupt - * @retval None - */ -void HAL_FLASHEx_EnableEccDetectionInterrupt(void) -{ - __HAL_FLASH_ENABLE_IT(FLASH_IT_DBECCERR); -} - -/** - * @brief Disable ECC detection interrupt - * @retval None - */ -void HAL_FLASHEx_DisableEccDetectionInterrupt(void) -{ - __HAL_FLASH_DISABLE_IT(FLASH_IT_DBECCERR); -} - -/** - * @brief Get the ECC error information. - * @param pData Pointer to an FLASH_EccInfoTypeDef structure that contains the - * ECC error information. - * @note This function should be called before ECC bit is cleared - * (in callback function) - * @retval None - */ -void HAL_FLASHEx_GetEccInfo(FLASH_EccInfoTypeDef *pData) -{ - /* Check Null pointer */ - assert_param(pData != NULL); - - /* Set address which generate ECC error */ - if ((FLASH->ISR & FLASH_FLAG_SNECCERR) != 0U) - { - pData->Address = FLASH->ECCSFADDR; - } - else - { - pData->Address = FLASH->ECCDFADDR; - } - - /* Set area according address */ - if (IS_FLASH_MAIN_MEM_ADDRESS(pData->Address)) - { - pData->Area = FLASH_ECC_AREA_USER_BANK1; - } - else if (IS_FLASH_OTP_ADDRESS(pData->Address)) - { - pData->Area = FLASH_ECC_AREA_OTP; - } - else if ((pData->Address >= SYSTEM_FLASH_BASE) && - (pData->Address < (SYSTEM_FLASH_BASE + SYSTEM_FLASH_SIZE))) - { - pData->Area = FLASH_ECC_AREA_SYSTEM; - } - else - { - pData->Area = FLASH_ECC_AREA_READ_ONLY; - } - - /* Set Master which initiates transaction. On H7RS, it's necessary CPU1 */ - pData->MasterID = FLASH_ECC_MASTER_CPU1; -} - -/** - * @brief Handle Flash ECC Detection interrupt request. - * @note On STM32H7RS, this Irq Handler should be called in Bus Fault - * interrupt subroutine. - * @retval None - */ -void HAL_FLASHEx_ECCD_IRQHandler(void) -{ - /* Check ECC Detection Error */ - if ((FLASH->ISR & FLASH_FLAG_DBECCERR) != 0U) - { - /* Call User callback */ - HAL_FLASHEx_EccDetectionCallback(); - - /* Clear ECC detection flag in order to allow new ECC error record */ - FLASH->ICR = FLASH_FLAG_DBECCERR; - } -} - -/** - * @brief FLASH ECC Correction interrupt callback. - * @retval None - */ -__weak void HAL_FLASHEx_EccCorrectionCallback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_FLASHEx_EccCorrectionCallback could be implemented in the user file - */ -} - -/** - * @brief FLASH ECC Detection interrupt callback. - * @retval None - */ -__weak void HAL_FLASHEx_EccDetectionCallback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_FLASHEx_EccDetectionCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ - -/** @addtogroup FLASHEx_Private_Functions - * @{ - */ -/** - * @brief Mass erase of FLASH memory. - * @retval None - */ -static void FLASH_MassErase(void) -{ - /* Set the Mass Erase Bit and proceed to erase */ - SET_BIT(FLASH->CR, (FLASH_CR_BER | FLASH_CR_START)); -} - -/** - * @brief Erase the specified FLASH memory sector. - * @param Sector FLASH sector to erase - * This parameter must be a value between 0 and (max number of sectors in the bank - 1) - * @retval None - */ -void FLASH_SectorErase(uint32_t Sector) -{ - /* Check the parameters */ - assert_param(IS_FLASH_SECTOR(Sector)); - - /* Proceed to erase the page */ - MODIFY_REG(FLASH->CR, (FLASH_CR_SSN | FLASH_CR_SER | FLASH_CR_START), \ - ((Sector << FLASH_CR_SSN_Pos) | FLASH_CR_SER | FLASH_CR_START)); -} - -/** - * @brief Configure the write protection of the desired sectors. - * - * @note To configure the WRP options, the option lock bit OPTLOCK must be - * cleared with the call of the HAL_FLASH_OB_Unlock() function. - * - * @param WRPState - * - * @param WRPSector - * - * @retval None - */ -static void FLASH_OB_WRPConfig(uint32_t WRPState, uint32_t WRPSector) -{ - /* Check the parameters */ - assert_param(IS_OB_WRPSTATE(WRPState)); - - /* Configure the write protected area */ - if (WRPState == OB_WRPSTATE_DISABLE) - { - FLASH->WRPSRP |= (WRPSector & FLASH_WRPSRP_WRPS); - } - else if (WRPState == OB_WRPSTATE_ENABLE) - { - FLASH->WRPSRP &= (~(WRPSector & FLASH_WRPSRP_WRPS)); - } - else - { - /* Empty statement (to be compliant MISRA 15.7) */ - } -} - -/** - * @brief Program the FLASH User Option Byte. - * - * @note To configure the user option bytes, the option lock bit OPTLOCK must - * be cleared with the call of the HAL_FLASH_OB_Unlock() function. - * @param UserType: The FLASH User Option Bytes to be modified. - * This parameter can be a combination of @ref FLASH_OB_USER_TYPE - * @param UserConfig1 The selected User Option Bytes values - * @param UserConfig2 The selected User Option Bytes values - * @retval None - */ -static void FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig1, uint32_t UserConfig2) -{ - uint32_t optr_reg_val = 0; - uint32_t optr_reg_mask = 0; - - /* Check the parameters */ - assert_param(IS_OB_USER_TYPE(UserType)); - - if ((UserType & OB_USER_BOR_LEV) != 0U) - { - /* BOR level option byte should be modified */ - assert_param(IS_OB_USER_BOR_LEVEL(UserConfig1 & FLASH_OBW1SR_BOR_LEVEL)); - - /* Set value and mask for BOR level option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_BOR_LEVEL); - optr_reg_mask |= FLASH_OBW1SR_BOR_LEVEL; - } - - if ((UserType & OB_USER_IWDG_SW) != 0U) - { - /* IWDG1_HW option byte should be modified */ - assert_param(IS_OB_USER_IWDG(UserConfig1 & FLASH_OBW1SR_IWDG_HW)); - - /* Set value and mask for IWDG1_HW option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_IWDG_HW); - optr_reg_mask |= FLASH_OBW1SR_IWDG_HW; - } - - if ((UserType & OB_USER_NRST_STOP) != 0U) - { - /* NRST_STOP_D1 option byte should be modified */ - assert_param(IS_OB_USER_STOP(UserConfig1 & FLASH_OBW1SR_NRST_STOP)); - - /* Set value and mask for NRST_STOP_D1 option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_NRST_STOP); - optr_reg_mask |= FLASH_OBW1SR_NRST_STOP; - } - - if ((UserType & OB_USER_NRST_STDBY) != 0U) - { - /* NRST_STBY_D1 option byte should be modified */ - assert_param(IS_OB_USER_STANDBY(UserConfig1 & FLASH_OBW1SR_NRST_STBY)); - - /* Set value and mask for NRST_STBY_D1 option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_NRST_STBY); - optr_reg_mask |= FLASH_OBW1SR_NRST_STBY; - } - - if ((UserType & OB_USER_XSPI1_HSLV) != 0U) - { - /* XSPI1_HSLV option byte should be modified */ - assert_param(IS_OB_USER_XSPI1_HSLV(UserConfig1 & FLASH_OBW1SR_XSPI1_HSLV)); - - /* Set value and mask for XSPI1_HSLV option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_XSPI1_HSLV); - optr_reg_mask |= FLASH_OBW1SR_XSPI1_HSLV; - } - - if ((UserType & OB_USER_XSPI2_HSLV) != 0U) - { - /* XSPI2_HSLV option byte should be modified */ - assert_param(IS_OB_USER_XSPI2_HSLV(UserConfig1 & FLASH_OBW1SR_XSPI2_HSLV)); - - /* Set value and mask for XSPI2_HSLV option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_XSPI2_HSLV); - optr_reg_mask |= FLASH_OBW1SR_XSPI2_HSLV; - } - - if ((UserType & OB_USER_IWDG_STOP) != 0U) - { - /* IWDG_FZ_STOP option byte should be modified */ - assert_param(IS_OB_USER_IWDG_STOP(UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STOP)); - - /* Set value and mask for IWDG_FZ_STOP option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STOP); - optr_reg_mask |= FLASH_OBW1SR_IWDG_FZ_STOP; - } - - if ((UserType & OB_USER_IWDG_STDBY) != 0U) - { - /* IWDG_FZ_SDBY option byte should be modified */ - assert_param(IS_OB_USER_IWDG_STDBY(UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STBY)); - - /* Set value and mask for IWDG_FZ_SDBY option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STBY); - optr_reg_mask |= FLASH_OBW1SR_IWDG_FZ_STBY; - } - - if ((UserType & OB_USER_VDDIO_HSLV) != 0U) - { - /* VDDIO_HSLV option byte should be modified */ - assert_param(IS_OB_USER_VDDIO_HSLV(UserConfig1 & FLASH_OBW1SR_VDDIO_HSLV)); - - /* Set value and mask for VDDIO_HSLV option byte */ - optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_VDDIO_HSLV); - optr_reg_mask |= FLASH_OBW1SR_VDDIO_HSLV; - } - - /* Configure the option bytes register 1 if necessary */ - if (optr_reg_mask != 0U) - { - MODIFY_REG(FLASH->OBW1SRP, optr_reg_mask, optr_reg_val); - } - - optr_reg_val = 0; - optr_reg_mask = 0; - - if ((UserType & OB_USER_ITCM_AXI_SHARE) != 0U) - { - /* ITCM_AXI_SHARE option byte should be modified */ - assert_param(IS_OB_USER_ITCM_AXI_SHARE(UserConfig2 & FLASH_OBW2SR_ITCM_AXI_SHARE)); - - /* Set value and mask for ITCM_AXI_SHARE option byte */ - optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_ITCM_AXI_SHARE); - optr_reg_mask |= FLASH_OBW2SR_ITCM_AXI_SHARE; - } - - if ((UserType & OB_USER_DTCM_AXI_SHARE) != 0U) - { - /* DTCM_AXI_SHARE option byte should be modified */ - assert_param(IS_OB_USER_DTCM_AXI_SHARE(UserConfig2 & FLASH_OBW2SR_DTCM_AXI_SHARE)); - - /* Set value and mask for DTCM_AXI_SHARE option byte */ - optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_DTCM_AXI_SHARE); - optr_reg_mask |= FLASH_OBW2SR_DTCM_AXI_SHARE; - } - - if ((UserType & OB_USER_SRAM_ECC) != 0U) - { - /* SRAM_ECC option byte should be modified */ - assert_param(IS_OB_USER_AXISRAM_ECC(UserConfig2 & FLASH_OBW2SR_ECC_ON_SRAM)); - - /* Set value and mask for SRAM_ECC option byte */ - optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_ECC_ON_SRAM); - optr_reg_mask |= FLASH_OBW2SR_ECC_ON_SRAM; - } - - if ((UserType & OB_USER_I2C_NI3C) != 0U) - { - /* I2C_NI3C option byte should be modified */ - assert_param(IS_OB_USER_I2C_NI3C(UserConfig2 & FLASH_OBW2SR_I2C_NI3C)); - - /* Set value and mask for I2C_NI3C option byte */ - optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_I2C_NI3C); - optr_reg_mask |= FLASH_OBW2SR_I2C_NI3C; - } - - /* Configure the option bytes register 2 if necessary */ - if (optr_reg_mask != 0U) - { - MODIFY_REG(FLASH->OBW2SRP, optr_reg_mask, optr_reg_val); - } -} - -/** - * @brief Configure the Hide Protection. - * - * @note To configure the HDP options, the option lock bit OPTLOCK must be - * cleared with the call of the HAL_FLASH_OB_Unlock() function. - * - * @param HDPStartPage - * - * @param HDPEndPage - * - * @retval None - */ -static void FLASH_OB_HDPConfig(uint32_t HDPStartPage, uint32_t HDPEndPage) -{ - /* Check the parameters */ - assert_param(IS_OB_HDP_PAGE(HDPStartPage)); - assert_param(IS_OB_HDP_PAGE(HDPEndPage)); - - MODIFY_REG(FLASH->HDPSRP, (FLASH_HDPSRP_HDP_AREA_START | FLASH_HDPSRP_HDP_AREA_END), \ - (HDPStartPage | (HDPEndPage << FLASH_HDPSRP_HDP_AREA_END_Pos))); -} - -/** - * @brief Configure the Non-Volatile state. - * - * @note To configure the Non-volatile options, the option lock bit OPTLOCK must be - * cleared with the call of the HAL_FLASH_OB_Unlock() function. - * - * @param NVState - * - * @retval None - */ -static void FLASH_OB_NVConfig(uint32_t NVState) -{ - /* Check the parameter */ - assert_param(IS_OB_NVSTATE(NVState)); - - MODIFY_REG(FLASH->NVSRP, FLASH_NVSRP_NVSTATE, NVState); -} - -/** - * @brief Return the FLASH Write Protection Option Bytes value. - * - * @param WRPState - * - * @param WRPSector - * - * @retval None - */ -static void FLASH_OB_GetWRP(uint32_t *WRPState, uint32_t *WRPSector) -{ - if ((FLASH->WRPSR & FLASH_WRPSR_WRPS) == FLASH_WRPSR_WRPS) - { - /* All sectors aren't write protected */ - *WRPState = OB_WRPSTATE_DISABLE; - } - else - { - /* Some sectors are write protected */ - *WRPState = OB_WRPSTATE_ENABLE; - *WRPSector = ((~(FLASH->WRPSR)) & FLASH_WRPSR_WRPS); - } -} - -/** - * @brief Return the FLASH User Option Byte value. - * - * @param UserConfig1 Address to return the FLASH User Option Bytes values configuration 1. - * The return value can be a combination of - * @param UserConfig2 Address to return the FLASH User Option Bytes values configuration 2. - * The return value can be a combination of - * - * @retval None - */ -static void FLASH_OB_GetUser(uint32_t *UserConfig1, uint32_t *UserConfig2) -{ - *UserConfig1 = FLASH->OBW1SR; - *UserConfig2 = FLASH->OBW2SR; -} - -/** - * @brief Return the FLASH Hide Protection Option Bytes value. - * - * @param HDPStartPage Address to return the FLASH HDP Option Bytes Start Sector. - * The return value can be a combination of - * @param HDPEndPage Address to return the FLASH HDP Option Bytes End Sector. - * The return value can be a combination of - * - * @retval None - */ -static void FLASH_OB_GetHDP(uint32_t *HDPStartPage, uint32_t *HDPEndPage) -{ - *HDPStartPage = (FLASH->HDPSR & FLASH_HDPSR_HDP_AREA_START); - *HDPEndPage = ((FLASH->HDPSR & FLASH_HDPSR_HDP_AREA_END) >> FLASH_HDPSR_HDP_AREA_END_Pos); -} - -/** - * @brief Return the FLASH Non-volatile state Option Bytes value. - * - * @retval Value of Non-volatile state - */ -static uint32_t FLASH_OB_GetNV(void) -{ - return (FLASH->NVSR & FLASH_NVSR_NVSTATE); -} - -/** - * @brief Return the FLASH RoT Option Bytes value. - * - * @retval Value of the RoT - */ -static uint32_t FLASH_OB_GetRoT(void) -{ - return (FLASH->ROTSR & (FLASH_ROTSR_OEM_PROVD | FLASH_ROTSR_DBG_AUTH | FLASH_ROTSR_IROT_SELECT)); -} - -/** - * @brief Return the FLASH Epoch Option Bytes value. - * - * @retval Value of the Epoch - */ -static uint32_t FLASH_OB_GetEpoch(void) -{ - return (FLASH->EPOCHSR & FLASH_EPOCHSR_EPOCH); -} - -/** - * @brief Add a CRC sector to the list of sectors on which the CRC will be calculated - * @param Sector Specifies the CRC sector number - * @retval None - */ -static void FLASH_CRC_AddSector(uint32_t Sector) -{ - /* Check the parameters */ - assert_param(IS_FLASH_SECTOR(Sector)); - - /* Clear CRC sector */ - MODIFY_REG(FLASH->CRCCR, FLASH_CRCCR_CRC_SECT, Sector); - - /* Activate ADD_SECT bit */ - SET_BIT(FLASH->CRCCR, FLASH_CRCCR_ADD_SECT); -} - -/** - * @brief Select CRC start and end memory addresses on which the CRC will be calculated - * @param CRCStartAddr Specifies the CRC start address - * @param CRCEndAddr Specifies the CRC end address - * @retval None - */ -static void FLASH_CRC_SelectAddress(uint32_t CRCStartAddr, uint32_t CRCEndAddr) -{ - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(CRCStartAddr)); - assert_param(IS_FLASH_MAIN_MEM_ADDRESS(CRCEndAddr)); - - /* Write CRC Start and End addresses */ - FLASH->CRCSADDR = (CRCStartAddr - FLASH_BASE); - FLASH->CRCEADDR = (CRCEndAddr - FLASH_BASE); -} - -/** - * @brief Wait for a FLASH CRC computation to complete. - * @param Timeout maximum flash operation timeout - * @retval HAL_StatusTypeDef HAL Status - */ -static HAL_StatusTypeDef FLASH_CRC_WaitForLastOperation(uint32_t Timeout) -{ - uint32_t timeout = HAL_GetTick() + Timeout; - - /* Wait for the FLASH CRC computation to complete by polling on CRC_BUSY flag to be reset */ - while ((FLASH->SR & FLASH_SR_CRC_BUSY) != 0U) - { - if (HAL_GetTick() >= timeout) - { - return HAL_TIMEOUT; - } - } - - /* Check FLASH CRC calculation error flag */ - if ((FLASH->ISR & FLASH_FLAG_CRCERR) != 0U) - { - /*Save the error code*/ - pFlash.ErrorCode |= HAL_FLASH_ERROR_CRC; - - /* Clear CRC error flag */ - FLASH->ICR = FLASH_FLAG_CRCERR; - - return HAL_ERROR; - } - - /* Check FLASH CRC End of Calculation flag */ - if ((FLASH->ISR & FLASH_FLAG_CRCEND) != 0U) - { - /* Clear FLASH End of Calculation pending bit */ - FLASH->ICR = FLASH_FLAG_CRCEND; - } - - /* If there is no error flag set */ - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_FLASH_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_flash_ex.c + * @author MCD Application Team + * @brief Extended FLASH HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the FLASH extended peripheral: + * + Extended programming operations functions + * + @verbatim + ============================================================================== + ##### Flash Extended features ##### + ============================================================================== + + [..] Comparing to other previous devices, the FLASH interface for STM32H7RSxx + devices contains the following additional features + + (+) Non-volatile state, Root-Of-Trust and Epoch option bytes + (+) Option byte keys associated with hide protection level + (+) CRC hardware module to check integrity + (+) OTP blocks lock mechanism + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure and program the FLASH memory + of all STM32H7RSxx devices. It includes: + (#) Flash Memory Erase functions: + (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and + HAL_FLASH_Lock() functions + (++) Erase function: Sector Erase and Mass Erase + (++) There are two modes of erase : + (+++) Polling Mode using HAL_FLASHEx_Erase() + (+++) Interrupt Mode using HAL_FLASHEx_Erase_IT() + + (#) Option Bytes Programming function: Use HAL_FLASHEx_OBProgram() to: + (++) Configure the write protection for each sector + (++) Program the user Option Bytes + (++) Configure the hide protection area + (++) Configure the non-volatile state + + (#) Get Option Bytes Configuration function: Use HAL_FLASHEx_OBGetConfig() to: + (++) Get the value of the sectors write protection + (++) Get the value of the user Option Bytes + (++) Get the configuration of the hide protection area + (++) Get the value of the non-volatile state + (++) Get the value of the Root-Of-Trust configuration + (++) Get the value of the Epoch + + (#) OTP lock configuration function: Use HAL_FLASHEx_OTPLockConfig() + (++) Activate the lock of an OTP block + + (#) Get the OTP lock configuration function: Use HAL_FLASHEx_GetOTPLock() + (++) Get the value of the OTP blocks lock configuration + + (#) Option Byte Keys configuration function: Use HAL_FLASHEx_KeyConfig() + (++) Program an option key for a specified hide protection level + + (#) Get an option byte key value: Use HAL_FLASHEx_GetKey() + (++) Get the value of an option byte key for a specified hide protection level + + (#) Perform a CRC computation function: Use HAL_FLASHEx_ComputeCRC() + (++) Perform CRC computation on a area defined either by sectors or by start/end + addresses and return computation result + + (#) ECC management functions: + (++) Handle ECC Detection flash interrupt by calling HAL_FLASHEx_ECCD_IRQHandler() + (++) Callback functions are called when the ECC detection or correction occurs : + HAL_FLASHEx_EccDetectionCallback() for ECC detection, otherwise + HAL_FLASHEx_EccCorrectionCallback() + (++) Get information about ECC error by calling HAL_FLASHEx_GetEccInfo() + (++) Enable/Disable the ECC correction and detection interrupts: + (+++) HAL_FLASHEx_EnableEccCorrectionInterrupt() to enable ECC correction interrupt + (+++) HAL_FLASHEx_DisableEccCorrectionInterrupt() to disable ECC correction interrupt + (+++) HAL_FLASHEx_EnableEccDetectionInterrupt() to enable ECC detection interrupt + (+++) HAL_FLASHEx_DisableEccDetectionInterrupt() to disable ECC detection interrupt + + @endverbatim + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup FLASHEx FLASHEx + * @brief FLASH Extended HAL module driver + * @{ + */ + +#ifdef HAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define SYSTEM_FLASH_SIZE 0x00020000UL /*!< System Flash size : 128 KB */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup FLASHEx_Private_Functions FLASHEx Private Functions + * @{ + */ +static void FLASH_MassErase(void); + +static void FLASH_OB_WRPConfig(uint32_t WRPState, uint32_t WRPSector); +static void FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig1, uint32_t UserConfig2); +static void FLASH_OB_HDPConfig(uint32_t HDPStartPage, uint32_t HDPEndPage); +static void FLASH_OB_NVConfig(uint32_t NVState); + +static void FLASH_OB_GetWRP(uint32_t *WRPState, uint32_t *WRPSector); +static void FLASH_OB_GetUser(uint32_t *UserConfig1, uint32_t *UserConfig2); +static void FLASH_OB_GetHDP(uint32_t *HDPStartPage, uint32_t *HDPEndPage); +static uint32_t FLASH_OB_GetNV(void); +static uint32_t FLASH_OB_GetRoT(void); +static uint32_t FLASH_OB_GetEpoch(void); + +static void FLASH_CRC_AddSector(uint32_t Sector); +static void FLASH_CRC_SelectAddress(uint32_t CRCStartAddr, uint32_t CRCEndAddr); +static HAL_StatusTypeDef FLASH_CRC_WaitForLastOperation(uint32_t Timeout); +/** + * @} + */ + +/* Exported functions -------------------------------------------------------*/ +/** @defgroup FLASHEx_Exported_Functions FLASH Extended Exported Functions + * @{ + */ + +/** @defgroup FLASHEx_Exported_Functions_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 Extended 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 Status + */ +HAL_StatusTypeDef HAL_FLASHEx_Erase(const FLASH_EraseInitTypeDef *pEraseInit, uint32_t *SectorError) +{ + HAL_StatusTypeDef status; + uint32_t sector_index; + + /* Check the parameters */ + assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) + { + /* Mass erase to be done */ + FLASH_MassErase(); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + } + else + { + /*Initialization of SectorError variable*/ + *SectorError = 0xFFFFFFFFU; + + for (sector_index = pEraseInit->Sector; sector_index < (pEraseInit->Sector + pEraseInit->NbSectors); + sector_index++) + { + FLASH_SectorErase(sector_index); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status != HAL_OK) + { + /* In case of error, stop erase procedure and return the faulty sector */ + *SectorError = sector_index; + break; + } + } + } + + /* If the erase operation is completed, disable the associated bits */ + CLEAR_BIT(FLASH->CR, (pEraseInit->TypeErase | FLASH_CR_SSN)); + } + + /* 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 Status + */ +HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(const FLASH_EraseInitTypeDef *pEraseInit) +{ + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status != HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + } + else + { + /* Set internal variables used by the IRQ handler */ + pFlash.ProcedureOnGoing = pEraseInit->TypeErase; + + /* Enable End of Operation and Error interrupts */ + SET_BIT(FLASH->IER, (FLASH_IT_EOP | FLASH_IT_WRPERR | FLASH_IT_PGSERR | FLASH_IT_STRBERR | FLASH_IT_INCERR)); + + if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) + { + /* Mass erase to be done */ + FLASH_MassErase(); + } + else + { + /* Erase by sector to be done */ + pFlash.NbSectorsToErase = pEraseInit->NbSectors; + pFlash.Sector = pEraseInit->Sector; + + /* Erase first sector and wait for IT */ + FLASH_SectorErase(pEraseInit->Sector); + } + } + + return status; +} + +/** + * @brief Program Option bytes. + * @param pOBInit pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @note To configure any option bytes, the option lock bit OPTLOCK must be + * cleared with the call of HAL_FLASH_OB_Unlock() function. + * @note New option bytes configuration will be taken into account in two cases: + * - after an option bytes launch through the call of HAL_FLASH_OB_Launch() + * - after a power reset (BOR reset or exit from Standby/Shutdown modes) + * + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_OBProgram(const FLASH_OBProgramInitTypeDef *pOBInit) +{ + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_OPTIONBYTE(pOBInit->OptionType)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if ((status == HAL_OK) && (pOBInit->OptionType != 0U)) + { + /* Set PG_OPT Bit */ + SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + + /* Write protection configuration */ + if ((pOBInit->OptionType & OPTIONBYTE_WRP) != 0U) + { + /* Configure of Write protection on the selected area */ + FLASH_OB_WRPConfig(pOBInit->WRPState, pOBInit->WRPSector); + } + + /* User Configuration */ + if ((pOBInit->OptionType & OPTIONBYTE_USER) != 0U) + { + /* Configure the user option bytes */ + FLASH_OB_UserConfig(pOBInit->USERType, pOBInit->USERConfig1, pOBInit->USERConfig2); + } + + /* HDP configuration */ + if ((pOBInit->OptionType & OPTIONBYTE_HDP) != 0U) + { + /* Configure the HDP Protection */ + FLASH_OB_HDPConfig(pOBInit->HDPStartPage, pOBInit->HDPEndPage); + } + + /* Non-volatile state configuration */ + if ((pOBInit->OptionType & OPTIONBYTE_NV) != 0U) + { + /* Configure the non-volatile state */ + FLASH_OB_NVConfig(pOBInit->NVState); + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + /* Clear PG_OPT Bit */ + CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Get the Option bytes configuration. + * @param pOBInit pointer to an FLASH_OBInitStruct structure that contains the + * configuration information. + * @note The fields pOBInit->WRPArea, pOBInit->WMSecConfig and pOBInit->BootAddrConfig + * should indicate which area/address is requested for the WRP, WM Security or + * Boot Address, else no information will be returned + * + * @retval None + */ +void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) +{ + /* Get write protection on the selected area */ + FLASH_OB_GetWRP(&(pOBInit->WRPState), &(pOBInit->WRPSector)); + + /* Get the user option bytes */ + FLASH_OB_GetUser(&(pOBInit->USERConfig1), &(pOBInit->USERConfig2)); + + /* Get the HDP Protection */ + FLASH_OB_GetHDP(&(pOBInit->HDPStartPage), &(pOBInit->HDPEndPage)); + + /* Get the non-volatile state */ + pOBInit->NVState = FLASH_OB_GetNV(); + + /* Get the Root-Of-Trust configuration */ + pOBInit->ROTConfig = FLASH_OB_GetRoT(); + + /* Get the epoch */ + pOBInit->EPOCH = FLASH_OB_GetEpoch(); +} + +/** + * @} + */ + +/** @defgroup FLASHEx_Exported_Functions_Group2 Extended protection operation functions + * @brief Extended protection operation functions + * +@verbatim + =============================================================================== + ##### Extended protection operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the Extended FLASH + CRC operations, OTP lock mechanism and option byte keys management. + +@endverbatim + * @{ + */ +/** + * @brief Configure the OTP Lock. + * + * @note To configure the OTP Lock options, the option lock bit OPTLOCK must be + * cleared with the call of the HAL_FLASH_OB_Unlock() function. + * + * @param OTPLBlock Specifies the block(s) to be OTP locked (used for OPTIONBYTE_OTPL). + * The value of this parameter depend on device used within the same series + * + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_OTPLockConfig(uint32_t OTPLBlock) +{ + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_OB_OTP_BLOCK(OTPLBlock)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + /* Set the bit for the OTP programmation */ + SET_BIT(FLASH->CR, FLASH_CR_PG_OTP); + + /* Set PG_OPT Bit */ + SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + + /* Configure the write protected area */ + MODIFY_REG(FLASH->OTPLSRP, FLASH_OTPLSRP_OTPL, (OTPLBlock & FLASH_OTPLSRP_OTPL)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + /* Clear PG_OPT Bit */ + CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + + /* Clear the bit for the OTP programmation */ + CLEAR_BIT(FLASH->CR, FLASH_CR_PG_OTP); + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Return the FLASH OTP Lock Option Bytes value. + * + * @retval Status of the OTP Lock + */ +uint32_t HAL_FLASHEx_GetOTPLock(void) +{ + return (FLASH->OTPLSR & FLASH_OTPLSR_OTPL); +} + +/** + * @brief Configure the Keys. + * + * @note To configure the Keys options, the option lock bit OPTLOCK must be + * cleared with the call of the HAL_FLASH_OB_Unlock() function. + * + * @param pKeyConfig Key(s) to be configured. + * + * @param pKey Address of the key + * + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_KeyConfig(const FLASH_KeyConfigTypeDef *pKeyConfig, const uint32_t *pKey) +{ + uint32_t index; + uint32_t index_max; + const uint32_t *pdata; + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_KEY_INDEX(pKeyConfig->Index)); + assert_param(IS_KEY_SIZE(pKeyConfig->Size)); + assert_param(IS_KEY_HDPL_LEVEL(pKeyConfig->HDPLLevel)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + /* Set PG_OPT Bit */ + SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + + switch (pKeyConfig->Size) + { + case FLASH_KEY_32_BITS : + index_max = 1U; + break; + + case FLASH_KEY_64_BITS : + index_max = 2U; + break; + + case FLASH_KEY_128_BITS : + index_max = 4U; + break; + + case FLASH_KEY_256_BITS : + index_max = 8U; + break; + + default: + /* This case should not occur */ + index_max = 0U; + break; + } + + pdata = pKey; + for (index = 0U; index < index_max; index++) + { + FLASH->OBKDR[index] = pdata[index]; + } + + MODIFY_REG(FLASH->OBKCR, (FLASH_OBKCR_OBKINDEX | FLASH_OBKCR_NEXTKL | FLASH_OBKCR_OBKSIZE), + (pKeyConfig->Index | pKeyConfig->HDPLLevel | pKeyConfig->Size)); + + SET_BIT(FLASH->OBKCR, (FLASH_OBKCR_KEYSTART | FLASH_OBKCR_KEYPROG)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + CLEAR_BIT(FLASH->OBKCR, FLASH_OBKCR_KEYPROG); + + /* Clear PG_OPT Bit */ + CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Load and optionally return the FLASH Option Bytes Key value. + * + * @param pKeyConfig Configuration of the key to be loaded and optionally returned + * + * @param pKey Address to return the FLASH Option Bytes Key value if not NULL. + * + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_GetKey(const FLASH_KeyConfigTypeDef *pKeyConfig, uint32_t *pKey) +{ + uint32_t index; + uint32_t index_max; + uint32_t *pdata; + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_KEY_INDEX(pKeyConfig->Index)); + assert_param(IS_KEY_SIZE(pKeyConfig->Size)); + assert_param(IS_KEY_HDPL_LEVEL(pKeyConfig->HDPLLevel)); + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + /* Set PG_OPT Bit */ + SET_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + + /* Configure index and HDPL level */ + MODIFY_REG(FLASH->OBKCR, (FLASH_OBKCR_OBKINDEX | FLASH_OBKCR_NEXTKL | FLASH_OBKCR_OBKSIZE | FLASH_OBKCR_KEYPROG), + (pKeyConfig->Index | pKeyConfig->HDPLLevel | pKeyConfig->Size)); + + /* Set the start bit to get the key value */ + SET_BIT(FLASH->OBKCR, FLASH_OBKCR_KEYSTART); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if ((status == HAL_OK) && (pKey != NULL)) + { + switch (pKeyConfig->Size) + { + case FLASH_KEY_32_BITS : + index_max = 1U; + break; + + case FLASH_KEY_64_BITS : + index_max = 2U; + break; + + case FLASH_KEY_128_BITS : + index_max = 4U; + break; + + case FLASH_KEY_256_BITS : + index_max = 8U; + break; + + default: + /* This case should not occur */ + index_max = 0U; + break; + } + + pdata = pKey; + for (index = 0U; index < index_max; index++) + { + *pdata = FLASH->OBKDR[index]; + pdata++; + } + } + + /* Clear PG_OPT Bit */ + CLEAR_BIT(FLASH->OPTCR, FLASH_OPTCR_PG_OPT); + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Perform a CRC computation on the specified FLASH memory area + * @param pCRCInit pointer to an FLASH_CRCInitTypeDef structure that + * contains the configuration information for the CRC computation. + * @param CRC_Result pointer to CRC result + * @note CRC computation uses CRC-32 (Ethernet) polynomial 0x4C11DB7 + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_ComputeCRC(const FLASH_CRCInitTypeDef *pCRCInit, uint32_t *CRC_Result) +{ + HAL_StatusTypeDef status; + uint32_t sector_index; + + /* Check the parameters */ + assert_param(IS_FLASH_TYPE_CRC(pCRCInit->TypeCRC)); + assert_param(IS_FLASH_BURST_SIZE_CRC(pCRCInit->BurstSize)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Reset error code */ + pFlash.ErrorCode = HAL_FLASH_ERROR_NONE; + + /* Enable CRC feature */ + SET_BIT(FLASH->CR, FLASH_CR_CRC_EN); + + /* Clear CRC flags in Status Register: CRC end of calculation and CRC read error */ + FLASH->ICR = (FLASH_ICR_CRCRDERRF | FLASH_ICR_CRCENDF); + + /* Clear current CRC result and program burst size */ + MODIFY_REG(FLASH->CRCCR, (FLASH_CRCCR_CLEAN_CRC | FLASH_CRCCR_CRC_BURST), + (FLASH_CRCCR_CLEAN_CRC | pCRCInit->BurstSize)); + + if (pCRCInit->TypeCRC == FLASH_CRC_SECTORS) + { + /* Select CRC by sector and clear sectors list */ + SET_BIT(FLASH->CRCCR, (FLASH_CRCCR_CRC_BY_SECT | FLASH_CRCCR_CLEAN_SECT)); + + /* Select CRC sectors */ + for (sector_index = pCRCInit->Sector; sector_index < (pCRCInit->NbSectors + pCRCInit->Sector); sector_index++) + { + FLASH_CRC_AddSector(sector_index); + } + } + else if (pCRCInit->TypeCRC == FLASH_CRC_BANK) + { + /* Select CRC by sector and all sectors */ + SET_BIT(FLASH->CRCCR, (FLASH_CRCCR_CRC_BY_SECT | FLASH_CRCCR_ALL_SECT)); + } + else + { + /* Select CRC by address */ + CLEAR_BIT(FLASH->CRCCR, FLASH_CRCCR_CRC_BY_SECT); + + /* Select CRC start and end addresses */ + FLASH_CRC_SelectAddress(pCRCInit->CRCStartAddr, pCRCInit->CRCEndAddr); + } + + /* Start the CRC calculation */ + SET_BIT(FLASH->CRCCR, FLASH_CRCCR_START_CRC); + + /* Wait on CRC busy flag */ + status = FLASH_CRC_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); + + /* Return CRC result */ + (*CRC_Result) = FLASH->CRCDATAR; + + /* Disable CRC feature */ + CLEAR_BIT(FLASH->CR, FLASH_CR_CRC_EN); + + /* Clear CRC flags */ + FLASH->ICR = (FLASH_ICR_CRCRDERRF | FLASH_ICR_CRCENDF); + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + } + + return status; +} + +/** + * @} + */ + +/** @defgroup FLASHEx_Exported_Functions_Group3 Extended ECC operation functions + * @brief Extended ECC operation functions + * +@verbatim + =============================================================================== + ##### Extended ECC operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the Extended FLASH + ECC Operations. + +@endverbatim + * @{ + */ +/** + * @brief Enable ECC correction interrupt + * @retval None + */ +void HAL_FLASHEx_EnableEccCorrectionInterrupt(void) +{ + __HAL_FLASH_ENABLE_IT(FLASH_IT_SNECCERR); +} + +/** + * @brief Disable ECC correction interrupt + * @retval None + */ +void HAL_FLASHEx_DisableEccCorrectionInterrupt(void) +{ + __HAL_FLASH_DISABLE_IT(FLASH_IT_SNECCERR); +} + +/** + * @brief Enable ECC detection interrupt + * @retval None + */ +void HAL_FLASHEx_EnableEccDetectionInterrupt(void) +{ + __HAL_FLASH_ENABLE_IT(FLASH_IT_DBECCERR); +} + +/** + * @brief Disable ECC detection interrupt + * @retval None + */ +void HAL_FLASHEx_DisableEccDetectionInterrupt(void) +{ + __HAL_FLASH_DISABLE_IT(FLASH_IT_DBECCERR); +} + +/** + * @brief Get the ECC error information. + * @param pData Pointer to an FLASH_EccInfoTypeDef structure that contains the + * ECC error information. + * @note This function should be called before ECC bit is cleared + * (in callback function) + * @retval None + */ +void HAL_FLASHEx_GetEccInfo(FLASH_EccInfoTypeDef *pData) +{ + /* Check Null pointer */ + assert_param(pData != NULL); + + /* Set address which generate ECC error */ + if ((FLASH->ISR & FLASH_FLAG_SNECCERR) != 0U) + { + pData->Address = FLASH->ECCSFADDR; + } + else + { + pData->Address = FLASH->ECCDFADDR; + } + + /* Set area according address */ + if (IS_FLASH_MAIN_MEM_ADDRESS(pData->Address)) + { + pData->Area = FLASH_ECC_AREA_USER_BANK1; + } + else if (IS_FLASH_OTP_ADDRESS(pData->Address)) + { + pData->Area = FLASH_ECC_AREA_OTP; + } + else if ((pData->Address >= SYSTEM_FLASH_BASE) && + (pData->Address < (SYSTEM_FLASH_BASE + SYSTEM_FLASH_SIZE))) + { + pData->Area = FLASH_ECC_AREA_SYSTEM; + } + else + { + pData->Area = FLASH_ECC_AREA_READ_ONLY; + } + + /* Set Master which initiates transaction. On H7RS, it's necessary CPU1 */ + pData->MasterID = FLASH_ECC_MASTER_CPU1; +} + +/** + * @brief Handle Flash ECC Detection interrupt request. + * @note On STM32H7RS, this Irq Handler should be called in Bus Fault + * interrupt subroutine. + * @retval None + */ +void HAL_FLASHEx_ECCD_IRQHandler(void) +{ + /* Check ECC Detection Error */ + if ((FLASH->ISR & FLASH_FLAG_DBECCERR) != 0U) + { + /* Call User callback */ + HAL_FLASHEx_EccDetectionCallback(); + + /* Clear ECC detection flag in order to allow new ECC error record */ + FLASH->ICR = FLASH_FLAG_DBECCERR; + } +} + +/** + * @brief FLASH ECC Correction interrupt callback. + * @retval None + */ +__weak void HAL_FLASHEx_EccCorrectionCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_FLASHEx_EccCorrectionCallback could be implemented in the user file + */ +} + +/** + * @brief FLASH ECC Detection interrupt callback. + * @retval None + */ +__weak void HAL_FLASHEx_EccDetectionCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_FLASHEx_EccDetectionCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +/** @addtogroup FLASHEx_Private_Functions + * @{ + */ +/** + * @brief Mass erase of FLASH memory. + * @retval None + */ +static void FLASH_MassErase(void) +{ + /* Set the Mass Erase Bit and proceed to erase */ + SET_BIT(FLASH->CR, (FLASH_CR_BER | FLASH_CR_START)); +} + +/** + * @brief Erase the specified FLASH memory sector. + * @param Sector FLASH sector to erase + * This parameter must be a value between 0 and (max number of sectors in the bank - 1) + * @retval None + */ +void FLASH_SectorErase(uint32_t Sector) +{ + /* Check the parameters */ + assert_param(IS_FLASH_SECTOR(Sector)); + + /* Proceed to erase the page */ + MODIFY_REG(FLASH->CR, (FLASH_CR_SSN | FLASH_CR_SER | FLASH_CR_START), \ + ((Sector << FLASH_CR_SSN_Pos) | FLASH_CR_SER | FLASH_CR_START)); +} + +/** + * @brief Configure the write protection of the desired sectors. + * + * @note To configure the WRP options, the option lock bit OPTLOCK must be + * cleared with the call of the HAL_FLASH_OB_Unlock() function. + * + * @param WRPState + * + * @param WRPSector + * + * @retval None + */ +static void FLASH_OB_WRPConfig(uint32_t WRPState, uint32_t WRPSector) +{ + /* Check the parameters */ + assert_param(IS_OB_WRPSTATE(WRPState)); + + /* Configure the write protected area */ + if (WRPState == OB_WRPSTATE_DISABLE) + { + FLASH->WRPSRP |= (WRPSector & FLASH_WRPSRP_WRPS); + } + else if (WRPState == OB_WRPSTATE_ENABLE) + { + FLASH->WRPSRP &= (~(WRPSector & FLASH_WRPSRP_WRPS)); + } + else + { + /* Empty statement (to be compliant MISRA 15.7) */ + } +} + +/** + * @brief Program the FLASH User Option Byte. + * + * @note To configure the user option bytes, the option lock bit OPTLOCK must + * be cleared with the call of the HAL_FLASH_OB_Unlock() function. + * @param UserType: The FLASH User Option Bytes to be modified. + * This parameter can be a combination of @ref FLASH_OB_USER_TYPE + * @param UserConfig1 The selected User Option Bytes values + * @param UserConfig2 The selected User Option Bytes values + * @retval None + */ +static void FLASH_OB_UserConfig(uint32_t UserType, uint32_t UserConfig1, uint32_t UserConfig2) +{ + uint32_t optr_reg_val = 0; + uint32_t optr_reg_mask = 0; + + /* Check the parameters */ + assert_param(IS_OB_USER_TYPE(UserType)); + + if ((UserType & OB_USER_BOR_LEV) != 0U) + { + /* BOR level option byte should be modified */ + assert_param(IS_OB_USER_BOR_LEVEL(UserConfig1 & FLASH_OBW1SR_BOR_LEVEL)); + + /* Set value and mask for BOR level option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_BOR_LEVEL); + optr_reg_mask |= FLASH_OBW1SR_BOR_LEVEL; + } + + if ((UserType & OB_USER_IWDG_SW) != 0U) + { + /* IWDG1_HW option byte should be modified */ + assert_param(IS_OB_USER_IWDG(UserConfig1 & FLASH_OBW1SR_IWDG_HW)); + + /* Set value and mask for IWDG1_HW option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_IWDG_HW); + optr_reg_mask |= FLASH_OBW1SR_IWDG_HW; + } + + if ((UserType & OB_USER_NRST_STOP) != 0U) + { + /* NRST_STOP_D1 option byte should be modified */ + assert_param(IS_OB_USER_STOP(UserConfig1 & FLASH_OBW1SR_NRST_STOP)); + + /* Set value and mask for NRST_STOP_D1 option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_NRST_STOP); + optr_reg_mask |= FLASH_OBW1SR_NRST_STOP; + } + + if ((UserType & OB_USER_NRST_STDBY) != 0U) + { + /* NRST_STBY_D1 option byte should be modified */ + assert_param(IS_OB_USER_STANDBY(UserConfig1 & FLASH_OBW1SR_NRST_STBY)); + + /* Set value and mask for NRST_STBY_D1 option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_NRST_STBY); + optr_reg_mask |= FLASH_OBW1SR_NRST_STBY; + } + + if ((UserType & OB_USER_XSPI1_HSLV) != 0U) + { + /* XSPI1_HSLV option byte should be modified */ + assert_param(IS_OB_USER_XSPI1_HSLV(UserConfig1 & FLASH_OBW1SR_XSPI1_HSLV)); + + /* Set value and mask for XSPI1_HSLV option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_XSPI1_HSLV); + optr_reg_mask |= FLASH_OBW1SR_XSPI1_HSLV; + } + + if ((UserType & OB_USER_XSPI2_HSLV) != 0U) + { + /* XSPI2_HSLV option byte should be modified */ + assert_param(IS_OB_USER_XSPI2_HSLV(UserConfig1 & FLASH_OBW1SR_XSPI2_HSLV)); + + /* Set value and mask for XSPI2_HSLV option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_XSPI2_HSLV); + optr_reg_mask |= FLASH_OBW1SR_XSPI2_HSLV; + } + + if ((UserType & OB_USER_IWDG_STOP) != 0U) + { + /* IWDG_FZ_STOP option byte should be modified */ + assert_param(IS_OB_USER_IWDG_STOP(UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STOP)); + + /* Set value and mask for IWDG_FZ_STOP option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STOP); + optr_reg_mask |= FLASH_OBW1SR_IWDG_FZ_STOP; + } + + if ((UserType & OB_USER_IWDG_STDBY) != 0U) + { + /* IWDG_FZ_SDBY option byte should be modified */ + assert_param(IS_OB_USER_IWDG_STDBY(UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STBY)); + + /* Set value and mask for IWDG_FZ_SDBY option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_IWDG_FZ_STBY); + optr_reg_mask |= FLASH_OBW1SR_IWDG_FZ_STBY; + } + + if ((UserType & OB_USER_VDDIO_HSLV) != 0U) + { + /* VDDIO_HSLV option byte should be modified */ + assert_param(IS_OB_USER_VDDIO_HSLV(UserConfig1 & FLASH_OBW1SR_VDDIO_HSLV)); + + /* Set value and mask for VDDIO_HSLV option byte */ + optr_reg_val |= (UserConfig1 & FLASH_OBW1SR_VDDIO_HSLV); + optr_reg_mask |= FLASH_OBW1SR_VDDIO_HSLV; + } + + /* Configure the option bytes register 1 if necessary */ + if (optr_reg_mask != 0U) + { + MODIFY_REG(FLASH->OBW1SRP, optr_reg_mask, optr_reg_val); + } + + optr_reg_val = 0; + optr_reg_mask = 0; + + if ((UserType & OB_USER_ITCM_AXI_SHARE) != 0U) + { + /* ITCM_AXI_SHARE option byte should be modified */ + assert_param(IS_OB_USER_ITCM_AXI_SHARE(UserConfig2 & FLASH_OBW2SR_ITCM_AXI_SHARE)); + + /* Set value and mask for ITCM_AXI_SHARE option byte */ + optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_ITCM_AXI_SHARE); + optr_reg_mask |= FLASH_OBW2SR_ITCM_AXI_SHARE; + } + + if ((UserType & OB_USER_DTCM_AXI_SHARE) != 0U) + { + /* DTCM_AXI_SHARE option byte should be modified */ + assert_param(IS_OB_USER_DTCM_AXI_SHARE(UserConfig2 & FLASH_OBW2SR_DTCM_AXI_SHARE)); + + /* Set value and mask for DTCM_AXI_SHARE option byte */ + optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_DTCM_AXI_SHARE); + optr_reg_mask |= FLASH_OBW2SR_DTCM_AXI_SHARE; + } + + if ((UserType & OB_USER_SRAM_ECC) != 0U) + { + /* SRAM_ECC option byte should be modified */ + assert_param(IS_OB_USER_AXISRAM_ECC(UserConfig2 & FLASH_OBW2SR_ECC_ON_SRAM)); + + /* Set value and mask for SRAM_ECC option byte */ + optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_ECC_ON_SRAM); + optr_reg_mask |= FLASH_OBW2SR_ECC_ON_SRAM; + } + + if ((UserType & OB_USER_I2C_NI3C) != 0U) + { + /* I2C_NI3C option byte should be modified */ + assert_param(IS_OB_USER_I2C_NI3C(UserConfig2 & FLASH_OBW2SR_I2C_NI3C)); + + /* Set value and mask for I2C_NI3C option byte */ + optr_reg_val |= (UserConfig2 & FLASH_OBW2SR_I2C_NI3C); + optr_reg_mask |= FLASH_OBW2SR_I2C_NI3C; + } + + /* Configure the option bytes register 2 if necessary */ + if (optr_reg_mask != 0U) + { + MODIFY_REG(FLASH->OBW2SRP, optr_reg_mask, optr_reg_val); + } +} + +/** + * @brief Configure the Hide Protection. + * + * @note To configure the HDP options, the option lock bit OPTLOCK must be + * cleared with the call of the HAL_FLASH_OB_Unlock() function. + * + * @param HDPStartPage + * + * @param HDPEndPage + * + * @retval None + */ +static void FLASH_OB_HDPConfig(uint32_t HDPStartPage, uint32_t HDPEndPage) +{ + /* Check the parameters */ + assert_param(IS_OB_HDP_PAGE(HDPStartPage)); + assert_param(IS_OB_HDP_PAGE(HDPEndPage)); + + MODIFY_REG(FLASH->HDPSRP, (FLASH_HDPSRP_HDP_AREA_START | FLASH_HDPSRP_HDP_AREA_END), \ + (HDPStartPage | (HDPEndPage << FLASH_HDPSRP_HDP_AREA_END_Pos))); +} + +/** + * @brief Configure the Non-Volatile state. + * + * @note To configure the Non-volatile options, the option lock bit OPTLOCK must be + * cleared with the call of the HAL_FLASH_OB_Unlock() function. + * + * @param NVState + * + * @retval None + */ +static void FLASH_OB_NVConfig(uint32_t NVState) +{ + /* Check the parameter */ + assert_param(IS_OB_NVSTATE(NVState)); + + MODIFY_REG(FLASH->NVSRP, FLASH_NVSRP_NVSTATE, NVState); +} + +/** + * @brief Return the FLASH Write Protection Option Bytes value. + * + * @param WRPState + * + * @param WRPSector + * + * @retval None + */ +static void FLASH_OB_GetWRP(uint32_t *WRPState, uint32_t *WRPSector) +{ + if ((FLASH->WRPSR & FLASH_WRPSR_WRPS) == FLASH_WRPSR_WRPS) + { + /* All sectors aren't write protected */ + *WRPState = OB_WRPSTATE_DISABLE; + } + else + { + /* Some sectors are write protected */ + *WRPState = OB_WRPSTATE_ENABLE; + *WRPSector = ((~(FLASH->WRPSR)) & FLASH_WRPSR_WRPS); + } +} + +/** + * @brief Return the FLASH User Option Byte value. + * + * @param UserConfig1 Address to return the FLASH User Option Bytes values configuration 1. + * The return value can be a combination of + * @param UserConfig2 Address to return the FLASH User Option Bytes values configuration 2. + * The return value can be a combination of + * + * @retval None + */ +static void FLASH_OB_GetUser(uint32_t *UserConfig1, uint32_t *UserConfig2) +{ + *UserConfig1 = FLASH->OBW1SR; + *UserConfig2 = FLASH->OBW2SR; +} + +/** + * @brief Return the FLASH Hide Protection Option Bytes value. + * + * @param HDPStartPage Address to return the FLASH HDP Option Bytes Start Sector. + * The return value can be a combination of + * @param HDPEndPage Address to return the FLASH HDP Option Bytes End Sector. + * The return value can be a combination of + * + * @retval None + */ +static void FLASH_OB_GetHDP(uint32_t *HDPStartPage, uint32_t *HDPEndPage) +{ + *HDPStartPage = (FLASH->HDPSR & FLASH_HDPSR_HDP_AREA_START); + *HDPEndPage = ((FLASH->HDPSR & FLASH_HDPSR_HDP_AREA_END) >> FLASH_HDPSR_HDP_AREA_END_Pos); +} + +/** + * @brief Return the FLASH Non-volatile state Option Bytes value. + * + * @retval Value of Non-volatile state + */ +static uint32_t FLASH_OB_GetNV(void) +{ + return (FLASH->NVSR & FLASH_NVSR_NVSTATE); +} + +/** + * @brief Return the FLASH RoT Option Bytes value. + * + * @retval Value of the RoT + */ +static uint32_t FLASH_OB_GetRoT(void) +{ + return (FLASH->ROTSR & (FLASH_ROTSR_OEM_PROVD | FLASH_ROTSR_DBG_AUTH | FLASH_ROTSR_IROT_SELECT)); +} + +/** + * @brief Return the FLASH Epoch Option Bytes value. + * + * @retval Value of the Epoch + */ +static uint32_t FLASH_OB_GetEpoch(void) +{ + return (FLASH->EPOCHSR & FLASH_EPOCHSR_EPOCH); +} + +/** + * @brief Add a CRC sector to the list of sectors on which the CRC will be calculated + * @param Sector Specifies the CRC sector number + * @retval None + */ +static void FLASH_CRC_AddSector(uint32_t Sector) +{ + /* Check the parameters */ + assert_param(IS_FLASH_SECTOR(Sector)); + + /* Clear CRC sector */ + MODIFY_REG(FLASH->CRCCR, FLASH_CRCCR_CRC_SECT, Sector); + + /* Activate ADD_SECT bit */ + SET_BIT(FLASH->CRCCR, FLASH_CRCCR_ADD_SECT); +} + +/** + * @brief Select CRC start and end memory addresses on which the CRC will be calculated + * @param CRCStartAddr Specifies the CRC start address + * @param CRCEndAddr Specifies the CRC end address + * @retval None + */ +static void FLASH_CRC_SelectAddress(uint32_t CRCStartAddr, uint32_t CRCEndAddr) +{ + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(CRCStartAddr)); + assert_param(IS_FLASH_MAIN_MEM_ADDRESS(CRCEndAddr)); + + /* Write CRC Start and End addresses */ + FLASH->CRCSADDR = (CRCStartAddr - FLASH_BASE); + FLASH->CRCEADDR = (CRCEndAddr - FLASH_BASE); +} + +/** + * @brief Wait for a FLASH CRC computation to complete. + * @param Timeout maximum flash operation timeout + * @retval HAL_StatusTypeDef HAL Status + */ +static HAL_StatusTypeDef FLASH_CRC_WaitForLastOperation(uint32_t Timeout) +{ + uint32_t timeout = HAL_GetTick() + Timeout; + + /* Wait for the FLASH CRC computation to complete by polling on CRC_BUSY flag to be reset */ + while ((FLASH->SR & FLASH_SR_CRC_BUSY) != 0U) + { + if (HAL_GetTick() >= timeout) + { + return HAL_TIMEOUT; + } + } + + /* Check FLASH CRC calculation error flag */ + if ((FLASH->ISR & FLASH_FLAG_CRCERR) != 0U) + { + /*Save the error code*/ + pFlash.ErrorCode |= HAL_FLASH_ERROR_CRC; + + /* Clear CRC error flag */ + FLASH->ICR = FLASH_FLAG_CRCERR; + + return HAL_ERROR; + } + + /* Check FLASH CRC End of Calculation flag */ + if ((FLASH->ISR & FLASH_FLAG_CRCEND) != 0U) + { + /* Clear FLASH End of Calculation pending bit */ + FLASH->ICR = FLASH_FLAG_CRCEND; + } + + /* If there is no error flag set */ + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_FLASH_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxmmu.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxmmu.c index 2b38a2b88..5ab6ac7b7 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxmmu.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxmmu.c @@ -1,872 +1,872 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_gfxmmu.c - * @author MCD Application Team - * @brief This file provides firmware functions to manage the following - * functionalities of the Graphic MMU (GFXMMU) peripheral: - * + Initialization and De-initialization. - * + LUT configuration. - * + Modify physical buffer addresses. - * + Packing configuration. - * + Error management. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - *** Initialization *** - ====================== - [..] - (#) As prerequisite, fill in the HAL_GFXMMU_MspInit() : - (++) Enable GFXMMU clock interface with __HAL_RCC_GFXMMU_CLK_ENABLE(). - (++) If interrupts are used, enable and configure GFXMMU global - interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). - (#) Configure the number of blocks per line, default value, physical - buffer addresses and interrupts using the HAL_GFXMMU_Init() function. - - *** LUT configuration *** - ========================= - [..] - (#) Use HAL_GFXMMU_DisableLutLines() to deactivate all LUT lines (or a - range of lines). - (#) Use HAL_GFXMMU_ConfigLut() to copy LUT from flash to look up RAM. - (#) Use HAL_GFXMMU_ConfigLutLine() to configure one line of LUT. - - *** Modify physical buffer addresses *** - ======================================== - [..] - (#) Use HAL_GFXMMU_ModifyBuffers() to modify physical buffer addresses. - - *** Packing configuration *** - ============================= - [..] - (#) Use HAL_GFXMMU_ConfigPacking() to configure packing. - - *** Error management *** - ======================== - [..] - (#) If interrupts are used, HAL_GFXMMU_IRQHandler() will be called when - an error occurs. This function will call HAL_GFXMMU_ErrorCallback(). - Use HAL_GFXMMU_GetError() to get the error code. - - *** De-initialization *** - ========================= - [..] - (#) As prerequisite, fill in the HAL_GFXMMU_MspDeInit() : - (++) Disable GFXMMU clock interface with __HAL_RCC_GFXMMU_CLK_ENABLE(). - (++) If interrupts has been used, disable GFXMMU global interrupt with - HAL_NVIC_DisableIRQ(). - (#) De-initialize GFXMMU using the HAL_GFXMMU_DeInit() function. - - *** Callback registration *** - ============================= - [..] - The compilation define USE_HAL_GFXMMU_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use functions HAL_GFXMMU_RegisterCallback() to register a user callback. - - [..] - Function HAL_GFXMMU_RegisterCallback() allows to register following callbacks: - (+) ErrorCallback : GFXMMU error. - (+) MspInitCallback : GFXMMU MspInit. - (+) MspDeInitCallback : GFXMMU MspDeInit. - [..] - This function takes as parameters the HAL peripheral handle, the callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_GFXMMU_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. - HAL_GFXMMU_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the callback ID. - [..] - This function allows to reset following callbacks: - (+) ErrorCallback : GFXMMU error. - (+) MspInitCallback : GFXMMU MspInit. - (+) MspDeInitCallback : GFXMMU MspDeInit. - - [..] - By default, after the HAL_GFXMMU_Init and if the state is HAL_GFXMMU_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions: - examples HAL_GFXMMU_ErrorCallback(). - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_GFXMMU_Init - and HAL_GFXMMU_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_GFXMMU_Init and HAL_GFXMMU_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_GFXMMU_RegisterCallback before calling HAL_GFXMMU_DeInit - or HAL_GFXMMU_Init function. - - [..] - When the compilation define USE_HAL_GFXMMU_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ -#ifdef HAL_GFXMMU_MODULE_ENABLED -#if defined(GFXMMU) -/** @defgroup GFXMMU GFXMMU - * @brief GFXMMU HAL driver module - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup GFXMMU_Private_Constants GFXMMU Private Constants - * @{ - */ -#define GFXMMU_LUTXL_FVB_OFFSET 8U -#define GFXMMU_LUTXL_LVB_OFFSET 16U -#define GFXMMU_CR_ITS_MASK 0x1FU -/** - * @} - */ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @defgroup GFXMMU_Exported_Functions GFXMMU Exported Functions - * @{ - */ - -/** @defgroup GFXMMU_Exported_Functions_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 GFXMMU. - (+) De-initialize the GFXMMU. -@endverbatim - * @{ - */ - -/** - * @brief Initialize the GFXMMU according to the specified parameters in the - * GFXMMU_InitTypeDef structure and initialize the associated handle. - * @param hgfxmmu GFXMMU handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_Init(GFXMMU_HandleTypeDef *hgfxmmu) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check GFXMMU handle */ - if (hgfxmmu == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - assert_param(IS_GFXMMU_BLOCK_SIZE(hgfxmmu->Init.BlockSize)); - assert_param(IS_FUNCTIONAL_STATE(hgfxmmu->Init.AddressTranslation)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf0Address)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf1Address)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf2Address)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf3Address)); - assert_param(IS_FUNCTIONAL_STATE(hgfxmmu->Init.Interrupts.Activation)); - -#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) - /* Reset callback pointers to the weak predefined callbacks */ - hgfxmmu->ErrorCallback = HAL_GFXMMU_ErrorCallback; - - /* Call GFXMMU MSP init function */ - if (hgfxmmu->MspInitCallback == NULL) - { - hgfxmmu->MspInitCallback = HAL_GFXMMU_MspInit; - } - hgfxmmu->MspInitCallback(hgfxmmu); -#else - /* Call GFXMMU MSP init function */ - HAL_GFXMMU_MspInit(hgfxmmu); -#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1 */ - - /* Configure GFXMMU_CR register */ - hgfxmmu->Instance->CR = 0U; - hgfxmmu->Instance->CR |= (hgfxmmu->Init.BlockSize); - if (hgfxmmu->Init.AddressTranslation == ENABLE) - { - hgfxmmu->Instance->CR |= GFXMMU_CR_ATE; - } - if (hgfxmmu->Init.Interrupts.Activation == ENABLE) - { - assert_param(IS_GFXMMU_INTERRUPTS(hgfxmmu->Init.Interrupts.UsedInterrupts)); - hgfxmmu->Instance->CR |= hgfxmmu->Init.Interrupts.UsedInterrupts; - } - - /* Configure default value on GFXMMU_DVR register */ - hgfxmmu->Instance->DVR = hgfxmmu->Init.DefaultValue; - - /* Configure physical buffer addresses on GFXMMU_BxCR registers */ - hgfxmmu->Instance->B0CR = hgfxmmu->Init.Buffers.Buf0Address; - hgfxmmu->Instance->B1CR = hgfxmmu->Init.Buffers.Buf1Address; - hgfxmmu->Instance->B2CR = hgfxmmu->Init.Buffers.Buf2Address; - hgfxmmu->Instance->B3CR = hgfxmmu->Init.Buffers.Buf3Address; - - /* Reset GFXMMU error code */ - hgfxmmu->ErrorCode = GFXMMU_ERROR_NONE; - - /* Set GFXMMU to ready state */ - hgfxmmu->State = HAL_GFXMMU_STATE_READY; - } - /* Return function status */ - return status; -} - -/** - * @brief De-initialize the GFXMMU. - * @param hgfxmmu GFXMMU handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_DeInit(GFXMMU_HandleTypeDef *hgfxmmu) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check GFXMMU handle */ - if (hgfxmmu == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - - /* Disable all interrupts on GFXMMU_CR register */ - hgfxmmu->Instance->CR &= ~(GFXMMU_CR_B0OIE | GFXMMU_CR_B1OIE | GFXMMU_CR_B2OIE | GFXMMU_CR_B3OIE | - GFXMMU_CR_AMEIE); - - /* Call GFXMMU MSP de-init function */ -#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) - if (hgfxmmu->MspDeInitCallback == NULL) - { - hgfxmmu->MspDeInitCallback = HAL_GFXMMU_MspDeInit; - } - hgfxmmu->MspDeInitCallback(hgfxmmu); -#else - HAL_GFXMMU_MspDeInit(hgfxmmu); -#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1 */ - - /* Set GFXMMU to reset state */ - hgfxmmu->State = HAL_GFXMMU_STATE_RESET; - } - /* Return function status */ - return status; -} - -/** - * @brief Initialize the GFXMMU MSP. - * @param hgfxmmu GFXMMU handle. - * @retval None. - */ -__weak void HAL_GFXMMU_MspInit(GFXMMU_HandleTypeDef *hgfxmmu) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxmmu); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXMMU_MspInit could be implemented in the user file. - */ -} - -/** - * @brief De-initialize the GFXMMU MSP. - * @param hgfxmmu GFXMMU handle. - * @retval None. - */ -__weak void HAL_GFXMMU_MspDeInit(GFXMMU_HandleTypeDef *hgfxmmu) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxmmu); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXMMU_MspDeInit could be implemented in the user file. - */ -} - -#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) -/** - * @brief Register a user GFXMMU callback - * to be used instead of the weak predefined callback. - * @param hgfxmmu GFXMMU handle. - * @param CallbackID ID of the callback to be registered. - * This parameter can be one of the following values: - * @arg @ref HAL_GFXMMU_ERROR_CB_ID error callback ID. - * @arg @ref HAL_GFXMMU_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_GFXMMU_MSPDEINIT_CB_ID MSP de-init callback ID. - * @param pCallback pointer to the callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_RegisterCallback(GFXMMU_HandleTypeDef *hgfxmmu, - HAL_GFXMMU_CallbackIDTypeDef CallbackID, - pGFXMMU_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - else - { - if (HAL_GFXMMU_STATE_READY == hgfxmmu->State) - { - switch (CallbackID) - { - case HAL_GFXMMU_ERROR_CB_ID : - hgfxmmu->ErrorCallback = pCallback; - break; - case HAL_GFXMMU_MSPINIT_CB_ID : - hgfxmmu->MspInitCallback = pCallback; - break; - case HAL_GFXMMU_MSPDEINIT_CB_ID : - hgfxmmu->MspDeInitCallback = pCallback; - break; - default : - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_GFXMMU_STATE_RESET == hgfxmmu->State) - { - switch (CallbackID) - { - case HAL_GFXMMU_MSPINIT_CB_ID : - hgfxmmu->MspInitCallback = pCallback; - break; - case HAL_GFXMMU_MSPDEINIT_CB_ID : - hgfxmmu->MspDeInitCallback = pCallback; - break; - default : - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - } - return status; -} - -/** - * @brief Unregister a user GFXMMU callback. - * GFXMMU callback is redirected to the weak predefined callback. - * @param hgfxmmu GFXMMU handle. - * @param CallbackID ID of the callback to be unregistered. - * This parameter can be one of the following values: - * @arg @ref HAL_GFXMMU_ERROR_CB_ID error callback ID. - * @arg @ref HAL_GFXMMU_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_GFXMMU_MSPDEINIT_CB_ID MSP de-init callback ID. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_UnRegisterCallback(GFXMMU_HandleTypeDef *hgfxmmu, - HAL_GFXMMU_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_GFXMMU_STATE_READY == hgfxmmu->State) - { - switch (CallbackID) - { - case HAL_GFXMMU_ERROR_CB_ID : - hgfxmmu->ErrorCallback = HAL_GFXMMU_ErrorCallback; - break; - case HAL_GFXMMU_MSPINIT_CB_ID : - hgfxmmu->MspInitCallback = HAL_GFXMMU_MspInit; - break; - case HAL_GFXMMU_MSPDEINIT_CB_ID : - hgfxmmu->MspDeInitCallback = HAL_GFXMMU_MspDeInit; - break; - default : - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_GFXMMU_STATE_RESET == hgfxmmu->State) - { - switch (CallbackID) - { - case HAL_GFXMMU_MSPINIT_CB_ID : - hgfxmmu->MspInitCallback = HAL_GFXMMU_MspInit; - break; - case HAL_GFXMMU_MSPDEINIT_CB_ID : - hgfxmmu->MspDeInitCallback = HAL_GFXMMU_MspDeInit; - break; - default : - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update the error code */ - hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - return status; -} -#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup GFXMMU_Exported_Functions_Group2 Operations functions - * @brief GFXMMU operation functions - * -@verbatim - ============================================================================== - ##### Operation functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) Configure LUT. - (+) Modify physical buffer addresses. - (+) Configure packing. - (+) Manage error. -@endverbatim - * @{ - */ - -/** - * @brief This function allows to copy LUT from flash to look up RAM. - * @param hgfxmmu GFXMMU handle. - * @param FirstLine First line enabled on LUT. - * This parameter must be a number between Min_Data = 0 and Max_Data = 1023. - * @param LinesNumber Number of lines enabled on LUT. - * This parameter must be a number between Min_Data = 1 and Max_Data = 1024. - * @param Address Start address of LUT in flash. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_ConfigLut(const GFXMMU_HandleTypeDef *hgfxmmu, - uint32_t FirstLine, - uint32_t LinesNumber, - uint32_t Address) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - assert_param(IS_GFXMMU_LUT_LINE(FirstLine)); - assert_param(IS_GFXMMU_LUT_LINES_NUMBER(LinesNumber)); - - /* Check GFXMMU state and coherent parameters */ - if ((hgfxmmu->State != HAL_GFXMMU_STATE_READY) || ((FirstLine + LinesNumber) > 1024U)) - { - status = HAL_ERROR; - } - /* Check address translation status */ - else if ((hgfxmmu->Instance->CR & GFXMMU_CR_ATE) == 0U) - { - status = HAL_ERROR; - } - else - { - uint32_t current_address; - uint32_t current_line; - uint32_t lutxl_address; - uint32_t lutxh_address; - - /* Initialize local variables */ - current_address = Address; - current_line = 0U; - lutxl_address = (uint32_t) &(hgfxmmu->Instance->LUT[2U * FirstLine]); - lutxh_address = (uint32_t) &(hgfxmmu->Instance->LUT[(2U * FirstLine) + 1U]); - - /* Copy LUT from flash to look up RAM */ - while (current_line < LinesNumber) - { - *((uint32_t *)lutxl_address) = *((uint32_t *)current_address); - current_address += 4U; - *((uint32_t *)lutxh_address) = *((uint32_t *)current_address); - current_address += 4U; - lutxl_address += 8U; - lutxh_address += 8U; - current_line++; - } - } - /* Return function status */ - return status; -} - -/** - * @brief This function allows to disable a range of LUT lines. - * @param hgfxmmu GFXMMU handle. - * @param FirstLine First line to disable on LUT. - * This parameter must be a number between Min_Data = 0 and Max_Data = 1023. - * @param LinesNumber Number of lines to disable on LUT. - * This parameter must be a number between Min_Data = 1 and Max_Data = 1024. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_DisableLutLines(const GFXMMU_HandleTypeDef *hgfxmmu, - uint32_t FirstLine, - uint32_t LinesNumber) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - assert_param(IS_GFXMMU_LUT_LINE(FirstLine)); - assert_param(IS_GFXMMU_LUT_LINES_NUMBER(LinesNumber)); - - /* Check GFXMMU state and coherent parameters */ - if ((hgfxmmu->State != HAL_GFXMMU_STATE_READY) || ((FirstLine + LinesNumber) > 1024U)) - { - status = HAL_ERROR; - } - /* Check address translation status */ - else if ((hgfxmmu->Instance->CR & GFXMMU_CR_ATE) == 0U) - { - status = HAL_ERROR; - } - else - { - uint32_t current_line; - uint32_t lutxl_address; - uint32_t lutxh_address; - - /* Initialize local variables */ - current_line = 0U; - lutxl_address = (uint32_t) &(hgfxmmu->Instance->LUT[2U * FirstLine]); - lutxh_address = (uint32_t) &(hgfxmmu->Instance->LUT[(2U * FirstLine) + 1U]); - - /* Disable LUT lines */ - while (current_line < LinesNumber) - { - *((uint32_t *)lutxl_address) = 0U; - *((uint32_t *)lutxh_address) = 0U; - lutxl_address += 8U; - lutxh_address += 8U; - current_line++; - } - } - /* Return function status */ - return status; -} - -/** - * @brief This function allows to configure one line of LUT. - * @param hgfxmmu GFXMMU handle. - * @param lutLine LUT line parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_ConfigLutLine(const GFXMMU_HandleTypeDef *hgfxmmu, const GFXMMU_LutLineTypeDef *lutLine) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - assert_param(IS_GFXMMU_LUT_LINE(lutLine->LineNumber)); - assert_param(IS_GFXMMU_LUT_LINE_STATUS(lutLine->LineStatus)); - assert_param(IS_GFXMMU_LUT_BLOCK(lutLine->FirstVisibleBlock)); - assert_param(IS_GFXMMU_LUT_BLOCK(lutLine->LastVisibleBlock)); - assert_param(IS_GFXMMU_LUT_LINE_OFFSET(lutLine->LineOffset)); - - /* Check GFXMMU state */ - if (hgfxmmu->State != HAL_GFXMMU_STATE_READY) - { - status = HAL_ERROR; - } - /* Check address translation status */ - else if ((hgfxmmu->Instance->CR & GFXMMU_CR_ATE) == 0U) - { - status = HAL_ERROR; - } - else - { - uint32_t lutxl_address; - uint32_t lutxh_address; - - /* Initialize local variables */ - lutxl_address = (uint32_t) &(hgfxmmu->Instance->LUT[2U * lutLine->LineNumber]); - lutxh_address = (uint32_t) &(hgfxmmu->Instance->LUT[(2U * lutLine->LineNumber) + 1U]); - - /* Configure LUT line */ - if (lutLine->LineStatus == GFXMMU_LUT_LINE_ENABLE) - { - /* Enable and configure LUT line */ - *((uint32_t *)lutxl_address) = (lutLine->LineStatus | - (lutLine->FirstVisibleBlock << GFXMMU_LUTXL_FVB_OFFSET) | - (lutLine->LastVisibleBlock << GFXMMU_LUTXL_LVB_OFFSET)); - *((uint32_t *)lutxh_address) = (uint32_t) lutLine->LineOffset; - } - else - { - /* Disable LUT line */ - *((uint32_t *)lutxl_address) = 0U; - *((uint32_t *)lutxh_address) = 0U; - } - } - /* Return function status */ - return status; -} - -/** - * @brief This function allows to modify physical buffer addresses. - * @param hgfxmmu GFXMMU handle. - * @param Buffers Buffers parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_ModifyBuffers(GFXMMU_HandleTypeDef *hgfxmmu, const GFXMMU_BuffersTypeDef *Buffers) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf0Address)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf1Address)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf2Address)); - assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf3Address)); - - /* Check GFXMMU state */ - if (hgfxmmu->State != HAL_GFXMMU_STATE_READY) - { - status = HAL_ERROR; - } - else - { - /* Modify physical buffer addresses on GFXMMU_BxCR registers */ - hgfxmmu->Instance->B0CR = Buffers->Buf0Address; - hgfxmmu->Instance->B1CR = Buffers->Buf1Address; - hgfxmmu->Instance->B2CR = Buffers->Buf2Address; - hgfxmmu->Instance->B3CR = Buffers->Buf3Address; - } - /* Return function status */ - return status; -} - -/** - * @brief This function allows to configure packing. - * @param hgfxmmu GFXMMU handle. - * @param pPacking Packing parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXMMU_ConfigPacking(GFXMMU_HandleTypeDef *hgfxmmu, const GFXMMU_PackingTypeDef *pPacking) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); - assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer0Activation)); - assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer1Activation)); - assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer2Activation)); - assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer3Activation)); - assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer0Mode)); - assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer1Mode)); - assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer2Mode)); - assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer3Mode)); - assert_param(IS_GFXMMU_DEFAULT_ALPHA_VALUE(pPacking->DefaultAlpha)); - - /* Check GFXMMU state */ - if (hgfxmmu->State != HAL_GFXMMU_STATE_READY) - { - status = HAL_ERROR; - } - /* Check block size is set to 12-byte*/ - else if ((hgfxmmu->Instance->CR & GFXMMU_CR_BS) == 0U) - { - status = HAL_ERROR; - } - else - { - uint32_t reg_value = 0U; - - /* Configure packing for all buffers on GFXMMU_CR register */ - if (pPacking->Buffer0Activation == ENABLE) - { - reg_value |= ((pPacking->Buffer0Mode << GFXMMU_CR_B0PM_Pos) | GFXMMU_CR_B0PE); - } - if (pPacking->Buffer1Activation == ENABLE) - { - reg_value |= ((pPacking->Buffer1Mode << GFXMMU_CR_B1PM_Pos) | GFXMMU_CR_B1PE); - } - if (pPacking->Buffer2Activation == ENABLE) - { - reg_value |= ((pPacking->Buffer2Mode << GFXMMU_CR_B2PM_Pos) | GFXMMU_CR_B2PE); - } - if (pPacking->Buffer3Activation == ENABLE) - { - reg_value |= ((pPacking->Buffer3Mode << GFXMMU_CR_B3PM_Pos) | GFXMMU_CR_B3PE); - } - hgfxmmu->Instance->CR &= ~(GFXMMU_CR_B0PE_Msk | GFXMMU_CR_B0PM_Msk | - GFXMMU_CR_B1PE_Msk | GFXMMU_CR_B1PM_Msk | - GFXMMU_CR_B2PE_Msk | GFXMMU_CR_B2PM_Msk | - GFXMMU_CR_B3PE_Msk | GFXMMU_CR_B3PM_Msk); - hgfxmmu->Instance->CR |= reg_value; - - /* Configure default alpha value on GFXMMU_DAR register */ - hgfxmmu->Instance->DAR = pPacking->DefaultAlpha; - } - /* Return function status */ - return status; -} - -/** - * @brief This function handles the GFXMMU interrupts. - * @param hgfxmmu GFXMMU handle. - * @retval None. - */ -void HAL_GFXMMU_IRQHandler(GFXMMU_HandleTypeDef *hgfxmmu) -{ - uint32_t flags, interrupts, error; - - /* Read current flags and interrupts and determine which error occurs */ - flags = hgfxmmu->Instance->SR; - interrupts = (hgfxmmu->Instance->CR & GFXMMU_CR_ITS_MASK); - error = (flags & interrupts); - - if (error != 0U) - { - /* Clear flags on GFXMMU_FCR register */ - hgfxmmu->Instance->FCR = error; - - /* Update GFXMMU error code */ - hgfxmmu->ErrorCode |= error; - - /* Call GFXMMU error callback */ -#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) - hgfxmmu->ErrorCallback(hgfxmmu); -#else - HAL_GFXMMU_ErrorCallback(hgfxmmu); -#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1 */ - } -} - -/** - * @brief Error callback. - * @param hgfxmmu GFXMMU handle. - * @retval None. - */ -__weak void HAL_GFXMMU_ErrorCallback(GFXMMU_HandleTypeDef *hgfxmmu) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxmmu); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_GFXMMU_ErrorCallback could be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup GFXMMU_Exported_Functions_Group3 State functions - * @brief GFXMMU state functions - * -@verbatim - ============================================================================== - ##### State functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) Get GFXMMU handle state. - (+) Get GFXMMU error code. -@endverbatim - * @{ - */ - -/** - * @brief This function allows to get the current GFXMMU handle state. - * @param hgfxmmu GFXMMU handle. - * @retval GFXMMU state. - */ -HAL_GFXMMU_StateTypeDef HAL_GFXMMU_GetState(const GFXMMU_HandleTypeDef *hgfxmmu) -{ - /* Return GFXMMU handle state */ - return hgfxmmu->State; -} - -/** - * @brief This function allows to get the current GFXMMU error code. - * @param hgfxmmu GFXMMU handle. - * @retval GFXMMU error code. - */ -uint32_t HAL_GFXMMU_GetError(GFXMMU_HandleTypeDef *hgfxmmu) -{ - uint32_t error_code; - - /* Enter in critical section */ - __disable_irq(); - - /* Store and reset GFXMMU error code */ - error_code = hgfxmmu->ErrorCode; - hgfxmmu->ErrorCode = GFXMMU_ERROR_NONE; - - /* Exit from critical section */ - __enable_irq(); - - /* Return GFXMMU error code */ - return error_code; -} - -/** - * @} - */ - -/** - * @} - */ -/* End of exported functions -------------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* End of private functions --------------------------------------------------*/ - -/** - * @} - */ -#endif /* GFXMMU */ -#endif /* HAL_GFXMMU_MODULE_ENABLED */ -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_gfxmmu.c + * @author MCD Application Team + * @brief This file provides firmware functions to manage the following + * functionalities of the Graphic MMU (GFXMMU) peripheral: + * + Initialization and De-initialization. + * + LUT configuration. + * + Modify physical buffer addresses. + * + Packing configuration. + * + Error management. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + *** Initialization *** + ====================== + [..] + (#) As prerequisite, fill in the HAL_GFXMMU_MspInit() : + (++) Enable GFXMMU clock interface with __HAL_RCC_GFXMMU_CLK_ENABLE(). + (++) If interrupts are used, enable and configure GFXMMU global + interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). + (#) Configure the number of blocks per line, default value, physical + buffer addresses and interrupts using the HAL_GFXMMU_Init() function. + + *** LUT configuration *** + ========================= + [..] + (#) Use HAL_GFXMMU_DisableLutLines() to deactivate all LUT lines (or a + range of lines). + (#) Use HAL_GFXMMU_ConfigLut() to copy LUT from flash to look up RAM. + (#) Use HAL_GFXMMU_ConfigLutLine() to configure one line of LUT. + + *** Modify physical buffer addresses *** + ======================================== + [..] + (#) Use HAL_GFXMMU_ModifyBuffers() to modify physical buffer addresses. + + *** Packing configuration *** + ============================= + [..] + (#) Use HAL_GFXMMU_ConfigPacking() to configure packing. + + *** Error management *** + ======================== + [..] + (#) If interrupts are used, HAL_GFXMMU_IRQHandler() will be called when + an error occurs. This function will call HAL_GFXMMU_ErrorCallback(). + Use HAL_GFXMMU_GetError() to get the error code. + + *** De-initialization *** + ========================= + [..] + (#) As prerequisite, fill in the HAL_GFXMMU_MspDeInit() : + (++) Disable GFXMMU clock interface with __HAL_RCC_GFXMMU_CLK_ENABLE(). + (++) If interrupts has been used, disable GFXMMU global interrupt with + HAL_NVIC_DisableIRQ(). + (#) De-initialize GFXMMU using the HAL_GFXMMU_DeInit() function. + + *** Callback registration *** + ============================= + [..] + The compilation define USE_HAL_GFXMMU_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use functions HAL_GFXMMU_RegisterCallback() to register a user callback. + + [..] + Function HAL_GFXMMU_RegisterCallback() allows to register following callbacks: + (+) ErrorCallback : GFXMMU error. + (+) MspInitCallback : GFXMMU MspInit. + (+) MspDeInitCallback : GFXMMU MspDeInit. + [..] + This function takes as parameters the HAL peripheral handle, the callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_GFXMMU_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. + HAL_GFXMMU_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the callback ID. + [..] + This function allows to reset following callbacks: + (+) ErrorCallback : GFXMMU error. + (+) MspInitCallback : GFXMMU MspInit. + (+) MspDeInitCallback : GFXMMU MspDeInit. + + [..] + By default, after the HAL_GFXMMU_Init and if the state is HAL_GFXMMU_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions: + examples HAL_GFXMMU_ErrorCallback(). + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_GFXMMU_Init + and HAL_GFXMMU_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_GFXMMU_Init and HAL_GFXMMU_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_GFXMMU_RegisterCallback before calling HAL_GFXMMU_DeInit + or HAL_GFXMMU_Init function. + + [..] + When the compilation define USE_HAL_GFXMMU_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ +#ifdef HAL_GFXMMU_MODULE_ENABLED +#if defined(GFXMMU) +/** @defgroup GFXMMU GFXMMU + * @brief GFXMMU HAL driver module + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup GFXMMU_Private_Constants GFXMMU Private Constants + * @{ + */ +#define GFXMMU_LUTXL_FVB_OFFSET 8U +#define GFXMMU_LUTXL_LVB_OFFSET 16U +#define GFXMMU_CR_ITS_MASK 0x1FU +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup GFXMMU_Exported_Functions GFXMMU Exported Functions + * @{ + */ + +/** @defgroup GFXMMU_Exported_Functions_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 GFXMMU. + (+) De-initialize the GFXMMU. +@endverbatim + * @{ + */ + +/** + * @brief Initialize the GFXMMU according to the specified parameters in the + * GFXMMU_InitTypeDef structure and initialize the associated handle. + * @param hgfxmmu GFXMMU handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_Init(GFXMMU_HandleTypeDef *hgfxmmu) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check GFXMMU handle */ + if (hgfxmmu == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + assert_param(IS_GFXMMU_BLOCK_SIZE(hgfxmmu->Init.BlockSize)); + assert_param(IS_FUNCTIONAL_STATE(hgfxmmu->Init.AddressTranslation)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf0Address)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf1Address)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf2Address)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(hgfxmmu->Init.Buffers.Buf3Address)); + assert_param(IS_FUNCTIONAL_STATE(hgfxmmu->Init.Interrupts.Activation)); + +#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) + /* Reset callback pointers to the weak predefined callbacks */ + hgfxmmu->ErrorCallback = HAL_GFXMMU_ErrorCallback; + + /* Call GFXMMU MSP init function */ + if (hgfxmmu->MspInitCallback == NULL) + { + hgfxmmu->MspInitCallback = HAL_GFXMMU_MspInit; + } + hgfxmmu->MspInitCallback(hgfxmmu); +#else + /* Call GFXMMU MSP init function */ + HAL_GFXMMU_MspInit(hgfxmmu); +#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1 */ + + /* Configure GFXMMU_CR register */ + hgfxmmu->Instance->CR = 0U; + hgfxmmu->Instance->CR |= (hgfxmmu->Init.BlockSize); + if (hgfxmmu->Init.AddressTranslation == ENABLE) + { + hgfxmmu->Instance->CR |= GFXMMU_CR_ATE; + } + if (hgfxmmu->Init.Interrupts.Activation == ENABLE) + { + assert_param(IS_GFXMMU_INTERRUPTS(hgfxmmu->Init.Interrupts.UsedInterrupts)); + hgfxmmu->Instance->CR |= hgfxmmu->Init.Interrupts.UsedInterrupts; + } + + /* Configure default value on GFXMMU_DVR register */ + hgfxmmu->Instance->DVR = hgfxmmu->Init.DefaultValue; + + /* Configure physical buffer addresses on GFXMMU_BxCR registers */ + hgfxmmu->Instance->B0CR = hgfxmmu->Init.Buffers.Buf0Address; + hgfxmmu->Instance->B1CR = hgfxmmu->Init.Buffers.Buf1Address; + hgfxmmu->Instance->B2CR = hgfxmmu->Init.Buffers.Buf2Address; + hgfxmmu->Instance->B3CR = hgfxmmu->Init.Buffers.Buf3Address; + + /* Reset GFXMMU error code */ + hgfxmmu->ErrorCode = GFXMMU_ERROR_NONE; + + /* Set GFXMMU to ready state */ + hgfxmmu->State = HAL_GFXMMU_STATE_READY; + } + /* Return function status */ + return status; +} + +/** + * @brief De-initialize the GFXMMU. + * @param hgfxmmu GFXMMU handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_DeInit(GFXMMU_HandleTypeDef *hgfxmmu) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check GFXMMU handle */ + if (hgfxmmu == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + + /* Disable all interrupts on GFXMMU_CR register */ + hgfxmmu->Instance->CR &= ~(GFXMMU_CR_B0OIE | GFXMMU_CR_B1OIE | GFXMMU_CR_B2OIE | GFXMMU_CR_B3OIE | + GFXMMU_CR_AMEIE); + + /* Call GFXMMU MSP de-init function */ +#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) + if (hgfxmmu->MspDeInitCallback == NULL) + { + hgfxmmu->MspDeInitCallback = HAL_GFXMMU_MspDeInit; + } + hgfxmmu->MspDeInitCallback(hgfxmmu); +#else + HAL_GFXMMU_MspDeInit(hgfxmmu); +#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1 */ + + /* Set GFXMMU to reset state */ + hgfxmmu->State = HAL_GFXMMU_STATE_RESET; + } + /* Return function status */ + return status; +} + +/** + * @brief Initialize the GFXMMU MSP. + * @param hgfxmmu GFXMMU handle. + * @retval None. + */ +__weak void HAL_GFXMMU_MspInit(GFXMMU_HandleTypeDef *hgfxmmu) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxmmu); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXMMU_MspInit could be implemented in the user file. + */ +} + +/** + * @brief De-initialize the GFXMMU MSP. + * @param hgfxmmu GFXMMU handle. + * @retval None. + */ +__weak void HAL_GFXMMU_MspDeInit(GFXMMU_HandleTypeDef *hgfxmmu) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxmmu); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXMMU_MspDeInit could be implemented in the user file. + */ +} + +#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) +/** + * @brief Register a user GFXMMU callback + * to be used instead of the weak predefined callback. + * @param hgfxmmu GFXMMU handle. + * @param CallbackID ID of the callback to be registered. + * This parameter can be one of the following values: + * @arg @ref HAL_GFXMMU_ERROR_CB_ID error callback ID. + * @arg @ref HAL_GFXMMU_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_GFXMMU_MSPDEINIT_CB_ID MSP de-init callback ID. + * @param pCallback pointer to the callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_RegisterCallback(GFXMMU_HandleTypeDef *hgfxmmu, + HAL_GFXMMU_CallbackIDTypeDef CallbackID, + pGFXMMU_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + else + { + if (HAL_GFXMMU_STATE_READY == hgfxmmu->State) + { + switch (CallbackID) + { + case HAL_GFXMMU_ERROR_CB_ID : + hgfxmmu->ErrorCallback = pCallback; + break; + case HAL_GFXMMU_MSPINIT_CB_ID : + hgfxmmu->MspInitCallback = pCallback; + break; + case HAL_GFXMMU_MSPDEINIT_CB_ID : + hgfxmmu->MspDeInitCallback = pCallback; + break; + default : + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_GFXMMU_STATE_RESET == hgfxmmu->State) + { + switch (CallbackID) + { + case HAL_GFXMMU_MSPINIT_CB_ID : + hgfxmmu->MspInitCallback = pCallback; + break; + case HAL_GFXMMU_MSPDEINIT_CB_ID : + hgfxmmu->MspDeInitCallback = pCallback; + break; + default : + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + } + return status; +} + +/** + * @brief Unregister a user GFXMMU callback. + * GFXMMU callback is redirected to the weak predefined callback. + * @param hgfxmmu GFXMMU handle. + * @param CallbackID ID of the callback to be unregistered. + * This parameter can be one of the following values: + * @arg @ref HAL_GFXMMU_ERROR_CB_ID error callback ID. + * @arg @ref HAL_GFXMMU_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_GFXMMU_MSPDEINIT_CB_ID MSP de-init callback ID. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_UnRegisterCallback(GFXMMU_HandleTypeDef *hgfxmmu, + HAL_GFXMMU_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_GFXMMU_STATE_READY == hgfxmmu->State) + { + switch (CallbackID) + { + case HAL_GFXMMU_ERROR_CB_ID : + hgfxmmu->ErrorCallback = HAL_GFXMMU_ErrorCallback; + break; + case HAL_GFXMMU_MSPINIT_CB_ID : + hgfxmmu->MspInitCallback = HAL_GFXMMU_MspInit; + break; + case HAL_GFXMMU_MSPDEINIT_CB_ID : + hgfxmmu->MspDeInitCallback = HAL_GFXMMU_MspDeInit; + break; + default : + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_GFXMMU_STATE_RESET == hgfxmmu->State) + { + switch (CallbackID) + { + case HAL_GFXMMU_MSPINIT_CB_ID : + hgfxmmu->MspInitCallback = HAL_GFXMMU_MspInit; + break; + case HAL_GFXMMU_MSPDEINIT_CB_ID : + hgfxmmu->MspDeInitCallback = HAL_GFXMMU_MspDeInit; + break; + default : + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update the error code */ + hgfxmmu->ErrorCode |= GFXMMU_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + return status; +} +#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup GFXMMU_Exported_Functions_Group2 Operations functions + * @brief GFXMMU operation functions + * +@verbatim + ============================================================================== + ##### Operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Configure LUT. + (+) Modify physical buffer addresses. + (+) Configure packing. + (+) Manage error. +@endverbatim + * @{ + */ + +/** + * @brief This function allows to copy LUT from flash to look up RAM. + * @param hgfxmmu GFXMMU handle. + * @param FirstLine First line enabled on LUT. + * This parameter must be a number between Min_Data = 0 and Max_Data = 1023. + * @param LinesNumber Number of lines enabled on LUT. + * This parameter must be a number between Min_Data = 1 and Max_Data = 1024. + * @param Address Start address of LUT in flash. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_ConfigLut(const GFXMMU_HandleTypeDef *hgfxmmu, + uint32_t FirstLine, + uint32_t LinesNumber, + uint32_t Address) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + assert_param(IS_GFXMMU_LUT_LINE(FirstLine)); + assert_param(IS_GFXMMU_LUT_LINES_NUMBER(LinesNumber)); + + /* Check GFXMMU state and coherent parameters */ + if ((hgfxmmu->State != HAL_GFXMMU_STATE_READY) || ((FirstLine + LinesNumber) > 1024U)) + { + status = HAL_ERROR; + } + /* Check address translation status */ + else if ((hgfxmmu->Instance->CR & GFXMMU_CR_ATE) == 0U) + { + status = HAL_ERROR; + } + else + { + uint32_t current_address; + uint32_t current_line; + uint32_t lutxl_address; + uint32_t lutxh_address; + + /* Initialize local variables */ + current_address = Address; + current_line = 0U; + lutxl_address = (uint32_t) &(hgfxmmu->Instance->LUT[2U * FirstLine]); + lutxh_address = (uint32_t) &(hgfxmmu->Instance->LUT[(2U * FirstLine) + 1U]); + + /* Copy LUT from flash to look up RAM */ + while (current_line < LinesNumber) + { + *((uint32_t *)lutxl_address) = *((uint32_t *)current_address); + current_address += 4U; + *((uint32_t *)lutxh_address) = *((uint32_t *)current_address); + current_address += 4U; + lutxl_address += 8U; + lutxh_address += 8U; + current_line++; + } + } + /* Return function status */ + return status; +} + +/** + * @brief This function allows to disable a range of LUT lines. + * @param hgfxmmu GFXMMU handle. + * @param FirstLine First line to disable on LUT. + * This parameter must be a number between Min_Data = 0 and Max_Data = 1023. + * @param LinesNumber Number of lines to disable on LUT. + * This parameter must be a number between Min_Data = 1 and Max_Data = 1024. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_DisableLutLines(const GFXMMU_HandleTypeDef *hgfxmmu, + uint32_t FirstLine, + uint32_t LinesNumber) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + assert_param(IS_GFXMMU_LUT_LINE(FirstLine)); + assert_param(IS_GFXMMU_LUT_LINES_NUMBER(LinesNumber)); + + /* Check GFXMMU state and coherent parameters */ + if ((hgfxmmu->State != HAL_GFXMMU_STATE_READY) || ((FirstLine + LinesNumber) > 1024U)) + { + status = HAL_ERROR; + } + /* Check address translation status */ + else if ((hgfxmmu->Instance->CR & GFXMMU_CR_ATE) == 0U) + { + status = HAL_ERROR; + } + else + { + uint32_t current_line; + uint32_t lutxl_address; + uint32_t lutxh_address; + + /* Initialize local variables */ + current_line = 0U; + lutxl_address = (uint32_t) &(hgfxmmu->Instance->LUT[2U * FirstLine]); + lutxh_address = (uint32_t) &(hgfxmmu->Instance->LUT[(2U * FirstLine) + 1U]); + + /* Disable LUT lines */ + while (current_line < LinesNumber) + { + *((uint32_t *)lutxl_address) = 0U; + *((uint32_t *)lutxh_address) = 0U; + lutxl_address += 8U; + lutxh_address += 8U; + current_line++; + } + } + /* Return function status */ + return status; +} + +/** + * @brief This function allows to configure one line of LUT. + * @param hgfxmmu GFXMMU handle. + * @param lutLine LUT line parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_ConfigLutLine(const GFXMMU_HandleTypeDef *hgfxmmu, const GFXMMU_LutLineTypeDef *lutLine) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + assert_param(IS_GFXMMU_LUT_LINE(lutLine->LineNumber)); + assert_param(IS_GFXMMU_LUT_LINE_STATUS(lutLine->LineStatus)); + assert_param(IS_GFXMMU_LUT_BLOCK(lutLine->FirstVisibleBlock)); + assert_param(IS_GFXMMU_LUT_BLOCK(lutLine->LastVisibleBlock)); + assert_param(IS_GFXMMU_LUT_LINE_OFFSET(lutLine->LineOffset)); + + /* Check GFXMMU state */ + if (hgfxmmu->State != HAL_GFXMMU_STATE_READY) + { + status = HAL_ERROR; + } + /* Check address translation status */ + else if ((hgfxmmu->Instance->CR & GFXMMU_CR_ATE) == 0U) + { + status = HAL_ERROR; + } + else + { + uint32_t lutxl_address; + uint32_t lutxh_address; + + /* Initialize local variables */ + lutxl_address = (uint32_t) &(hgfxmmu->Instance->LUT[2U * lutLine->LineNumber]); + lutxh_address = (uint32_t) &(hgfxmmu->Instance->LUT[(2U * lutLine->LineNumber) + 1U]); + + /* Configure LUT line */ + if (lutLine->LineStatus == GFXMMU_LUT_LINE_ENABLE) + { + /* Enable and configure LUT line */ + *((uint32_t *)lutxl_address) = (lutLine->LineStatus | + (lutLine->FirstVisibleBlock << GFXMMU_LUTXL_FVB_OFFSET) | + (lutLine->LastVisibleBlock << GFXMMU_LUTXL_LVB_OFFSET)); + *((uint32_t *)lutxh_address) = (uint32_t) lutLine->LineOffset; + } + else + { + /* Disable LUT line */ + *((uint32_t *)lutxl_address) = 0U; + *((uint32_t *)lutxh_address) = 0U; + } + } + /* Return function status */ + return status; +} + +/** + * @brief This function allows to modify physical buffer addresses. + * @param hgfxmmu GFXMMU handle. + * @param Buffers Buffers parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_ModifyBuffers(GFXMMU_HandleTypeDef *hgfxmmu, const GFXMMU_BuffersTypeDef *Buffers) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf0Address)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf1Address)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf2Address)); + assert_param(IS_GFXMMU_BUFFER_ADDRESS(Buffers->Buf3Address)); + + /* Check GFXMMU state */ + if (hgfxmmu->State != HAL_GFXMMU_STATE_READY) + { + status = HAL_ERROR; + } + else + { + /* Modify physical buffer addresses on GFXMMU_BxCR registers */ + hgfxmmu->Instance->B0CR = Buffers->Buf0Address; + hgfxmmu->Instance->B1CR = Buffers->Buf1Address; + hgfxmmu->Instance->B2CR = Buffers->Buf2Address; + hgfxmmu->Instance->B3CR = Buffers->Buf3Address; + } + /* Return function status */ + return status; +} + +/** + * @brief This function allows to configure packing. + * @param hgfxmmu GFXMMU handle. + * @param pPacking Packing parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXMMU_ConfigPacking(GFXMMU_HandleTypeDef *hgfxmmu, const GFXMMU_PackingTypeDef *pPacking) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_GFXMMU_ALL_INSTANCE(hgfxmmu->Instance)); + assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer0Activation)); + assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer1Activation)); + assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer2Activation)); + assert_param(IS_FUNCTIONAL_STATE(pPacking->Buffer3Activation)); + assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer0Mode)); + assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer1Mode)); + assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer2Mode)); + assert_param(IS_GFXMMU_PACKING_MODE(pPacking->Buffer3Mode)); + assert_param(IS_GFXMMU_DEFAULT_ALPHA_VALUE(pPacking->DefaultAlpha)); + + /* Check GFXMMU state */ + if (hgfxmmu->State != HAL_GFXMMU_STATE_READY) + { + status = HAL_ERROR; + } + /* Check block size is set to 12-byte*/ + else if ((hgfxmmu->Instance->CR & GFXMMU_CR_BS) == 0U) + { + status = HAL_ERROR; + } + else + { + uint32_t reg_value = 0U; + + /* Configure packing for all buffers on GFXMMU_CR register */ + if (pPacking->Buffer0Activation == ENABLE) + { + reg_value |= ((pPacking->Buffer0Mode << GFXMMU_CR_B0PM_Pos) | GFXMMU_CR_B0PE); + } + if (pPacking->Buffer1Activation == ENABLE) + { + reg_value |= ((pPacking->Buffer1Mode << GFXMMU_CR_B1PM_Pos) | GFXMMU_CR_B1PE); + } + if (pPacking->Buffer2Activation == ENABLE) + { + reg_value |= ((pPacking->Buffer2Mode << GFXMMU_CR_B2PM_Pos) | GFXMMU_CR_B2PE); + } + if (pPacking->Buffer3Activation == ENABLE) + { + reg_value |= ((pPacking->Buffer3Mode << GFXMMU_CR_B3PM_Pos) | GFXMMU_CR_B3PE); + } + hgfxmmu->Instance->CR &= ~(GFXMMU_CR_B0PE_Msk | GFXMMU_CR_B0PM_Msk | + GFXMMU_CR_B1PE_Msk | GFXMMU_CR_B1PM_Msk | + GFXMMU_CR_B2PE_Msk | GFXMMU_CR_B2PM_Msk | + GFXMMU_CR_B3PE_Msk | GFXMMU_CR_B3PM_Msk); + hgfxmmu->Instance->CR |= reg_value; + + /* Configure default alpha value on GFXMMU_DAR register */ + hgfxmmu->Instance->DAR = pPacking->DefaultAlpha; + } + /* Return function status */ + return status; +} + +/** + * @brief This function handles the GFXMMU interrupts. + * @param hgfxmmu GFXMMU handle. + * @retval None. + */ +void HAL_GFXMMU_IRQHandler(GFXMMU_HandleTypeDef *hgfxmmu) +{ + uint32_t flags, interrupts, error; + + /* Read current flags and interrupts and determine which error occurs */ + flags = hgfxmmu->Instance->SR; + interrupts = (hgfxmmu->Instance->CR & GFXMMU_CR_ITS_MASK); + error = (flags & interrupts); + + if (error != 0U) + { + /* Clear flags on GFXMMU_FCR register */ + hgfxmmu->Instance->FCR = error; + + /* Update GFXMMU error code */ + hgfxmmu->ErrorCode |= error; + + /* Call GFXMMU error callback */ +#if (USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1) + hgfxmmu->ErrorCallback(hgfxmmu); +#else + HAL_GFXMMU_ErrorCallback(hgfxmmu); +#endif /* USE_HAL_GFXMMU_REGISTER_CALLBACKS == 1 */ + } +} + +/** + * @brief Error callback. + * @param hgfxmmu GFXMMU handle. + * @retval None. + */ +__weak void HAL_GFXMMU_ErrorCallback(GFXMMU_HandleTypeDef *hgfxmmu) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxmmu); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_GFXMMU_ErrorCallback could be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup GFXMMU_Exported_Functions_Group3 State functions + * @brief GFXMMU state functions + * +@verbatim + ============================================================================== + ##### State functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Get GFXMMU handle state. + (+) Get GFXMMU error code. +@endverbatim + * @{ + */ + +/** + * @brief This function allows to get the current GFXMMU handle state. + * @param hgfxmmu GFXMMU handle. + * @retval GFXMMU state. + */ +HAL_GFXMMU_StateTypeDef HAL_GFXMMU_GetState(const GFXMMU_HandleTypeDef *hgfxmmu) +{ + /* Return GFXMMU handle state */ + return hgfxmmu->State; +} + +/** + * @brief This function allows to get the current GFXMMU error code. + * @param hgfxmmu GFXMMU handle. + * @retval GFXMMU error code. + */ +uint32_t HAL_GFXMMU_GetError(GFXMMU_HandleTypeDef *hgfxmmu) +{ + uint32_t error_code; + + /* Enter in critical section */ + __disable_irq(); + + /* Store and reset GFXMMU error code */ + error_code = hgfxmmu->ErrorCode; + hgfxmmu->ErrorCode = GFXMMU_ERROR_NONE; + + /* Exit from critical section */ + __enable_irq(); + + /* Return GFXMMU error code */ + return error_code; +} + +/** + * @} + */ + +/** + * @} + */ +/* End of exported functions -------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* End of private functions --------------------------------------------------*/ + +/** + * @} + */ +#endif /* GFXMMU */ +#endif /* HAL_GFXMMU_MODULE_ENABLED */ +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxtim.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxtim.c index f423bd099..2a1b90c18 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxtim.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gfxtim.c @@ -1,2032 +1,2032 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_gfxtim.c - * @author MCD Application Team - * @brief This file provides firmware functions to manage the following - * functionalities of the Multi-function Digital Filter (GFXTIM) - * peripheral: - * + Initialization and de-initialization - * + Integrated frame and line clock generation - * + One absolute frame counter with one compare channel - * + Two auto reload relative frame counter - * + One line timer with two compare channel - * + External Tearing Effect line management & synchronization - * + Four programmable event generators with external trigger generation - * + One watchdog counter - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - *** Initialization and de-initialization *** - ============================================ - [..] - (#) User has first to initialize GFXTIM. - (#) As prerequisite, fill in the HAL_GFXTIM_MspInit() : - (++) Enable GFXTIM with __HAL_RCC_GFXTIM_CLK_ENABLE - (++) Enable the clocks for the used GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). - (++) Configure these pins in alternate mode using HAL_GPIO_Init(). - (++) If interrupt mode is used, enable and configure GFXTIM - interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). - - [..] - (#) User can de-initialize GFXTIM with HAL_GFXTIM_DeInit() function. - - *** generic functions *** - ========================= - [..] - (#) HAL_GFXTIM_IRQHandler will be called when GFXTIM interrupt occurs. - (#) HAL_GFXTIM_ErrorCallback will be called when GFXTIM or ADF error occurs. - (#) Use HAL_GFXTIM_GetState() to get the current GFXTIM or ADF instance state. - (#) Use HAL_GFXTIM_GetErrorCode() to get the current GFXTIM or ADF instance error code. - - - -#if defined(GENERATOR_CALLBACKS_REGISTERING_AVAILABLE) - *** Callback registration *** - ============================================= - - The compilation define USE_HAL_GFXTIM_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Function @ref HAL_GFXTIM_RegisterCallback() to register an interrupt callback. - - Function @ref HAL_GFXTIM_RegisterCallback() registers following callbacks: - (+) HAL_GFXTIM_AbsoluteTimer_AFCC1Callback - (+) HAL_GFXTIM_AbsoluteTimer_AFCOFCallback - (+) HAL_GFXTIM_AbsoluteTimer_ALCC1Callback - (+) HAL_GFXTIM_AbsoluteTimer_ALCC2Callback - (+) HAL_GFXTIM_AbsoluteTimer_ALCOFCallback - (+) HAL_GFXTIM_RelativeTimer_RFC1RCallback - (+) HAL_GFXTIM_RelativeTimer_RFC2RCallback - (+) HAL_GFXTIM_TECallback - (+) HAL_GFXTIM_EventGenerator_EV1Callback - (+) HAL_GFXTIM_EventGenerator_EV2Callback - (+) HAL_GFXTIM_EventGenerator_EV3Callback - (+) HAL_GFXTIM_EventGenerator_EV4Callback - (+) HAL_GFXTIM_WatchdogTimer_AlarmCallback - (+) HAL_GFXTIM_WatchdogTimer_PreAlarmCallback - (+) MspInitCallback - (+) MspDeInitCallback - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function @ref HAL_GFXTIM_UnRegisterCallback() to reset a callback to the default - weak function. - @ref HAL_GFXTIM_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function resets following callbacks: - (+) HAL_GFXTIM_AbsoluteTimer_AFCC1Callback - (+) HAL_GFXTIM_AbsoluteTimer_AFCOFCallback - (+) HAL_GFXTIM_AbsoluteTimer_ALCC1Callback - (+) HAL_GFXTIM_AbsoluteTimer_ALCC2Callback - (+) HAL_GFXTIM_AbsoluteTimer_ALCOFCallback - (+) HAL_GFXTIM_RelativeTimer_RFC1RCallback - (+) HAL_GFXTIM_RelativeTimer_RFC2RCallback - (+) HAL_GFXTIM_TECallback - (+) HAL_GFXTIM_EventGenerator_EV1Callback - (+) HAL_GFXTIM_EventGenerator_EV2Callback - (+) HAL_GFXTIM_EventGenerator_EV3Callback - (+) HAL_GFXTIM_EventGenerator_EV4Callback - (+) HAL_GFXTIM_WatchdogTimer_AlarmCallback - (+) HAL_GFXTIM_WatchdogTimer_PreAlarmCallback - (+) MspInitCallback - (+) MspDeInitCallback - - By default, after the HAL_GFXTIM_Init() and when the state is HAL_GFXTIM_STATE_RESET, - all callbacks are set to the corresponding weak functions: - examples @ref HAL_GFXTIM_ErrorCallback(), @ref HAL_GFXTIM_CalculateCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak function in the HAL_GFXTIM_Init()/ @ref HAL_GFXTIM_DeInit() only when - these callbacks are null (not registered beforehand). - if not, MspInit or MspDeInit are not null, the HAL_GFXTIM_Init()/ @ref HAL_GFXTIM_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in HAL_GFXTIM_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_GFXTIM_STATE_READY or HAL_GFXTIM_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using @ref HAL_GFXTIM_RegisterCallback() before calling @ref HAL_GFXTIM_DeInit() - or HAL_GFXTIM_Init() function. - - When The compilation define USE_HAL_GFXTIM_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. -#endif - - @endverbatim - */ -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ -#ifdef HAL_GFXTIM_MODULE_ENABLED -#if defined(GFXTIM) -/** @defgroup GFXTIM GFXTIM - * @brief GFXTIM HAL module driver - * @{ - */ - -/* Exported functions ---------------------------------------------------------*/ -/** @defgroup GFXTIM_Exported_Functions GFXTIM Exported Functions - * @{ - */ - -/** @defgroup GFXTIM_Exported_Functions_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 GFXTIM instance. - (+) De-initialize the GFXTIM instance. - (+) Register and unregister callbacks. -@endverbatim - * @{ - */ - -/** - * @brief Initialize the GFXTIM instance according to the specified parameters - * in the GFXTIM_InitTypeDef structure and initialize the associated handle. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_Init(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_ERROR; - - if (hgfxtim != NULL) - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_SYNC_SRC(hgfxtim->Init.SynchroSrc)); - assert_param(IS_GFXTIM_TE_SRC(hgfxtim->Init.TearingEffectSrc)); - assert_param(IS_GFXTIM_TE_POLARITY(hgfxtim->Init.TearingEffectPolarity)); - assert_param(IS_GFXTIM_INTERRUPT(hgfxtim->Init.TearingEffectInterrupt)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_RESET) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) - /* Reset callback pointers to the weak predefined callbacks */ - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback = HAL_GFXTIM_AbsoluteTimer_AFCC1Callback; - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback = HAL_GFXTIM_AbsoluteTimer_AFCOFCallback; - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback = HAL_GFXTIM_AbsoluteTimer_ALCC1Callback; - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback = HAL_GFXTIM_AbsoluteTimer_ALCC2Callback; - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback = HAL_GFXTIM_AbsoluteTimer_ALCOFCallback; - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback = HAL_GFXTIM_RelativeTimer_RFC1RCallback; - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback = HAL_GFXTIM_RelativeTimer_RFC2RCallback; - hgfxtim->HAL_GFXTIM_TECallback = HAL_GFXTIM_TECallback; - hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback = HAL_GFXTIM_EventGenerator_EV1Callback; - hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback = HAL_GFXTIM_EventGenerator_EV2Callback; - hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback = HAL_GFXTIM_EventGenerator_EV3Callback; - hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback = HAL_GFXTIM_EventGenerator_EV4Callback; - hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback = HAL_GFXTIM_WatchdogTimer_AlarmCallback; - hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback = HAL_GFXTIM_WatchdogTimer_PreAlarmCallback; - hgfxtim->ErrorCallback = HAL_GFXTIM_ErrorCallback; - - /* Call GFXTIM MSP init function */ - if (hgfxtim->MspInitCallback == NULL) - { - hgfxtim->MspInitCallback = HAL_GFXTIM_MspInit; - } - hgfxtim->MspInitCallback(hgfxtim); -#else /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - /* Call GFXTIM MSP init function */ - HAL_GFXTIM_MspInit(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - - /* Set Synchronization signals sources (HSYNC and VSYNC), Tearing Effect source and polarity, */ - MODIFY_REG(hgfxtim->Instance->CR, \ - GFXTIM_CR_SYNCS | GFXTIM_CR_TES | GFXTIM_CR_TEPOL, - hgfxtim->Init.SynchroSrc | hgfxtim->Init.TearingEffectSrc | hgfxtim->Init.TearingEffectPolarity); - - /* Set tearing effect interrupt */ - MODIFY_REG(hgfxtim->Instance->IER, GFXTIM_IER_TEIE, - (hgfxtim->Init.TearingEffectInterrupt << GFXTIM_IER_TEIE_Pos)); - - /* Update error code and state */ - hgfxtim->ErrorCode = GFXTIM_ERROR_NONE; - hgfxtim->State = HAL_GFXTIM_STATE_READY; - status = HAL_OK; - } - } - - return status; -} - -/** - * @brief De-initialize the GFXTIM instance. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_DeInit(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_ERROR; - - if (hgfxtim != NULL) - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Call GFXTIM MSP deinit function */ -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) - if (hgfxtim->MspDeInitCallback == NULL) - { - hgfxtim->MspDeInitCallback = HAL_GFXTIM_MspDeInit; - } - hgfxtim->MspDeInitCallback(hgfxtim); -#else /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - HAL_GFXTIM_MspDeInit(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - - /* Update state */ - hgfxtim->State = HAL_GFXTIM_STATE_RESET; - status = HAL_OK; - } - } - - return status; -} - -/** - * @brief Initialize the GFXTIM instance MSP. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_MspInit(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_MspInit could be implemented in the user file */ -} - -/** - * @brief De-initialize the GFXTIM instance MSP. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_MspDeInit(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_MspDeInit could be implemented in the user file */ -} - -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) -/** - * @brief Register a user GFXTIM callback to be used instead of the weak predefined callback. - * @param hgfxtim GFXTIM handle. - * @param CallbackID ID of the callback to be registered. - * This parameter can be one of the following values: - * @arg @ref HAL_GFXTIM_AFC_COMPARE1_CB_ID Absolute frame counter compare 1 callback ID - * @arg @ref HAL_GFXTIM_AFC_OVERFLOW_CB_ID Absolute frame counter overflow callback ID - * @arg @ref HAL_GFXTIM_ALC_COMPARE1_CB_ID Absolute line counter compare 1 callback ID - * @arg @ref HAL_GFXTIM_ALC_COMPARE2_CB_ID Absolute line counter compare 2 callback ID - * @arg @ref HAL_GFXTIM_ALC_OVERFLOW_CB_ID Absolute line counter overflow callback ID - * @arg @ref HAL_GFXTIM_RFC1_RELOAD_CB_ID Relative frame counter 1 reload callback ID - * @arg @ref HAL_GFXTIM_RFC2_RELOAD_CB_ID Relative frame counter 2 reload callback ID - * @arg @ref HAL_GFXTIM_TE_CB_ID External tearing effect callback ID - * @arg @ref HAL_GFXTIM_EVENT1_CB_ID Event events 1 callback ID - * @arg @ref HAL_GFXTIM_EVENT2_CB_ID Event events 2 callback ID - * @arg @ref HAL_GFXTIM_EVENT3_CB_ID Event events 3 callback ID - * @arg @ref HAL_GFXTIM_EVENT4_CB_ID Event events 4 callback ID - * @arg @ref HAL_GFXTIM_WDG_ALARM_CB_ID Watchdog alarm callback ID - * @arg @ref HAL_GFXTIM_WDG_PREALARM_CB_ID Watchdog pre alarm callback ID - * @arg @ref HAL_GFXTIM_ERROR_CB_ID error callback ID - * @arg @ref HAL_GFXTIM_MSP_INIT_CB_ID MSP initialization user callback ID - * @arg @ref HAL_GFXTIM_MSP_DEINIT_CB_ID MSP de-initialization user callback ID - * @param pCallback pointer to the callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RegisterCallback(GFXTIM_HandleTypeDef *hgfxtim, - HAL_GFXTIM_CallbackIDTypeDef CallbackID, - pGFXTIM_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else if (pCallback == NULL) - { - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - else - { - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - switch (CallbackID) - { - case HAL_GFXTIM_AFC_COMPARE1_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback = pCallback; - break; - case HAL_GFXTIM_AFC_OVERFLOW_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback = pCallback; - break; - case HAL_GFXTIM_ALC_COMPARE1_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback = pCallback; - break; - case HAL_GFXTIM_ALC_COMPARE2_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback = pCallback; - break; - case HAL_GFXTIM_ALC_OVERFLOW_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback = pCallback; - break; - case HAL_GFXTIM_RFC1_RELOAD_CB_ID : - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback = pCallback; - break; - case HAL_GFXTIM_RFC2_RELOAD_CB_ID : - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback = pCallback; - break; - case HAL_GFXTIM_TE_CB_ID : - hgfxtim->HAL_GFXTIM_TECallback = pCallback; - break; - case HAL_GFXTIM_EVENT1_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback = pCallback; - break; - case HAL_GFXTIM_EVENT2_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback = pCallback; - break; - case HAL_GFXTIM_EVENT3_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback = pCallback; - break; - case HAL_GFXTIM_EVENT4_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback = pCallback; - break; - case HAL_GFXTIM_WDG_ALARM_CB_ID : - hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback = pCallback; - break; - case HAL_GFXTIM_WDG_PREALARM_CB_ID : - hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback = pCallback; - break; - case HAL_GFXTIM_ERROR_CB_ID : - hgfxtim->ErrorCallback = pCallback; - break; - case HAL_GFXTIM_MSP_INIT_CB_ID : - hgfxtim->MspInitCallback = pCallback; - break; - case HAL_GFXTIM_MSP_DEINIT_CB_ID : - hgfxtim->MspDeInitCallback = pCallback; - break; - default : - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (hgfxtim->State == HAL_GFXTIM_STATE_RESET) - { - switch (CallbackID) - { - case HAL_GFXTIM_MSP_INIT_CB_ID : - hgfxtim->MspInitCallback = pCallback; - break; - case HAL_GFXTIM_MSP_DEINIT_CB_ID : - hgfxtim->MspDeInitCallback = pCallback; - break; - default : - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief Unregister a user GFXTIM callback. - * GFXTIM callback is redirected to the weak predefined callback. - * @param hgfxtim GFXTIM handle. - * @param CallbackID ID of the callback to be unregistered. - * This parameter can be one of the following values: - * @arg @ref HAL_GFXTIM_AFC_COMPARE1_CB_ID Absolute frame counter compare 1 callback ID - * @arg @ref HAL_GFXTIM_AFC_OVERFLOW_CB_ID Absolute frame counter overflow callback ID - * @arg @ref HAL_GFXTIM_ALC_COMPARE1_CB_ID Absolute line counter compare 1 callback ID - * @arg @ref HAL_GFXTIM_ALC_COMPARE2_CB_ID Absolute line counter compare 2 callback ID - * @arg @ref HAL_GFXTIM_ALC_OVERFLOW_CB_ID Absolute line counter overflow callback ID - * @arg @ref HAL_GFXTIM_RFC1_RELOAD_CB_ID Relative frame counter 1 reload callback ID - * @arg @ref HAL_GFXTIM_RFC2_RELOAD_CB_ID Relative frame counter 2 reload callback ID - * @arg @ref HAL_GFXTIM_TE_CB_ID External tearing effect callback ID - * @arg @ref HAL_GFXTIM_EVENT1_CB_ID Event events 1 callback ID - * @arg @ref HAL_GFXTIM_EVENT2_CB_ID Event events 2 callback ID - * @arg @ref HAL_GFXTIM_EVENT3_CB_ID Event events 3 callback ID - * @arg @ref HAL_GFXTIM_EVENT4_CB_ID Event events 4 callback ID - * @arg @ref HAL_GFXTIM_WDG_ALARM_CB_ID Watchdog alarm callback ID - * @arg @ref HAL_GFXTIM_WDG_PREALARM_CB_ID Watchdog pre alarm callback ID - * @arg @ref HAL_GFXTIM_ERROR_CB_ID error callback ID - * @arg @ref HAL_GFXTIM_MSP_INIT_CB_ID MSP initialization user callback ID - * @arg @ref HAL_GFXTIM_MSP_DEINIT_CB_ID MSP de-initialization user callback ID - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_UnRegisterCallback(GFXTIM_HandleTypeDef *hgfxtim, - HAL_GFXTIM_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - switch (CallbackID) - { - case HAL_GFXTIM_AFC_COMPARE1_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback = HAL_GFXTIM_AbsoluteTimer_AFCC1Callback; - break; - case HAL_GFXTIM_AFC_OVERFLOW_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback = HAL_GFXTIM_AbsoluteTimer_AFCOFCallback; - break; - case HAL_GFXTIM_ALC_COMPARE1_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback = HAL_GFXTIM_AbsoluteTimer_ALCC1Callback; - break; - case HAL_GFXTIM_ALC_COMPARE2_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback = HAL_GFXTIM_AbsoluteTimer_ALCC2Callback; - break; - case HAL_GFXTIM_ALC_OVERFLOW_CB_ID : - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback = HAL_GFXTIM_AbsoluteTimer_ALCOFCallback; - break; - case HAL_GFXTIM_RFC1_RELOAD_CB_ID : - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback = HAL_GFXTIM_RelativeTimer_RFC1RCallback; - break; - case HAL_GFXTIM_RFC2_RELOAD_CB_ID : - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback = HAL_GFXTIM_RelativeTimer_RFC2RCallback; - break; - case HAL_GFXTIM_TE_CB_ID : - hgfxtim->HAL_GFXTIM_TECallback = HAL_GFXTIM_TECallback; - break; - case HAL_GFXTIM_EVENT1_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback = HAL_GFXTIM_EventGenerator_EV1Callback; - break; - case HAL_GFXTIM_EVENT2_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback = HAL_GFXTIM_EventGenerator_EV2Callback; - break; - case HAL_GFXTIM_EVENT3_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback = HAL_GFXTIM_EventGenerator_EV3Callback; - break; - case HAL_GFXTIM_EVENT4_CB_ID : - hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback = HAL_GFXTIM_EventGenerator_EV4Callback; - break; - case HAL_GFXTIM_WDG_ALARM_CB_ID : - hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback = HAL_GFXTIM_WatchdogTimer_AlarmCallback; - break; - case HAL_GFXTIM_WDG_PREALARM_CB_ID : - hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback = HAL_GFXTIM_WatchdogTimer_PreAlarmCallback; - break; - case HAL_GFXTIM_ERROR_CB_ID : - hgfxtim->ErrorCallback = HAL_GFXTIM_ErrorCallback; - break; - case HAL_GFXTIM_MSP_INIT_CB_ID : - hgfxtim->MspInitCallback = HAL_GFXTIM_MspInit; - break; - case HAL_GFXTIM_MSP_DEINIT_CB_ID : - hgfxtim->MspDeInitCallback = HAL_GFXTIM_MspDeInit; - break; - default : - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (hgfxtim->State == HAL_GFXTIM_STATE_RESET) - { - switch (CallbackID) - { - case HAL_GFXTIM_MSP_INIT_CB_ID : - hgfxtim->MspInitCallback = HAL_GFXTIM_MspInit; - break; - case HAL_GFXTIM_MSP_DEINIT_CB_ID : - hgfxtim->MspDeInitCallback = HAL_GFXTIM_MspDeInit; - break; - default : - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - /* Update error code and status */ - hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - } - - return status; -} -#endif /* #if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) */ - -/** - * @} - */ - -/** @defgroup GFXTIM_Exported_Functions_Group2 Clock Generator functions - * @brief Clock Generator functions - * -@verbatim - ============================================================================== - ##### Clock Generator functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Configure the clock generator. - (+) Force reload of FCC and LCC. - -@endverbatim - * @{ - */ - -/** - * @brief This function configures the clock generator. - * @param hgfxtim GFXTIM handle. - * @param pClockGeneratorConfig Clock Generator configuration parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_ClockGenerator_Config(GFXTIM_HandleTypeDef *hgfxtim, - const GFXTIM_ClockGeneratorConfigTypeDef *pClockGeneratorConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - if ((hgfxtim == NULL) || (pClockGeneratorConfig == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_LCC_HW_RELOAD_SRC(pClockGeneratorConfig->LCCHwReloadSrc)); - assert_param(IS_GFXTIM_LCC_RELOAD_VALUE(pClockGeneratorConfig->LCCReloadValue)); - assert_param(IS_GFXTIM_LCC_CLK_SRC(pClockGeneratorConfig->LCCClockSrc)); - assert_param(IS_GFXTIM_LINE_CLK_SRC(pClockGeneratorConfig->LineClockSrc)); - assert_param(IS_GFXTIM_FCC_HW_RELOAD_SRC(pClockGeneratorConfig->FCCHwReloadSrc)); - assert_param(IS_GFXTIM_FCC_RELOAD_VALUE(pClockGeneratorConfig->FCCReloadValue)); - assert_param(IS_GFXTIM_FCC_CLK_SRC(pClockGeneratorConfig->FCCClockSrc)); - assert_param(IS_GFXTIM_FRAME_CLK_SRC(pClockGeneratorConfig->FrameClockSrc)); - assert_param(IS_GFXTIM_LINE_CLK_CALIB(pClockGeneratorConfig->LineClockCalib)); - assert_param(IS_GFXTIM_FRAME_CLK_CALIB(pClockGeneratorConfig->FrameClockCalib)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Disable FCC and LCC */ - CLEAR_BIT(hgfxtim->Instance->CGCR, - GFXTIM_CGCR_LCCCS | GFXTIM_CGCR_FCCCS); - - /* Set Line Clock Counter (LCC) reload value (22 bits) */ - MODIFY_REG(hgfxtim->Instance->LCCRR, GFXTIM_LCCRR_RELOAD, - (pClockGeneratorConfig->LCCReloadValue << GFXTIM_LCCRR_RELOAD_Pos)); - - /* Set Frame Clock Counter (FCC) reload value (12 bits) */ - MODIFY_REG(hgfxtim->Instance->FCCRR, GFXTIM_FCCRR_RELOAD, - (pClockGeneratorConfig->FCCReloadValue << GFXTIM_FCCRR_RELOAD_Pos)); - - /* Set line and frame config */ - MODIFY_REG(hgfxtim->Instance->CGCR, - GFXTIM_CGCR_LCCHRS | GFXTIM_CGCR_LCCCS | GFXTIM_CGCR_LCS | - GFXTIM_CGCR_FCCHRS | GFXTIM_CGCR_FCCCS | GFXTIM_CGCR_FCS, - pClockGeneratorConfig->LCCHwReloadSrc | pClockGeneratorConfig->LCCClockSrc | - pClockGeneratorConfig->LineClockSrc | pClockGeneratorConfig->FCCHwReloadSrc | - pClockGeneratorConfig->FCCClockSrc | pClockGeneratorConfig->FrameClockSrc); - - /* Set debug output config for Line and frame clocks */ - MODIFY_REG(hgfxtim->Instance->CR, - GFXTIM_CR_LCCOE | GFXTIM_CR_FCCOE, - pClockGeneratorConfig->LineClockCalib | pClockGeneratorConfig->FrameClockCalib); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function force clock generator counter(s) reload - * @param hgfxtim GFXTIM handle. - * @param ClockGeneratorCounter Clock Generator counter - * This parameter can be a value of @ref GFXTIM_ClockGeneratorCounter. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_ClockGenerator_Reload(GFXTIM_HandleTypeDef *hgfxtim, uint32_t ClockGeneratorCounter) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_CLOCK_GENERATOR_COUNTER(ClockGeneratorCounter)); - - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - SET_BIT(hgfxtim->Instance->CGCR, ClockGeneratorCounter); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - - -/** - * @brief GFXTIM Tearing effect callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_TECallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_TECallback could be implemented in the user file */ -} - -/** - * @} - */ - -/** @defgroup GFXTIM_Exported_Functions_Group3 Absolute Timer functions - * @brief Absolute Timer functions - * -@verbatim - ============================================================================== - ##### Absolute Timers functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Configure the absolute timer. - (+) Start the absolute timer. - (+) Stop the absolute timer. - (+) Reset the absolute timer counters. - (+) Get the absolute time value. - (+) Set the absolute frame compare value. - (+) Set the absolute line compare value. -@endverbatim - * @{ - */ - -/** - * @brief This function configures an absolute Timer. - * @param hgfxtim GFXTIM handle. - * @param pAbsoluteTimerConfig pointer to a GFXTIM_AbsoluteTimerConfigTypeDef structure that - * contains absoluite timer comparators and counters values. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Config(GFXTIM_HandleTypeDef *hgfxtim, - const GFXTIM_AbsoluteTimerConfigTypeDef *pAbsoluteTimerConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - if ((hgfxtim == NULL) || (pAbsoluteTimerConfig == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_ABSOLUTE_FRAME_VALUE(pAbsoluteTimerConfig->FrameCompare1Value)); - assert_param(IS_GFXTIM_ABSOLUTE_FRAME_VALUE(pAbsoluteTimerConfig->FrameCounterValue)); - assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->FrameOverflowInterrupt)); - assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->FrameCompare1Interrupt)); - assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(pAbsoluteTimerConfig->LineCompare1Value)); - assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(pAbsoluteTimerConfig->LineCompare2Value)); - assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(pAbsoluteTimerConfig->LineCounterValue)); - assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->LineOverflowInterrupt)); - assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->LineCompare1Interrupt)); - assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->LineCompare2Interrupt)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - - /* Set AFC compare 1 value */ - MODIFY_REG(hgfxtim->Instance->AFCC1R, GFXTIM_AFCC1R_FRAME, - (pAbsoluteTimerConfig->FrameCompare1Value << GFXTIM_AFCC1R_FRAME_Pos)); - - /* Set AFC counter value */ - MODIFY_REG(hgfxtim->Instance->AFCR, GFXTIM_AFCR_FRAME, - (pAbsoluteTimerConfig->FrameCounterValue << GFXTIM_AFCR_FRAME_Pos)); - - /* Set ALC compare 1 value */ - MODIFY_REG(hgfxtim->Instance->ALCC1R, GFXTIM_ALCC1R_LINE, - (pAbsoluteTimerConfig->LineCompare1Value << GFXTIM_ALCC1R_LINE_Pos)); - - /* Set ALC compare 2 value */ - MODIFY_REG(hgfxtim->Instance->ALCC2R, GFXTIM_ALCC2R_LINE, - (pAbsoluteTimerConfig->LineCompare2Value << GFXTIM_ALCC2R_LINE_Pos)); - - /* Set ALC counter value */ - MODIFY_REG(hgfxtim->Instance->ALCR, GFXTIM_ALCR_LINE, - (pAbsoluteTimerConfig->LineCounterValue << GFXTIM_ALCR_LINE_Pos)); - - /* Set ALC compare 1, compare 2, overflow interrupts, AFC compare 1 and overflow interrupts */ - MODIFY_REG(hgfxtim->Instance->IER, - GFXTIM_IER_ALCC1IE | GFXTIM_IER_ALCC2IE | GFXTIM_IER_ALCOIE | GFXTIM_IER_AFCC1IE | GFXTIM_IER_AFCOIE, - (pAbsoluteTimerConfig->FrameOverflowInterrupt << GFXTIM_IER_AFCOIE_Pos) | - (pAbsoluteTimerConfig->FrameCompare1Interrupt << GFXTIM_IER_AFCC1IE_Pos) | - (pAbsoluteTimerConfig->LineOverflowInterrupt << GFXTIM_IER_ALCOIE_Pos) | - (pAbsoluteTimerConfig->LineCompare1Interrupt << GFXTIM_IER_ALCC1IE_Pos) | - (pAbsoluteTimerConfig->LineCompare2Interrupt << GFXTIM_IER_ALCC2IE_Pos)); - } - else - { - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function starts absolute timer. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Start(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Enable absolute Timer */ - SET_BIT(hgfxtim->Instance->TCR, (GFXTIM_TCR_AFCEN | GFXTIM_TCR_ALCEN)); - } - else - { - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function stops absolute timer counter(s). - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Stop(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Disable absolute counter(s) */ - SET_BIT(hgfxtim->Instance->TDR, (GFXTIM_TDR_ALCDIS | GFXTIM_TDR_AFCDIS)); - } - else - { - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function resets absolute timer counters. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Reset(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Disable absolute counter(s) */ - SET_BIT(hgfxtim->Instance->TCR, (GFXTIM_TCR_FAFCR | GFXTIM_TCR_FALCR)); - } - else - { - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function gets absolute timer value. - * @param hgfxtim GFXTIM handle. - * @param AbsoluteTime absolute time - * This parameter can be a value of @ref GFXTIM_AbsoluteTime. - * @param pValue Absolute time value - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_GetCounter(const GFXTIM_HandleTypeDef *hgfxtim, uint32_t AbsoluteTime, - uint32_t *pValue) -{ - HAL_StatusTypeDef status = HAL_OK; - - if ((hgfxtim == NULL) || (pValue == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_ABSOLUTE_TIME(AbsoluteTime)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - switch (AbsoluteTime) - { - case GFXTIM_ABSOLUTE_GLOBAL_TIME: - *pValue = READ_REG(hgfxtim->Instance->ATR); - break; - case GFXTIM_ABSOLUTE_FRAME_TIME: - *pValue = READ_REG(hgfxtim->Instance->AFCR); - break; - default: - /* GFXTIM_ABSOLUTE_LINE_TIME */ - *pValue = READ_REG(hgfxtim->Instance->ALCR); - break; - } - } - else - { - status = HAL_ERROR; - } - } - return status; -} - -/** - * @brief This function sets absolute frame compare value. - * @param hgfxtim GFXTIM handle. - * @param Value Absolute frame compare 1 value - * This parameter can be a number between Min_Data = 0x00000 and Max_Data = 0xFFFFF - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_SetFrameCompare(GFXTIM_HandleTypeDef *hgfxtim, uint32_t Value) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Set absolute frame counter compare 1 register value */ - MODIFY_REG(hgfxtim->Instance->AFCC1R, GFXTIM_AFCC1R_FRAME, - (Value << GFXTIM_AFCC1R_FRAME_Pos)); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function sets line compare value. - * @param hgfxtim GFXTIM handle. - * @param AbsoluteLineComparator Absolute line compare value - * This parameter can be a value of @ref GFXTIM_AbsoluteLineComparator. - * @param Value Absolute line compare value - * This parameter can be a number between Min_Data = 0x000 and Max_Data = 0xFFF - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_SetLineCompare(GFXTIM_HandleTypeDef *hgfxtim, - uint32_t AbsoluteLineComparator, uint32_t Value) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_ABSOLUTE_LINE_COMPARATOR(AbsoluteLineComparator)); - assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(Value)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - switch (AbsoluteLineComparator) - { - case GFXTIM_ABSOLUTE_LINE_COMPARE1: - WRITE_REG(hgfxtim->Instance->ALCC1R, Value); - break; - default: - /* GFXTIM_ABSOLUTE_LINE_COMPARE2 */ - WRITE_REG(hgfxtim->Instance->ALCC2R, Value); - break; - } - } - else - { - status = HAL_ERROR; - } - } - return status; -} - -/** - * @brief GFXTIM Absolute frame counter overflow callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_AbsoluteTimer_AFCOFCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_AbsoluteTimer_AFCOFCallback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Absolute frame counter compare 1 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_AbsoluteTimer_AFCC1Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_AbsoluteTimer_AFCC1Callback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Absolute line counter compare 1 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_AbsoluteTimer_ALCC1Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_AbsoluteTimer_ALCC1Callback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Absolute line counter compare 2 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_AbsoluteTimer_ALCC2Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_AbsoluteTimer_ALCC2Callback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Absolute line counter overflow callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_AbsoluteTimer_ALCOFCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_AbsoluteTimer_ALCOFCallback could be implemented in the user file */ -} - -/** - * @} - */ - -/** @defgroup GFXTIM_Exported_Functions_Group4 Relative Timer functions - * @brief Clock Generator functions - * -@verbatim - ============================================================================== - ##### Relative Timer functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Configure a relative timer. - (+) Start a relative timer counter. - (+) Stop a relative timer counter. - (+) Force a relative timer counter reload. - (+) Set a relative timer reload value. - (+) Get a relative timer counter value. - -@endverbatim - * @{ - */ - -/** - * @brief This function configures a Relative Timer. - * @param hgfxtim GFXTIM handle. - * @param pRelativeTimerConfig pointer to a GFXTIM_RelativeTimerConfigTypeDef structure that - * contains relative timer comparators and counters values. - * @param RelativeTimer Relative Timer identifier - * This parameter can be a value of @ref GFXTIM_RelativeTimer. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_Config(GFXTIM_HandleTypeDef *hgfxtim, - const GFXTIM_RelativeTimerConfigTypeDef *pRelativeTimerConfig, - uint32_t RelativeTimer) -{ - HAL_StatusTypeDef status = HAL_OK; - - if ((hgfxtim == NULL) || (pRelativeTimerConfig == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_RELATIVE_FRAME_VALUE(pRelativeTimerConfig->AutoReloadValue)); - assert_param(IS_GFXTIM_RELATIVE_FRAME_VALUE(pRelativeTimerConfig->CounterMode)); - assert_param(IS_GFXTIM_INTERRUPT(pRelativeTimerConfig->ReloadInterrupt)); - assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) - { - /* Set RFC1 auto reload */ - MODIFY_REG(hgfxtim->Instance->RFC1RR, GFXTIM_RFC1RR_FRAME, - pRelativeTimerConfig->AutoReloadValue << GFXTIM_RFC1RR_FRAME_Pos); - - /* Set relative timer mode */ - MODIFY_REG(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC1CM, - (pRelativeTimerConfig->CounterMode << GFXTIM_TCR_RFC1CM_Pos)); - - /* Set relative timer 1 interrupt */ - MODIFY_REG(hgfxtim->Instance->IER, GFXTIM_IER_RFC1RIE_Msk, - (pRelativeTimerConfig->ReloadInterrupt << GFXTIM_IER_RFC1RIE_Pos)); - } - else - { - /* Set RFC2 auto reload */ - MODIFY_REG(hgfxtim->Instance->RFC2RR, GFXTIM_RFC2RR_FRAME, - pRelativeTimerConfig->AutoReloadValue << GFXTIM_RFC2RR_FRAME_Pos); - - /* Set relative timer mode */ - MODIFY_REG(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC2CM, - (pRelativeTimerConfig->CounterMode << GFXTIM_TCR_RFC2CM_Pos)); - - /* Set relative timer 2 interrupt */ - MODIFY_REG(hgfxtim->Instance->IER, GFXTIM_IER_RFC2RIE_Msk, - (pRelativeTimerConfig->ReloadInterrupt << GFXTIM_IER_RFC2RIE_Pos)); - } - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function starts a relative Timer. - * @param hgfxtim GFXTIM handle. - * @param RelativeTimer Relative timer counter to Enable - * This parameter can be a value of @ref GFXTIM_RelativeTimer. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_Start(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) - { - /* Enable relative timer 1 */ - SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC1EN); - } - else - { - /* Enable relative timer 2 */ - SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC2EN); - } - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function stops a relative Timer counter. - * @param hgfxtim GFXTIM handle. - * @param RelativeTimer Relative timer counter to Disable - * This parameter can be a value of @ref GFXTIM_RelativeTimer. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_Stop(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) - { - /* Disable relative timer 1 */ - SET_BIT(hgfxtim->Instance->TDR, GFXTIM_TDR_RFC1DIS); - } - else - { - /* Disable relative timer 2 */ - SET_BIT(hgfxtim->Instance->TDR, GFXTIM_TDR_RFC2DIS); - } - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - - -/** - * @brief This function force a relative Timer reload. - * @param hgfxtim GFXTIM handle. - * @param RelativeTimer Relative timer to Foce Reload - * This parameter can be a value of @ref GFXTIM_RelativeTimer. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_ForceReload(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) - { - /* Force relative timer 1 reload */ - SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_FRFC1R); - } - else - { - /* Force relative timer 2 reload*/ - SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_FRFC2R); - } - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - - -/** - * @brief This function sets Relative frame timer reload value. - * @param hgfxtim GFXTIM handle. - * @param RelativeTimer specifies the Auto-reload register to be modified. - * This parameter can be a value of @ref GFXTIM_RelativeTimer. - * @param Value Reload value - * This parameter can be a number between Min_Data = 0x000 and Max_Data = 0xFFF - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_SetReload(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer, - uint32_t Value) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_RELATIVE_FRAME_VALUE(Value)); - assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) - { - /* Set RFC1 auto reload */ - WRITE_REG(hgfxtim->Instance->RFC1RR, Value); - } - else - { - /* Set RFC2 auto reload */ - WRITE_REG(hgfxtim->Instance->RFC2RR, Value); - } - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function sets Relative frame timer compare value. - * @param hgfxtim GFXTIM handle. - * @param RelativeTimer Relative frame counter reload - * This parameter can be a value of @ref GFXTIM_RelativeTimer. - * @param pValue pointer to a relative frame counter value - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_GetCounter(const GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer, - uint32_t *pValue) -{ - HAL_StatusTypeDef status = HAL_OK; - - if ((hgfxtim == NULL) || (pValue == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) - { - /* Set RFC1 auto reload */ - *pValue = READ_REG(hgfxtim->Instance->RFC1R); - } - else - { - /* Set RFC2 auto reload */ - *pValue = READ_REG(hgfxtim->Instance->RFC2R); - } - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - - - - -/** - * @brief GFXTIM Relative frame counter 1 reload callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_RelativeTimer_RFC1RCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_RelativeTimer_RFC1RCallback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Relative frame counter 2 reload callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_RelativeTimer_RFC2RCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_RelativeTimer_RFC2RCallback could be implemented in the user file */ -} - -/** - * @} - */ - -/** @defgroup GFXTIM_Exported_Functions_Group5 Event Generator functions - * @brief Event Generator functions - * -@verbatim - ============================================================================== - ##### Event Generator functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Configure an Event Generator. - (+) Enable an Event Generator. - (+) Disable an Event Generator. -@endverbatim - * @{ - */ - -/** - * @brief This function configures an Event Generator. - * @param hgfxtim GFXTIM handle. - * @param EventGenerator Event Generator - * This parameter can be a value of @ref GFXTIM_EventGenerator. - * @param pEventGeneratorConfig pointer to a GFXTIM_EventGeneratorConfigTypeDef structure that - * contains Event Generator configuration parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_EventGenerator_Config(GFXTIM_HandleTypeDef *hgfxtim, uint32_t EventGenerator, - const GFXTIM_EventGeneratorConfigTypeDef *pEventGeneratorConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t shift; - - if ((hgfxtim == NULL) || (pEventGeneratorConfig == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_EVENT_GENERATOR(EventGenerator)); - assert_param(IS_GFXTIM_EVENT_LINE(pEventGeneratorConfig->LineEvent)); - assert_param(IS_GFXTIM_EVENT_FRAME(pEventGeneratorConfig->FrameEvent)); - assert_param(IS_GFXTIM_INTERRUPT(pEventGeneratorConfig->EventInterrupt)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Select frame and line events */ - shift = (EventGenerator) * 8U; - MODIFY_REG(hgfxtim->Instance->EVSR, \ - ((GFXTIM_EVSR_LES1 | GFXTIM_EVSR_FES1) << shift), - ((pEventGeneratorConfig->LineEvent | pEventGeneratorConfig->FrameEvent) << shift)); - - /* Event interrupt */ - MODIFY_REG(hgfxtim->Instance->IER, \ - (GFXTIM_IER_EV1IE << (EventGenerator)), \ - (pEventGeneratorConfig->EventInterrupt << (EventGenerator + GFXTIM_IER_EV1IE_Pos))); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function enables an Event Generator. - * @param hgfxtim GFXTIM handle. - * @param EventGenerator Event Generator - * This parameter can be a value of @ref GFXTIM_EventGenerator. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_EventGenerator_Enable(GFXTIM_HandleTypeDef *hgfxtim, uint32_t EventGenerator) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_EVENT_GENERATOR(EventGenerator)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Enable event generator */ - SET_BIT(hgfxtim->Instance->EVCR, GFXTIM_EVCR_EV1EN << EventGenerator); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function disables an Event Generator. - * @param hgfxtim GFXTIM handle. - * @param EventGenerator Event Generator - * This parameter can be a value of @ref GFXTIM_EventGenerator. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_EventGenerator_Disable(GFXTIM_HandleTypeDef *hgfxtim, uint32_t EventGenerator) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_EVENT_GENERATOR(EventGenerator)); - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Disable event generator */ - CLEAR_BIT(hgfxtim->Instance->EVCR, GFXTIM_EVCR_EV1EN << EventGenerator); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - - - -/** - * @brief GFXTIM Combined events 1 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_EventGenerator_EV1Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_EventGenerator_EV1Callback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Combined events 2 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_EventGenerator_EV2Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_EventGenerator_EV2Callback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Combined events 3 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_EventGenerator_EV3Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_EventGenerator_EV3Callback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Combined events 4 callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_EventGenerator_EV4Callback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_EventGenerator_EV4Callback could be implemented in the user file */ -} - -/** - * @} - */ - -/** @defgroup GFXTIM_Exported_Functions_Group6 Watchdog functions - * @brief Event Generator functions - * -@verbatim - ============================================================================== - ##### Watchdog functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Configure the Watchdog. - (+) Enable the Watchdog - (+) Disable the Watchdog. - (+) Refresh the Watchdog. -@endverbatim - * @{ - */ - -/** - * @brief This function configures the Watchdog. - * @param hgfxtim GFXTIM handle. - * @param pWatchdogConfig Watchdog configuration parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Config(GFXTIM_HandleTypeDef *hgfxtim, - const GFXTIM_WatchdogConfigTypeDef *pWatchdogConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - if ((hgfxtim == NULL) || (pWatchdogConfig == NULL)) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - assert_param(IS_GFXTIM_WATCHDOG_CLOCK_SRC(pWatchdogConfig->ClockSrc)); - assert_param(IS_GFXTIM_WATCHDOG_HW_RELOAD_CONFIG(pWatchdogConfig->HwReloadConfig)); - - assert_param(IS_GFXTIM_WATCHDOG_VALUE(pWatchdogConfig->AutoReloadValue)); - assert_param(IS_GFXTIM_WATCHDOG_VALUE(pWatchdogConfig->PreAlarmValue)); - - assert_param(IS_GFXTIM_INTERRUPT(pWatchdogConfig->AlarmInterrupt)); - assert_param(IS_GFXTIM_INTERRUPT(pWatchdogConfig->PreAlarmInterrupt)); - - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Set watchdog auto reload value */ - MODIFY_REG(hgfxtim->Instance->WDGRR, GFXTIM_WDGRR_RELOAD, - (pWatchdogConfig->AutoReloadValue << GFXTIM_WDGRR_RELOAD_Pos)); - - /* Set watchdog pre alarm value */ - MODIFY_REG(hgfxtim->Instance->WDGPAR, GFXTIM_WDGPAR_PREALARM, - pWatchdogConfig->PreAlarmValue << GFXTIM_WDGPAR_PREALARM_Pos); - - /* Set watchdog clock source and hardware reload */ - MODIFY_REG(hgfxtim->Instance->WDGTCR, (GFXTIM_WDGTCR_WDGCS | GFXTIM_WDGTCR_WDGHRC), - (pWatchdogConfig->ClockSrc | pWatchdogConfig->HwReloadConfig)); - - /* Set watchdog interrupts */ - MODIFY_REG(hgfxtim->Instance->IER, \ - (GFXTIM_IER_WDGAIE | GFXTIM_IER_WDGPIE), \ - ((pWatchdogConfig->AlarmInterrupt << GFXTIM_IER_WDGAIE_Pos) | \ - (pWatchdogConfig->PreAlarmInterrupt << GFXTIM_IER_WDGPIE_Pos))); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function Enable the Watchdog Counter. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Enable(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Set watchdog enable bit */ - SET_BIT(hgfxtim->Instance->WDGTCR, GFXTIM_WDGTCR_WDGEN); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function Disable the Watchdog Counter. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Disable(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Set watchdog disable bit */ - SET_BIT(hgfxtim->Instance->WDGTCR, GFXTIM_WDGTCR_WDGDIS); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief This function refresh the Watchdog counter. - * @param hgfxtim GFXTIM handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Refresh(GFXTIM_HandleTypeDef *hgfxtim) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hgfxtim == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); - - - if (hgfxtim->State == HAL_GFXTIM_STATE_READY) - { - /* Set watchdog SW relaod */ - SET_BIT(hgfxtim->Instance->WDGTCR, GFXTIM_WDGTCR_FWDGR); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief GFXTIM Watchdog alarm callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_WatchdogTimer_AlarmCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_WatchdogTimer_AlarmCallback could be implemented in the user file */ -} - -/** - * @brief GFXTIM Watchdog pre alarm callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_WatchdogTimer_PreAlarmCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_WatchdogTimer_PreAlarmCallback could be implemented in the user file */ -} - -/** - * @} - */ - -/** @defgroup GFXTIM_Exported_Functions_Group7 Generic functions - * @brief Generic functions - * -@verbatim - ============================================================================== - ##### Generic functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Handle GFXTIM interrupt. - (+) Inform user that error occurs. - (+) Get the current GFXTIM instance state - (+) Get the current GFXTIM instance error code. -@endverbatim - * @{ - */ - -/** - * @brief This function handles the GFXTIM interrupts. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -void HAL_GFXTIM_IRQHandler(GFXTIM_HandleTypeDef *hgfxtim) -{ - uint32_t tmp_reg1; - uint32_t tmp_reg2; - uint32_t interrupts; - - /* Read all pending interrupts */ - tmp_reg1 = READ_REG(hgfxtim->Instance->ISR); - tmp_reg2 = READ_REG(hgfxtim->Instance->IER); - interrupts = tmp_reg1 & tmp_reg2; - - if ((interrupts & GFXTIM_ISR_AFCC1F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback(hgfxtim); -#else - HAL_GFXTIM_AbsoluteTimer_AFCC1Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_AFCOF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback(hgfxtim); -#else - HAL_GFXTIM_AbsoluteTimer_AFCOFCallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_ALCC1F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback(hgfxtim); -#else - HAL_GFXTIM_AbsoluteTimer_ALCC1Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_ALCC2F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback(hgfxtim); -#else - HAL_GFXTIM_AbsoluteTimer_ALCC2Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_ALCOF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback(hgfxtim); -#else - HAL_GFXTIM_AbsoluteTimer_ALCOFCallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_TEF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_TECallback(hgfxtim); -#else - HAL_GFXTIM_TECallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_RFC1RF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback(hgfxtim); -#else - HAL_GFXTIM_RelativeTimer_RFC1RCallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_RFC2RF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback(hgfxtim); -#else - HAL_GFXTIM_RelativeTimer_RFC2RCallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_EV1F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback(hgfxtim); -#else - HAL_GFXTIM_EventGenerator_EV1Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_EV2F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback(hgfxtim); -#else - HAL_GFXTIM_EventGenerator_EV2Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_EV3F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback(hgfxtim); -#else - HAL_GFXTIM_EventGenerator_EV3Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_EV4F) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback(hgfxtim); -#else - HAL_GFXTIM_EventGenerator_EV4Callback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_WDGAF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback(hgfxtim); -#else - HAL_GFXTIM_WatchdogTimer_AlarmCallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - - if ((interrupts & GFXTIM_ISR_WDGPF) != 0U) - { -#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) - hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback(hgfxtim); -#else - HAL_GFXTIM_WatchdogTimer_PreAlarmCallback(hgfxtim); -#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ - } - /* Clear all pending interrupts */ - WRITE_REG(hgfxtim->Instance->ICR, interrupts); -} - -/** - * @brief GFXTIM error callback. - * @param hgfxtim GFXTIM handle. - * @retval None. - */ -__weak void HAL_GFXTIM_ErrorCallback(GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgfxtim); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_GFXTIM_ErrorCallback could be implemented in the user file. */ -} - -/** - * @brief This function get the current GFXTIM state. - * @param hgfxtim GFXTIM handle. - * @retval GFXTIM state. - */ -HAL_GFXTIM_StateTypeDef HAL_GFXTIM_GetState(const GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Return GFXTIM state */ - return hgfxtim->State; -} - -/** - * @brief This function get the current GFXTIM error. - * @param hgfxtim GFXTIM handle. - * @retval GFXTIM error code. - */ -uint32_t HAL_GFXTIM_GetError(const GFXTIM_HandleTypeDef *hgfxtim) -{ - /* Return GFXTIM error code */ - return hgfxtim->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* GFXTIM */ -#endif /* HAL_GFXTIM_MODULE_ENABLED */ -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_gfxtim.c + * @author MCD Application Team + * @brief This file provides firmware functions to manage the following + * functionalities of the Multi-function Digital Filter (GFXTIM) + * peripheral: + * + Initialization and de-initialization + * + Integrated frame and line clock generation + * + One absolute frame counter with one compare channel + * + Two auto reload relative frame counter + * + One line timer with two compare channel + * + External Tearing Effect line management & synchronization + * + Four programmable event generators with external trigger generation + * + One watchdog counter + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + *** Initialization and de-initialization *** + ============================================ + [..] + (#) User has first to initialize GFXTIM. + (#) As prerequisite, fill in the HAL_GFXTIM_MspInit() : + (++) Enable GFXTIM with __HAL_RCC_GFXTIM_CLK_ENABLE + (++) Enable the clocks for the used GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). + (++) Configure these pins in alternate mode using HAL_GPIO_Init(). + (++) If interrupt mode is used, enable and configure GFXTIM + interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). + + [..] + (#) User can de-initialize GFXTIM with HAL_GFXTIM_DeInit() function. + + *** generic functions *** + ========================= + [..] + (#) HAL_GFXTIM_IRQHandler will be called when GFXTIM interrupt occurs. + (#) HAL_GFXTIM_ErrorCallback will be called when GFXTIM or ADF error occurs. + (#) Use HAL_GFXTIM_GetState() to get the current GFXTIM or ADF instance state. + (#) Use HAL_GFXTIM_GetErrorCode() to get the current GFXTIM or ADF instance error code. + + + +#if defined(GENERATOR_CALLBACKS_REGISTERING_AVAILABLE) + *** Callback registration *** + ============================================= + + The compilation define USE_HAL_GFXTIM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function @ref HAL_GFXTIM_RegisterCallback() to register an interrupt callback. + + Function @ref HAL_GFXTIM_RegisterCallback() registers following callbacks: + (+) HAL_GFXTIM_AbsoluteTimer_AFCC1Callback + (+) HAL_GFXTIM_AbsoluteTimer_AFCOFCallback + (+) HAL_GFXTIM_AbsoluteTimer_ALCC1Callback + (+) HAL_GFXTIM_AbsoluteTimer_ALCC2Callback + (+) HAL_GFXTIM_AbsoluteTimer_ALCOFCallback + (+) HAL_GFXTIM_RelativeTimer_RFC1RCallback + (+) HAL_GFXTIM_RelativeTimer_RFC2RCallback + (+) HAL_GFXTIM_TECallback + (+) HAL_GFXTIM_EventGenerator_EV1Callback + (+) HAL_GFXTIM_EventGenerator_EV2Callback + (+) HAL_GFXTIM_EventGenerator_EV3Callback + (+) HAL_GFXTIM_EventGenerator_EV4Callback + (+) HAL_GFXTIM_WatchdogTimer_AlarmCallback + (+) HAL_GFXTIM_WatchdogTimer_PreAlarmCallback + (+) MspInitCallback + (+) MspDeInitCallback + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function @ref HAL_GFXTIM_UnRegisterCallback() to reset a callback to the default + weak function. + @ref HAL_GFXTIM_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function resets following callbacks: + (+) HAL_GFXTIM_AbsoluteTimer_AFCC1Callback + (+) HAL_GFXTIM_AbsoluteTimer_AFCOFCallback + (+) HAL_GFXTIM_AbsoluteTimer_ALCC1Callback + (+) HAL_GFXTIM_AbsoluteTimer_ALCC2Callback + (+) HAL_GFXTIM_AbsoluteTimer_ALCOFCallback + (+) HAL_GFXTIM_RelativeTimer_RFC1RCallback + (+) HAL_GFXTIM_RelativeTimer_RFC2RCallback + (+) HAL_GFXTIM_TECallback + (+) HAL_GFXTIM_EventGenerator_EV1Callback + (+) HAL_GFXTIM_EventGenerator_EV2Callback + (+) HAL_GFXTIM_EventGenerator_EV3Callback + (+) HAL_GFXTIM_EventGenerator_EV4Callback + (+) HAL_GFXTIM_WatchdogTimer_AlarmCallback + (+) HAL_GFXTIM_WatchdogTimer_PreAlarmCallback + (+) MspInitCallback + (+) MspDeInitCallback + + By default, after the HAL_GFXTIM_Init() and when the state is HAL_GFXTIM_STATE_RESET, + all callbacks are set to the corresponding weak functions: + examples @ref HAL_GFXTIM_ErrorCallback(), @ref HAL_GFXTIM_CalculateCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the HAL_GFXTIM_Init()/ @ref HAL_GFXTIM_DeInit() only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the HAL_GFXTIM_Init()/ @ref HAL_GFXTIM_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in HAL_GFXTIM_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_GFXTIM_STATE_READY or HAL_GFXTIM_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using @ref HAL_GFXTIM_RegisterCallback() before calling @ref HAL_GFXTIM_DeInit() + or HAL_GFXTIM_Init() function. + + When The compilation define USE_HAL_GFXTIM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. +#endif + + @endverbatim + */ +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ +#ifdef HAL_GFXTIM_MODULE_ENABLED +#if defined(GFXTIM) +/** @defgroup GFXTIM GFXTIM + * @brief GFXTIM HAL module driver + * @{ + */ + +/* Exported functions ---------------------------------------------------------*/ +/** @defgroup GFXTIM_Exported_Functions GFXTIM Exported Functions + * @{ + */ + +/** @defgroup GFXTIM_Exported_Functions_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 GFXTIM instance. + (+) De-initialize the GFXTIM instance. + (+) Register and unregister callbacks. +@endverbatim + * @{ + */ + +/** + * @brief Initialize the GFXTIM instance according to the specified parameters + * in the GFXTIM_InitTypeDef structure and initialize the associated handle. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_Init(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + if (hgfxtim != NULL) + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_SYNC_SRC(hgfxtim->Init.SynchroSrc)); + assert_param(IS_GFXTIM_TE_SRC(hgfxtim->Init.TearingEffectSrc)); + assert_param(IS_GFXTIM_TE_POLARITY(hgfxtim->Init.TearingEffectPolarity)); + assert_param(IS_GFXTIM_INTERRUPT(hgfxtim->Init.TearingEffectInterrupt)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_RESET) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) + /* Reset callback pointers to the weak predefined callbacks */ + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback = HAL_GFXTIM_AbsoluteTimer_AFCC1Callback; + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback = HAL_GFXTIM_AbsoluteTimer_AFCOFCallback; + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback = HAL_GFXTIM_AbsoluteTimer_ALCC1Callback; + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback = HAL_GFXTIM_AbsoluteTimer_ALCC2Callback; + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback = HAL_GFXTIM_AbsoluteTimer_ALCOFCallback; + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback = HAL_GFXTIM_RelativeTimer_RFC1RCallback; + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback = HAL_GFXTIM_RelativeTimer_RFC2RCallback; + hgfxtim->HAL_GFXTIM_TECallback = HAL_GFXTIM_TECallback; + hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback = HAL_GFXTIM_EventGenerator_EV1Callback; + hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback = HAL_GFXTIM_EventGenerator_EV2Callback; + hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback = HAL_GFXTIM_EventGenerator_EV3Callback; + hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback = HAL_GFXTIM_EventGenerator_EV4Callback; + hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback = HAL_GFXTIM_WatchdogTimer_AlarmCallback; + hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback = HAL_GFXTIM_WatchdogTimer_PreAlarmCallback; + hgfxtim->ErrorCallback = HAL_GFXTIM_ErrorCallback; + + /* Call GFXTIM MSP init function */ + if (hgfxtim->MspInitCallback == NULL) + { + hgfxtim->MspInitCallback = HAL_GFXTIM_MspInit; + } + hgfxtim->MspInitCallback(hgfxtim); +#else /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + /* Call GFXTIM MSP init function */ + HAL_GFXTIM_MspInit(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + + /* Set Synchronization signals sources (HSYNC and VSYNC), Tearing Effect source and polarity, */ + MODIFY_REG(hgfxtim->Instance->CR, \ + GFXTIM_CR_SYNCS | GFXTIM_CR_TES | GFXTIM_CR_TEPOL, + hgfxtim->Init.SynchroSrc | hgfxtim->Init.TearingEffectSrc | hgfxtim->Init.TearingEffectPolarity); + + /* Set tearing effect interrupt */ + MODIFY_REG(hgfxtim->Instance->IER, GFXTIM_IER_TEIE, + (hgfxtim->Init.TearingEffectInterrupt << GFXTIM_IER_TEIE_Pos)); + + /* Update error code and state */ + hgfxtim->ErrorCode = GFXTIM_ERROR_NONE; + hgfxtim->State = HAL_GFXTIM_STATE_READY; + status = HAL_OK; + } + } + + return status; +} + +/** + * @brief De-initialize the GFXTIM instance. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_DeInit(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + if (hgfxtim != NULL) + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Call GFXTIM MSP deinit function */ +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) + if (hgfxtim->MspDeInitCallback == NULL) + { + hgfxtim->MspDeInitCallback = HAL_GFXTIM_MspDeInit; + } + hgfxtim->MspDeInitCallback(hgfxtim); +#else /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + HAL_GFXTIM_MspDeInit(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + + /* Update state */ + hgfxtim->State = HAL_GFXTIM_STATE_RESET; + status = HAL_OK; + } + } + + return status; +} + +/** + * @brief Initialize the GFXTIM instance MSP. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_MspInit(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_MspInit could be implemented in the user file */ +} + +/** + * @brief De-initialize the GFXTIM instance MSP. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_MspDeInit(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_MspDeInit could be implemented in the user file */ +} + +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a user GFXTIM callback to be used instead of the weak predefined callback. + * @param hgfxtim GFXTIM handle. + * @param CallbackID ID of the callback to be registered. + * This parameter can be one of the following values: + * @arg @ref HAL_GFXTIM_AFC_COMPARE1_CB_ID Absolute frame counter compare 1 callback ID + * @arg @ref HAL_GFXTIM_AFC_OVERFLOW_CB_ID Absolute frame counter overflow callback ID + * @arg @ref HAL_GFXTIM_ALC_COMPARE1_CB_ID Absolute line counter compare 1 callback ID + * @arg @ref HAL_GFXTIM_ALC_COMPARE2_CB_ID Absolute line counter compare 2 callback ID + * @arg @ref HAL_GFXTIM_ALC_OVERFLOW_CB_ID Absolute line counter overflow callback ID + * @arg @ref HAL_GFXTIM_RFC1_RELOAD_CB_ID Relative frame counter 1 reload callback ID + * @arg @ref HAL_GFXTIM_RFC2_RELOAD_CB_ID Relative frame counter 2 reload callback ID + * @arg @ref HAL_GFXTIM_TE_CB_ID External tearing effect callback ID + * @arg @ref HAL_GFXTIM_EVENT1_CB_ID Event events 1 callback ID + * @arg @ref HAL_GFXTIM_EVENT2_CB_ID Event events 2 callback ID + * @arg @ref HAL_GFXTIM_EVENT3_CB_ID Event events 3 callback ID + * @arg @ref HAL_GFXTIM_EVENT4_CB_ID Event events 4 callback ID + * @arg @ref HAL_GFXTIM_WDG_ALARM_CB_ID Watchdog alarm callback ID + * @arg @ref HAL_GFXTIM_WDG_PREALARM_CB_ID Watchdog pre alarm callback ID + * @arg @ref HAL_GFXTIM_ERROR_CB_ID error callback ID + * @arg @ref HAL_GFXTIM_MSP_INIT_CB_ID MSP initialization user callback ID + * @arg @ref HAL_GFXTIM_MSP_DEINIT_CB_ID MSP de-initialization user callback ID + * @param pCallback pointer to the callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RegisterCallback(GFXTIM_HandleTypeDef *hgfxtim, + HAL_GFXTIM_CallbackIDTypeDef CallbackID, + pGFXTIM_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else if (pCallback == NULL) + { + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + else + { + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + switch (CallbackID) + { + case HAL_GFXTIM_AFC_COMPARE1_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback = pCallback; + break; + case HAL_GFXTIM_AFC_OVERFLOW_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback = pCallback; + break; + case HAL_GFXTIM_ALC_COMPARE1_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback = pCallback; + break; + case HAL_GFXTIM_ALC_COMPARE2_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback = pCallback; + break; + case HAL_GFXTIM_ALC_OVERFLOW_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback = pCallback; + break; + case HAL_GFXTIM_RFC1_RELOAD_CB_ID : + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback = pCallback; + break; + case HAL_GFXTIM_RFC2_RELOAD_CB_ID : + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback = pCallback; + break; + case HAL_GFXTIM_TE_CB_ID : + hgfxtim->HAL_GFXTIM_TECallback = pCallback; + break; + case HAL_GFXTIM_EVENT1_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback = pCallback; + break; + case HAL_GFXTIM_EVENT2_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback = pCallback; + break; + case HAL_GFXTIM_EVENT3_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback = pCallback; + break; + case HAL_GFXTIM_EVENT4_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback = pCallback; + break; + case HAL_GFXTIM_WDG_ALARM_CB_ID : + hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback = pCallback; + break; + case HAL_GFXTIM_WDG_PREALARM_CB_ID : + hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback = pCallback; + break; + case HAL_GFXTIM_ERROR_CB_ID : + hgfxtim->ErrorCallback = pCallback; + break; + case HAL_GFXTIM_MSP_INIT_CB_ID : + hgfxtim->MspInitCallback = pCallback; + break; + case HAL_GFXTIM_MSP_DEINIT_CB_ID : + hgfxtim->MspDeInitCallback = pCallback; + break; + default : + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (hgfxtim->State == HAL_GFXTIM_STATE_RESET) + { + switch (CallbackID) + { + case HAL_GFXTIM_MSP_INIT_CB_ID : + hgfxtim->MspInitCallback = pCallback; + break; + case HAL_GFXTIM_MSP_DEINIT_CB_ID : + hgfxtim->MspDeInitCallback = pCallback; + break; + default : + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Unregister a user GFXTIM callback. + * GFXTIM callback is redirected to the weak predefined callback. + * @param hgfxtim GFXTIM handle. + * @param CallbackID ID of the callback to be unregistered. + * This parameter can be one of the following values: + * @arg @ref HAL_GFXTIM_AFC_COMPARE1_CB_ID Absolute frame counter compare 1 callback ID + * @arg @ref HAL_GFXTIM_AFC_OVERFLOW_CB_ID Absolute frame counter overflow callback ID + * @arg @ref HAL_GFXTIM_ALC_COMPARE1_CB_ID Absolute line counter compare 1 callback ID + * @arg @ref HAL_GFXTIM_ALC_COMPARE2_CB_ID Absolute line counter compare 2 callback ID + * @arg @ref HAL_GFXTIM_ALC_OVERFLOW_CB_ID Absolute line counter overflow callback ID + * @arg @ref HAL_GFXTIM_RFC1_RELOAD_CB_ID Relative frame counter 1 reload callback ID + * @arg @ref HAL_GFXTIM_RFC2_RELOAD_CB_ID Relative frame counter 2 reload callback ID + * @arg @ref HAL_GFXTIM_TE_CB_ID External tearing effect callback ID + * @arg @ref HAL_GFXTIM_EVENT1_CB_ID Event events 1 callback ID + * @arg @ref HAL_GFXTIM_EVENT2_CB_ID Event events 2 callback ID + * @arg @ref HAL_GFXTIM_EVENT3_CB_ID Event events 3 callback ID + * @arg @ref HAL_GFXTIM_EVENT4_CB_ID Event events 4 callback ID + * @arg @ref HAL_GFXTIM_WDG_ALARM_CB_ID Watchdog alarm callback ID + * @arg @ref HAL_GFXTIM_WDG_PREALARM_CB_ID Watchdog pre alarm callback ID + * @arg @ref HAL_GFXTIM_ERROR_CB_ID error callback ID + * @arg @ref HAL_GFXTIM_MSP_INIT_CB_ID MSP initialization user callback ID + * @arg @ref HAL_GFXTIM_MSP_DEINIT_CB_ID MSP de-initialization user callback ID + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_UnRegisterCallback(GFXTIM_HandleTypeDef *hgfxtim, + HAL_GFXTIM_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + switch (CallbackID) + { + case HAL_GFXTIM_AFC_COMPARE1_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback = HAL_GFXTIM_AbsoluteTimer_AFCC1Callback; + break; + case HAL_GFXTIM_AFC_OVERFLOW_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback = HAL_GFXTIM_AbsoluteTimer_AFCOFCallback; + break; + case HAL_GFXTIM_ALC_COMPARE1_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback = HAL_GFXTIM_AbsoluteTimer_ALCC1Callback; + break; + case HAL_GFXTIM_ALC_COMPARE2_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback = HAL_GFXTIM_AbsoluteTimer_ALCC2Callback; + break; + case HAL_GFXTIM_ALC_OVERFLOW_CB_ID : + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback = HAL_GFXTIM_AbsoluteTimer_ALCOFCallback; + break; + case HAL_GFXTIM_RFC1_RELOAD_CB_ID : + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback = HAL_GFXTIM_RelativeTimer_RFC1RCallback; + break; + case HAL_GFXTIM_RFC2_RELOAD_CB_ID : + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback = HAL_GFXTIM_RelativeTimer_RFC2RCallback; + break; + case HAL_GFXTIM_TE_CB_ID : + hgfxtim->HAL_GFXTIM_TECallback = HAL_GFXTIM_TECallback; + break; + case HAL_GFXTIM_EVENT1_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback = HAL_GFXTIM_EventGenerator_EV1Callback; + break; + case HAL_GFXTIM_EVENT2_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback = HAL_GFXTIM_EventGenerator_EV2Callback; + break; + case HAL_GFXTIM_EVENT3_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback = HAL_GFXTIM_EventGenerator_EV3Callback; + break; + case HAL_GFXTIM_EVENT4_CB_ID : + hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback = HAL_GFXTIM_EventGenerator_EV4Callback; + break; + case HAL_GFXTIM_WDG_ALARM_CB_ID : + hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback = HAL_GFXTIM_WatchdogTimer_AlarmCallback; + break; + case HAL_GFXTIM_WDG_PREALARM_CB_ID : + hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback = HAL_GFXTIM_WatchdogTimer_PreAlarmCallback; + break; + case HAL_GFXTIM_ERROR_CB_ID : + hgfxtim->ErrorCallback = HAL_GFXTIM_ErrorCallback; + break; + case HAL_GFXTIM_MSP_INIT_CB_ID : + hgfxtim->MspInitCallback = HAL_GFXTIM_MspInit; + break; + case HAL_GFXTIM_MSP_DEINIT_CB_ID : + hgfxtim->MspDeInitCallback = HAL_GFXTIM_MspDeInit; + break; + default : + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (hgfxtim->State == HAL_GFXTIM_STATE_RESET) + { + switch (CallbackID) + { + case HAL_GFXTIM_MSP_INIT_CB_ID : + hgfxtim->MspInitCallback = HAL_GFXTIM_MspInit; + break; + case HAL_GFXTIM_MSP_DEINIT_CB_ID : + hgfxtim->MspDeInitCallback = HAL_GFXTIM_MspDeInit; + break; + default : + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + /* Update error code and status */ + hgfxtim->ErrorCode |= GFXTIM_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + } + + return status; +} +#endif /* #if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1) */ + +/** + * @} + */ + +/** @defgroup GFXTIM_Exported_Functions_Group2 Clock Generator functions + * @brief Clock Generator functions + * +@verbatim + ============================================================================== + ##### Clock Generator functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Configure the clock generator. + (+) Force reload of FCC and LCC. + +@endverbatim + * @{ + */ + +/** + * @brief This function configures the clock generator. + * @param hgfxtim GFXTIM handle. + * @param pClockGeneratorConfig Clock Generator configuration parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_ClockGenerator_Config(GFXTIM_HandleTypeDef *hgfxtim, + const GFXTIM_ClockGeneratorConfigTypeDef *pClockGeneratorConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + if ((hgfxtim == NULL) || (pClockGeneratorConfig == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_LCC_HW_RELOAD_SRC(pClockGeneratorConfig->LCCHwReloadSrc)); + assert_param(IS_GFXTIM_LCC_RELOAD_VALUE(pClockGeneratorConfig->LCCReloadValue)); + assert_param(IS_GFXTIM_LCC_CLK_SRC(pClockGeneratorConfig->LCCClockSrc)); + assert_param(IS_GFXTIM_LINE_CLK_SRC(pClockGeneratorConfig->LineClockSrc)); + assert_param(IS_GFXTIM_FCC_HW_RELOAD_SRC(pClockGeneratorConfig->FCCHwReloadSrc)); + assert_param(IS_GFXTIM_FCC_RELOAD_VALUE(pClockGeneratorConfig->FCCReloadValue)); + assert_param(IS_GFXTIM_FCC_CLK_SRC(pClockGeneratorConfig->FCCClockSrc)); + assert_param(IS_GFXTIM_FRAME_CLK_SRC(pClockGeneratorConfig->FrameClockSrc)); + assert_param(IS_GFXTIM_LINE_CLK_CALIB(pClockGeneratorConfig->LineClockCalib)); + assert_param(IS_GFXTIM_FRAME_CLK_CALIB(pClockGeneratorConfig->FrameClockCalib)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Disable FCC and LCC */ + CLEAR_BIT(hgfxtim->Instance->CGCR, + GFXTIM_CGCR_LCCCS | GFXTIM_CGCR_FCCCS); + + /* Set Line Clock Counter (LCC) reload value (22 bits) */ + MODIFY_REG(hgfxtim->Instance->LCCRR, GFXTIM_LCCRR_RELOAD, + (pClockGeneratorConfig->LCCReloadValue << GFXTIM_LCCRR_RELOAD_Pos)); + + /* Set Frame Clock Counter (FCC) reload value (12 bits) */ + MODIFY_REG(hgfxtim->Instance->FCCRR, GFXTIM_FCCRR_RELOAD, + (pClockGeneratorConfig->FCCReloadValue << GFXTIM_FCCRR_RELOAD_Pos)); + + /* Set line and frame config */ + MODIFY_REG(hgfxtim->Instance->CGCR, + GFXTIM_CGCR_LCCHRS | GFXTIM_CGCR_LCCCS | GFXTIM_CGCR_LCS | + GFXTIM_CGCR_FCCHRS | GFXTIM_CGCR_FCCCS | GFXTIM_CGCR_FCS, + pClockGeneratorConfig->LCCHwReloadSrc | pClockGeneratorConfig->LCCClockSrc | + pClockGeneratorConfig->LineClockSrc | pClockGeneratorConfig->FCCHwReloadSrc | + pClockGeneratorConfig->FCCClockSrc | pClockGeneratorConfig->FrameClockSrc); + + /* Set debug output config for Line and frame clocks */ + MODIFY_REG(hgfxtim->Instance->CR, + GFXTIM_CR_LCCOE | GFXTIM_CR_FCCOE, + pClockGeneratorConfig->LineClockCalib | pClockGeneratorConfig->FrameClockCalib); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function force clock generator counter(s) reload + * @param hgfxtim GFXTIM handle. + * @param ClockGeneratorCounter Clock Generator counter + * This parameter can be a value of @ref GFXTIM_ClockGeneratorCounter. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_ClockGenerator_Reload(GFXTIM_HandleTypeDef *hgfxtim, uint32_t ClockGeneratorCounter) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_CLOCK_GENERATOR_COUNTER(ClockGeneratorCounter)); + + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + SET_BIT(hgfxtim->Instance->CGCR, ClockGeneratorCounter); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + + +/** + * @brief GFXTIM Tearing effect callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_TECallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_TECallback could be implemented in the user file */ +} + +/** + * @} + */ + +/** @defgroup GFXTIM_Exported_Functions_Group3 Absolute Timer functions + * @brief Absolute Timer functions + * +@verbatim + ============================================================================== + ##### Absolute Timers functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Configure the absolute timer. + (+) Start the absolute timer. + (+) Stop the absolute timer. + (+) Reset the absolute timer counters. + (+) Get the absolute time value. + (+) Set the absolute frame compare value. + (+) Set the absolute line compare value. +@endverbatim + * @{ + */ + +/** + * @brief This function configures an absolute Timer. + * @param hgfxtim GFXTIM handle. + * @param pAbsoluteTimerConfig pointer to a GFXTIM_AbsoluteTimerConfigTypeDef structure that + * contains absoluite timer comparators and counters values. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Config(GFXTIM_HandleTypeDef *hgfxtim, + const GFXTIM_AbsoluteTimerConfigTypeDef *pAbsoluteTimerConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + if ((hgfxtim == NULL) || (pAbsoluteTimerConfig == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_ABSOLUTE_FRAME_VALUE(pAbsoluteTimerConfig->FrameCompare1Value)); + assert_param(IS_GFXTIM_ABSOLUTE_FRAME_VALUE(pAbsoluteTimerConfig->FrameCounterValue)); + assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->FrameOverflowInterrupt)); + assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->FrameCompare1Interrupt)); + assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(pAbsoluteTimerConfig->LineCompare1Value)); + assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(pAbsoluteTimerConfig->LineCompare2Value)); + assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(pAbsoluteTimerConfig->LineCounterValue)); + assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->LineOverflowInterrupt)); + assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->LineCompare1Interrupt)); + assert_param(IS_GFXTIM_INTERRUPT(pAbsoluteTimerConfig->LineCompare2Interrupt)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + + /* Set AFC compare 1 value */ + MODIFY_REG(hgfxtim->Instance->AFCC1R, GFXTIM_AFCC1R_FRAME, + (pAbsoluteTimerConfig->FrameCompare1Value << GFXTIM_AFCC1R_FRAME_Pos)); + + /* Set AFC counter value */ + MODIFY_REG(hgfxtim->Instance->AFCR, GFXTIM_AFCR_FRAME, + (pAbsoluteTimerConfig->FrameCounterValue << GFXTIM_AFCR_FRAME_Pos)); + + /* Set ALC compare 1 value */ + MODIFY_REG(hgfxtim->Instance->ALCC1R, GFXTIM_ALCC1R_LINE, + (pAbsoluteTimerConfig->LineCompare1Value << GFXTIM_ALCC1R_LINE_Pos)); + + /* Set ALC compare 2 value */ + MODIFY_REG(hgfxtim->Instance->ALCC2R, GFXTIM_ALCC2R_LINE, + (pAbsoluteTimerConfig->LineCompare2Value << GFXTIM_ALCC2R_LINE_Pos)); + + /* Set ALC counter value */ + MODIFY_REG(hgfxtim->Instance->ALCR, GFXTIM_ALCR_LINE, + (pAbsoluteTimerConfig->LineCounterValue << GFXTIM_ALCR_LINE_Pos)); + + /* Set ALC compare 1, compare 2, overflow interrupts, AFC compare 1 and overflow interrupts */ + MODIFY_REG(hgfxtim->Instance->IER, + GFXTIM_IER_ALCC1IE | GFXTIM_IER_ALCC2IE | GFXTIM_IER_ALCOIE | GFXTIM_IER_AFCC1IE | GFXTIM_IER_AFCOIE, + (pAbsoluteTimerConfig->FrameOverflowInterrupt << GFXTIM_IER_AFCOIE_Pos) | + (pAbsoluteTimerConfig->FrameCompare1Interrupt << GFXTIM_IER_AFCC1IE_Pos) | + (pAbsoluteTimerConfig->LineOverflowInterrupt << GFXTIM_IER_ALCOIE_Pos) | + (pAbsoluteTimerConfig->LineCompare1Interrupt << GFXTIM_IER_ALCC1IE_Pos) | + (pAbsoluteTimerConfig->LineCompare2Interrupt << GFXTIM_IER_ALCC2IE_Pos)); + } + else + { + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function starts absolute timer. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Start(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Enable absolute Timer */ + SET_BIT(hgfxtim->Instance->TCR, (GFXTIM_TCR_AFCEN | GFXTIM_TCR_ALCEN)); + } + else + { + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function stops absolute timer counter(s). + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Stop(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Disable absolute counter(s) */ + SET_BIT(hgfxtim->Instance->TDR, (GFXTIM_TDR_ALCDIS | GFXTIM_TDR_AFCDIS)); + } + else + { + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function resets absolute timer counters. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_Reset(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Disable absolute counter(s) */ + SET_BIT(hgfxtim->Instance->TCR, (GFXTIM_TCR_FAFCR | GFXTIM_TCR_FALCR)); + } + else + { + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function gets absolute timer value. + * @param hgfxtim GFXTIM handle. + * @param AbsoluteTime absolute time + * This parameter can be a value of @ref GFXTIM_AbsoluteTime. + * @param pValue Absolute time value + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_GetCounter(const GFXTIM_HandleTypeDef *hgfxtim, uint32_t AbsoluteTime, + uint32_t *pValue) +{ + HAL_StatusTypeDef status = HAL_OK; + + if ((hgfxtim == NULL) || (pValue == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_ABSOLUTE_TIME(AbsoluteTime)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + switch (AbsoluteTime) + { + case GFXTIM_ABSOLUTE_GLOBAL_TIME: + *pValue = READ_REG(hgfxtim->Instance->ATR); + break; + case GFXTIM_ABSOLUTE_FRAME_TIME: + *pValue = READ_REG(hgfxtim->Instance->AFCR); + break; + default: + /* GFXTIM_ABSOLUTE_LINE_TIME */ + *pValue = READ_REG(hgfxtim->Instance->ALCR); + break; + } + } + else + { + status = HAL_ERROR; + } + } + return status; +} + +/** + * @brief This function sets absolute frame compare value. + * @param hgfxtim GFXTIM handle. + * @param Value Absolute frame compare 1 value + * This parameter can be a number between Min_Data = 0x00000 and Max_Data = 0xFFFFF + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_SetFrameCompare(GFXTIM_HandleTypeDef *hgfxtim, uint32_t Value) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Set absolute frame counter compare 1 register value */ + MODIFY_REG(hgfxtim->Instance->AFCC1R, GFXTIM_AFCC1R_FRAME, + (Value << GFXTIM_AFCC1R_FRAME_Pos)); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function sets line compare value. + * @param hgfxtim GFXTIM handle. + * @param AbsoluteLineComparator Absolute line compare value + * This parameter can be a value of @ref GFXTIM_AbsoluteLineComparator. + * @param Value Absolute line compare value + * This parameter can be a number between Min_Data = 0x000 and Max_Data = 0xFFF + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_AbsoluteTimer_SetLineCompare(GFXTIM_HandleTypeDef *hgfxtim, + uint32_t AbsoluteLineComparator, uint32_t Value) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_ABSOLUTE_LINE_COMPARATOR(AbsoluteLineComparator)); + assert_param(IS_GFXTIM_ABSOLUTE_LINE_VALUE(Value)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + switch (AbsoluteLineComparator) + { + case GFXTIM_ABSOLUTE_LINE_COMPARE1: + WRITE_REG(hgfxtim->Instance->ALCC1R, Value); + break; + default: + /* GFXTIM_ABSOLUTE_LINE_COMPARE2 */ + WRITE_REG(hgfxtim->Instance->ALCC2R, Value); + break; + } + } + else + { + status = HAL_ERROR; + } + } + return status; +} + +/** + * @brief GFXTIM Absolute frame counter overflow callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_AbsoluteTimer_AFCOFCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_AbsoluteTimer_AFCOFCallback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Absolute frame counter compare 1 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_AbsoluteTimer_AFCC1Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_AbsoluteTimer_AFCC1Callback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Absolute line counter compare 1 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_AbsoluteTimer_ALCC1Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_AbsoluteTimer_ALCC1Callback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Absolute line counter compare 2 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_AbsoluteTimer_ALCC2Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_AbsoluteTimer_ALCC2Callback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Absolute line counter overflow callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_AbsoluteTimer_ALCOFCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_AbsoluteTimer_ALCOFCallback could be implemented in the user file */ +} + +/** + * @} + */ + +/** @defgroup GFXTIM_Exported_Functions_Group4 Relative Timer functions + * @brief Clock Generator functions + * +@verbatim + ============================================================================== + ##### Relative Timer functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Configure a relative timer. + (+) Start a relative timer counter. + (+) Stop a relative timer counter. + (+) Force a relative timer counter reload. + (+) Set a relative timer reload value. + (+) Get a relative timer counter value. + +@endverbatim + * @{ + */ + +/** + * @brief This function configures a Relative Timer. + * @param hgfxtim GFXTIM handle. + * @param pRelativeTimerConfig pointer to a GFXTIM_RelativeTimerConfigTypeDef structure that + * contains relative timer comparators and counters values. + * @param RelativeTimer Relative Timer identifier + * This parameter can be a value of @ref GFXTIM_RelativeTimer. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_Config(GFXTIM_HandleTypeDef *hgfxtim, + const GFXTIM_RelativeTimerConfigTypeDef *pRelativeTimerConfig, + uint32_t RelativeTimer) +{ + HAL_StatusTypeDef status = HAL_OK; + + if ((hgfxtim == NULL) || (pRelativeTimerConfig == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_RELATIVE_FRAME_VALUE(pRelativeTimerConfig->AutoReloadValue)); + assert_param(IS_GFXTIM_RELATIVE_FRAME_VALUE(pRelativeTimerConfig->CounterMode)); + assert_param(IS_GFXTIM_INTERRUPT(pRelativeTimerConfig->ReloadInterrupt)); + assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) + { + /* Set RFC1 auto reload */ + MODIFY_REG(hgfxtim->Instance->RFC1RR, GFXTIM_RFC1RR_FRAME, + pRelativeTimerConfig->AutoReloadValue << GFXTIM_RFC1RR_FRAME_Pos); + + /* Set relative timer mode */ + MODIFY_REG(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC1CM, + (pRelativeTimerConfig->CounterMode << GFXTIM_TCR_RFC1CM_Pos)); + + /* Set relative timer 1 interrupt */ + MODIFY_REG(hgfxtim->Instance->IER, GFXTIM_IER_RFC1RIE_Msk, + (pRelativeTimerConfig->ReloadInterrupt << GFXTIM_IER_RFC1RIE_Pos)); + } + else + { + /* Set RFC2 auto reload */ + MODIFY_REG(hgfxtim->Instance->RFC2RR, GFXTIM_RFC2RR_FRAME, + pRelativeTimerConfig->AutoReloadValue << GFXTIM_RFC2RR_FRAME_Pos); + + /* Set relative timer mode */ + MODIFY_REG(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC2CM, + (pRelativeTimerConfig->CounterMode << GFXTIM_TCR_RFC2CM_Pos)); + + /* Set relative timer 2 interrupt */ + MODIFY_REG(hgfxtim->Instance->IER, GFXTIM_IER_RFC2RIE_Msk, + (pRelativeTimerConfig->ReloadInterrupt << GFXTIM_IER_RFC2RIE_Pos)); + } + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function starts a relative Timer. + * @param hgfxtim GFXTIM handle. + * @param RelativeTimer Relative timer counter to Enable + * This parameter can be a value of @ref GFXTIM_RelativeTimer. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_Start(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) + { + /* Enable relative timer 1 */ + SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC1EN); + } + else + { + /* Enable relative timer 2 */ + SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_RFC2EN); + } + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function stops a relative Timer counter. + * @param hgfxtim GFXTIM handle. + * @param RelativeTimer Relative timer counter to Disable + * This parameter can be a value of @ref GFXTIM_RelativeTimer. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_Stop(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) + { + /* Disable relative timer 1 */ + SET_BIT(hgfxtim->Instance->TDR, GFXTIM_TDR_RFC1DIS); + } + else + { + /* Disable relative timer 2 */ + SET_BIT(hgfxtim->Instance->TDR, GFXTIM_TDR_RFC2DIS); + } + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + + +/** + * @brief This function force a relative Timer reload. + * @param hgfxtim GFXTIM handle. + * @param RelativeTimer Relative timer to Foce Reload + * This parameter can be a value of @ref GFXTIM_RelativeTimer. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_ForceReload(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) + { + /* Force relative timer 1 reload */ + SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_FRFC1R); + } + else + { + /* Force relative timer 2 reload*/ + SET_BIT(hgfxtim->Instance->TCR, GFXTIM_TCR_FRFC2R); + } + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + + +/** + * @brief This function sets Relative frame timer reload value. + * @param hgfxtim GFXTIM handle. + * @param RelativeTimer specifies the Auto-reload register to be modified. + * This parameter can be a value of @ref GFXTIM_RelativeTimer. + * @param Value Reload value + * This parameter can be a number between Min_Data = 0x000 and Max_Data = 0xFFF + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_SetReload(GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer, + uint32_t Value) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_RELATIVE_FRAME_VALUE(Value)); + assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) + { + /* Set RFC1 auto reload */ + WRITE_REG(hgfxtim->Instance->RFC1RR, Value); + } + else + { + /* Set RFC2 auto reload */ + WRITE_REG(hgfxtim->Instance->RFC2RR, Value); + } + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function sets Relative frame timer compare value. + * @param hgfxtim GFXTIM handle. + * @param RelativeTimer Relative frame counter reload + * This parameter can be a value of @ref GFXTIM_RelativeTimer. + * @param pValue pointer to a relative frame counter value + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_RelativeTimer_GetCounter(const GFXTIM_HandleTypeDef *hgfxtim, uint32_t RelativeTimer, + uint32_t *pValue) +{ + HAL_StatusTypeDef status = HAL_OK; + + if ((hgfxtim == NULL) || (pValue == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_RELATIVE_TIMER(RelativeTimer)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + if (RelativeTimer == GFXTIM_RELATIVE_TIMER1) + { + /* Set RFC1 auto reload */ + *pValue = READ_REG(hgfxtim->Instance->RFC1R); + } + else + { + /* Set RFC2 auto reload */ + *pValue = READ_REG(hgfxtim->Instance->RFC2R); + } + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + + + + +/** + * @brief GFXTIM Relative frame counter 1 reload callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_RelativeTimer_RFC1RCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_RelativeTimer_RFC1RCallback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Relative frame counter 2 reload callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_RelativeTimer_RFC2RCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_RelativeTimer_RFC2RCallback could be implemented in the user file */ +} + +/** + * @} + */ + +/** @defgroup GFXTIM_Exported_Functions_Group5 Event Generator functions + * @brief Event Generator functions + * +@verbatim + ============================================================================== + ##### Event Generator functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Configure an Event Generator. + (+) Enable an Event Generator. + (+) Disable an Event Generator. +@endverbatim + * @{ + */ + +/** + * @brief This function configures an Event Generator. + * @param hgfxtim GFXTIM handle. + * @param EventGenerator Event Generator + * This parameter can be a value of @ref GFXTIM_EventGenerator. + * @param pEventGeneratorConfig pointer to a GFXTIM_EventGeneratorConfigTypeDef structure that + * contains Event Generator configuration parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_EventGenerator_Config(GFXTIM_HandleTypeDef *hgfxtim, uint32_t EventGenerator, + const GFXTIM_EventGeneratorConfigTypeDef *pEventGeneratorConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t shift; + + if ((hgfxtim == NULL) || (pEventGeneratorConfig == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_EVENT_GENERATOR(EventGenerator)); + assert_param(IS_GFXTIM_EVENT_LINE(pEventGeneratorConfig->LineEvent)); + assert_param(IS_GFXTIM_EVENT_FRAME(pEventGeneratorConfig->FrameEvent)); + assert_param(IS_GFXTIM_INTERRUPT(pEventGeneratorConfig->EventInterrupt)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Select frame and line events */ + shift = (EventGenerator) * 8U; + MODIFY_REG(hgfxtim->Instance->EVSR, \ + ((GFXTIM_EVSR_LES1 | GFXTIM_EVSR_FES1) << shift), + ((pEventGeneratorConfig->LineEvent | pEventGeneratorConfig->FrameEvent) << shift)); + + /* Event interrupt */ + MODIFY_REG(hgfxtim->Instance->IER, \ + (GFXTIM_IER_EV1IE << (EventGenerator)), \ + (pEventGeneratorConfig->EventInterrupt << (EventGenerator + GFXTIM_IER_EV1IE_Pos))); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function enables an Event Generator. + * @param hgfxtim GFXTIM handle. + * @param EventGenerator Event Generator + * This parameter can be a value of @ref GFXTIM_EventGenerator. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_EventGenerator_Enable(GFXTIM_HandleTypeDef *hgfxtim, uint32_t EventGenerator) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_EVENT_GENERATOR(EventGenerator)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Enable event generator */ + SET_BIT(hgfxtim->Instance->EVCR, GFXTIM_EVCR_EV1EN << EventGenerator); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function disables an Event Generator. + * @param hgfxtim GFXTIM handle. + * @param EventGenerator Event Generator + * This parameter can be a value of @ref GFXTIM_EventGenerator. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_EventGenerator_Disable(GFXTIM_HandleTypeDef *hgfxtim, uint32_t EventGenerator) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_EVENT_GENERATOR(EventGenerator)); + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Disable event generator */ + CLEAR_BIT(hgfxtim->Instance->EVCR, GFXTIM_EVCR_EV1EN << EventGenerator); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + + + +/** + * @brief GFXTIM Combined events 1 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_EventGenerator_EV1Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_EventGenerator_EV1Callback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Combined events 2 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_EventGenerator_EV2Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_EventGenerator_EV2Callback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Combined events 3 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_EventGenerator_EV3Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_EventGenerator_EV3Callback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Combined events 4 callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_EventGenerator_EV4Callback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_EventGenerator_EV4Callback could be implemented in the user file */ +} + +/** + * @} + */ + +/** @defgroup GFXTIM_Exported_Functions_Group6 Watchdog functions + * @brief Event Generator functions + * +@verbatim + ============================================================================== + ##### Watchdog functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Configure the Watchdog. + (+) Enable the Watchdog + (+) Disable the Watchdog. + (+) Refresh the Watchdog. +@endverbatim + * @{ + */ + +/** + * @brief This function configures the Watchdog. + * @param hgfxtim GFXTIM handle. + * @param pWatchdogConfig Watchdog configuration parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Config(GFXTIM_HandleTypeDef *hgfxtim, + const GFXTIM_WatchdogConfigTypeDef *pWatchdogConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + if ((hgfxtim == NULL) || (pWatchdogConfig == NULL)) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + assert_param(IS_GFXTIM_WATCHDOG_CLOCK_SRC(pWatchdogConfig->ClockSrc)); + assert_param(IS_GFXTIM_WATCHDOG_HW_RELOAD_CONFIG(pWatchdogConfig->HwReloadConfig)); + + assert_param(IS_GFXTIM_WATCHDOG_VALUE(pWatchdogConfig->AutoReloadValue)); + assert_param(IS_GFXTIM_WATCHDOG_VALUE(pWatchdogConfig->PreAlarmValue)); + + assert_param(IS_GFXTIM_INTERRUPT(pWatchdogConfig->AlarmInterrupt)); + assert_param(IS_GFXTIM_INTERRUPT(pWatchdogConfig->PreAlarmInterrupt)); + + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Set watchdog auto reload value */ + MODIFY_REG(hgfxtim->Instance->WDGRR, GFXTIM_WDGRR_RELOAD, + (pWatchdogConfig->AutoReloadValue << GFXTIM_WDGRR_RELOAD_Pos)); + + /* Set watchdog pre alarm value */ + MODIFY_REG(hgfxtim->Instance->WDGPAR, GFXTIM_WDGPAR_PREALARM, + pWatchdogConfig->PreAlarmValue << GFXTIM_WDGPAR_PREALARM_Pos); + + /* Set watchdog clock source and hardware reload */ + MODIFY_REG(hgfxtim->Instance->WDGTCR, (GFXTIM_WDGTCR_WDGCS | GFXTIM_WDGTCR_WDGHRC), + (pWatchdogConfig->ClockSrc | pWatchdogConfig->HwReloadConfig)); + + /* Set watchdog interrupts */ + MODIFY_REG(hgfxtim->Instance->IER, \ + (GFXTIM_IER_WDGAIE | GFXTIM_IER_WDGPIE), \ + ((pWatchdogConfig->AlarmInterrupt << GFXTIM_IER_WDGAIE_Pos) | \ + (pWatchdogConfig->PreAlarmInterrupt << GFXTIM_IER_WDGPIE_Pos))); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function Enable the Watchdog Counter. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Enable(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Set watchdog enable bit */ + SET_BIT(hgfxtim->Instance->WDGTCR, GFXTIM_WDGTCR_WDGEN); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function Disable the Watchdog Counter. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Disable(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Set watchdog disable bit */ + SET_BIT(hgfxtim->Instance->WDGTCR, GFXTIM_WDGTCR_WDGDIS); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief This function refresh the Watchdog counter. + * @param hgfxtim GFXTIM handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_GFXTIM_WatchdogTimer_Refresh(GFXTIM_HandleTypeDef *hgfxtim) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hgfxtim == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_GFXTIM_ALL_INSTANCE(hgfxtim->Instance)); + + + if (hgfxtim->State == HAL_GFXTIM_STATE_READY) + { + /* Set watchdog SW relaod */ + SET_BIT(hgfxtim->Instance->WDGTCR, GFXTIM_WDGTCR_FWDGR); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief GFXTIM Watchdog alarm callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_WatchdogTimer_AlarmCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_WatchdogTimer_AlarmCallback could be implemented in the user file */ +} + +/** + * @brief GFXTIM Watchdog pre alarm callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_WatchdogTimer_PreAlarmCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_WatchdogTimer_PreAlarmCallback could be implemented in the user file */ +} + +/** + * @} + */ + +/** @defgroup GFXTIM_Exported_Functions_Group7 Generic functions + * @brief Generic functions + * +@verbatim + ============================================================================== + ##### Generic functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Handle GFXTIM interrupt. + (+) Inform user that error occurs. + (+) Get the current GFXTIM instance state + (+) Get the current GFXTIM instance error code. +@endverbatim + * @{ + */ + +/** + * @brief This function handles the GFXTIM interrupts. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +void HAL_GFXTIM_IRQHandler(GFXTIM_HandleTypeDef *hgfxtim) +{ + uint32_t tmp_reg1; + uint32_t tmp_reg2; + uint32_t interrupts; + + /* Read all pending interrupts */ + tmp_reg1 = READ_REG(hgfxtim->Instance->ISR); + tmp_reg2 = READ_REG(hgfxtim->Instance->IER); + interrupts = tmp_reg1 & tmp_reg2; + + if ((interrupts & GFXTIM_ISR_AFCC1F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCC1Callback(hgfxtim); +#else + HAL_GFXTIM_AbsoluteTimer_AFCC1Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_AFCOF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_AbsoluteTimer_AFCOFCallback(hgfxtim); +#else + HAL_GFXTIM_AbsoluteTimer_AFCOFCallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_ALCC1F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC1Callback(hgfxtim); +#else + HAL_GFXTIM_AbsoluteTimer_ALCC1Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_ALCC2F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCC2Callback(hgfxtim); +#else + HAL_GFXTIM_AbsoluteTimer_ALCC2Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_ALCOF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_AbsoluteTimer_ALCOFCallback(hgfxtim); +#else + HAL_GFXTIM_AbsoluteTimer_ALCOFCallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_TEF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_TECallback(hgfxtim); +#else + HAL_GFXTIM_TECallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_RFC1RF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC1RCallback(hgfxtim); +#else + HAL_GFXTIM_RelativeTimer_RFC1RCallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_RFC2RF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_RelativeTimer_RFC2RCallback(hgfxtim); +#else + HAL_GFXTIM_RelativeTimer_RFC2RCallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_EV1F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_EventGenerator_EV1Callback(hgfxtim); +#else + HAL_GFXTIM_EventGenerator_EV1Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_EV2F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_EventGenerator_EV2Callback(hgfxtim); +#else + HAL_GFXTIM_EventGenerator_EV2Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_EV3F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_EventGenerator_EV3Callback(hgfxtim); +#else + HAL_GFXTIM_EventGenerator_EV3Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_EV4F) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_EventGenerator_EV4Callback(hgfxtim); +#else + HAL_GFXTIM_EventGenerator_EV4Callback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_WDGAF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_WatchdogTimer_AlarmCallback(hgfxtim); +#else + HAL_GFXTIM_WatchdogTimer_AlarmCallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + + if ((interrupts & GFXTIM_ISR_WDGPF) != 0U) + { +#if (USE_HAL_GFXTIM_REGISTER_CALLBACKS == 1U) + hgfxtim->HAL_GFXTIM_WatchdogTimer_PreAlarmCallback(hgfxtim); +#else + HAL_GFXTIM_WatchdogTimer_PreAlarmCallback(hgfxtim); +#endif /* USE_HAL_GFXTIM_REGISTER_CALLBACKS */ + } + /* Clear all pending interrupts */ + WRITE_REG(hgfxtim->Instance->ICR, interrupts); +} + +/** + * @brief GFXTIM error callback. + * @param hgfxtim GFXTIM handle. + * @retval None. + */ +__weak void HAL_GFXTIM_ErrorCallback(GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgfxtim); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_GFXTIM_ErrorCallback could be implemented in the user file. */ +} + +/** + * @brief This function get the current GFXTIM state. + * @param hgfxtim GFXTIM handle. + * @retval GFXTIM state. + */ +HAL_GFXTIM_StateTypeDef HAL_GFXTIM_GetState(const GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Return GFXTIM state */ + return hgfxtim->State; +} + +/** + * @brief This function get the current GFXTIM error. + * @param hgfxtim GFXTIM handle. + * @retval GFXTIM error code. + */ +uint32_t HAL_GFXTIM_GetError(const GFXTIM_HandleTypeDef *hgfxtim) +{ + /* Return GFXTIM error code */ + return hgfxtim->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* GFXTIM */ +#endif /* HAL_GFXTIM_MODULE_ENABLED */ +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpio.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpio.c index ef62f421e..84aeac7b0 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpio.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpio.c @@ -1,555 +1,554 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_gpio.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 39 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: __HAL_RCC_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 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(). - - (#) To set the level of several pins and reset level of several other pins in - same cycle, use HAL_GPIO_WriteMultipleStatePin(). - - (#) To lock pin configuration until next reset use HAL_GPIO_LockPin(). - - (#) 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 - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @addtogroup GPIO - * @{ - */ -/** MISRA C:2012 deviation rule has been granted for following rules: - * Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of - * range of the shift operator in following API : - * HAL_GPIO_Init - * HAL_GPIO_DeInit - */ - -#ifdef HAL_GPIO_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private defines ------------------------------------------------------------*/ -/** @addtogroup GPIO_Private_Constants - * @{ - */ -#define GPIO_NUMBER (16u) -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup GPIO_Exported_Functions - * @{ - */ - -/** @addtogroup GPIO_Exported_Functions_Group1 - * @brief Initialization and Configuration functions - * -@verbatim - =============================================================================== - ##### Initialization and de-initialization functions ##### - =============================================================================== - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the GPIOx peripheral according to the specified parameters in the GPIO_Init. - * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @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, const GPIO_InitTypeDef *GPIO_Init) -{ - uint32_t position = 0x00u; - uint32_t iocurrent; - uint32_t temp; - - /* Check the parameters */ - assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); - assert_param(IS_GPIO_PIN(GPIO_Init->Pin)); - assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); - - /* Configure the port pins */ - while (((GPIO_Init->Pin) >> position) != 0x00u) - { - /* Get current io position */ - iocurrent = (GPIO_Init->Pin) & (1uL << position); - - if (iocurrent != 0x00u) - { - /*--------------------- GPIO Mode Configuration ------------------------*/ - /* In case of Output or Alternate function mode selection */ - if (((GPIO_Init->Mode & GPIO_MODE) == MODE_OUTPUT) || ((GPIO_Init->Mode & GPIO_MODE) == MODE_AF)) - { - /* Check the Speed parameter */ - assert_param(IS_GPIO_SPEED(GPIO_Init->Speed)); - - /* Configure the IO Speed */ - temp = GPIOx->OSPEEDR; - temp &= ~(GPIO_OSPEEDR_OSPEED0 << (position * GPIO_OSPEEDR_OSPEED1_Pos)); - temp |= (GPIO_Init->Speed << (position * GPIO_OSPEEDR_OSPEED1_Pos)); - GPIOx->OSPEEDR = temp; - - /* Configure the IO Output Type */ - temp = GPIOx->OTYPER; - temp &= ~(GPIO_OTYPER_OT0 << position) ; - temp |= (((GPIO_Init->Mode & OUTPUT_TYPE) >> OUTPUT_TYPE_Pos) << position); - GPIOx->OTYPER = temp; - } - - if ((GPIO_Init->Mode & GPIO_MODE) != MODE_ANALOG) - { - /* Check the Pull parameter */ - assert_param(IS_GPIO_PULL(GPIO_Init->Pull)); - - /* Activate the Pull-up or Pull down resistor for the current IO */ - temp = GPIOx->PUPDR; - temp &= ~(GPIO_PUPDR_PUPD0 << (position * GPIO_PUPDR_PUPD1_Pos)); - temp |= ((GPIO_Init->Pull) << (position * GPIO_PUPDR_PUPD1_Pos)); - GPIOx->PUPDR = temp; - } - - /* In case of Alternate function mode selection */ - if ((GPIO_Init->Mode & GPIO_MODE) == MODE_AF) - { - /* Check the Alternate function parameters */ - assert_param(IS_GPIO_AF_INSTANCE(GPIOx)); - assert_param(IS_GPIO_AF(GPIO_Init->Alternate)); - - /* Configure Alternate function mapped with the current IO */ - temp = GPIOx->AFR[position >> 3u]; - temp &= ~(0xFu << ((position & 0x07u) * GPIO_AFRL_AFSEL1_Pos)); - temp |= ((GPIO_Init->Alternate) << ((position & 0x07u) * GPIO_AFRL_AFSEL1_Pos)); - GPIOx->AFR[position >> 3u] = temp; - } - - /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ - temp = GPIOx->MODER; - temp &= ~(GPIO_MODER_MODE0 << (position * GPIO_MODER_MODE1_Pos)); - temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * GPIO_MODER_MODE1_Pos)); - GPIOx->MODER = temp; - - /*--------------------- EXTI Mode Configuration ------------------------*/ - /* Configure the External Interrupt or event for the current IO */ - if ((GPIO_Init->Mode & EXTI_MODE) != 0x00u) - { - temp = SBS->EXTICR[position >> 2u]; - temp &= ~(0x0FuL << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos)); - temp |= (GPIO_GET_INDEX(GPIOx) << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos)); - SBS->EXTICR[position >> 2u] = temp; - - /* Clear Rising Falling edge configuration */ - temp = EXTI->RTSR1; - temp &= ~(iocurrent); - if ((GPIO_Init->Mode & TRIGGER_RISING) != 0x00u) - { - temp |= iocurrent; - } - EXTI->RTSR1 = temp; - - temp = EXTI->FTSR1; - temp &= ~(iocurrent); - if ((GPIO_Init->Mode & TRIGGER_FALLING) != 0x00u) - { - temp |= iocurrent; - } - EXTI->FTSR1 = temp; - - /* Clear EXTI line configuration */ - temp = EXTI->EMR1; - temp &= ~(iocurrent); - if ((GPIO_Init->Mode & EXTI_EVT) != 0x00u) - { - temp |= iocurrent; - } - EXTI->EMR1 = temp; - - temp = EXTI->IMR1; - temp &= ~(iocurrent); - if ((GPIO_Init->Mode & EXTI_IT) != 0x00u) - { - temp |= iocurrent; - } - EXTI->IMR1 = temp; - } - } - - position++; - } -} - -/** - * @brief De-initialize the GPIOx peripheral registers to their default reset values. - * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @param GPIO_Pin specifies the port bit to be written. - * This parameter can be any combination 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 = 0x00u; - uint32_t iocurrent; - uint32_t tmp; - - /* Check the parameters */ - assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); - assert_param(IS_GPIO_PIN(GPIO_Pin)); - - /* Configure the port pins */ - while ((GPIO_Pin >> position) != 0x00u) - { - /* Get current io position */ - iocurrent = (GPIO_Pin) & (1uL << position); - - if (iocurrent != 0x00u) - { - /*------------------------- EXTI Mode Configuration --------------------*/ - /* Clear the External Interrupt or Event for the current IO */ - - tmp = SBS->EXTICR[position >> 2u]; - tmp &= (0x0FuL << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos)); - if (tmp == (GPIO_GET_INDEX(GPIOx) << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos))) - { - /* Clear EXTI line configuration */ - EXTI->IMR1 &= ~(iocurrent); - EXTI->EMR1 &= ~(iocurrent); - - /* Clear Rising Falling edge configuration */ - EXTI->FTSR1 &= ~(iocurrent); - EXTI->RTSR1 &= ~(iocurrent); - - /* Clear EXTICR configuration */ - tmp = 0x0FuL << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos); - SBS->EXTICR[position >> 2u] &= ~tmp; - } - - /*------------------------- GPIO Mode Configuration --------------------*/ - /* Configure IO in Analog Mode */ - GPIOx->MODER |= (GPIO_MODER_MODE0 << (position * GPIO_MODER_MODE1_Pos)); - - /* Configure the default Alternate Function in current IO */ - GPIOx->AFR[position >> 3u] &= ~(0xFu << ((position & 0x07u) * GPIO_AFRL_AFSEL1_Pos)) ; - - /* Configure the default value for IO Speed */ - GPIOx->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEED0 << (position * GPIO_OSPEEDR_OSPEED1_Pos)); - - /* Configure the default value IO Output Type */ - GPIOx->OTYPER &= ~(GPIO_OTYPER_OT0 << position) ; - - /* Deactivate the Pull-up and Pull-down resistor for the current IO */ - GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * GPIO_PUPDR_PUPD1_Pos)); - } - - position++; - } -} - -/** - * @} - */ - -/** @addtogroup GPIO_Exported_Functions_Group2 - * @brief GPIO Read, Write, Toggle, Lock and EXTI management functions. - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - -@endverbatim - * @{ - */ - -/** - * @brief Read the specified input port pin. - * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @param GPIO_Pin specifies the port bit to read. - * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). - * @retval The input port pin value. - */ -GPIO_PinState HAL_GPIO_ReadPin(const GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) -{ - GPIO_PinState bitstatus; - - /* Check the parameters */ - assert_param(IS_GPIO_PIN(GPIO_Pin)); - - if ((GPIOx->IDR & GPIO_Pin) != 0x00u) - { - bitstatus = GPIO_PIN_SET; - } - else - { - bitstatus = GPIO_PIN_RESET; - } - return bitstatus; -} - -/** - * @brief Set or clear the selected data port bit. - * @note This function uses GPIOx_BSRR and GPIOx_BRR registers 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..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @param GPIO_Pin specifies the port bit to be written. - * This parameter can be any combination 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_PIN_RESET: to clear the port pin - * @arg GPIO_PIN_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_GPIO_PIN(GPIO_Pin)); - assert_param(IS_GPIO_PIN_ACTION(PinState)); - - if (PinState != GPIO_PIN_RESET) - { - GPIOx->BSRR = (uint32_t)GPIO_Pin; - } - else - { - GPIOx->BRR = (uint32_t)GPIO_Pin; - } -} - -/** - * @brief Set and clear several pins of a dedicated port in same cycle. - * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @param PinReset specifies the port bits to be reset - * This parameter can be any combination of GPIO_Pin_x where x can be (0..15) or zero. - * @param PinSet specifies the port bits to be set - * This parameter can be any combination of GPIO_Pin_x where x can be (0..15) or zero. - * @note Both PinReset and PinSet combinations shall not get any common bit, else - * assert would be triggered. - * @note At least one of the two parameters used to set or reset shall be different from zero. - * @retval None - */ -void HAL_GPIO_WriteMultipleStatePin(GPIO_TypeDef *GPIOx, uint16_t PinReset, uint16_t PinSet) -{ - uint32_t tmp; - - /* Check the parameters */ - /* Make sure at least one parameter is different from zero and that there is no common pin */ - assert_param(IS_GPIO_PIN((uint32_t)PinReset | (uint32_t)PinSet)); - assert_param(IS_GPIO_COMMON_PIN(PinReset, PinSet)); - - tmp = (((uint32_t)PinReset << 16) | PinSet); - GPIOx->BSRR = tmp; -} - -/** - * @brief Toggle the specified GPIO pin. - * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @param GPIO_Pin specifies the pin to be toggled. - * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). - * @retval None - */ -void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) -{ - uint32_t odr; - - /* Check the parameters */ - assert_param(IS_GPIO_PIN(GPIO_Pin)); - - /* get current Output Data Register value */ - odr = GPIOx->ODR; - - /* Set selected pins that were at low level, and reset ones that were high */ - GPIOx->BSRR = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin); -} - -/** - * @brief Lock GPIO Pins configuration registers. - * @note The locked registers are GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR, - * GPIOx_PUPDR, GPIOx_AFRL and GPIOx_AFRH. - * @note The configuration of the locked GPIO pins can no longer be modified - * until the next reset. - * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family - * @param GPIO_Pin specifies the port bits to be locked. - * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). - * @retval None - */ -HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) -{ - __IO uint32_t tmp = GPIO_LCKR_LCKK; - - /* Check the parameters */ - assert_param(IS_GPIO_LOCK_INSTANCE(GPIOx)); - assert_param(IS_GPIO_PIN(GPIO_Pin)); - - /* Apply lock key write sequence */ - tmp |= GPIO_Pin; - /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ - GPIOx->LCKR = tmp; - /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */ - GPIOx->LCKR = GPIO_Pin; - /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ - GPIOx->LCKR = tmp; - /* Read LCKK register. This read is mandatory to complete key lock sequence */ - tmp = GPIOx->LCKR; - - /* read again in order to confirm lock is active */ - if ((GPIOx->LCKR & GPIO_LCKR_LCKK) != 0x00u) - { - return HAL_OK; - } - else - { - return HAL_ERROR; - } -} - -/** - * @brief Handle EXTI interrupt request. - * @param GPIO_Pin Specifies the port pin connected to corresponding 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) != 0U) - { - __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin); - HAL_GPIO_EXTI_Callback(GPIO_Pin); - } -} - -/** - * @brief EXTI line detection callback. - * @param GPIO_Pin Specifies the port pin connected to corresponding EXTI line. - * @retval None - */ -__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_gpio.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 39 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: __HAL_RCC_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 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(). + + (#) To set the level of several pins and reset level of several other pins in + same cycle, use HAL_GPIO_WriteMultipleStatePin(). + + (#) To lock pin configuration until next reset use HAL_GPIO_LockPin(). + + (#) 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 + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @addtogroup GPIO + * @{ + */ +/** MISRA C:2012 deviation rule has been granted for following rules: + * Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of + * range of the shift operator in following API : + * HAL_GPIO_Init + * HAL_GPIO_DeInit + */ + +#ifdef HAL_GPIO_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines ------------------------------------------------------------*/ +/** @addtogroup GPIO_Private_Constants + * @{ + */ +#define GPIO_NUMBER (16u) +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup GPIO_Exported_Functions + * @{ + */ + +/** @addtogroup GPIO_Exported_Functions_Group1 + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the GPIOx peripheral according to the specified parameters in the GPIO_Init. + * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @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, const GPIO_InitTypeDef *GPIO_Init) +{ + uint32_t position = 0x00u; + uint32_t iocurrent; + uint32_t temp; + + /* Check the parameters */ + assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); + assert_param(IS_GPIO_PIN(GPIO_Init->Pin)); + assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); + + /* Configure the port pins */ + while (((GPIO_Init->Pin) >> position) != 0x00u) + { + /* Get current io position */ + iocurrent = (GPIO_Init->Pin) & (1uL << position); + + if (iocurrent != 0x00u) + { + /*--------------------- GPIO Mode Configuration ------------------------*/ + /* In case of Output or Alternate function mode selection */ + if (((GPIO_Init->Mode & GPIO_MODE) == MODE_OUTPUT) || ((GPIO_Init->Mode & GPIO_MODE) == MODE_AF)) + { + /* Check the Speed parameter */ + assert_param(IS_GPIO_SPEED(GPIO_Init->Speed)); + + /* Configure the IO Speed */ + temp = GPIOx->OSPEEDR; + temp &= ~(GPIO_OSPEEDR_OSPEED0 << (position * GPIO_OSPEEDR_OSPEED1_Pos)); + temp |= (GPIO_Init->Speed << (position * GPIO_OSPEEDR_OSPEED1_Pos)); + GPIOx->OSPEEDR = temp; + + /* Configure the IO Output Type */ + temp = GPIOx->OTYPER; + temp &= ~(GPIO_OTYPER_OT0 << position) ; + temp |= (((GPIO_Init->Mode & OUTPUT_TYPE) >> OUTPUT_TYPE_Pos) << position); + GPIOx->OTYPER = temp; + } + + if ((GPIO_Init->Mode & GPIO_MODE) != MODE_ANALOG) + { + /* Check the Pull parameter */ + assert_param(IS_GPIO_PULL(GPIO_Init->Pull)); + + /* Activate the Pull-up or Pull down resistor for the current IO */ + temp = GPIOx->PUPDR; + temp &= ~(GPIO_PUPDR_PUPD0 << (position * GPIO_PUPDR_PUPD1_Pos)); + temp |= ((GPIO_Init->Pull) << (position * GPIO_PUPDR_PUPD1_Pos)); + GPIOx->PUPDR = temp; + } + + /* In case of Alternate function mode selection */ + if ((GPIO_Init->Mode & GPIO_MODE) == MODE_AF) + { + /* Check the Alternate function parameters */ + assert_param(IS_GPIO_AF_INSTANCE(GPIOx)); + assert_param(IS_GPIO_AF(GPIO_Init->Alternate)); + + /* Configure Alternate function mapped with the current IO */ + temp = GPIOx->AFR[position >> 3u]; + temp &= ~(0xFu << ((position & 0x07u) * GPIO_AFRL_AFSEL1_Pos)); + temp |= ((GPIO_Init->Alternate) << ((position & 0x07u) * GPIO_AFRL_AFSEL1_Pos)); + GPIOx->AFR[position >> 3u] = temp; + } + + /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ + temp = GPIOx->MODER; + temp &= ~(GPIO_MODER_MODE0 << (position * GPIO_MODER_MODE1_Pos)); + temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * GPIO_MODER_MODE1_Pos)); + GPIOx->MODER = temp; + + /*--------------------- EXTI Mode Configuration ------------------------*/ + /* Configure the External Interrupt or event for the current IO */ + if ((GPIO_Init->Mode & EXTI_MODE) != 0x00u) + { + temp = SBS->EXTICR[position >> 2u]; + temp &= ~(0x0FuL << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos)); + temp |= (GPIO_GET_INDEX(GPIOx) << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos)); + SBS->EXTICR[position >> 2u] = temp; + + /* Clear Rising Falling edge configuration */ + temp = EXTI->RTSR1; + temp &= ~(iocurrent); + if ((GPIO_Init->Mode & TRIGGER_RISING) != 0x00u) + { + temp |= iocurrent; + } + EXTI->RTSR1 = temp; + + temp = EXTI->FTSR1; + temp &= ~(iocurrent); + if ((GPIO_Init->Mode & TRIGGER_FALLING) != 0x00u) + { + temp |= iocurrent; + } + EXTI->FTSR1 = temp; + + /* Clear EXTI line configuration */ + temp = EXTI->EMR1; + temp &= ~(iocurrent); + if ((GPIO_Init->Mode & EXTI_EVT) != 0x00u) + { + temp |= iocurrent; + } + EXTI->EMR1 = temp; + + temp = EXTI->IMR1; + temp &= ~(iocurrent); + if ((GPIO_Init->Mode & EXTI_IT) != 0x00u) + { + temp |= iocurrent; + } + EXTI->IMR1 = temp; + } + } + + position++; + } +} + +/** + * @brief De-initialize the GPIOx peripheral registers to their default reset values. + * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @param GPIO_Pin specifies the port bit to be written. + * This parameter can be any combination 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 = 0x00u; + uint32_t iocurrent; + uint32_t tmp; + + /* Check the parameters */ + assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + /* Configure the port pins */ + while ((GPIO_Pin >> position) != 0x00u) + { + /* Get current io position */ + iocurrent = (GPIO_Pin) & (1uL << position); + + if (iocurrent != 0x00u) + { + /*------------------------- EXTI Mode Configuration --------------------*/ + /* Clear the External Interrupt or Event for the current IO */ + + tmp = SBS->EXTICR[position >> 2u]; + tmp &= (0x0FuL << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos)); + if (tmp == (GPIO_GET_INDEX(GPIOx) << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos))) + { + /* Clear EXTI line configuration */ + EXTI->IMR1 &= ~(iocurrent); + EXTI->EMR1 &= ~(iocurrent); + + /* Clear Rising Falling edge configuration */ + EXTI->FTSR1 &= ~(iocurrent); + EXTI->RTSR1 &= ~(iocurrent); + + /* Clear EXTICR configuration */ + tmp = 0x0FuL << ((position & 0x03u) * SBS_EXTICR1_PC_EXTI1_Pos); + SBS->EXTICR[position >> 2u] &= ~tmp; + } + + /*------------------------- GPIO Mode Configuration --------------------*/ + /* Configure IO in Analog Mode */ + GPIOx->MODER |= (GPIO_MODER_MODE0 << (position * GPIO_MODER_MODE1_Pos)); + + /* Configure the default Alternate Function in current IO */ + GPIOx->AFR[position >> 3u] &= ~(0xFu << ((position & 0x07u) * GPIO_AFRL_AFSEL1_Pos)) ; + + /* Configure the default value for IO Speed */ + GPIOx->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEED0 << (position * GPIO_OSPEEDR_OSPEED1_Pos)); + + /* Configure the default value IO Output Type */ + GPIOx->OTYPER &= ~(GPIO_OTYPER_OT0 << position) ; + + /* Deactivate the Pull-up and Pull-down resistor for the current IO */ + GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * GPIO_PUPDR_PUPD1_Pos)); + } + + position++; + } +} + +/** + * @} + */ + +/** @addtogroup GPIO_Exported_Functions_Group2 + * @brief GPIO Read, Write, Toggle, Lock and EXTI management functions. + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Read the specified input port pin. + * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @param GPIO_Pin specifies the port bit to read. + * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). + * @retval The input port pin value. + */ +GPIO_PinState HAL_GPIO_ReadPin(const GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) +{ + GPIO_PinState bitstatus; + + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + if ((GPIOx->IDR & GPIO_Pin) != 0x00u) + { + bitstatus = GPIO_PIN_SET; + } + else + { + bitstatus = GPIO_PIN_RESET; + } + return bitstatus; +} + +/** + * @brief Set or clear the selected data port bit. + * @note This function uses GPIOx_BSRR and GPIOx_BRR registers 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..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @param GPIO_Pin specifies the port bit to be written. + * This parameter can be any combination 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_PIN_RESET: to clear the port pin + * @arg GPIO_PIN_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_GPIO_PIN(GPIO_Pin)); + assert_param(IS_GPIO_PIN_ACTION(PinState)); + + if (PinState != GPIO_PIN_RESET) + { + GPIOx->BSRR = (uint32_t)GPIO_Pin; + } + else + { + GPIOx->BRR = (uint32_t)GPIO_Pin; + } +} + +/** + * @brief Set and clear several pins of a dedicated port in same cycle. + * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @param PinReset specifies the port bits to be reset + * This parameter can be any combination of GPIO_Pin_x where x can be (0..15) or zero. + * @param PinSet specifies the port bits to be set + * This parameter can be any combination of GPIO_Pin_x where x can be (0..15) or zero. + * @note Both PinReset and PinSet combinations shall not get any common bit, else + * assert would be triggered. + * @note At least one of the two parameters used to set or reset shall be different from zero. + * @retval None + */ +void HAL_GPIO_WriteMultipleStatePin(GPIO_TypeDef *GPIOx, uint16_t PinReset, uint16_t PinSet) +{ + uint32_t tmp; + + /* Check the parameters */ + /* Make sure at least one parameter is different from zero and that there is no common pin */ + assert_param(IS_GPIO_PIN((uint32_t)PinReset | (uint32_t)PinSet)); + assert_param(IS_GPIO_COMMON_PIN(PinReset, PinSet)); + + tmp = (((uint32_t)PinReset << 16) | PinSet); + GPIOx->BSRR = tmp; +} + +/** + * @brief Toggle the specified GPIO pin. + * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @param GPIO_Pin specifies the pin to be toggled. + * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). + * @retval None + */ +void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) +{ + uint32_t odr; + + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + /* get current Output Data Register value */ + odr = GPIOx->ODR; + + /* Set selected pins that were at low level, and reset ones that were high */ + GPIOx->BSRR = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin); +} + +/** + * @brief Lock GPIO Pins configuration registers. + * @note The locked registers are GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR, + * GPIOx_PUPDR, GPIOx_AFRL and GPIOx_AFRH. + * @note The configuration of the locked GPIO pins can no longer be modified + * until the next reset. + * @param GPIOx where x can be (A..H and M..P) to select the GPIO peripheral for STM32H7RSxx family + * @param GPIO_Pin specifies the port bits to be locked. + * This parameter can be any combination of GPIO_Pin_x where x can be (0..15). + * @retval None + */ +HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) +{ + __IO uint32_t tmp = GPIO_LCKR_LCKK; + + /* Check the parameters */ + assert_param(IS_GPIO_LOCK_INSTANCE(GPIOx)); + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + /* Apply lock key write sequence */ + tmp |= GPIO_Pin; + /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ + GPIOx->LCKR = tmp; + /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */ + GPIOx->LCKR = GPIO_Pin; + /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ + GPIOx->LCKR = tmp; + /* Read LCKK register. This read is mandatory to complete key lock sequence */ + tmp = GPIOx->LCKR; + + /* read again in order to confirm lock is active */ + if ((GPIOx->LCKR & GPIO_LCKR_LCKK) != 0x00u) + { + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Handle EXTI interrupt request. + * @param GPIO_Pin Specifies the port pin connected to corresponding 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) != 0U) + { + __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin); + HAL_GPIO_EXTI_Callback(GPIO_Pin); + } +} + +/** + * @brief EXTI line detection callback. + * @param GPIO_Pin Specifies the port pin connected to corresponding EXTI line. + * @retval None + */ +__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpu2d.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpu2d.c index a2eb7a880..cb8b2171e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpu2d.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_gpu2d.c @@ -1,750 +1,750 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_gpu2d.c - * @author MCD Application Team - * @brief GPU2D HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the GPU2D peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State and Errors functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Peripheral control is exclusively done by the accompanying middleware library. - - *** Interrupt mode IO operation *** - =================================== - [..] - (#) Configure the GPU2D hardware to perform graphics operation using the Third Party MW - Library APIs. - (#) Submit command List to the hardware. - (#) Wait indefinitely for the completion of submitted Command List by GPU2D hardware. - (#) Use HAL_GPU2D_IRQHandler() called under GPU2D_IRQHandler() interrupt subroutine. - (#) At the end of Command List execution HAL_GPU2D_IRQHandler() function is executed - and user can add his own function by customization of function pointer - (#) CommandListCpltCallback (member of GPU2D handle structure) to notify the upper level - about the completion of Command List execution. - - (#) Callback HAL_GPU2D_CommandListCpltCallback is invoked when the GPU2D hardware executes - the programmed command list (Command List execution completion). - - (++) This callback is called when the compilation defines USE_HAL_GPU2D_REGISTER_CALLBACKS - is set to 0 or not defined. - - (++) This callback should be implemented in the application side. It should notify - the upper level that the programmed command list is completed. - - (#) To control the GPU2D state, use the following function: HAL_GPU2D_GetState(). - - (#) To read the GPU2D error code, use the following function: HAL_GPU2D_GetError(). - - *** GPU2D HAL driver macros list *** - ============================================= - [..] - Below the list of most used macros in GPU2D HAL driver : - - (+) __HAL_GPU2D_RESET_HANDLE_STATE: Reset GPU2D handle state. - (+) __HAL_GPU2D_GET_FLAG: Get the GPU2D pending flags. - (+) __HAL_GPU2D_CLEAR_FLAG: Clear the GPU2D pending flags. - (+) __HAL_GPU2D_GET_IT_SOURCE: Check whether the specified GPU2D interrupt is enabled or not. - - *** Callback registration *** - =================================== - [..] - (#) The compilation define USE_HAL_GPU2D_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use function @ref HAL_GPU2D_RegisterCallback() to register a user callback. - - (#) Function @ref HAL_GPU2D_RegisterCallback() allows to register following callbacks: - (+) CommandListCpltCallback : callback for Command List completion. - (+) MspInitCallback : GPU2D MspInit. - (+) MspDeInitCallback : GPU2D MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - (#) Use function @ref HAL_GPU2D_UnRegisterCallback() to reset a callback to the default - weak (surcharged) function. - @ref HAL_GPU2D_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) CommandListCpltCallback : callback for Command List completion. - (+) MspInitCallback : GPU2D MspInit. - (+) MspDeInitCallback : GPU2D MspDeInit. - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using @ref HAL_GPU2D_RegisterCallback before calling @ref HAL_GPU2D_DeInit - or @ref HAL_GPU2D_Init function. - - When The compilation define USE_HAL_GPU2D_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (surcharged) callbacks are used. - - [..] - (@) You can refer to the GPU2D HAL driver header file for more useful macros - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -#ifdef HAL_GPU2D_MODULE_ENABLED -#if defined (GPU2D) - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup GPU2D GPU2D - * @brief GPU2D HAL module driver - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/** @defgroup GPU2D_Private_Macros GPU2D Private Macros - * @{ - */ - -/** @defgroup GPU2D_Write_Read Common write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in GPU2D register - * @param __INSTANCE__ GPU2D Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define GPU2D_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(*(__IO uint32_t *)(__INSTANCE__\ - + __REG__), __VALUE__) - -/** - * @brief Read a value in GPU2D register - * @param __INSTANCE__ GPU2D Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define GPU2D_ReadReg(__INSTANCE__, __REG__) READ_REG(*(__IO uint32_t *)(__INSTANCE__ + __REG__)) -/** - * @} - */ - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @defgroup GPU2D_Exported_Functions GPU2D Exported Functions - * @{ - */ - -/** @defgroup GPU2D_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * -@verbatim - =============================================================================== - ##### Initialization and Configuration functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Initialize and configure the GPU2D - (+) De-initialize the GPU2D - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the GPU2D according to the specified - * parameters in the GPU2D_InitTypeDef and create the associated handle. - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_GPU2D_Init(GPU2D_HandleTypeDef *hgpu2d) -{ - /* Check the GPU2D handle validity */ - if (hgpu2d == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); - - if (hgpu2d->State == HAL_GPU2D_STATE_RESET) - { -#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) - /* Reset Callback pointers in HAL_GPU2D_STATE_RESET only */ - hgpu2d->CommandListCpltCallback = HAL_GPU2D_CommandListCpltCallback; - if (hgpu2d->MspInitCallback == NULL) - { - hgpu2d->MspInitCallback = HAL_GPU2D_MspInit; - } - - /* Init the low level hardware */ - hgpu2d->MspInitCallback(hgpu2d); -#else /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 0 */ - /* Init the low level hardware */ - HAL_GPU2D_MspInit(hgpu2d); -#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ - - /* Allocate lock resource and initialize it */ - hgpu2d->Lock = HAL_UNLOCKED; - } - - /* Process locked */ - __HAL_LOCK(hgpu2d); - -#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) - /* Reset the CommandListCpltCallback handler */ - hgpu2d->CommandListCpltCallback = NULL; -#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ - - /* Update error code */ - hgpu2d->ErrorCode = HAL_GPU2D_ERROR_NONE; - - /* Initialize the GPU2D state*/ - hgpu2d->State = HAL_GPU2D_STATE_READY; - - /* Release Lock */ - __HAL_UNLOCK(hgpu2d); - - return HAL_OK; -} - -/** - * @brief Deinitializes the GPU2D peripheral registers to their default reset - * values. - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval None - */ -HAL_StatusTypeDef HAL_GPU2D_DeInit(GPU2D_HandleTypeDef *hgpu2d) -{ - /* Check the GPU2D handle validity */ - if (hgpu2d == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); - - /* Process locked */ - __HAL_LOCK(hgpu2d); - - if (hgpu2d->State == HAL_GPU2D_STATE_READY) - { -#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) - if (hgpu2d->MspDeInitCallback == NULL) - { - hgpu2d->MspDeInitCallback = HAL_GPU2D_MspDeInit; - } - - /* DeInit the low level hardware */ - hgpu2d->MspDeInitCallback(hgpu2d); -#else /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 0 */ - /* Carry on with de-initialization of low level hardware */ - HAL_GPU2D_MspDeInit(hgpu2d); -#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ - } - -#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) - /* Reset the CommandListCpltCallback handler */ - hgpu2d->CommandListCpltCallback = NULL; -#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ - - /* Update error code */ - hgpu2d->ErrorCode = HAL_GPU2D_ERROR_NONE; - - /* Reset the GPU2D state*/ - hgpu2d->State = HAL_GPU2D_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hgpu2d); - - return HAL_OK; -} - -/** - * @brief Initializes the GPU2D MSP. - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval None - */ -__weak void HAL_GPU2D_MspInit(GPU2D_HandleTypeDef *hgpu2d) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgpu2d); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_GPU2D_MspInit can be implemented in the user file. - */ -} - -/** - * @brief DeInitializes the GPU2D MSP. - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval None - */ -__weak void HAL_GPU2D_MspDeInit(GPU2D_HandleTypeDef *hgpu2d) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgpu2d); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_GPU2D_MspDeInit can be implemented in the user file. - */ -} - -#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User GPU2D callback - * To be used instead of the weak (surcharged) predefined callback - * @param hgpu2d GPU2D handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_GPU2D_MSPINIT_CB_ID GPU2D MspInit callback ID - * @arg @ref HAL_GPU2D_MSPDEINIT_CB_ID GPU2D MspDeInit callback ID - * @param pCallback pointer to the callback function - * @note Weak predefined callback is defined for HAL_GPU2D_MSPINIT_CB_ID and HAL_GPU2D_MSPDEINIT_CB_ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_GPU2D_RegisterCallback(GPU2D_HandleTypeDef *hgpu2d, HAL_GPU2D_CallbackIDTypeDef CallbackID, - pGPU2D_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the GPU2D handle validity */ - if (hgpu2d == NULL) - { - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hgpu2d); - - /* Check the pCallback parameter is valid or not */ - if (pCallback == NULL) - { - /* Update the error code */ - hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - else - { - if ((hgpu2d->State == HAL_GPU2D_STATE_READY) - || (hgpu2d->State == HAL_GPU2D_STATE_RESET)) - { - switch (CallbackID) - { - case HAL_GPU2D_MSPINIT_CB_ID: - hgpu2d->MspInitCallback = pCallback; - break; - - case HAL_GPU2D_MSPDEINIT_CB_ID: - hgpu2d->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - status = HAL_ERROR; - } - } - - /* Release lock */ - __HAL_UNLOCK(hgpu2d); - - return status; -} - -/** - * @brief Unregister a GPU2D callback - * GPU2D Callback is redirected to the weak (surcharged) predefined callback - * @param hgpu2d GPU2D handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_GPU2D_MSPINIT_CB_ID GPU2D MspInit callback ID - * @arg @ref HAL_GPU2D_MSPDEINIT_CB_ID GPU2D MspDeInit callback ID - * @note Callback pointers will be set to legacy weak predefined callbacks for HAL_GPU2D_MSPINIT_CB_ID and - * HAL_GPU2D_MSPDEINIT_CB_ID - * @retval status - */ -HAL_StatusTypeDef HAL_GPU2D_UnRegisterCallback(GPU2D_HandleTypeDef *hgpu2d, HAL_GPU2D_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the GPU2D handle validity */ - if (hgpu2d == NULL) - { - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hgpu2d); - - if ((HAL_GPU2D_STATE_READY == hgpu2d->State) - || (HAL_GPU2D_STATE_RESET == hgpu2d->State)) - { - switch (CallbackID) - { - case HAL_GPU2D_MSPINIT_CB_ID: - hgpu2d->MspInitCallback = HAL_GPU2D_MspInit; /* Legacy weak Msp Init */ - break; - - case HAL_GPU2D_MSPDEINIT_CB_ID: - hgpu2d->MspDeInitCallback = HAL_GPU2D_MspDeInit; /* Legacy weak Msp DeInit */ - break; - - default : - /* Update the error code */ - hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - status = HAL_ERROR; - } - - /* Release lock */ - __HAL_UNLOCK(hgpu2d); - - return status; -} - -/** - * @brief Register GPU2D Command List Complete Callback - * To be used instead of the weak (surcharged) predefined callback - * @param hgpu2d GPU2D handle - * @param pCallback pointer to the Command List Complete Callback function - * @note Weak predefined callback is defined for Command List Complete - * @retval status - */ -HAL_StatusTypeDef HAL_GPU2D_RegisterCommandListCpltCallback(GPU2D_HandleTypeDef *hgpu2d, - pGPU2D_CommandListCpltCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the GPU2D handle validity */ - if (hgpu2d == NULL) - { - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hgpu2d); - - /* Check the CallbackID is valid or not */ - if (pCallback == NULL) - { - /* Update the error code */ - hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - else - { - if ((HAL_GPU2D_STATE_READY == hgpu2d->State) - || (HAL_GPU2D_STATE_RESET == hgpu2d->State)) - { - hgpu2d->CommandListCpltCallback = pCallback; - } - else - { - status = HAL_ERROR; - } - } - - /* Release lock */ - __HAL_UNLOCK(hgpu2d); - - return status; -} - -/** - * @brief Unregister a GPU2D Command List Complete Callback - * GPU2D Command List Complete Callback is redirected to the weak (surcharged) predefined callback - * @param hgpu2d GPU2D handle - * @note Callback pointer will be invalidate (NULL value) - * @retval status - */ -HAL_StatusTypeDef HAL_GPU2D_UnRegisterCommandListCpltCallback(GPU2D_HandleTypeDef *hgpu2d) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the GPU2D handle validity */ - if (hgpu2d == NULL) - { - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hgpu2d); - - if ((hgpu2d->State == HAL_GPU2D_STATE_READY) - || (hgpu2d->State == HAL_GPU2D_STATE_RESET)) - { - hgpu2d->CommandListCpltCallback = NULL; /* Invalidate the Callback pointer */ - } - else - { - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hgpu2d); - - return status; -} -#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ - -/** - * @} - */ - - -/** @defgroup GPU2D_Exported_Functions_Group2 IO operation functions - * @brief IO operation functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Read GPU2D Register value. - (+) Write a value to GPU2D Register. - (+) handle GPU2D interrupt request. - (+) Command List Complete Transfer Complete callback. - - -@endverbatim - * @{ - */ - -/** - * @brief Read GPU2D Register. Helper function for the higher-level library. - * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @param offset The register offset from GPU2D base address to read. - * @retval Register value - */ -uint32_t HAL_GPU2D_ReadRegister(const GPU2D_HandleTypeDef *hgpu2d, uint32_t offset) -{ - uint32_t value; - - /* Check the GPU2D handle validity */ - assert_param(hgpu2d != NULL); - - /* Check the parameters */ - assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); - assert_param(IS_GPU2D_OFFSET(offset)); - - /* No locking is required since reading a register is an atomic operation - * and doesn't incur a state change in hal_gpu2d. */ - value = GPU2D_ReadReg(hgpu2d->Instance, offset); - - return value; -} - -/** - * @brief Write a value to GPU2D Register. Helper function for the higher-level library. - * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @param offset The register offset from GPU2D base address to write. - * @param value The value to be written to provided register. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_GPU2D_WriteRegister(GPU2D_HandleTypeDef *hgpu2d, uint32_t offset, uint32_t value) -{ - /* Check the GPU2D handle validity */ - assert_param(hgpu2d != NULL); - - /* Check the parameters */ - assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); - assert_param(IS_GPU2D_OFFSET(offset)); - - /* No locking is required since writing a register is an atomic operation - * and doesn't incur a state change in hal_gpu2d. */ - GPU2D_WriteReg(hgpu2d->Instance, offset, value); - - return HAL_OK; -} - -/** - * @brief Handle GPU2D interrupt request. - * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval None - */ -void HAL_GPU2D_IRQHandler(GPU2D_HandleTypeDef *hgpu2d) -{ - uint32_t isr_flags = GPU2D_ReadReg(hgpu2d->Instance, GPU2D_ITCTRL); - - /* Command List Complete Interrupt management */ - if ((isr_flags & GPU2D_FLAG_CLC) != 0U) - { - uint32_t last_cl_id; - - /* Clear the completion flag */ - __HAL_GPU2D_CLEAR_FLAG(hgpu2d, GPU2D_FLAG_CLC); - - last_cl_id = GPU2D_ReadReg(hgpu2d->Instance, GPU2D_CLID); - - /* Command List Complete Callback */ -#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) - if (hgpu2d->CommandListCpltCallback != NULL) - { - hgpu2d->CommandListCpltCallback(hgpu2d, last_cl_id); - } -#else /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 0 */ - HAL_GPU2D_CommandListCpltCallback(hgpu2d, last_cl_id); -#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ - } -} - -/** - * @brief Handle GPU2D Error interrupt request. - * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval None - */ -void HAL_GPU2D_ER_IRQHandler(GPU2D_HandleTypeDef *hgpu2d) -{ - HAL_GPU2D_ErrorCallback(hgpu2d); -} - -/** - * @brief Command List Complete callback. - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @param CmdListID Command list ID that got completed. - * @retval None - */ -__weak void HAL_GPU2D_CommandListCpltCallback(GPU2D_HandleTypeDef *hgpu2d, uint32_t CmdListID) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgpu2d); - UNUSED(CmdListID); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_GPU2D_CommandListCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Error handler callback. - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval None - */ -__weak void HAL_GPU2D_ErrorCallback(GPU2D_HandleTypeDef *hgpu2d) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hgpu2d); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_GPU2D_ErrorCallback can be implemented in the user file. - The default implementation stops the execution as an error is considered - fatal and non recoverable. - */ - - /* Infinite loop */ - for (;;) {}; -} - -/** - * @} - */ - - -/** @defgroup GPU2D_Exported_Functions_Group3 Peripheral State and Error functions - * @brief Peripheral State functions - * -@verbatim - =============================================================================== - ##### Peripheral State and Errors functions ##### - =============================================================================== - [..] - This subsection provides functions allowing to: - (+) Get the GPU2D state - (+) Get the GPU2D error code - -@endverbatim - * @{ - */ - -/** - * @brief Return the GPU2D state - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for the GPU2D. - * @retval GPU2D state - */ -HAL_GPU2D_StateTypeDef HAL_GPU2D_GetState(GPU2D_HandleTypeDef const *const hgpu2d) -{ - return hgpu2d->State; -} - -/** - * @brief Return the GPU2D error code - * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains - * the configuration information for GPU2D. - * @retval GPU2D Error Code - */ -uint32_t HAL_GPU2D_GetError(GPU2D_HandleTypeDef const *const hgpu2d) -{ - return hgpu2d->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* GPU2D */ -#endif /* HAL_GPU2D_MODULE_ENABLED */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_gpu2d.c + * @author MCD Application Team + * @brief GPU2D HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the GPU2D peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Peripheral control is exclusively done by the accompanying middleware library. + + *** Interrupt mode IO operation *** + =================================== + [..] + (#) Configure the GPU2D hardware to perform graphics operation using the Third Party MW + Library APIs. + (#) Submit command List to the hardware. + (#) Wait indefinitely for the completion of submitted Command List by GPU2D hardware. + (#) Use HAL_GPU2D_IRQHandler() called under GPU2D_IRQHandler() interrupt subroutine. + (#) At the end of Command List execution HAL_GPU2D_IRQHandler() function is executed + and user can add his own function by customization of function pointer + (#) CommandListCpltCallback (member of GPU2D handle structure) to notify the upper level + about the completion of Command List execution. + + (#) Callback HAL_GPU2D_CommandListCpltCallback is invoked when the GPU2D hardware executes + the programmed command list (Command List execution completion). + + (++) This callback is called when the compilation defines USE_HAL_GPU2D_REGISTER_CALLBACKS + is set to 0 or not defined. + + (++) This callback should be implemented in the application side. It should notify + the upper level that the programmed command list is completed. + + (#) To control the GPU2D state, use the following function: HAL_GPU2D_GetState(). + + (#) To read the GPU2D error code, use the following function: HAL_GPU2D_GetError(). + + *** GPU2D HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in GPU2D HAL driver : + + (+) __HAL_GPU2D_RESET_HANDLE_STATE: Reset GPU2D handle state. + (+) __HAL_GPU2D_GET_FLAG: Get the GPU2D pending flags. + (+) __HAL_GPU2D_CLEAR_FLAG: Clear the GPU2D pending flags. + (+) __HAL_GPU2D_GET_IT_SOURCE: Check whether the specified GPU2D interrupt is enabled or not. + + *** Callback registration *** + =================================== + [..] + (#) The compilation define USE_HAL_GPU2D_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use function @ref HAL_GPU2D_RegisterCallback() to register a user callback. + + (#) Function @ref HAL_GPU2D_RegisterCallback() allows to register following callbacks: + (+) CommandListCpltCallback : callback for Command List completion. + (+) MspInitCallback : GPU2D MspInit. + (+) MspDeInitCallback : GPU2D MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + (#) Use function @ref HAL_GPU2D_UnRegisterCallback() to reset a callback to the default + weak (surcharged) function. + @ref HAL_GPU2D_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) CommandListCpltCallback : callback for Command List completion. + (+) MspInitCallback : GPU2D MspInit. + (+) MspDeInitCallback : GPU2D MspDeInit. + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using @ref HAL_GPU2D_RegisterCallback before calling @ref HAL_GPU2D_DeInit + or @ref HAL_GPU2D_Init function. + + When The compilation define USE_HAL_GPU2D_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + [..] + (@) You can refer to the GPU2D HAL driver header file for more useful macros + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +#ifdef HAL_GPU2D_MODULE_ENABLED +#if defined (GPU2D) + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup GPU2D GPU2D + * @brief GPU2D HAL module driver + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/** @defgroup GPU2D_Private_Macros GPU2D Private Macros + * @{ + */ + +/** @defgroup GPU2D_Write_Read Common write and read registers Macros + * @{ + */ + +/** + * @brief Write a value in GPU2D register + * @param __INSTANCE__ GPU2D Instance + * @param __REG__ Register to be written + * @param __VALUE__ Value to be written in the register + * @retval None + */ +#define GPU2D_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(*(__IO uint32_t *)(__INSTANCE__\ + + __REG__), __VALUE__) + +/** + * @brief Read a value in GPU2D register + * @param __INSTANCE__ GPU2D Instance + * @param __REG__ Register to be read + * @retval Register value + */ +#define GPU2D_ReadReg(__INSTANCE__, __REG__) READ_REG(*(__IO uint32_t *)(__INSTANCE__ + __REG__)) +/** + * @} + */ + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup GPU2D_Exported_Functions GPU2D Exported Functions + * @{ + */ + +/** @defgroup GPU2D_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the GPU2D + (+) De-initialize the GPU2D + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the GPU2D according to the specified + * parameters in the GPU2D_InitTypeDef and create the associated handle. + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_GPU2D_Init(GPU2D_HandleTypeDef *hgpu2d) +{ + /* Check the GPU2D handle validity */ + if (hgpu2d == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); + + if (hgpu2d->State == HAL_GPU2D_STATE_RESET) + { +#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) + /* Reset Callback pointers in HAL_GPU2D_STATE_RESET only */ + hgpu2d->CommandListCpltCallback = HAL_GPU2D_CommandListCpltCallback; + if (hgpu2d->MspInitCallback == NULL) + { + hgpu2d->MspInitCallback = HAL_GPU2D_MspInit; + } + + /* Init the low level hardware */ + hgpu2d->MspInitCallback(hgpu2d); +#else /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 0 */ + /* Init the low level hardware */ + HAL_GPU2D_MspInit(hgpu2d); +#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ + + /* Allocate lock resource and initialize it */ + hgpu2d->Lock = HAL_UNLOCKED; + } + + /* Process locked */ + __HAL_LOCK(hgpu2d); + +#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) + /* Reset the CommandListCpltCallback handler */ + hgpu2d->CommandListCpltCallback = NULL; +#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ + + /* Update error code */ + hgpu2d->ErrorCode = HAL_GPU2D_ERROR_NONE; + + /* Initialize the GPU2D state*/ + hgpu2d->State = HAL_GPU2D_STATE_READY; + + /* Release Lock */ + __HAL_UNLOCK(hgpu2d); + + return HAL_OK; +} + +/** + * @brief Deinitializes the GPU2D peripheral registers to their default reset + * values. + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval None + */ +HAL_StatusTypeDef HAL_GPU2D_DeInit(GPU2D_HandleTypeDef *hgpu2d) +{ + /* Check the GPU2D handle validity */ + if (hgpu2d == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); + + /* Process locked */ + __HAL_LOCK(hgpu2d); + + if (hgpu2d->State == HAL_GPU2D_STATE_READY) + { +#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) + if (hgpu2d->MspDeInitCallback == NULL) + { + hgpu2d->MspDeInitCallback = HAL_GPU2D_MspDeInit; + } + + /* DeInit the low level hardware */ + hgpu2d->MspDeInitCallback(hgpu2d); +#else /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 0 */ + /* Carry on with de-initialization of low level hardware */ + HAL_GPU2D_MspDeInit(hgpu2d); +#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ + } + +#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) + /* Reset the CommandListCpltCallback handler */ + hgpu2d->CommandListCpltCallback = NULL; +#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ + + /* Update error code */ + hgpu2d->ErrorCode = HAL_GPU2D_ERROR_NONE; + + /* Reset the GPU2D state*/ + hgpu2d->State = HAL_GPU2D_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hgpu2d); + + return HAL_OK; +} + +/** + * @brief Initializes the GPU2D MSP. + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval None + */ +__weak void HAL_GPU2D_MspInit(GPU2D_HandleTypeDef *hgpu2d) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgpu2d); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_GPU2D_MspInit can be implemented in the user file. + */ +} + +/** + * @brief DeInitializes the GPU2D MSP. + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval None + */ +__weak void HAL_GPU2D_MspDeInit(GPU2D_HandleTypeDef *hgpu2d) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgpu2d); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_GPU2D_MspDeInit can be implemented in the user file. + */ +} + +#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User GPU2D callback + * To be used instead of the weak (surcharged) predefined callback + * @param hgpu2d GPU2D handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_GPU2D_MSPINIT_CB_ID GPU2D MspInit callback ID + * @arg @ref HAL_GPU2D_MSPDEINIT_CB_ID GPU2D MspDeInit callback ID + * @param pCallback pointer to the callback function + * @note Weak predefined callback is defined for HAL_GPU2D_MSPINIT_CB_ID and HAL_GPU2D_MSPDEINIT_CB_ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_GPU2D_RegisterCallback(GPU2D_HandleTypeDef *hgpu2d, HAL_GPU2D_CallbackIDTypeDef CallbackID, + pGPU2D_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the GPU2D handle validity */ + if (hgpu2d == NULL) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hgpu2d); + + /* Check the pCallback parameter is valid or not */ + if (pCallback == NULL) + { + /* Update the error code */ + hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + else + { + if ((hgpu2d->State == HAL_GPU2D_STATE_READY) + || (hgpu2d->State == HAL_GPU2D_STATE_RESET)) + { + switch (CallbackID) + { + case HAL_GPU2D_MSPINIT_CB_ID: + hgpu2d->MspInitCallback = pCallback; + break; + + case HAL_GPU2D_MSPDEINIT_CB_ID: + hgpu2d->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + status = HAL_ERROR; + } + } + + /* Release lock */ + __HAL_UNLOCK(hgpu2d); + + return status; +} + +/** + * @brief Unregister a GPU2D callback + * GPU2D Callback is redirected to the weak (surcharged) predefined callback + * @param hgpu2d GPU2D handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_GPU2D_MSPINIT_CB_ID GPU2D MspInit callback ID + * @arg @ref HAL_GPU2D_MSPDEINIT_CB_ID GPU2D MspDeInit callback ID + * @note Callback pointers will be set to legacy weak predefined callbacks for HAL_GPU2D_MSPINIT_CB_ID and + * HAL_GPU2D_MSPDEINIT_CB_ID + * @retval status + */ +HAL_StatusTypeDef HAL_GPU2D_UnRegisterCallback(GPU2D_HandleTypeDef *hgpu2d, HAL_GPU2D_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the GPU2D handle validity */ + if (hgpu2d == NULL) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hgpu2d); + + if ((HAL_GPU2D_STATE_READY == hgpu2d->State) + || (HAL_GPU2D_STATE_RESET == hgpu2d->State)) + { + switch (CallbackID) + { + case HAL_GPU2D_MSPINIT_CB_ID: + hgpu2d->MspInitCallback = HAL_GPU2D_MspInit; /* Legacy weak Msp Init */ + break; + + case HAL_GPU2D_MSPDEINIT_CB_ID: + hgpu2d->MspDeInitCallback = HAL_GPU2D_MspDeInit; /* Legacy weak Msp DeInit */ + break; + + default : + /* Update the error code */ + hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + status = HAL_ERROR; + } + + /* Release lock */ + __HAL_UNLOCK(hgpu2d); + + return status; +} + +/** + * @brief Register GPU2D Command List Complete Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hgpu2d GPU2D handle + * @param pCallback pointer to the Command List Complete Callback function + * @note Weak predefined callback is defined for Command List Complete + * @retval status + */ +HAL_StatusTypeDef HAL_GPU2D_RegisterCommandListCpltCallback(GPU2D_HandleTypeDef *hgpu2d, + pGPU2D_CommandListCpltCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the GPU2D handle validity */ + if (hgpu2d == NULL) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hgpu2d); + + /* Check the CallbackID is valid or not */ + if (pCallback == NULL) + { + /* Update the error code */ + hgpu2d->ErrorCode |= HAL_GPU2D_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + else + { + if ((HAL_GPU2D_STATE_READY == hgpu2d->State) + || (HAL_GPU2D_STATE_RESET == hgpu2d->State)) + { + hgpu2d->CommandListCpltCallback = pCallback; + } + else + { + status = HAL_ERROR; + } + } + + /* Release lock */ + __HAL_UNLOCK(hgpu2d); + + return status; +} + +/** + * @brief Unregister a GPU2D Command List Complete Callback + * GPU2D Command List Complete Callback is redirected to the weak (surcharged) predefined callback + * @param hgpu2d GPU2D handle + * @note Callback pointer will be invalidate (NULL value) + * @retval status + */ +HAL_StatusTypeDef HAL_GPU2D_UnRegisterCommandListCpltCallback(GPU2D_HandleTypeDef *hgpu2d) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the GPU2D handle validity */ + if (hgpu2d == NULL) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hgpu2d); + + if ((hgpu2d->State == HAL_GPU2D_STATE_READY) + || (hgpu2d->State == HAL_GPU2D_STATE_RESET)) + { + hgpu2d->CommandListCpltCallback = NULL; /* Invalidate the Callback pointer */ + } + else + { + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hgpu2d); + + return status; +} +#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ + +/** + * @} + */ + + +/** @defgroup GPU2D_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Read GPU2D Register value. + (+) Write a value to GPU2D Register. + (+) handle GPU2D interrupt request. + (+) Command List Complete Transfer Complete callback. + + +@endverbatim + * @{ + */ + +/** + * @brief Read GPU2D Register. Helper function for the higher-level library. + * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @param offset The register offset from GPU2D base address to read. + * @retval Register value + */ +uint32_t HAL_GPU2D_ReadRegister(const GPU2D_HandleTypeDef *hgpu2d, uint32_t offset) +{ + uint32_t value; + + /* Check the GPU2D handle validity */ + assert_param(hgpu2d != NULL); + + /* Check the parameters */ + assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); + assert_param(IS_GPU2D_OFFSET(offset)); + + /* No locking is required since reading a register is an atomic operation + * and doesn't incur a state change in hal_gpu2d. */ + value = GPU2D_ReadReg(hgpu2d->Instance, offset); + + return value; +} + +/** + * @brief Write a value to GPU2D Register. Helper function for the higher-level library. + * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @param offset The register offset from GPU2D base address to write. + * @param value The value to be written to provided register. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_GPU2D_WriteRegister(GPU2D_HandleTypeDef *hgpu2d, uint32_t offset, uint32_t value) +{ + /* Check the GPU2D handle validity */ + assert_param(hgpu2d != NULL); + + /* Check the parameters */ + assert_param(IS_GPU2D_ALL_INSTANCE(hgpu2d->Instance)); + assert_param(IS_GPU2D_OFFSET(offset)); + + /* No locking is required since writing a register is an atomic operation + * and doesn't incur a state change in hal_gpu2d. */ + GPU2D_WriteReg(hgpu2d->Instance, offset, value); + + return HAL_OK; +} + +/** + * @brief Handle GPU2D interrupt request. + * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval None + */ +void HAL_GPU2D_IRQHandler(GPU2D_HandleTypeDef *hgpu2d) +{ + uint32_t isr_flags = GPU2D_ReadReg(hgpu2d->Instance, GPU2D_ITCTRL); + + /* Command List Complete Interrupt management */ + if ((isr_flags & GPU2D_FLAG_CLC) != 0U) + { + uint32_t last_cl_id; + + /* Clear the completion flag */ + __HAL_GPU2D_CLEAR_FLAG(hgpu2d, GPU2D_FLAG_CLC); + + last_cl_id = GPU2D_ReadReg(hgpu2d->Instance, GPU2D_CLID); + + /* Command List Complete Callback */ +#if (USE_HAL_GPU2D_REGISTER_CALLBACKS == 1) + if (hgpu2d->CommandListCpltCallback != NULL) + { + hgpu2d->CommandListCpltCallback(hgpu2d, last_cl_id); + } +#else /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 0 */ + HAL_GPU2D_CommandListCpltCallback(hgpu2d, last_cl_id); +#endif /* USE_HAL_GPU2D_REGISTER_CALLBACKS = 1 */ + } +} + +/** + * @brief Handle GPU2D Error interrupt request. + * @param hgpu2d Pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval None + */ +void HAL_GPU2D_ER_IRQHandler(GPU2D_HandleTypeDef *hgpu2d) +{ + HAL_GPU2D_ErrorCallback(hgpu2d); +} + +/** + * @brief Command List Complete callback. + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @param CmdListID Command list ID that got completed. + * @retval None + */ +__weak void HAL_GPU2D_CommandListCpltCallback(GPU2D_HandleTypeDef *hgpu2d, uint32_t CmdListID) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgpu2d); + UNUSED(CmdListID); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_GPU2D_CommandListCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Error handler callback. + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval None + */ +__weak void HAL_GPU2D_ErrorCallback(GPU2D_HandleTypeDef *hgpu2d) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hgpu2d); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_GPU2D_ErrorCallback can be implemented in the user file. + The default implementation stops the execution as an error is considered + fatal and non recoverable. + */ + + /* Infinite loop */ + for (;;) {}; +} + +/** + * @} + */ + + +/** @defgroup GPU2D_Exported_Functions_Group3 Peripheral State and Error functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to: + (+) Get the GPU2D state + (+) Get the GPU2D error code + +@endverbatim + * @{ + */ + +/** + * @brief Return the GPU2D state + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for the GPU2D. + * @retval GPU2D state + */ +HAL_GPU2D_StateTypeDef HAL_GPU2D_GetState(GPU2D_HandleTypeDef const *const hgpu2d) +{ + return hgpu2d->State; +} + +/** + * @brief Return the GPU2D error code + * @param hgpu2d pointer to a GPU2D_HandleTypeDef structure that contains + * the configuration information for GPU2D. + * @retval GPU2D Error Code + */ +uint32_t HAL_GPU2D_GetError(GPU2D_HandleTypeDef const *const hgpu2d) +{ + return hgpu2d->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* GPU2D */ +#endif /* HAL_GPU2D_MODULE_ENABLED */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hash.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hash.c index a3767e5c1..764382228 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hash.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hash.c @@ -1,3170 +1,3170 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_hash.c - * @author MCD Application Team - * @brief HASH HAL module driver. - * This file provides firmware functions to manage HASH peripheral - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 __HAL_RCC_HASH_CLK_ENABLE() - (##) When resorting to interrupt-based APIs (e.g. HAL_HASH_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() API - (##) When resorting to DMA-based APIs (e.g. HAL_HASH_Start_DMA()) - (+++) Enable the DMA interface clock - (+++) Configure and enable one DMA to manage data transfer from - memory to peripheral (input DMA). 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: use - HAL_NVIC_SetPriority() and - HAL_NVIC_EnableIRQ() - - (#)Initialize the HASH HAL using HAL_HASH_Init(). This function: - (##) resorts to HAL_HASH_MspInit() for low-level initialization, - (##) configures the data type: no swap, half word swap, bit swap or byte swap, - (##) configures the Algorithm : MD5, SHA1 or SHA2 - - (#)Three processing schemes 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_Start() for HASH or HAL_HMAC_Start() for HMAC - (##) Interrupt mode: processing APIs are not blocking functions - i.e. they process the data under interrupt, - e.g. HAL_HASH_Start_IT() for HASH or HAL_HMAC_Start_IT() for HMAC - (##) 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_Start_DMA() for HASH or HAL_HMAC_Start_DMA() for HMAC. - - (#)When the processing function is called after HAL_HASH_Init(), the HASH peripheral is - initialized and processes the buffer fed in input. When the input data have all been - fed to the Peripheral, the digest computation can start. - - (#)Multi-buffer processing HASH and HMAC are possible in polling, interrupt and DMA modes. - (##) In polling mode, API HAL_HASH_Accumulate()/HAL_HASH_HMAC_Accumulate() must be called - for each input buffer, except for the last one. - User must resort to HAL_HASH_AccumulateLast()/HAL_HASH_HMAC_AccumulateLast() - to enter the last one and retrieve as well the computed digest. - - (##) In interrupt mode, API HAL_HASH_Accumulate_IT()/HAL_HASH_HMAC_Accumulate_IT() must - be called for each input buffer, except for the last one. - User must resort to HAL_HASH_AccumulateLast_IT()/HAL_HASH_HMAC_AccumulateLast_IT() - to enter the last one and retrieve as well the computed digest. - - (##) In DMA mode, once initialization is done, MDMAT bit must be set through - __HAL_HASH_SET_MDMAT() macro. - From that point, each buffer can be fed to the Peripheral through HAL_HASH_Start_DMA() API - for HASH and HAL_HASH_HMAC_Start_DMA() API for HMAC . - Before entering the last buffer, reset the MDMAT bit with __HAL_HASH_RESET_MDMAT() - macro then wrap-up the HASH processing in feeding the last input buffer through the - same API HAL_HASH_Start_DMA()for HASH and HAL_HASH_HMAC_Start_DMA() API for HMAC and - retrieve as well the computed digest. - - (#)To use this driver (version 2.0.0) with application developed with old driver (version 1.0.0) user have to: - (##) Add Algorithm as parameter like DataType or KeySize. - (##) Use new API HAL_HASH_Start() for HASH and HAL_HASH_HMAC_Start() for HMAC processing instead of old API - like HAL_HASH_SHA1_Start and HAL_HMAC_SHA1_Start. - - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#if defined (HASH) - -/** @defgroup HASH HASH - * @brief HASH HAL module driver. - * @{ - */ - -#ifdef HAL_HASH_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup HASH_Private_Defines HASH Private Defines - * @{ - */ -#define HASH_TIMEOUTVALUE 1000U /*!< Time-out value */ -#define BLOCK_64B 64U /*!< block Size equal to 64 bytes */ -#define BLOCK_128B 128U /*!< block Size equal to 128 bytes */ -/** - * @} - */ - -/** @defgroup HASH_Number_Of_CSR_Registers HASH Number of Context Swap Registers - * @{ - */ -#define HASH_NUMBER_OF_CSR_REGISTERS 103U /*!< Number of Context Swap Registers */ -/** - * @} - */ - -/* Private Constants ---------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup HASH_Private_Functions HASH Private Functions - * @{ - */ -static void HASH_GetDigest(const HASH_HandleTypeDef *hhash, const uint8_t *pMsgDigest, uint8_t Size); -static void HASH_WriteData(HASH_HandleTypeDef *hhash, const uint8_t *pInBuffer, uint32_t Size); -static HAL_StatusTypeDef HASH_WriteData_IT(HASH_HandleTypeDef *hhash); -static void HASH_DMAXferCplt(DMA_HandleTypeDef *hdma); -static void HASH_DMAError(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, - uint32_t Timeout); -/** - * @} - */ - -/* Exported functions ---------------------------------------------------------*/ - -/** @defgroup HASH_Exported_Functions HASH Exported Functions - * @{ - */ - -/** @defgroup HASH_Exported_Functions_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 create the associated handle - (+) DeInitialize the HASH peripheral - (+) Initialize the HASH MCU Specific Package (MSP) - (+) DeInitialize the HASH MSP - (+) Configure HASH (HAL_HASH_SetConfig) with the specified parameters in the HASH_ConfigTypeDef - Parameters which are configured in This section are : - (+) Data Type : no swap, half word swap, bit swap or byte swap - (+) Algorithm : MD5,SHA1 or SHA2 - (+) Get HASH configuration (HAL_HASH_GetConfig) from the specified parameters in the HASH_HandleTypeDef - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the HASH according to the specified parameters in the - HASH_HandleTypeDef and create the associated handle. - * @note Only Algorithm and DATATYPE bits of HASH Peripheral are set by HAL_HASH_Init(), - * other configuration bits are set by HASH or HMAC processing APIs. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_Init(HASH_HandleTypeDef *hhash) -{ - uint32_t cr_value; - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_HASH_DATATYPE(hhash->Init.DataType)); - assert_param(IS_HASH_ALGORITHM(hhash->Init.Algorithm)); - -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - if (hhash->State == HAL_HASH_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hhash->Lock = HAL_UNLOCKED; - - /* Reset Callback pointers in HAL_HASH_STATE_RESET only */ - hhash->InCpltCallback = HAL_HASH_InCpltCallback; /* Legacy weak InCpltCallback */ - hhash->DgstCpltCallback = HAL_HASH_DgstCpltCallback; /* Legacy weak DgstCpltCallback */ - hhash->ErrorCallback = HAL_HASH_ErrorCallback; /* Legacy weak ErrorCallback */ - if (hhash->MspInitCallback == NULL) - { - hhash->MspInitCallback = HAL_HASH_MspInit; - } - - /* Init the low level hardware */ - hhash->MspInitCallback(hhash); - } -#else - if (hhash->State == HAL_HASH_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hhash->Lock = HAL_UNLOCKED; - - /* Init the low level hardware */ - HAL_HASH_MspInit(hhash); - } -#endif /* (USE_HAL_HASH_REGISTER_CALLBACKS) */ - - /* Set the key size, data type and Algorithm */ - cr_value = (uint32_t)(hhash->Init.DataType | hhash->Init.Algorithm); - /* Set the key size, data type, algorithm and mode */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_DATATYPE | HASH_CR_ALGO | HASH_CR_INIT, cr_value); - - /* Change HASH phase to Ready */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Change HASH state to Ready */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset error code field */ - hhash->ErrorCode = HAL_HASH_ERROR_NONE; - -#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) - /* Reset suspension request flag */ - hhash->SuspendRequest = HAL_HASH_SUSPEND_NONE; -#endif /* (USE_HAL_HASH_SUSPEND_RESUME) */ - /* Return function status */ - return HAL_OK; -} - -/** - * @brief DeInitialize the HASH peripheral. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_DeInit(HASH_HandleTypeDef *hhash) -{ - /* Check the HASH handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Change the default HASH phase */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Reset HashInCount */ - hhash->HashInCount = 0U; - - /* Reset multi buffers accumulation flag */ - hhash->Accumulation = 0U; - -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - if (hhash->MspDeInitCallback == NULL) - { - hhash->MspDeInitCallback = HAL_HASH_MspDeInit; - } - - /* DeInit the low level hardware */ - hhash->MspDeInitCallback(hhash); -#else - /* DeInit the low level hardware: CLOCK, NVIC */ - HAL_HASH_MspDeInit(hhash); -#endif /* (USE_HAL_HASH_REGISTER_CALLBACKS) */ - - /* Set the HASH state to Ready */ - hhash->State = HAL_HASH_STATE_RESET; - - __HAL_UNLOCK(hhash); - - return HAL_OK; -} - -/** - * @brief Configure the HASH according to the specified - * parameters in the HASH_ConfigTypeDef - * @param hhash pointer to a HASH_HandleTypeDef structure - * @param pConf pointer to a HASH_ConfigTypeDef structure that contains - * the configuration information for HASH module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_SetConfig(HASH_HandleTypeDef *hhash, HASH_ConfigTypeDef *pConf) -{ - uint32_t cr_value; - - /* Check the HASH handle allocation */ - if ((hhash == NULL) || (pConf == NULL)) - { - return HAL_ERROR; - } - - /* Check parameters */ - assert_param(IS_HASH_DATATYPE(pConf->DataType)); - assert_param(IS_HASH_ALGORITHM(pConf->Algorithm)); - - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - __HAL_LOCK(hhash); - - /* Set HASH parameters */ - hhash->Init.DataType = pConf->DataType; - hhash->Init.pKey = pConf->pKey; - hhash->Init.Algorithm = pConf->Algorithm; - hhash->Init.KeySize = pConf->KeySize; - - /* Set the key size, data type and Algorithm */ - cr_value = (uint32_t)(hhash->Init.DataType | hhash->Init.Algorithm); - /* Set the key size, data type, algorithm and mode */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_DATATYPE | HASH_CR_ALGO | HASH_CR_INIT, cr_value); - - /* Change HASH phase to Ready */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Change HASH state to Ready */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset error code field */ - hhash->ErrorCode = HAL_HASH_ERROR_NONE; - - __HAL_UNLOCK(hhash); - - return HAL_OK; - - } - else - { - /* Busy error code field */ - hhash->ErrorCode |= HAL_HASH_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Get HASH Configuration parameters in associated handle - * @param pConf pointer to a HASH_HandleTypeDef structure - * @param hhash pointer to a HASH_ConfigTypeDef structure that contains - * the configuration information for HASH module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_GetConfig(HASH_HandleTypeDef *hhash, HASH_ConfigTypeDef *pConf) -{ - - /* Check the HASH handle allocation */ - if ((hhash == NULL) || (pConf == NULL)) - { - return HAL_ERROR; - } - - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - __HAL_LOCK(hhash); - - /* Set HASH parameters */ - pConf->DataType = hhash->Init.DataType; - pConf->pKey = hhash->Init.pKey; - pConf->Algorithm = hhash->Init.Algorithm; - pConf->KeySize = hhash->Init.KeySize; - - /* Change HASH state to Ready */ - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - - return HAL_OK; - - } - else - { - /* Busy error code field */ - hhash->ErrorCode |= HAL_HASH_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Initialize the HASH MSP. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval None - */ -__weak void HAL_HASH_MspInit(HASH_HandleTypeDef *hhash) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* NOTE : This function should not be modified; when the callback is needed, - HAL_HASH_MspInit() can be implemented in the user file. - */ -} - -/** - * @brief DeInitialize the HASH MSP. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval None - */ -__weak void HAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* NOTE : This function should not be modified; when the callback is needed, - HAL_HASH_MspDeInit() can be implemented in the user file. - */ -} - - -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User HASH Callback - * To be used instead of the weak (overridden) predefined callback - * @param hhash HASH handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg HAL_HASH_INPUTCPLT_CB_ID input completion callback ID - * @arg HAL_HASH_DGSTCPLT_CB_ID digest computation completion callback ID - * @arg HAL_HASH_ERROR_CB_ID error callback ID - * @arg HAL_HASH_MSPINIT_CB_ID MspInit callback ID - * @arg HAL_HASH_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_HASH_RegisterCallback(HASH_HandleTypeDef *hhash, HAL_HASH_CallbackIDTypeDef CallbackID, - pHASH_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hhash->State == HAL_HASH_STATE_READY) - { - switch (CallbackID) - { - case HAL_HASH_INPUTCPLT_CB_ID : - hhash->InCpltCallback = pCallback; - break; - - case HAL_HASH_DGSTCPLT_CB_ID : - hhash->DgstCpltCallback = pCallback; - break; - - case HAL_HASH_ERROR_CB_ID : - hhash->ErrorCallback = pCallback; - break; - - case HAL_HASH_MSPINIT_CB_ID : - hhash->MspInitCallback = pCallback; - break; - - case HAL_HASH_MSPDEINIT_CB_ID : - hhash->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hhash->State == HAL_HASH_STATE_RESET) - { - switch (CallbackID) - { - case HAL_HASH_MSPINIT_CB_ID : - hhash->MspInitCallback = pCallback; - break; - - case HAL_HASH_MSPDEINIT_CB_ID : - hhash->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a HASH Callback - * HASH Callback is redirected to the weak (overridden) predefined callback - * @param hhash HASH handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg HAL_HASH_INPUTCPLT_CB_ID HASH input completion Callback ID - * @arg HAL_HASH_DGSTCPLT_CB_ID HASH digest computation completion Callback ID - * @arg HAL_HASH_ERROR_CB_ID HASH error Callback ID - * @arg HAL_HASH_MSPINIT_CB_ID HASH MspInit callback ID - * @arg HAL_HASH_MSPDEINIT_CB_ID HASH MspDeInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_HASH_UnRegisterCallback(HASH_HandleTypeDef *hhash, HAL_HASH_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - - if (hhash->State == HAL_HASH_STATE_READY) - { - switch (CallbackID) - { - case HAL_HASH_INPUTCPLT_CB_ID : - hhash->InCpltCallback = HAL_HASH_InCpltCallback; /* Legacy weak input completion callback */ - break; - - case HAL_HASH_DGSTCPLT_CB_ID : - hhash->DgstCpltCallback = HAL_HASH_DgstCpltCallback; /* Legacy weak digest computation - completion callback */ - break; - - case HAL_HASH_ERROR_CB_ID : - hhash->ErrorCallback = HAL_HASH_ErrorCallback; /* Legacy weak error callback */ - break; - - case HAL_HASH_MSPINIT_CB_ID : - hhash->MspInitCallback = HAL_HASH_MspInit; /* Legacy weak MspInit Callback */ - break; - - case HAL_HASH_MSPDEINIT_CB_ID : - hhash->MspDeInitCallback = HAL_HASH_MspDeInit; /* Legacy weak MspDeInit Callback */ - break; - - default : - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hhash->State == HAL_HASH_STATE_RESET) - { - switch (CallbackID) - { - case HAL_HASH_MSPINIT_CB_ID : - hhash->MspInitCallback = HAL_HASH_MspInit; /* Legacy weak MspInit Callback */ - break; - - case HAL_HASH_MSPDEINIT_CB_ID : - hhash->MspDeInitCallback = HAL_HASH_MspDeInit; /* Legacy weak MspDeInit Callback */ - break; - - default : - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - -#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) -/** - * @brief Save the HASH context in case of processing suspension. - * @param hhash HASH handle. - * @param pMemBuffer pointer to the memory buffer where the HASH context - * is saved. - * @note The IMR, STR, CR then all the CSR registers are saved - * in that order. Only the r/w bits are read to be restored later on. - * @note By default, all the context swap registers (there are - * HASH_NUMBER_OF_CSR_REGISTERS of those) are saved. - * @note pMemBuffer points to a buffer allocated by the user. The buffer size - * must be at least (HASH_NUMBER_OF_CSR_REGISTERS + 3) * 4 uint8 long. - * @retval None - */ -void HAL_HASH_Suspend(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer) -{ - uint32_t mem_ptr = (uint32_t)pMemBuffer; - uint32_t csr_ptr = (uint32_t)(hhash->Instance->CSR); - uint32_t i; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* Save IMR register content */ - *(uint32_t *)(mem_ptr) = READ_BIT(hhash->Instance->IMR, HASH_IT_DINI | HASH_IT_DCI); - mem_ptr += 4U; - /* Save STR register content */ - *(uint32_t *)(mem_ptr) = READ_BIT(hhash->Instance->STR, HASH_STR_NBLW); - mem_ptr += 4U; - /* Save CR register content */ - *(uint32_t *)(mem_ptr) = READ_BIT(hhash->Instance->CR, HASH_CR_DMAE | HASH_CR_DATATYPE | HASH_CR_MODE | HASH_CR_ALGO | - HASH_CR_LKEY | HASH_CR_MDMAT); - - mem_ptr += 4U; - /* By default, save all CSRs registers */ - for (i = HASH_NUMBER_OF_CSR_REGISTERS; i > 0U; i--) - { - *(uint32_t *)(mem_ptr) = *(uint32_t *)(csr_ptr); - mem_ptr += 4U; - csr_ptr += 4U; - } - /* Save low-priority block HASH handle parameters */ - hhash->Init_saved = hhash->Init; - hhash->pHashOutBuffPtr_saved = hhash->pHashOutBuffPtr; - hhash->HashInCount_saved = hhash->HashInCount; - hhash->Size_saved = hhash->Size; - hhash->pHashInBuffPtr_saved = hhash->pHashInBuffPtr; - hhash->Phase_saved = hhash->Phase; - hhash->pHashKeyBuffPtr_saved = hhash->pHashKeyBuffPtr; -} - - -/** - * @brief Restore the HASH context in case of processing resumption. - * @param hhash HASH handle. - * @param pMemBuffer pointer to the memory buffer where the HASH context - * is stored. - * @note The IMR, STR, CR then all the CSR registers are restored - * in that order. Only the r/w bits are restored. - * @note By default, all the context swap registers (HASH_NUMBER_OF_CSR_REGISTERS - * of those) are restored (all of them have been saved by default - * beforehand). - * @retval None - */ -void HAL_HASH_Resume(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer) -{ - uint32_t mem_ptr = (uint32_t)pMemBuffer; - uint32_t csr_ptr = (uint32_t)(hhash->Instance->CSR); - uint32_t i; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* Restore IMR register content */ - WRITE_REG(hhash->Instance->IMR, (*(uint32_t *)(mem_ptr))); - mem_ptr += 4U; - /* Restore STR register content */ - WRITE_REG(hhash->Instance->STR, (*(uint32_t *)(mem_ptr))); - mem_ptr += 4U; - /* Restore CR register content */ - WRITE_REG(hhash->Instance->CR, (*(uint32_t *)(mem_ptr))); - mem_ptr += 4U; - - /* Reset the HASH processor before restoring the Context - Swap Registers (CSR) */ - SET_BIT(hhash->Instance->CR, HASH_CR_INIT); - - - /* By default, restore all CSR registers */ - for (i = HASH_NUMBER_OF_CSR_REGISTERS; i > 0U; i--) - { - WRITE_REG((*(uint32_t *)(csr_ptr)), (*(uint32_t *)(mem_ptr))); - mem_ptr += 4U; - csr_ptr += 4U; - } - - /* Restore low-priority block HASH handle parameters */ - hhash->Init = hhash->Init_saved; - hhash->pHashOutBuffPtr = hhash->pHashOutBuffPtr_saved; - hhash->HashInCount = hhash->HashInCount_saved; - hhash->Size = hhash->Size_saved; - hhash->pHashInBuffPtr = hhash->pHashInBuffPtr_saved; - hhash->Phase = hhash->Phase_saved; - hhash->State = HAL_HASH_STATE_SUSPENDED; - hhash->pHashKeyBuffPtr = hhash->pHashKeyBuffPtr_saved; -} - -/** - * @brief Initiate HASH processing suspension when in interruption mode. - * @param hhash HASH handle. - * @note Set the handle field SuspendRequest to the appropriate value so that - * the on-going HASH processing is suspended as soon as the required - * conditions are met. Note that the actual suspension is carried out - * by the functions HASH_WriteData() in polling mode and HASH_IT() in - * interruption mode. - * @retval None - */ -HAL_StatusTypeDef HAL_HASH_ProcessSuspend(HASH_HandleTypeDef *hhash) -{ - uint32_t remainingwords; /*remaining number in of source block to be transferred.*/ - uint32_t nbbytePartialHash = (((hhash->Instance->SR) >> 16U) * 4U); /* Nb byte to enter in HASH fifo - to trig a partial HASH computation*/ - uint32_t sizeinwords;/* number in word of source block to be transferred.*/ - - /* suspension in DMA mode*/ - if (__HAL_HASH_GET_FLAG(hhash, HASH_FLAG_DMAS) != RESET) - { - if (hhash->State == HAL_HASH_STATE_READY) - { - return HAL_ERROR; - } - else - { - - /* Clear the DMAE bit to disable the DMA interface */ - CLEAR_BIT(HASH->CR, HASH_CR_DMAE); - - /* Wait until the last DMA transfer is complete (DMAS = 0 in the HASH_SR register) */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DMAS, SET, HASH_TIMEOUTVALUE) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* At this point, DMA interface is disabled and no transfer is on-going */ - /* Retrieve from the DMA handle how many words remain to be written */ - /* DMA3 used, DMA_CBR1_BNDT in bytes, DMA_CSR_FIFOL in words */ - remainingwords = ((((DMA_Channel_TypeDef *)hhash->hdmain->Instance)->CBR1) \ - & DMA_CBR1_BNDT) / 4U; - remainingwords += ((((DMA_Channel_TypeDef *)hhash->hdmain->Instance)->CSR) \ - & DMA_CSR_FIFOL) >> DMA_CSR_FIFOL_Pos; - - if (remainingwords <= nbbytePartialHash) - { - /* No suspension attempted since almost to the end of the transferred data. */ - /* Best option for user code is to wrap up low priority message hashing */ - return HAL_ERROR; - } - - /* Disable DMA channel */ - /* Note that the Abort function will - - Clear the transfer error flags - - Unlock - - Set the State - */ - if (HAL_DMA_Abort(hhash->hdmain) != HAL_OK) - { - return HAL_ERROR; - } - - if (__HAL_HASH_GET_FLAG(hhash, HASH_FLAG_DCIS) != RESET) - { - return HAL_ERROR; - } - - /* Wait until the hash processor is ready (no block is being processed), that is wait for DINIS=1 in HASH_SR */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DINIS, RESET, HASH_TIMEOUTVALUE) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Compute how many words were supposed to be transferred by DMA */ - sizeinwords = (((hhash->Size % 4U) != 0U) ? \ - ((hhash->Size + 3U) / 4U) : (hhash->Size / 4U)); - /* Accordingly, update the input pointer that points at the next word to be - transferred to the Peripheral by DMA */ - hhash->pHashInBuffPtr += 4U * (sizeinwords - remainingwords) ; - - /* And store in HashInCount the remaining size to transfer (in bytes) */ - hhash->HashInCount = 4U * remainingwords; - - - hhash->State = HAL_HASH_STATE_SUSPENDED; - __HAL_UNLOCK(hhash); - return HAL_OK; - } - - } - else /* suspension when in interruption mode*/ - { - /* Set Handle Suspend Request field */ - hhash->SuspendRequest = HAL_HASH_SUSPEND; - return HAL_OK; - } -} -#endif /* USE_HAL_HASH_SUSPEND_RESUME */ -/** - * @} - */ - - -/** @defgroup HASH_Exported_Functions_Group2 HASH processing functions - * @brief HASH processing functions using different mode. - * -@verbatim - =============================================================================== - ##### HASH processing functions ##### - =============================================================================== - [..] This section provides API allowing to calculate the hash value using - one of the HASH algorithms supported by the peripheral. - - [..] For a single buffer to be hashed, user can resort to one of three processing - functions available . - (+) Polling mode : HAL_HASH_Start() - (+) Interrupt mode : HAL_HASH_Start_IT() - (+) DMA mode : HAL_HASH_Start_DMA() - - [..] In case of multi-buffer HASH processing (a single digest is computed while - several buffers are fed to the Peripheral), the user can resort to successive calls - to : - (+) Polling mode : HAL_HASH_Accumulate() and wrap-up the digest computation by a call - to HAL_HASH_AccumulateLast() - (+) Interrupt mode : HAL_HASH_Accumulate_IT() and wrap-up the digest computation by a call - to HAL_HASH_AccumulateLast_IT() - (+) DMA mode : HAL_HASH_Start_DMA(), MDMAT bit must be set through __HAL_HASH_SET_MDMAT() macro, - before entering the last buffer, reset the MDMAT bit with __HAL_HASH_RESET_MDMAT() - macro then wrap-up the HASH processing in feeding the last input buffer through the - same API HAL_HASH_Start_DMA() - -@endverbatim - * @{ - */ - -/** - * @brief HASH peripheral processes in polling mode pInBuffer then reads the computed 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. - * @param pOutBuffer pointer to the computed digest. - * @param Timeout specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer, uint32_t Timeout) -{ - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->HashInCount = 0U; - hhash->Size = Size; - - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - - HASH_WriteData(hhash, pInBuffer, Size); - - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for digest calculation completion status(DCIS) flag to be set */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Read the message digest */ - HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - /* Return function status */ - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - - -/** - * @brief HASH peripheral processes in interrupt mode pInBuffer then reads the computed 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. - * @param pOutBuffer pointer to the computed digest. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer) -{ - HAL_StatusTypeDef status; - HAL_HASH_StateTypeDef temp_state; - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process or suspended */ - temp_state = hhash->State; - if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->HashInCount = 0U; - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->Size = Size; - - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); - } - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - - /* Enable the specified HASH interrupt*/ - __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - status = HASH_WriteData_IT(hhash); - } - else - { - status = HAL_BUSY; - } - /* Return function status */ - return status; -} - -/** - * @brief HASH peripheral processes in DMA mode pInBuffer then reads the computed digest. - * @note Multi-buffer HASH processing is possible, consecutive calls to HAL_HASH_Start_DMA - * (MDMAT bit must be set) can be used to feed several input buffers - * back-to-back to the Peripheral that will yield a single - * HASH signature once all buffers have been entered. Wrap-up of input - * buffers feeding and retrieval of digest is done by a call to - * HAL_HASH_Start_DMA (MDMAT bit must be reset). - * @param hhash HASH handle. - * @param pInBuffer pointer to the input buffer (buffer to be hashed). - * @param Size length of the input buffer in bytes (must be a multiple of 4 in - * case of Multi-buffer and not last buffer). - * @param pOutBuffer pointer to the computed digest. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer) -{ - HAL_StatusTypeDef status; - HAL_HASH_StateTypeDef temp_state; - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process or suspended */ - temp_state = hhash->State; - if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) - { - - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Check if initialization phase has not been already performed */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->HashInCount = 0U; - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->HashInCount = 0U; - hhash->Size = Size; - - /* Check if initialization phase has already been performed. - If Phase is already set to HAL_HASH_PHASE_PROCESS, this means the - API is processing a new input data message in case of multi-buffer HASH - computation. */ - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - /* Configure the number of valid bits in last word of the message */ - if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Size) % 4U)); - } - else - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); - } - - } - else /* HAL_HASH_STATE_SUSPENDED */ - { - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - /*only part not yet hashed to compute */ - hhash->Size = hhash->HashInCount; - } - /* Set the HASH DMA transfer complete callback */ - hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; - /* Set the DMA error callback */ - hhash->hdmain->XferErrorCallback = HASH_DMAError; - - if ((hhash->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hhash->hdmain->LinkedListQueue != NULL) && (hhash->hdmain->LinkedListQueue->Head != NULL)) - { - /* Enable the DMA channel */ - hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET]\ - = ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : (hhash->Size)); - hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET]\ - = (uint32_t)(hhash->pHashInBuffPtr); /* Set DMA source address */ - hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET]\ - = (uint32_t)&hhash->Instance->DIN; /* Set DMA destination address */ - - status = HAL_DMAEx_List_Start_IT(hhash->hdmain); - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hhash->hdmain, (uint32_t)pInBuffer, (uint32_t)&hhash->Instance->DIN, \ - ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : \ - (hhash->Size))); - } - if (status != HAL_OK) - { - /* DMA error code field */ - hhash->ErrorCode |= HAL_HASH_ERROR_DMA; - - /* Return error */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) - /*Call registered error callback*/ - hhash->ErrorCallback(hhash); -#else - /*Call legacy weak error callback*/ - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - else - { - /* Enable DMA requests */ - SET_BIT(hhash->Instance->CR, HASH_CR_DMAE); - } - } - else - { - status = HAL_BUSY; - - } - - /* Return function status */ - return status; -} - - -/** - * @brief HASH peripheral processes in polling mode several input buffers. - * @note Consecutive calls to HAL_HASH_Accumulate() can be used to feed - * several input buffers back-to-back to the Peripheral that will yield a single - * HASH signature once all buffers have been entered. Wrap-up of input - * buffers feeding and retrieval of digest is done by a call to - * HAL_HASH_AccumulateLast() - * @param hhash HASH handle. - * @param pInBuffer pointer to the input buffer (buffer to be hashed). - * @param Size length of the input buffer in bytes and a multiple of 4. - * @param Timeout specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_Accumulate(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint32_t Timeout) -{ - HAL_HASH_StateTypeDef temp_state; - - /* Check the hash handle allocation and buffer length multiple of 4 */ - if ((hhash == NULL) || ((Size % 4U) != 0U)) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process or suspended */ - temp_state = hhash->State; - if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->HashInCount = 0U; - hhash->Size = Size; - - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - HASH_WriteData(hhash, pInBuffer, Size); - - /* Wait for BUSY flag to be cleared */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - - -/** - * @brief End computation of a single HASH signature after several calls to HAL_HASH_Accumulate() API. - * @note 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. - * @param pOutBuffer pointer to the computed digest. - * @param Timeout specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_AccumulateLast(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer, uint32_t Timeout) -{ - HAL_HASH_StateTypeDef temp_state; - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process or suspended */ - temp_state = hhash->State; - if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->HashInCount = 0U; - hhash->Size = Size; - - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); - - - HASH_WriteData(hhash, pInBuffer, Size); - - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for digest calculation completion status(DCIS) flag to be set */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - /* Read the message digest */ - HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - hhash->Accumulation = 0; - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief HASH peripheral processes in interrupt mode several input buffers. - * @note Consecutive calls to HAL_HASH_Accumulate_IT() can be used to feed - * several input buffers back-to-back to the Peripheral that will yield a single - * HASH signature once all buffers have been entered. Wrap-up of input - * buffers feeding and retrieval of digest is done by a call to - * HAL_HASH_AccumulateLast_IT() - * @param hhash HASH handle. - * @param pInBuffer pointer to the input buffer (buffer to be hashed). - * @param Size length of the input buffer in bytes and a multiple of 4. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) -{ - HAL_StatusTypeDef status; - - /* Check the hash handle allocation */ - if ((hhash == NULL) || ((Size % 4U) != 0U)) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size and pHashInBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->HashInCount = 0U; - hhash->Size = Size; - /* Set multi buffers accumulation flag */ - hhash->Accumulation = 1U; - - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - /* Enable the specified HASH interrupt*/ - __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI); - - status = HASH_WriteData_IT(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - } - else - { - status = HAL_BUSY; - } - /* Return function status */ - return status; -} - - -/** - * @brief End computation of a single HASH signature after several calls to HAL_HASH_Accumulate_IT() API. - * @note 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. - * @param pOutBuffer pointer to the computed digest. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_AccumulateLast_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer) -{ - HAL_StatusTypeDef status; - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->HashInCount = 0U; - hhash->Size = Size; - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Set HASH mode */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); - /* Reset the HASH processor core */ - MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); - - /* Enable the specified HASH interrupt*/ - __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - status = HASH_WriteData_IT(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - } - else - { - status = HAL_BUSY; - } - /* Return function status */ - return status; -} - -/** - * @} - */ - - -/** @defgroup HASH_Exported_Functions_Group3 HMAC processing functions - * @brief HMAC processing functions using different mode. - * -@verbatim - =============================================================================== - ##### HMAC processing functions ##### - =============================================================================== - [..] This section provides API allowing to calculate the HMAC (keyed-hash - message authentication code) value using: - (+) one of the algorithms supported by the peripheral - (+) Key selection - (++) Long key : HMAC key is longer than the block size - (++) Short key : HMAC key is shorter or equal to the block size - - [..] To calculate the HMAC for a single buffer, user can resort to one of three processing - functions available . - (+) Polling mode : HAL_HASH_HMAC_Start() - (+) Interrupt mode : HAL_HASH_HMAC_Start_IT() - (+) DMA mode : HAL_HASH_HMAC_Start_DMA() - - [..] In case of multi-buffer HMAC processing (a single digest is computed while - several buffers are fed to the Peripheral), the user can resort to successive calls - to : - (+) Polling mode : HAL_HASH_HMAC_Accumulate() and wrap-up the digest computation by a call - to HAL_HASH_HMAC_AccumulateLast() - (+) Interrupt mode : HAL_HASH_HMAC_Accumulate_IT() and wrap-up the digest computation by a call - to HAL_HASH_HMAC_AccumulateLast_IT() - (+) DMA mode : HAL_HASH_HMAC_Start_DMA(),MDMAT bit must be set through __HAL_HASH_SET_MDMAT() macro, - before entering the last buffer, reset the MDMAT bit with __HAL_HASH_RESET_MDMAT() - macro then wrap-up the HMAC processing in feeding the last input buffer through the - same API HAL_HASH_HMAC_Start_DMA() - -@endverbatim - * @{ - */ - -/** - * @brief HMAC in polling mode, HASH peripheral processes Key then pInBuffer then reads the computed 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. - * @param pOutBuffer pointer to the computed digest. - * @param Timeout specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer, uint32_t Timeout) -{ - uint32_t blocksize; /* Block size in bytes */ - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HASH Phase */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Reset HashInCount and Initialize Size, pHashKeyBuffPtr, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->HashInCount = 0U; - hhash->Size = Size; - - /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting bits */ - if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) - { - blocksize = BLOCK_64B; - } - else - { - blocksize = BLOCK_128B; - } - if (hhash->Init.KeySize > blocksize) - { - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); - } - else - { - - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_CR_INIT); - } - - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - /* Write Key */ - HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); - - /* Start the Key padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for BUSY flag to be cleared */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); - - /* Write message */ - HASH_WriteData(hhash, pInBuffer, Size); - - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for BUSY flag to be cleared */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - /* Write Key */ - HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); - - /* Start the Key padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for digest calculation completion status(DCIS) flag to be set */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Read the message digest */ - HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Change the HASH phase */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - /* Return function status */ - return HAL_OK; - - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief HMAC accumulate mode, HASH peripheral processes Key then several input buffers. - * @note Consecutive calls to HAL_HASH_HMAC_Accumulate() can be used to feed - * several input buffers back-to-back to the Peripheral that will yield a single - * HASH signature once all buffers have been entered. Wrap-up of input - * buffers feeding and retrieval of digest is done by a call to - * HAL_HASH_HMAC_AccumulateLast() - * @param hhash HASH handle. - * @param pInBuffer pointer to the input buffer (buffer to be hashed). - * @param Size length of the input buffer in bytes and a multiple of 4 - * @param Timeout specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_Accumulate(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint32_t Timeout) -{ - uint32_t blocksize; /* Block size in bytes */ - - /* Check the hash handle allocation and buffer length multiple of 4 */ - if ((hhash == NULL) || ((Size % 4U) != 0U)) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Initialize Size, pHashInBuffPtr and pHashKeyBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->Size = Size; - - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Reset HashInCount parameter */ - hhash->HashInCount = 0U; - /* Check if key size is larger than 64 bytes, accordingly set LKEY and the other setting bits */ - /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting */ - if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) - { - blocksize = BLOCK_64B; - } - else - { - blocksize = BLOCK_128B; - } - if (hhash->Init.KeySize > blocksize) - { - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); - } - else - { - - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_CR_INIT); - } - /* Set phase process */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - /* Write Key */ - HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); - - /* Start the Key padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for BUSY flag to be cleared */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - } - - /* Change the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); - - /* Write message */ - HASH_WriteData(hhash, pInBuffer, Size); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - /* Return function status */ - return HAL_OK; - - } - else - { - return HAL_BUSY; - } -} -/** - * @brief End computation of a single HMAC signature after several calls to HAL_HASH_HMAC_Accumulate() API. - * @note 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. - * @param pOutBuffer pointer to the computed digest. - * @param Timeout specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_AccumulateLast(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer, uint32_t Timeout) -{ - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Initialize Size, pHashInBuffPtr, pHashKeyBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->Size = Size; - - if (hhash->Phase != HAL_HASH_PHASE_PROCESS) - { - return HAL_ERROR; - } - else - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); - - /* Write message */ - HASH_WriteData(hhash, pInBuffer, Size); - - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for BUSY flag to be cleared */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - /* Write Key */ - HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); - - /* Start the Key padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for digest calculation completion status(DCIS) flag to be set */ - if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Read the message digest */ - HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); - } - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - /* Return function status */ - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief HMAC in interrupt mode, HASH peripheral process Key then pInBuffer then read the computed 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. - * @param pOutBuffer pointer to the computed digest. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer) -{ - HAL_StatusTypeDef status; - uint32_t blocksize; /* Block size in bytes */ - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HASH Phase */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Reset HashInCount and Initialize Size, pHashKeyBuffPtr, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->HashInCount = 0U; - hhash->Size = Size; - - /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting bits */ - if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) - { - blocksize = BLOCK_64B; - } - else - { - blocksize = BLOCK_128B; - } - if (hhash->Init.KeySize > blocksize) - { - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); - } - else - { - - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_CR_INIT); - } - - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - else if (hhash->State == HAL_HASH_STATE_SUSPENDED) - { - /* Process Locked */ - __HAL_LOCK(hhash); - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - } - else - { - return HAL_BUSY; - } - - /* Enable the specified HASH interrupt*/ - __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - status = HASH_WriteData_IT(hhash); - - /* Return function status */ - return status; -} - -/** - * @brief HMAC accumulate in interrupt mode, HASH peripheral processes Key then several input buffers. - * @note Consecutive calls to HAL_HASH_HMAC_Accumulate_IT() can be used to feed - * several input buffers back-to-back to the Peripheral that will yield a single - * HASH signature once all buffers have been entered. Wrap-up of input - * buffers feeding and retrieval of digest is done by a call to - * HAL_HASH_HMAC_AccumulateLast_IT() - * @param hhash HASH handle. - * @param pInBuffer pointer to the input buffer (buffer to be hashed). - * @param Size length of the input buffer in bytes and a multiple of 4. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_Accumulate_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) -{ - HAL_StatusTypeDef status; - uint32_t blocksize; /* Block size in bytes */ - - /* Check the hash handle allocation and buffer length multiple of 4 */ - if ((hhash == NULL) || ((Size % 4U) != 0U)) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process */ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->HashInCount = 0U; - hhash->Size = Size; - /* Set multi buffers accumulation flag */ - hhash->Accumulation = 1U; - - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting */ - if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) - { - blocksize = BLOCK_64B; - } - else - { - blocksize = BLOCK_128B; - } - if (hhash->Init.KeySize > blocksize) - { - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); - } - else - { - - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_CR_INIT); - } - - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_PROCESS; - } - /* Enable the specified HASH interrupt*/ - __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - status = HASH_WriteData_IT(hhash); - } - else - { - status = HAL_BUSY; - } - /* Return function status */ - return status; -} -/** - * @brief End computation of a single HMAC signature in interrupt mode, after - * several calls to HAL_HASH_HMAC_Accumulate() API. - * @note 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. - * @param pOutBuffer pointer to the computed digest. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_AccumulateLast_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, - uint32_t Size, uint8_t *const pOutBuffer) -{ - HAL_StatusTypeDef status; - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process*/ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->HashInCount = 0U; - hhash->Size = Size; - /* Set multi buffers accumulation flag */ - hhash->Accumulation = 0U; - /* Enable the specified HASH interrupt*/ - __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - status = HASH_WriteData_IT(hhash); - } - else - { - status = HAL_BUSY; - } - /* Return function status */ - return status; -} - -/** - * @brief HMAC in DMA mode,HASH peripheral processes Key then pInBuffer in DMA mode - * then read the computed digest. - * @note Multi-buffer HMAC processing is possible, consecutive calls to HAL_HASH_HMAC_Start_DMA - * (MDMAT bit must be set) can be used to feed several input buffers - * back-to-back to the Peripheral that will yield a single - * HASH signature once all buffers have been entered. Wrap-up of input - * buffers feeding and retrieval of digest is done by a call to - * HAL_HASH_HMAC_Start_DMA (MDMAT bit must be reset). - * @param hhash HASH handle. - * @param pInBuffer pointer to the input buffer (buffer to be hashed). - * @param Size length of the input buffer in bytes. - * @param pOutBuffer pointer to the computed digest. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HASH_HMAC_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, - uint8_t *const pOutBuffer) -{ - HAL_StatusTypeDef status; - uint32_t count; - uint32_t blocksize; /* Block size in bytes */ - - /* Check the hash handle allocation */ - if (hhash == NULL) - { - return HAL_ERROR; - } - - /* Check if peripheral is ready to start process*/ - if (hhash->State == HAL_HASH_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hhash); - - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ - hhash->pHashInBuffPtr = pInBuffer; - hhash->pHashOutBuffPtr = pOutBuffer; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - hhash->HashInCount = 0U; - hhash->Size = Size; - - /* Set the phase */ - if (hhash->Phase == HAL_HASH_PHASE_READY) - { - /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting */ - if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || - (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) - { - blocksize = BLOCK_64B; - } - else - { - blocksize = BLOCK_128B; - } - if (hhash->Init.KeySize > blocksize) - { - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); - } - else - { - - MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, - HASH_ALGOMODE_HMAC | HASH_CR_INIT); - } - - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_1; - - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - /* Write Key */ - HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); - - /* Start the Key padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for DCIS flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_BUSY)); - } - - hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_2; - if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Size) % 4U)); - } - else - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); - } - } - else if (hhash->State == HAL_HASH_STATE_SUSPENDED) - { - /* Process Locked */ - __HAL_LOCK(hhash); - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_BUSY; - - /*only part not yet hashed to compute */ - hhash->Size = hhash->HashInCount; - } - - else - { - /* Return busy status */ - return HAL_BUSY; - } - - /* Set the HASH DMA transfer complete callback */ - hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; - /* Set the DMA error callback */ - hhash->hdmain->XferErrorCallback = HASH_DMAError; - - if ((hhash->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hhash->hdmain->LinkedListQueue != NULL) && (hhash->hdmain->LinkedListQueue->Head != NULL)) - { - /* Enable the DMA channel */ - hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET]\ - = ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : ((hhash->Size))); - hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET]\ - = (uint32_t)(hhash->pHashInBuffPtr); /* Set DMA source address */ - hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET]\ - = (uint32_t)&hhash->Instance->DIN; /* Set DMA destination address */ - - status = HAL_DMAEx_List_Start_IT(hhash->hdmain); - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hhash->hdmain, (uint32_t)(hhash->pHashInBuffPtr), (uint32_t)&hhash->Instance->DIN, \ - ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : \ - ((hhash->Size)))); - } - if (status != HAL_OK) - { - /* DMA error code field */ - hhash->ErrorCode |= HAL_HASH_ERROR_DMA; - - /* Return error */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) - /*Call registered error callback*/ - hhash->ErrorCallback(hhash); -#else - /*Call legacy weak error callback*/ - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - else - { - /* Enable DMA requests */ - SET_BIT(hhash->Instance->CR, HASH_CR_DMAE); - } - - /* Return function status */ - return status; -} - - -/** - * @} - */ - -/** @defgroup HASH_Exported_Functions_Group4 HASH IRQ handler management - * @brief HASH IRQ handler. - * -@verbatim - ============================================================================== - ##### HASH IRQ handler management ##### - ============================================================================== -[..] This section provides HASH IRQ handler and callback functions. - (+) HAL_HASH_IRQHandler HASH interrupt request - (+) HAL_HASH_InCpltCallback input data transfer complete callback - (+) HAL_HASH_DgstCpltCallback digest computation complete callback - (+) HAL_HASH_ErrorCallback HASH error callback - (+) HAL_HASH_GetState return the HASH state - (+) HAL_HASH_GetError return the HASH error code -@endverbatim - * @{ - */ - -/** - * @brief Handle HASH interrupt request. - * @param hhash HASH handle. - * @note HAL_HASH_IRQHandler() handles interrupts in HMAC processing as well. - * @retval None - */ -void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash) -{ - HAL_StatusTypeDef status; - uint32_t itsource = hhash->Instance->IMR; - uint32_t itflag = hhash->Instance->SR; - - /* If digest is ready */ - if ((itflag & HASH_FLAG_DCIS) == HASH_FLAG_DCIS) - { - /* Read the digest */ - HASH_GetDigest(hhash, hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH(hhash)); - - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_READY; - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - /* Call digest computation complete call back */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->DgstCpltCallback(hhash); -#else - HAL_HASH_DgstCpltCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - - } - /* If Peripheral ready to accept new data */ - if ((itflag & HASH_FLAG_DINIS) == HASH_FLAG_DINIS) - { - if ((itsource & HASH_IT_DINI) == HASH_IT_DINI) - { - status = HASH_WriteData_IT(hhash); - if (status != HAL_OK) - { - /* Call error callback */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->ErrorCallback(hhash); -#else - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - } - } -} - -/** - * @brief Input data transfer complete call back. - * @note HAL_HASH_InCpltCallback() is called when the complete input message - * has been fed to the Peripheral. This API is invoked only when input data are - * entered under interruption or through DMA. - * @note In case of HASH or HMAC multi-buffer DMA feeding case (MDMAT bit set), - * HAL_HASH_InCpltCallback() is called at the end of each buffer feeding - * to the Peripheral. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval None - */ -__weak void HAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* NOTE : This function should not be modified; when the callback is needed, - HAL_HASH_InCpltCallback() can be implemented in the user file. - */ -} - -/** - * @brief Digest computation complete call back. - * @note HAL_HASH_DgstCpltCallback() is used under interruption, is not - * relevant with DMA. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval None - */ -__weak void HAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* NOTE : This function should not be modified; when the callback is needed, - HAL_HASH_DgstCpltCallback() can be implemented in the user file. - */ -} - -/** - * @brief HASH error callback. - * @note Code user can resort to hhash->Status (HAL_ERROR, HAL_TIMEOUT,...) - * to retrieve the error type. - * @param hhash pointer to a HASH_HandleTypeDef structure that contains - * the configuration information for HASH module. - * @retval None - */ -__weak void HAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhash); - - /* NOTE : This function should not be modified; when the callback is needed, - HAL_HASH_ErrorCallback() can be implemented in the user file. - */ -} - -/** - * @brief Return the HASH handle state. - * @note The API yields the current state of the handle (BUSY, READY,...). - * @param hhash HASH handle. - * @retval HAL HASH state - */ -HAL_HASH_StateTypeDef HAL_HASH_GetState(const HASH_HandleTypeDef *hhash) -{ - return hhash->State; -} - -/** - * @brief Return the HASH handle error code. - * @param hhash pointer to a HASH_HandleTypeDef structure. - * @retval HASH Error Code - */ -uint32_t HAL_HASH_GetError(const HASH_HandleTypeDef *hhash) -{ - /* Return HASH Error Code */ - return hhash->ErrorCode; -} -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @addtogroup HASH_Private_Functions - * @{ - */ - -/** - * @brief DMA HASH Input Data transfer completion 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 count; - - if (READ_BIT(hhash->Instance->CR, HASH_CR_MODE) == 0U) - { - if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) - { - /* Disable the DMA transfer */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_DMAE); - - - /* Wait for DCIS flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->ErrorCallback(hhash); -#else - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); - /* Call Input data transfer complete call back */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->InCpltCallback(hhash); -#else - HAL_HASH_InCpltCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - - /* Read the message digest */ - HASH_GetDigest(hhash, hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH(hhash)); - - /* Change the HASH state to ready */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Process UnLock */ - __HAL_UNLOCK(hhash); - - /* Call digest complete call back */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->DgstCpltCallback(hhash); -#else - HAL_HASH_DgstCpltCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - else - { - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - } - } - else /*HMAC DMA*/ - { - if (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_2) - { - if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) - { - /* Set the phase */ - hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_3; - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - /* Write Key */ - HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); - - /* Start the Key padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for DCIS flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable the DMA transfer */ - CLEAR_BIT(hhash->Instance->CR, HASH_CR_DMAE); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_DMA; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->ErrorCallback(hhash); -#else - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); - - /* Read the message digest */ - HASH_GetDigest(hhash, hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH(hhash)); - - /* Change the HASH state to ready */ - hhash->State = HAL_HASH_STATE_READY; - - /* Reset HASH state machine */ - hhash->Phase = HAL_HASH_PHASE_READY; - - /* Process UnLock */ - __HAL_UNLOCK(hhash); - - /* Call digest complete call back */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->DgstCpltCallback(hhash); -#else - HAL_HASH_DgstCpltCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - - } - else - { - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - hhash->Accumulation = 1; - } - } - } -} - -/** - * @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->ErrorCode |= HAL_HASH_ERROR_DMA; - /* Set HASH state to ready to prevent any blocking issue in user code - present in HAL_HASH_ErrorCallback() */ - hhash->State = HAL_HASH_STATE_READY; - -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) - hhash->ErrorCallback(hhash); -#else - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ -} - -/** - * @brief Feed the input buffer to the HASH peripheral in polling. - * @param hhash HASH handle. - * @param pInBuffer pointer to input buffer. - * @param Size the size of input buffer in bytes. - * @retval HAL status - */ -static void HASH_WriteData(HASH_HandleTypeDef *hhash, const uint8_t *pInBuffer, uint32_t Size) -{ - uint32_t buffercounter; - __IO uint32_t inputaddr = (uint32_t) pInBuffer; - uint8_t tmp1; - uint8_t tmp2; - uint8_t tmp3; - - for (buffercounter = 0U; buffercounter < (Size / 4U) ; buffercounter++) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)inputaddr; - inputaddr += 4U; - hhash->HashInCount += 4U; - } - - if ((Size % 4U) != 0U) - { - if (hhash->Init.DataType == HASH_HALFWORD_SWAP) - { - /* Write remaining input data */ - if ((Size % 4U) <= 2U) - { - hhash->Instance->DIN = (uint32_t) * (uint16_t *)inputaddr; - } - if ((Size % 4U) == 3U) - { - hhash->Instance->DIN = *(uint32_t *)inputaddr; - } - } - else if ((hhash->Init.DataType == HASH_BYTE_SWAP) - || (hhash->Init.DataType == HASH_BIT_SWAP)) /* byte swap or bit swap or */ - { - /* Write remaining input data */ - if ((Size % 4U) == 1U) - { - hhash->Instance->DIN = (uint32_t) * (uint8_t *)inputaddr; - } - if ((Size % 4U) == 2U) - { - hhash->Instance->DIN = (uint32_t) * (uint16_t *)inputaddr; - } - if ((Size % 4U) == 3U) - { - tmp1 = *(uint8_t *)inputaddr; - tmp2 = *(((uint8_t *)inputaddr) + 1U); - tmp3 = *(((uint8_t *)inputaddr) + 2U); - hhash->Instance->DIN = ((uint32_t)tmp1) | ((uint32_t)tmp2 << 8U) | ((uint32_t)tmp3 << 16U); - } - } - else - { - hhash->Instance->DIN = *(uint32_t *)inputaddr; - } - hhash->HashInCount += 4U; - } -} - -/** - * @brief Feed the input buffer to the HASH peripheral in interruption mode. - * @param hhash HASH handle. - * @retval HAL status - */ -static HAL_StatusTypeDef HASH_WriteData_IT(HASH_HandleTypeDef *hhash) -{ - uint32_t buffercounter; - uint32_t count; - __IO uint32_t keyaddr = (uint32_t)(hhash->pHashKeyBuffPtr); - __IO uint32_t inputaddr = (uint32_t)(hhash->pHashInBuffPtr); - uint32_t nbbytePartialHash = (((hhash->Instance->SR) >> 16U) * 4U); /* Nb byte to enter in HASH fifo to trig - a partial HASH computation*/ - - if (hhash->State == HAL_HASH_STATE_BUSY) - { - if ((hhash->Instance->CR & HASH_CR_MODE) == 0U) - { -#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) - /* If suspension flag has been raised, suspend processing */ - if (hhash->SuspendRequest == HAL_HASH_SUSPEND) - { - /* reset SuspendRequest */ - hhash->SuspendRequest = HAL_HASH_SUSPEND_NONE; - /* Disable Computation Complete Flag and Errors Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_SUSPENDED; - __HAL_UNLOCK(hhash); - } - else - { -#endif /* USE_HAL_HASH_SUSPEND_RESUME */ - - if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Size)) - { - for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)inputaddr; - inputaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashInBuffPtr += 4U; - } - /* Wait for HASH_IT_DINI flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); - } - else - { - while ((hhash->HashInCount) < hhash->Size) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)inputaddr; - inputaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashInBuffPtr += 4U; - } - /* Call Input transfer complete callback */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) - /*Call registered Input complete callback*/ - hhash->InCpltCallback(hhash); -#else - /*Call legacy weak Input complete callback*/ - HAL_HASH_InCpltCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - if (hhash->Accumulation == 0U) - { - if (__HAL_HASH_GET_IT_SOURCE(hhash, HASH_IT_DINI)) - { - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for HASH_FLAG_DCIS flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); - } - } - else - { - /* Reset multi buffers accumulation flag */ - hhash->Accumulation = 0U; - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI); - } - } -#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) - } -#endif /* USE_HAL_HASH_SUSPEND_RESUME */ - } - else /*HMAC */ - { - if (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_2) /* loading input*/ - { -#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) - /* If suspension flag has been raised, suspend processing */ - if (hhash->SuspendRequest == HAL_HASH_SUSPEND) - { - /* reset SuspendRequest */ - hhash->SuspendRequest = HAL_HASH_SUSPEND_NONE; - /* Disable Computation Complete Flag and Errors Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - /* Change the HASH state */ - hhash->State = HAL_HASH_STATE_SUSPENDED; - __HAL_UNLOCK(hhash); - } - else - { -#endif /* USE_HAL_HASH_SUSPEND_RESUME */ - if (hhash->Accumulation == 1U) - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); - } - else - { - /* Configure the number of valid bits in last word of the message */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (hhash->Size % 4U)); - } - if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Size)) - { - for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)inputaddr; - inputaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashInBuffPtr += 4U; - } - /* Wait for HASH_IT_DINI flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); - } - else - { - while ((hhash->HashInCount) < hhash->Size) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)inputaddr; - inputaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashInBuffPtr += 4U; - } - /* Call Input transfer complete callback */ -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) - /*Call registered Input complete callback*/ - hhash->InCpltCallback(hhash); -#else - /*Call legacy weak Input complete callback*/ - HAL_HASH_InCpltCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - - if (hhash->Accumulation == 0U) - { - if (__HAL_HASH_GET_IT_SOURCE(hhash, HASH_IT_DINI)) - { - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for HASH_FLAG_BUSY flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_SET(hhash->Instance->SR, HASH_FLAG_BUSY)); - - hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_3; - hhash->HashInCount = 0U; - hhash->pHashKeyBuffPtr = hhash->Init.pKey; - } - } - - else - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_OK; - } - } -#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) - } -#endif /* USE_HAL_HASH_SUSPEND_RESUME */ - } - - else if (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_3)/* loading Key*/ - { - - /* Configure the number of valid bits in last word of the Key */ - MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); - - if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Init.KeySize)) - { - for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)keyaddr; - keyaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashKeyBuffPtr += 4U; - } - /* Wait for HASH_IT_DINI flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); - } - else - { - while ((hhash->HashInCount) < (hhash->Init.KeySize)) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)keyaddr; - keyaddr += 4U; - hhash->HashInCount += 4U; - } - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for HASH_FLAG_DCIS flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); - } - } - else /*first step , loading key*/ - { - - hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_1; - - if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Init.KeySize)) - { - for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)keyaddr; - keyaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashKeyBuffPtr += 4U; - } - /* Wait for HASH_IT_DINI flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); - } - else - { - while ((hhash->HashInCount) < (hhash->Init.KeySize)) - { - /* Write input data 4 bytes at a time */ - hhash->Instance->DIN = *(uint32_t *)keyaddr; - keyaddr += 4U; - hhash->HashInCount += 4U; - hhash->pHashKeyBuffPtr += 4U; - } - /* Start the message padding then the Digest calculation */ - SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); - - /* Wait for HASH_FLAG_BUSY flag to be set */ - count = HASH_TIMEOUTVALUE; - do - { - count--; - if (count == 0U) - { - /* Disable Interrupts */ - __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); - - /* Change state */ - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - hhash->State = HAL_HASH_STATE_READY; - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } while (HAL_IS_BIT_SET(hhash->Instance->SR, HASH_FLAG_BUSY)); - /*change Phase to step 2*/ - hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_2; - hhash->HashInCount = 0U; - } - } - } - } - else if ((hhash->State == HAL_HASH_STATE_SUSPENDED)) - { - return HAL_OK; - } - else - { - /* Busy error code field */ - hhash->ErrorCode |= HAL_HASH_ERROR_BUSY; -#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) - /*Call registered error callback*/ - hhash->ErrorCallback(hhash); -#else - /*Call legacy weak error callback*/ - HAL_HASH_ErrorCallback(hhash); -#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @brief Retrieve the message digest. - * @param hhash HASH handle - * @param pMsgDigest pointer to the computed digest. - * @param Size message digest size in bytes. - * @retval None - */ -static void HASH_GetDigest(const HASH_HandleTypeDef *hhash, const uint8_t *pMsgDigest, uint8_t Size) -{ - uint32_t msgdigest = (uint32_t)pMsgDigest; - - switch (Size) - { - case 20: /* SHA1 */ - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); - break; - - case 28: /* SHA224 */ - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); - - break; - case 32: /* SHA256 */ - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); - break; - case 48: /* SHA384 */ - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[8]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[9]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[10]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[11]); - break; - - case 64: /* SHA 512 */ - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[8]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[9]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[10]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[11]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[12]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[13]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[14]); - msgdigest += 4U; - *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[15]); - - break; - default: - break; - } -} - -/** - * @brief Handle HASH processing Timeout. - * @param hhash HASH handle. - * @param Flag specifies the HASH flag to check. - * @param Status the Flag status (SET or RESET). - * @param Timeout Timeout duration. - * @retval HAL status - */ -static HAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, - uint32_t Timeout) -{ - uint32_t tickstart = HAL_GetTick(); - - /* Wait until flag is set */ - if (Status == RESET) - { - while (__HAL_HASH_GET_FLAG(hhash, Flag) == RESET) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* Set State to Ready to be able to restart later on */ - hhash->State = HAL_HASH_STATE_READY; - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - return HAL_ERROR; - } - } - } - } - else - { - while (__HAL_HASH_GET_FLAG(hhash, Flag) != RESET) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* Set State to Ready to be able to restart later on */ - hhash->State = HAL_HASH_STATE_READY; - hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; - /* Process Unlocked */ - __HAL_UNLOCK(hhash); - - return HAL_ERROR; - } - } - } - } - return HAL_OK; -} - -/** - * @} - */ - - -#endif /* HAL_HASH_MODULE_ENABLED */ - -#endif /* HASH*/ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_hash.c + * @author MCD Application Team + * @brief HASH HAL module driver. + * This file provides firmware functions to manage HASH peripheral + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 __HAL_RCC_HASH_CLK_ENABLE() + (##) When resorting to interrupt-based APIs (e.g. HAL_HASH_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() API + (##) When resorting to DMA-based APIs (e.g. HAL_HASH_Start_DMA()) + (+++) Enable the DMA interface clock + (+++) Configure and enable one DMA to manage data transfer from + memory to peripheral (input DMA). 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: use + HAL_NVIC_SetPriority() and + HAL_NVIC_EnableIRQ() + + (#)Initialize the HASH HAL using HAL_HASH_Init(). This function: + (##) resorts to HAL_HASH_MspInit() for low-level initialization, + (##) configures the data type: no swap, half word swap, bit swap or byte swap, + (##) configures the Algorithm : MD5, SHA1 or SHA2 + + (#)Three processing schemes 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_Start() for HASH or HAL_HMAC_Start() for HMAC + (##) Interrupt mode: processing APIs are not blocking functions + i.e. they process the data under interrupt, + e.g. HAL_HASH_Start_IT() for HASH or HAL_HMAC_Start_IT() for HMAC + (##) 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_Start_DMA() for HASH or HAL_HMAC_Start_DMA() for HMAC. + + (#)When the processing function is called after HAL_HASH_Init(), the HASH peripheral is + initialized and processes the buffer fed in input. When the input data have all been + fed to the Peripheral, the digest computation can start. + + (#)Multi-buffer processing HASH and HMAC are possible in polling, interrupt and DMA modes. + (##) In polling mode, API HAL_HASH_Accumulate()/HAL_HASH_HMAC_Accumulate() must be called + for each input buffer, except for the last one. + User must resort to HAL_HASH_AccumulateLast()/HAL_HASH_HMAC_AccumulateLast() + to enter the last one and retrieve as well the computed digest. + + (##) In interrupt mode, API HAL_HASH_Accumulate_IT()/HAL_HASH_HMAC_Accumulate_IT() must + be called for each input buffer, except for the last one. + User must resort to HAL_HASH_AccumulateLast_IT()/HAL_HASH_HMAC_AccumulateLast_IT() + to enter the last one and retrieve as well the computed digest. + + (##) In DMA mode, once initialization is done, MDMAT bit must be set through + __HAL_HASH_SET_MDMAT() macro. + From that point, each buffer can be fed to the Peripheral through HAL_HASH_Start_DMA() API + for HASH and HAL_HASH_HMAC_Start_DMA() API for HMAC . + Before entering the last buffer, reset the MDMAT bit with __HAL_HASH_RESET_MDMAT() + macro then wrap-up the HASH processing in feeding the last input buffer through the + same API HAL_HASH_Start_DMA()for HASH and HAL_HASH_HMAC_Start_DMA() API for HMAC and + retrieve as well the computed digest. + + (#)To use this driver (version 2.0.0) with application developed with old driver (version 1.0.0) user have to: + (##) Add Algorithm as parameter like DataType or KeySize. + (##) Use new API HAL_HASH_Start() for HASH and HAL_HASH_HMAC_Start() for HMAC processing instead of old API + like HAL_HASH_SHA1_Start and HAL_HMAC_SHA1_Start. + + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#if defined (HASH) + +/** @defgroup HASH HASH + * @brief HASH HAL module driver. + * @{ + */ + +#ifdef HAL_HASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup HASH_Private_Defines HASH Private Defines + * @{ + */ +#define HASH_TIMEOUTVALUE 1000U /*!< Time-out value */ +#define BLOCK_64B 64U /*!< block Size equal to 64 bytes */ +#define BLOCK_128B 128U /*!< block Size equal to 128 bytes */ +/** + * @} + */ + +/** @defgroup HASH_Number_Of_CSR_Registers HASH Number of Context Swap Registers + * @{ + */ +#define HASH_NUMBER_OF_CSR_REGISTERS 103U /*!< Number of Context Swap Registers */ +/** + * @} + */ + +/* Private Constants ---------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup HASH_Private_Functions HASH Private Functions + * @{ + */ +static void HASH_GetDigest(const HASH_HandleTypeDef *hhash, const uint8_t *pMsgDigest, uint8_t Size); +static void HASH_WriteData(HASH_HandleTypeDef *hhash, const uint8_t *pInBuffer, uint32_t Size); +static HAL_StatusTypeDef HASH_WriteData_IT(HASH_HandleTypeDef *hhash); +static void HASH_DMAXferCplt(DMA_HandleTypeDef *hdma); +static void HASH_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, + uint32_t Timeout); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup HASH_Exported_Functions HASH Exported Functions + * @{ + */ + +/** @defgroup HASH_Exported_Functions_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 create the associated handle + (+) DeInitialize the HASH peripheral + (+) Initialize the HASH MCU Specific Package (MSP) + (+) DeInitialize the HASH MSP + (+) Configure HASH (HAL_HASH_SetConfig) with the specified parameters in the HASH_ConfigTypeDef + Parameters which are configured in This section are : + (+) Data Type : no swap, half word swap, bit swap or byte swap + (+) Algorithm : MD5,SHA1 or SHA2 + (+) Get HASH configuration (HAL_HASH_GetConfig) from the specified parameters in the HASH_HandleTypeDef + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the HASH according to the specified parameters in the + HASH_HandleTypeDef and create the associated handle. + * @note Only Algorithm and DATATYPE bits of HASH Peripheral are set by HAL_HASH_Init(), + * other configuration bits are set by HASH or HMAC processing APIs. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_Init(HASH_HandleTypeDef *hhash) +{ + uint32_t cr_value; + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_HASH_DATATYPE(hhash->Init.DataType)); + assert_param(IS_HASH_ALGORITHM(hhash->Init.Algorithm)); + +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + if (hhash->State == HAL_HASH_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhash->Lock = HAL_UNLOCKED; + + /* Reset Callback pointers in HAL_HASH_STATE_RESET only */ + hhash->InCpltCallback = HAL_HASH_InCpltCallback; /* Legacy weak InCpltCallback */ + hhash->DgstCpltCallback = HAL_HASH_DgstCpltCallback; /* Legacy weak DgstCpltCallback */ + hhash->ErrorCallback = HAL_HASH_ErrorCallback; /* Legacy weak ErrorCallback */ + if (hhash->MspInitCallback == NULL) + { + hhash->MspInitCallback = HAL_HASH_MspInit; + } + + /* Init the low level hardware */ + hhash->MspInitCallback(hhash); + } +#else + if (hhash->State == HAL_HASH_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhash->Lock = HAL_UNLOCKED; + + /* Init the low level hardware */ + HAL_HASH_MspInit(hhash); + } +#endif /* (USE_HAL_HASH_REGISTER_CALLBACKS) */ + + /* Set the key size, data type and Algorithm */ + cr_value = (uint32_t)(hhash->Init.DataType | hhash->Init.Algorithm); + /* Set the key size, data type, algorithm and mode */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_DATATYPE | HASH_CR_ALGO | HASH_CR_INIT, cr_value); + + /* Change HASH phase to Ready */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Change HASH state to Ready */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset error code field */ + hhash->ErrorCode = HAL_HASH_ERROR_NONE; + +#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) + /* Reset suspension request flag */ + hhash->SuspendRequest = HAL_HASH_SUSPEND_NONE; +#endif /* (USE_HAL_HASH_SUSPEND_RESUME) */ + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitialize the HASH peripheral. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_DeInit(HASH_HandleTypeDef *hhash) +{ + /* Check the HASH handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Change the default HASH phase */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Reset HashInCount */ + hhash->HashInCount = 0U; + + /* Reset multi buffers accumulation flag */ + hhash->Accumulation = 0U; + +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + if (hhash->MspDeInitCallback == NULL) + { + hhash->MspDeInitCallback = HAL_HASH_MspDeInit; + } + + /* DeInit the low level hardware */ + hhash->MspDeInitCallback(hhash); +#else + /* DeInit the low level hardware: CLOCK, NVIC */ + HAL_HASH_MspDeInit(hhash); +#endif /* (USE_HAL_HASH_REGISTER_CALLBACKS) */ + + /* Set the HASH state to Ready */ + hhash->State = HAL_HASH_STATE_RESET; + + __HAL_UNLOCK(hhash); + + return HAL_OK; +} + +/** + * @brief Configure the HASH according to the specified + * parameters in the HASH_ConfigTypeDef + * @param hhash pointer to a HASH_HandleTypeDef structure + * @param pConf pointer to a HASH_ConfigTypeDef structure that contains + * the configuration information for HASH module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_SetConfig(HASH_HandleTypeDef *hhash, HASH_ConfigTypeDef *pConf) +{ + uint32_t cr_value; + + /* Check the HASH handle allocation */ + if ((hhash == NULL) || (pConf == NULL)) + { + return HAL_ERROR; + } + + /* Check parameters */ + assert_param(IS_HASH_DATATYPE(pConf->DataType)); + assert_param(IS_HASH_ALGORITHM(pConf->Algorithm)); + + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + __HAL_LOCK(hhash); + + /* Set HASH parameters */ + hhash->Init.DataType = pConf->DataType; + hhash->Init.pKey = pConf->pKey; + hhash->Init.Algorithm = pConf->Algorithm; + hhash->Init.KeySize = pConf->KeySize; + + /* Set the key size, data type and Algorithm */ + cr_value = (uint32_t)(hhash->Init.DataType | hhash->Init.Algorithm); + /* Set the key size, data type, algorithm and mode */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_DATATYPE | HASH_CR_ALGO | HASH_CR_INIT, cr_value); + + /* Change HASH phase to Ready */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Change HASH state to Ready */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset error code field */ + hhash->ErrorCode = HAL_HASH_ERROR_NONE; + + __HAL_UNLOCK(hhash); + + return HAL_OK; + + } + else + { + /* Busy error code field */ + hhash->ErrorCode |= HAL_HASH_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Get HASH Configuration parameters in associated handle + * @param pConf pointer to a HASH_HandleTypeDef structure + * @param hhash pointer to a HASH_ConfigTypeDef structure that contains + * the configuration information for HASH module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_GetConfig(HASH_HandleTypeDef *hhash, HASH_ConfigTypeDef *pConf) +{ + + /* Check the HASH handle allocation */ + if ((hhash == NULL) || (pConf == NULL)) + { + return HAL_ERROR; + } + + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + __HAL_LOCK(hhash); + + /* Set HASH parameters */ + pConf->DataType = hhash->Init.DataType; + pConf->pKey = hhash->Init.pKey; + pConf->Algorithm = hhash->Init.Algorithm; + pConf->KeySize = hhash->Init.KeySize; + + /* Change HASH state to Ready */ + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + + return HAL_OK; + + } + else + { + /* Busy error code field */ + hhash->ErrorCode |= HAL_HASH_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Initialize the HASH MSP. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval None + */ +__weak void HAL_HASH_MspInit(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + HAL_HASH_MspInit() can be implemented in the user file. + */ +} + +/** + * @brief DeInitialize the HASH MSP. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval None + */ +__weak void HAL_HASH_MspDeInit(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + HAL_HASH_MspDeInit() can be implemented in the user file. + */ +} + + +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User HASH Callback + * To be used instead of the weak (overridden) predefined callback + * @param hhash HASH handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg HAL_HASH_INPUTCPLT_CB_ID input completion callback ID + * @arg HAL_HASH_DGSTCPLT_CB_ID digest computation completion callback ID + * @arg HAL_HASH_ERROR_CB_ID error callback ID + * @arg HAL_HASH_MSPINIT_CB_ID MspInit callback ID + * @arg HAL_HASH_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_HASH_RegisterCallback(HASH_HandleTypeDef *hhash, HAL_HASH_CallbackIDTypeDef CallbackID, + pHASH_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hhash->State == HAL_HASH_STATE_READY) + { + switch (CallbackID) + { + case HAL_HASH_INPUTCPLT_CB_ID : + hhash->InCpltCallback = pCallback; + break; + + case HAL_HASH_DGSTCPLT_CB_ID : + hhash->DgstCpltCallback = pCallback; + break; + + case HAL_HASH_ERROR_CB_ID : + hhash->ErrorCallback = pCallback; + break; + + case HAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = pCallback; + break; + + case HAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hhash->State == HAL_HASH_STATE_RESET) + { + switch (CallbackID) + { + case HAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = pCallback; + break; + + case HAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a HASH Callback + * HASH Callback is redirected to the weak (overridden) predefined callback + * @param hhash HASH handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg HAL_HASH_INPUTCPLT_CB_ID HASH input completion Callback ID + * @arg HAL_HASH_DGSTCPLT_CB_ID HASH digest computation completion Callback ID + * @arg HAL_HASH_ERROR_CB_ID HASH error Callback ID + * @arg HAL_HASH_MSPINIT_CB_ID HASH MspInit callback ID + * @arg HAL_HASH_MSPDEINIT_CB_ID HASH MspDeInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_HASH_UnRegisterCallback(HASH_HandleTypeDef *hhash, HAL_HASH_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + + if (hhash->State == HAL_HASH_STATE_READY) + { + switch (CallbackID) + { + case HAL_HASH_INPUTCPLT_CB_ID : + hhash->InCpltCallback = HAL_HASH_InCpltCallback; /* Legacy weak input completion callback */ + break; + + case HAL_HASH_DGSTCPLT_CB_ID : + hhash->DgstCpltCallback = HAL_HASH_DgstCpltCallback; /* Legacy weak digest computation + completion callback */ + break; + + case HAL_HASH_ERROR_CB_ID : + hhash->ErrorCallback = HAL_HASH_ErrorCallback; /* Legacy weak error callback */ + break; + + case HAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = HAL_HASH_MspInit; /* Legacy weak MspInit Callback */ + break; + + case HAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = HAL_HASH_MspDeInit; /* Legacy weak MspDeInit Callback */ + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hhash->State == HAL_HASH_STATE_RESET) + { + switch (CallbackID) + { + case HAL_HASH_MSPINIT_CB_ID : + hhash->MspInitCallback = HAL_HASH_MspInit; /* Legacy weak MspInit Callback */ + break; + + case HAL_HASH_MSPDEINIT_CB_ID : + hhash->MspDeInitCallback = HAL_HASH_MspDeInit; /* Legacy weak MspDeInit Callback */ + break; + + default : + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhash->ErrorCode |= HAL_HASH_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + +#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) +/** + * @brief Save the HASH context in case of processing suspension. + * @param hhash HASH handle. + * @param pMemBuffer pointer to the memory buffer where the HASH context + * is saved. + * @note The IMR, STR, CR then all the CSR registers are saved + * in that order. Only the r/w bits are read to be restored later on. + * @note By default, all the context swap registers (there are + * HASH_NUMBER_OF_CSR_REGISTERS of those) are saved. + * @note pMemBuffer points to a buffer allocated by the user. The buffer size + * must be at least (HASH_NUMBER_OF_CSR_REGISTERS + 3) * 4 uint8 long. + * @retval None + */ +void HAL_HASH_Suspend(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer) +{ + uint32_t mem_ptr = (uint32_t)pMemBuffer; + uint32_t csr_ptr = (uint32_t)(hhash->Instance->CSR); + uint32_t i; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* Save IMR register content */ + *(uint32_t *)(mem_ptr) = READ_BIT(hhash->Instance->IMR, HASH_IT_DINI | HASH_IT_DCI); + mem_ptr += 4U; + /* Save STR register content */ + *(uint32_t *)(mem_ptr) = READ_BIT(hhash->Instance->STR, HASH_STR_NBLW); + mem_ptr += 4U; + /* Save CR register content */ + *(uint32_t *)(mem_ptr) = READ_BIT(hhash->Instance->CR, HASH_CR_DMAE | HASH_CR_DATATYPE | HASH_CR_MODE | HASH_CR_ALGO | + HASH_CR_LKEY | HASH_CR_MDMAT); + + mem_ptr += 4U; + /* By default, save all CSRs registers */ + for (i = HASH_NUMBER_OF_CSR_REGISTERS; i > 0U; i--) + { + *(uint32_t *)(mem_ptr) = *(uint32_t *)(csr_ptr); + mem_ptr += 4U; + csr_ptr += 4U; + } + /* Save low-priority block HASH handle parameters */ + hhash->Init_saved = hhash->Init; + hhash->pHashOutBuffPtr_saved = hhash->pHashOutBuffPtr; + hhash->HashInCount_saved = hhash->HashInCount; + hhash->Size_saved = hhash->Size; + hhash->pHashInBuffPtr_saved = hhash->pHashInBuffPtr; + hhash->Phase_saved = hhash->Phase; + hhash->pHashKeyBuffPtr_saved = hhash->pHashKeyBuffPtr; +} + + +/** + * @brief Restore the HASH context in case of processing resumption. + * @param hhash HASH handle. + * @param pMemBuffer pointer to the memory buffer where the HASH context + * is stored. + * @note The IMR, STR, CR then all the CSR registers are restored + * in that order. Only the r/w bits are restored. + * @note By default, all the context swap registers (HASH_NUMBER_OF_CSR_REGISTERS + * of those) are restored (all of them have been saved by default + * beforehand). + * @retval None + */ +void HAL_HASH_Resume(HASH_HandleTypeDef *hhash, uint8_t *pMemBuffer) +{ + uint32_t mem_ptr = (uint32_t)pMemBuffer; + uint32_t csr_ptr = (uint32_t)(hhash->Instance->CSR); + uint32_t i; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* Restore IMR register content */ + WRITE_REG(hhash->Instance->IMR, (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + /* Restore STR register content */ + WRITE_REG(hhash->Instance->STR, (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + /* Restore CR register content */ + WRITE_REG(hhash->Instance->CR, (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + + /* Reset the HASH processor before restoring the Context + Swap Registers (CSR) */ + SET_BIT(hhash->Instance->CR, HASH_CR_INIT); + + + /* By default, restore all CSR registers */ + for (i = HASH_NUMBER_OF_CSR_REGISTERS; i > 0U; i--) + { + WRITE_REG((*(uint32_t *)(csr_ptr)), (*(uint32_t *)(mem_ptr))); + mem_ptr += 4U; + csr_ptr += 4U; + } + + /* Restore low-priority block HASH handle parameters */ + hhash->Init = hhash->Init_saved; + hhash->pHashOutBuffPtr = hhash->pHashOutBuffPtr_saved; + hhash->HashInCount = hhash->HashInCount_saved; + hhash->Size = hhash->Size_saved; + hhash->pHashInBuffPtr = hhash->pHashInBuffPtr_saved; + hhash->Phase = hhash->Phase_saved; + hhash->State = HAL_HASH_STATE_SUSPENDED; + hhash->pHashKeyBuffPtr = hhash->pHashKeyBuffPtr_saved; +} + +/** + * @brief Initiate HASH processing suspension when in interruption mode. + * @param hhash HASH handle. + * @note Set the handle field SuspendRequest to the appropriate value so that + * the on-going HASH processing is suspended as soon as the required + * conditions are met. Note that the actual suspension is carried out + * by the functions HASH_WriteData() in polling mode and HASH_IT() in + * interruption mode. + * @retval None + */ +HAL_StatusTypeDef HAL_HASH_ProcessSuspend(HASH_HandleTypeDef *hhash) +{ + uint32_t remainingwords; /*remaining number in of source block to be transferred.*/ + uint32_t nbbytePartialHash = (((hhash->Instance->SR) >> 16U) * 4U); /* Nb byte to enter in HASH fifo + to trig a partial HASH computation*/ + uint32_t sizeinwords;/* number in word of source block to be transferred.*/ + + /* suspension in DMA mode*/ + if (__HAL_HASH_GET_FLAG(hhash, HASH_FLAG_DMAS) != RESET) + { + if (hhash->State == HAL_HASH_STATE_READY) + { + return HAL_ERROR; + } + else + { + + /* Clear the DMAE bit to disable the DMA interface */ + CLEAR_BIT(HASH->CR, HASH_CR_DMAE); + + /* Wait until the last DMA transfer is complete (DMAS = 0 in the HASH_SR register) */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DMAS, SET, HASH_TIMEOUTVALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* At this point, DMA interface is disabled and no transfer is on-going */ + /* Retrieve from the DMA handle how many words remain to be written */ + /* DMA3 used, DMA_CBR1_BNDT in bytes, DMA_CSR_FIFOL in words */ + remainingwords = ((((DMA_Channel_TypeDef *)hhash->hdmain->Instance)->CBR1) \ + & DMA_CBR1_BNDT) / 4U; + remainingwords += ((((DMA_Channel_TypeDef *)hhash->hdmain->Instance)->CSR) \ + & DMA_CSR_FIFOL) >> DMA_CSR_FIFOL_Pos; + + if (remainingwords <= nbbytePartialHash) + { + /* No suspension attempted since almost to the end of the transferred data. */ + /* Best option for user code is to wrap up low priority message hashing */ + return HAL_ERROR; + } + + /* Disable DMA channel */ + /* Note that the Abort function will + - Clear the transfer error flags + - Unlock + - Set the State + */ + if (HAL_DMA_Abort(hhash->hdmain) != HAL_OK) + { + return HAL_ERROR; + } + + if (__HAL_HASH_GET_FLAG(hhash, HASH_FLAG_DCIS) != RESET) + { + return HAL_ERROR; + } + + /* Wait until the hash processor is ready (no block is being processed), that is wait for DINIS=1 in HASH_SR */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DINIS, RESET, HASH_TIMEOUTVALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Compute how many words were supposed to be transferred by DMA */ + sizeinwords = (((hhash->Size % 4U) != 0U) ? \ + ((hhash->Size + 3U) / 4U) : (hhash->Size / 4U)); + /* Accordingly, update the input pointer that points at the next word to be + transferred to the Peripheral by DMA */ + hhash->pHashInBuffPtr += 4U * (sizeinwords - remainingwords) ; + + /* And store in HashInCount the remaining size to transfer (in bytes) */ + hhash->HashInCount = 4U * remainingwords; + + + hhash->State = HAL_HASH_STATE_SUSPENDED; + __HAL_UNLOCK(hhash); + return HAL_OK; + } + + } + else /* suspension when in interruption mode*/ + { + /* Set Handle Suspend Request field */ + hhash->SuspendRequest = HAL_HASH_SUSPEND; + return HAL_OK; + } +} +#endif /* USE_HAL_HASH_SUSPEND_RESUME */ +/** + * @} + */ + + +/** @defgroup HASH_Exported_Functions_Group2 HASH processing functions + * @brief HASH processing functions using different mode. + * +@verbatim + =============================================================================== + ##### HASH processing functions ##### + =============================================================================== + [..] This section provides API allowing to calculate the hash value using + one of the HASH algorithms supported by the peripheral. + + [..] For a single buffer to be hashed, user can resort to one of three processing + functions available . + (+) Polling mode : HAL_HASH_Start() + (+) Interrupt mode : HAL_HASH_Start_IT() + (+) DMA mode : HAL_HASH_Start_DMA() + + [..] In case of multi-buffer HASH processing (a single digest is computed while + several buffers are fed to the Peripheral), the user can resort to successive calls + to : + (+) Polling mode : HAL_HASH_Accumulate() and wrap-up the digest computation by a call + to HAL_HASH_AccumulateLast() + (+) Interrupt mode : HAL_HASH_Accumulate_IT() and wrap-up the digest computation by a call + to HAL_HASH_AccumulateLast_IT() + (+) DMA mode : HAL_HASH_Start_DMA(), MDMAT bit must be set through __HAL_HASH_SET_MDMAT() macro, + before entering the last buffer, reset the MDMAT bit with __HAL_HASH_RESET_MDMAT() + macro then wrap-up the HASH processing in feeding the last input buffer through the + same API HAL_HASH_Start_DMA() + +@endverbatim + * @{ + */ + +/** + * @brief HASH peripheral processes in polling mode pInBuffer then reads the computed 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. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer, uint32_t Timeout) +{ + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->HashInCount = 0U; + hhash->Size = Size; + + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + + HASH_WriteData(hhash, pInBuffer, Size); + + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for digest calculation completion status(DCIS) flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Read the message digest */ + HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + + +/** + * @brief HASH peripheral processes in interrupt mode pInBuffer then reads the computed 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. + * @param pOutBuffer pointer to the computed digest. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer) +{ + HAL_StatusTypeDef status; + HAL_HASH_StateTypeDef temp_state; + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process or suspended */ + temp_state = hhash->State; + if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->HashInCount = 0U; + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->Size = Size; + + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); + } + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + + /* Enable the specified HASH interrupt*/ + __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + status = HASH_WriteData_IT(hhash); + } + else + { + status = HAL_BUSY; + } + /* Return function status */ + return status; +} + +/** + * @brief HASH peripheral processes in DMA mode pInBuffer then reads the computed digest. + * @note Multi-buffer HASH processing is possible, consecutive calls to HAL_HASH_Start_DMA + * (MDMAT bit must be set) can be used to feed several input buffers + * back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * HAL_HASH_Start_DMA (MDMAT bit must be reset). + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes (must be a multiple of 4 in + * case of Multi-buffer and not last buffer). + * @param pOutBuffer pointer to the computed digest. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer) +{ + HAL_StatusTypeDef status; + HAL_HASH_StateTypeDef temp_state; + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process or suspended */ + temp_state = hhash->State; + if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) + { + + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Check if initialization phase has not been already performed */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->HashInCount = 0U; + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->HashInCount = 0U; + hhash->Size = Size; + + /* Check if initialization phase has already been performed. + If Phase is already set to HAL_HASH_PHASE_PROCESS, this means the + API is processing a new input data message in case of multi-buffer HASH + computation. */ + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + /* Configure the number of valid bits in last word of the message */ + if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Size) % 4U)); + } + else + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); + } + + } + else /* HAL_HASH_STATE_SUSPENDED */ + { + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + /*only part not yet hashed to compute */ + hhash->Size = hhash->HashInCount; + } + /* Set the HASH DMA transfer complete callback */ + hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; + /* Set the DMA error callback */ + hhash->hdmain->XferErrorCallback = HASH_DMAError; + + if ((hhash->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hhash->hdmain->LinkedListQueue != NULL) && (hhash->hdmain->LinkedListQueue->Head != NULL)) + { + /* Enable the DMA channel */ + hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET]\ + = ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : (hhash->Size)); + hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET]\ + = (uint32_t)(hhash->pHashInBuffPtr); /* Set DMA source address */ + hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET]\ + = (uint32_t)&hhash->Instance->DIN; /* Set DMA destination address */ + + status = HAL_DMAEx_List_Start_IT(hhash->hdmain); + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hhash->hdmain, (uint32_t)pInBuffer, (uint32_t)&hhash->Instance->DIN, \ + ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : \ + (hhash->Size))); + } + if (status != HAL_OK) + { + /* DMA error code field */ + hhash->ErrorCode |= HAL_HASH_ERROR_DMA; + + /* Return error */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hhash->ErrorCallback(hhash); +#else + /*Call legacy weak error callback*/ + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + else + { + /* Enable DMA requests */ + SET_BIT(hhash->Instance->CR, HASH_CR_DMAE); + } + } + else + { + status = HAL_BUSY; + + } + + /* Return function status */ + return status; +} + + +/** + * @brief HASH peripheral processes in polling mode several input buffers. + * @note Consecutive calls to HAL_HASH_Accumulate() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * HAL_HASH_AccumulateLast() + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes and a multiple of 4. + * @param Timeout specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_Accumulate(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Timeout) +{ + HAL_HASH_StateTypeDef temp_state; + + /* Check the hash handle allocation and buffer length multiple of 4 */ + if ((hhash == NULL) || ((Size % 4U) != 0U)) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process or suspended */ + temp_state = hhash->State; + if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->HashInCount = 0U; + hhash->Size = Size; + + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + HASH_WriteData(hhash, pInBuffer, Size); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + + +/** + * @brief End computation of a single HASH signature after several calls to HAL_HASH_Accumulate() API. + * @note 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. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_AccumulateLast(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer, uint32_t Timeout) +{ + HAL_HASH_StateTypeDef temp_state; + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process or suspended */ + temp_state = hhash->State; + if ((temp_state == HAL_HASH_STATE_READY) || (temp_state == HAL_HASH_STATE_SUSPENDED)) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->HashInCount = 0U; + hhash->Size = Size; + + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); + + + HASH_WriteData(hhash, pInBuffer, Size); + + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for digest calculation completion status(DCIS) flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + /* Read the message digest */ + HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + hhash->Accumulation = 0; + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief HASH peripheral processes in interrupt mode several input buffers. + * @note Consecutive calls to HAL_HASH_Accumulate_IT() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * HAL_HASH_AccumulateLast_IT() + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes and a multiple of 4. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_Accumulate_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) +{ + HAL_StatusTypeDef status; + + /* Check the hash handle allocation */ + if ((hhash == NULL) || ((Size % 4U) != 0U)) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size and pHashInBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->HashInCount = 0U; + hhash->Size = Size; + /* Set multi buffers accumulation flag */ + hhash->Accumulation = 1U; + + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + /* Enable the specified HASH interrupt*/ + __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI); + + status = HASH_WriteData_IT(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + } + else + { + status = HAL_BUSY; + } + /* Return function status */ + return status; +} + + +/** + * @brief End computation of a single HASH signature after several calls to HAL_HASH_Accumulate_IT() API. + * @note 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. + * @param pOutBuffer pointer to the computed digest. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_AccumulateLast_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer) +{ + HAL_StatusTypeDef status; + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->HashInCount = 0U; + hhash->Size = Size; + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Set HASH mode */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_MODE); + /* Reset the HASH processor core */ + MODIFY_REG(hhash->Instance->CR, HASH_CR_INIT, HASH_CR_INIT); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); + + /* Enable the specified HASH interrupt*/ + __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + status = HASH_WriteData_IT(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + } + else + { + status = HAL_BUSY; + } + /* Return function status */ + return status; +} + +/** + * @} + */ + + +/** @defgroup HASH_Exported_Functions_Group3 HMAC processing functions + * @brief HMAC processing functions using different mode. + * +@verbatim + =============================================================================== + ##### HMAC processing functions ##### + =============================================================================== + [..] This section provides API allowing to calculate the HMAC (keyed-hash + message authentication code) value using: + (+) one of the algorithms supported by the peripheral + (+) Key selection + (++) Long key : HMAC key is longer than the block size + (++) Short key : HMAC key is shorter or equal to the block size + + [..] To calculate the HMAC for a single buffer, user can resort to one of three processing + functions available . + (+) Polling mode : HAL_HASH_HMAC_Start() + (+) Interrupt mode : HAL_HASH_HMAC_Start_IT() + (+) DMA mode : HAL_HASH_HMAC_Start_DMA() + + [..] In case of multi-buffer HMAC processing (a single digest is computed while + several buffers are fed to the Peripheral), the user can resort to successive calls + to : + (+) Polling mode : HAL_HASH_HMAC_Accumulate() and wrap-up the digest computation by a call + to HAL_HASH_HMAC_AccumulateLast() + (+) Interrupt mode : HAL_HASH_HMAC_Accumulate_IT() and wrap-up the digest computation by a call + to HAL_HASH_HMAC_AccumulateLast_IT() + (+) DMA mode : HAL_HASH_HMAC_Start_DMA(),MDMAT bit must be set through __HAL_HASH_SET_MDMAT() macro, + before entering the last buffer, reset the MDMAT bit with __HAL_HASH_RESET_MDMAT() + macro then wrap-up the HMAC processing in feeding the last input buffer through the + same API HAL_HASH_HMAC_Start_DMA() + +@endverbatim + * @{ + */ + +/** + * @brief HMAC in polling mode, HASH peripheral processes Key then pInBuffer then reads the computed 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. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_Start(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer, uint32_t Timeout) +{ + uint32_t blocksize; /* Block size in bytes */ + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HASH Phase */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Reset HashInCount and Initialize Size, pHashKeyBuffPtr, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->HashInCount = 0U; + hhash->Size = Size; + + /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting bits */ + if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) + { + blocksize = BLOCK_64B; + } + else + { + blocksize = BLOCK_128B; + } + if (hhash->Init.KeySize > blocksize) + { + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); + } + else + { + + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_CR_INIT); + } + + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + /* Write Key */ + HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); + + /* Start the Key padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); + + /* Write message */ + HASH_WriteData(hhash, pInBuffer, Size); + + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + /* Write Key */ + HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); + + /* Start the Key padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for digest calculation completion status(DCIS) flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Read the message digest */ + HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Change the HASH phase */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + /* Return function status */ + return HAL_OK; + + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief HMAC accumulate mode, HASH peripheral processes Key then several input buffers. + * @note Consecutive calls to HAL_HASH_HMAC_Accumulate() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * HAL_HASH_HMAC_AccumulateLast() + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes and a multiple of 4 + * @param Timeout specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_Accumulate(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint32_t Timeout) +{ + uint32_t blocksize; /* Block size in bytes */ + + /* Check the hash handle allocation and buffer length multiple of 4 */ + if ((hhash == NULL) || ((Size % 4U) != 0U)) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Initialize Size, pHashInBuffPtr and pHashKeyBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->Size = Size; + + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Reset HashInCount parameter */ + hhash->HashInCount = 0U; + /* Check if key size is larger than 64 bytes, accordingly set LKEY and the other setting bits */ + /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting */ + if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) + { + blocksize = BLOCK_64B; + } + else + { + blocksize = BLOCK_128B; + } + if (hhash->Init.KeySize > blocksize) + { + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); + } + else + { + + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_CR_INIT); + } + /* Set phase process */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + /* Write Key */ + HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); + + /* Start the Key padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + } + + /* Change the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); + + /* Write message */ + HASH_WriteData(hhash, pInBuffer, Size); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + /* Return function status */ + return HAL_OK; + + } + else + { + return HAL_BUSY; + } +} +/** + * @brief End computation of a single HMAC signature after several calls to HAL_HASH_HMAC_Accumulate() API. + * @note 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. + * @param pOutBuffer pointer to the computed digest. + * @param Timeout specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_AccumulateLast(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer, uint32_t Timeout) +{ + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Initialize Size, pHashInBuffPtr, pHashKeyBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->Size = Size; + + if (hhash->Phase != HAL_HASH_PHASE_PROCESS) + { + return HAL_ERROR; + } + else + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (Size % 4U)); + + /* Write message */ + HASH_WriteData(hhash, pInBuffer, Size); + + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for BUSY flag to be cleared */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + /* Write Key */ + HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); + + /* Start the Key padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for digest calculation completion status(DCIS) flag to be set */ + if (HASH_WaitOnFlagUntilTimeout(hhash, HASH_FLAG_DCIS, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Read the message digest */ + HASH_GetDigest(hhash, pOutBuffer, HASH_DIGEST_LENGTH(hhash)); + } + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief HMAC in interrupt mode, HASH peripheral process Key then pInBuffer then read the computed 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. + * @param pOutBuffer pointer to the computed digest. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_Start_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer) +{ + HAL_StatusTypeDef status; + uint32_t blocksize; /* Block size in bytes */ + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HASH Phase */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Reset HashInCount and Initialize Size, pHashKeyBuffPtr, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->HashInCount = 0U; + hhash->Size = Size; + + /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting bits */ + if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) + { + blocksize = BLOCK_64B; + } + else + { + blocksize = BLOCK_128B; + } + if (hhash->Init.KeySize > blocksize) + { + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); + } + else + { + + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_CR_INIT); + } + + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + else if (hhash->State == HAL_HASH_STATE_SUSPENDED) + { + /* Process Locked */ + __HAL_LOCK(hhash); + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + } + else + { + return HAL_BUSY; + } + + /* Enable the specified HASH interrupt*/ + __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + status = HASH_WriteData_IT(hhash); + + /* Return function status */ + return status; +} + +/** + * @brief HMAC accumulate in interrupt mode, HASH peripheral processes Key then several input buffers. + * @note Consecutive calls to HAL_HASH_HMAC_Accumulate_IT() can be used to feed + * several input buffers back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * HAL_HASH_HMAC_AccumulateLast_IT() + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes and a multiple of 4. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_Accumulate_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size) +{ + HAL_StatusTypeDef status; + uint32_t blocksize; /* Block size in bytes */ + + /* Check the hash handle allocation and buffer length multiple of 4 */ + if ((hhash == NULL) || ((Size % 4U) != 0U)) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process */ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->HashInCount = 0U; + hhash->Size = Size; + /* Set multi buffers accumulation flag */ + hhash->Accumulation = 1U; + + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting */ + if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) + { + blocksize = BLOCK_64B; + } + else + { + blocksize = BLOCK_128B; + } + if (hhash->Init.KeySize > blocksize) + { + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); + } + else + { + + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_CR_INIT); + } + + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_PROCESS; + } + /* Enable the specified HASH interrupt*/ + __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + status = HASH_WriteData_IT(hhash); + } + else + { + status = HAL_BUSY; + } + /* Return function status */ + return status; +} +/** + * @brief End computation of a single HMAC signature in interrupt mode, after + * several calls to HAL_HASH_HMAC_Accumulate() API. + * @note 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. + * @param pOutBuffer pointer to the computed digest. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_AccumulateLast_IT(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, + uint32_t Size, uint8_t *const pOutBuffer) +{ + HAL_StatusTypeDef status; + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process*/ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->HashInCount = 0U; + hhash->Size = Size; + /* Set multi buffers accumulation flag */ + hhash->Accumulation = 0U; + /* Enable the specified HASH interrupt*/ + __HAL_HASH_ENABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + status = HASH_WriteData_IT(hhash); + } + else + { + status = HAL_BUSY; + } + /* Return function status */ + return status; +} + +/** + * @brief HMAC in DMA mode,HASH peripheral processes Key then pInBuffer in DMA mode + * then read the computed digest. + * @note Multi-buffer HMAC processing is possible, consecutive calls to HAL_HASH_HMAC_Start_DMA + * (MDMAT bit must be set) can be used to feed several input buffers + * back-to-back to the Peripheral that will yield a single + * HASH signature once all buffers have been entered. Wrap-up of input + * buffers feeding and retrieval of digest is done by a call to + * HAL_HASH_HMAC_Start_DMA (MDMAT bit must be reset). + * @param hhash HASH handle. + * @param pInBuffer pointer to the input buffer (buffer to be hashed). + * @param Size length of the input buffer in bytes. + * @param pOutBuffer pointer to the computed digest. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HASH_HMAC_Start_DMA(HASH_HandleTypeDef *hhash, const uint8_t *const pInBuffer, uint32_t Size, + uint8_t *const pOutBuffer) +{ + HAL_StatusTypeDef status; + uint32_t count; + uint32_t blocksize; /* Block size in bytes */ + + /* Check the hash handle allocation */ + if (hhash == NULL) + { + return HAL_ERROR; + } + + /* Check if peripheral is ready to start process*/ + if (hhash->State == HAL_HASH_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hhash); + + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /* Reset HashInCount and Initialize Size, pHashInBuffPtr and pHashOutBuffPtr parameters */ + hhash->pHashInBuffPtr = pInBuffer; + hhash->pHashOutBuffPtr = pOutBuffer; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + hhash->HashInCount = 0U; + hhash->Size = Size; + + /* Set the phase */ + if (hhash->Phase == HAL_HASH_PHASE_READY) + { + /* Check if key size is larger than block size of the algorithm, accordingly set LKEY and the other setting */ + if ((hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA1) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA224) || + (hhash->Init.Algorithm == HASH_ALGOSELECTION_SHA256)) + { + blocksize = BLOCK_64B; + } + else + { + blocksize = BLOCK_128B; + } + if (hhash->Init.KeySize > blocksize) + { + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_LONGKEY | HASH_CR_INIT); + } + else + { + + MODIFY_REG(hhash->Instance->CR, HASH_CR_LKEY | HASH_CR_MODE | HASH_CR_INIT, + HASH_ALGOMODE_HMAC | HASH_CR_INIT); + } + + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_1; + + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + /* Write Key */ + HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); + + /* Start the Key padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for DCIS flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_BUSY)); + } + + hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_2; + if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Size) % 4U)); + } + else + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); + } + } + else if (hhash->State == HAL_HASH_STATE_SUSPENDED) + { + /* Process Locked */ + __HAL_LOCK(hhash); + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_BUSY; + + /*only part not yet hashed to compute */ + hhash->Size = hhash->HashInCount; + } + + else + { + /* Return busy status */ + return HAL_BUSY; + } + + /* Set the HASH DMA transfer complete callback */ + hhash->hdmain->XferCpltCallback = HASH_DMAXferCplt; + /* Set the DMA error callback */ + hhash->hdmain->XferErrorCallback = HASH_DMAError; + + if ((hhash->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hhash->hdmain->LinkedListQueue != NULL) && (hhash->hdmain->LinkedListQueue->Head != NULL)) + { + /* Enable the DMA channel */ + hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET]\ + = ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : ((hhash->Size))); + hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET]\ + = (uint32_t)(hhash->pHashInBuffPtr); /* Set DMA source address */ + hhash->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET]\ + = (uint32_t)&hhash->Instance->DIN; /* Set DMA destination address */ + + status = HAL_DMAEx_List_Start_IT(hhash->hdmain); + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hhash->hdmain, (uint32_t)(hhash->pHashInBuffPtr), (uint32_t)&hhash->Instance->DIN, \ + ((((hhash->Size) % 4U) != 0U) ? ((hhash->Size) + (4U - ((hhash->Size) % 4U))) : \ + ((hhash->Size)))); + } + if (status != HAL_OK) + { + /* DMA error code field */ + hhash->ErrorCode |= HAL_HASH_ERROR_DMA; + + /* Return error */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hhash->ErrorCallback(hhash); +#else + /*Call legacy weak error callback*/ + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + else + { + /* Enable DMA requests */ + SET_BIT(hhash->Instance->CR, HASH_CR_DMAE); + } + + /* Return function status */ + return status; +} + + +/** + * @} + */ + +/** @defgroup HASH_Exported_Functions_Group4 HASH IRQ handler management + * @brief HASH IRQ handler. + * +@verbatim + ============================================================================== + ##### HASH IRQ handler management ##### + ============================================================================== +[..] This section provides HASH IRQ handler and callback functions. + (+) HAL_HASH_IRQHandler HASH interrupt request + (+) HAL_HASH_InCpltCallback input data transfer complete callback + (+) HAL_HASH_DgstCpltCallback digest computation complete callback + (+) HAL_HASH_ErrorCallback HASH error callback + (+) HAL_HASH_GetState return the HASH state + (+) HAL_HASH_GetError return the HASH error code +@endverbatim + * @{ + */ + +/** + * @brief Handle HASH interrupt request. + * @param hhash HASH handle. + * @note HAL_HASH_IRQHandler() handles interrupts in HMAC processing as well. + * @retval None + */ +void HAL_HASH_IRQHandler(HASH_HandleTypeDef *hhash) +{ + HAL_StatusTypeDef status; + uint32_t itsource = hhash->Instance->IMR; + uint32_t itflag = hhash->Instance->SR; + + /* If digest is ready */ + if ((itflag & HASH_FLAG_DCIS) == HASH_FLAG_DCIS) + { + /* Read the digest */ + HASH_GetDigest(hhash, hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH(hhash)); + + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_READY; + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + /* Call digest computation complete call back */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->DgstCpltCallback(hhash); +#else + HAL_HASH_DgstCpltCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + + } + /* If Peripheral ready to accept new data */ + if ((itflag & HASH_FLAG_DINIS) == HASH_FLAG_DINIS) + { + if ((itsource & HASH_IT_DINI) == HASH_IT_DINI) + { + status = HASH_WriteData_IT(hhash); + if (status != HAL_OK) + { + /* Call error callback */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->ErrorCallback(hhash); +#else + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + } + } +} + +/** + * @brief Input data transfer complete call back. + * @note HAL_HASH_InCpltCallback() is called when the complete input message + * has been fed to the Peripheral. This API is invoked only when input data are + * entered under interruption or through DMA. + * @note In case of HASH or HMAC multi-buffer DMA feeding case (MDMAT bit set), + * HAL_HASH_InCpltCallback() is called at the end of each buffer feeding + * to the Peripheral. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval None + */ +__weak void HAL_HASH_InCpltCallback(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + HAL_HASH_InCpltCallback() can be implemented in the user file. + */ +} + +/** + * @brief Digest computation complete call back. + * @note HAL_HASH_DgstCpltCallback() is used under interruption, is not + * relevant with DMA. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval None + */ +__weak void HAL_HASH_DgstCpltCallback(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + HAL_HASH_DgstCpltCallback() can be implemented in the user file. + */ +} + +/** + * @brief HASH error callback. + * @note Code user can resort to hhash->Status (HAL_ERROR, HAL_TIMEOUT,...) + * to retrieve the error type. + * @param hhash pointer to a HASH_HandleTypeDef structure that contains + * the configuration information for HASH module. + * @retval None + */ +__weak void HAL_HASH_ErrorCallback(HASH_HandleTypeDef *hhash) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhash); + + /* NOTE : This function should not be modified; when the callback is needed, + HAL_HASH_ErrorCallback() can be implemented in the user file. + */ +} + +/** + * @brief Return the HASH handle state. + * @note The API yields the current state of the handle (BUSY, READY,...). + * @param hhash HASH handle. + * @retval HAL HASH state + */ +HAL_HASH_StateTypeDef HAL_HASH_GetState(const HASH_HandleTypeDef *hhash) +{ + return hhash->State; +} + +/** + * @brief Return the HASH handle error code. + * @param hhash pointer to a HASH_HandleTypeDef structure. + * @retval HASH Error Code + */ +uint32_t HAL_HASH_GetError(const HASH_HandleTypeDef *hhash) +{ + /* Return HASH Error Code */ + return hhash->ErrorCode; +} +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup HASH_Private_Functions + * @{ + */ + +/** + * @brief DMA HASH Input Data transfer completion 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 count; + + if (READ_BIT(hhash->Instance->CR, HASH_CR_MODE) == 0U) + { + if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) + { + /* Disable the DMA transfer */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_DMAE); + + + /* Wait for DCIS flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->ErrorCallback(hhash); +#else + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); + /* Call Input data transfer complete call back */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->InCpltCallback(hhash); +#else + HAL_HASH_InCpltCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + + /* Read the message digest */ + HASH_GetDigest(hhash, hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH(hhash)); + + /* Change the HASH state to ready */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Process UnLock */ + __HAL_UNLOCK(hhash); + + /* Call digest complete call back */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->DgstCpltCallback(hhash); +#else + HAL_HASH_DgstCpltCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + else + { + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + } + } + else /*HMAC DMA*/ + { + if (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_2) + { + if ((hhash->Instance->CR & HASH_CR_MDMAT) == 0U) + { + /* Set the phase */ + hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_3; + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + /* Write Key */ + HASH_WriteData(hhash, hhash->Init.pKey, hhash->Init.KeySize); + + /* Start the Key padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for DCIS flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable the DMA transfer */ + CLEAR_BIT(hhash->Instance->CR, HASH_CR_DMAE); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_DMA; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->ErrorCallback(hhash); +#else + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); + + /* Read the message digest */ + HASH_GetDigest(hhash, hhash->pHashOutBuffPtr, HASH_DIGEST_LENGTH(hhash)); + + /* Change the HASH state to ready */ + hhash->State = HAL_HASH_STATE_READY; + + /* Reset HASH state machine */ + hhash->Phase = HAL_HASH_PHASE_READY; + + /* Process UnLock */ + __HAL_UNLOCK(hhash); + + /* Call digest complete call back */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->DgstCpltCallback(hhash); +#else + HAL_HASH_DgstCpltCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + + } + else + { + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + hhash->Accumulation = 1; + } + } + } +} + +/** + * @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->ErrorCode |= HAL_HASH_ERROR_DMA; + /* Set HASH state to ready to prevent any blocking issue in user code + present in HAL_HASH_ErrorCallback() */ + hhash->State = HAL_HASH_STATE_READY; + +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1) + hhash->ErrorCallback(hhash); +#else + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ +} + +/** + * @brief Feed the input buffer to the HASH peripheral in polling. + * @param hhash HASH handle. + * @param pInBuffer pointer to input buffer. + * @param Size the size of input buffer in bytes. + * @retval HAL status + */ +static void HASH_WriteData(HASH_HandleTypeDef *hhash, const uint8_t *pInBuffer, uint32_t Size) +{ + uint32_t buffercounter; + __IO uint32_t inputaddr = (uint32_t) pInBuffer; + uint8_t tmp1; + uint8_t tmp2; + uint8_t tmp3; + + for (buffercounter = 0U; buffercounter < (Size / 4U) ; buffercounter++) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)inputaddr; + inputaddr += 4U; + hhash->HashInCount += 4U; + } + + if ((Size % 4U) != 0U) + { + if (hhash->Init.DataType == HASH_HALFWORD_SWAP) + { + /* Write remaining input data */ + if ((Size % 4U) <= 2U) + { + hhash->Instance->DIN = (uint32_t) * (uint16_t *)inputaddr; + } + if ((Size % 4U) == 3U) + { + hhash->Instance->DIN = *(uint32_t *)inputaddr; + } + } + else if ((hhash->Init.DataType == HASH_BYTE_SWAP) + || (hhash->Init.DataType == HASH_BIT_SWAP)) /* byte swap or bit swap or */ + { + /* Write remaining input data */ + if ((Size % 4U) == 1U) + { + hhash->Instance->DIN = (uint32_t) * (uint8_t *)inputaddr; + } + if ((Size % 4U) == 2U) + { + hhash->Instance->DIN = (uint32_t) * (uint16_t *)inputaddr; + } + if ((Size % 4U) == 3U) + { + tmp1 = *(uint8_t *)inputaddr; + tmp2 = *(((uint8_t *)inputaddr) + 1U); + tmp3 = *(((uint8_t *)inputaddr) + 2U); + hhash->Instance->DIN = ((uint32_t)tmp1) | ((uint32_t)tmp2 << 8U) | ((uint32_t)tmp3 << 16U); + } + } + else + { + hhash->Instance->DIN = *(uint32_t *)inputaddr; + } + hhash->HashInCount += 4U; + } +} + +/** + * @brief Feed the input buffer to the HASH peripheral in interruption mode. + * @param hhash HASH handle. + * @retval HAL status + */ +static HAL_StatusTypeDef HASH_WriteData_IT(HASH_HandleTypeDef *hhash) +{ + uint32_t buffercounter; + uint32_t count; + __IO uint32_t keyaddr = (uint32_t)(hhash->pHashKeyBuffPtr); + __IO uint32_t inputaddr = (uint32_t)(hhash->pHashInBuffPtr); + uint32_t nbbytePartialHash = (((hhash->Instance->SR) >> 16U) * 4U); /* Nb byte to enter in HASH fifo to trig + a partial HASH computation*/ + + if (hhash->State == HAL_HASH_STATE_BUSY) + { + if ((hhash->Instance->CR & HASH_CR_MODE) == 0U) + { +#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) + /* If suspension flag has been raised, suspend processing */ + if (hhash->SuspendRequest == HAL_HASH_SUSPEND) + { + /* reset SuspendRequest */ + hhash->SuspendRequest = HAL_HASH_SUSPEND_NONE; + /* Disable Computation Complete Flag and Errors Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_SUSPENDED; + __HAL_UNLOCK(hhash); + } + else + { +#endif /* USE_HAL_HASH_SUSPEND_RESUME */ + + if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Size)) + { + for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)inputaddr; + inputaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashInBuffPtr += 4U; + } + /* Wait for HASH_IT_DINI flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); + } + else + { + while ((hhash->HashInCount) < hhash->Size) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)inputaddr; + inputaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashInBuffPtr += 4U; + } + /* Call Input transfer complete callback */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) + /*Call registered Input complete callback*/ + hhash->InCpltCallback(hhash); +#else + /*Call legacy weak Input complete callback*/ + HAL_HASH_InCpltCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + if (hhash->Accumulation == 0U) + { + if (__HAL_HASH_GET_IT_SOURCE(hhash, HASH_IT_DINI)) + { + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for HASH_FLAG_DCIS flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); + } + } + else + { + /* Reset multi buffers accumulation flag */ + hhash->Accumulation = 0U; + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI); + } + } +#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) + } +#endif /* USE_HAL_HASH_SUSPEND_RESUME */ + } + else /*HMAC */ + { + if (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_2) /* loading input*/ + { +#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) + /* If suspension flag has been raised, suspend processing */ + if (hhash->SuspendRequest == HAL_HASH_SUSPEND) + { + /* reset SuspendRequest */ + hhash->SuspendRequest = HAL_HASH_SUSPEND_NONE; + /* Disable Computation Complete Flag and Errors Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + /* Change the HASH state */ + hhash->State = HAL_HASH_STATE_SUSPENDED; + __HAL_UNLOCK(hhash); + } + else + { +#endif /* USE_HAL_HASH_SUSPEND_RESUME */ + if (hhash->Accumulation == 1U) + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 0U); + } + else + { + /* Configure the number of valid bits in last word of the message */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * (hhash->Size % 4U)); + } + if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Size)) + { + for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)inputaddr; + inputaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashInBuffPtr += 4U; + } + /* Wait for HASH_IT_DINI flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); + } + else + { + while ((hhash->HashInCount) < hhash->Size) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)inputaddr; + inputaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashInBuffPtr += 4U; + } + /* Call Input transfer complete callback */ +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) + /*Call registered Input complete callback*/ + hhash->InCpltCallback(hhash); +#else + /*Call legacy weak Input complete callback*/ + HAL_HASH_InCpltCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + + if (hhash->Accumulation == 0U) + { + if (__HAL_HASH_GET_IT_SOURCE(hhash, HASH_IT_DINI)) + { + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for HASH_FLAG_BUSY flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_SET(hhash->Instance->SR, HASH_FLAG_BUSY)); + + hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_3; + hhash->HashInCount = 0U; + hhash->pHashKeyBuffPtr = hhash->Init.pKey; + } + } + + else + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_OK; + } + } +#if (USE_HAL_HASH_SUSPEND_RESUME == 1U) + } +#endif /* USE_HAL_HASH_SUSPEND_RESUME */ + } + + else if (hhash->Phase == HAL_HASH_PHASE_HMAC_STEP_3)/* loading Key*/ + { + + /* Configure the number of valid bits in last word of the Key */ + MODIFY_REG(hhash->Instance->STR, HASH_STR_NBLW, 8U * ((hhash->Init.KeySize) % 4U)); + + if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Init.KeySize)) + { + for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)keyaddr; + keyaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashKeyBuffPtr += 4U; + } + /* Wait for HASH_IT_DINI flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); + } + else + { + while ((hhash->HashInCount) < (hhash->Init.KeySize)) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)keyaddr; + keyaddr += 4U; + hhash->HashInCount += 4U; + } + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for HASH_FLAG_DCIS flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DCIS)); + } + } + else /*first step , loading key*/ + { + + hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_1; + + if (((hhash->HashInCount) + nbbytePartialHash) < (hhash->Init.KeySize)) + { + for (buffercounter = 0U; buffercounter < nbbytePartialHash ; buffercounter += 4U) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)keyaddr; + keyaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashKeyBuffPtr += 4U; + } + /* Wait for HASH_IT_DINI flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_CLR(hhash->Instance->SR, HASH_FLAG_DINIS)); + } + else + { + while ((hhash->HashInCount) < (hhash->Init.KeySize)) + { + /* Write input data 4 bytes at a time */ + hhash->Instance->DIN = *(uint32_t *)keyaddr; + keyaddr += 4U; + hhash->HashInCount += 4U; + hhash->pHashKeyBuffPtr += 4U; + } + /* Start the message padding then the Digest calculation */ + SET_BIT(hhash->Instance->STR, HASH_STR_DCAL); + + /* Wait for HASH_FLAG_BUSY flag to be set */ + count = HASH_TIMEOUTVALUE; + do + { + count--; + if (count == 0U) + { + /* Disable Interrupts */ + __HAL_HASH_DISABLE_IT(hhash, HASH_IT_DINI | HASH_IT_DCI); + + /* Change state */ + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + hhash->State = HAL_HASH_STATE_READY; + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } while (HAL_IS_BIT_SET(hhash->Instance->SR, HASH_FLAG_BUSY)); + /*change Phase to step 2*/ + hhash->Phase = HAL_HASH_PHASE_HMAC_STEP_2; + hhash->HashInCount = 0U; + } + } + } + } + else if ((hhash->State == HAL_HASH_STATE_SUSPENDED)) + { + return HAL_OK; + } + else + { + /* Busy error code field */ + hhash->ErrorCode |= HAL_HASH_ERROR_BUSY; +#if (USE_HAL_HASH_REGISTER_CALLBACKS == 1U) + /*Call registered error callback*/ + hhash->ErrorCallback(hhash); +#else + /*Call legacy weak error callback*/ + HAL_HASH_ErrorCallback(hhash); +#endif /* USE_HAL_HASH_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @brief Retrieve the message digest. + * @param hhash HASH handle + * @param pMsgDigest pointer to the computed digest. + * @param Size message digest size in bytes. + * @retval None + */ +static void HASH_GetDigest(const HASH_HandleTypeDef *hhash, const uint8_t *pMsgDigest, uint8_t Size) +{ + uint32_t msgdigest = (uint32_t)pMsgDigest; + + switch (Size) + { + case 20: /* SHA1 */ + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); + break; + + case 28: /* SHA224 */ + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); + + break; + case 32: /* SHA256 */ + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); + break; + case 48: /* SHA384 */ + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[8]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[9]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[10]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[11]); + break; + + case 64: /* SHA 512 */ + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[0]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[1]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[2]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[3]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(hhash->Instance->HR[4]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[5]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[6]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[7]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[8]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[9]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[10]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[11]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[12]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[13]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[14]); + msgdigest += 4U; + *(uint32_t *)(msgdigest) = __REV(HASH_DIGEST->HR[15]); + + break; + default: + break; + } +} + +/** + * @brief Handle HASH processing Timeout. + * @param hhash HASH handle. + * @param Flag specifies the HASH flag to check. + * @param Status the Flag status (SET or RESET). + * @param Timeout Timeout duration. + * @retval HAL status + */ +static HAL_StatusTypeDef HASH_WaitOnFlagUntilTimeout(HASH_HandleTypeDef *hhash, uint32_t Flag, FlagStatus Status, + uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if (Status == RESET) + { + while (__HAL_HASH_GET_FLAG(hhash, Flag) == RESET) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Set State to Ready to be able to restart later on */ + hhash->State = HAL_HASH_STATE_READY; + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + return HAL_ERROR; + } + } + } + } + else + { + while (__HAL_HASH_GET_FLAG(hhash, Flag) != RESET) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Set State to Ready to be able to restart later on */ + hhash->State = HAL_HASH_STATE_READY; + hhash->ErrorCode |= HAL_HASH_ERROR_TIMEOUT; + /* Process Unlocked */ + __HAL_UNLOCK(hhash); + + return HAL_ERROR; + } + } + } + } + return HAL_OK; +} + +/** + * @} + */ + + +#endif /* HAL_HASH_MODULE_ENABLED */ + +#endif /* HASH*/ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hcd.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hcd.c index 57cb5db53..50bd50fdc 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hcd.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_hcd.c @@ -1,1985 +1,1985 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_hcd.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 the following macros - (+++) __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); - (+++) __HAL_RCC_USB_OTG_HS_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 - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_HCD_MODULE_ENABLED -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) - -/** @defgroup HCD HCD - * @brief HCD HAL module driver - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup HCD_Private_Functions HCD Private Functions - * @{ - */ -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); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup HCD_Exported_Functions HCD Exported Functions - * @{ - */ - -/** @defgroup HCD_Exported_Functions_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 status - */ -HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) -{ -#if defined (USB_OTG_FS) - const USB_OTG_GlobalTypeDef *USBx; -#endif /* defined (USB_OTG_FS) */ - - /* Check the HCD handle allocation */ - if (hhcd == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_HCD_ALL_INSTANCE(hhcd->Instance)); - -#if defined (USB_OTG_FS) - USBx = hhcd->Instance; -#endif /* defined (USB_OTG_FS) */ - - if (hhcd->State == HAL_HCD_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hhcd->Lock = HAL_UNLOCKED; - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->SOFCallback = HAL_HCD_SOF_Callback; - hhcd->ConnectCallback = HAL_HCD_Connect_Callback; - hhcd->DisconnectCallback = HAL_HCD_Disconnect_Callback; - hhcd->PortEnabledCallback = HAL_HCD_PortEnabled_Callback; - hhcd->PortDisabledCallback = HAL_HCD_PortDisabled_Callback; - hhcd->HC_NotifyURBChangeCallback = HAL_HCD_HC_NotifyURBChange_Callback; - - if (hhcd->MspInitCallback == NULL) - { - hhcd->MspInitCallback = HAL_HCD_MspInit; - } - - /* Init the low level hardware */ - hhcd->MspInitCallback(hhcd); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC... */ - HAL_HCD_MspInit(hhcd); -#endif /* (USE_HAL_HCD_REGISTER_CALLBACKS) */ - } - - hhcd->State = HAL_HCD_STATE_BUSY; - -#if defined (USB_OTG_FS) - /* Disable DMA mode for FS instance */ - if (USBx == USB_OTG_FS) - { - hhcd->Init.dma_enable = 0U; - } -#endif /* defined (USB_OTG_FS) */ - - /* Disable the Interrupts */ - __HAL_HCD_DISABLE(hhcd); - - /* Init the Core (common init.) */ - if (USB_CoreInit(hhcd->Instance, hhcd->Init) != HAL_OK) - { - hhcd->State = HAL_HCD_STATE_ERROR; - return HAL_ERROR; - } - - /* Force Host Mode */ - if (USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE) != HAL_OK) - { - hhcd->State = HAL_HCD_STATE_ERROR; - return HAL_ERROR; - } - - /* Init Host */ - if (USB_HostInit(hhcd->Instance, hhcd->Init) != HAL_OK) - { - hhcd->State = HAL_HCD_STATE_ERROR; - return HAL_ERROR; - } - - hhcd->State = HAL_HCD_STATE_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 these values: - * HCD_DEVICE_SPEED_HIGH: High speed mode, - * HCD_DEVICE_SPEED_FULL: Full speed mode, - * HCD_DEVICE_SPEED_LOW: Low speed mode - * @param ep_type Endpoint Type. - * This parameter can be one of these values: - * EP_TYPE_CTRL: Control type, - * EP_TYPE_ISOC: Isochronous type, - * EP_TYPE_BULK: Bulk type, - * EP_TYPE_INTR: Interrupt type - * @param mps Max Packet Size. - * This parameter can be a value from 0 to32K - * @retval HAL status - */ -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; - uint32_t HostCoreSpeed; - uint32_t HCcharMps = mps; - - __HAL_LOCK(hhcd); - hhcd->hc[ch_num].do_ping = 0U; - hhcd->hc[ch_num].dev_addr = dev_address; - hhcd->hc[ch_num].ch_num = ch_num; - hhcd->hc[ch_num].ep_type = ep_type; - hhcd->hc[ch_num].ep_num = epnum & 0x7FU; - - (void)HAL_HCD_HC_ClearHubInfo(hhcd, ch_num); - - if ((epnum & 0x80U) == 0x80U) - { - hhcd->hc[ch_num].ep_is_in = 1U; - } - else - { - hhcd->hc[ch_num].ep_is_in = 0U; - } - - HostCoreSpeed = USB_GetHostSpeed(hhcd->Instance); - - if (ep_type == EP_TYPE_ISOC) - { - /* FS device plugged to HS HUB */ - if ((speed == HCD_DEVICE_SPEED_FULL) && (HostCoreSpeed == HPRT0_PRTSPD_HIGH_SPEED)) - { - if (HCcharMps > ISO_SPLT_MPS) - { - /* ISO Max Packet Size for Split mode */ - HCcharMps = ISO_SPLT_MPS; - } - } - } - - hhcd->hc[ch_num].speed = speed; - hhcd->hc[ch_num].max_packet = (uint16_t)HCcharMps; - - status = USB_HC_Init(hhcd->Instance, ch_num, epnum, - dev_address, speed, ep_type, (uint16_t)HCcharMps); - - __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 status - */ -HAL_StatusTypeDef HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num) -{ - HAL_StatusTypeDef status = HAL_OK; - - __HAL_LOCK(hhcd); - (void)USB_HC_Halt(hhcd->Instance, ch_num); - __HAL_UNLOCK(hhcd); - - return status; -} - -/** - * @brief DeInitialize the host driver. - * @param hhcd HCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd) -{ - /* Check the HCD handle allocation */ - if (hhcd == NULL) - { - return HAL_ERROR; - } - - hhcd->State = HAL_HCD_STATE_BUSY; - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - if (hhcd->MspDeInitCallback == NULL) - { - hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware */ - hhcd->MspDeInitCallback(hhcd); -#else - /* DeInit the low level hardware: CLOCK, NVIC.*/ - HAL_HCD_MspDeInit(hhcd); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - - __HAL_HCD_DISABLE(hhcd); - - hhcd->State = HAL_HCD_STATE_RESET; - - return HAL_OK; -} - -/** - * @brief Initialize the HCD MSP. - * @param hhcd HCD handle - * @retval None - */ -__weak void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitialize the HCD MSP. - * @param hhcd HCD handle - * @retval None - */ -__weak void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup HCD_Exported_Functions_Group2 Input and Output 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 these values: - * 0 : Output / 1 : Input - * @param ep_type Endpoint Type. - * This parameter can be one of these values: - * EP_TYPE_CTRL: Control type/ - * EP_TYPE_ISOC: Isochronous type/ - * EP_TYPE_BULK: Bulk type/ - * EP_TYPE_INTR: Interrupt type/ - * @param token Endpoint Type. - * This parameter can be one of these values: - * 0: HC_PID_SETUP / 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 these values: - * 0 : do ping inactive / 1 : do ping active - * @retval HAL status - */ -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 == 0U) - { - hhcd->hc[ch_num].data_pid = HC_PID_SETUP; - hhcd->hc[ch_num].do_ping = do_ping; - } - else - { - hhcd->hc[ch_num].data_pid = HC_PID_DATA1; - } - - /* Manage Data Toggle */ - switch (ep_type) - { - case EP_TYPE_CTRL: - if (token == 1U) /* send data */ - { - if (direction == 0U) - { - if (length == 0U) - { - /* For Status OUT stage, Length == 0U, Status Out PID = 1 */ - hhcd->hc[ch_num].toggle_out = 1U; - } - - /* Set the Data Toggle bit as per the Flag */ - if (hhcd->hc[ch_num].toggle_out == 0U) - { - /* 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].do_ssplit == 1U) - { - if (hhcd->hc[ch_num].toggle_in == 0U) - { - hhcd->hc[ch_num].data_pid = HC_PID_DATA0; - } - else - { - hhcd->hc[ch_num].data_pid = HC_PID_DATA1; - } - } - } - } - break; - - case EP_TYPE_BULK: - if (direction == 0U) - { - /* Set the Data Toggle bit as per the Flag */ - if (hhcd->hc[ch_num].toggle_out == 0U) - { - /* 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 == 0U) - { - 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 == 0U) - { - /* Set the Data Toggle bit as per the Flag */ - if (hhcd->hc[ch_num].toggle_out == 0U) - { - /* 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 == 0U) - { - 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; - - default: - 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 = 0U; - 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], (uint8_t)hhcd->Init.dma_enable); -} - -/** - * @brief Handle HCD interrupt request. - * @param hhcd HCD handle - * @retval None - */ -void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) -{ - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t i; - uint32_t interrupt; - - /* 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)) - { - __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_DISCINT); - - if ((USBx_HPRT0 & USB_OTG_HPRT_PCSTS) == 0U) - { - /* Flush USB Fifo */ - (void)USB_FlushTxFifo(USBx, 0x10U); - (void)USB_FlushRxFifo(USBx); - - if (hhcd->Init.phy_itface == USB_OTG_EMBEDDED_PHY) - { - /* Restore FS Clock */ - (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); - } - - /* Handle Host Port Disconnect Interrupt */ -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->DisconnectCallback(hhcd); -#else - HAL_HCD_Disconnect_Callback(hhcd); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - } - - /* Handle Host Port Interrupts */ - if (__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HPRTINT)) - { - HCD_Port_IRQHandler(hhcd); - } - - /* Handle Host SOF Interrupt */ - if (__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_SOF)) - { -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->SOFCallback(hhcd); -#else - HAL_HCD_SOF_Callback(hhcd); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - - __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_SOF); - } - - /* Handle Host channel Interrupt */ - if (__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HCINT)) - { - interrupt = USB_HC_ReadInterrupt(hhcd->Instance); - for (i = 0U; i < hhcd->Init.Host_channels; i++) - { - if ((interrupt & (1UL << (i & 0xFU))) != 0U) - { - if ((USBx_HC(i)->HCCHAR & USB_OTG_HCCHAR_EPDIR) == USB_OTG_HCCHAR_EPDIR) - { - HCD_HC_IN_IRQHandler(hhcd, (uint8_t)i); - } - else - { - HCD_HC_OUT_IRQHandler(hhcd, (uint8_t)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)) != 0U) - { - 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_SOF_Callback could be implemented in the user file - */ -} - -/** - * @brief Connection Event callback. - * @param hhcd HCD handle - * @retval None - */ -__weak void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_Connect_Callback could be implemented in the user file - */ -} - -/** - * @brief Disconnection Event callback. - * @param hhcd HCD handle - * @retval None - */ -__weak void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_Disconnect_Callback could be implemented in the user file - */ -} - -/** - * @brief Port Enabled Event callback. - * @param hhcd HCD handle - * @retval None - */ -__weak void HAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_Disconnect_Callback could be implemented in the user file - */ -} - -/** - * @brief Port Disabled Event callback. - * @param hhcd HCD handle - * @retval None - */ -__weak void HAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_Disconnect_Callback could be implemented 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 these values: - * URB_IDLE/ - * URB_DONE/ - * URB_NOTREADY/ - * URB_NYET/ - * URB_ERROR/ - * URB_STALL/ - * @retval None - */ -__weak void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hhcd); - UNUSED(chnum); - UNUSED(urb_state); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_HCD_HC_NotifyURBChange_Callback could be implemented in the user file - */ -} - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a User USB HCD Callback - * To be used instead of the weak predefined callback - * @param hhcd USB HCD handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_HCD_SOF_CB_ID USB HCD SOF callback ID - * @arg @ref HAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID - * @arg @ref HAL_HCD_DISCONNECT_CB_ID OTG HCD Disconnect callback ID - * @arg @ref HAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enable callback ID - * @arg @ref HAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disable callback ID - * @arg @ref HAL_HCD_MSPINIT_CB_ID MspDeInit callback ID - * @arg @ref HAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_RegisterCallback(HCD_HandleTypeDef *hhcd, - HAL_HCD_CallbackIDTypeDef CallbackID, - pHCD_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hhcd); - - if (hhcd->State == HAL_HCD_STATE_READY) - { - switch (CallbackID) - { - case HAL_HCD_SOF_CB_ID : - hhcd->SOFCallback = pCallback; - break; - - case HAL_HCD_CONNECT_CB_ID : - hhcd->ConnectCallback = pCallback; - break; - - case HAL_HCD_DISCONNECT_CB_ID : - hhcd->DisconnectCallback = pCallback; - break; - - case HAL_HCD_PORT_ENABLED_CB_ID : - hhcd->PortEnabledCallback = pCallback; - break; - - case HAL_HCD_PORT_DISABLED_CB_ID : - hhcd->PortDisabledCallback = pCallback; - break; - - case HAL_HCD_MSPINIT_CB_ID : - hhcd->MspInitCallback = pCallback; - break; - - case HAL_HCD_MSPDEINIT_CB_ID : - hhcd->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hhcd->State == HAL_HCD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_HCD_MSPINIT_CB_ID : - hhcd->MspInitCallback = pCallback; - break; - - case HAL_HCD_MSPDEINIT_CB_ID : - hhcd->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hhcd); - return status; -} - -/** - * @brief Unregister an USB HCD Callback - * USB HCD callback is redirected to the weak predefined callback - * @param hhcd USB HCD handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_HCD_SOF_CB_ID USB HCD SOF callback ID - * @arg @ref HAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID - * @arg @ref HAL_HCD_DISCONNECT_CB_ID OTG HCD Disconnect callback ID - * @arg @ref HAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enabled callback ID - * @arg @ref HAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disabled callback ID - * @arg @ref HAL_HCD_MSPINIT_CB_ID MspDeInit callback ID - * @arg @ref HAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_UnRegisterCallback(HCD_HandleTypeDef *hhcd, HAL_HCD_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hhcd); - - /* Setup Legacy weak Callbacks */ - if (hhcd->State == HAL_HCD_STATE_READY) - { - switch (CallbackID) - { - case HAL_HCD_SOF_CB_ID : - hhcd->SOFCallback = HAL_HCD_SOF_Callback; - break; - - case HAL_HCD_CONNECT_CB_ID : - hhcd->ConnectCallback = HAL_HCD_Connect_Callback; - break; - - case HAL_HCD_DISCONNECT_CB_ID : - hhcd->DisconnectCallback = HAL_HCD_Disconnect_Callback; - break; - - case HAL_HCD_PORT_ENABLED_CB_ID : - hhcd->PortEnabledCallback = HAL_HCD_PortEnabled_Callback; - break; - - case HAL_HCD_PORT_DISABLED_CB_ID : - hhcd->PortDisabledCallback = HAL_HCD_PortDisabled_Callback; - break; - - case HAL_HCD_MSPINIT_CB_ID : - hhcd->MspInitCallback = HAL_HCD_MspInit; - break; - - case HAL_HCD_MSPDEINIT_CB_ID : - hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; - break; - - default : - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hhcd->State == HAL_HCD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_HCD_MSPINIT_CB_ID : - hhcd->MspInitCallback = HAL_HCD_MspInit; - break; - - case HAL_HCD_MSPDEINIT_CB_ID : - hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; - break; - - default : - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hhcd); - return status; -} - -/** - * @brief Register USB HCD Host Channel Notify URB Change Callback - * To be used instead of the weak HAL_HCD_HC_NotifyURBChange_Callback() predefined callback - * @param hhcd HCD handle - * @param pCallback pointer to the USB HCD Host Channel Notify URB Change Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_RegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd, - pHCD_HC_NotifyURBChangeCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hhcd); - - if (hhcd->State == HAL_HCD_STATE_READY) - { - hhcd->HC_NotifyURBChangeCallback = pCallback; - } - else - { - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hhcd); - - return status; -} - -/** - * @brief Unregister the USB HCD Host Channel Notify URB Change Callback - * USB HCD Host Channel Notify URB Change Callback is redirected - * to the weak HAL_HCD_HC_NotifyURBChange_Callback() predefined callback - * @param hhcd HCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_UnRegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hhcd); - - if (hhcd->State == HAL_HCD_STATE_READY) - { - hhcd->HC_NotifyURBChangeCallback = HAL_HCD_HC_NotifyURBChange_Callback; /* Legacy weak DataOutStageCallback */ - } - else - { - /* Update the error code */ - hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hhcd); - - return status; -} -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup HCD_Exported_Functions_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 status - */ -HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd) -{ - __HAL_LOCK(hhcd); - /* Enable port power */ - (void)USB_DriveVbus(hhcd->Instance, 1U); - - /* Enable global interrupt */ - __HAL_HCD_ENABLE(hhcd); - __HAL_UNLOCK(hhcd); - - return HAL_OK; -} - -/** - * @brief Stop the host driver. - * @param hhcd HCD handle - * @retval HAL status - */ - -HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd) -{ - __HAL_LOCK(hhcd); - (void)USB_StopHost(hhcd->Instance); - __HAL_UNLOCK(hhcd); - - return HAL_OK; -} - -/** - * @brief Reset the host port. - * @param hhcd HCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd) -{ - return (USB_ResetPort(hhcd->Instance)); -} - -/** - * @} - */ - -/** @defgroup HCD_Exported_Functions_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. - -@endverbatim - * @{ - */ - -/** - * @brief Return the HCD handle state. - * @param hhcd HCD handle - * @retval HAL state - */ -HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef const *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 these values: - * URB_IDLE/ - * URB_DONE/ - * URB_NOTREADY/ - * URB_NYET/ - * URB_ERROR/ - * URB_STALL - */ -HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef const *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 const *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 these values: - * HC_IDLE/ - * HC_XFRC/ - * HC_HALTED/ - * HC_NYET/ - * HC_NAK/ - * HC_STALL/ - * HC_XACTERR/ - * HC_BBLERR/ - * HC_DATATGLERR - */ -HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef const *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 Set host channel Hub information. - * @param hhcd HCD handle - * @param ch_num Channel number. - * This parameter can be a value from 1 to 15 - * @param addr Hub address - * @param PortNbr Hub port number - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_HC_SetHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num, - uint8_t addr, uint8_t PortNbr) -{ - uint32_t HostCoreSpeed = USB_GetHostSpeed(hhcd->Instance); - - /* LS/FS device plugged to HS HUB */ - if ((hhcd->hc[ch_num].speed != HCD_DEVICE_SPEED_HIGH) && (HostCoreSpeed == HPRT0_PRTSPD_HIGH_SPEED)) - { - hhcd->hc[ch_num].do_ssplit = 1U; - - if ((hhcd->hc[ch_num].ep_type == EP_TYPE_CTRL) && (hhcd->hc[ch_num].ep_is_in != 0U)) - { - hhcd->hc[ch_num].toggle_in = 1U; - } - } - - hhcd->hc[ch_num].hub_addr = addr; - hhcd->hc[ch_num].hub_port_nbr = PortNbr; - - return HAL_OK; -} - - -/** - * @brief Clear host channel hub information. - * @param hhcd HCD handle - * @param ch_num Channel number. - * This parameter can be a value from 1 to 15 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HCD_HC_ClearHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num) -{ - hhcd->hc[ch_num].do_ssplit = 0U; - hhcd->hc[ch_num].do_csplit = 0U; - hhcd->hc[ch_num].hub_addr = 0U; - hhcd->hc[ch_num].hub_port_nbr = 0U; - - return HAL_OK; -} -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup HCD_Private_Functions - * @{ - */ -/** - * @brief Handle 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) -{ - const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - - if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_AHBERR)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_AHBERR); - hhcd->hc[chnum].state = HC_XACTERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_BBERR)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_BBERR); - hhcd->hc[chnum].state = HC_BBLERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_STALL)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_STALL); - hhcd->hc[chnum].state = HC_STALL; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_DTERR)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_DTERR); - hhcd->hc[chnum].state = HC_DATATGLERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_TXERR)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR); - hhcd->hc[chnum].state = HC_XACTERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else - { - /* ... */ - } - - if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_FRMOR)) - { - (void)USB_HC_Halt(hhcd->Instance, chnum); - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_FRMOR); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_XFRC)) - { - /* Clear any pending ACK IT */ - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); - - if (hhcd->hc[chnum].do_csplit == 1U) - { - hhcd->hc[chnum].do_csplit = 0U; - __HAL_HCD_CLEAR_HC_CSPLT(chnum); - } - - if (hhcd->Init.dma_enable != 0U) - { - hhcd->hc[chnum].xfer_count = hhcd->hc[chnum].XferSize - (USBx_HC(chnum)->HCTSIZ & USB_OTG_HCTSIZ_XFRSIZ); - } - - hhcd->hc[chnum].state = HC_XFRC; - hhcd->hc[chnum].ErrCnt = 0U; - __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)) - { - (void)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) || - (hhcd->hc[chnum].ep_type == EP_TYPE_ISOC)) - { - USBx_HC(chnum)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM; - hhcd->hc[chnum].urb_state = URB_DONE; - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#else - HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - else - { - /* ... */ - } - - if (hhcd->Init.dma_enable == 1U) - { - if ((((hhcd->hc[chnum].xfer_count + hhcd->hc[chnum].max_packet - 1U) / hhcd->hc[chnum].max_packet) & 1U) != 0U) - { - hhcd->hc[chnum].toggle_in ^= 1U; - } - } - else - { - hhcd->hc[chnum].toggle_in ^= 1U; - } - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_ACK)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); - - if (hhcd->hc[chnum].do_ssplit == 1U) - { - hhcd->hc[chnum].do_csplit = 1U; - hhcd->hc[chnum].state = HC_ACK; - - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_CHH)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); - - if (hhcd->hc[chnum].state == HC_XFRC) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_DONE; - } - else if (hhcd->hc[chnum].state == HC_STALL) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_STALL; - } - else if ((hhcd->hc[chnum].state == HC_XACTERR) || - (hhcd->hc[chnum].state == HC_DATATGLERR)) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].ErrCnt++; - if (hhcd->hc[chnum].ErrCnt > 2U) - { - hhcd->hc[chnum].ErrCnt = 0U; - - if (hhcd->hc[chnum].do_ssplit == 1U) - { - hhcd->hc[chnum].do_csplit = 0U; - hhcd->hc[chnum].ep_ss_schedule = 0U; - __HAL_HCD_CLEAR_HC_CSPLT(chnum); - } - - hhcd->hc[chnum].urb_state = URB_ERROR; - } - else - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - - if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || - (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) - { - /* re-activate the channel */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - } - } - } - else if (hhcd->hc[chnum].state == HC_NYET) - { - hhcd->hc[chnum].state = HC_HALTED; - - if (hhcd->hc[chnum].do_csplit == 1U) - { - if (hhcd->hc[chnum].ep_type == EP_TYPE_INTR) - { - hhcd->hc[chnum].NyetErrCnt++; - if (hhcd->hc[chnum].NyetErrCnt > 2U) - { - hhcd->hc[chnum].NyetErrCnt = 0U; - hhcd->hc[chnum].do_csplit = 0U; - - if (hhcd->hc[chnum].ErrCnt < 3U) - { - hhcd->hc[chnum].ep_ss_schedule = 1U; - } - __HAL_HCD_CLEAR_HC_CSPLT(chnum); - hhcd->hc[chnum].urb_state = URB_ERROR; - } - else - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - } - } - else - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - } - - if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || - (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) - { - /* re-activate the channel */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - } - } - } - else if (hhcd->hc[chnum].state == HC_ACK) - { - hhcd->hc[chnum].state = HC_HALTED; - - if (hhcd->hc[chnum].do_csplit == 1U) - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - - /* Set Complete split and re-activate the channel */ - USBx_HC(chnum)->HCSPLT |= USB_OTG_HCSPLT_COMPLSPLT; - USBx_HC(chnum)->HCINTMSK |= USB_OTG_HCINTMSK_NYET; - USBx_HC(chnum)->HCINTMSK &= ~USB_OTG_HCINT_ACK; - - if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || - (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) - { - /* re-activate the channel */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - } - } - } - else if (hhcd->hc[chnum].state == HC_NAK) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_NOTREADY; - - if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || - (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) - { - /* re-activate the channel */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - } - } - else if (hhcd->hc[chnum].state == HC_BBLERR) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].ErrCnt++; - hhcd->hc[chnum].urb_state = URB_ERROR; - } - else - { - if (hhcd->hc[chnum].state == HC_HALTED) - { - return; - } - } - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#else - HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NYET)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); - hhcd->hc[chnum].state = HC_NYET; - - if (hhcd->hc[chnum].do_ssplit == 0U) - { - hhcd->hc[chnum].ErrCnt = 0U; - } - - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NAK)) - { - if (hhcd->hc[chnum].ep_type == EP_TYPE_INTR) - { - hhcd->hc[chnum].ErrCnt = 0U; - hhcd->hc[chnum].state = HC_NAK; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || - (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) - { - hhcd->hc[chnum].ErrCnt = 0U; - - if ((hhcd->Init.dma_enable == 0U) || (hhcd->hc[chnum].do_csplit == 1U)) - { - hhcd->hc[chnum].state = HC_NAK; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - } - else - { - /* ... */ - } - - if (hhcd->hc[chnum].do_csplit == 1U) - { - hhcd->hc[chnum].do_csplit = 0U; - __HAL_HCD_CLEAR_HC_CSPLT(chnum); - __HAL_HCD_UNMASK_ACK_HC_INT(chnum); - } - - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK); - } - else - { - /* ... */ - } -} - -/** - * @brief Handle 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) -{ - const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - uint32_t num_packets; - - if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_AHBERR)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_AHBERR); - hhcd->hc[chnum].state = HC_XACTERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_ACK)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); - - if (hhcd->hc[chnum].do_ping == 1U) - { - hhcd->hc[chnum].do_ping = 0U; - hhcd->hc[chnum].urb_state = URB_NOTREADY; - hhcd->hc[chnum].state = HC_ACK; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - - if ((hhcd->hc[chnum].do_ssplit == 1U) && (hhcd->hc[chnum].do_csplit == 0U)) - { - if (hhcd->hc[chnum].ep_type != EP_TYPE_ISOC) - { - hhcd->hc[chnum].do_csplit = 1U; - } - - hhcd->hc[chnum].state = HC_ACK; - (void)USB_HC_Halt(hhcd->Instance, chnum); - - /* reset error_count */ - hhcd->hc[chnum].ErrCnt = 0U; - } - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_FRMOR)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_FRMOR); - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_XFRC)) - { - hhcd->hc[chnum].ErrCnt = 0U; - - /* transaction completed with NYET state, update do ping state */ - if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NYET)) - { - hhcd->hc[chnum].do_ping = 1U; - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); - } - - if (hhcd->hc[chnum].do_csplit != 0U) - { - hhcd->hc[chnum].do_csplit = 0U; - __HAL_HCD_CLEAR_HC_CSPLT(chnum); - } - - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_XFRC); - hhcd->hc[chnum].state = HC_XFRC; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NYET)) - { - hhcd->hc[chnum].state = HC_NYET; - - if (hhcd->hc[chnum].do_ssplit == 0U) - { - hhcd->hc[chnum].do_ping = 1U; - } - - hhcd->hc[chnum].ErrCnt = 0U; - (void)USB_HC_Halt(hhcd->Instance, chnum); - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_STALL)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_STALL); - hhcd->hc[chnum].state = HC_STALL; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NAK)) - { - hhcd->hc[chnum].ErrCnt = 0U; - hhcd->hc[chnum].state = HC_NAK; - - if (hhcd->hc[chnum].do_ping == 0U) - { - if (hhcd->hc[chnum].speed == HCD_DEVICE_SPEED_HIGH) - { - hhcd->hc[chnum].do_ping = 1U; - } - } - - (void)USB_HC_Halt(hhcd->Instance, chnum); - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_TXERR)) - { - if (hhcd->Init.dma_enable == 0U) - { - hhcd->hc[chnum].state = HC_XACTERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - } - else - { - hhcd->hc[chnum].ErrCnt++; - if (hhcd->hc[chnum].ErrCnt > 2U) - { - hhcd->hc[chnum].ErrCnt = 0U; - hhcd->hc[chnum].urb_state = URB_ERROR; - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#else - HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - else - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - } - } - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_DTERR)) - { - hhcd->hc[chnum].state = HC_DATATGLERR; - (void)USB_HC_Halt(hhcd->Instance, chnum); - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_DTERR); - } - else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_CHH)) - { - __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); - - if (hhcd->hc[chnum].state == HC_XFRC) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_DONE; - - if ((hhcd->hc[chnum].ep_type == EP_TYPE_BULK) || - (hhcd->hc[chnum].ep_type == EP_TYPE_INTR)) - { - if (hhcd->Init.dma_enable == 0U) - { - hhcd->hc[chnum].toggle_out ^= 1U; - } - - if ((hhcd->Init.dma_enable == 1U) && (hhcd->hc[chnum].xfer_len > 0U)) - { - num_packets = (hhcd->hc[chnum].xfer_len + hhcd->hc[chnum].max_packet - 1U) / hhcd->hc[chnum].max_packet; - - if ((num_packets & 1U) != 0U) - { - hhcd->hc[chnum].toggle_out ^= 1U; - } - } - } - } - else if (hhcd->hc[chnum].state == HC_ACK) - { - hhcd->hc[chnum].state = HC_HALTED; - - if (hhcd->hc[chnum].do_csplit == 1U) - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - } - } - else if (hhcd->hc[chnum].state == HC_NAK) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_NOTREADY; - - if (hhcd->hc[chnum].do_csplit == 1U) - { - hhcd->hc[chnum].do_csplit = 0U; - __HAL_HCD_CLEAR_HC_CSPLT(chnum); - } - } - else if (hhcd->hc[chnum].state == HC_NYET) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_NOTREADY; - } - else if (hhcd->hc[chnum].state == HC_STALL) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].urb_state = URB_STALL; - } - else if ((hhcd->hc[chnum].state == HC_XACTERR) || - (hhcd->hc[chnum].state == HC_DATATGLERR)) - { - hhcd->hc[chnum].state = HC_HALTED; - hhcd->hc[chnum].ErrCnt++; - if (hhcd->hc[chnum].ErrCnt > 2U) - { - hhcd->hc[chnum].ErrCnt = 0U; - hhcd->hc[chnum].urb_state = URB_ERROR; - } - else - { - hhcd->hc[chnum].urb_state = URB_NOTREADY; - - /* re-activate the channel */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - } - } - else - { - return; - } - -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#else - HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - else - { - return; - } -} - -/** - * @brief Handle Rx Queue Level interrupt requests. - * @param hhcd HCD handle - * @retval none - */ -static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) -{ - const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t pktsts; - uint32_t pktcnt; - uint32_t GrxstspReg; - uint32_t xferSizePktCnt; - uint32_t tmpreg; - uint32_t chnum; - - GrxstspReg = hhcd->Instance->GRXSTSP; - chnum = GrxstspReg & USB_OTG_GRXSTSP_EPNUM; - pktsts = (GrxstspReg & USB_OTG_GRXSTSP_PKTSTS) >> 17; - pktcnt = (GrxstspReg & USB_OTG_GRXSTSP_BCNT) >> 4; - - switch (pktsts) - { - case GRXSTS_PKTSTS_IN: - /* Read the data into the host buffer. */ - if ((pktcnt > 0U) && (hhcd->hc[chnum].xfer_buff != (void *)0)) - { - if ((hhcd->hc[chnum].xfer_count + pktcnt) <= hhcd->hc[chnum].xfer_len) - { - (void)USB_ReadPacket(hhcd->Instance, - hhcd->hc[chnum].xfer_buff, (uint16_t)pktcnt); - - /* manage multiple Xfer */ - hhcd->hc[chnum].xfer_buff += pktcnt; - hhcd->hc[chnum].xfer_count += pktcnt; - - /* get transfer size packet count */ - xferSizePktCnt = (USBx_HC(chnum)->HCTSIZ & USB_OTG_HCTSIZ_PKTCNT) >> 19; - - if ((hhcd->hc[chnum].max_packet == pktcnt) && (xferSizePktCnt > 0U)) - { - /* re-activate the channel when more packets are expected */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - hhcd->hc[chnum].toggle_in ^= 1U; - } - } - else - { - hhcd->hc[chnum].urb_state = URB_ERROR; - } - } - break; - - case GRXSTS_PKTSTS_DATA_TOGGLE_ERR: - break; - - case GRXSTS_PKTSTS_IN_XFER_COMP: - case GRXSTS_PKTSTS_CH_HALTED: - default: - break; - } -} - -/** - * @brief Handle Host Port interrupt requests. - * @param hhcd HCD handle - * @retval None - */ -static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd) -{ - const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - __IO uint32_t hprt0; - __IO uint32_t 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 whether Port Connect detected */ - if ((hprt0 & USB_OTG_HPRT_PCDET) == USB_OTG_HPRT_PCDET) - { - if ((hprt0 & USB_OTG_HPRT_PCSTS) == USB_OTG_HPRT_PCSTS) - { -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->ConnectCallback(hhcd); -#else - HAL_HCD_Connect_Callback(hhcd); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - 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)) - { - (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_6_MHZ); - } - else - { - (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); - } - } - else - { - if (hhcd->Init.speed == HCD_SPEED_FULL) - { - USBx_HOST->HFIR = HFIR_60_MHZ; - } - } -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->PortEnabledCallback(hhcd); -#else - HAL_HCD_PortEnabled_Callback(hhcd); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - - } - else - { -#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) - hhcd->PortDisabledCallback(hhcd); -#else - HAL_HCD_PortDisabled_Callback(hhcd); -#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ - } - } - - /* 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 /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ -#endif /* HAL_HCD_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_hcd.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 the following macros + (+++) __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + (+++) __HAL_RCC_USB_OTG_HS_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 + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_HCD_MODULE_ENABLED +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) + +/** @defgroup HCD HCD + * @brief HCD HAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup HCD_Private_Functions HCD Private Functions + * @{ + */ +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); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup HCD_Exported_Functions HCD Exported Functions + * @{ + */ + +/** @defgroup HCD_Exported_Functions_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 status + */ +HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) +{ +#if defined (USB_OTG_FS) + const USB_OTG_GlobalTypeDef *USBx; +#endif /* defined (USB_OTG_FS) */ + + /* Check the HCD handle allocation */ + if (hhcd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_HCD_ALL_INSTANCE(hhcd->Instance)); + +#if defined (USB_OTG_FS) + USBx = hhcd->Instance; +#endif /* defined (USB_OTG_FS) */ + + if (hhcd->State == HAL_HCD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hhcd->Lock = HAL_UNLOCKED; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->SOFCallback = HAL_HCD_SOF_Callback; + hhcd->ConnectCallback = HAL_HCD_Connect_Callback; + hhcd->DisconnectCallback = HAL_HCD_Disconnect_Callback; + hhcd->PortEnabledCallback = HAL_HCD_PortEnabled_Callback; + hhcd->PortDisabledCallback = HAL_HCD_PortDisabled_Callback; + hhcd->HC_NotifyURBChangeCallback = HAL_HCD_HC_NotifyURBChange_Callback; + + if (hhcd->MspInitCallback == NULL) + { + hhcd->MspInitCallback = HAL_HCD_MspInit; + } + + /* Init the low level hardware */ + hhcd->MspInitCallback(hhcd); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_HCD_MspInit(hhcd); +#endif /* (USE_HAL_HCD_REGISTER_CALLBACKS) */ + } + + hhcd->State = HAL_HCD_STATE_BUSY; + +#if defined (USB_OTG_FS) + /* Disable DMA mode for FS instance */ + if (USBx == USB_OTG_FS) + { + hhcd->Init.dma_enable = 0U; + } +#endif /* defined (USB_OTG_FS) */ + + /* Disable the Interrupts */ + __HAL_HCD_DISABLE(hhcd); + + /* Init the Core (common init.) */ + if (USB_CoreInit(hhcd->Instance, hhcd->Init) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } + + /* Force Host Mode */ + if (USB_SetCurrentMode(hhcd->Instance, USB_HOST_MODE) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } + + /* Init Host */ + if (USB_HostInit(hhcd->Instance, hhcd->Init) != HAL_OK) + { + hhcd->State = HAL_HCD_STATE_ERROR; + return HAL_ERROR; + } + + hhcd->State = HAL_HCD_STATE_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 these values: + * HCD_DEVICE_SPEED_HIGH: High speed mode, + * HCD_DEVICE_SPEED_FULL: Full speed mode, + * HCD_DEVICE_SPEED_LOW: Low speed mode + * @param ep_type Endpoint Type. + * This parameter can be one of these values: + * EP_TYPE_CTRL: Control type, + * EP_TYPE_ISOC: Isochronous type, + * EP_TYPE_BULK: Bulk type, + * EP_TYPE_INTR: Interrupt type + * @param mps Max Packet Size. + * This parameter can be a value from 0 to32K + * @retval HAL status + */ +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; + uint32_t HostCoreSpeed; + uint32_t HCcharMps = mps; + + __HAL_LOCK(hhcd); + hhcd->hc[ch_num].do_ping = 0U; + hhcd->hc[ch_num].dev_addr = dev_address; + hhcd->hc[ch_num].ch_num = ch_num; + hhcd->hc[ch_num].ep_type = ep_type; + hhcd->hc[ch_num].ep_num = epnum & 0x7FU; + + (void)HAL_HCD_HC_ClearHubInfo(hhcd, ch_num); + + if ((epnum & 0x80U) == 0x80U) + { + hhcd->hc[ch_num].ep_is_in = 1U; + } + else + { + hhcd->hc[ch_num].ep_is_in = 0U; + } + + HostCoreSpeed = USB_GetHostSpeed(hhcd->Instance); + + if (ep_type == EP_TYPE_ISOC) + { + /* FS device plugged to HS HUB */ + if ((speed == HCD_DEVICE_SPEED_FULL) && (HostCoreSpeed == HPRT0_PRTSPD_HIGH_SPEED)) + { + if (HCcharMps > ISO_SPLT_MPS) + { + /* ISO Max Packet Size for Split mode */ + HCcharMps = ISO_SPLT_MPS; + } + } + } + + hhcd->hc[ch_num].speed = speed; + hhcd->hc[ch_num].max_packet = (uint16_t)HCcharMps; + + status = USB_HC_Init(hhcd->Instance, ch_num, epnum, + dev_address, speed, ep_type, (uint16_t)HCcharMps); + + __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 status + */ +HAL_StatusTypeDef HAL_HCD_HC_Halt(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + HAL_StatusTypeDef status = HAL_OK; + + __HAL_LOCK(hhcd); + (void)USB_HC_Halt(hhcd->Instance, ch_num); + __HAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief DeInitialize the host driver. + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd) +{ + /* Check the HCD handle allocation */ + if (hhcd == NULL) + { + return HAL_ERROR; + } + + hhcd->State = HAL_HCD_STATE_BUSY; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + if (hhcd->MspDeInitCallback == NULL) + { + hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hhcd->MspDeInitCallback(hhcd); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_HCD_MspDeInit(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + __HAL_HCD_DISABLE(hhcd); + + hhcd->State = HAL_HCD_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initialize the HCD MSP. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_MspInit(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the HCD MSP. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_Group2 Input and Output 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 these values: + * 0 : Output / 1 : Input + * @param ep_type Endpoint Type. + * This parameter can be one of these values: + * EP_TYPE_CTRL: Control type/ + * EP_TYPE_ISOC: Isochronous type/ + * EP_TYPE_BULK: Bulk type/ + * EP_TYPE_INTR: Interrupt type/ + * @param token Endpoint Type. + * This parameter can be one of these values: + * 0: HC_PID_SETUP / 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 these values: + * 0 : do ping inactive / 1 : do ping active + * @retval HAL status + */ +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 == 0U) + { + hhcd->hc[ch_num].data_pid = HC_PID_SETUP; + hhcd->hc[ch_num].do_ping = do_ping; + } + else + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + + /* Manage Data Toggle */ + switch (ep_type) + { + case EP_TYPE_CTRL: + if (token == 1U) /* send data */ + { + if (direction == 0U) + { + if (length == 0U) + { + /* For Status OUT stage, Length == 0U, Status Out PID = 1 */ + hhcd->hc[ch_num].toggle_out = 1U; + } + + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num].toggle_out == 0U) + { + /* 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].do_ssplit == 1U) + { + if (hhcd->hc[ch_num].toggle_in == 0U) + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA0; + } + else + { + hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + } + } + } + } + break; + + case EP_TYPE_BULK: + if (direction == 0U) + { + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num].toggle_out == 0U) + { + /* 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 == 0U) + { + 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 == 0U) + { + /* Set the Data Toggle bit as per the Flag */ + if (hhcd->hc[ch_num].toggle_out == 0U) + { + /* 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 == 0U) + { + 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; + + default: + 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 = 0U; + 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], (uint8_t)hhcd->Init.dma_enable); +} + +/** + * @brief Handle HCD interrupt request. + * @param hhcd HCD handle + * @retval None + */ +void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + uint32_t interrupt; + + /* 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)) + { + __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_DISCINT); + + if ((USBx_HPRT0 & USB_OTG_HPRT_PCSTS) == 0U) + { + /* Flush USB Fifo */ + (void)USB_FlushTxFifo(USBx, 0x10U); + (void)USB_FlushRxFifo(USBx); + + if (hhcd->Init.phy_itface == USB_OTG_EMBEDDED_PHY) + { + /* Restore FS Clock */ + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); + } + + /* Handle Host Port Disconnect Interrupt */ +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->DisconnectCallback(hhcd); +#else + HAL_HCD_Disconnect_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + } + + /* Handle Host Port Interrupts */ + if (__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HPRTINT)) + { + HCD_Port_IRQHandler(hhcd); + } + + /* Handle Host SOF Interrupt */ + if (__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_SOF)) + { +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->SOFCallback(hhcd); +#else + HAL_HCD_SOF_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_SOF); + } + + /* Handle Host channel Interrupt */ + if (__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HCINT)) + { + interrupt = USB_HC_ReadInterrupt(hhcd->Instance); + for (i = 0U; i < hhcd->Init.Host_channels; i++) + { + if ((interrupt & (1UL << (i & 0xFU))) != 0U) + { + if ((USBx_HC(i)->HCCHAR & USB_OTG_HCCHAR_EPDIR) == USB_OTG_HCCHAR_EPDIR) + { + HCD_HC_IN_IRQHandler(hhcd, (uint8_t)i); + } + else + { + HCD_HC_OUT_IRQHandler(hhcd, (uint8_t)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)) != 0U) + { + 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_SOF_Callback could be implemented in the user file + */ +} + +/** + * @brief Connection Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_Connect_Callback could be implemented in the user file + */ +} + +/** + * @brief Disconnection Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} + +/** + * @brief Port Enabled Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_PortEnabled_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_Disconnect_Callback could be implemented in the user file + */ +} + +/** + * @brief Port Disabled Event callback. + * @param hhcd HCD handle + * @retval None + */ +__weak void HAL_HCD_PortDisabled_Callback(HCD_HandleTypeDef *hhcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_Disconnect_Callback could be implemented 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 these values: + * URB_IDLE/ + * URB_DONE/ + * URB_NOTREADY/ + * URB_NYET/ + * URB_ERROR/ + * URB_STALL/ + * @retval None + */ +__weak void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hhcd); + UNUSED(chnum); + UNUSED(urb_state); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_HCD_HC_NotifyURBChange_Callback could be implemented in the user file + */ +} + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User USB HCD Callback + * To be used instead of the weak predefined callback + * @param hhcd USB HCD handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_HCD_SOF_CB_ID USB HCD SOF callback ID + * @arg @ref HAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID + * @arg @ref HAL_HCD_DISCONNECT_CB_ID OTG HCD Disconnect callback ID + * @arg @ref HAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enable callback ID + * @arg @ref HAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disable callback ID + * @arg @ref HAL_HCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_RegisterCallback(HCD_HandleTypeDef *hhcd, + HAL_HCD_CallbackIDTypeDef CallbackID, + pHCD_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hhcd); + + if (hhcd->State == HAL_HCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_HCD_SOF_CB_ID : + hhcd->SOFCallback = pCallback; + break; + + case HAL_HCD_CONNECT_CB_ID : + hhcd->ConnectCallback = pCallback; + break; + + case HAL_HCD_DISCONNECT_CB_ID : + hhcd->DisconnectCallback = pCallback; + break; + + case HAL_HCD_PORT_ENABLED_CB_ID : + hhcd->PortEnabledCallback = pCallback; + break; + + case HAL_HCD_PORT_DISABLED_CB_ID : + hhcd->PortDisabledCallback = pCallback; + break; + + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = pCallback; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hhcd->State == HAL_HCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = pCallback; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + return status; +} + +/** + * @brief Unregister an USB HCD Callback + * USB HCD callback is redirected to the weak predefined callback + * @param hhcd USB HCD handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_HCD_SOF_CB_ID USB HCD SOF callback ID + * @arg @ref HAL_HCD_CONNECT_CB_ID USB HCD Connect callback ID + * @arg @ref HAL_HCD_DISCONNECT_CB_ID OTG HCD Disconnect callback ID + * @arg @ref HAL_HCD_PORT_ENABLED_CB_ID USB HCD Port Enabled callback ID + * @arg @ref HAL_HCD_PORT_DISABLED_CB_ID USB HCD Port Disabled callback ID + * @arg @ref HAL_HCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_HCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_UnRegisterCallback(HCD_HandleTypeDef *hhcd, HAL_HCD_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hhcd); + + /* Setup Legacy weak Callbacks */ + if (hhcd->State == HAL_HCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_HCD_SOF_CB_ID : + hhcd->SOFCallback = HAL_HCD_SOF_Callback; + break; + + case HAL_HCD_CONNECT_CB_ID : + hhcd->ConnectCallback = HAL_HCD_Connect_Callback; + break; + + case HAL_HCD_DISCONNECT_CB_ID : + hhcd->DisconnectCallback = HAL_HCD_Disconnect_Callback; + break; + + case HAL_HCD_PORT_ENABLED_CB_ID : + hhcd->PortEnabledCallback = HAL_HCD_PortEnabled_Callback; + break; + + case HAL_HCD_PORT_DISABLED_CB_ID : + hhcd->PortDisabledCallback = HAL_HCD_PortDisabled_Callback; + break; + + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = HAL_HCD_MspInit; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hhcd->State == HAL_HCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_HCD_MSPINIT_CB_ID : + hhcd->MspInitCallback = HAL_HCD_MspInit; + break; + + case HAL_HCD_MSPDEINIT_CB_ID : + hhcd->MspDeInitCallback = HAL_HCD_MspDeInit; + break; + + default : + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + return status; +} + +/** + * @brief Register USB HCD Host Channel Notify URB Change Callback + * To be used instead of the weak HAL_HCD_HC_NotifyURBChange_Callback() predefined callback + * @param hhcd HCD handle + * @param pCallback pointer to the USB HCD Host Channel Notify URB Change Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_RegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd, + pHCD_HC_NotifyURBChangeCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hhcd); + + if (hhcd->State == HAL_HCD_STATE_READY) + { + hhcd->HC_NotifyURBChangeCallback = pCallback; + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + + return status; +} + +/** + * @brief Unregister the USB HCD Host Channel Notify URB Change Callback + * USB HCD Host Channel Notify URB Change Callback is redirected + * to the weak HAL_HCD_HC_NotifyURBChange_Callback() predefined callback + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_UnRegisterHC_NotifyURBChangeCallback(HCD_HandleTypeDef *hhcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hhcd); + + if (hhcd->State == HAL_HCD_STATE_READY) + { + hhcd->HC_NotifyURBChangeCallback = HAL_HCD_HC_NotifyURBChange_Callback; /* Legacy weak DataOutStageCallback */ + } + else + { + /* Update the error code */ + hhcd->ErrorCode |= HAL_HCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hhcd); + + return status; +} +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_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 status + */ +HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd) +{ + __HAL_LOCK(hhcd); + /* Enable port power */ + (void)USB_DriveVbus(hhcd->Instance, 1U); + + /* Enable global interrupt */ + __HAL_HCD_ENABLE(hhcd); + __HAL_UNLOCK(hhcd); + + return HAL_OK; +} + +/** + * @brief Stop the host driver. + * @param hhcd HCD handle + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_HCD_Stop(HCD_HandleTypeDef *hhcd) +{ + __HAL_LOCK(hhcd); + (void)USB_StopHost(hhcd->Instance); + __HAL_UNLOCK(hhcd); + + return HAL_OK; +} + +/** + * @brief Reset the host port. + * @param hhcd HCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd) +{ + return (USB_ResetPort(hhcd->Instance)); +} + +/** + * @} + */ + +/** @defgroup HCD_Exported_Functions_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. + +@endverbatim + * @{ + */ + +/** + * @brief Return the HCD handle state. + * @param hhcd HCD handle + * @retval HAL state + */ +HCD_StateTypeDef HAL_HCD_GetState(HCD_HandleTypeDef const *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 these values: + * URB_IDLE/ + * URB_DONE/ + * URB_NOTREADY/ + * URB_NYET/ + * URB_ERROR/ + * URB_STALL + */ +HCD_URBStateTypeDef HAL_HCD_HC_GetURBState(HCD_HandleTypeDef const *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 const *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 these values: + * HC_IDLE/ + * HC_XFRC/ + * HC_HALTED/ + * HC_NYET/ + * HC_NAK/ + * HC_STALL/ + * HC_XACTERR/ + * HC_BBLERR/ + * HC_DATATGLERR + */ +HCD_HCStateTypeDef HAL_HCD_HC_GetState(HCD_HandleTypeDef const *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 Set host channel Hub information. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 15 + * @param addr Hub address + * @param PortNbr Hub port number + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_HC_SetHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num, + uint8_t addr, uint8_t PortNbr) +{ + uint32_t HostCoreSpeed = USB_GetHostSpeed(hhcd->Instance); + + /* LS/FS device plugged to HS HUB */ + if ((hhcd->hc[ch_num].speed != HCD_DEVICE_SPEED_HIGH) && (HostCoreSpeed == HPRT0_PRTSPD_HIGH_SPEED)) + { + hhcd->hc[ch_num].do_ssplit = 1U; + + if ((hhcd->hc[ch_num].ep_type == EP_TYPE_CTRL) && (hhcd->hc[ch_num].ep_is_in != 0U)) + { + hhcd->hc[ch_num].toggle_in = 1U; + } + } + + hhcd->hc[ch_num].hub_addr = addr; + hhcd->hc[ch_num].hub_port_nbr = PortNbr; + + return HAL_OK; +} + + +/** + * @brief Clear host channel hub information. + * @param hhcd HCD handle + * @param ch_num Channel number. + * This parameter can be a value from 1 to 15 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HCD_HC_ClearHubInfo(HCD_HandleTypeDef *hhcd, uint8_t ch_num) +{ + hhcd->hc[ch_num].do_ssplit = 0U; + hhcd->hc[ch_num].do_csplit = 0U; + hhcd->hc[ch_num].hub_addr = 0U; + hhcd->hc[ch_num].hub_port_nbr = 0U; + + return HAL_OK; +} +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup HCD_Private_Functions + * @{ + */ +/** + * @brief Handle 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) +{ + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_AHBERR)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_AHBERR); + hhcd->hc[chnum].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_BBERR)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_BBERR); + hhcd->hc[chnum].state = HC_BBLERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_STALL)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_STALL); + hhcd->hc[chnum].state = HC_STALL; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_DTERR)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_DTERR); + hhcd->hc[chnum].state = HC_DATATGLERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_TXERR)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR); + hhcd->hc[chnum].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else + { + /* ... */ + } + + if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_FRMOR)) + { + (void)USB_HC_Halt(hhcd->Instance, chnum); + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_FRMOR); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_XFRC)) + { + /* Clear any pending ACK IT */ + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); + + if (hhcd->hc[chnum].do_csplit == 1U) + { + hhcd->hc[chnum].do_csplit = 0U; + __HAL_HCD_CLEAR_HC_CSPLT(chnum); + } + + if (hhcd->Init.dma_enable != 0U) + { + hhcd->hc[chnum].xfer_count = hhcd->hc[chnum].XferSize - (USBx_HC(chnum)->HCTSIZ & USB_OTG_HCTSIZ_XFRSIZ); + } + + hhcd->hc[chnum].state = HC_XFRC; + hhcd->hc[chnum].ErrCnt = 0U; + __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)) + { + (void)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) || + (hhcd->hc[chnum].ep_type == EP_TYPE_ISOC)) + { + USBx_HC(chnum)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM; + hhcd->hc[chnum].urb_state = URB_DONE; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + else + { + /* ... */ + } + + if (hhcd->Init.dma_enable == 1U) + { + if ((((hhcd->hc[chnum].xfer_count + hhcd->hc[chnum].max_packet - 1U) / hhcd->hc[chnum].max_packet) & 1U) != 0U) + { + hhcd->hc[chnum].toggle_in ^= 1U; + } + } + else + { + hhcd->hc[chnum].toggle_in ^= 1U; + } + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_ACK)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); + + if (hhcd->hc[chnum].do_ssplit == 1U) + { + hhcd->hc[chnum].do_csplit = 1U; + hhcd->hc[chnum].state = HC_ACK; + + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_CHH)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); + + if (hhcd->hc[chnum].state == HC_XFRC) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_DONE; + } + else if (hhcd->hc[chnum].state == HC_STALL) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_STALL; + } + else if ((hhcd->hc[chnum].state == HC_XACTERR) || + (hhcd->hc[chnum].state == HC_DATATGLERR)) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].ErrCnt++; + if (hhcd->hc[chnum].ErrCnt > 2U) + { + hhcd->hc[chnum].ErrCnt = 0U; + + if (hhcd->hc[chnum].do_ssplit == 1U) + { + hhcd->hc[chnum].do_csplit = 0U; + hhcd->hc[chnum].ep_ss_schedule = 0U; + __HAL_HCD_CLEAR_HC_CSPLT(chnum); + } + + hhcd->hc[chnum].urb_state = URB_ERROR; + } + else + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + + if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) + { + /* re-activate the channel */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + } + } + } + else if (hhcd->hc[chnum].state == HC_NYET) + { + hhcd->hc[chnum].state = HC_HALTED; + + if (hhcd->hc[chnum].do_csplit == 1U) + { + if (hhcd->hc[chnum].ep_type == EP_TYPE_INTR) + { + hhcd->hc[chnum].NyetErrCnt++; + if (hhcd->hc[chnum].NyetErrCnt > 2U) + { + hhcd->hc[chnum].NyetErrCnt = 0U; + hhcd->hc[chnum].do_csplit = 0U; + + if (hhcd->hc[chnum].ErrCnt < 3U) + { + hhcd->hc[chnum].ep_ss_schedule = 1U; + } + __HAL_HCD_CLEAR_HC_CSPLT(chnum); + hhcd->hc[chnum].urb_state = URB_ERROR; + } + else + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + } + } + else + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + } + + if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) + { + /* re-activate the channel */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + } + } + } + else if (hhcd->hc[chnum].state == HC_ACK) + { + hhcd->hc[chnum].state = HC_HALTED; + + if (hhcd->hc[chnum].do_csplit == 1U) + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + + /* Set Complete split and re-activate the channel */ + USBx_HC(chnum)->HCSPLT |= USB_OTG_HCSPLT_COMPLSPLT; + USBx_HC(chnum)->HCINTMSK |= USB_OTG_HCINTMSK_NYET; + USBx_HC(chnum)->HCINTMSK &= ~USB_OTG_HCINT_ACK; + + if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) + { + /* re-activate the channel */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + } + } + } + else if (hhcd->hc[chnum].state == HC_NAK) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_NOTREADY; + + if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) + { + /* re-activate the channel */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + } + } + else if (hhcd->hc[chnum].state == HC_BBLERR) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].ErrCnt++; + hhcd->hc[chnum].urb_state = URB_ERROR; + } + else + { + if (hhcd->hc[chnum].state == HC_HALTED) + { + return; + } + } + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NYET)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); + hhcd->hc[chnum].state = HC_NYET; + + if (hhcd->hc[chnum].do_ssplit == 0U) + { + hhcd->hc[chnum].ErrCnt = 0U; + } + + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NAK)) + { + if (hhcd->hc[chnum].ep_type == EP_TYPE_INTR) + { + hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].state = HC_NAK; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL) || + (hhcd->hc[chnum].ep_type == EP_TYPE_BULK)) + { + hhcd->hc[chnum].ErrCnt = 0U; + + if ((hhcd->Init.dma_enable == 0U) || (hhcd->hc[chnum].do_csplit == 1U)) + { + hhcd->hc[chnum].state = HC_NAK; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + } + else + { + /* ... */ + } + + if (hhcd->hc[chnum].do_csplit == 1U) + { + hhcd->hc[chnum].do_csplit = 0U; + __HAL_HCD_CLEAR_HC_CSPLT(chnum); + __HAL_HCD_UNMASK_ACK_HC_INT(chnum); + } + + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK); + } + else + { + /* ... */ + } +} + +/** + * @brief Handle 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) +{ + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + uint32_t num_packets; + + if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_AHBERR)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_AHBERR); + hhcd->hc[chnum].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_ACK)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); + + if (hhcd->hc[chnum].do_ping == 1U) + { + hhcd->hc[chnum].do_ping = 0U; + hhcd->hc[chnum].urb_state = URB_NOTREADY; + hhcd->hc[chnum].state = HC_ACK; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + + if ((hhcd->hc[chnum].do_ssplit == 1U) && (hhcd->hc[chnum].do_csplit == 0U)) + { + if (hhcd->hc[chnum].ep_type != EP_TYPE_ISOC) + { + hhcd->hc[chnum].do_csplit = 1U; + } + + hhcd->hc[chnum].state = HC_ACK; + (void)USB_HC_Halt(hhcd->Instance, chnum); + + /* reset error_count */ + hhcd->hc[chnum].ErrCnt = 0U; + } + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_FRMOR)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_FRMOR); + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_XFRC)) + { + hhcd->hc[chnum].ErrCnt = 0U; + + /* transaction completed with NYET state, update do ping state */ + if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NYET)) + { + hhcd->hc[chnum].do_ping = 1U; + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); + } + + if (hhcd->hc[chnum].do_csplit != 0U) + { + hhcd->hc[chnum].do_csplit = 0U; + __HAL_HCD_CLEAR_HC_CSPLT(chnum); + } + + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_XFRC); + hhcd->hc[chnum].state = HC_XFRC; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NYET)) + { + hhcd->hc[chnum].state = HC_NYET; + + if (hhcd->hc[chnum].do_ssplit == 0U) + { + hhcd->hc[chnum].do_ping = 1U; + } + + hhcd->hc[chnum].ErrCnt = 0U; + (void)USB_HC_Halt(hhcd->Instance, chnum); + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_STALL)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_STALL); + hhcd->hc[chnum].state = HC_STALL; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_NAK)) + { + hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].state = HC_NAK; + + if (hhcd->hc[chnum].do_ping == 0U) + { + if (hhcd->hc[chnum].speed == HCD_DEVICE_SPEED_HIGH) + { + hhcd->hc[chnum].do_ping = 1U; + } + } + + (void)USB_HC_Halt(hhcd->Instance, chnum); + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NAK); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_TXERR)) + { + if (hhcd->Init.dma_enable == 0U) + { + hhcd->hc[chnum].state = HC_XACTERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + } + else + { + hhcd->hc[chnum].ErrCnt++; + if (hhcd->hc[chnum].ErrCnt > 2U) + { + hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].urb_state = URB_ERROR; + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + else + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + } + } + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_TXERR); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_DTERR)) + { + hhcd->hc[chnum].state = HC_DATATGLERR; + (void)USB_HC_Halt(hhcd->Instance, chnum); + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_DTERR); + } + else if (__HAL_HCD_GET_CH_FLAG(hhcd, chnum, USB_OTG_HCINT_CHH)) + { + __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); + + if (hhcd->hc[chnum].state == HC_XFRC) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_DONE; + + if ((hhcd->hc[chnum].ep_type == EP_TYPE_BULK) || + (hhcd->hc[chnum].ep_type == EP_TYPE_INTR)) + { + if (hhcd->Init.dma_enable == 0U) + { + hhcd->hc[chnum].toggle_out ^= 1U; + } + + if ((hhcd->Init.dma_enable == 1U) && (hhcd->hc[chnum].xfer_len > 0U)) + { + num_packets = (hhcd->hc[chnum].xfer_len + hhcd->hc[chnum].max_packet - 1U) / hhcd->hc[chnum].max_packet; + + if ((num_packets & 1U) != 0U) + { + hhcd->hc[chnum].toggle_out ^= 1U; + } + } + } + } + else if (hhcd->hc[chnum].state == HC_ACK) + { + hhcd->hc[chnum].state = HC_HALTED; + + if (hhcd->hc[chnum].do_csplit == 1U) + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + } + } + else if (hhcd->hc[chnum].state == HC_NAK) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_NOTREADY; + + if (hhcd->hc[chnum].do_csplit == 1U) + { + hhcd->hc[chnum].do_csplit = 0U; + __HAL_HCD_CLEAR_HC_CSPLT(chnum); + } + } + else if (hhcd->hc[chnum].state == HC_NYET) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_NOTREADY; + } + else if (hhcd->hc[chnum].state == HC_STALL) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].urb_state = URB_STALL; + } + else if ((hhcd->hc[chnum].state == HC_XACTERR) || + (hhcd->hc[chnum].state == HC_DATATGLERR)) + { + hhcd->hc[chnum].state = HC_HALTED; + hhcd->hc[chnum].ErrCnt++; + if (hhcd->hc[chnum].ErrCnt > 2U) + { + hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].urb_state = URB_ERROR; + } + else + { + hhcd->hc[chnum].urb_state = URB_NOTREADY; + + /* re-activate the channel */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + } + } + else + { + return; + } + +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->HC_NotifyURBChangeCallback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#else + HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + else + { + return; + } +} + +/** + * @brief Handle Rx Queue Level interrupt requests. + * @param hhcd HCD handle + * @retval none + */ +static void HCD_RXQLVL_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t pktsts; + uint32_t pktcnt; + uint32_t GrxstspReg; + uint32_t xferSizePktCnt; + uint32_t tmpreg; + uint32_t chnum; + + GrxstspReg = hhcd->Instance->GRXSTSP; + chnum = GrxstspReg & USB_OTG_GRXSTSP_EPNUM; + pktsts = (GrxstspReg & USB_OTG_GRXSTSP_PKTSTS) >> 17; + pktcnt = (GrxstspReg & USB_OTG_GRXSTSP_BCNT) >> 4; + + switch (pktsts) + { + case GRXSTS_PKTSTS_IN: + /* Read the data into the host buffer. */ + if ((pktcnt > 0U) && (hhcd->hc[chnum].xfer_buff != (void *)0)) + { + if ((hhcd->hc[chnum].xfer_count + pktcnt) <= hhcd->hc[chnum].xfer_len) + { + (void)USB_ReadPacket(hhcd->Instance, + hhcd->hc[chnum].xfer_buff, (uint16_t)pktcnt); + + /* manage multiple Xfer */ + hhcd->hc[chnum].xfer_buff += pktcnt; + hhcd->hc[chnum].xfer_count += pktcnt; + + /* get transfer size packet count */ + xferSizePktCnt = (USBx_HC(chnum)->HCTSIZ & USB_OTG_HCTSIZ_PKTCNT) >> 19; + + if ((hhcd->hc[chnum].max_packet == pktcnt) && (xferSizePktCnt > 0U)) + { + /* re-activate the channel when more packets are expected */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + hhcd->hc[chnum].toggle_in ^= 1U; + } + } + else + { + hhcd->hc[chnum].urb_state = URB_ERROR; + } + } + break; + + case GRXSTS_PKTSTS_DATA_TOGGLE_ERR: + break; + + case GRXSTS_PKTSTS_IN_XFER_COMP: + case GRXSTS_PKTSTS_CH_HALTED: + default: + break; + } +} + +/** + * @brief Handle Host Port interrupt requests. + * @param hhcd HCD handle + * @retval None + */ +static void HCD_Port_IRQHandler(HCD_HandleTypeDef *hhcd) +{ + const USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t hprt0; + __IO uint32_t 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 whether Port Connect detected */ + if ((hprt0 & USB_OTG_HPRT_PCDET) == USB_OTG_HPRT_PCDET) + { + if ((hprt0 & USB_OTG_HPRT_PCSTS) == USB_OTG_HPRT_PCSTS) + { +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->ConnectCallback(hhcd); +#else + HAL_HCD_Connect_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + 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)) + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_6_MHZ); + } + else + { + (void)USB_InitFSLSPClkSel(hhcd->Instance, HCFG_48_MHZ); + } + } + else + { + if (hhcd->Init.speed == HCD_SPEED_FULL) + { + USBx_HOST->HFIR = HFIR_60_MHZ; + } + } +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->PortEnabledCallback(hhcd); +#else + HAL_HCD_PortEnabled_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + + } + else + { +#if (USE_HAL_HCD_REGISTER_CALLBACKS == 1U) + hhcd->PortDisabledCallback(hhcd); +#else + HAL_HCD_PortDisabled_Callback(hhcd); +#endif /* USE_HAL_HCD_REGISTER_CALLBACKS */ + } + } + + /* 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 /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* HAL_HCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c.c index 72fdb1cad..6503ce390 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c.c @@ -1,7809 +1,7809 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_i2c.c - * @author MCD Application Team - * @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 State and Errors functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 implementing 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 channel - (+++) Enable the DMAx interface clock using - (+++) Configure the DMA handle parameters - (+++) Configure the DMA Tx or Rx channel - (+++) Associate the initialized 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 channel - - (#) Configure the Communication Clock Timing, Own Address1, Master Addressing mode, Dual Addressing mode, - Own Address2, Own Address2 Mask, General call and Nostretch mode in the hi2c Init structure. - - (#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware - (GPIO, CLOCK, NVIC...etc) by calling the customized 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 operation modes 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 users can - add their 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 users can - add their 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 users can - add their 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 users can - add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can - add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() - (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() - (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. - This action will inform Master to generate a Stop condition to discard the communication. - - - *** Interrupt mode or DMA mode IO sequential operation *** - ========================================================== - [..] - (@) These interfaces allow to manage a sequential transfer with a repeated start condition - when a direction change during transfer - [..] - (+) A specific option field manage the different steps of a sequential transfer - (+) Option field values are defined through I2C_XFEROPTIONS and are listed below: - (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functional is same as associated interfaces in - no sequential mode - (++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address - and data to transfer without a final stop condition - (++) I2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with - start condition, address and data to transfer without a final stop condition, - an then permit a call the same master sequential interface several times - (like HAL_I2C_Master_Seq_Transmit_IT() then HAL_I2C_Master_Seq_Transmit_IT() - or HAL_I2C_Master_Seq_Transmit_DMA() then HAL_I2C_Master_Seq_Transmit_DMA()) - (++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address - and with new data to transfer if the direction change or manage only the new data to - transfer - if no direction change and without a final stop condition in both cases - (++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address - and with new data to transfer if the direction change or manage only the new data to - transfer - if no direction change and with a final stop condition in both cases - (++) I2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition - after several call of the same master sequential interface several times - (link with option I2C_FIRST_AND_NEXT_FRAME). - Usage can, transfer several bytes one by one using - HAL_I2C_Master_Seq_Transmit_IT - or HAL_I2C_Master_Seq_Receive_IT - or HAL_I2C_Master_Seq_Transmit_DMA - or HAL_I2C_Master_Seq_Receive_DMA - with option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME. - Then usage of this option I2C_LAST_FRAME_NO_STOP at the last Transmit or - Receive sequence permit to call the opposite interface Receive or Transmit - without stopping the communication and so generate a restart condition. - (++) I2C_OTHER_FRAME: Sequential usage (Master only), this option allow to manage a restart condition after - each call of the same master sequential - interface. - Usage can, transfer several bytes one by one with a restart with slave address between - each bytes using - HAL_I2C_Master_Seq_Transmit_IT - or HAL_I2C_Master_Seq_Receive_IT - or HAL_I2C_Master_Seq_Transmit_DMA - or HAL_I2C_Master_Seq_Receive_DMA - with option I2C_FIRST_FRAME then I2C_OTHER_FRAME. - Then usage of this option I2C_OTHER_AND_LAST_FRAME at the last frame to help automatic - generation of STOP condition. - - (+) Different sequential I2C interfaces are listed below: - (++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using - HAL_I2C_Master_Seq_Transmit_IT() or using HAL_I2C_Master_Seq_Transmit_DMA() - (+++) At transmission end of current frame transfer, HAL_I2C_MasterTxCpltCallback() is executed and - users can add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback() - (++) Sequential receive in master I2C mode an amount of data in non-blocking mode using - HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA() - (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() - (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() - (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() - HAL_I2C_DisableListen_IT() - (+++) When address slave I2C match, HAL_I2C_AddrCallback() is executed and users can - add their own code to check the Address Match Code and the transmission direction request by master - (Write/Read). - (+++) At Listen mode end HAL_I2C_ListenCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_ListenCpltCallback() - (++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using - HAL_I2C_Slave_Seq_Transmit_IT() or using HAL_I2C_Slave_Seq_Transmit_DMA() - (+++) At transmission end of current frame transfer, HAL_I2C_SlaveTxCpltCallback() is executed and - users can add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback() - (++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using - HAL_I2C_Slave_Seq_Receive_IT() or using HAL_I2C_Slave_Seq_Receive_DMA() - (+++) At reception end of current frame transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() - (++) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can - add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (++) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. - This action will inform Master to generate a Stop condition to discard the communication. - - *** Interrupt mode IO MEM operation *** - ======================================= - [..] - (+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using - HAL_I2C_Mem_Write_IT() - (+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback() - (+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using - HAL_I2C_Mem_Read_IT() - (+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback() - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can - add their 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 users can - add their 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 users can - add their 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 users can - add their 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 users can - add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can - add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() - (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() - (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. - This action will inform Master to generate a Stop condition to discard the communication. - - *** DMA mode IO MEM operation *** - ================================= - [..] - (+) Write an amount of data in non-blocking mode with DMA to a specific memory address using - HAL_I2C_Mem_Write_DMA() - (+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback() - (+) Read an amount of data in non-blocking mode with DMA from a specific memory address using - HAL_I2C_Mem_Read_DMA() - (+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback() - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can - add their 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_GENERATE_NACK: Generate a Non-Acknowledge I2C peripheral in Slave mode - (+) __HAL_I2C_GET_FLAG: Check whether the specified I2C flag is set or not - (+) __HAL_I2C_CLEAR_FLAG: Clear the specified I2C pending flag - (+) __HAL_I2C_ENABLE_IT: Enable the specified I2C interrupt - (+) __HAL_I2C_DISABLE_IT: Disable the specified I2C interrupt - - *** Callback registration *** - ============================================= - [..] - The compilation flag USE_HAL_I2C_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_I2C_RegisterCallback() or HAL_I2C_RegisterAddrCallback() - to register an interrupt callback. - [..] - Function HAL_I2C_RegisterCallback() allows to register following callbacks: - (+) MasterTxCpltCallback : callback for Master transmission end of transfer. - (+) MasterRxCpltCallback : callback for Master reception end of transfer. - (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. - (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. - (+) ListenCpltCallback : callback for end of listen mode. - (+) MemTxCpltCallback : callback for Memory transmission end of transfer. - (+) MemRxCpltCallback : callback for Memory reception end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - [..] - For specific callback AddrCallback use dedicated register callbacks : HAL_I2C_RegisterAddrCallback(). - [..] - Use function HAL_I2C_UnRegisterCallback to reset a callback to the default - weak function. - HAL_I2C_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) MasterTxCpltCallback : callback for Master transmission end of transfer. - (+) MasterRxCpltCallback : callback for Master reception end of transfer. - (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. - (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. - (+) ListenCpltCallback : callback for end of listen mode. - (+) MemTxCpltCallback : callback for Memory transmission end of transfer. - (+) MemRxCpltCallback : callback for Memory reception end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - [..] - For callback AddrCallback use dedicated register callbacks : HAL_I2C_UnRegisterAddrCallback(). - [..] - By default, after the HAL_I2C_Init() and when the state is HAL_I2C_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_I2C_MasterTxCpltCallback(), HAL_I2C_MasterRxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the HAL_I2C_Init()/ HAL_I2C_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the HAL_I2C_Init()/ HAL_I2C_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - [..] - Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using HAL_I2C_RegisterCallback() before calling HAL_I2C_DeInit() - or HAL_I2C_Init() function. - [..] - When the compilation flag USE_HAL_I2C_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - [..] - (@) You can refer to the I2C HAL driver header file for more useful macros - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup I2C I2C - * @brief I2C HAL module driver - * @{ - */ - -#ifdef HAL_I2C_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ - -/** @defgroup I2C_Private_Define I2C Private Define - * @{ - */ -#define TIMING_CLEAR_MASK (0xF0FFFFFFU) /*!< I2C TIMING clear register Mask */ -#define I2C_TIMEOUT_ADDR (10000U) /*!< 10 s */ -#define I2C_TIMEOUT_BUSY (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_DIR (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_RXNE (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_STOPF (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_TC (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_TCR (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_TXIS (25U) /*!< 25 ms */ -#define I2C_TIMEOUT_FLAG (25U) /*!< 25 ms */ - -#define MAX_NBYTE_SIZE 255U -#define SLAVE_ADDR_SHIFT 7U -#define SLAVE_ADDR_MSK 0x06U - -/* Private define for @ref PreviousState usage */ -#define I2C_STATE_MSK ((uint32_t)((uint32_t)((uint32_t)HAL_I2C_STATE_BUSY_TX | \ - (uint32_t)HAL_I2C_STATE_BUSY_RX) & \ - (uint32_t)(~((uint32_t)HAL_I2C_STATE_READY)))) -/*!< Mask State define, keep only RX and TX bits */ -#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE)) -/*!< Default Value */ -#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \ - (uint32_t)HAL_I2C_MODE_MASTER)) -/*!< Master Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \ - (uint32_t)HAL_I2C_MODE_MASTER)) -/*!< Master Busy RX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \ - (uint32_t)HAL_I2C_MODE_SLAVE)) -/*!< Slave Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \ - (uint32_t)HAL_I2C_MODE_SLAVE)) -/*!< Slave Busy RX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_MEM_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \ - (uint32_t)HAL_I2C_MODE_MEM)) -/*!< Memory Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_MEM_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \ - (uint32_t)HAL_I2C_MODE_MEM)) -/*!< Memory Busy RX, combinaison of State LSB and Mode enum */ - - -/* Private define to centralize the enable/disable of Interrupts */ -#define I2C_XFER_TX_IT (uint16_t)(0x0001U) /*!< Bit field can be combinated with - @ref I2C_XFER_LISTEN_IT */ -#define I2C_XFER_RX_IT (uint16_t)(0x0002U) /*!< Bit field can be combinated with - @ref I2C_XFER_LISTEN_IT */ -#define I2C_XFER_LISTEN_IT (uint16_t)(0x8000U) /*!< Bit field can be combinated with @ref I2C_XFER_TX_IT - and @ref I2C_XFER_RX_IT */ - -#define I2C_XFER_ERROR_IT (uint16_t)(0x0010U) /*!< Bit definition to manage addition of global Error - and NACK treatment */ -#define I2C_XFER_CPLT_IT (uint16_t)(0x0020U) /*!< Bit definition to manage only STOP evenement */ -#define I2C_XFER_RELOAD_IT (uint16_t)(0x0040U) /*!< Bit definition to manage only Reload of NBYTE */ - -/* Private define Sequential Transfer Options default/reset value */ -#define I2C_NO_OPTION_FRAME (0xFFFF0000U) -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup I2C_Private_Macro - * @{ - */ -#if defined(HAL_DMA_MODULE_ENABLED) -/* Macro to get remaining data to transfer on DMA side */ -#define I2C_GET_DMA_REMAIN_DATA(__HANDLE__) (__HAL_DMA_GET_COUNTER(__HANDLE__) + HAL_DMAEx_GetFifoLevel(__HANDLE__)) -#endif /* HAL_DMA_MODULE_ENABLED */ -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/** @defgroup I2C_Private_Functions I2C Private Functions - * @{ - */ -#if defined(HAL_DMA_MODULE_ENABLED) -/* Private functions to handle DMA transfer */ -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_DMAError(DMA_HandleTypeDef *hdma); -static void I2C_DMAAbort(DMA_HandleTypeDef *hdma); - -#endif /* HAL_DMA_MODULE_ENABLED */ - -/* Private functions to handle IT transfer */ -static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); -static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c); -static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c); -static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); -static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); -static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); -static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode); - -/* Private functions to handle IT transfer */ -static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, - uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, - uint32_t Tickstart); -static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, - uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, - uint32_t Tickstart); - -/* Private functions for I2C transfer IRQ handler */ -static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources); -static HAL_StatusTypeDef I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources); -static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources); -#if defined(HAL_DMA_MODULE_ENABLED) -static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources); -static HAL_StatusTypeDef I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources); -static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources); -#endif /* HAL_DMA_MODULE_ENABLED */ - -/* Private functions to handle flags during polling transfer */ -static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, - uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart); -static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart); - -/* Private functions to centralize the enable/disable of Interrupts */ -static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest); -static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest); - -/* Private function to treat different error callback */ -static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c); - -/* Private function to flush TXDR register */ -static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c); - -/* Private function to handle start, restart or stop a transfer */ -static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, - uint32_t Request); - -/* Private function to Convert Specific options */ -static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup I2C_Exported_Functions I2C Exported Functions - * @{ - */ - -/** @defgroup I2C_Exported_Functions_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 - deinitialize 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: - (++) Clock Timing - (++) Own Address 1 - (++) Addressing mode (Master, Slave) - (++) Dual Addressing mode - (++) Own Address 2 - (++) Own Address 2 Mask - (++) General call mode - (++) Nostretch mode - - (+) Call the function HAL_I2C_DeInit() to restore the default configuration - of the selected I2Cx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the I2C according to the specified parameters - * in the I2C_InitTypeDef and initialize 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) -{ - /* 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_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_OWN_ADDRESS2_MASK(hi2c->Init.OwnAddress2Masks)); - 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) - { - /* Allocate lock resource and initialize it */ - hi2c->Lock = HAL_UNLOCKED; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - /* Init the I2C Callback settings */ - hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ - hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ - hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ - hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ - hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ - hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ - hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ - hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ - hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ - - if (hi2c->MspInitCallback == NULL) - { - hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - hi2c->MspInitCallback(hi2c); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_I2C_MspInit(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /*---------------------------- I2Cx TIMINGR Configuration ------------------*/ - /* Configure I2Cx: Frequency range */ - hi2c->Instance->TIMINGR = hi2c->Init.Timing & TIMING_CLEAR_MASK; - - /*---------------------------- I2Cx OAR1 Configuration ---------------------*/ - /* Disable Own Address1 before set the Own Address1 configuration */ - hi2c->Instance->OAR1 &= ~I2C_OAR1_OA1EN; - - /* Configure I2Cx: Own Address1 and ack own address1 mode */ - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) - { - hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | hi2c->Init.OwnAddress1); - } - else /* I2C_ADDRESSINGMODE_10BIT */ - { - hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hi2c->Init.OwnAddress1); - } - - /*---------------------------- I2Cx CR2 Configuration ----------------------*/ - /* Configure I2Cx: Addressing Master mode */ - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) - { - SET_BIT(hi2c->Instance->CR2, I2C_CR2_ADD10); - } - else - { - /* Clear the I2C ADD10 bit */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_ADD10); - } - /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */ - hi2c->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); - - /*---------------------------- I2Cx OAR2 Configuration ---------------------*/ - /* Disable Own Address2 before set the Own Address2 configuration */ - hi2c->Instance->OAR2 &= ~I2C_DUALADDRESS_ENABLE; - - /* Configure I2Cx: Dual mode and Own Address2 */ - hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2 | \ - (hi2c->Init.OwnAddress2Masks << 8)); - - /*---------------------------- I2Cx CR1 Configuration ----------------------*/ - /* Configure I2Cx: Generalcall and NoStretch mode */ - hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode); - - /* Enable the selected I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - - return HAL_OK; -} - -/** - * @brief DeInitialize 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); - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - if (hi2c->MspDeInitCallback == NULL) - { - hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - hi2c->MspDeInitCallback(hi2c); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_I2C_MspDeInit(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->State = HAL_I2C_STATE_RESET; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief Initialize the I2C MSP. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 DeInitialize the I2C MSP. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User I2C Callback - * To be used instead of the weak predefined callback - * @note The HAL_I2C_RegisterCallback() may be called before HAL_I2C_Init() in HAL_I2C_STATE_RESET - * to register callbacks for HAL_I2C_MSPINIT_CB_ID and HAL_I2C_MSPDEINIT_CB_ID. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID - * @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID - * @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID - * @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID - * @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID - * @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID - * @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID - * @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID, - pI2C_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (HAL_I2C_STATE_READY == hi2c->State) - { - switch (CallbackID) - { - case HAL_I2C_MASTER_TX_COMPLETE_CB_ID : - hi2c->MasterTxCpltCallback = pCallback; - break; - - case HAL_I2C_MASTER_RX_COMPLETE_CB_ID : - hi2c->MasterRxCpltCallback = pCallback; - break; - - case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID : - hi2c->SlaveTxCpltCallback = pCallback; - break; - - case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID : - hi2c->SlaveRxCpltCallback = pCallback; - break; - - case HAL_I2C_LISTEN_COMPLETE_CB_ID : - hi2c->ListenCpltCallback = pCallback; - break; - - case HAL_I2C_MEM_TX_COMPLETE_CB_ID : - hi2c->MemTxCpltCallback = pCallback; - break; - - case HAL_I2C_MEM_RX_COMPLETE_CB_ID : - hi2c->MemRxCpltCallback = pCallback; - break; - - case HAL_I2C_ERROR_CB_ID : - hi2c->ErrorCallback = pCallback; - break; - - case HAL_I2C_ABORT_CB_ID : - hi2c->AbortCpltCallback = pCallback; - break; - - case HAL_I2C_MSPINIT_CB_ID : - hi2c->MspInitCallback = pCallback; - break; - - case HAL_I2C_MSPDEINIT_CB_ID : - hi2c->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_I2C_STATE_RESET == hi2c->State) - { - switch (CallbackID) - { - case HAL_I2C_MSPINIT_CB_ID : - hi2c->MspInitCallback = pCallback; - break; - - case HAL_I2C_MSPDEINIT_CB_ID : - hi2c->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an I2C Callback - * I2C callback is redirected to the weak predefined callback - * @note The HAL_I2C_UnRegisterCallback() may be called before HAL_I2C_Init() in HAL_I2C_STATE_RESET - * to un-register callbacks for HAL_I2C_MSPINIT_CB_ID and HAL_I2C_MSPDEINIT_CB_ID. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * This parameter can be one of the following values: - * @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID - * @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID - * @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID - * @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID - * @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID - * @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID - * @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID - * @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_I2C_STATE_READY == hi2c->State) - { - switch (CallbackID) - { - case HAL_I2C_MASTER_TX_COMPLETE_CB_ID : - hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ - break; - - case HAL_I2C_MASTER_RX_COMPLETE_CB_ID : - hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ - break; - - case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID : - hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ - break; - - case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID : - hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ - break; - - case HAL_I2C_LISTEN_COMPLETE_CB_ID : - hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ - break; - - case HAL_I2C_MEM_TX_COMPLETE_CB_ID : - hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ - break; - - case HAL_I2C_MEM_RX_COMPLETE_CB_ID : - hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ - break; - - case HAL_I2C_ERROR_CB_ID : - hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_I2C_ABORT_CB_ID : - hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_I2C_MSPINIT_CB_ID : - hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_I2C_MSPDEINIT_CB_ID : - hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_I2C_STATE_RESET == hi2c->State) - { - switch (CallbackID) - { - case HAL_I2C_MSPINIT_CB_ID : - hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_I2C_MSPDEINIT_CB_ID : - hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register the Slave Address Match I2C Callback - * To be used instead of the weak HAL_I2C_AddrCallback() predefined callback - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pCallback pointer to the Address Match Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (HAL_I2C_STATE_READY == hi2c->State) - { - hi2c->AddrCallback = pCallback; - } - else - { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Slave Address Match I2C Callback - * Info Ready I2C Callback is redirected to the weak HAL_I2C_AddrCallback() predefined callback - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_I2C_STATE_READY == hi2c->State) - { - hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ - } - else - { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup I2C_Exported_Functions_Group2 Input and Output 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 are two modes 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() - (++) HAL_I2C_Master_Seq_Transmit_IT() - (++) HAL_I2C_Master_Seq_Receive_IT() - (++) HAL_I2C_Slave_Seq_Transmit_IT() - (++) HAL_I2C_Slave_Seq_Receive_IT() - (++) HAL_I2C_EnableListen_IT() - (++) HAL_I2C_DisableListen_IT() - (++) HAL_I2C_Master_Abort_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() - (++) HAL_I2C_Master_Seq_Transmit_DMA() - (++) HAL_I2C_Master_Seq_Receive_DMA() - (++) HAL_I2C_Slave_Seq_Transmit_DMA() - (++) HAL_I2C_Slave_Seq_Receive_DMA() - - (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (++) HAL_I2C_MasterTxCpltCallback() - (++) HAL_I2C_MasterRxCpltCallback() - (++) HAL_I2C_SlaveTxCpltCallback() - (++) HAL_I2C_SlaveRxCpltCallback() - (++) HAL_I2C_MemTxCpltCallback() - (++) HAL_I2C_MemRxCpltCallback() - (++) HAL_I2C_AddrCallback() - (++) HAL_I2C_ListenCpltCallback() - (++) HAL_I2C_ErrorCallback() - (++) HAL_I2C_AbortCpltCallback() - -@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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t tickstart; - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferISR = NULL; - - /* Send Slave Address */ - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, - I2C_GENERATE_START_WRITE); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_WRITE); - } - - while (hi2c->XferCount > 0U) - { - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - - if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) - { - /* Wait until TCR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, - I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_NO_STARTSTOP); - } - } - } - - /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ - /* Wait until STOPF flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* 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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t tickstart; - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferISR = NULL; - - /* Send Slave Address */ - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, - I2C_GENERATE_START_READ); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_READ); - } - - while (hi2c->XferCount > 0U) - { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - - if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) - { - /* Wait until TCR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, - I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_NO_STARTSTOP); - } - } - } - - /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ - /* Wait until STOPF flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* 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) -{ - uint32_t tickstart; - uint16_t tmpXferCount; - HAL_StatusTypeDef error; - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferISR = NULL; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Preload TX data if no stretch enable */ - if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) - { - /* Preload TX register */ - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - } - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - - /* 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, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - } - - /* Wait until DIR flag is set Transmitter mode */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - return HAL_ERROR; - } - - while (hi2c->XferCount > 0U) - { - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - } - - /* Wait until AF flag is set */ - error = I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart); - - if (error != HAL_OK) - { - /* Check that I2C transfer finished */ - /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ - /* Mean XferCount == 0 */ - - tmpXferCount = hi2c->XferCount; - if ((hi2c->ErrorCode == HAL_I2C_ERROR_AF) && (tmpXferCount == 0U)) - { - /* Reset ErrorCode to NONE */ - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - } - else - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - } - else - { - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Wait until STOP flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - return HAL_ERROR; - } - - /* Clear STOP flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - } - - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* 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) -{ - uint32_t tickstart; - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferISR = NULL; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - - /* Wait until DIR flag is reset Receiver mode */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - - while (hi2c->XferCount > 0U) - { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) - { - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - } - - return HAL_ERROR; - } - - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - } - - /* Wait until STOP flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - - /* Clear STOP flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in master mode an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t xfermode; - - 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_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Master_ISR_IT; - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = I2C_AUTOEND_MODE; - } - - /* Send Slave Address */ - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master mode an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t xfermode; - - 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_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Master_ISR_IT; - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = I2C_AUTOEND_MODE; - } - - /* Send Slave Address */ - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ); - - /* 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 ERR, TC, STOP, NACK, RXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in slave mode an amount of data in non-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) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Slave_ISR_IT; - - /* Preload TX data if no stretch enable */ - if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) - { - /* Preload TX register */ - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - } - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in non-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) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Slave_ISR_IT; - - /* 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 ERR, TC, STOP, NACK, RXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Transmit in master mode an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t xfermode; - HAL_StatusTypeDef dmaxferstatus; - - 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_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Master_ISR_DMA; - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = I2C_AUTOEND_MODE; - } - - if (hi2c->XferSize > 0U) - { - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; - - /* Set DMA destination address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->TXDR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Send Slave Address */ - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE); - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* 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 ERR and NACK interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - /* Update Transfer ISR function pointer */ - hi2c->XferISR = I2C_Master_ISR_IT; - - /* Send Slave Address */ - /* Set NBYTES to write and generate START condition */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master mode an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t xfermode; - HAL_StatusTypeDef dmaxferstatus; - - 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_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Master_ISR_DMA; - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = I2C_AUTOEND_MODE; - } - - if (hi2c->XferSize > 0U) - { - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->RXDR; - - /* Set DMA destination address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Send Slave Address */ - /* Set NBYTES to read and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ); - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* 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 ERR and NACK interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - /* Update Transfer ISR function pointer */ - hi2c->XferISR = I2C_Master_ISR_IT; - - /* Send Slave Address */ - /* Set NBYTES to read and generate START condition */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_READ); - - /* 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 ERR, TC, STOP, NACK, RXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in slave mode an amount of data in non-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) -{ - HAL_StatusTypeDef dmaxferstatus; - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Slave_ISR_DMA; - - /* Preload TX data if no stretch enable */ - if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) - { - /* Preload TX register */ - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - } - - if (hi2c->XferCount != 0U) - { - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr; - - /* Set DMA destination address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->TXDR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, - (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* 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 ERR, STOP, NACK, ADDR interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* 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 ERR, STOP, NACK, ADDR interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in non-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) -{ - HAL_StatusTypeDef dmaxferstatus; - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Slave_ISR_DMA; - - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->RXDR; - - /* Set DMA destination address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* 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 ERR, STOP, NACK, ADDR interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferISR = NULL; - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } - - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); - } - - do - { - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - - if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) - { - /* Wait until TCR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, - I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_NO_STARTSTOP); - } - } - - } while (hi2c->XferCount > 0U); - - /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ - /* Wait until STOPF flag is reset */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* 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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferISR = NULL; - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } - - /* Send Slave Address */ - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, - I2C_GENERATE_START_READ); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_READ); - } - - do - { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - - if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) - { - /* Wait until TCR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t) hi2c->XferSize, I2C_RELOAD_MODE, - I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_NO_STARTSTOP); - } - } - } while (hi2c->XferCount > 0U); - - /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ - /* Wait until STOPF flag is reset */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -/** - * @brief Write an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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 == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - 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->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->XferSize = 0U; - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Mem_ISR_IT; - hi2c->Devaddress = DevAddress; - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) - { - /* Prefetch Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - - /* Reset Memaddress content */ - hi2c->Memaddress = 0xFFFFFFFFU; - } - /* If Memory address size is 16Bit */ - else - { - /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ - hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); - - /* Prepare Memaddress buffer for LSB part */ - hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); - } - /* Send Slave Address and Memory Address */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Read an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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 == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - 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->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Mem_ISR_IT; - hi2c->Devaddress = DevAddress; - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) - { - /* Prefetch Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - - /* Reset Memaddress content */ - hi2c->Memaddress = 0xFFFFFFFFU; - } - /* If Memory address size is 16Bit */ - else - { - /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ - hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); - - /* Prepare Memaddress buffer for LSB part */ - hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); - } - /* Send Slave Address and Memory Address */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Write an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - 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->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Mem_ISR_DMA; - hi2c->Devaddress = DevAddress; - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) - { - /* Prefetch Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - - /* Reset Memaddress content */ - hi2c->Memaddress = 0xFFFFFFFFU; - } - /* If Memory address size is 16Bit */ - else - { - /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ - hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); - - /* Prepare Memaddress buffer for LSB part */ - hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); - } - - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; - - /* Set DMA destination address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->TXDR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Send Slave Address and Memory Address */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Reads an amount of data in non-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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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) -{ - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - 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->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferISR = I2C_Mem_ISR_DMA; - hi2c->Devaddress = DevAddress; - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) - { - /* Prefetch Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - - /* Reset Memaddress content */ - hi2c->Memaddress = 0xFFFFFFFFU; - } - /* If Memory address size is 16Bit */ - else - { - /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ - hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); - - /* Prepare Memaddress buffer for LSB part */ - hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); - } - - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->RXDR; - - /* Set DMA destination address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Send Slave Address and Memory Address */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @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 tickstart; - - __IO uint32_t I2C_Trials = 0UL; - - FlagStatus tmp1; - FlagStatus tmp2; - - 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->CR2 = I2C_GENERATE_START(hi2c->Init.AddressingMode, DevAddress); - - /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ - /* Wait until STOPF flag is set or a NACK flag is set*/ - tickstart = HAL_GetTick(); - - tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF); - tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); - - while ((tmp1 == RESET) && (tmp2 == RESET)) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - - tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF); - tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); - } - - /* Check if the NACKF flag has not been set */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET) - { - /* Wait until STOPF flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Device is ready */ - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - /* Wait until STOPF flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Clear STOP Flag, auto generated with autoend*/ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - } - - /* Increment Trials */ - I2C_Trials++; - } while (I2C_Trials < Trials); - - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with Interrupt. - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, - uint16_t Size, uint32_t XferOptions) -{ - uint32_t xfermode; - uint32_t xferrequest = I2C_GENERATE_START_WRITE; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Master_ISR_IT; - - /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = hi2c->XferOptions; - } - - /* If transfer direction not change and there is no request to start another frame, - do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \ - (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) - { - xferrequest = I2C_NO_STARTSTOP; - } - else - { - /* Convert OTHER_xxx XferOptions if any */ - I2C_ConvertOtherXferOptions(hi2c); - - /* Update xfermode accordingly if no reload is necessary */ - if (hi2c->XferCount <= MAX_NBYTE_SIZE) - { - xfermode = hi2c->XferOptions; - } - } - - /* Send Slave Address and set NBYTES to write */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with DMA. - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, - uint16_t Size, uint32_t XferOptions) -{ - uint32_t xfermode; - uint32_t xferrequest = I2C_GENERATE_START_WRITE; - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Master_ISR_DMA; - - /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = hi2c->XferOptions; - } - - /* If transfer direction not change and there is no request to start another frame, - do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \ - (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) - { - xferrequest = I2C_NO_STARTSTOP; - } - else - { - /* Convert OTHER_xxx XferOptions if any */ - I2C_ConvertOtherXferOptions(hi2c); - - /* Update xfermode accordingly if no reload is necessary */ - if (hi2c->XferCount <= MAX_NBYTE_SIZE) - { - xfermode = hi2c->XferOptions; - } - } - - if (hi2c->XferSize > 0U) - { - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; - - /* Set DMA destination address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->TXDR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Send Slave Address and set NBYTES to write */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* 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 ERR and NACK interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - /* Update Transfer ISR function pointer */ - hi2c->XferISR = I2C_Master_ISR_IT; - - /* Send Slave Address */ - /* Set NBYTES to write and generate START condition */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_WRITE); - - /* 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 ERR, TC, STOP, NACK, TXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, - uint16_t Size, uint32_t XferOptions) -{ - uint32_t xfermode; - uint32_t xferrequest = I2C_GENERATE_START_READ; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Master_ISR_IT; - - /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = hi2c->XferOptions; - } - - /* If transfer direction not change and there is no request to start another frame, - do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \ - (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) - { - xferrequest = I2C_NO_STARTSTOP; - } - else - { - /* Convert OTHER_xxx XferOptions if any */ - I2C_ConvertOtherXferOptions(hi2c); - - /* Update xfermode accordingly if no reload is necessary */ - if (hi2c->XferCount <= MAX_NBYTE_SIZE) - { - xfermode = hi2c->XferOptions; - } - } - - /* Send Slave Address and set NBYTES to read */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); - - /* 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 */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with DMA - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, - uint16_t Size, uint32_t XferOptions) -{ - uint32_t xfermode; - uint32_t xferrequest = I2C_GENERATE_START_READ; - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Master_ISR_DMA; - - /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - xfermode = hi2c->XferOptions; - } - - /* If transfer direction not change and there is no request to start another frame, - do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \ - (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) - { - xferrequest = I2C_NO_STARTSTOP; - } - else - { - /* Convert OTHER_xxx XferOptions if any */ - I2C_ConvertOtherXferOptions(hi2c); - - /* Update xfermode accordingly if no reload is necessary */ - if (hi2c->XferCount <= MAX_NBYTE_SIZE) - { - xfermode = hi2c->XferOptions; - } - } - - if (hi2c->XferSize > 0U) - { - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->RXDR; - - /* Set DMA destination address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); - } - else - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Send Slave Address and set NBYTES to read */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* 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 ERR and NACK interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - /* Update Transfer ISR function pointer */ - hi2c->XferISR = I2C_Master_ISR_IT; - - /* Send Slave Address */ - /* Set NBYTES to read and generate START condition */ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, - I2C_GENERATE_START_READ); - - /* 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 ERR, TC, STOP, NACK, RXI interrupt */ - /* possible to enable all of these */ - /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | - I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, - uint32_t XferOptions) -{ - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - FlagStatus tmp; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ - /* and then toggle the HAL slave RX state to TX state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) - { - /* Disable associated Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort DMA Xfer if any */ - if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) - { - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - } - - hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Slave_ISR_IT; - - tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE) && (tmp != RESET)) - { - /* Clear ADDR flag after prepare the transfer parameters */ - /* This action will generate an acknowledge to the Master */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - } - - /* 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 */ - /* REnable ADDR interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_ERROR; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with DMA - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, - uint32_t XferOptions) -{ - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - FlagStatus tmp; - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT); - - /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ - /* and then toggle the HAL slave RX state to TX state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) - { - /* Disable associated Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); - - if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) - { - /* Abort DMA Xfer if any */ - if (hi2c->hdmarx != NULL) - { - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } - } - else if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) - { - if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) - { - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - - /* Abort DMA Xfer if any */ - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - } - } - else - { - /* Nothing to do */ - } - - hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Slave_ISR_DMA; - - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; - - /* Set DMA destination address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->TXDR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* Reset XferSize */ - hi2c->XferSize = 0; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE) && (tmp != RESET)) - { - /* Clear ADDR flag after prepare the transfer parameters */ - /* This action will generate an acknowledge to the Master */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - - /* 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 ERR, STOP, NACK, ADDR interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_ERROR; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, - uint32_t XferOptions) -{ - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - FlagStatus tmp; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ - /* and then toggle the HAL slave TX state to RX state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) - { - /* Disable associated Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - -#if defined(HAL_DMA_MODULE_ENABLED) - if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) - { - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - - /* Abort DMA Xfer if any */ - if (hi2c->hdmatx != NULL) - { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - } - - hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Slave_ISR_IT; - - tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT) && (tmp != RESET)) - { - /* Clear ADDR flag after prepare the transfer parameters */ - /* This action will generate an acknowledge to the Master */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - } - - /* 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 */ - /* REnable ADDR interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_ERROR; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with DMA - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, - uint32_t XferOptions) -{ - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - FlagStatus tmp; - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) - { - if ((pData == NULL) || (Size == 0U)) - { - hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ - /* and then toggle the HAL slave TX state to RX state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) - { - /* Disable associated Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - - if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) - { - /* Abort DMA Xfer if any */ - if (hi2c->hdmatx != NULL) - { - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - } - } - else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) - { - if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) - { - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - - /* Abort DMA Xfer if any */ - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } - } - else - { - /* Nothing to do */ - } - - hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->XferISR = I2C_Slave_ISR_DMA; - - if (hi2c->hdmarx != NULL) - { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ - = (uint32_t)&hi2c->Instance->RXDR; - - /* Set DMA destination address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, - hi2c->XferSize); - } - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* Reset XferSize */ - hi2c->XferSize = 0; - } - else - { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT) && (tmp != RESET)) - { - /* Clear ADDR flag after prepare the transfer parameters */ - /* This action will generate an acknowledge to the Master */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Enable DMA Request */ - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* REnable ADDR interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_ERROR; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Enable the Address listen mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c) -{ - if (hi2c->State == HAL_I2C_STATE_READY) - { - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->XferISR = I2C_Slave_ISR_IT; - - /* Enable the Address Match interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Disable the Address listen mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) -{ - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - uint32_t tmp; - - /* Disable Address listen mode only if a transfer is not ongoing */ - if (hi2c->State == HAL_I2C_STATE_LISTEN) - { - tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK; - hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode); - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->XferISR = NULL; - - /* Disable the Address Match interrupt */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) -{ - HAL_I2C_ModeTypeDef tmp_mode = hi2c->Mode; - - if ((tmp_mode == HAL_I2C_MODE_MASTER) || (tmp_mode == HAL_I2C_MODE_MEM)) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Disable Interrupts and Store Previous state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - } - else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; - } - else - { - /* Do nothing */ - } - - /* Set State at HAL_I2C_STATE_ABORT */ - hi2c->State = HAL_I2C_STATE_ABORT; - - /* Set NBYTES to 1 to generate a dummy read on I2C peripheral */ - /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ - I2C_TransferConfig(hi2c, DevAddress, 1, I2C_AUTOEND_MODE, I2C_GENERATE_STOP); - - /* 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 */ - I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); - - return HAL_OK; - } - else - { - /* Wrong usage of abort function */ - /* This function should be used only in case of abort monitored by master device */ - return HAL_ERROR; - } -} - -/** - * @} - */ - -/** @defgroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks - * @{ - */ - -/** - * @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 None - */ -void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Get current IT Flags and IT sources value */ - uint32_t itflags = READ_REG(hi2c->Instance->ISR); - uint32_t itsources = READ_REG(hi2c->Instance->CR1); - - /* I2C events treatment -------------------------------------*/ - if (hi2c->XferISR != NULL) - { - hi2c->XferISR(hi2c, itflags, itsources); - } -} - -/** - * @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 None - */ -void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) -{ - uint32_t itflags = READ_REG(hi2c->Instance->ISR); - uint32_t itsources = READ_REG(hi2c->Instance->CR1); - uint32_t tmperror; - - /* I2C Bus error interrupt occurred ------------------------------------*/ - if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_BERR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_BERR; - - /* Clear BERR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); - } - - /* I2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/ - if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_OVR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_OVR; - - /* Clear OVR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); - } - - /* I2C Arbitration Loss error interrupt occurred -------------------------------------*/ - if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_ARLO) != RESET) && \ - (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO; - - /* Clear ARLO flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); - } - - /* Store current volatile hi2c->ErrorCode, misra rule */ - tmperror = hi2c->ErrorCode; - - /* Call the Error Callback in case of Error detected */ - if ((tmperror & (HAL_I2C_ERROR_BERR | HAL_I2C_ERROR_OVR | HAL_I2C_ERROR_ARLO)) != HAL_I2C_ERROR_NONE) - { - I2C_ITError(hi2c, tmperror); - } -} - -/** - * @brief Master Tx Transfer completed callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MasterTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Master Rx Transfer completed callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MasterRxCpltCallback could be implemented in the user file - */ -} - -/** @brief Slave Tx Transfer completed callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_SlaveTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Slave Rx Transfer completed callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_SlaveRxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Slave Address Match callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XFERDIRECTION - * @param AddrMatchCode Address Match Code - * @retval None - */ -__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - UNUSED(TransferDirection); - UNUSED(AddrMatchCode); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_AddrCallback() could be implemented in the user file - */ -} - -/** - * @brief Listen Complete callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_ListenCpltCallback() could be implemented in the user file - */ -} - -/** - * @brief Memory Tx Transfer completed callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MemTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Memory Rx Transfer completed callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MemRxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief I2C error callback. - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief I2C abort callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_AbortCpltCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions - * @brief Peripheral State, Mode and Error functions - * -@verbatim - =============================================================================== - ##### Peripheral State, Mode and Error functions ##### - =============================================================================== - [..] - This subsection permit to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the I2C handle state. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL state - */ -HAL_I2C_StateTypeDef HAL_I2C_GetState(const I2C_HandleTypeDef *hi2c) -{ - /* Return I2C handle state */ - return hi2c->State; -} - -/** - * @brief Returns the I2C Master, Slave, Memory or no mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL mode - */ -HAL_I2C_ModeTypeDef HAL_I2C_GetMode(const I2C_HandleTypeDef *hi2c) -{ - return hi2c->Mode; -} - -/** - * @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(const I2C_HandleTypeDef *hi2c) -{ - return hi2c->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup I2C_Private_Functions - * @{ - */ - -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param ITFlags Interrupt flags to handle. - * @param ITSources Interrupt sources enabled. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources) -{ - uint16_t devaddress; - uint32_t tmpITFlags = ITFlags; - - /* Process Locked */ - __HAL_LOCK(hi2c); - - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set corresponding Error Code */ - /* No need to generate STOP, it is automatically done */ - /* Error callback will be send during stop flag treatment */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET)) - { - /* Remove RXNE flag on temporary variable as read done */ - tmpITFlags &= ~I2C_FLAG_RXNE; - - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) - { - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) - { - devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD); - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - if (hi2c->XferOptions != I2C_NO_OPTION_FRAME) - { - I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, - hi2c->XferOptions, I2C_NO_STARTSTOP); - } - else - { - I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, - I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); - } - } - } - else - { - /* Call TxCpltCallback() if no stop mode is set */ - if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) - { - /* Call I2C Master Sequential complete process */ - I2C_ITMasterSeqCplt(hi2c); - } - else - { - /* Wrong size Status regarding TCR flag event */ - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); - } - } - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - if (hi2c->XferCount == 0U) - { - if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) - { - /* Generate a stop condition in case of no transfer option */ - if (hi2c->XferOptions == I2C_NO_OPTION_FRAME) - { - /* Generate Stop */ - hi2c->Instance->CR2 |= I2C_CR2_STOP; - } - else - { - /* Call I2C Master Sequential complete process */ - I2C_ITMasterSeqCplt(hi2c); - } - } - } - else - { - /* Wrong size Status regarding TC flag event */ - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); - } - } - else - { - /* Nothing to do */ - } - - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) - { - /* Call I2C Master complete process */ - I2C_ITMasterCplt(hi2c, tmpITFlags); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Memory Mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param ITFlags Interrupt flags to handle. - * @param ITSources Interrupt sources enabled. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources) -{ - uint32_t direction = I2C_GENERATE_START_WRITE; - uint32_t tmpITFlags = ITFlags; - - /* Process Locked */ - __HAL_LOCK(hi2c); - - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set corresponding Error Code */ - /* No need to generate STOP, it is automatically done */ - /* Error callback will be send during stop flag treatment */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET)) - { - /* Remove RXNE flag on temporary variable as read done */ - tmpITFlags &= ~I2C_FLAG_RXNE; - - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) - { - if (hi2c->Memaddress == 0xFFFFFFFFU) - { - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - } - else - { - /* Write LSB part of Memory Address */ - hi2c->Instance->TXDR = hi2c->Memaddress; - - /* Reset Memaddress content */ - hi2c->Memaddress = 0xFFFFFFFFU; - } - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) - { - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_RELOAD_MODE, I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); - } - } - else - { - /* Wrong size Status regarding TCR flag event */ - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); - } - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - /* Disable Interrupt related to address step */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - - /* Enable ERR, TC, STOP, NACK and RXI interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); - - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - direction = I2C_GENERATE_START_READ; - } - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_RELOAD_MODE, direction); - } - else - { - hi2c->XferSize = hi2c->XferCount; - - /* Set NBYTES to write and generate RESTART */ - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_AUTOEND_MODE, direction); - } - } - else - { - /* Nothing to do */ - } - - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) - { - /* Call I2C Master complete process */ - I2C_ITMasterCplt(hi2c, tmpITFlags); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param ITFlags Interrupt flags to handle. - * @param ITSources Interrupt sources enabled. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources) -{ - uint32_t tmpoptions = hi2c->XferOptions; - uint32_t tmpITFlags = ITFlags; - - /* Process locked */ - __HAL_LOCK(hi2c); - - /* Check if STOPF is set */ - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) - { - /* Call I2C Slave complete process */ - I2C_ITSlaveCplt(hi2c, tmpITFlags); - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) - { - /* Check that I2C transfer finished */ - /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ - /* Mean XferCount == 0*/ - /* So clear Flag NACKF only */ - if (hi2c->XferCount == 0U) - { - if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) - /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for - Warning[Pa134]: left and right operands are identical */ - { - /* Call I2C Listen complete process */ - I2C_ITListenCplt(hi2c, tmpITFlags); - } - else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* Last Byte is Transmitted */ - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - else - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - } - } - else - { - /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, hi2c->ErrorCode); - } - } - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET)) - { - if (hi2c->XferCount > 0U) - { - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferSize--; - hi2c->XferCount--; - } - - if ((hi2c->XferCount == 0U) && \ - (tmpoptions != I2C_NO_OPTION_FRAME)) - { - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_ADDR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET)) - { - I2C_ITAddrCplt(hi2c, tmpITFlags); - } - else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) - { - /* Write data to TXDR only if XferCount not reach "0" */ - /* A TXIS flag can be set, during STOP treatment */ - /* Check if all Data have already been sent */ - /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ - if (hi2c->XferCount > 0U) - { - /* Write data to TXDR */ - hi2c->Instance->TXDR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - hi2c->XferCount--; - hi2c->XferSize--; - } - else - { - if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME)) - { - /* Last Byte is Transmitted */ - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - } - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with DMA. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param ITFlags Interrupt flags to handle. - * @param ITSources Interrupt sources enabled. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources) -{ - uint16_t devaddress; - uint32_t xfermode; - - /* Process Locked */ - __HAL_LOCK(hi2c); - - if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set corresponding Error Code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* No need to generate STOP, it is automatically done */ - /* But enable STOP interrupt, to treat it */ - /* Error callback will be send during stop flag treatment */ - I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - /* Disable TC interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_TCI); - - if (hi2c->XferCount != 0U) - { - /* Recover Slave address */ - devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD); - - /* Prepare the new XferSize to transfer */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - xfermode = I2C_RELOAD_MODE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - if (hi2c->XferOptions != I2C_NO_OPTION_FRAME) - { - xfermode = hi2c->XferOptions; - } - else - { - xfermode = I2C_AUTOEND_MODE; - } - } - - /* Set the new XferSize in Nbytes register */ - I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, xfermode, I2C_NO_STARTSTOP); - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* Enable DMA Request */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - } - else - { - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - } - } - else - { - /* Call TxCpltCallback() if no stop mode is set */ - if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) - { - /* Call I2C Master Sequential complete process */ - I2C_ITMasterSeqCplt(hi2c); - } - else - { - /* Wrong size Status regarding TCR flag event */ - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); - } - } - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - if (hi2c->XferCount == 0U) - { - if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) - { - /* Generate a stop condition in case of no transfer option */ - if (hi2c->XferOptions == I2C_NO_OPTION_FRAME) - { - /* Generate Stop */ - hi2c->Instance->CR2 |= I2C_CR2_STOP; - } - else - { - /* Call I2C Master Sequential complete process */ - I2C_ITMasterSeqCplt(hi2c); - } - } - } - else - { - /* Wrong size Status regarding TC flag event */ - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); - } - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) - { - /* Call I2C Master complete process */ - I2C_ITMasterCplt(hi2c, ITFlags); - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Memory Mode with DMA. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param ITFlags Interrupt flags to handle. - * @param ITSources Interrupt sources enabled. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources) -{ - uint32_t direction = I2C_GENERATE_START_WRITE; - - /* Process Locked */ - __HAL_LOCK(hi2c); - - if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set corresponding Error Code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* No need to generate STOP, it is automatically done */ - /* But enable STOP interrupt, to treat it */ - /* Error callback will be send during stop flag treatment */ - I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TXIS) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) - { - /* Write LSB part of Memory Address */ - hi2c->Instance->TXDR = hi2c->Memaddress; - - /* Reset Memaddress content */ - hi2c->Memaddress = 0xFFFFFFFFU; - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - /* Disable Interrupt related to address step */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - - /* Enable only Error interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); - - if (hi2c->XferCount != 0U) - { - /* Prepare the new XferSize to transfer */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_RELOAD_MODE, I2C_NO_STARTSTOP); - } - else - { - hi2c->XferSize = hi2c->XferCount; - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); - } - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* Enable DMA Request */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - } - else - { - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - } - } - else - { - /* Wrong size Status regarding TCR flag event */ - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); - } - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) - { - /* Disable Interrupt related to address step */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - - /* Enable only Error and NACK interrupt for data transfer */ - I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); - - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - direction = I2C_GENERATE_START_READ; - } - - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - - /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_RELOAD_MODE, direction); - } - else - { - hi2c->XferSize = hi2c->XferCount; - - /* Set NBYTES to write and generate RESTART */ - I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, - I2C_AUTOEND_MODE, direction); - } - - /* Update XferCount value */ - hi2c->XferCount -= hi2c->XferSize; - - /* Enable DMA Request */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; - } - else - { - hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; - } - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) - { - /* Call I2C Master complete process */ - I2C_ITMasterCplt(hi2c, ITFlags); - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with DMA. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param ITFlags Interrupt flags to handle. - * @param ITSources Interrupt sources enabled. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, - uint32_t ITSources) -{ - uint32_t tmpoptions = hi2c->XferOptions; - uint32_t treatdmanack = 0U; - HAL_I2C_StateTypeDef tmpstate; - - /* Process locked */ - __HAL_LOCK(hi2c); - - /* Check if STOPF is set */ - if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) - { - /* Call I2C Slave complete process */ - I2C_ITSlaveCplt(hi2c, ITFlags); - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) - { - /* Check that I2C transfer finished */ - /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ - /* Mean XferCount == 0 */ - /* So clear Flag NACKF only */ - if ((I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET) || - (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET)) - { - /* Split check of hdmarx, for MISRA compliance */ - if (hi2c->hdmarx != NULL) - { - if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET) - { - if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U) - { - treatdmanack = 1U; - } - } - } - - /* Split check of hdmatx, for MISRA compliance */ - if (hi2c->hdmatx != NULL) - { - if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET) - { - if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx) == 0U) - { - treatdmanack = 1U; - } - } - } - - if (treatdmanack == 1U) - { - if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) - /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for - Warning[Pa134]: left and right operands are identical */ - { - /* Call I2C Listen complete process */ - I2C_ITListenCplt(hi2c, ITFlags); - } - else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* Last Byte is Transmitted */ - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - else - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - } - } - else - { - /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* Store current hi2c->State, solve MISRA2012-Rule-13.5 */ - tmpstate = hi2c->State; - - if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) - { - if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN)) - { - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; - } - else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN)) - { - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; - } - else - { - /* Do nothing */ - } - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, hi2c->ErrorCode); - } - } - } - else - { - /* Only Clear NACK Flag, no DMA treatment is pending */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - } - } - else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_ADDR) != RESET) && \ - (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET)) - { - I2C_ITAddrCplt(hi2c, ITFlags); - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, - uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, - uint32_t Tickstart) -{ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); - - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) - { - /* Send Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - } - /* If Memory address size is 16Bit */ - else - { - /* Send MSB of Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); - - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Send LSB of Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - } - - /* Wait until TCR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - 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: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, - uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, - uint32_t Tickstart) -{ - I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); - - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) - { - /* Send Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - } - /* If Memory address size is 16Bit */ - else - { - /* Send MSB of Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); - - /* Wait until TXIS flag is set */ - if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Send LSB of Memory Address */ - hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); - } - - /* Wait until TC flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TC, RESET, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief I2C Address complete process callback. - * @param hi2c I2C handle. - * @param ITFlags Interrupt flags to handle. - * @retval None - */ -static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) -{ - uint8_t transferdirection; - uint16_t slaveaddrcode; - uint16_t ownadd1code; - uint16_t ownadd2code; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(ITFlags); - - /* In case of Listen state, need to inform upper layer of address match code event */ - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) - { - transferdirection = I2C_GET_DIR(hi2c); - slaveaddrcode = I2C_GET_ADDR_MATCH(hi2c); - ownadd1code = I2C_GET_OWN_ADDRESS1(hi2c); - ownadd2code = I2C_GET_OWN_ADDRESS2(hi2c); - - /* If 10bits addressing mode is selected */ - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) - { - if ((slaveaddrcode & SLAVE_ADDR_MSK) == ((ownadd1code >> SLAVE_ADDR_SHIFT) & SLAVE_ADDR_MSK)) - { - slaveaddrcode = ownadd1code; - hi2c->AddrEventCount++; - if (hi2c->AddrEventCount == 2U) - { - /* Reset Address Event counter */ - hi2c->AddrEventCount = 0U; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call Slave Addr callback */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode); -#else - HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - else - { - slaveaddrcode = ownadd2code; - - /* Disable ADDR Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call Slave Addr callback */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode); -#else - HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - /* else 7 bits addressing mode is selected */ - else - { - /* Disable ADDR Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call Slave Addr callback */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode); -#else - HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - /* Else clear address flag only */ - else - { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - } -} - -/** - * @brief I2C Master sequential complete process. - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c) -{ - /* Reset I2C handle mode */ - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* No Generate Stop, to permit restart mode */ - /* The stop will be done at the end of transfer, when I2C_AUTOEND_MODE enable */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - hi2c->XferISR = NULL; - - /* Disable Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterTxCpltCallback(hi2c); -#else - HAL_I2C_MasterTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - /* hi2c->State == HAL_I2C_STATE_BUSY_RX */ - else - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; - hi2c->XferISR = NULL; - - /* Disable Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterRxCpltCallback(hi2c); -#else - HAL_I2C_MasterRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } -} - -/** - * @brief I2C Slave sequential complete process. - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c) -{ - uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1); - - /* Reset I2C handle mode */ - hi2c->Mode = HAL_I2C_MODE_NONE; - -#if defined(HAL_DMA_MODULE_ENABLED) - /* If a DMA is ongoing, Update handle size context */ - if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET) - { - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - } - else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET) - { - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - } - else - { - /* Do nothing */ - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) - { - /* Remove HAL_I2C_STATE_SLAVE_BUSY_TX, keep only HAL_I2C_STATE_LISTEN */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; - - /* Disable Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveTxCpltCallback(hi2c); -#else - HAL_I2C_SlaveTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - - else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) - { - /* Remove HAL_I2C_STATE_SLAVE_BUSY_RX, keep only HAL_I2C_STATE_LISTEN */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; - - /* Disable Interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveRxCpltCallback(hi2c); -#else - HAL_I2C_SlaveRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } -} - -/** - * @brief I2C Master complete process. - * @param hi2c I2C handle. - * @param ITFlags Interrupt flags to handle. - * @retval None - */ -static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) -{ - uint32_t tmperror; - uint32_t tmpITFlags = ITFlags; - __IO uint32_t tmpreg; - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Disable Interrupts and Store Previous state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - } - else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; - } - else - { - /* Do nothing */ - } - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - /* Reset handle parameters */ - hi2c->XferISR = NULL; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set acknowledge error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - - /* Fetch Last receive data if any */ - if ((hi2c->State == HAL_I2C_STATE_ABORT) && (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET)) - { - /* Read data from RXDR */ - tmpreg = (uint8_t)hi2c->Instance->RXDR; - UNUSED(tmpreg); - } - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* Store current volatile hi2c->ErrorCode, misra rule */ - tmperror = hi2c->ErrorCode; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if ((hi2c->State == HAL_I2C_STATE_ABORT) || (tmperror != HAL_I2C_ERROR_NONE)) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, hi2c->ErrorCode); - } - /* hi2c->State == HAL_I2C_STATE_BUSY_TX */ - else if (hi2c->State == HAL_I2C_STATE_BUSY_TX) - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) - { - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemTxCpltCallback(hi2c); -#else - HAL_I2C_MemTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - else - { - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterTxCpltCallback(hi2c); -#else - HAL_I2C_MasterTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - /* hi2c->State == HAL_I2C_STATE_BUSY_RX */ - else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) - { - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemRxCpltCallback(hi2c); -#else - HAL_I2C_MemRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - else - { - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterRxCpltCallback(hi2c); -#else - HAL_I2C_MasterRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } -} - -/** - * @brief I2C Slave complete process. - * @param hi2c I2C handle. - * @param ITFlags Interrupt flags to handle. - * @retval None - */ -static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) -{ - uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1); - uint32_t tmpITFlags = ITFlags; - uint32_t tmpoptions = hi2c->XferOptions; - HAL_I2C_StateTypeDef tmpstate = hi2c->State; - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Disable Interrupts and Store Previous state */ - if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN)) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT); - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; - } - else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN)) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT); - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; - } - else if (tmpstate == HAL_I2C_STATE_LISTEN) - { - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT | I2C_XFER_RX_IT); - hi2c->PreviousState = I2C_STATE_NONE; - } - else - { - /* Do nothing */ - } - - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* If a DMA is ongoing, Update handle size context */ - if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET) - { - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - - if (hi2c->hdmatx != NULL) - { - hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx); - } - } - else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET) - { - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - - if (hi2c->hdmarx != NULL) - { - hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx); - } - } - else - { - /* Do nothing */ - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Store Last receive data if any */ - if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) - { - /* Remove RXNE flag on temporary variable as read done */ - tmpITFlags &= ~I2C_FLAG_RXNE; - - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - if ((hi2c->XferSize > 0U)) - { - hi2c->XferSize--; - hi2c->XferCount--; - } - } - - /* All data are not transferred, so set error code accordingly */ - if (hi2c->XferCount != 0U) - { - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - - if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ - (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_IT_NACKI) != RESET)) - { - /* Check that I2C transfer finished */ - /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ - /* Mean XferCount == 0*/ - /* So clear Flag NACKF only */ - if (hi2c->XferCount == 0U) - { - if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) - /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for - Warning[Pa134]: left and right operands are identical */ - { - /* Call I2C Listen complete process */ - I2C_ITListenCplt(hi2c, tmpITFlags); - } - else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* Last Byte is Transmitted */ - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - else - { - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - } - } - else - { - /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, hi2c->ErrorCode); - } - } - } - - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->XferISR = NULL; - - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, hi2c->ErrorCode); - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ - if (hi2c->State == HAL_I2C_STATE_LISTEN) - { - /* Call I2C Listen complete process */ - I2C_ITListenCplt(hi2c, tmpITFlags); - } - } - else if (hi2c->XferOptions != I2C_NO_OPTION_FRAME) - { - /* Call the Sequential Complete callback, to inform upper layer of the end of Transfer */ - I2C_ITSlaveSeqCplt(hi2c); - - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ListenCpltCallback(hi2c); -#else - HAL_I2C_ListenCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - /* Call the corresponding callback to inform upper layer of End of Transfer */ - else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveRxCpltCallback(hi2c); -#else - HAL_I2C_SlaveRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - else - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveTxCpltCallback(hi2c); -#else - HAL_I2C_SlaveTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } -} - -/** - * @brief I2C Listen complete process. - * @param hi2c I2C handle. - * @param ITFlags Interrupt flags to handle. - * @retval None - */ -static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) -{ - /* Reset handle parameters */ - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->XferISR = NULL; - - /* Store Last receive data if any */ - if (I2C_CHECK_FLAG(ITFlags, I2C_FLAG_RXNE) != RESET) - { - /* Read data from RXDR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - if ((hi2c->XferSize > 0U)) - { - hi2c->XferSize--; - hi2c->XferCount--; - - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - } - - /* Disable all Interrupts*/ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT); - - /* Clear NACK Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ListenCpltCallback(hi2c); -#else - HAL_I2C_ListenCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -} - -/** - * @brief I2C interrupts error process. - * @param hi2c I2C handle. - * @param ErrorCode Error code to handle. - * @retval None - */ -static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode) -{ - HAL_I2C_StateTypeDef tmpstate = hi2c->State; - -#if defined(HAL_DMA_MODULE_ENABLED) - uint32_t tmppreviousstate; -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset handle parameters */ - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferCount = 0U; - - /* Set new error code */ - hi2c->ErrorCode |= ErrorCode; - - /* Disable Interrupts */ - if ((tmpstate == HAL_I2C_STATE_LISTEN) || - (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN) || - (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN)) - { - /* Disable all interrupts, except interrupts related to LISTEN state */ - I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_TX_IT); - - /* keep HAL_I2C_STATE_LISTEN if set */ - hi2c->State = HAL_I2C_STATE_LISTEN; - hi2c->XferISR = I2C_Slave_ISR_IT; - } - else - { - /* Disable all interrupts */ - I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT); - - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* If state is an abort treatment on going, don't change state */ - /* This change will be do later */ - if (hi2c->State != HAL_I2C_STATE_ABORT) - { - /* Set HAL_I2C_STATE_READY */ - hi2c->State = HAL_I2C_STATE_READY; - - /* Check if a STOPF is detected */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) - { - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) - { - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - } - - } - hi2c->XferISR = NULL; - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort DMA TX transfer if any */ - tmppreviousstate = hi2c->PreviousState; - - if ((hi2c->hdmatx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_TX) || \ - (tmppreviousstate == I2C_STATE_SLAVE_BUSY_TX))) - { - if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) - { - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - } - - if (HAL_DMA_GetState(hi2c->hdmatx) != HAL_DMA_STATE_READY) - { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - else - { - I2C_TreatErrorCallback(hi2c); - } - } - /* Abort DMA RX transfer if any */ - else if ((hi2c->hdmarx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_RX) || \ - (tmppreviousstate == I2C_STATE_SLAVE_BUSY_RX))) - { - if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) - { - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - } - - if (HAL_DMA_GetState(hi2c->hdmarx) != HAL_DMA_STATE_READY) - { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) - { - /* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - else - { - I2C_TreatErrorCallback(hi2c); - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - I2C_TreatErrorCallback(hi2c); - } -} - -/** - * @brief I2C Error callback treatment. - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c) -{ - if (hi2c->State == HAL_I2C_STATE_ABORT) - { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AbortCpltCallback(hi2c); -#else - HAL_I2C_AbortCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - else - { - hi2c->PreviousState = I2C_STATE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ErrorCallback(hi2c); -#else - HAL_I2C_ErrorCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } -} - -/** - * @brief I2C Tx data register flush process. - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c) -{ - /* If a pending TXIS flag is set */ - /* Write a dummy data in TXDR to clear it */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) != RESET) - { - hi2c->Instance->TXDR = 0x00U; - } - - /* Flush TX register if not empty */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET) - { - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_TXE); - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief DMA I2C master transmit process complete callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma) -{ - HAL_StatusTypeDef dmaxferstatus = HAL_OK; - /* Derogation MISRAC2012-Rule-11.5 */ - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - - /* If last transfer, enable STOP interrupt */ - if (hi2c->XferCount == 0U) - { - /* Enable STOP interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); - } - /* else prepare a new DMA transfer and enable TCReload interrupt */ - else - { - /* Update Buffer pointer */ - hi2c->pBuffPtr += hi2c->XferSize; - - /* Set the XferSize to transfer */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - } - - /* Enable the DMA channel */ - if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr; - - /* Set DMA destination address */ - hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2c->Instance->TXDR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); - } - else - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, - hi2c->XferSize); - } - - if (dmaxferstatus != HAL_OK) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); - } - else - { - /* Enable TC interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT); - } - } -} - - -/** - * @brief DMA I2C slave transmit process complete callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - uint32_t tmpoptions = hi2c->XferOptions; - - if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME)) - { - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; - - /* Last Byte is Transmitted */ - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - else - { - /* No specific action, Master fully manage the generation of STOP condition */ - /* Mean that this generation can arrive at any time, at the end or during DMA process */ - /* So STOP condition should be manage through Interrupt treatment */ - } -} - - -/** - * @brief DMA I2C master receive process complete callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma) -{ - HAL_StatusTypeDef dmaxferstatus = HAL_OK; - /* Derogation MISRAC2012-Rule-11.5 */ - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - - /* If last transfer, enable STOP interrupt */ - if (hi2c->XferCount == 0U) - { - /* Enable STOP interrupt */ - I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); - } - /* else prepare a new DMA transfer and enable TCReload interrupt */ - else - { - /* Update Buffer pointer */ - hi2c->pBuffPtr += hi2c->XferSize; - - /* Set the XferSize to transfer */ - if (hi2c->XferCount > MAX_NBYTE_SIZE) - { - hi2c->XferSize = MAX_NBYTE_SIZE; - } - else - { - hi2c->XferSize = hi2c->XferCount; - } - - /* Enable the DMA channel */ - if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2c->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; - - /* Set DMA source address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2c->Instance->RXDR; - - /* Set DMA destination address */ - hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); - } - else - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr, - hi2c->XferSize); - } - - if (dmaxferstatus != HAL_OK) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); - } - else - { - /* Enable TC interrupts */ - I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT); - } - } -} - - -/** - * @brief DMA I2C slave receive process complete callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - uint32_t tmpoptions = hi2c->XferOptions; - - if ((I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U) && \ - (tmpoptions != I2C_NO_OPTION_FRAME)) - { - /* Disable DMA Request */ - hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; - - /* Call I2C Slave Sequential complete process */ - I2C_ITSlaveSeqCplt(hi2c); - } - else - { - /* No specific action, Master fully manage the generation of STOP condition */ - /* Mean that this generation can arrive at any time, at the end or during DMA process */ - /* So STOP condition should be manage through Interrupt treatment */ - } -} - - -/** - * @brief DMA I2C communication error callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAError(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Disable Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); -} - - -/** - * @brief DMA I2C communication abort callback - * (To be called at end of DMA Abort procedure). - * @param hdma DMA handle. - * @retval None - */ -static void I2C_DMAAbort(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Reset AbortCpltCallback */ - if (hi2c->hdmatx != NULL) - { - hi2c->hdmatx->XferAbortCallback = NULL; - } - if (hi2c->hdmarx != NULL) - { - hi2c->hdmarx->XferAbortCallback = NULL; - } - - I2C_TreatErrorCallback(hi2c); -} - -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief This function handles I2C Communication Timeout. It waits - * until a flag is no longer in the specified status. - * @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 actual Flag status (SET or RESET). - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, - uint32_t Timeout, uint32_t Tickstart) -{ - while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status) - { - /* Check if an error is detected */ - if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - if ((__HAL_I2C_GET_FLAG(hi2c, Flag) == Status)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of TXIS flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart) -{ - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET) - { - /* Check if an error is detected */ - if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of STOP flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart) -{ - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) - { - /* Check if an error is detected */ - if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) - { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, - uint32_t Tickstart) -{ - HAL_StatusTypeDef status = HAL_OK; - - while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) && (status == HAL_OK)) - { - /* Check if an error is detected */ - if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) - { - status = HAL_ERROR; - } - - /* Check if a STOPF is detected */ - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) && (status == HAL_OK)) - { - /* Check if an RXNE is pending */ - /* Store Last receive data if any */ - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) && (hi2c->XferSize > 0U)) - { - /* Return HAL_OK */ - /* The Reading of data from RXDR will be done in caller function */ - status = HAL_OK; - } - - /* Check a no-acknowledge have been detected */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) - { - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - hi2c->ErrorCode = HAL_I2C_ERROR_AF; - - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - status = HAL_ERROR; - } - else - { - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - } - } - - /* Check for the Timeout */ - if ((((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) && (status == HAL_OK)) - { - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET)) - { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - status = HAL_ERROR; - } - } - } - return status; -} - -/** - * @brief This function handles errors detection during an I2C Communication. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t itflag = hi2c->Instance->ISR; - uint32_t error_code = 0; - uint32_t tickstart = Tickstart; - uint32_t tmp1; - HAL_I2C_ModeTypeDef tmp2; - - if (HAL_IS_BIT_SET(itflag, I2C_FLAG_AF)) - { - /* Clear NACKF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Wait until STOP Flag is set or timeout occurred */ - /* AutoEnd should be initiate after AF */ - while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) && (status == HAL_OK)) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - tmp1 = (uint32_t)(hi2c->Instance->CR2 & I2C_CR2_STOP); - tmp2 = hi2c->Mode; - - /* In case of I2C still busy, try to regenerate a STOP manually */ - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && \ - (tmp1 != I2C_CR2_STOP) && \ - (tmp2 != HAL_I2C_MODE_SLAVE)) - { - /* Generate Stop */ - hi2c->Instance->CR2 |= I2C_CR2_STOP; - - /* Update Tick with new reference */ - tickstart = HAL_GetTick(); - } - - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > I2C_TIMEOUT_STOPF) - { - error_code |= HAL_I2C_ERROR_TIMEOUT; - - status = HAL_ERROR; - - break; - } - } - } - } - } - - /* In case STOP Flag is detected, clear it */ - if (status == HAL_OK) - { - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - } - - error_code |= HAL_I2C_ERROR_AF; - - status = HAL_ERROR; - } - - /* Refresh Content of Status register */ - itflag = hi2c->Instance->ISR; - - /* Then verify if an additional errors occurs */ - /* Check if a Bus error occurred */ - if (HAL_IS_BIT_SET(itflag, I2C_FLAG_BERR)) - { - error_code |= HAL_I2C_ERROR_BERR; - - /* Clear BERR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); - - status = HAL_ERROR; - } - - /* Check if an Over-Run/Under-Run error occurred */ - if (HAL_IS_BIT_SET(itflag, I2C_FLAG_OVR)) - { - error_code |= HAL_I2C_ERROR_OVR; - - /* Clear OVR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); - - status = HAL_ERROR; - } - - /* Check if an Arbitration Loss error occurred */ - if (HAL_IS_BIT_SET(itflag, I2C_FLAG_ARLO)) - { - error_code |= HAL_I2C_ERROR_ARLO; - - /* Clear ARLO flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); - - status = HAL_ERROR; - } - - if (status != HAL_OK) - { - /* Flush TX register */ - I2C_Flush_TXDR(hi2c); - - /* Clear Configuration Register 2 */ - I2C_RESET_CR2(hi2c); - - hi2c->ErrorCode |= error_code; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - } - - return status; -} - -/** - * @brief Handles I2Cx communication when starting transfer or during transfer (TC or TCR flag are set). - * @param hi2c I2C handle. - * @param DevAddress Specifies the slave address to be programmed. - * @param Size Specifies the number of bytes to be programmed. - * This parameter must be a value between 0 and 255. - * @param Mode New state of the I2C START condition generation. - * This parameter can be one of the following values: - * @arg @ref I2C_RELOAD_MODE Enable Reload mode . - * @arg @ref I2C_AUTOEND_MODE Enable Automatic end mode. - * @arg @ref I2C_SOFTEND_MODE Enable Software end mode. - * @param Request New state of the I2C START condition generation. - * This parameter can be one of the following values: - * @arg @ref I2C_NO_STARTSTOP Don't Generate stop and start condition. - * @arg @ref I2C_GENERATE_STOP Generate stop condition (Size should be set to 0). - * @arg @ref I2C_GENERATE_START_READ Generate Restart for read request. - * @arg @ref I2C_GENERATE_START_WRITE Generate Restart for write request. - * @retval None - */ -static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, - uint32_t Request) -{ - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - assert_param(IS_TRANSFER_MODE(Mode)); - assert_param(IS_TRANSFER_REQUEST(Request)); - - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - uint32_t tmp = ((uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \ - (((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \ - (uint32_t)Mode | (uint32_t)Request) & (~0x80000000U)); - - /* update CR2 register */ - MODIFY_REG(hi2c->Instance->CR2, \ - ((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \ - (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31U - I2C_CR2_RD_WRN_Pos))) | \ - I2C_CR2_START | I2C_CR2_STOP)), tmp); -} - -/** - * @brief Manage the enabling of Interrupts. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param InterruptRequest Value of @ref I2C_Interrupt_configuration_definition. - * @retval None - */ -static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest) -{ - uint32_t tmpisr = 0U; - -#if defined(HAL_DMA_MODULE_ENABLED) - if ((hi2c->XferISR != I2C_Master_ISR_DMA) && \ - (hi2c->XferISR != I2C_Slave_ISR_DMA) && \ - (hi2c->XferISR != I2C_Mem_ISR_DMA)) -#endif /* HAL_DMA_MODULE_ENABLED */ - { - if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT) - { - /* Enable ERR, STOP, NACK and ADDR interrupts */ - tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; - } - - if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT) - { - /* Enable ERR, TC, STOP, NACK and TXI interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI; - } - - if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT) - { - /* Enable ERR, TC, STOP, NACK and RXI interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI; - } - - if (InterruptRequest == I2C_XFER_ERROR_IT) - { - /* Enable ERR and NACK interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI; - } - - if (InterruptRequest == I2C_XFER_CPLT_IT) - { - /* Enable STOP interrupts */ - tmpisr |= I2C_IT_STOPI; - } - } - -#if defined(HAL_DMA_MODULE_ENABLED) - else - { - if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT) - { - /* Enable ERR, STOP, NACK and ADDR interrupts */ - tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; - } - - if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT) - { - /* Enable ERR, TC, STOP, NACK and TXI interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI; - } - - if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT) - { - /* Enable ERR, TC, STOP, NACK and RXI interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI; - } - - if (InterruptRequest == I2C_XFER_ERROR_IT) - { - /* Enable ERR and NACK interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI; - } - - if (InterruptRequest == I2C_XFER_CPLT_IT) - { - /* Enable STOP interrupts */ - tmpisr |= (I2C_IT_STOPI | I2C_IT_TCI); - } - - if (InterruptRequest == I2C_XFER_RELOAD_IT) - { - /* Enable TC interrupts */ - tmpisr |= I2C_IT_TCI; - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Enable interrupts only at the end */ - /* to avoid the risk of I2C interrupt handle execution before */ - /* all interrupts requested done */ - __HAL_I2C_ENABLE_IT(hi2c, tmpisr); -} - -/** - * @brief Manage the disabling of Interrupts. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param InterruptRequest Value of @ref I2C_Interrupt_configuration_definition. - * @retval None - */ -static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest) -{ - uint32_t tmpisr = 0U; - - if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT) - { - /* Disable TC and TXI interrupts */ - tmpisr |= I2C_IT_TCI | I2C_IT_TXI; - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN) - { - /* Disable NACK and STOP interrupts */ - tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; - } - } - - if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT) - { - /* Disable TC and RXI interrupts */ - tmpisr |= I2C_IT_TCI | I2C_IT_RXI; - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN) - { - /* Disable NACK and STOP interrupts */ - tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; - } - } - - if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT) - { - /* Disable ADDR, NACK and STOP interrupts */ - tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; - } - - if (InterruptRequest == I2C_XFER_ERROR_IT) - { - /* Enable ERR and NACK interrupts */ - tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI; - } - - if (InterruptRequest == I2C_XFER_CPLT_IT) - { - /* Enable STOP interrupts */ - tmpisr |= I2C_IT_STOPI; - } - - if (InterruptRequest == I2C_XFER_RELOAD_IT) - { - /* Enable TC interrupts */ - tmpisr |= I2C_IT_TCI; - } - - /* Disable interrupts only at the end */ - /* to avoid a breaking situation like at "t" time */ - /* all disable interrupts request are not done */ - __HAL_I2C_DISABLE_IT(hi2c, tmpisr); -} - -/** - * @brief Convert I2Cx OTHER_xxx XferOptions to functional XferOptions. - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c) -{ - /* if user set XferOptions to I2C_OTHER_FRAME */ - /* it request implicitly to generate a restart condition */ - /* set XferOptions to I2C_FIRST_FRAME */ - if (hi2c->XferOptions == I2C_OTHER_FRAME) - { - hi2c->XferOptions = I2C_FIRST_FRAME; - } - /* else if user set XferOptions to I2C_OTHER_AND_LAST_FRAME */ - /* it request implicitly to generate a restart condition */ - /* then generate a stop condition at the end of transfer */ - /* set XferOptions to I2C_FIRST_AND_LAST_FRAME */ - else if (hi2c->XferOptions == I2C_OTHER_AND_LAST_FRAME) - { - hi2c->XferOptions = I2C_FIRST_AND_LAST_FRAME; - } - else - { - /* Nothing to do */ - } -} - -/** - * @} - */ - -#endif /* HAL_I2C_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_i2c.c + * @author MCD Application Team + * @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 State and Errors functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 implementing 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 channel + (+++) Enable the DMAx interface clock using + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx or Rx channel + (+++) Associate the initialized 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 channel + + (#) Configure the Communication Clock Timing, Own Address1, Master Addressing mode, Dual Addressing mode, + Own Address2, Own Address2 Mask, General call and Nostretch mode in the hi2c Init structure. + + (#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware + (GPIO, CLOCK, NVIC...etc) by calling the customized 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 operation modes 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 users can + add their 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 users can + add their 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 users can + add their 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 users can + add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can + add their own code by customization of function pointer HAL_I2C_ErrorCallback() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() + (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. + This action will inform Master to generate a Stop condition to discard the communication. + + + *** Interrupt mode or DMA mode IO sequential operation *** + ========================================================== + [..] + (@) These interfaces allow to manage a sequential transfer with a repeated start condition + when a direction change during transfer + [..] + (+) A specific option field manage the different steps of a sequential transfer + (+) Option field values are defined through I2C_XFEROPTIONS and are listed below: + (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functional is same as associated interfaces in + no sequential mode + (++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address + and data to transfer without a final stop condition + (++) I2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with + start condition, address and data to transfer without a final stop condition, + an then permit a call the same master sequential interface several times + (like HAL_I2C_Master_Seq_Transmit_IT() then HAL_I2C_Master_Seq_Transmit_IT() + or HAL_I2C_Master_Seq_Transmit_DMA() then HAL_I2C_Master_Seq_Transmit_DMA()) + (++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address + and with new data to transfer if the direction change or manage only the new data to + transfer + if no direction change and without a final stop condition in both cases + (++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address + and with new data to transfer if the direction change or manage only the new data to + transfer + if no direction change and with a final stop condition in both cases + (++) I2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition + after several call of the same master sequential interface several times + (link with option I2C_FIRST_AND_NEXT_FRAME). + Usage can, transfer several bytes one by one using + HAL_I2C_Master_Seq_Transmit_IT + or HAL_I2C_Master_Seq_Receive_IT + or HAL_I2C_Master_Seq_Transmit_DMA + or HAL_I2C_Master_Seq_Receive_DMA + with option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME. + Then usage of this option I2C_LAST_FRAME_NO_STOP at the last Transmit or + Receive sequence permit to call the opposite interface Receive or Transmit + without stopping the communication and so generate a restart condition. + (++) I2C_OTHER_FRAME: Sequential usage (Master only), this option allow to manage a restart condition after + each call of the same master sequential + interface. + Usage can, transfer several bytes one by one with a restart with slave address between + each bytes using + HAL_I2C_Master_Seq_Transmit_IT + or HAL_I2C_Master_Seq_Receive_IT + or HAL_I2C_Master_Seq_Transmit_DMA + or HAL_I2C_Master_Seq_Receive_DMA + with option I2C_FIRST_FRAME then I2C_OTHER_FRAME. + Then usage of this option I2C_OTHER_AND_LAST_FRAME at the last frame to help automatic + generation of STOP condition. + + (+) Different sequential I2C interfaces are listed below: + (++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using + HAL_I2C_Master_Seq_Transmit_IT() or using HAL_I2C_Master_Seq_Transmit_DMA() + (+++) At transmission end of current frame transfer, HAL_I2C_MasterTxCpltCallback() is executed and + users can add their own code by customization of function pointer HAL_I2C_MasterTxCpltCallback() + (++) Sequential receive in master I2C mode an amount of data in non-blocking mode using + HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA() + (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() + (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() + (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() + HAL_I2C_DisableListen_IT() + (+++) When address slave I2C match, HAL_I2C_AddrCallback() is executed and users can + add their own code to check the Address Match Code and the transmission direction request by master + (Write/Read). + (+++) At Listen mode end HAL_I2C_ListenCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_ListenCpltCallback() + (++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using + HAL_I2C_Slave_Seq_Transmit_IT() or using HAL_I2C_Slave_Seq_Transmit_DMA() + (+++) At transmission end of current frame transfer, HAL_I2C_SlaveTxCpltCallback() is executed and + users can add their own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback() + (++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using + HAL_I2C_Slave_Seq_Receive_IT() or using HAL_I2C_Slave_Seq_Receive_DMA() + (+++) At reception end of current frame transfer, HAL_I2C_SlaveRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() + (++) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can + add their own code by customization of function pointer HAL_I2C_ErrorCallback() + (++) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. + This action will inform Master to generate a Stop condition to discard the communication. + + *** Interrupt mode IO MEM operation *** + ======================================= + [..] + (+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using + HAL_I2C_Mem_Write_IT() + (+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback() + (+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using + HAL_I2C_Mem_Read_IT() + (+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback() + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can + add their 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 users can + add their 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 users can + add their 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 users can + add their 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 users can + add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can + add their own code by customization of function pointer HAL_I2C_ErrorCallback() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() + (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. + This action will inform Master to generate a Stop condition to discard the communication. + + *** DMA mode IO MEM operation *** + ================================= + [..] + (+) Write an amount of data in non-blocking mode with DMA to a specific memory address using + HAL_I2C_Mem_Write_DMA() + (+) At Memory end of write transfer, HAL_I2C_MemTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_MemTxCpltCallback() + (+) Read an amount of data in non-blocking mode with DMA from a specific memory address using + HAL_I2C_Mem_Read_DMA() + (+) At Memory end of read transfer, HAL_I2C_MemRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I2C_MemRxCpltCallback() + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can + add their 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_GENERATE_NACK: Generate a Non-Acknowledge I2C peripheral in Slave mode + (+) __HAL_I2C_GET_FLAG: Check whether the specified I2C flag is set or not + (+) __HAL_I2C_CLEAR_FLAG: Clear the specified I2C pending flag + (+) __HAL_I2C_ENABLE_IT: Enable the specified I2C interrupt + (+) __HAL_I2C_DISABLE_IT: Disable the specified I2C interrupt + + *** Callback registration *** + ============================================= + [..] + The compilation flag USE_HAL_I2C_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_I2C_RegisterCallback() or HAL_I2C_RegisterAddrCallback() + to register an interrupt callback. + [..] + Function HAL_I2C_RegisterCallback() allows to register following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) MemTxCpltCallback : callback for Memory transmission end of transfer. + (+) MemRxCpltCallback : callback for Memory reception end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + For specific callback AddrCallback use dedicated register callbacks : HAL_I2C_RegisterAddrCallback(). + [..] + Use function HAL_I2C_UnRegisterCallback to reset a callback to the default + weak function. + HAL_I2C_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) MemTxCpltCallback : callback for Memory transmission end of transfer. + (+) MemRxCpltCallback : callback for Memory reception end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + [..] + For callback AddrCallback use dedicated register callbacks : HAL_I2C_UnRegisterAddrCallback(). + [..] + By default, after the HAL_I2C_Init() and when the state is HAL_I2C_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_I2C_MasterTxCpltCallback(), HAL_I2C_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the HAL_I2C_Init()/ HAL_I2C_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the HAL_I2C_Init()/ HAL_I2C_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using HAL_I2C_RegisterCallback() before calling HAL_I2C_DeInit() + or HAL_I2C_Init() function. + [..] + When the compilation flag USE_HAL_I2C_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + [..] + (@) You can refer to the I2C HAL driver header file for more useful macros + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup I2C I2C + * @brief I2C HAL module driver + * @{ + */ + +#ifdef HAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup I2C_Private_Define I2C Private Define + * @{ + */ +#define TIMING_CLEAR_MASK (0xF0FFFFFFU) /*!< I2C TIMING clear register Mask */ +#define I2C_TIMEOUT_ADDR (10000U) /*!< 10 s */ +#define I2C_TIMEOUT_BUSY (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_DIR (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_RXNE (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_STOPF (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_TC (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_TCR (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_TXIS (25U) /*!< 25 ms */ +#define I2C_TIMEOUT_FLAG (25U) /*!< 25 ms */ + +#define MAX_NBYTE_SIZE 255U +#define SLAVE_ADDR_SHIFT 7U +#define SLAVE_ADDR_MSK 0x06U + +/* Private define for @ref PreviousState usage */ +#define I2C_STATE_MSK ((uint32_t)((uint32_t)((uint32_t)HAL_I2C_STATE_BUSY_TX | \ + (uint32_t)HAL_I2C_STATE_BUSY_RX) & \ + (uint32_t)(~((uint32_t)HAL_I2C_STATE_READY)))) +/*!< Mask State define, keep only RX and TX bits */ +#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE)) +/*!< Default Value */ +#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \ + (uint32_t)HAL_I2C_MODE_MASTER)) +/*!< Master Busy TX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \ + (uint32_t)HAL_I2C_MODE_MASTER)) +/*!< Master Busy RX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \ + (uint32_t)HAL_I2C_MODE_SLAVE)) +/*!< Slave Busy TX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \ + (uint32_t)HAL_I2C_MODE_SLAVE)) +/*!< Slave Busy RX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_MEM_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | \ + (uint32_t)HAL_I2C_MODE_MEM)) +/*!< Memory Busy TX, combinaison of State LSB and Mode enum */ +#define I2C_STATE_MEM_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | \ + (uint32_t)HAL_I2C_MODE_MEM)) +/*!< Memory Busy RX, combinaison of State LSB and Mode enum */ + + +/* Private define to centralize the enable/disable of Interrupts */ +#define I2C_XFER_TX_IT (uint16_t)(0x0001U) /*!< Bit field can be combinated with + @ref I2C_XFER_LISTEN_IT */ +#define I2C_XFER_RX_IT (uint16_t)(0x0002U) /*!< Bit field can be combinated with + @ref I2C_XFER_LISTEN_IT */ +#define I2C_XFER_LISTEN_IT (uint16_t)(0x8000U) /*!< Bit field can be combinated with @ref I2C_XFER_TX_IT + and @ref I2C_XFER_RX_IT */ + +#define I2C_XFER_ERROR_IT (uint16_t)(0x0010U) /*!< Bit definition to manage addition of global Error + and NACK treatment */ +#define I2C_XFER_CPLT_IT (uint16_t)(0x0020U) /*!< Bit definition to manage only STOP evenement */ +#define I2C_XFER_RELOAD_IT (uint16_t)(0x0040U) /*!< Bit definition to manage only Reload of NBYTE */ + +/* Private define Sequential Transfer Options default/reset value */ +#define I2C_NO_OPTION_FRAME (0xFFFF0000U) +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup I2C_Private_Macro + * @{ + */ +#if defined(HAL_DMA_MODULE_ENABLED) +/* Macro to get remaining data to transfer on DMA side */ +#define I2C_GET_DMA_REMAIN_DATA(__HANDLE__) (__HAL_DMA_GET_COUNTER(__HANDLE__) + HAL_DMAEx_GetFifoLevel(__HANDLE__)) +#endif /* HAL_DMA_MODULE_ENABLED */ +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/** @defgroup I2C_Private_Functions I2C Private Functions + * @{ + */ +#if defined(HAL_DMA_MODULE_ENABLED) +/* Private functions to handle DMA transfer */ +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_DMAError(DMA_HandleTypeDef *hdma); +static void I2C_DMAAbort(DMA_HandleTypeDef *hdma); + +#endif /* HAL_DMA_MODULE_ENABLED */ + +/* Private functions to handle IT transfer */ +static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); +static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c); +static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c); +static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); +static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); +static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags); +static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode); + +/* Private functions to handle IT transfer */ +static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, + uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, + uint32_t Tickstart); +static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, + uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, + uint32_t Tickstart); + +/* Private functions for I2C transfer IRQ handler */ +static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources); +static HAL_StatusTypeDef I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources); +static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources); +#if defined(HAL_DMA_MODULE_ENABLED) +static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources); +static HAL_StatusTypeDef I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources); +static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources); +#endif /* HAL_DMA_MODULE_ENABLED */ + +/* Private functions to handle flags during polling transfer */ +static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, + uint32_t Timeout, uint32_t Tickstart); +static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart); +static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart); +static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart); +static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart); + +/* Private functions to centralize the enable/disable of Interrupts */ +static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest); +static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest); + +/* Private function to treat different error callback */ +static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c); + +/* Private function to flush TXDR register */ +static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c); + +/* Private function to handle start, restart or stop a transfer */ +static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, + uint32_t Request); + +/* Private function to Convert Specific options */ +static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup I2C_Exported_Functions I2C Exported Functions + * @{ + */ + +/** @defgroup I2C_Exported_Functions_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 + deinitialize 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: + (++) Clock Timing + (++) Own Address 1 + (++) Addressing mode (Master, Slave) + (++) Dual Addressing mode + (++) Own Address 2 + (++) Own Address 2 Mask + (++) General call mode + (++) Nostretch mode + + (+) Call the function HAL_I2C_DeInit() to restore the default configuration + of the selected I2Cx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the I2C according to the specified parameters + * in the I2C_InitTypeDef and initialize 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) +{ + /* 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_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_OWN_ADDRESS2_MASK(hi2c->Init.OwnAddress2Masks)); + 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) + { + /* Allocate lock resource and initialize it */ + hi2c->Lock = HAL_UNLOCKED; + +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + /* Init the I2C Callback settings */ + hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ + hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ + hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ + hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ + + if (hi2c->MspInitCallback == NULL) + { + hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + hi2c->MspInitCallback(hi2c); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I2C_MspInit(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /*---------------------------- I2Cx TIMINGR Configuration ------------------*/ + /* Configure I2Cx: Frequency range */ + hi2c->Instance->TIMINGR = hi2c->Init.Timing & TIMING_CLEAR_MASK; + + /*---------------------------- I2Cx OAR1 Configuration ---------------------*/ + /* Disable Own Address1 before set the Own Address1 configuration */ + hi2c->Instance->OAR1 &= ~I2C_OAR1_OA1EN; + + /* Configure I2Cx: Own Address1 and ack own address1 mode */ + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) + { + hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | hi2c->Init.OwnAddress1); + } + else /* I2C_ADDRESSINGMODE_10BIT */ + { + hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hi2c->Init.OwnAddress1); + } + + /*---------------------------- I2Cx CR2 Configuration ----------------------*/ + /* Configure I2Cx: Addressing Master mode */ + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + SET_BIT(hi2c->Instance->CR2, I2C_CR2_ADD10); + } + else + { + /* Clear the I2C ADD10 bit */ + CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_ADD10); + } + /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */ + hi2c->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); + + /*---------------------------- I2Cx OAR2 Configuration ---------------------*/ + /* Disable Own Address2 before set the Own Address2 configuration */ + hi2c->Instance->OAR2 &= ~I2C_DUALADDRESS_ENABLE; + + /* Configure I2Cx: Dual mode and Own Address2 */ + hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2 | \ + (hi2c->Init.OwnAddress2Masks << 8)); + + /*---------------------------- I2Cx CR1 Configuration ----------------------*/ + /* Configure I2Cx: Generalcall and NoStretch mode */ + hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode); + + /* Enable the selected I2C peripheral */ + __HAL_I2C_ENABLE(hi2c); + + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->Mode = HAL_I2C_MODE_NONE; + + return HAL_OK; +} + +/** + * @brief DeInitialize 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); + +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + if (hi2c->MspDeInitCallback == NULL) + { + hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hi2c->MspDeInitCallback(hi2c); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_I2C_MspDeInit(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + hi2c->State = HAL_I2C_STATE_RESET; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Release Lock */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Initialize the I2C MSP. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 DeInitialize the I2C MSP. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User I2C Callback + * To be used instead of the weak predefined callback + * @note The HAL_I2C_RegisterCallback() may be called before HAL_I2C_Init() in HAL_I2C_STATE_RESET + * to register callbacks for HAL_I2C_MSPINIT_CB_ID and HAL_I2C_MSPDEINIT_CB_ID. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID + * @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID + * @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID + * @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID + * @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID, + pI2C_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (HAL_I2C_STATE_READY == hi2c->State) + { + switch (CallbackID) + { + case HAL_I2C_MASTER_TX_COMPLETE_CB_ID : + hi2c->MasterTxCpltCallback = pCallback; + break; + + case HAL_I2C_MASTER_RX_COMPLETE_CB_ID : + hi2c->MasterRxCpltCallback = pCallback; + break; + + case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID : + hi2c->SlaveTxCpltCallback = pCallback; + break; + + case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID : + hi2c->SlaveRxCpltCallback = pCallback; + break; + + case HAL_I2C_LISTEN_COMPLETE_CB_ID : + hi2c->ListenCpltCallback = pCallback; + break; + + case HAL_I2C_MEM_TX_COMPLETE_CB_ID : + hi2c->MemTxCpltCallback = pCallback; + break; + + case HAL_I2C_MEM_RX_COMPLETE_CB_ID : + hi2c->MemRxCpltCallback = pCallback; + break; + + case HAL_I2C_ERROR_CB_ID : + hi2c->ErrorCallback = pCallback; + break; + + case HAL_I2C_ABORT_CB_ID : + hi2c->AbortCpltCallback = pCallback; + break; + + case HAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = pCallback; + break; + + case HAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_I2C_STATE_RESET == hi2c->State) + { + switch (CallbackID) + { + case HAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = pCallback; + break; + + case HAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an I2C Callback + * I2C callback is redirected to the weak predefined callback + * @note The HAL_I2C_UnRegisterCallback() may be called before HAL_I2C_Init() in HAL_I2C_STATE_RESET + * to un-register callbacks for HAL_I2C_MSPINIT_CB_ID and HAL_I2C_MSPDEINIT_CB_ID. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * This parameter can be one of the following values: + * @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID + * @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID + * @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID + * @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID + * @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_I2C_STATE_READY == hi2c->State) + { + switch (CallbackID) + { + case HAL_I2C_MASTER_TX_COMPLETE_CB_ID : + hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + break; + + case HAL_I2C_MASTER_RX_COMPLETE_CB_ID : + hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + break; + + case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID : + hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + break; + + case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID : + hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + break; + + case HAL_I2C_LISTEN_COMPLETE_CB_ID : + hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + break; + + case HAL_I2C_MEM_TX_COMPLETE_CB_ID : + hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ + break; + + case HAL_I2C_MEM_RX_COMPLETE_CB_ID : + hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ + break; + + case HAL_I2C_ERROR_CB_ID : + hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_I2C_ABORT_CB_ID : + hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_I2C_STATE_RESET == hi2c->State) + { + switch (CallbackID) + { + case HAL_I2C_MSPINIT_CB_ID : + hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_I2C_MSPDEINIT_CB_ID : + hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register the Slave Address Match I2C Callback + * To be used instead of the weak HAL_I2C_AddrCallback() predefined callback + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pCallback pointer to the Address Match Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (HAL_I2C_STATE_READY == hi2c->State) + { + hi2c->AddrCallback = pCallback; + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Slave Address Match I2C Callback + * Info Ready I2C Callback is redirected to the weak HAL_I2C_AddrCallback() predefined callback + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_I2C_STATE_READY == hi2c->State) + { + hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ + } + else + { + /* Update the error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup I2C_Exported_Functions_Group2 Input and Output 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 are two modes 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() + (++) HAL_I2C_Master_Seq_Transmit_IT() + (++) HAL_I2C_Master_Seq_Receive_IT() + (++) HAL_I2C_Slave_Seq_Transmit_IT() + (++) HAL_I2C_Slave_Seq_Receive_IT() + (++) HAL_I2C_EnableListen_IT() + (++) HAL_I2C_DisableListen_IT() + (++) HAL_I2C_Master_Abort_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() + (++) HAL_I2C_Master_Seq_Transmit_DMA() + (++) HAL_I2C_Master_Seq_Receive_DMA() + (++) HAL_I2C_Slave_Seq_Transmit_DMA() + (++) HAL_I2C_Slave_Seq_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) HAL_I2C_MasterTxCpltCallback() + (++) HAL_I2C_MasterRxCpltCallback() + (++) HAL_I2C_SlaveTxCpltCallback() + (++) HAL_I2C_SlaveRxCpltCallback() + (++) HAL_I2C_MemTxCpltCallback() + (++) HAL_I2C_MemRxCpltCallback() + (++) HAL_I2C_AddrCallback() + (++) HAL_I2C_ListenCpltCallback() + (++) HAL_I2C_ErrorCallback() + (++) HAL_I2C_AbortCpltCallback() + +@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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t tickstart; + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferISR = NULL; + + /* Send Slave Address */ + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, + I2C_GENERATE_START_WRITE); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_WRITE); + } + + while (hi2c->XferCount > 0U) + { + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + + if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) + { + /* Wait until TCR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, + I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_NO_STARTSTOP); + } + } + } + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* 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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t tickstart; + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferISR = NULL; + + /* Send Slave Address */ + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, + I2C_GENERATE_START_READ); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_READ); + } + + while (hi2c->XferCount > 0U) + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + + if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) + { + /* Wait until TCR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, + I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_NO_STARTSTOP); + } + } + } + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* 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) +{ + uint32_t tickstart; + uint16_t tmpXferCount; + HAL_StatusTypeDef error; + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferISR = NULL; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Preload TX data if no stretch enable */ + if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) + { + /* Preload TX register */ + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + } + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + return HAL_ERROR; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + + /* 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, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + return HAL_ERROR; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + + /* Wait until DIR flag is set Transmitter mode */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + return HAL_ERROR; + } + + while (hi2c->XferCount > 0U) + { + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + } + + /* Wait until AF flag is set */ + error = I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart); + + if (error != HAL_OK) + { + /* Check that I2C transfer finished */ + /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ + /* Mean XferCount == 0 */ + + tmpXferCount = hi2c->XferCount; + if ((hi2c->ErrorCode == HAL_I2C_ERROR_AF) && (tmpXferCount == 0U)) + { + /* Reset ErrorCode to NONE */ + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + } + else + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + } + else + { + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Clear AF flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Wait until STOP flag is set */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + return HAL_ERROR; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* 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) +{ + uint32_t tickstart; + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferISR = NULL; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + + /* Wait until DIR flag is reset Receiver mode */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + + while (hi2c->XferCount > 0U) + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Store Last receive data if any */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + } + + return HAL_ERROR; + } + + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + } + + /* Wait until STOP flag is set */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_ERROR; + } + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t xfermode; + + 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_TX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Master_ISR_IT; + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = I2C_AUTOEND_MODE; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t xfermode; + + 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_RX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Master_ISR_IT; + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = I2C_AUTOEND_MODE; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ); + + /* 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 ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in non-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) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Slave_ISR_IT; + + /* Preload TX data if no stretch enable */ + if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) + { + /* Preload TX register */ + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + } + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in non-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) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Slave_ISR_IT; + + /* 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 ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Transmit in master mode an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t xfermode; + HAL_StatusTypeDef dmaxferstatus; + + 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_TX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Master_ISR_DMA; + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = I2C_AUTOEND_MODE; + } + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; + + /* Set DMA destination address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->TXDR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Send Slave Address */ + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_WRITE); + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* 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 ERR and NACK interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + /* Update Transfer ISR function pointer */ + hi2c->XferISR = I2C_Master_ISR_IT; + + /* Send Slave Address */ + /* Set NBYTES to write and generate START condition */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t xfermode; + HAL_StatusTypeDef dmaxferstatus; + + 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_RX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Master_ISR_DMA; + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = I2C_AUTOEND_MODE; + } + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->RXDR; + + /* Set DMA destination address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Send Slave Address */ + /* Set NBYTES to read and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, I2C_GENERATE_START_READ); + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* 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 ERR and NACK interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + /* Update Transfer ISR function pointer */ + hi2c->XferISR = I2C_Master_ISR_IT; + + /* Send Slave Address */ + /* Set NBYTES to read and generate START condition */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_READ); + + /* 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 ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in non-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) +{ + HAL_StatusTypeDef dmaxferstatus; + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Slave_ISR_DMA; + + /* Preload TX data if no stretch enable */ + if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) + { + /* Preload TX register */ + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + } + + if (hi2c->XferCount != 0U) + { + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr; + + /* Set DMA destination address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->TXDR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, + (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* 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 ERR, STOP, NACK, ADDR interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* 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 ERR, STOP, NACK, ADDR interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in non-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) +{ + HAL_StatusTypeDef dmaxferstatus; + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Slave_ISR_DMA; + + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->RXDR; + + /* Set DMA destination address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* 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 ERR, STOP, NACK, ADDR interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_MEM; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferISR = NULL; + + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + do + { + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + + if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) + { + /* Wait until TCR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, + I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_NO_STARTSTOP); + } + } + + } while (hi2c->XferCount > 0U); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* 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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_MEM; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferISR = NULL; + + /* Send Slave Address and Memory Address */ + if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, + I2C_GENERATE_START_READ); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_READ); + } + + do + { + /* Wait until RXNE flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + + if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) + { + /* Wait until TCR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t) hi2c->XferSize, I2C_RELOAD_MODE, + I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_NO_STARTSTOP); + } + } + } while (hi2c->XferCount > 0U); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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 == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + 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->Mode = HAL_I2C_MODE_MEM; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->XferSize = 0U; + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Mem_ISR_IT; + hi2c->Devaddress = DevAddress; + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Prefetch Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + + /* Reset Memaddress content */ + hi2c->Memaddress = 0xFFFFFFFFU; + } + /* If Memory address size is 16Bit */ + else + { + /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ + hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); + + /* Prepare Memaddress buffer for LSB part */ + hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); + } + /* Send Slave Address and Memory Address */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Read an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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 == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + 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->Mode = HAL_I2C_MODE_MEM; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Mem_ISR_IT; + hi2c->Devaddress = DevAddress; + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Prefetch Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + + /* Reset Memaddress content */ + hi2c->Memaddress = 0xFFFFFFFFU; + } + /* If Memory address size is 16Bit */ + else + { + /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ + hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); + + /* Prepare Memaddress buffer for LSB part */ + hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); + } + /* Send Slave Address and Memory Address */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Write an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + HAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + 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->Mode = HAL_I2C_MODE_MEM; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Mem_ISR_DMA; + hi2c->Devaddress = DevAddress; + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Prefetch Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + + /* Reset Memaddress content */ + hi2c->Memaddress = 0xFFFFFFFFU; + } + /* If Memory address size is 16Bit */ + else + { + /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ + hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); + + /* Prepare Memaddress buffer for LSB part */ + hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); + } + + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; + + /* Set DMA destination address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->TXDR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Send Slave Address and Memory Address */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Reads an amount of data in non-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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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) +{ + HAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + 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->Mode = HAL_I2C_MODE_MEM; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferISR = I2C_Mem_ISR_DMA; + hi2c->Devaddress = DevAddress; + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Prefetch Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + + /* Reset Memaddress content */ + hi2c->Memaddress = 0xFFFFFFFFU; + } + /* If Memory address size is 16Bit */ + else + { + /* Prefetch Memory Address (MSB part, LSB will be manage through interrupt) */ + hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); + + /* Prepare Memaddress buffer for LSB part */ + hi2c->Memaddress = I2C_MEM_ADD_LSB(MemAddress); + } + + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->RXDR; + + /* Set DMA destination address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Send Slave Address and Memory Address */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @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 tickstart; + + __IO uint32_t I2C_Trials = 0UL; + + FlagStatus tmp1; + FlagStatus tmp2; + + 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->CR2 = I2C_GENERATE_START(hi2c->Init.AddressingMode, DevAddress); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set or a NACK flag is set*/ + tickstart = HAL_GetTick(); + + tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF); + tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); + + while ((tmp1 == RESET) && (tmp2 == RESET)) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + + tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF); + tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); + } + + /* Check if the NACKF flag has not been set */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET) + { + /* Wait until STOPF flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Device is ready */ + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + /* Wait until STOPF flag is reset */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Clear STOP Flag, auto generated with autoend*/ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + + /* Increment Trials */ + I2C_Trials++; + } while (I2C_Trials < Trials); + + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with Interrupt. + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, + uint16_t Size, uint32_t XferOptions) +{ + uint32_t xfermode; + uint32_t xferrequest = I2C_GENERATE_START_WRITE; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Master_ISR_IT; + + /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = hi2c->XferOptions; + } + + /* If transfer direction not change and there is no request to start another frame, + do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \ + (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) + { + xferrequest = I2C_NO_STARTSTOP; + } + else + { + /* Convert OTHER_xxx XferOptions if any */ + I2C_ConvertOtherXferOptions(hi2c); + + /* Update xfermode accordingly if no reload is necessary */ + if (hi2c->XferCount <= MAX_NBYTE_SIZE) + { + xfermode = hi2c->XferOptions; + } + } + + /* Send Slave Address and set NBYTES to write */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with DMA. + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, + uint16_t Size, uint32_t XferOptions) +{ + uint32_t xfermode; + uint32_t xferrequest = I2C_GENERATE_START_WRITE; + HAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_TX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Master_ISR_DMA; + + /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = hi2c->XferOptions; + } + + /* If transfer direction not change and there is no request to start another frame, + do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) && \ + (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) + { + xferrequest = I2C_NO_STARTSTOP; + } + else + { + /* Convert OTHER_xxx XferOptions if any */ + I2C_ConvertOtherXferOptions(hi2c); + + /* Update xfermode accordingly if no reload is necessary */ + if (hi2c->XferCount <= MAX_NBYTE_SIZE) + { + xfermode = hi2c->XferOptions; + } + } + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; + + /* Set DMA destination address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->TXDR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Send Slave Address and set NBYTES to write */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* 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 ERR and NACK interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + /* Update Transfer ISR function pointer */ + hi2c->XferISR = I2C_Master_ISR_IT; + + /* Send Slave Address */ + /* Set NBYTES to write and generate START condition */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_WRITE); + + /* 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 ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with Interrupt + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, + uint16_t Size, uint32_t XferOptions) +{ + uint32_t xfermode; + uint32_t xferrequest = I2C_GENERATE_START_READ; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Master_ISR_IT; + + /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = hi2c->XferOptions; + } + + /* If transfer direction not change and there is no request to start another frame, + do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \ + (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) + { + xferrequest = I2C_NO_STARTSTOP; + } + else + { + /* Convert OTHER_xxx XferOptions if any */ + I2C_ConvertOtherXferOptions(hi2c); + + /* Update xfermode accordingly if no reload is necessary */ + if (hi2c->XferCount <= MAX_NBYTE_SIZE) + { + xfermode = hi2c->XferOptions; + } + } + + /* Send Slave Address and set NBYTES to read */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); + + /* 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 */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with DMA + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, + uint16_t Size, uint32_t XferOptions) +{ + uint32_t xfermode; + uint32_t xferrequest = I2C_GENERATE_START_READ; + HAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY_RX; + hi2c->Mode = HAL_I2C_MODE_MASTER; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Master_ISR_DMA; + + /* If hi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + xfermode = hi2c->XferOptions; + } + + /* If transfer direction not change and there is no request to start another frame, + do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) && \ + (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 0)) + { + xferrequest = I2C_NO_STARTSTOP; + } + else + { + /* Convert OTHER_xxx XferOptions if any */ + I2C_ConvertOtherXferOptions(hi2c); + + /* Update xfermode accordingly if no reload is necessary */ + if (hi2c->XferCount <= MAX_NBYTE_SIZE) + { + xfermode = hi2c->XferOptions; + } + } + + if (hi2c->XferSize > 0U) + { + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->RXDR; + + /* Set DMA destination address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); + } + else + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Send Slave Address and set NBYTES to read */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, xfermode, xferrequest); + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* 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 ERR and NACK interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + /* Update Transfer ISR function pointer */ + hi2c->XferISR = I2C_Master_ISR_IT; + + /* Send Slave Address */ + /* Set NBYTES to read and generate START condition */ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)hi2c->XferSize, I2C_AUTOEND_MODE, + I2C_GENERATE_START_READ); + + /* 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 ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | + I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with Interrupt + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, + uint32_t XferOptions) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + FlagStatus tmp; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT); + + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ + /* and then toggle the HAL slave RX state to TX state */ + if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) + { + /* Disable associated Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort DMA Xfer if any */ + if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) + { + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + } + + hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Slave_ISR_IT; + + tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); + if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE) && (tmp != RESET)) + { + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the Master */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + + /* 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 */ + /* REnable ADDR interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_TX_IT | I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Sequential transmit in slave/device I2C mode an amount of data in non-blocking mode with DMA + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, + uint32_t XferOptions) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + FlagStatus tmp; + HAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT); + + /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ + /* and then toggle the HAL slave RX state to TX state */ + if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) + { + /* Disable associated Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); + + if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) + { + /* Abort DMA Xfer if any */ + if (hi2c->hdmarx != NULL) + { + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } + } + else if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) + { + if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) + { + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Abort DMA Xfer if any */ + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + } + } + else + { + /* Nothing to do */ + } + + hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Slave_ISR_DMA; + + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmatx->XferHalfCpltCallback = NULL; + hi2c->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; + + /* Set DMA destination address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->TXDR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* Reset XferSize */ + hi2c->XferSize = 0; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); + if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_RECEIVE) && (tmp != RESET)) + { + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the Master */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* 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 ERR, STOP, NACK, ADDR interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with Interrupt + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, + uint32_t XferOptions) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + FlagStatus tmp; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT); + + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ + /* and then toggle the HAL slave TX state to RX state */ + if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) + { + /* Disable associated Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + +#if defined(HAL_DMA_MODULE_ENABLED) + if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) + { + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Abort DMA Xfer if any */ + if (hi2c->hdmatx != NULL) + { + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + } + + hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Slave_ISR_IT; + + tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); + if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT) && (tmp != RESET)) + { + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the Master */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + + /* 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 */ + /* REnable ADDR interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Sequential receive in slave/device I2C mode an amount of data in non-blocking mode with DMA + * @note This interface allow to manage repeated start condition when a direction change during transfer + * @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 XferOptions Options of Transfer, value of @ref I2C_XFEROPTIONS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, + uint32_t XferOptions) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + FlagStatus tmp; + HAL_StatusTypeDef dmaxferstatus; + + /* Check the parameters */ + assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0U)) + { + hi2c->ErrorCode = HAL_I2C_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT); + + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ + /* and then toggle the HAL slave TX state to RX state */ + if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) + { + /* Disable associated Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + + if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) + { + /* Abort DMA Xfer if any */ + if (hi2c->hdmatx != NULL) + { + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + } + } + else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) + { + if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) + { + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Abort DMA Xfer if any */ + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + } + } + else + { + /* Nothing to do */ + } + + hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; + hi2c->Mode = HAL_I2C_MODE_SLAVE; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = hi2c->XferCount; + hi2c->XferOptions = XferOptions; + hi2c->XferISR = I2C_Slave_ISR_DMA; + + if (hi2c->hdmarx != NULL) + { + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi2c->hdmarx->XferHalfCpltCallback = NULL; + hi2c->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA channel */ + if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] \ + = (uint32_t)&hi2c->Instance->RXDR; + + /* Set DMA destination address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, + hi2c->XferSize); + } + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA_PARAM; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* Reset XferSize */ + hi2c->XferSize = 0; + } + else + { + /* Update I2C state */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Update I2C error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + tmp = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); + if ((I2C_GET_DIR(hi2c) == I2C_DIRECTION_TRANSMIT) && (tmp != RESET)) + { + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the Master */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Enable the Address listen mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->State == HAL_I2C_STATE_READY) + { + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->XferISR = I2C_Slave_ISR_IT; + + /* Enable the Address Match interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Disable the Address listen mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) +{ + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + uint32_t tmp; + + /* Disable Address listen mode only if a transfer is not ongoing */ + if (hi2c->State == HAL_I2C_STATE_LISTEN) + { + tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK; + hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode); + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + hi2c->XferISR = NULL; + + /* Disable the Address Match interrupt */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) +{ + HAL_I2C_ModeTypeDef tmp_mode = hi2c->Mode; + + if ((tmp_mode == HAL_I2C_MODE_MASTER) || (tmp_mode == HAL_I2C_MODE_MEM)) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + /* Disable Interrupts and Store Previous state */ + if (hi2c->State == HAL_I2C_STATE_BUSY_TX) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; + } + else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } + else + { + /* Do nothing */ + } + + /* Set State at HAL_I2C_STATE_ABORT */ + hi2c->State = HAL_I2C_STATE_ABORT; + + /* Set NBYTES to 1 to generate a dummy read on I2C peripheral */ + /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ + I2C_TransferConfig(hi2c, DevAddress, 1, I2C_AUTOEND_MODE, I2C_GENERATE_STOP); + + /* 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 */ + I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); + + return HAL_OK; + } + else + { + /* Wrong usage of abort function */ + /* This function should be used only in case of abort monitored by master device */ + return HAL_ERROR; + } +} + +/** + * @} + */ + +/** @defgroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks + * @{ + */ + +/** + * @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 None + */ +void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Get current IT Flags and IT sources value */ + uint32_t itflags = READ_REG(hi2c->Instance->ISR); + uint32_t itsources = READ_REG(hi2c->Instance->CR1); + + /* I2C events treatment -------------------------------------*/ + if (hi2c->XferISR != NULL) + { + hi2c->XferISR(hi2c, itflags, itsources); + } +} + +/** + * @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 None + */ +void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + uint32_t itflags = READ_REG(hi2c->Instance->ISR); + uint32_t itsources = READ_REG(hi2c->Instance->CR1); + uint32_t tmperror; + + /* I2C Bus error interrupt occurred ------------------------------------*/ + if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_BERR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); + } + + /* I2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_OVR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); + } + + /* I2C Arbitration Loss error interrupt occurred -------------------------------------*/ + if ((I2C_CHECK_FLAG(itflags, I2C_FLAG_ARLO) != RESET) && \ + (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERRI) != RESET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); + } + + /* Store current volatile hi2c->ErrorCode, misra rule */ + tmperror = hi2c->ErrorCode; + + /* Call the Error Callback in case of Error detected */ + if ((tmperror & (HAL_I2C_ERROR_BERR | HAL_I2C_ERROR_OVR | HAL_I2C_ERROR_ARLO)) != HAL_I2C_ERROR_NONE) + { + I2C_ITError(hi2c, tmperror); + } +} + +/** + * @brief Master Tx Transfer completed callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_MasterTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_MasterRxCpltCallback could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_SlaveTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_SlaveRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Address Match callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XFERDIRECTION + * @param AddrMatchCode Address Match Code + * @retval None + */ +__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + UNUSED(TransferDirection); + UNUSED(AddrMatchCode); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_AddrCallback() could be implemented in the user file + */ +} + +/** + * @brief Listen Complete callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_ListenCpltCallback() could be implemented in the user file + */ +} + +/** + * @brief Memory Tx Transfer completed callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_MemTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Memory Rx Transfer completed callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_MemRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief I2C error callback. + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief I2C abort callback. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I2C_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions + * @brief Peripheral State, Mode and Error functions + * +@verbatim + =============================================================================== + ##### Peripheral State, Mode and Error functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the I2C handle state. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL state + */ +HAL_I2C_StateTypeDef HAL_I2C_GetState(const I2C_HandleTypeDef *hi2c) +{ + /* Return I2C handle state */ + return hi2c->State; +} + +/** + * @brief Returns the I2C Master, Slave, Memory or no mode. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for I2C module + * @retval HAL mode + */ +HAL_I2C_ModeTypeDef HAL_I2C_GetMode(const I2C_HandleTypeDef *hi2c) +{ + return hi2c->Mode; +} + +/** + * @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(const I2C_HandleTypeDef *hi2c) +{ + return hi2c->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup I2C_Private_Functions + * @{ + */ + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param ITFlags Interrupt flags to handle. + * @param ITSources Interrupt sources enabled. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_Master_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources) +{ + uint16_t devaddress; + uint32_t tmpITFlags = ITFlags; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set corresponding Error Code */ + /* No need to generate STOP, it is automatically done */ + /* Error callback will be send during stop flag treatment */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET)) + { + /* Remove RXNE flag on temporary variable as read done */ + tmpITFlags &= ~I2C_FLAG_RXNE; + + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) + { + devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD); + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + if (hi2c->XferOptions != I2C_NO_OPTION_FRAME) + { + I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, + hi2c->XferOptions, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, + I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + } + } + else + { + /* Call TxCpltCallback() if no stop mode is set */ + if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) + { + /* Call I2C Master Sequential complete process */ + I2C_ITMasterSeqCplt(hi2c); + } + else + { + /* Wrong size Status regarding TCR flag event */ + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); + } + } + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + if (hi2c->XferCount == 0U) + { + if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) + { + /* Generate a stop condition in case of no transfer option */ + if (hi2c->XferOptions == I2C_NO_OPTION_FRAME) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + } + else + { + /* Call I2C Master Sequential complete process */ + I2C_ITMasterSeqCplt(hi2c); + } + } + } + else + { + /* Wrong size Status regarding TC flag event */ + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); + } + } + else + { + /* Nothing to do */ + } + + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) + { + /* Call I2C Master complete process */ + I2C_ITMasterCplt(hi2c, tmpITFlags); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Memory Mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param ITFlags Interrupt flags to handle. + * @param ITSources Interrupt sources enabled. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_Mem_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources) +{ + uint32_t direction = I2C_GENERATE_START_WRITE; + uint32_t tmpITFlags = ITFlags; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set corresponding Error Code */ + /* No need to generate STOP, it is automatically done */ + /* Error callback will be send during stop flag treatment */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET)) + { + /* Remove RXNE flag on temporary variable as read done */ + tmpITFlags &= ~I2C_FLAG_RXNE; + + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) + { + if (hi2c->Memaddress == 0xFFFFFFFFU) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + } + else + { + /* Write LSB part of Memory Address */ + hi2c->Instance->TXDR = hi2c->Memaddress; + + /* Reset Memaddress content */ + hi2c->Memaddress = 0xFFFFFFFFU; + } + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TCR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + if ((hi2c->XferCount != 0U) && (hi2c->XferSize == 0U)) + { + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + } + else + { + /* Wrong size Status regarding TCR flag event */ + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); + } + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TC) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + /* Disable Interrupt related to address step */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + + /* Enable ERR, TC, STOP, NACK and RXI interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RX_IT); + + if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + direction = I2C_GENERATE_START_READ; + } + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_RELOAD_MODE, direction); + } + else + { + hi2c->XferSize = hi2c->XferCount; + + /* Set NBYTES to write and generate RESTART */ + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_AUTOEND_MODE, direction); + } + } + else + { + /* Nothing to do */ + } + + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) + { + /* Call I2C Master complete process */ + I2C_ITMasterCplt(hi2c, tmpITFlags); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with Interrupt. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param ITFlags Interrupt flags to handle. + * @param ITSources Interrupt sources enabled. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_Slave_ISR_IT(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources) +{ + uint32_t tmpoptions = hi2c->XferOptions; + uint32_t tmpITFlags = ITFlags; + + /* Process locked */ + __HAL_LOCK(hi2c); + + /* Check if STOPF is set */ + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_STOPF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) + { + /* Call I2C Slave complete process */ + I2C_ITSlaveCplt(hi2c, tmpITFlags); + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + { + /* Check that I2C transfer finished */ + /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ + /* Mean XferCount == 0*/ + /* So clear Flag NACKF only */ + if (hi2c->XferCount == 0U) + { + if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) + /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for + Warning[Pa134]: left and right operands are identical */ + { + /* Call I2C Listen complete process */ + I2C_ITListenCplt(hi2c, tmpITFlags); + } + else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Last Byte is Transmitted */ + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + else + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + } + } + else + { + /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, hi2c->ErrorCode); + } + } + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_RXI) != RESET)) + { + if (hi2c->XferCount > 0U) + { + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferSize--; + hi2c->XferCount--; + } + + if ((hi2c->XferCount == 0U) && \ + (tmpoptions != I2C_NO_OPTION_FRAME)) + { + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_ADDR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET)) + { + I2C_ITAddrCplt(hi2c, tmpITFlags); + } + else if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_TXIS) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) + { + /* Write data to TXDR only if XferCount not reach "0" */ + /* A TXIS flag can be set, during STOP treatment */ + /* Check if all Data have already been sent */ + /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ + if (hi2c->XferCount > 0U) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = *hi2c->pBuffPtr; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + hi2c->XferCount--; + hi2c->XferSize--; + } + else + { + if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME)) + { + /* Last Byte is Transmitted */ + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + } + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with DMA. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param ITFlags Interrupt flags to handle. + * @param ITSources Interrupt sources enabled. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_Master_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources) +{ + uint16_t devaddress; + uint32_t xfermode; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set corresponding Error Code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + /* No need to generate STOP, it is automatically done */ + /* But enable STOP interrupt, to treat it */ + /* Error callback will be send during stop flag treatment */ + I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + /* Disable TC interrupt */ + __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_TCI); + + if (hi2c->XferCount != 0U) + { + /* Recover Slave address */ + devaddress = (uint16_t)(hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Prepare the new XferSize to transfer */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + xfermode = I2C_RELOAD_MODE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + if (hi2c->XferOptions != I2C_NO_OPTION_FRAME) + { + xfermode = hi2c->XferOptions; + } + else + { + xfermode = I2C_AUTOEND_MODE; + } + } + + /* Set the new XferSize in Nbytes register */ + I2C_TransferConfig(hi2c, devaddress, (uint8_t)hi2c->XferSize, xfermode, I2C_NO_STARTSTOP); + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* Enable DMA Request */ + if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + else + { + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + else + { + /* Call TxCpltCallback() if no stop mode is set */ + if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) + { + /* Call I2C Master Sequential complete process */ + I2C_ITMasterSeqCplt(hi2c); + } + else + { + /* Wrong size Status regarding TCR flag event */ + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); + } + } + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + if (hi2c->XferCount == 0U) + { + if (I2C_GET_STOP_MODE(hi2c) != I2C_AUTOEND_MODE) + { + /* Generate a stop condition in case of no transfer option */ + if (hi2c->XferOptions == I2C_NO_OPTION_FRAME) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + } + else + { + /* Call I2C Master Sequential complete process */ + I2C_ITMasterSeqCplt(hi2c); + } + } + } + else + { + /* Wrong size Status regarding TC flag event */ + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); + } + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) + { + /* Call I2C Master complete process */ + I2C_ITMasterCplt(hi2c, ITFlags); + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Memory Mode with DMA. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param ITFlags Interrupt flags to handle. + * @param ITSources Interrupt sources enabled. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_Mem_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources) +{ + uint32_t direction = I2C_GENERATE_START_WRITE; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set corresponding Error Code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + /* No need to generate STOP, it is automatically done */ + /* But enable STOP interrupt, to treat it */ + /* Error callback will be send during stop flag treatment */ + I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TXIS) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TXI) != RESET)) + { + /* Write LSB part of Memory Address */ + hi2c->Instance->TXDR = hi2c->Memaddress; + + /* Reset Memaddress content */ + hi2c->Memaddress = 0xFFFFFFFFU; + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TCR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + /* Disable Interrupt related to address step */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + + /* Enable only Error interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); + + if (hi2c->XferCount != 0U) + { + /* Prepare the new XferSize to transfer */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + hi2c->XferSize = hi2c->XferCount; + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* Enable DMA Request */ + if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + else + { + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + else + { + /* Wrong size Status regarding TCR flag event */ + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_SIZE); + } + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_TC) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_TCI) != RESET)) + { + /* Disable Interrupt related to address step */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + + /* Enable only Error and NACK interrupt for data transfer */ + I2C_Enable_IRQ(hi2c, I2C_XFER_ERROR_IT); + + if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + direction = I2C_GENERATE_START_READ; + } + + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + + /* Set NBYTES to write and reload if hi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */ + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_RELOAD_MODE, direction); + } + else + { + hi2c->XferSize = hi2c->XferCount; + + /* Set NBYTES to write and generate RESTART */ + I2C_TransferConfig(hi2c, (uint16_t)hi2c->Devaddress, (uint8_t)hi2c->XferSize, + I2C_AUTOEND_MODE, direction); + } + + /* Update XferCount value */ + hi2c->XferCount -= hi2c->XferSize; + + /* Enable DMA Request */ + if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + else + { + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) + { + /* Call I2C Master complete process */ + I2C_ITMasterCplt(hi2c, ITFlags); + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with DMA. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param ITFlags Interrupt flags to handle. + * @param ITSources Interrupt sources enabled. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_Slave_ISR_DMA(struct __I2C_HandleTypeDef *hi2c, uint32_t ITFlags, + uint32_t ITSources) +{ + uint32_t tmpoptions = hi2c->XferOptions; + uint32_t treatdmanack = 0U; + HAL_I2C_StateTypeDef tmpstate; + + /* Process locked */ + __HAL_LOCK(hi2c); + + /* Check if STOPF is set */ + if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_STOPF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_STOPI) != RESET)) + { + /* Call I2C Slave complete process */ + I2C_ITSlaveCplt(hi2c, ITFlags); + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_NACKI) != RESET)) + { + /* Check that I2C transfer finished */ + /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ + /* Mean XferCount == 0 */ + /* So clear Flag NACKF only */ + if ((I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET) || + (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET)) + { + /* Split check of hdmarx, for MISRA compliance */ + if (hi2c->hdmarx != NULL) + { + if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_RXDMAEN) != RESET) + { + if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U) + { + treatdmanack = 1U; + } + } + } + + /* Split check of hdmatx, for MISRA compliance */ + if (hi2c->hdmatx != NULL) + { + if (I2C_CHECK_IT_SOURCE(ITSources, I2C_CR1_TXDMAEN) != RESET) + { + if (I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx) == 0U) + { + treatdmanack = 1U; + } + } + } + + if (treatdmanack == 1U) + { + if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) + /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for + Warning[Pa134]: left and right operands are identical */ + { + /* Call I2C Listen complete process */ + I2C_ITListenCplt(hi2c, ITFlags); + } + else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Last Byte is Transmitted */ + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + else + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + } + } + else + { + /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + /* Store current hi2c->State, solve MISRA2012-Rule-13.5 */ + tmpstate = hi2c->State; + + if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) + { + if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN)) + { + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; + } + else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN)) + { + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; + } + else + { + /* Do nothing */ + } + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, hi2c->ErrorCode); + } + } + } + else + { + /* Only Clear NACK Flag, no DMA treatment is pending */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + } + } + else if ((I2C_CHECK_FLAG(ITFlags, I2C_FLAG_ADDR) != RESET) && \ + (I2C_CHECK_IT_SOURCE(ITSources, I2C_IT_ADDRI) != RESET)) + { + I2C_ITAddrCplt(hi2c, ITFlags); + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, + uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, + uint32_t Tickstart) +{ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Send LSB of Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TCR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + 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: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param MemAddress Internal memory address + * @param MemAddSize Size of internal memory address + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, + uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, + uint32_t Tickstart) +{ + I2C_TransferConfig(hi2c, DevAddress, (uint8_t)MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); + + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* If Memory address size is 8Bit */ + if (MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXIS flag is set */ + if (I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Send LSB of Memory Address */ + hi2c->Instance->TXDR = I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TC flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TC, RESET, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief I2C Address complete process callback. + * @param hi2c I2C handle. + * @param ITFlags Interrupt flags to handle. + * @retval None + */ +static void I2C_ITAddrCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) +{ + uint8_t transferdirection; + uint16_t slaveaddrcode; + uint16_t ownadd1code; + uint16_t ownadd2code; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(ITFlags); + + /* In case of Listen state, need to inform upper layer of address match code event */ + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) + { + transferdirection = I2C_GET_DIR(hi2c); + slaveaddrcode = I2C_GET_ADDR_MATCH(hi2c); + ownadd1code = I2C_GET_OWN_ADDRESS1(hi2c); + ownadd2code = I2C_GET_OWN_ADDRESS2(hi2c); + + /* If 10bits addressing mode is selected */ + if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + if ((slaveaddrcode & SLAVE_ADDR_MSK) == ((ownadd1code >> SLAVE_ADDR_SHIFT) & SLAVE_ADDR_MSK)) + { + slaveaddrcode = ownadd1code; + hi2c->AddrEventCount++; + if (hi2c->AddrEventCount == 2U) + { + /* Reset Address Event counter */ + hi2c->AddrEventCount = 0U; + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call Slave Addr callback */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode); +#else + HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + } + else + { + slaveaddrcode = ownadd2code; + + /* Disable ADDR Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call Slave Addr callback */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode); +#else + HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + } + /* else 7 bits addressing mode is selected */ + else + { + /* Disable ADDR Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call Slave Addr callback */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AddrCallback(hi2c, transferdirection, slaveaddrcode); +#else + HAL_I2C_AddrCallback(hi2c, transferdirection, slaveaddrcode); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + } + /* Else clear address flag only */ + else + { + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + } +} + +/** + * @brief I2C Master sequential complete process. + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_ITMasterSeqCplt(I2C_HandleTypeDef *hi2c) +{ + /* Reset I2C handle mode */ + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* No Generate Stop, to permit restart mode */ + /* The stop will be done at the end of transfer, when I2C_AUTOEND_MODE enable */ + if (hi2c->State == HAL_I2C_STATE_BUSY_TX) + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; + hi2c->XferISR = NULL; + + /* Disable Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterTxCpltCallback(hi2c); +#else + HAL_I2C_MasterTxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + /* hi2c->State == HAL_I2C_STATE_BUSY_RX */ + else + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + hi2c->XferISR = NULL; + + /* Disable Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterRxCpltCallback(hi2c); +#else + HAL_I2C_MasterRxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } +} + +/** + * @brief I2C Slave sequential complete process. + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_ITSlaveSeqCplt(I2C_HandleTypeDef *hi2c) +{ + uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1); + + /* Reset I2C handle mode */ + hi2c->Mode = HAL_I2C_MODE_NONE; + +#if defined(HAL_DMA_MODULE_ENABLED) + /* If a DMA is ongoing, Update handle size context */ + if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET) + { + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + } + else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET) + { + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + } + else + { + /* Do nothing */ + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) + { + /* Remove HAL_I2C_STATE_SLAVE_BUSY_TX, keep only HAL_I2C_STATE_LISTEN */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; + + /* Disable Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveTxCpltCallback(hi2c); +#else + HAL_I2C_SlaveTxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + + else if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) + { + /* Remove HAL_I2C_STATE_SLAVE_BUSY_RX, keep only HAL_I2C_STATE_LISTEN */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; + + /* Disable Interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveRxCpltCallback(hi2c); +#else + HAL_I2C_SlaveRxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief I2C Master complete process. + * @param hi2c I2C handle. + * @param ITFlags Interrupt flags to handle. + * @retval None + */ +static void I2C_ITMasterCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) +{ + uint32_t tmperror; + uint32_t tmpITFlags = ITFlags; + __IO uint32_t tmpreg; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Disable Interrupts and Store Previous state */ + if (hi2c->State == HAL_I2C_STATE_BUSY_TX) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_TX_IT); + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; + } + else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT); + hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; + } + else + { + /* Do nothing */ + } + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + /* Reset handle parameters */ + hi2c->XferISR = NULL; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + + if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set acknowledge error code */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + } + + /* Fetch Last receive data if any */ + if ((hi2c->State == HAL_I2C_STATE_ABORT) && (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET)) + { + /* Read data from RXDR */ + tmpreg = (uint8_t)hi2c->Instance->RXDR; + UNUSED(tmpreg); + } + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Store current volatile hi2c->ErrorCode, misra rule */ + tmperror = hi2c->ErrorCode; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if ((hi2c->State == HAL_I2C_STATE_ABORT) || (tmperror != HAL_I2C_ERROR_NONE)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, hi2c->ErrorCode); + } + /* hi2c->State == HAL_I2C_STATE_BUSY_TX */ + else if (hi2c->State == HAL_I2C_STATE_BUSY_TX) + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + + if (hi2c->Mode == HAL_I2C_MODE_MEM) + { + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemTxCpltCallback(hi2c); +#else + HAL_I2C_MemTxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterTxCpltCallback(hi2c); +#else + HAL_I2C_MasterTxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + } + /* hi2c->State == HAL_I2C_STATE_BUSY_RX */ + else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + + if (hi2c->Mode == HAL_I2C_MODE_MEM) + { + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MemRxCpltCallback(hi2c); +#else + HAL_I2C_MemRxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->MasterRxCpltCallback(hi2c); +#else + HAL_I2C_MasterRxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief I2C Slave complete process. + * @param hi2c I2C handle. + * @param ITFlags Interrupt flags to handle. + * @retval None + */ +static void I2C_ITSlaveCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) +{ + uint32_t tmpcr1value = READ_REG(hi2c->Instance->CR1); + uint32_t tmpITFlags = ITFlags; + uint32_t tmpoptions = hi2c->XferOptions; + HAL_I2C_StateTypeDef tmpstate = hi2c->State; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Disable Interrupts and Store Previous state */ + if ((tmpstate == HAL_I2C_STATE_BUSY_TX) || (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN)) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT); + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; + } + else if ((tmpstate == HAL_I2C_STATE_BUSY_RX) || (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN)) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT); + hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; + } + else if (tmpstate == HAL_I2C_STATE_LISTEN) + { + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_TX_IT | I2C_XFER_RX_IT); + hi2c->PreviousState = I2C_STATE_NONE; + } + else + { + /* Do nothing */ + } + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* If a DMA is ongoing, Update handle size context */ + if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_TXDMAEN) != RESET) + { + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + if (hi2c->hdmatx != NULL) + { + hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmatx); + } + } + else if (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_CR1_RXDMAEN) != RESET) + { + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + if (hi2c->hdmarx != NULL) + { + hi2c->XferCount = (uint16_t)I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx); + } + } + else + { + /* Do nothing */ + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Store Last receive data if any */ + if (I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_RXNE) != RESET) + { + /* Remove RXNE flag on temporary variable as read done */ + tmpITFlags &= ~I2C_FLAG_RXNE; + + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + if ((hi2c->XferSize > 0U)) + { + hi2c->XferSize--; + hi2c->XferCount--; + } + } + + /* All data are not transferred, so set error code accordingly */ + if (hi2c->XferCount != 0U) + { + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + } + + if ((I2C_CHECK_FLAG(tmpITFlags, I2C_FLAG_AF) != RESET) && \ + (I2C_CHECK_IT_SOURCE(tmpcr1value, I2C_IT_NACKI) != RESET)) + { + /* Check that I2C transfer finished */ + /* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */ + /* Mean XferCount == 0*/ + /* So clear Flag NACKF only */ + if (hi2c->XferCount == 0U) + { + if ((hi2c->State == HAL_I2C_STATE_LISTEN) && (tmpoptions == I2C_FIRST_AND_LAST_FRAME)) + /* Same action must be done for (tmpoptions == I2C_LAST_FRAME) which removed for + Warning[Pa134]: left and right operands are identical */ + { + /* Call I2C Listen complete process */ + I2C_ITListenCplt(hi2c, tmpITFlags); + } + else if ((hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) && (tmpoptions != I2C_NO_OPTION_FRAME)) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Last Byte is Transmitted */ + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + else + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + } + } + else + { + /* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/ + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + + if ((tmpoptions == I2C_FIRST_FRAME) || (tmpoptions == I2C_NEXT_FRAME)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, hi2c->ErrorCode); + } + } + } + + hi2c->Mode = HAL_I2C_MODE_NONE; + hi2c->XferISR = NULL; + + if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, hi2c->ErrorCode); + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ + if (hi2c->State == HAL_I2C_STATE_LISTEN) + { + /* Call I2C Listen complete process */ + I2C_ITListenCplt(hi2c, tmpITFlags); + } + } + else if (hi2c->XferOptions != I2C_NO_OPTION_FRAME) + { + /* Call the Sequential Complete callback, to inform upper layer of the end of Transfer */ + I2C_ITSlaveSeqCplt(hi2c); + + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ListenCpltCallback(hi2c); +#else + HAL_I2C_ListenCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + /* Call the corresponding callback to inform upper layer of End of Transfer */ + else if (hi2c->State == HAL_I2C_STATE_BUSY_RX) + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveRxCpltCallback(hi2c); +#else + HAL_I2C_SlaveRxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->SlaveTxCpltCallback(hi2c); +#else + HAL_I2C_SlaveTxCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } +} + +/** + * @brief I2C Listen complete process. + * @param hi2c I2C handle. + * @param ITFlags Interrupt flags to handle. + * @retval None + */ +static void I2C_ITListenCplt(I2C_HandleTypeDef *hi2c, uint32_t ITFlags) +{ + /* Reset handle parameters */ + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->PreviousState = I2C_STATE_NONE; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + hi2c->XferISR = NULL; + + /* Store Last receive data if any */ + if (I2C_CHECK_FLAG(ITFlags, I2C_FLAG_RXNE) != RESET) + { + /* Read data from RXDR */ + *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->RXDR; + + /* Increment Buffer pointer */ + hi2c->pBuffPtr++; + + if ((hi2c->XferSize > 0U)) + { + hi2c->XferSize--; + hi2c->XferCount--; + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + } + } + + /* Disable all Interrupts*/ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT); + + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ListenCpltCallback(hi2c); +#else + HAL_I2C_ListenCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ +} + +/** + * @brief I2C interrupts error process. + * @param hi2c I2C handle. + * @param ErrorCode Error code to handle. + * @retval None + */ +static void I2C_ITError(I2C_HandleTypeDef *hi2c, uint32_t ErrorCode) +{ + HAL_I2C_StateTypeDef tmpstate = hi2c->State; + +#if defined(HAL_DMA_MODULE_ENABLED) + uint32_t tmppreviousstate; +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset handle parameters */ + hi2c->Mode = HAL_I2C_MODE_NONE; + hi2c->XferOptions = I2C_NO_OPTION_FRAME; + hi2c->XferCount = 0U; + + /* Set new error code */ + hi2c->ErrorCode |= ErrorCode; + + /* Disable Interrupts */ + if ((tmpstate == HAL_I2C_STATE_LISTEN) || + (tmpstate == HAL_I2C_STATE_BUSY_TX_LISTEN) || + (tmpstate == HAL_I2C_STATE_BUSY_RX_LISTEN)) + { + /* Disable all interrupts, except interrupts related to LISTEN state */ + I2C_Disable_IRQ(hi2c, I2C_XFER_RX_IT | I2C_XFER_TX_IT); + + /* keep HAL_I2C_STATE_LISTEN if set */ + hi2c->State = HAL_I2C_STATE_LISTEN; + hi2c->XferISR = I2C_Slave_ISR_IT; + } + else + { + /* Disable all interrupts */ + I2C_Disable_IRQ(hi2c, I2C_XFER_LISTEN_IT | I2C_XFER_RX_IT | I2C_XFER_TX_IT); + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* If state is an abort treatment on going, don't change state */ + /* This change will be do later */ + if (hi2c->State != HAL_I2C_STATE_ABORT) + { + /* Set HAL_I2C_STATE_READY */ + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if a STOPF is detected */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + + } + hi2c->XferISR = NULL; + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort DMA TX transfer if any */ + tmppreviousstate = hi2c->PreviousState; + + if ((hi2c->hdmatx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_TX) || \ + (tmppreviousstate == I2C_STATE_SLAVE_BUSY_TX))) + { + if ((hi2c->Instance->CR1 & I2C_CR1_TXDMAEN) == I2C_CR1_TXDMAEN) + { + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + } + + if (HAL_DMA_GetState(hi2c->hdmatx) != HAL_DMA_STATE_READY) + { + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); + } + } + else + { + I2C_TreatErrorCallback(hi2c); + } + } + /* Abort DMA RX transfer if any */ + else if ((hi2c->hdmarx != NULL) && ((tmppreviousstate == I2C_STATE_MASTER_BUSY_RX) || \ + (tmppreviousstate == I2C_STATE_SLAVE_BUSY_RX))) + { + if ((hi2c->Instance->CR1 & I2C_CR1_RXDMAEN) == I2C_CR1_RXDMAEN) + { + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + } + + if (HAL_DMA_GetState(hi2c->hdmarx) != HAL_DMA_STATE_READY) + { + /* Set the I2C DMA Abort callback : + will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ + hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) + { + /* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */ + hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); + } + } + else + { + I2C_TreatErrorCallback(hi2c); + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + I2C_TreatErrorCallback(hi2c); + } +} + +/** + * @brief I2C Error callback treatment. + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_TreatErrorCallback(I2C_HandleTypeDef *hi2c) +{ + if (hi2c->State == HAL_I2C_STATE_ABORT) + { + hi2c->State = HAL_I2C_STATE_READY; + hi2c->PreviousState = I2C_STATE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->AbortCpltCallback(hi2c); +#else + HAL_I2C_AbortCpltCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } + else + { + hi2c->PreviousState = I2C_STATE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) + hi2c->ErrorCallback(hi2c); +#else + HAL_I2C_ErrorCallback(hi2c); +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + } +} + +/** + * @brief I2C Tx data register flush process. + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_Flush_TXDR(I2C_HandleTypeDef *hi2c) +{ + /* If a pending TXIS flag is set */ + /* Write a dummy data in TXDR to clear it */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) != RESET) + { + hi2c->Instance->TXDR = 0x00U; + } + + /* Flush TX register if not empty */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET) + { + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_TXE); + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief DMA I2C master transmit process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma) +{ + HAL_StatusTypeDef dmaxferstatus = HAL_OK; + /* Derogation MISRAC2012-Rule-11.5 */ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* If last transfer, enable STOP interrupt */ + if (hi2c->XferCount == 0U) + { + /* Enable STOP interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); + } + /* else prepare a new DMA transfer and enable TCReload interrupt */ + else + { + /* Update Buffer pointer */ + hi2c->pBuffPtr += hi2c->XferSize; + + /* Set the XferSize to transfer */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + /* Enable the DMA channel */ + if ((hi2c->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr; + + /* Set DMA destination address */ + hi2c->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2c->Instance->TXDR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmatx); + } + else + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, + hi2c->XferSize); + } + + if (dmaxferstatus != HAL_OK) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); + } + else + { + /* Enable TC interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT); + } + } +} + + +/** + * @brief DMA I2C slave transmit process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + uint32_t tmpoptions = hi2c->XferOptions; + + if ((tmpoptions == I2C_NEXT_FRAME) || (tmpoptions == I2C_FIRST_FRAME)) + { + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Last Byte is Transmitted */ + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + else + { + /* No specific action, Master fully manage the generation of STOP condition */ + /* Mean that this generation can arrive at any time, at the end or during DMA process */ + /* So STOP condition should be manage through Interrupt treatment */ + } +} + + +/** + * @brief DMA I2C master receive process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma) +{ + HAL_StatusTypeDef dmaxferstatus = HAL_OK; + /* Derogation MISRAC2012-Rule-11.5 */ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* If last transfer, enable STOP interrupt */ + if (hi2c->XferCount == 0U) + { + /* Enable STOP interrupt */ + I2C_Enable_IRQ(hi2c, I2C_XFER_CPLT_IT); + } + /* else prepare a new DMA transfer and enable TCReload interrupt */ + else + { + /* Update Buffer pointer */ + hi2c->pBuffPtr += hi2c->XferSize; + + /* Set the XferSize to transfer */ + if (hi2c->XferCount > MAX_NBYTE_SIZE) + { + hi2c->XferSize = MAX_NBYTE_SIZE; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + /* Enable the DMA channel */ + if ((hi2c->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2c->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2c->XferSize; + + /* Set DMA source address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2c->Instance->RXDR; + + /* Set DMA destination address */ + hi2c->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2c->pBuffPtr; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hi2c->hdmarx); + } + else + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr, + hi2c->XferSize); + } + + if (dmaxferstatus != HAL_OK) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); + } + else + { + /* Enable TC interrupts */ + I2C_Enable_IRQ(hi2c, I2C_XFER_RELOAD_IT); + } + } +} + + +/** + * @brief DMA I2C slave receive process complete callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + uint32_t tmpoptions = hi2c->XferOptions; + + if ((I2C_GET_DMA_REMAIN_DATA(hi2c->hdmarx) == 0U) && \ + (tmpoptions != I2C_NO_OPTION_FRAME)) + { + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Call I2C Slave Sequential complete process */ + I2C_ITSlaveSeqCplt(hi2c); + } + else + { + /* No specific action, Master fully manage the generation of STOP condition */ + /* Mean that this generation can arrive at any time, at the end or during DMA process */ + /* So STOP condition should be manage through Interrupt treatment */ + } +} + + +/** + * @brief DMA I2C communication error callback. + * @param hdma DMA handle + * @retval None + */ +static void I2C_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Disable Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + I2C_ITError(hi2c, HAL_I2C_ERROR_DMA); +} + + +/** + * @brief DMA I2C communication abort callback + * (To be called at end of DMA Abort procedure). + * @param hdma DMA handle. + * @retval None + */ +static void I2C_DMAAbort(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Reset AbortCpltCallback */ + if (hi2c->hdmatx != NULL) + { + hi2c->hdmatx->XferAbortCallback = NULL; + } + if (hi2c->hdmarx != NULL) + { + hi2c->hdmarx->XferAbortCallback = NULL; + } + + I2C_TreatErrorCallback(hi2c); +} + +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief This function handles I2C Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @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 actual Flag status (SET or RESET). + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, + uint32_t Timeout, uint32_t Tickstart) +{ + while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status) + { + /* Check if an error is detected */ + if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + if ((__HAL_I2C_GET_FLAG(hi2c, Flag) == Status)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + } + } + } + return HAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of TXIS flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart) +{ + while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET) + { + /* Check if an error is detected */ + if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + } + } + return HAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of STOP flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart) +{ + while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) + { + /* Check if an error is detected */ + if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) + { + return HAL_ERROR; + } + + /* Check for the Timeout */ + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + } + } + return HAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, + uint32_t Tickstart) +{ + HAL_StatusTypeDef status = HAL_OK; + + while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) && (status == HAL_OK)) + { + /* Check if an error is detected */ + if (I2C_IsErrorOccurred(hi2c, Timeout, Tickstart) != HAL_OK) + { + status = HAL_ERROR; + } + + /* Check if a STOPF is detected */ + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) && (status == HAL_OK)) + { + /* Check if an RXNE is pending */ + /* Store Last receive data if any */ + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) && (hi2c->XferSize > 0U)) + { + /* Return HAL_OK */ + /* The Reading of data from RXDR will be done in caller function */ + status = HAL_OK; + } + + /* Check a no-acknowledge have been detected */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + hi2c->ErrorCode = HAL_I2C_ERROR_AF; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + status = HAL_ERROR; + } + else + { + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + } + } + + /* Check for the Timeout */ + if ((((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) && (status == HAL_OK)) + { + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + status = HAL_ERROR; + } + } + } + return status; +} + +/** + * @brief This function handles errors detection during an I2C Communication. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_IsErrorOccurred(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t itflag = hi2c->Instance->ISR; + uint32_t error_code = 0; + uint32_t tickstart = Tickstart; + uint32_t tmp1; + HAL_I2C_ModeTypeDef tmp2; + + if (HAL_IS_BIT_SET(itflag, I2C_FLAG_AF)) + { + /* Clear NACKF Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Wait until STOP Flag is set or timeout occurred */ + /* AutoEnd should be initiate after AF */ + while ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) && (status == HAL_OK)) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + tmp1 = (uint32_t)(hi2c->Instance->CR2 & I2C_CR2_STOP); + tmp2 = hi2c->Mode; + + /* In case of I2C still busy, try to regenerate a STOP manually */ + if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && \ + (tmp1 != I2C_CR2_STOP) && \ + (tmp2 != HAL_I2C_MODE_SLAVE)) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + + /* Update Tick with new reference */ + tickstart = HAL_GetTick(); + } + + while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > I2C_TIMEOUT_STOPF) + { + error_code |= HAL_I2C_ERROR_TIMEOUT; + + status = HAL_ERROR; + + break; + } + } + } + } + } + + /* In case STOP Flag is detected, clear it */ + if (status == HAL_OK) + { + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + + error_code |= HAL_I2C_ERROR_AF; + + status = HAL_ERROR; + } + + /* Refresh Content of Status register */ + itflag = hi2c->Instance->ISR; + + /* Then verify if an additional errors occurs */ + /* Check if a Bus error occurred */ + if (HAL_IS_BIT_SET(itflag, I2C_FLAG_BERR)) + { + error_code |= HAL_I2C_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); + + status = HAL_ERROR; + } + + /* Check if an Over-Run/Under-Run error occurred */ + if (HAL_IS_BIT_SET(itflag, I2C_FLAG_OVR)) + { + error_code |= HAL_I2C_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); + + status = HAL_ERROR; + } + + /* Check if an Arbitration Loss error occurred */ + if (HAL_IS_BIT_SET(itflag, I2C_FLAG_ARLO)) + { + error_code |= HAL_I2C_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); + + status = HAL_ERROR; + } + + if (status != HAL_OK) + { + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + /* Clear Configuration Register 2 */ + I2C_RESET_CR2(hi2c); + + hi2c->ErrorCode |= error_code; + hi2c->State = HAL_I2C_STATE_READY; + hi2c->Mode = HAL_I2C_MODE_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + } + + return status; +} + +/** + * @brief Handles I2Cx communication when starting transfer or during transfer (TC or TCR flag are set). + * @param hi2c I2C handle. + * @param DevAddress Specifies the slave address to be programmed. + * @param Size Specifies the number of bytes to be programmed. + * This parameter must be a value between 0 and 255. + * @param Mode New state of the I2C START condition generation. + * This parameter can be one of the following values: + * @arg @ref I2C_RELOAD_MODE Enable Reload mode . + * @arg @ref I2C_AUTOEND_MODE Enable Automatic end mode. + * @arg @ref I2C_SOFTEND_MODE Enable Software end mode. + * @param Request New state of the I2C START condition generation. + * This parameter can be one of the following values: + * @arg @ref I2C_NO_STARTSTOP Don't Generate stop and start condition. + * @arg @ref I2C_GENERATE_STOP Generate stop condition (Size should be set to 0). + * @arg @ref I2C_GENERATE_START_READ Generate Restart for read request. + * @arg @ref I2C_GENERATE_START_WRITE Generate Restart for write request. + * @retval None + */ +static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, + uint32_t Request) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_TRANSFER_MODE(Mode)); + assert_param(IS_TRANSFER_REQUEST(Request)); + + /* Declaration of tmp to prevent undefined behavior of volatile usage */ + uint32_t tmp = ((uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \ + (((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \ + (uint32_t)Mode | (uint32_t)Request) & (~0x80000000U)); + + /* update CR2 register */ + MODIFY_REG(hi2c->Instance->CR2, \ + ((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \ + (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31U - I2C_CR2_RD_WRN_Pos))) | \ + I2C_CR2_START | I2C_CR2_STOP)), tmp); +} + +/** + * @brief Manage the enabling of Interrupts. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param InterruptRequest Value of @ref I2C_Interrupt_configuration_definition. + * @retval None + */ +static void I2C_Enable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest) +{ + uint32_t tmpisr = 0U; + +#if defined(HAL_DMA_MODULE_ENABLED) + if ((hi2c->XferISR != I2C_Master_ISR_DMA) && \ + (hi2c->XferISR != I2C_Slave_ISR_DMA) && \ + (hi2c->XferISR != I2C_Mem_ISR_DMA)) +#endif /* HAL_DMA_MODULE_ENABLED */ + { + if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT) + { + /* Enable ERR, STOP, NACK and ADDR interrupts */ + tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; + } + + if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT) + { + /* Enable ERR, TC, STOP, NACK and TXI interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI; + } + + if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT) + { + /* Enable ERR, TC, STOP, NACK and RXI interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI; + } + + if (InterruptRequest == I2C_XFER_ERROR_IT) + { + /* Enable ERR and NACK interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI; + } + + if (InterruptRequest == I2C_XFER_CPLT_IT) + { + /* Enable STOP interrupts */ + tmpisr |= I2C_IT_STOPI; + } + } + +#if defined(HAL_DMA_MODULE_ENABLED) + else + { + if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT) + { + /* Enable ERR, STOP, NACK and ADDR interrupts */ + tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; + } + + if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT) + { + /* Enable ERR, TC, STOP, NACK and TXI interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI; + } + + if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT) + { + /* Enable ERR, TC, STOP, NACK and RXI interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_RXI; + } + + if (InterruptRequest == I2C_XFER_ERROR_IT) + { + /* Enable ERR and NACK interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI; + } + + if (InterruptRequest == I2C_XFER_CPLT_IT) + { + /* Enable STOP interrupts */ + tmpisr |= (I2C_IT_STOPI | I2C_IT_TCI); + } + + if (InterruptRequest == I2C_XFER_RELOAD_IT) + { + /* Enable TC interrupts */ + tmpisr |= I2C_IT_TCI; + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Enable interrupts only at the end */ + /* to avoid the risk of I2C interrupt handle execution before */ + /* all interrupts requested done */ + __HAL_I2C_ENABLE_IT(hi2c, tmpisr); +} + +/** + * @brief Manage the disabling of Interrupts. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param InterruptRequest Value of @ref I2C_Interrupt_configuration_definition. + * @retval None + */ +static void I2C_Disable_IRQ(I2C_HandleTypeDef *hi2c, uint16_t InterruptRequest) +{ + uint32_t tmpisr = 0U; + + if ((InterruptRequest & I2C_XFER_TX_IT) == I2C_XFER_TX_IT) + { + /* Disable TC and TXI interrupts */ + tmpisr |= I2C_IT_TCI | I2C_IT_TXI; + + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN) + { + /* Disable NACK and STOP interrupts */ + tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; + } + } + + if ((InterruptRequest & I2C_XFER_RX_IT) == I2C_XFER_RX_IT) + { + /* Disable TC and RXI interrupts */ + tmpisr |= I2C_IT_TCI | I2C_IT_RXI; + + if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) != (uint32_t)HAL_I2C_STATE_LISTEN) + { + /* Disable NACK and STOP interrupts */ + tmpisr |= I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; + } + } + + if ((InterruptRequest & I2C_XFER_LISTEN_IT) == I2C_XFER_LISTEN_IT) + { + /* Disable ADDR, NACK and STOP interrupts */ + tmpisr |= I2C_IT_ADDRI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ERRI; + } + + if (InterruptRequest == I2C_XFER_ERROR_IT) + { + /* Enable ERR and NACK interrupts */ + tmpisr |= I2C_IT_ERRI | I2C_IT_NACKI; + } + + if (InterruptRequest == I2C_XFER_CPLT_IT) + { + /* Enable STOP interrupts */ + tmpisr |= I2C_IT_STOPI; + } + + if (InterruptRequest == I2C_XFER_RELOAD_IT) + { + /* Enable TC interrupts */ + tmpisr |= I2C_IT_TCI; + } + + /* Disable interrupts only at the end */ + /* to avoid a breaking situation like at "t" time */ + /* all disable interrupts request are not done */ + __HAL_I2C_DISABLE_IT(hi2c, tmpisr); +} + +/** + * @brief Convert I2Cx OTHER_xxx XferOptions to functional XferOptions. + * @param hi2c I2C handle. + * @retval None + */ +static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c) +{ + /* if user set XferOptions to I2C_OTHER_FRAME */ + /* it request implicitly to generate a restart condition */ + /* set XferOptions to I2C_FIRST_FRAME */ + if (hi2c->XferOptions == I2C_OTHER_FRAME) + { + hi2c->XferOptions = I2C_FIRST_FRAME; + } + /* else if user set XferOptions to I2C_OTHER_AND_LAST_FRAME */ + /* it request implicitly to generate a restart condition */ + /* then generate a stop condition at the end of transfer */ + /* set XferOptions to I2C_FIRST_AND_LAST_FRAME */ + else if (hi2c->XferOptions == I2C_OTHER_AND_LAST_FRAME) + { + hi2c->XferOptions = I2C_FIRST_AND_LAST_FRAME; + } + else + { + /* Nothing to do */ + } +} + +/** + * @} + */ + +#endif /* HAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c_ex.c index 10853efa4..71dcd7607 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2c_ex.c @@ -1,359 +1,359 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_i2c_ex.c - * @author MCD Application Team - * @brief I2C Extended HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of I2C Extended peripheral: - * + Filter Mode Functions - * + WakeUp Mode Functions - * + FastModePlus Functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### I2C peripheral Extended features ##### - ============================================================================== - - [..] Comparing to other previous devices, the I2C interface for STM32H7RSxx - devices contains the following additional features - - (+) Possibility to disable or enable Analog Noise Filter - (+) Use of a configured Digital Noise Filter - (+) Disable or enable wakeup from Stop mode(s) - (+) Disable or enable Fast Mode Plus - - ##### How to use this driver ##### - ============================================================================== - [..] This driver provides functions to configure Noise Filter and Wake Up Feature - (#) Configure I2C Analog noise filter using the function HAL_I2CEx_ConfigAnalogFilter() - (#) Configure I2C Digital noise filter using the function HAL_I2CEx_ConfigDigitalFilter() - (#) Configure the enable or disable of I2C Wake Up Mode using the functions : - (++) HAL_I2CEx_EnableWakeUp() - (++) HAL_I2CEx_DisableWakeUp() - (#) Configure the enable or disable of fast mode plus driving capability using the functions : - (++) HAL_I2CEx_ConfigFastModePlus() - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup I2CEx I2CEx - * @brief I2C Extended HAL module driver - * @{ - */ - -#ifdef HAL_I2C_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ - -/** @defgroup I2CEx_Exported_Functions I2C Extended Exported Functions - * @{ - */ - -/** @defgroup I2CEx_Exported_Functions_Group1 Filter Mode Functions - * @brief Filter Mode Functions - * -@verbatim - =============================================================================== - ##### Filter Mode Functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure Noise Filters - -@endverbatim - * @{ - */ - -/** - * @brief Configure 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_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter) -{ - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - assert_param(IS_I2C_ANALOG_FILTER(AnalogFilter)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /* Reset I2Cx ANOFF bit */ - hi2c->Instance->CR1 &= ~(I2C_CR1_ANFOFF); - - /* Set analog filter bit*/ - hi2c->Instance->CR1 |= AnalogFilter; - - __HAL_I2C_ENABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Configure 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 Min_Data=0x00 and Max_Data=0x0F. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter) -{ - uint32_t tmpreg; - - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - assert_param(IS_I2C_DIGITAL_FILTER(DigitalFilter)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /* Get the old register value */ - tmpreg = hi2c->Instance->CR1; - - /* Reset I2Cx DNF bits [11:8] */ - tmpreg &= ~(I2C_CR1_DNF); - - /* Set I2Cx DNF coefficient */ - tmpreg |= DigitalFilter << 8U; - - /* Store the new register value */ - hi2c->Instance->CR1 = tmpreg; - - __HAL_I2C_ENABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -/** - * @} - */ - -/** @defgroup I2CEx_Exported_Functions_Group2 WakeUp Mode Functions - * @brief WakeUp Mode Functions - * -@verbatim - =============================================================================== - ##### WakeUp Mode Functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure Wake Up Feature - -@endverbatim - * @{ - */ - -/** - * @brief Enable I2C wakeup from Stop mode(s). - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2Cx peripheral. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp(I2C_HandleTypeDef *hi2c) -{ - /* Check the parameters */ - assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hi2c->Instance)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /* Enable wakeup from stop mode */ - hi2c->Instance->CR1 |= I2C_CR1_WUPEN; - - __HAL_I2C_ENABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Disable I2C wakeup from Stop mode(s). - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2Cx peripheral. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp(I2C_HandleTypeDef *hi2c) -{ - /* Check the parameters */ - assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hi2c->Instance)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /* Enable wakeup from stop mode */ - hi2c->Instance->CR1 &= ~(I2C_CR1_WUPEN); - - __HAL_I2C_ENABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -/** - * @} - */ - -/** @defgroup I2CEx_Exported_Functions_Group3 Fast Mode Plus Functions - * @brief Fast Mode Plus Functions - * -@verbatim - =============================================================================== - ##### Fast Mode Plus Functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure Fast Mode Plus - -@endverbatim - * @{ - */ - -/** - * @brief Configure I2C Fast Mode Plus. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2Cx peripheral. - * @param FastModePlus New state of the Fast Mode Plus. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2CEx_ConfigFastModePlus(I2C_HandleTypeDef *hi2c, uint32_t FastModePlus) -{ - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - assert_param(IS_I2C_FASTMODEPLUS(FastModePlus)); - - if (hi2c->State == HAL_I2C_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - if (FastModePlus == I2C_FASTMODEPLUS_ENABLE) - { - /* Set I2Cx FMP bit */ - hi2c->Instance->CR1 |= (I2C_CR1_FMP); - } - else - { - /* Reset I2Cx FMP bit */ - hi2c->Instance->CR1 &= ~(I2C_CR1_FMP); - } - - __HAL_I2C_ENABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @} - */ -/** - * @} - */ - -#endif /* HAL_I2C_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_i2c_ex.c + * @author MCD Application Team + * @brief I2C Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of I2C Extended peripheral: + * + Filter Mode Functions + * + WakeUp Mode Functions + * + FastModePlus Functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### I2C peripheral Extended features ##### + ============================================================================== + + [..] Comparing to other previous devices, the I2C interface for STM32H7RSxx + devices contains the following additional features + + (+) Possibility to disable or enable Analog Noise Filter + (+) Use of a configured Digital Noise Filter + (+) Disable or enable wakeup from Stop mode(s) + (+) Disable or enable Fast Mode Plus + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure Noise Filter and Wake Up Feature + (#) Configure I2C Analog noise filter using the function HAL_I2CEx_ConfigAnalogFilter() + (#) Configure I2C Digital noise filter using the function HAL_I2CEx_ConfigDigitalFilter() + (#) Configure the enable or disable of I2C Wake Up Mode using the functions : + (++) HAL_I2CEx_EnableWakeUp() + (++) HAL_I2CEx_DisableWakeUp() + (#) Configure the enable or disable of fast mode plus driving capability using the functions : + (++) HAL_I2CEx_ConfigFastModePlus() + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup I2CEx I2CEx + * @brief I2C Extended HAL module driver + * @{ + */ + +#ifdef HAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup I2CEx_Exported_Functions I2C Extended Exported Functions + * @{ + */ + +/** @defgroup I2CEx_Exported_Functions_Group1 Filter Mode Functions + * @brief Filter Mode Functions + * +@verbatim + =============================================================================== + ##### Filter Mode Functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Noise Filters + +@endverbatim + * @{ + */ + +/** + * @brief Configure 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_ConfigAnalogFilter(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_ANALOG_FILTER(AnalogFilter)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Reset I2Cx ANOFF bit */ + hi2c->Instance->CR1 &= ~(I2C_CR1_ANFOFF); + + /* Set analog filter bit*/ + hi2c->Instance->CR1 |= AnalogFilter; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Configure 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 Min_Data=0x00 and Max_Data=0x0F. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_ConfigDigitalFilter(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter) +{ + uint32_t tmpreg; + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_DIGITAL_FILTER(DigitalFilter)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Get the old register value */ + tmpreg = hi2c->Instance->CR1; + + /* Reset I2Cx DNF bits [11:8] */ + tmpreg &= ~(I2C_CR1_DNF); + + /* Set I2Cx DNF coefficient */ + tmpreg |= DigitalFilter << 8U; + + /* Store the new register value */ + hi2c->Instance->CR1 = tmpreg; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @} + */ + +/** @defgroup I2CEx_Exported_Functions_Group2 WakeUp Mode Functions + * @brief WakeUp Mode Functions + * +@verbatim + =============================================================================== + ##### WakeUp Mode Functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Wake Up Feature + +@endverbatim + * @{ + */ + +/** + * @brief Enable I2C wakeup from Stop mode(s). + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp(I2C_HandleTypeDef *hi2c) +{ + /* Check the parameters */ + assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hi2c->Instance)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Enable wakeup from stop mode */ + hi2c->Instance->CR1 |= I2C_CR1_WUPEN; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Disable I2C wakeup from Stop mode(s). + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp(I2C_HandleTypeDef *hi2c) +{ + /* Check the parameters */ + assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hi2c->Instance)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Enable wakeup from stop mode */ + hi2c->Instance->CR1 &= ~(I2C_CR1_WUPEN); + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @} + */ + +/** @defgroup I2CEx_Exported_Functions_Group3 Fast Mode Plus Functions + * @brief Fast Mode Plus Functions + * +@verbatim + =============================================================================== + ##### Fast Mode Plus Functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Fast Mode Plus + +@endverbatim + * @{ + */ + +/** + * @brief Configure I2C Fast Mode Plus. + * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param FastModePlus New state of the Fast Mode Plus. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_ConfigFastModePlus(I2C_HandleTypeDef *hi2c, uint32_t FastModePlus) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_FASTMODEPLUS(FastModePlus)); + + if (hi2c->State == HAL_I2C_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + if (FastModePlus == I2C_FASTMODEPLUS_ENABLE) + { + /* Set I2Cx FMP bit */ + hi2c->Instance->CR1 |= (I2C_CR1_FMP); + } + else + { + /* Reset I2Cx FMP bit */ + hi2c->Instance->CR1 &= ~(I2C_CR1_FMP); + } + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ +/** + * @} + */ + +#endif /* HAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s.c index 04bdfee60..5456295fa 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s.c @@ -1,2710 +1,2709 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_i2s.c - * @author MCD Application Team - * @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 - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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/Channel. - (+++) Enable the DMAx interface clock. - (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. - (+++) Configure the DMA Tx/Rx Stream/Channel. - (+++) Associate the initialized 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/Channel. - - (#) 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 - __HAL_I2S_ENABLE_IT() and __HAL_I2S_DISABLE_IT() inside the transmit and receive process. - - (+@) External clock source is configured after setting correctly - the define constant EXTERNAL_CLOCK_VALUE in the stm32h7rsxx_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 I2S 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 - - *** I2S HAL driver macros list *** - =================================== - [..] - Callback registration: - - (#) The compilation flag USE_HAL_I2S_REGISTER_CALLBACKS when set to 1UL - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_I2S_RegisterCallback() to register an interrupt callback. - - Function HAL_I2S_RegisterCallback() allows to register following callbacks: - (+) TxCpltCallback : I2S Tx Completed callback - (+) RxCpltCallback : I2S Rx Completed callback - (+) TxRxCpltCallback : I2S TxRx Completed callback - (+) TxHalfCpltCallback : I2S Tx Half Completed callback - (+) RxHalfCpltCallback : I2S Rx Half Completed callback - (+) TxRxHalfCpltCallback : I2S TxRx Half Completed callback - (+) ErrorCallback : I2S Error callback - (+) MspInitCallback : I2S Msp Init callback - (+) MspDeInitCallback : I2S Msp DeInit callback - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - - (#) Use function HAL_I2S_UnRegisterCallback to reset a callback to the default - weak function. - HAL_I2S_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxCpltCallback : I2S Tx Completed callback - (+) RxCpltCallback : I2S Rx Completed callback - (+) TxRxCpltCallback : I2S TxRx Completed callback - (+) TxHalfCpltCallback : I2S Tx Half Completed callback - (+) RxHalfCpltCallback : I2S Rx Half Completed callback - (+) TxRxHalfCpltCallback : I2S TxRx Half Completed callback - (+) ErrorCallback : I2S Error callback - (+) MspInitCallback : I2S Msp Init callback - (+) MspDeInitCallback : I2S Msp DeInit callback - - By default, after the HAL_I2S_Init() and when the state is HAL_I2S_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_I2S_MasterTxCpltCallback(), HAL_I2S_MasterRxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the HAL_I2S_Init()/ HAL_I2S_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the HAL_I2S_Init()/ HAL_I2S_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - - Callbacks can be registered/unregistered in HAL_I2S_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in HAL_I2S_STATE_READY or HAL_I2S_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using HAL_I2S_RegisterCallback() before calling HAL_I2S_DeInit() - or HAL_I2S_Init() function. - - When The compilation define USE_HAL_I2S_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (surcharged) callbacks are used. - - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -#ifdef HAL_I2S_MODULE_ENABLED - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup I2S I2S - * @brief I2S HAL module driver - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup I2S_Private_Define I2S Private Define - * @{ - */ -#define I2S_TIMEOUT 0xFFFFUL -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup I2S_Private_Functions I2S Private Functions - * @{ - */ -static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); -static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); -static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); -static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); -static void I2SEx_DMATxRxCplt(DMA_HandleTypeDef *hdma); -static void I2SEx_DMATxRxHalfCplt(DMA_HandleTypeDef *hdma); -static void I2S_DMAError(DMA_HandleTypeDef *hdma); -static void I2S_Transmit_16Bit_IT(I2S_HandleTypeDef *hi2s); -static void I2S_Transmit_32Bit_IT(I2S_HandleTypeDef *hi2s); -static void I2S_Receive_16Bit_IT(I2S_HandleTypeDef *hi2s); -static void I2S_Receive_32Bit_IT(I2S_HandleTypeDef *hi2s); -static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State, - uint32_t Tickstart, uint32_t Timeout); -/** - * @} - */ - -/* Exported functions ---------------------------------------------------------*/ - -/** @defgroup I2S_Exported_Functions I2S Exported Functions - * @{ - */ - -/** @defgroup I2S_Exported_Functions_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 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 - - (+) Call the function HAL_I2S_DeInit() to restore the default configuration - of the selected I2Sx peripheral. - @endverbatim - * @{ - */ - -/** - * @brief Initializes the I2S according to the specified parameters - * in the I2S_InitTypeDef and create the associated handle. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) -{ - uint32_t i2sdiv; - uint32_t i2sodd; - uint32_t packetlength; - uint32_t tmp; - uint32_t i2sclk; - uint32_t ispcm; - - /* Check the I2S handle allocation */ - if (hi2s == NULL) - { - return HAL_ERROR; - } - - /* Check the I2S parameters */ - assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance)); - 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_FIRST_BIT(hi2s->Init.FirstBit)); - assert_param(IS_I2S_WS_INVERSION(hi2s->Init.WSInversion)); - assert_param(IS_I2S_DATA_24BIT_ALIGNMENT(hi2s->Init.Data24BitAlignment)); - assert_param(IS_I2S_MASTER_KEEP_IO_STATE(hi2s->Init.MasterKeepIOState)); - - if (hi2s->State == HAL_I2S_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hi2s->Lock = HAL_UNLOCKED; - -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - /* Init the I2S Callback settings */ - hi2s->TxCpltCallback = HAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */ - hi2s->RxCpltCallback = HAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */ - hi2s->TxRxCpltCallback = HAL_I2SEx_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ - hi2s->TxHalfCpltCallback = HAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - hi2s->RxHalfCpltCallback = HAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - hi2s->TxRxHalfCpltCallback = HAL_I2SEx_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ - hi2s->ErrorCallback = HAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */ - - if (hi2s->MspInitCallback == NULL) - { - hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware : GPIO, CLOCK, NVIC... */ - hi2s->MspInitCallback(hi2s); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_I2S_MspInit(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - - hi2s->State = HAL_I2S_STATE_BUSY; - - /* Disable the selected I2S peripheral */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) == SPI_CR1_SPE) - { - /* Disable I2S peripheral */ - __HAL_I2S_DISABLE(hi2s); - } - - /* Clear I2S configuration register */ - CLEAR_REG(hi2s->Instance->I2SCFGR); - - if (IS_I2S_MASTER(hi2s->Init.Mode)) - { - /*------------------------- I2SDIV and ODD Calculation ---------------------*/ - /* 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) - { - /* Channel length is 32 bits */ - packetlength = 2UL; - } - else - { - /* Channel length is 16 bits */ - packetlength = 1UL; - } - - /* Check if PCM standard is used */ - if ((hi2s->Init.Standard == I2S_STANDARD_PCM_SHORT) || - (hi2s->Init.Standard == I2S_STANDARD_PCM_LONG)) - { - ispcm = 1UL; - } - else - { - ispcm = 0UL; - } - - /* Get the source clock value: based on System Clock value */ - if (hi2s->Instance == SPI1) - { - i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI1); - } - else if ((hi2s->Instance == SPI2) || (hi2s->Instance == SPI3)) - { - i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI23); - } - else /* SPI6 source clock */ - { - i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI6); - } - - /* 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 / (256UL >> ispcm)) * 10UL) / hi2s->Init.AudioFreq) + 5UL); - } - else - { - /* MCLK output is disabled */ - tmp = (uint32_t)((((i2sclk / ((32UL >> ispcm) * packetlength)) * 10UL) / hi2s->Init.AudioFreq) + 5UL); - } - - /* Remove the flatting point */ - tmp = tmp / 10UL; - - /* Check the parity of the divider */ - i2sodd = (uint32_t)(tmp & (uint32_t)1UL); - - /* Compute the i2sdiv prescaler */ - i2sdiv = (uint32_t)((tmp - i2sodd) / 2UL); - } - else - { - /* Set the default values */ - i2sdiv = 2UL; - i2sodd = 0UL; - } - - /* Test if the obtain values are forbidden or out of range */ - if (((i2sodd == 1UL) && (i2sdiv == 1UL)) || (i2sdiv > 0xFFUL)) - { - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_PRESCALER); - return HAL_ERROR; - } - - /* Force i2smod to 1 just to be sure that (2xi2sdiv + i2sodd) is always higher than 0 */ - if (i2sdiv == 0UL) - { - i2sodd = 1UL; - } - - MODIFY_REG(hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_I2SDIV | SPI_I2SCFGR_ODD), - ((i2sdiv << SPI_I2SCFGR_I2SDIV_Pos) | (i2sodd << SPI_I2SCFGR_ODD_Pos))); - } - - /*-------------------------- I2Sx I2SCFGR Configuration --------------------*/ - /* Configure I2SMOD, I2SCFG, I2SSTD, PCMSYNC, DATLEN ,CHLEN ,CKPOL, WSINV, DATAFMT, I2SDIV, ODD and MCKOE bits bits */ - /* And configure the I2S with the I2S_InitStruct values */ - MODIFY_REG(hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_I2SMOD | SPI_I2SCFGR_I2SCFG | \ - SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | \ - SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN | \ - SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_WSINV | \ - SPI_I2SCFGR_DATFMT | SPI_I2SCFGR_MCKOE), - (SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | \ - hi2s->Init.Standard | hi2s->Init.DataFormat | \ - hi2s->Init.CPOL | hi2s->Init.WSInversion | \ - hi2s->Init.Data24BitAlignment | hi2s->Init.MCLKOutput)); - /*Clear status register*/ - WRITE_REG(hi2s->Instance->IFCR, 0x0FF8); - - /*---------------------------- I2Sx CFG2 Configuration ----------------------*/ - - /* Unlock the AF configuration to configure CFG2 register*/ - CLEAR_BIT(hi2s->Instance->CR1, SPI_CR1_IOLOCK); - - MODIFY_REG(hi2s->Instance->CFG2, SPI_CFG2_LSBFRST, hi2s->Init.FirstBit); - - /* Insure that AFCNTR is managed only by Master */ - if (IS_I2S_MASTER(hi2s->Init.Mode)) - { - /* Alternate function GPIOs control */ - MODIFY_REG(hi2s->Instance->CFG2, SPI_CFG2_AFCNTR, (hi2s->Init.MasterKeepIOState)); - } - - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitializes the I2S peripheral - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) -{ - /* Check the I2S handle allocation */ - if (hi2s == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance)); - - hi2s->State = HAL_I2S_STATE_BUSY; - - /* Disable the I2S Peripheral Clock */ - __HAL_I2S_DISABLE(hi2s); - -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - if (hi2s->MspDeInitCallback == NULL) - { - hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ - hi2s->MspDeInitCallback(hi2s); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ - HAL_I2S_MspDeInit(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hi2s); - - return HAL_OK; -} - -/** - * @brief I2S MSP Init - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_MspInit could be implemented in the user file - */ -} - -/** - * @brief I2S MSP DeInit - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) -/** - * @brief Register a User I2S Callback - * To be used instead of the weak predefined callback - * @param hi2s Pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for the specified I2S. - * @param CallbackID ID of the callback to be registered - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_RegisterCallback(I2S_HandleTypeDef *hi2s, HAL_I2S_CallbackIDTypeDef CallbackID, - pI2S_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hi2s->ErrorCode |= HAL_I2S_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hi2s); - - if (HAL_I2S_STATE_READY == hi2s->State) - { - switch (CallbackID) - { - case HAL_I2S_TX_COMPLETE_CB_ID : - hi2s->TxCpltCallback = pCallback; - break; - - case HAL_I2S_RX_COMPLETE_CB_ID : - hi2s->RxCpltCallback = pCallback; - break; - - case HAL_I2S_TX_RX_COMPLETE_CB_ID : - hi2s->TxRxCpltCallback = pCallback; - break; - - case HAL_I2S_TX_HALF_COMPLETE_CB_ID : - hi2s->TxHalfCpltCallback = pCallback; - break; - - case HAL_I2S_RX_HALF_COMPLETE_CB_ID : - hi2s->RxHalfCpltCallback = pCallback; - break; - - - case HAL_I2S_TX_RX_HALF_COMPLETE_CB_ID : - hi2s->TxRxHalfCpltCallback = pCallback; - break; - - case HAL_I2S_ERROR_CB_ID : - hi2s->ErrorCallback = pCallback; - break; - - case HAL_I2S_MSPINIT_CB_ID : - hi2s->MspInitCallback = pCallback; - break; - - case HAL_I2S_MSPDEINIT_CB_ID : - hi2s->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_I2S_STATE_RESET == hi2s->State) - { - switch (CallbackID) - { - case HAL_I2S_MSPINIT_CB_ID : - hi2s->MspInitCallback = pCallback; - break; - - case HAL_I2S_MSPDEINIT_CB_ID : - hi2s->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hi2s); - return status; -} - -/** - * @brief Unregister an I2S Callback - * I2S callback is redirected to the weak predefined callback - * @param hi2s Pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for the specified I2S. - * @param CallbackID ID of the callback to be unregistered - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_UnRegisterCallback(I2S_HandleTypeDef *hi2s, HAL_I2S_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hi2s); - - if (HAL_I2S_STATE_READY == hi2s->State) - { - switch (CallbackID) - { - case HAL_I2S_TX_COMPLETE_CB_ID : - hi2s->TxCpltCallback = HAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_I2S_RX_COMPLETE_CB_ID : - hi2s->RxCpltCallback = HAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_I2S_TX_RX_COMPLETE_CB_ID : - hi2s->TxRxCpltCallback = HAL_I2SEx_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ - break; - - case HAL_I2S_TX_HALF_COMPLETE_CB_ID : - hi2s->TxHalfCpltCallback = HAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - break; - - case HAL_I2S_RX_HALF_COMPLETE_CB_ID : - hi2s->RxHalfCpltCallback = HAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - break; - - case HAL_I2S_TX_RX_HALF_COMPLETE_CB_ID : - hi2s->TxRxHalfCpltCallback = HAL_I2SEx_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ - break; - - case HAL_I2S_ERROR_CB_ID : - hi2s->ErrorCallback = HAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_I2S_MSPINIT_CB_ID : - hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_I2S_MSPDEINIT_CB_ID : - hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_I2S_STATE_RESET == hi2s->State) - { - switch (CallbackID) - { - case HAL_I2S_MSPINIT_CB_ID : - hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_I2S_MSPDEINIT_CB_ID : - hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hi2s); - return status; -} -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -/** - * @} - */ - -/** @defgroup I2S_Exported_Functions_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 are two modes 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() - (++) HAL_I2SEx_TransmitReceive() - - (#) No-Blocking mode functions with Interrupt are : - (++) HAL_I2S_Transmit_IT() - (++) HAL_I2S_Receive_IT() - (++) HAL_I2SEx_TransmitReceive_IT() - - (#) No-Blocking mode functions with DMA are : - (++) HAL_I2S_Transmit_DMA() - (++) HAL_I2S_Receive_DMA() - (++) HAL_I2SEx_TransmitReceive_DMA() - - (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (++) HAL_I2S_TxCpltCallback() - (++) HAL_I2S_RxCpltCallback() - (++) HAL_I2SEx_TxRxCpltCallback() - (++) HAL_I2S_ErrorCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Transmit an amount of data in blocking mode - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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, const uint16_t *pData, uint16_t Size, uint32_t Timeout) -{ -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->TXDR)); -#endif /* __GNUC__ */ - uint32_t tickstart; - - if ((pData == NULL) || (Size == 0UL)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY_TX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->pTxBuffPtr = (const uint16_t *)pData; - hi2s->TxXferSize = Size; - hi2s->TxXferCount = Size; - - /* Initialize fields not used in handle to zero */ - hi2s->pRxBuffPtr = NULL; - hi2s->RxXferSize = (uint16_t) 0UL; - hi2s->RxXferCount = (uint16_t) 0UL; - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - - /* Wait until TXP flag is set */ - if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXP, SET, tickstart, Timeout) != HAL_OK) - { - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_TIMEOUT; - } - - while (hi2s->TxXferCount > 0UL) - { - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - /* Transmit data in 32 Bit mode */ - hi2s->Instance->TXDR = *((const uint32_t *)hi2s->pTxBuffPtr); - hi2s->pTxBuffPtr += 2; - hi2s->TxXferCount--; - } - else - { - /* Transmit data in 16 Bit mode */ -#if defined (__GNUC__) - *ptxdr_16bits = *((const uint16_t *)hi2s->pTxBuffPtr); -#else - *((__IO uint16_t *)&hi2s->Instance->TXDR) = *((const uint16_t *)hi2s->pTxBuffPtr); -#endif /* __GNUC__ */ - - hi2s->pTxBuffPtr++; - hi2s->TxXferCount--; - } - - /* Wait until TXP flag is set */ - if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXP, SET, tickstart, Timeout) != HAL_OK) - { - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_TIMEOUT; - } - - /* Check if an underrun occurs */ - if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) - { - /* Clear underrun flag */ - __HAL_I2S_CLEAR_UDRFLAG(hi2s); - - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); - } - } - - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_OK; -} - -/** - * @brief Receive an amount of data in blocking mode - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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 continuous 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) -{ -#if defined (__GNUC__) - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->RXDR)); -#endif /* __GNUC__ */ - uint32_t tickstart; - - if ((pData == NULL) || (Size == 0UL)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY_RX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->pRxBuffPtr = pData; - hi2s->RxXferSize = Size; - hi2s->RxXferCount = Size; - - /* Initialize fields not used in handle to zero */ - hi2s->pTxBuffPtr = NULL; - hi2s->TxXferSize = (uint16_t) 0UL; - hi2s->TxXferCount = (uint16_t) 0UL; - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - /* Receive data */ - while (hi2s->RxXferCount > 0UL) - { - /* Wait until RXP flag is set */ - if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXP, SET, tickstart, Timeout) != HAL_OK) - { - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_TIMEOUT; - } - - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - /* Receive data in 32 Bit mode */ - *((uint32_t *)hi2s->pRxBuffPtr) = hi2s->Instance->RXDR; - hi2s->pRxBuffPtr += 2; - hi2s->RxXferCount--; - } - else - { - /* Receive data in 16 Bit mode */ -#if defined (__GNUC__) - *((uint16_t *)hi2s->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hi2s->pRxBuffPtr) = *((__IO uint16_t *)&hi2s->Instance->RXDR); -#endif /* __GNUC__ */ - hi2s->pRxBuffPtr++; - hi2s->RxXferCount--; - } - - /* Check if an overrun occurs */ - if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) - { - /* Clear overrun flag */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); - } - } - - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_OK; -} - -/** - * @brief Full-Duplex Transmit/Receive data in blocking mode. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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, const uint16_t *pTxData, uint16_t *pRxData, - uint16_t Size, uint32_t Timeout) -{ - uint32_t tmp_TxXferCount; - uint32_t tmp_RxXferCount; - uint32_t tickstart; - -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->TXDR)); - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->RXDR)); -#endif /* __GNUC__ */ - - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - hi2s->TxXferSize = Size; - hi2s->TxXferCount = Size; - hi2s->pTxBuffPtr = (const uint16_t *)pTxData; - hi2s->RxXferSize = Size; - hi2s->RxXferCount = Size; - hi2s->pRxBuffPtr = pRxData; - - tmp_TxXferCount = hi2s->TxXferCount; - tmp_RxXferCount = hi2s->RxXferCount; - - /* Set state and reset error code */ - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - while ((tmp_TxXferCount > 0UL) || (tmp_RxXferCount > 0UL)) - { - if ((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXP) == SET) && (tmp_TxXferCount != 0UL)) - { - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - /* Transmit data in 32 Bit mode */ - hi2s->Instance->TXDR = *((const uint32_t *)hi2s->pTxBuffPtr); - hi2s->pTxBuffPtr += 2; - tmp_TxXferCount--; - } - else - { - /* Transmit data in 16 Bit mode */ -#if defined (__GNUC__) - *ptxdr_16bits = *((const uint16_t *)hi2s->pTxBuffPtr); -#else - *((__IO uint16_t *)&hi2s->Instance->TXDR) = *((const uint16_t *)hi2s->pTxBuffPtr); -#endif /* __GNUC__ */ - - hi2s->pTxBuffPtr++; - tmp_TxXferCount--; - } - - /* Check if an underrun occurs */ - if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) - { - /* Clear underrun flag */ - __HAL_I2S_CLEAR_UDRFLAG(hi2s); - - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); - } - } - - if ((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXP) == SET) && (tmp_RxXferCount != 0UL)) - { - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - /* Receive data in 32 Bit mode */ - *((uint32_t *)hi2s->pRxBuffPtr) = hi2s->Instance->RXDR; - hi2s->pRxBuffPtr += 2; - tmp_RxXferCount--; - } - else - { - /* Receive data in 16 Bit mode */ -#if defined (__GNUC__) - *((uint16_t *)hi2s->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hi2s->pRxBuffPtr) = *((__IO uint16_t *)&hi2s->Instance->RXDR); -#endif /* __GNUC__ */ - hi2s->pRxBuffPtr++; - tmp_RxXferCount--; - } - - /* Check if an overrun occurs */ - if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) - { - /* Clear overrun flag */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); - } - } - - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Set the error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_TIMEOUT; - } - } - - hi2s->State = HAL_I2S_STATE_READY; - __HAL_UNLOCK(hi2s); - return HAL_OK; -} - -/** - * @brief Transmit an amount of data in non-blocking mode with Interrupt - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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, const uint16_t *pData, uint16_t Size) -{ - if ((pData == NULL) || (Size == 0UL)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY_TX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->pTxBuffPtr = (const uint16_t *)pData; - hi2s->TxXferSize = Size; - hi2s->TxXferCount = Size; - - /* Initialize fields not used in handle to zero */ - hi2s->pRxBuffPtr = NULL; - hi2s->RxXferSize = (uint16_t) 0UL; - hi2s->RxXferCount = (uint16_t) 0UL; - - /* Set the function for IT treatment */ - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - hi2s->TxISR = I2S_Transmit_32Bit_IT; - } - else - { - hi2s->TxISR = I2S_Transmit_16Bit_IT; - } - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Enable TXP and UDR interrupt */ - __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_UDR)); - - /* Enable TIFRE interrupt if the mode is Slave */ - if (hi2s->Init.Mode == I2S_MODE_SLAVE_TX) - { - __HAL_I2S_ENABLE_IT(hi2s, I2S_IT_FRE); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - __HAL_UNLOCK(hi2s); - return HAL_OK; -} - -/** - * @brief Receive an amount of data in non-blocking mode with Interrupt - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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-synchronization - * 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) -{ - if ((pData == NULL) || (Size == 0UL)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY_RX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->pRxBuffPtr = pData; - hi2s->RxXferSize = Size; - hi2s->RxXferCount = Size; - - /* Initialize fields not used in handle to zero */ - hi2s->pTxBuffPtr = NULL; - hi2s->TxXferSize = (uint16_t) 0UL; - hi2s->TxXferCount = (uint16_t) 0UL; - - /* Set the function for IT treatment */ - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - hi2s->RxISR = I2S_Receive_32Bit_IT; - } - else - { - hi2s->RxISR = I2S_Receive_16Bit_IT; - } - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - /* Enable RXP and ERR interrupt */ - __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_OVR)); - - /* Enable TIFRE interrupt if the mode is Slave */ - if (hi2s->Init.Mode == I2S_MODE_SLAVE_RX) - { - __HAL_I2S_ENABLE_IT(hi2s, I2S_IT_FRE); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - __HAL_UNLOCK(hi2s); - return HAL_OK; -} - -/** - * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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. - * @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, const uint16_t *pTxData, uint16_t *pRxData, - uint16_t Size) -{ - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - hi2s->pTxBuffPtr = (const uint16_t *)pTxData; - hi2s->pRxBuffPtr = pRxData; - - hi2s->TxXferSize = Size; - hi2s->TxXferCount = Size; - hi2s->RxXferSize = Size; - hi2s->RxXferCount = Size; - - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; - - - /* Set the function for IT treatment */ - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) - { - hi2s->TxISR = I2S_Transmit_32Bit_IT; - hi2s->RxISR = I2S_Receive_32Bit_IT; - } - else - { - hi2s->TxISR = I2S_Transmit_16Bit_IT; - hi2s->RxISR = I2S_Receive_16Bit_IT; - } - - /* Check if the I2S is already enabled */ - if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Enable TXP, RXP, DXP, UDR, OVR interrupts */ - __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_DXP | I2S_IT_UDR | I2S_IT_OVR)); - - /* Enable TIFRE interrupt if the mode is Slave */ - if (hi2s->Init.Mode == I2S_MODE_SLAVE_FULLDUPLEX) - { - __HAL_I2S_ENABLE_IT(hi2s, I2S_IT_FRE); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - __HAL_UNLOCK(hi2s); - return HAL_OK; - -} - -/** - * @brief Transmit an amount of data in non-blocking mode with DMA - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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, const uint16_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef errorcode; - - if ((pData == NULL) || (Size == 0UL)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY_TX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->pTxBuffPtr = (const uint16_t *)pData; - hi2s->TxXferSize = Size; - hi2s->TxXferCount = Size; - - /* Init field not used in handle to zero */ - hi2s->pRxBuffPtr = NULL; - hi2s->RxXferSize = (uint16_t)0UL; - hi2s->RxXferCount = (uint16_t)0UL; - - /* Set the I2S Tx DMA Half transfer complete callback */ - hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; - - /* Set the I2S Tx DMA transfer complete callback */ - hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; - - /* Set the DMA error callback */ - hi2s->hdmatx->XferErrorCallback = I2S_DMAError; - - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) - { - hi2s->TxXferCount = Size * 2U; - } - else - { - hi2s->TxXferCount = Size * 4U; - } - - /* Enable the Tx DMA Stream/Channel */ - if ((hi2s->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2s->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->TxXferCount; - - /* Set DMA source address */ - hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pTxBuffPtr; - - /* Set DMA destination address */ - hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->TXDR; - - errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmatx); - } - else - { - /* Update SPI error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hi2s->hdmatx, (uint32_t)hi2s->pTxBuffPtr, (uint32_t)&hi2s->Instance->TXDR, - hi2s->TxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update I2S error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - hi2s->State = HAL_I2S_STATE_READY; - - __HAL_UNLOCK(hi2s); - errorcode = HAL_ERROR; - return errorcode; - } - - /* Check if the I2S Tx request is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN)) - { - /* Enable Tx DMA Request */ - SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); - } - - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CR1, SPI_CR1_SPE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - __HAL_UNLOCK(hi2s); - return errorcode; -} - -/** - * @brief Receive an amount of data in non-blocking mode with DMA - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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) -{ - HAL_StatusTypeDef errorcode; - - if ((pData == NULL) || (Size == 0UL)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY_RX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->pRxBuffPtr = pData; - hi2s->RxXferSize = Size; - hi2s->RxXferCount = Size; - - /* Init field not used in handle to zero */ - hi2s->pTxBuffPtr = NULL; - hi2s->TxXferSize = (uint16_t)0UL; - hi2s->TxXferCount = (uint16_t)0UL; - - - /* Set the I2S Rx DMA Half transfer complete callback */ - hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; - - /* Set the I2S Rx DMA transfer complete callback */ - hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; - - /* Set the DMA error callback */ - hi2s->hdmarx->XferErrorCallback = I2S_DMAError; - - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) - { - hi2s->RxXferCount = Size * 2U; - } - else - { - hi2s->RxXferCount = Size * 4U; - } - - /* Enable the Rx DMA Stream/Channel */ - if ((hi2s->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2s->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->RxXferCount; - - /* Set DMA source address */ - hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->RXDR; - - /* Set DMA destination address */ - hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pRxBuffPtr; - - errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmarx); - } - else - { - /* Update SPI error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->RXDR, (uint32_t)hi2s->pRxBuffPtr, - hi2s->RxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update I2S error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - hi2s->State = HAL_I2S_STATE_READY; - errorcode = HAL_ERROR; - __HAL_UNLOCK(hi2s); - return errorcode; - } - - /* Check if the I2S Rx request is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN)) - { - /* Enable Rx DMA Request */ - SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); - } - - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CR1, SPI_CR1_SPE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - __HAL_UNLOCK(hi2s); - return errorcode; -} - -/** - * @brief Full-Duplex Transmit/Receive data in non-blocking mode using DMA - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @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. - * @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, const uint16_t *pTxData, uint16_t *pRxData, - uint16_t Size) -{ - HAL_StatusTypeDef errorcode; - - - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hi2s->State != HAL_I2S_STATE_READY) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2s); - - hi2s->pTxBuffPtr = (const uint16_t *)pTxData; - hi2s->pRxBuffPtr = pRxData; - - hi2s->TxXferSize = Size; - hi2s->TxXferCount = Size; - hi2s->RxXferSize = Size; - hi2s->RxXferCount = Size; - - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; - - /* Reset the Tx/Rx DMA bits */ - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); - - /* Set the I2S Rx DMA Half transfer complete callback */ - hi2s->hdmarx->XferHalfCpltCallback = I2SEx_DMATxRxHalfCplt; - - /* Set the I2S Rx DMA transfer complete callback */ - hi2s->hdmarx->XferCpltCallback = I2SEx_DMATxRxCplt; - - /* Set the I2S Rx DMA error callback */ - hi2s->hdmarx->XferErrorCallback = I2S_DMAError; - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) - { - hi2s->TxXferCount = Size * 2U; - } - else - { - hi2s->TxXferCount = Size * 4U; - } - - /* Enable the Tx DMA Stream/Channel */ - if ((hi2s->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2s->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->TxXferCount; - - /* Set DMA source address */ - hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pTxBuffPtr; - - /* Set DMA destination address */ - hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->TXDR; - - errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmatx); - } - else - { - /* Update SPI error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hi2s->hdmatx, (uint32_t)hi2s->pTxBuffPtr, (uint32_t)&hi2s->Instance->TXDR, - hi2s->TxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update I2S error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - hi2s->State = HAL_I2S_STATE_READY; - - __HAL_UNLOCK(hi2s); - errorcode = HAL_ERROR; - return errorcode; - } - - /* Check if the I2S Tx request is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN)) - { - /* Enable Tx DMA Request */ - SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); - } - - if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) - { - hi2s->RxXferCount = Size * 2U; - } - else - { - hi2s->RxXferCount = Size * 4U; - } - - /* Enable the Rx DMA Stream/Channel */ - if ((hi2s->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hi2s->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->RxXferCount; - - /* Set DMA source address */ - hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->RXDR; - - /* Set DMA destination address */ - hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pRxBuffPtr; - - errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmarx); - } - else - { - /* Update SPI error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->RXDR, (uint32_t)hi2s->pRxBuffPtr, - hi2s->RxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update I2S error code */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - hi2s->State = HAL_I2S_STATE_READY; - errorcode = HAL_ERROR; - __HAL_UNLOCK(hi2s); - return errorcode; - } - - /* Check if the I2S Rx request is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN)) - { - /* Enable Rx DMA Request */ - SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); - } - - /* Check if the I2S is already enabled */ - if (HAL_IS_BIT_CLR(hi2s->Instance->CR1, SPI_CR1_SPE)) - { - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - } - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - __HAL_UNLOCK(hi2s); - return errorcode; -} - -/** - * @brief Pauses the audio DMA Stream/Channel playing from the Media. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) -{ - /* Process Locked */ - __HAL_LOCK(hi2s); - - uint32_t tickstart; - - /* Get tick */ - tickstart = HAL_GetTick(); - - - /* Check if the I2S peripheral is in master mode */ - if (IS_I2S_MASTER(hi2s->Init.Mode)) - { - /* Check if there is a transfer on-going */ - if (HAL_IS_BIT_SET(hi2s->Instance->CR1, SPI_CR1_CSTART) == 0UL) - { - /* Set error code to no on going transfer */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_NO_OGT); - hi2s->State = HAL_I2S_STATE_READY; - - __HAL_UNLOCK(hi2s); - return HAL_ERROR; - } - - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSUSP); - - while (HAL_IS_BIT_SET(hi2s->Instance->CR1, SPI_CR1_CSTART) != 0UL) - { - if ((((HAL_GetTick() - tickstart) >= I2S_TIMEOUT) && (I2S_TIMEOUT != HAL_MAX_DELAY)) || (I2S_TIMEOUT == 0U)) - { - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2s); - - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - hi2s->State = HAL_I2S_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Disable I2S peripheral */ - __HAL_I2S_DISABLE(hi2s); - - hi2s->State = HAL_I2S_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2s); - - return HAL_OK; - } - else - { - /* Set error code to not supported */ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_NOT_SUPPORTED); - hi2s->State = HAL_I2S_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2s); - - return HAL_ERROR; - } -} - -/** - * @brief Resumes the audio DMA Stream/Channel playing from the Media. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) -{ - /* Process Locked */ - __HAL_LOCK(hi2s); - - if (hi2s->State != HAL_I2S_STATE_READY) - { - hi2s->State = HAL_I2S_STATE_READY; - - __HAL_UNLOCK(hi2s); - return HAL_ERROR; - } - - /* Set state and reset error code */ - hi2s->State = HAL_I2S_STATE_BUSY; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - - /* Enable I2S peripheral */ - __HAL_I2S_ENABLE(hi2s); - - /* Start the transfer */ - SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2s); - - return HAL_OK; -} - -/** - * @brief Stops the audio DMA Stream/Channel playing from the Media. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) -{ - HAL_StatusTypeDef errorcode = HAL_OK; - /* The Lock is not implemented on this API to allow the user application - to call the HAL I2S API under callbacks HAL_I2S_TxCpltCallback() or HAL_I2S_RxCpltCallback() - when calling HAL_DMA_Abort() API the DMA TX or RX Transfer complete interrupt is generated - and the correspond call back is executed HAL_I2S_TxCpltCallback() or HAL_I2S_RxCpltCallback() - */ - - /* Disable the I2S Tx/Rx DMA requests */ - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); - - /* Abort the I2S DMA tx Stream/Channel */ - if (hi2s->hdmatx != NULL) - { - /* Disable the I2S DMA tx Stream/Channel */ - if (HAL_OK != HAL_DMA_Abort(hi2s->hdmatx)) - { - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - errorcode = HAL_ERROR; - } - } - - /* Abort the I2S DMA rx Stream/Channel */ - if (hi2s->hdmarx != NULL) - { - /* Disable the I2S DMA rx Stream/Channel */ - if (HAL_OK != HAL_DMA_Abort(hi2s->hdmarx)) - { - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - errorcode = HAL_ERROR; - } - } - - /* Disable I2S peripheral */ - __HAL_I2S_DISABLE(hi2s); - - hi2s->State = HAL_I2S_STATE_READY; - - return errorcode; -} - -/** - * @brief This function handles I2S interrupt request. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) -{ - uint32_t i2sier = hi2s->Instance->IER; - uint32_t i2ssr = hi2s->Instance->SR; - uint32_t trigger = i2sier & i2ssr; - - if (hi2s->State == HAL_I2S_STATE_BUSY_RX) - { - /* I2S in mode Receiver ------------------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_RXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_OVR)) - { - hi2s->RxISR(hi2s); - } - - /* I2S Overrun error interrupt occurred -------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_OVR)) - { - /* Disable RXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_ERR)); - - /* Clear Overrun flag */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); - /* Call user error callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->ErrorCallback(hi2s); -#else - HAL_I2S_ErrorCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - } - - if (hi2s->State == HAL_I2S_STATE_BUSY_TX) - { - /* I2S in mode Transmitter -----------------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_TXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_UDR)) - { - hi2s->TxISR(hi2s); - } - - /* I2S Underrun error interrupt occurred --------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_UDR)) - { - /* Disable TXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_ERR)); - - /* Clear Underrun flag */ - __HAL_I2S_CLEAR_UDRFLAG(hi2s); - - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); - /* Call user error callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->ErrorCallback(hi2s); -#else - HAL_I2S_ErrorCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - } - if (hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) - { - /* I2S in mode Transmitter -----------------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_DXP)) - { - hi2s->TxISR(hi2s); - hi2s->RxISR(hi2s); - } - /* I2S in mode Receiver ------------------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_RXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_DXP)) - { - hi2s->RxISR(hi2s); - } - /* I2S in mode Transmitter -----------------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_TXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_DXP)) - { - hi2s->TxISR(hi2s); - } - - /* I2S Underrun error interrupt occurred --------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_UDR)) - { - /* Disable TXP, RXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_ERR)); - - /* Clear Underrun flag */ - __HAL_I2S_CLEAR_UDRFLAG(hi2s); - - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); - /* Call user error callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->ErrorCallback(hi2s); -#else - HAL_I2S_ErrorCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - - /* I2S Overrun error interrupt occurred -------------------------------------*/ - if (HAL_IS_BIT_SET(trigger, I2S_FLAG_OVR)) - { - /* Disable TXP, RXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_ERR)); - - /* Clear Overrun flag */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); - - /* Call user error callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->ErrorCallback(hi2s); -#else - HAL_I2S_ErrorCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Tx Transfer Half completed callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_TxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Tx Transfer completed callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_TxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer half completed callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_RxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer half completed callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2SEx_TxRxHalfCpltCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_RxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2SEx_TxRxCpltCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief I2S error callbacks - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -__weak void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2s); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2S_ErrorCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup I2S_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief Peripheral State functions - * -@verbatim - =============================================================================== - ##### Peripheral State and Errors functions ##### - =============================================================================== - [..] - This subsection permits to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the I2S state - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL state - */ -HAL_I2S_StateTypeDef HAL_I2S_GetState(const I2S_HandleTypeDef *hi2s) -{ - return hi2s->State; -} - -/** - * @brief Return the I2S error code - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval I2S Error Code - */ -uint32_t HAL_I2S_GetError(const I2S_HandleTypeDef *hi2s) -{ - return hi2s->ErrorCode; -} -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup I2S_Private_Functions - * @{ - */ -/** - * @brief DMA I2S transmit process complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* if DMA is configured in DMA_NORMAL Mode */ - if (hdma->Init.Mode == DMA_NORMAL) - { - /* Disable Tx DMA Request */ - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); - - hi2s->TxXferCount = (uint16_t) 0UL; - hi2s->State = HAL_I2S_STATE_READY; - } - /* Call user Tx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->TxCpltCallback(hi2s); -#else - HAL_I2S_TxCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2S transmit process half complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Call user Tx half complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->TxHalfCpltCallback(hi2s); -#else - HAL_I2S_TxHalfCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2S receive process complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* if DMA is configured in DMA_NORMAL Mode */ - if (hdma->Init.Mode == DMA_NORMAL) - { - /* Disable Rx DMA Request */ - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); - hi2s->RxXferCount = (uint16_t)0UL; - hi2s->State = HAL_I2S_STATE_READY; - } - /* Call user Rx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->RxCpltCallback(hi2s); -#else - HAL_I2S_RxCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2S receive process half complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Call user Rx half complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->RxHalfCpltCallback(hi2s); -#else - HAL_I2S_RxHalfCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2S transmit receive process complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2SEx_DMATxRxCplt(DMA_HandleTypeDef *hdma) -{ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* if DMA is configured in DMA_NORMAL Mode */ - if (hdma->Init.Mode == DMA_NORMAL) - { - /* Disable Tx DMA Request */ - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); - hi2s->TxXferCount = (uint16_t) 0UL; - - /* Disable Rx DMA Request */ - CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); - hi2s->RxXferCount = (uint16_t)0UL; - - /* Updated HAL State */ - hi2s->State = HAL_I2S_STATE_READY; - } - - /* Call user TxRx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U) - hi2s->TxRxCpltCallback(hi2s); -#else - HAL_I2SEx_TxRxCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2S transmit receive process half complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2SEx_DMATxRxHalfCplt(DMA_HandleTypeDef *hdma) -{ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Call user TxRx Half complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U) - hi2s->TxRxHalfCpltCallback(hi2s); -#else - HAL_I2SEx_TxRxHalfCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2S communication error callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void I2S_DMAError(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable Rx and Tx DMA Request */ - CLEAR_BIT(hi2s->Instance->CFG1, (SPI_CFG1_RXDMAEN | SPI_CFG1_TXDMAEN)); - hi2s->TxXferCount = (uint16_t) 0UL; - hi2s->RxXferCount = (uint16_t) 0UL; - - hi2s->State = HAL_I2S_STATE_READY; - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); - /* Call user error callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->ErrorCallback(hi2s); -#else - HAL_I2S_ErrorCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ -} - -/** - * @brief Manage the transmission 16-bit in Interrupt context - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -static void I2S_Transmit_16Bit_IT(I2S_HandleTypeDef *hi2s) -{ - /* Transmit data */ -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->TXDR)); - - *ptxdr_16bits = *((const uint16_t *)hi2s->pTxBuffPtr); -#else - *((__IO uint16_t *)&hi2s->Instance->TXDR) = *((const uint16_t *)hi2s->pTxBuffPtr); -#endif /* __GNUC__ */ - hi2s->pTxBuffPtr++; - hi2s->TxXferCount--; - - if (hi2s->TxXferCount == 0UL) - { - /* Disable TXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_ERR)); - - if ((hi2s->Init.Mode == I2S_MODE_SLAVE_TX) || (hi2s->Init.Mode == I2S_MODE_MASTER_TX)) - { - hi2s->State = HAL_I2S_STATE_READY; - - /* Call user Tx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->TxCpltCallback(hi2s); -#else - HAL_I2S_TxCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Manage the transmission 32-bit in Interrupt context - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -static void I2S_Transmit_32Bit_IT(I2S_HandleTypeDef *hi2s) -{ - /* Transmit data */ - hi2s->Instance->TXDR = *((const uint32_t *)hi2s->pTxBuffPtr); - hi2s->pTxBuffPtr += 2; - hi2s->TxXferCount--; - - if (hi2s->TxXferCount == 0UL) - { - /* Disable TXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_ERR)); - - if ((hi2s->Init.Mode == I2S_MODE_SLAVE_TX) || (hi2s->Init.Mode == I2S_MODE_MASTER_TX)) - { - hi2s->State = HAL_I2S_STATE_READY; - - /* Call user Tx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - hi2s->TxCpltCallback(hi2s); -#else - HAL_I2S_TxCpltCallback(hi2s); -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Manage the reception 16-bit in Interrupt context - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -static void I2S_Receive_16Bit_IT(I2S_HandleTypeDef *hi2s) -{ - /* Receive data */ -#if defined (__GNUC__) - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->RXDR)); - - *((uint16_t *)hi2s->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hi2s->pRxBuffPtr) = *((__IO uint16_t *)&hi2s->Instance->RXDR); -#endif /* __GNUC__ */ - hi2s->pRxBuffPtr++; - hi2s->RxXferCount--; - - if (hi2s->RxXferCount == 0UL) - { - if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) - { - /* Disable TXP, RXP, DXP, ERR interrupts */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_DXP | I2S_IT_ERR)); - } - else - { - /* Disable RXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_ERR)); - } - - hi2s->State = HAL_I2S_STATE_READY; - /* Call user Rx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) - { - hi2s->TxRxCpltCallback(hi2s); - } - else - { - hi2s->RxCpltCallback(hi2s); - } -#else - if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) - { - HAL_I2SEx_TxRxCpltCallback(hi2s); - } - else - { - HAL_I2S_RxCpltCallback(hi2s); - } -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Manage the reception 32-bit in Interrupt context - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval None - */ -static void I2S_Receive_32Bit_IT(I2S_HandleTypeDef *hi2s) -{ - /* Receive data */ - *((uint32_t *)hi2s->pRxBuffPtr) = hi2s->Instance->RXDR; - hi2s->pRxBuffPtr += 2; - hi2s->RxXferCount--; - - if (hi2s->RxXferCount == 0UL) - { - if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) - { - /* Disable TXP, RXP, DXP, ERR interrupts */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_DXP | I2S_IT_ERR)); - } - else - { - /* Disable RXP and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_ERR)); - } - - hi2s->State = HAL_I2S_STATE_READY; - /* Call user Rx complete callback */ -#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) - if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) - { - hi2s->TxRxCpltCallback(hi2s); - } - else - { - hi2s->RxCpltCallback(hi2s); - } -#else - if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) - { - HAL_I2SEx_TxRxCpltCallback(hi2s); - } - else - { - HAL_I2S_RxCpltCallback(hi2s); - } -#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ - } -} - -/** - * @brief This function handles I2S Communication Timeout. - * @param hi2s pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @param Flag Flag checked - * @param State Value of the flag expected - * @param Tickstart Tick start value - * @param Timeout Duration of the timeout - * @retval HAL status - */ -static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State, - uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is set to status*/ - while (((__HAL_I2S_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) >= Timeout) || (Timeout == 0UL)) - { - /* 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 */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_i2s.c + * @author MCD Application Team + * @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 + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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/Channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx Stream/Channel. + (+++) Associate the initialized 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/Channel. + + (#) 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 + __HAL_I2S_ENABLE_IT() and __HAL_I2S_DISABLE_IT() inside the transmit and receive process. + + (+@) External clock source is configured after setting correctly + the define constant EXTERNAL_CLOCK_VALUE in the stm32h7rsxx_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 I2S 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 + + *** I2S HAL driver macros list *** + =================================== + [..] + Callback registration: + + (#) The compilation flag USE_HAL_I2S_REGISTER_CALLBACKS when set to 1UL + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_I2S_RegisterCallback() to register an interrupt callback. + + Function HAL_I2S_RegisterCallback() allows to register following callbacks: + (+) TxCpltCallback : I2S Tx Completed callback + (+) RxCpltCallback : I2S Rx Completed callback + (+) TxRxCpltCallback : I2S TxRx Completed callback + (+) TxHalfCpltCallback : I2S Tx Half Completed callback + (+) RxHalfCpltCallback : I2S Rx Half Completed callback + (+) TxRxHalfCpltCallback : I2S TxRx Half Completed callback + (+) ErrorCallback : I2S Error callback + (+) MspInitCallback : I2S Msp Init callback + (+) MspDeInitCallback : I2S Msp DeInit callback + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + + (#) Use function HAL_I2S_UnRegisterCallback to reset a callback to the default + weak function. + HAL_I2S_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxCpltCallback : I2S Tx Completed callback + (+) RxCpltCallback : I2S Rx Completed callback + (+) TxRxCpltCallback : I2S TxRx Completed callback + (+) TxHalfCpltCallback : I2S Tx Half Completed callback + (+) RxHalfCpltCallback : I2S Rx Half Completed callback + (+) TxRxHalfCpltCallback : I2S TxRx Half Completed callback + (+) ErrorCallback : I2S Error callback + (+) MspInitCallback : I2S Msp Init callback + (+) MspDeInitCallback : I2S Msp DeInit callback + + By default, after the HAL_I2S_Init() and when the state is HAL_I2S_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_I2S_MasterTxCpltCallback(), HAL_I2S_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the HAL_I2S_Init()/ HAL_I2S_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the HAL_I2S_Init()/ HAL_I2S_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + + Callbacks can be registered/unregistered in HAL_I2S_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in HAL_I2S_STATE_READY or HAL_I2S_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using HAL_I2S_RegisterCallback() before calling HAL_I2S_DeInit() + or HAL_I2S_Init() function. + + When The compilation define USE_HAL_I2S_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +#ifdef HAL_I2S_MODULE_ENABLED + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup I2S I2S + * @brief I2S HAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup I2S_Private_Define I2S Private Define + * @{ + */ +#define I2S_TIMEOUT 0xFFFFUL +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup I2S_Private_Functions I2S Private Functions + * @{ + */ +static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2SEx_DMATxRxCplt(DMA_HandleTypeDef *hdma); +static void I2SEx_DMATxRxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMAError(DMA_HandleTypeDef *hdma); +static void I2S_Transmit_16Bit_IT(I2S_HandleTypeDef *hi2s); +static void I2S_Transmit_32Bit_IT(I2S_HandleTypeDef *hi2s); +static void I2S_Receive_16Bit_IT(I2S_HandleTypeDef *hi2s); +static void I2S_Receive_32Bit_IT(I2S_HandleTypeDef *hi2s); +static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State, + uint32_t Tickstart, uint32_t Timeout); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup I2S_Exported_Functions I2S Exported Functions + * @{ + */ + +/** @defgroup I2S_Exported_Functions_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 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 + + (+) Call the function HAL_I2S_DeInit() to restore the default configuration + of the selected I2Sx peripheral. + @endverbatim + * @{ + */ + +/** + * @brief Initializes the I2S according to the specified parameters + * in the I2S_InitTypeDef and create the associated handle. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) +{ + uint32_t i2sdiv; + uint32_t i2sodd; + uint32_t packetlength; + uint32_t tmp; + uint32_t i2sclk; + uint32_t ispcm; + + /* Check the I2S handle allocation */ + if (hi2s == NULL) + { + return HAL_ERROR; + } + + /* Check the I2S parameters */ + assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance)); + 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_FIRST_BIT(hi2s->Init.FirstBit)); + assert_param(IS_I2S_WS_INVERSION(hi2s->Init.WSInversion)); + assert_param(IS_I2S_DATA_24BIT_ALIGNMENT(hi2s->Init.Data24BitAlignment)); + assert_param(IS_I2S_MASTER_KEEP_IO_STATE(hi2s->Init.MasterKeepIOState)); + + if (hi2s->State == HAL_I2S_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hi2s->Lock = HAL_UNLOCKED; + +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + /* Init the I2S Callback settings */ + hi2s->TxCpltCallback = HAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hi2s->RxCpltCallback = HAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hi2s->TxRxCpltCallback = HAL_I2SEx_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + hi2s->TxHalfCpltCallback = HAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + hi2s->RxHalfCpltCallback = HAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + hi2s->TxRxHalfCpltCallback = HAL_I2SEx_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + hi2s->ErrorCallback = HAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hi2s->MspInitCallback == NULL) + { + hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + hi2s->MspInitCallback(hi2s); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I2S_MspInit(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + + hi2s->State = HAL_I2S_STATE_BUSY; + + /* Disable the selected I2S peripheral */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) == SPI_CR1_SPE) + { + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + } + + /* Clear I2S configuration register */ + CLEAR_REG(hi2s->Instance->I2SCFGR); + + if (IS_I2S_MASTER(hi2s->Init.Mode)) + { + /*------------------------- I2SDIV and ODD Calculation ---------------------*/ + /* 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) + { + /* Channel length is 32 bits */ + packetlength = 2UL; + } + else + { + /* Channel length is 16 bits */ + packetlength = 1UL; + } + + /* Check if PCM standard is used */ + if ((hi2s->Init.Standard == I2S_STANDARD_PCM_SHORT) || + (hi2s->Init.Standard == I2S_STANDARD_PCM_LONG)) + { + ispcm = 1UL; + } + else + { + ispcm = 0UL; + } + + /* Get the source clock value: based on System Clock value */ + if (hi2s->Instance == SPI1) + { + i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI1); + } + else if ((hi2s->Instance == SPI2) || (hi2s->Instance == SPI3)) + { + i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI23); + } + else /* SPI6 source clock */ + { + i2sclk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI6); + } + + /* 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 / (256UL >> ispcm)) * 10UL) / hi2s->Init.AudioFreq) + 5UL); + } + else + { + /* MCLK output is disabled */ + tmp = (uint32_t)((((i2sclk / ((32UL >> ispcm) * packetlength)) * 10UL) / hi2s->Init.AudioFreq) + 5UL); + } + + /* Remove the flatting point */ + tmp = tmp / 10UL; + + /* Check the parity of the divider */ + i2sodd = (uint32_t)(tmp & (uint32_t)1UL); + + /* Compute the i2sdiv prescaler */ + i2sdiv = (uint32_t)((tmp - i2sodd) / 2UL); + } + else + { + /* Set the default values */ + i2sdiv = 2UL; + i2sodd = 0UL; + } + + /* Test if the obtain values are forbidden or out of range */ + if (((i2sodd == 1UL) && (i2sdiv == 1UL)) || (i2sdiv > 0xFFUL)) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_PRESCALER); + return HAL_ERROR; + } + + /* Force i2smod to 1 just to be sure that (2xi2sdiv + i2sodd) is always higher than 0 */ + if (i2sdiv == 0UL) + { + i2sodd = 1UL; + } + + MODIFY_REG(hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_I2SDIV | SPI_I2SCFGR_ODD), + ((i2sdiv << SPI_I2SCFGR_I2SDIV_Pos) | (i2sodd << SPI_I2SCFGR_ODD_Pos))); + } + + /*-------------------------- I2Sx I2SCFGR Configuration --------------------*/ + /* Configure I2SMOD, I2SCFG, I2SSTD, PCMSYNC, DATLEN ,CHLEN ,CKPOL, WSINV, DATAFMT, I2SDIV, ODD and MCKOE bits bits */ + /* And configure the I2S with the I2S_InitStruct values */ + MODIFY_REG(hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_I2SMOD | SPI_I2SCFGR_I2SCFG | \ + SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | \ + SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN | \ + SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_WSINV | \ + SPI_I2SCFGR_DATFMT | SPI_I2SCFGR_MCKOE), + (SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | \ + hi2s->Init.Standard | hi2s->Init.DataFormat | \ + hi2s->Init.CPOL | hi2s->Init.WSInversion | \ + hi2s->Init.Data24BitAlignment | hi2s->Init.MCLKOutput)); + /*Clear status register*/ + WRITE_REG(hi2s->Instance->IFCR, 0x0FF8); + + /*---------------------------- I2Sx CFG2 Configuration ----------------------*/ + + /* Unlock the AF configuration to configure CFG2 register*/ + CLEAR_BIT(hi2s->Instance->CR1, SPI_CR1_IOLOCK); + + MODIFY_REG(hi2s->Instance->CFG2, SPI_CFG2_LSBFRST, hi2s->Init.FirstBit); + + /* Insure that AFCNTR is managed only by Master */ + if (IS_I2S_MASTER(hi2s->Init.Mode)) + { + /* Alternate function GPIOs control */ + MODIFY_REG(hi2s->Instance->CFG2, SPI_CFG2_AFCNTR, (hi2s->Init.MasterKeepIOState)); + } + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the I2S peripheral + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) +{ + /* Check the I2S handle allocation */ + if (hi2s == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance)); + + hi2s->State = HAL_I2S_STATE_BUSY; + + /* Disable the I2S Peripheral Clock */ + __HAL_I2S_DISABLE(hi2s); + +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + if (hi2s->MspDeInitCallback == NULL) + { + hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + hi2s->MspDeInitCallback(hi2s); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_I2S_MspDeInit(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** + * @brief I2S MSP Init + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_MspInit could be implemented in the user file + */ +} + +/** + * @brief I2S MSP DeInit + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) +/** + * @brief Register a User I2S Callback + * To be used instead of the weak predefined callback + * @param hi2s Pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for the specified I2S. + * @param CallbackID ID of the callback to be registered + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_RegisterCallback(I2S_HandleTypeDef *hi2s, HAL_I2S_CallbackIDTypeDef CallbackID, + pI2S_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hi2s->ErrorCode |= HAL_I2S_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hi2s); + + if (HAL_I2S_STATE_READY == hi2s->State) + { + switch (CallbackID) + { + case HAL_I2S_TX_COMPLETE_CB_ID : + hi2s->TxCpltCallback = pCallback; + break; + + case HAL_I2S_RX_COMPLETE_CB_ID : + hi2s->RxCpltCallback = pCallback; + break; + + case HAL_I2S_TX_RX_COMPLETE_CB_ID : + hi2s->TxRxCpltCallback = pCallback; + break; + + case HAL_I2S_TX_HALF_COMPLETE_CB_ID : + hi2s->TxHalfCpltCallback = pCallback; + break; + + case HAL_I2S_RX_HALF_COMPLETE_CB_ID : + hi2s->RxHalfCpltCallback = pCallback; + break; + + + case HAL_I2S_TX_RX_HALF_COMPLETE_CB_ID : + hi2s->TxRxHalfCpltCallback = pCallback; + break; + + case HAL_I2S_ERROR_CB_ID : + hi2s->ErrorCallback = pCallback; + break; + + case HAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = pCallback; + break; + + case HAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_I2S_STATE_RESET == hi2s->State) + { + switch (CallbackID) + { + case HAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = pCallback; + break; + + case HAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hi2s); + return status; +} + +/** + * @brief Unregister an I2S Callback + * I2S callback is redirected to the weak predefined callback + * @param hi2s Pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for the specified I2S. + * @param CallbackID ID of the callback to be unregistered + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_UnRegisterCallback(I2S_HandleTypeDef *hi2s, HAL_I2S_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hi2s); + + if (HAL_I2S_STATE_READY == hi2s->State) + { + switch (CallbackID) + { + case HAL_I2S_TX_COMPLETE_CB_ID : + hi2s->TxCpltCallback = HAL_I2S_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_I2S_RX_COMPLETE_CB_ID : + hi2s->RxCpltCallback = HAL_I2S_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_I2S_TX_RX_COMPLETE_CB_ID : + hi2s->TxRxCpltCallback = HAL_I2SEx_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + break; + + case HAL_I2S_TX_HALF_COMPLETE_CB_ID : + hi2s->TxHalfCpltCallback = HAL_I2S_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case HAL_I2S_RX_HALF_COMPLETE_CB_ID : + hi2s->RxHalfCpltCallback = HAL_I2S_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case HAL_I2S_TX_RX_HALF_COMPLETE_CB_ID : + hi2s->TxRxHalfCpltCallback = HAL_I2SEx_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + break; + + case HAL_I2S_ERROR_CB_ID : + hi2s->ErrorCallback = HAL_I2S_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_I2S_STATE_RESET == hi2s->State) + { + switch (CallbackID) + { + case HAL_I2S_MSPINIT_CB_ID : + hi2s->MspInitCallback = HAL_I2S_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_I2S_MSPDEINIT_CB_ID : + hi2s->MspDeInitCallback = HAL_I2S_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hi2s); + return status; +} +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup I2S_Exported_Functions_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 are two modes 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() + (++) HAL_I2SEx_TransmitReceive() + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_I2S_Transmit_IT() + (++) HAL_I2S_Receive_IT() + (++) HAL_I2SEx_TransmitReceive_IT() + + (#) No-Blocking mode functions with DMA are : + (++) HAL_I2S_Transmit_DMA() + (++) HAL_I2S_Receive_DMA() + (++) HAL_I2SEx_TransmitReceive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) HAL_I2S_TxCpltCallback() + (++) HAL_I2S_RxCpltCallback() + (++) HAL_I2SEx_TxRxCpltCallback() + (++) HAL_I2S_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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, const uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->TXDR)); +#endif /* __GNUC__ */ + uint32_t tickstart; + + if ((pData == NULL) || (Size == 0UL)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->pTxBuffPtr = (const uint16_t *)pData; + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + + /* Initialize fields not used in handle to zero */ + hi2s->pRxBuffPtr = NULL; + hi2s->RxXferSize = (uint16_t) 0UL; + hi2s->RxXferCount = (uint16_t) 0UL; + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + + /* Wait until TXP flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXP, SET, tickstart, Timeout) != HAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_TIMEOUT; + } + + while (hi2s->TxXferCount > 0UL) + { + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + /* Transmit data in 32 Bit mode */ + hi2s->Instance->TXDR = *((const uint32_t *)hi2s->pTxBuffPtr); + hi2s->pTxBuffPtr += 2; + hi2s->TxXferCount--; + } + else + { + /* Transmit data in 16 Bit mode */ +#if defined (__GNUC__) + *ptxdr_16bits = *((const uint16_t *)hi2s->pTxBuffPtr); +#else + *((__IO uint16_t *)&hi2s->Instance->TXDR) = *((const uint16_t *)hi2s->pTxBuffPtr); +#endif /* __GNUC__ */ + + hi2s->pTxBuffPtr++; + hi2s->TxXferCount--; + } + + /* Wait until TXP flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXP, SET, tickstart, Timeout) != HAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_TIMEOUT; + } + + /* Check if an underrun occurs */ + if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) + { + /* Clear underrun flag */ + __HAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); + } + } + + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_OK; +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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 continuous 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) +{ +#if defined (__GNUC__) + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->RXDR)); +#endif /* __GNUC__ */ + uint32_t tickstart; + + if ((pData == NULL) || (Size == 0UL)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->pRxBuffPtr = pData; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + + /* Initialize fields not used in handle to zero */ + hi2s->pTxBuffPtr = NULL; + hi2s->TxXferSize = (uint16_t) 0UL; + hi2s->TxXferCount = (uint16_t) 0UL; + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + /* Receive data */ + while (hi2s->RxXferCount > 0UL) + { + /* Wait until RXP flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXP, SET, tickstart, Timeout) != HAL_OK) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_TIMEOUT; + } + + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + /* Receive data in 32 Bit mode */ + *((uint32_t *)hi2s->pRxBuffPtr) = hi2s->Instance->RXDR; + hi2s->pRxBuffPtr += 2; + hi2s->RxXferCount--; + } + else + { + /* Receive data in 16 Bit mode */ +#if defined (__GNUC__) + *((uint16_t *)hi2s->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hi2s->pRxBuffPtr) = *((__IO uint16_t *)&hi2s->Instance->RXDR); +#endif /* __GNUC__ */ + hi2s->pRxBuffPtr++; + hi2s->RxXferCount--; + } + + /* Check if an overrun occurs */ + if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + { + /* Clear overrun flag */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); + } + } + + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_OK; +} + +/** + * @brief Full-Duplex Transmit/Receive data in blocking mode. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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, const uint16_t *pTxData, uint16_t *pRxData, + uint16_t Size, uint32_t Timeout) +{ + uint32_t tmp_TxXferCount; + uint32_t tmp_RxXferCount; + uint32_t tickstart; + +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->TXDR)); + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->RXDR)); +#endif /* __GNUC__ */ + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + hi2s->pTxBuffPtr = (const uint16_t *)pTxData; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + hi2s->pRxBuffPtr = pRxData; + + tmp_TxXferCount = hi2s->TxXferCount; + tmp_RxXferCount = hi2s->RxXferCount; + + /* Set state and reset error code */ + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + while ((tmp_TxXferCount > 0UL) || (tmp_RxXferCount > 0UL)) + { + if ((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXP) == SET) && (tmp_TxXferCount != 0UL)) + { + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + /* Transmit data in 32 Bit mode */ + hi2s->Instance->TXDR = *((const uint32_t *)hi2s->pTxBuffPtr); + hi2s->pTxBuffPtr += 2; + tmp_TxXferCount--; + } + else + { + /* Transmit data in 16 Bit mode */ +#if defined (__GNUC__) + *ptxdr_16bits = *((const uint16_t *)hi2s->pTxBuffPtr); +#else + *((__IO uint16_t *)&hi2s->Instance->TXDR) = *((const uint16_t *)hi2s->pTxBuffPtr); +#endif /* __GNUC__ */ + + hi2s->pTxBuffPtr++; + tmp_TxXferCount--; + } + + /* Check if an underrun occurs */ + if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) + { + /* Clear underrun flag */ + __HAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); + } + } + + if ((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXP) == SET) && (tmp_RxXferCount != 0UL)) + { + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + /* Receive data in 32 Bit mode */ + *((uint32_t *)hi2s->pRxBuffPtr) = hi2s->Instance->RXDR; + hi2s->pRxBuffPtr += 2; + tmp_RxXferCount--; + } + else + { + /* Receive data in 16 Bit mode */ +#if defined (__GNUC__) + *((uint16_t *)hi2s->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hi2s->pRxBuffPtr) = *((__IO uint16_t *)&hi2s->Instance->RXDR); +#endif /* __GNUC__ */ + hi2s->pRxBuffPtr++; + tmp_RxXferCount--; + } + + /* Check if an overrun occurs */ + if (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + { + /* Clear overrun flag */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); + } + } + + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Set the error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_TIMEOUT; + } + } + + hi2s->State = HAL_I2S_STATE_READY; + __HAL_UNLOCK(hi2s); + return HAL_OK; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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, const uint16_t *pData, uint16_t Size) +{ + if ((pData == NULL) || (Size == 0UL)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->pTxBuffPtr = (const uint16_t *)pData; + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + + /* Initialize fields not used in handle to zero */ + hi2s->pRxBuffPtr = NULL; + hi2s->RxXferSize = (uint16_t) 0UL; + hi2s->RxXferCount = (uint16_t) 0UL; + + /* Set the function for IT treatment */ + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + hi2s->TxISR = I2S_Transmit_32Bit_IT; + } + else + { + hi2s->TxISR = I2S_Transmit_16Bit_IT; + } + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Enable TXP and UDR interrupt */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_UDR)); + + /* Enable TIFRE interrupt if the mode is Slave */ + if (hi2s->Init.Mode == I2S_MODE_SLAVE_TX) + { + __HAL_I2S_ENABLE_IT(hi2s, I2S_IT_FRE); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + __HAL_UNLOCK(hi2s); + return HAL_OK; +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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-synchronization + * 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) +{ + if ((pData == NULL) || (Size == 0UL)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->pRxBuffPtr = pData; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + + /* Initialize fields not used in handle to zero */ + hi2s->pTxBuffPtr = NULL; + hi2s->TxXferSize = (uint16_t) 0UL; + hi2s->TxXferCount = (uint16_t) 0UL; + + /* Set the function for IT treatment */ + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + hi2s->RxISR = I2S_Receive_32Bit_IT; + } + else + { + hi2s->RxISR = I2S_Receive_16Bit_IT; + } + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + /* Enable RXP and ERR interrupt */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_OVR)); + + /* Enable TIFRE interrupt if the mode is Slave */ + if (hi2s->Init.Mode == I2S_MODE_SLAVE_RX) + { + __HAL_I2S_ENABLE_IT(hi2s, I2S_IT_FRE); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + __HAL_UNLOCK(hi2s); + return HAL_OK; +} + +/** + * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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. + * @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, const uint16_t *pTxData, uint16_t *pRxData, + uint16_t Size) +{ + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->pTxBuffPtr = (const uint16_t *)pTxData; + hi2s->pRxBuffPtr = pRxData; + + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; + + + /* Set the function for IT treatment */ + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_24B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_32B)) + { + hi2s->TxISR = I2S_Transmit_32Bit_IT; + hi2s->RxISR = I2S_Receive_32Bit_IT; + } + else + { + hi2s->TxISR = I2S_Transmit_16Bit_IT; + hi2s->RxISR = I2S_Receive_16Bit_IT; + } + + /* Check if the I2S is already enabled */ + if ((hi2s->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Enable TXP, RXP, DXP, UDR, OVR interrupts */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_DXP | I2S_IT_UDR | I2S_IT_OVR)); + + /* Enable TIFRE interrupt if the mode is Slave */ + if (hi2s->Init.Mode == I2S_MODE_SLAVE_FULLDUPLEX) + { + __HAL_I2S_ENABLE_IT(hi2s, I2S_IT_FRE); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + __HAL_UNLOCK(hi2s); + return HAL_OK; + +} + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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, const uint16_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef errorcode; + + if ((pData == NULL) || (Size == 0UL)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->pTxBuffPtr = (const uint16_t *)pData; + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + + /* Init field not used in handle to zero */ + hi2s->pRxBuffPtr = NULL; + hi2s->RxXferSize = (uint16_t)0UL; + hi2s->RxXferCount = (uint16_t)0UL; + + /* Set the I2S Tx DMA Half transfer complete callback */ + hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; + + /* Set the I2S Tx DMA transfer complete callback */ + hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; + + /* Set the DMA error callback */ + hi2s->hdmatx->XferErrorCallback = I2S_DMAError; + + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) + { + hi2s->TxXferCount = Size * 2U; + } + else + { + hi2s->TxXferCount = Size * 4U; + } + + /* Enable the Tx DMA Stream/Channel */ + if ((hi2s->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2s->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->TxXferCount; + + /* Set DMA source address */ + hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pTxBuffPtr; + + /* Set DMA destination address */ + hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->TXDR; + + errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmatx); + } + else + { + /* Update SPI error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hi2s->hdmatx, (uint32_t)hi2s->pTxBuffPtr, (uint32_t)&hi2s->Instance->TXDR, + hi2s->TxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update I2S error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + hi2s->State = HAL_I2S_STATE_READY; + + __HAL_UNLOCK(hi2s); + errorcode = HAL_ERROR; + return errorcode; + } + + /* Check if the I2S Tx request is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN)) + { + /* Enable Tx DMA Request */ + SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); + } + + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CR1, SPI_CR1_SPE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + __HAL_UNLOCK(hi2s); + return errorcode; +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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) +{ + HAL_StatusTypeDef errorcode; + + if ((pData == NULL) || (Size == 0UL)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->pRxBuffPtr = pData; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + + /* Init field not used in handle to zero */ + hi2s->pTxBuffPtr = NULL; + hi2s->TxXferSize = (uint16_t)0UL; + hi2s->TxXferCount = (uint16_t)0UL; + + + /* Set the I2S Rx DMA Half transfer complete callback */ + hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; + + /* Set the I2S Rx DMA transfer complete callback */ + hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; + + /* Set the DMA error callback */ + hi2s->hdmarx->XferErrorCallback = I2S_DMAError; + + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) + { + hi2s->RxXferCount = Size * 2U; + } + else + { + hi2s->RxXferCount = Size * 4U; + } + + /* Enable the Rx DMA Stream/Channel */ + if ((hi2s->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2s->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->RxXferCount; + + /* Set DMA source address */ + hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->RXDR; + + /* Set DMA destination address */ + hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pRxBuffPtr; + + errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmarx); + } + else + { + /* Update SPI error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->RXDR, (uint32_t)hi2s->pRxBuffPtr, + hi2s->RxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update I2S error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + hi2s->State = HAL_I2S_STATE_READY; + errorcode = HAL_ERROR; + __HAL_UNLOCK(hi2s); + return errorcode; + } + + /* Check if the I2S Rx request is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN)) + { + /* Enable Rx DMA Request */ + SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); + } + + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CR1, SPI_CR1_SPE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + __HAL_UNLOCK(hi2s); + return errorcode; +} + +/** + * @brief Full-Duplex Transmit/Receive data in non-blocking mode using DMA + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @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. + * @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, const uint16_t *pTxData, uint16_t *pRxData, + uint16_t Size) +{ + HAL_StatusTypeDef errorcode; + + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hi2s->State != HAL_I2S_STATE_READY) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->pTxBuffPtr = (const uint16_t *)pTxData; + hi2s->pRxBuffPtr = pRxData; + + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; + + /* Reset the Tx/Rx DMA bits */ + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); + + /* Set the I2S Rx DMA Half transfer complete callback */ + hi2s->hdmarx->XferHalfCpltCallback = I2SEx_DMATxRxHalfCplt; + + /* Set the I2S Rx DMA transfer complete callback */ + hi2s->hdmarx->XferCpltCallback = I2SEx_DMATxRxCplt; + + /* Set the I2S Rx DMA error callback */ + hi2s->hdmarx->XferErrorCallback = I2S_DMAError; + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) + { + hi2s->TxXferCount = Size * 2U; + } + else + { + hi2s->TxXferCount = Size * 4U; + } + + /* Enable the Tx DMA Stream/Channel */ + if ((hi2s->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2s->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->TxXferCount; + + /* Set DMA source address */ + hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pTxBuffPtr; + + /* Set DMA destination address */ + hi2s->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->TXDR; + + errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmatx); + } + else + { + /* Update SPI error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hi2s->hdmatx, (uint32_t)hi2s->pTxBuffPtr, (uint32_t)&hi2s->Instance->TXDR, + hi2s->TxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update I2S error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + hi2s->State = HAL_I2S_STATE_READY; + + __HAL_UNLOCK(hi2s); + errorcode = HAL_ERROR; + return errorcode; + } + + /* Check if the I2S Tx request is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN)) + { + /* Enable Tx DMA Request */ + SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); + } + + if ((hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) || (hi2s->Init.DataFormat == I2S_DATAFORMAT_16B_EXTENDED)) + { + hi2s->RxXferCount = Size * 2U; + } + else + { + hi2s->RxXferCount = Size * 4U; + } + + /* Enable the Rx DMA Stream/Channel */ + if ((hi2s->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hi2s->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hi2s->RxXferCount; + + /* Set DMA source address */ + hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hi2s->Instance->RXDR; + + /* Set DMA destination address */ + hi2s->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hi2s->pRxBuffPtr; + + errorcode = HAL_DMAEx_List_Start_IT(hi2s->hdmarx); + } + else + { + /* Update SPI error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->RXDR, (uint32_t)hi2s->pRxBuffPtr, + hi2s->RxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update I2S error code */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + hi2s->State = HAL_I2S_STATE_READY; + errorcode = HAL_ERROR; + __HAL_UNLOCK(hi2s); + return errorcode; + } + + /* Check if the I2S Rx request is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN)) + { + /* Enable Rx DMA Request */ + SET_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); + } + + /* Check if the I2S is already enabled */ + if (HAL_IS_BIT_CLR(hi2s->Instance->CR1, SPI_CR1_SPE)) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + __HAL_UNLOCK(hi2s); + return errorcode; +} + +/** + * @brief Pauses the audio DMA Stream/Channel playing from the Media. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + uint32_t tickstart; + + /* Get tick */ + tickstart = HAL_GetTick(); + + + /* Check if the I2S peripheral is in master mode */ + if (IS_I2S_MASTER(hi2s->Init.Mode)) + { + /* Check if there is a transfer on-going */ + if (HAL_IS_BIT_SET(hi2s->Instance->CR1, SPI_CR1_CSTART) == 0UL) + { + /* Set error code to no on going transfer */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_NO_OGT); + hi2s->State = HAL_I2S_STATE_READY; + + __HAL_UNLOCK(hi2s); + return HAL_ERROR; + } + + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSUSP); + + while (HAL_IS_BIT_SET(hi2s->Instance->CR1, SPI_CR1_CSTART) != 0UL) + { + if ((((HAL_GetTick() - tickstart) >= I2S_TIMEOUT) && (I2S_TIMEOUT != HAL_MAX_DELAY)) || (I2S_TIMEOUT == 0U)) + { + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); + hi2s->State = HAL_I2S_STATE_READY; + return HAL_TIMEOUT; + } + } + + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + /* Set error code to not supported */ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_NOT_SUPPORTED); + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_ERROR; + } +} + +/** + * @brief Resumes the audio DMA Stream/Channel playing from the Media. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + if (hi2s->State != HAL_I2S_STATE_READY) + { + hi2s->State = HAL_I2S_STATE_READY; + + __HAL_UNLOCK(hi2s); + return HAL_ERROR; + } + + /* Set state and reset error code */ + hi2s->State = HAL_I2S_STATE_BUSY; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + + /* Start the transfer */ + SET_BIT(hi2s->Instance->CR1, SPI_CR1_CSTART); + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** + * @brief Stops the audio DMA Stream/Channel playing from the Media. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) +{ + HAL_StatusTypeDef errorcode = HAL_OK; + /* The Lock is not implemented on this API to allow the user application + to call the HAL I2S API under callbacks HAL_I2S_TxCpltCallback() or HAL_I2S_RxCpltCallback() + when calling HAL_DMA_Abort() API the DMA TX or RX Transfer complete interrupt is generated + and the correspond call back is executed HAL_I2S_TxCpltCallback() or HAL_I2S_RxCpltCallback() + */ + + /* Disable the I2S Tx/Rx DMA requests */ + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); + + /* Abort the I2S DMA tx Stream/Channel */ + if (hi2s->hdmatx != NULL) + { + /* Disable the I2S DMA tx Stream/Channel */ + if (HAL_OK != HAL_DMA_Abort(hi2s->hdmatx)) + { + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + errorcode = HAL_ERROR; + } + } + + /* Abort the I2S DMA rx Stream/Channel */ + if (hi2s->hdmarx != NULL) + { + /* Disable the I2S DMA rx Stream/Channel */ + if (HAL_OK != HAL_DMA_Abort(hi2s->hdmarx)) + { + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + errorcode = HAL_ERROR; + } + } + + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + + return errorcode; +} + +/** + * @brief This function handles I2S interrupt request. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) +{ + uint32_t i2sier = hi2s->Instance->IER; + uint32_t i2ssr = hi2s->Instance->SR; + uint32_t trigger = i2sier & i2ssr; + + if (hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + /* I2S in mode Receiver ------------------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_RXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_OVR)) + { + hi2s->RxISR(hi2s); + } + + /* I2S Overrun error interrupt occurred -------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_OVR)) + { + /* Disable RXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_ERR)); + + /* Clear Overrun flag */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); + /* Call user error callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->ErrorCallback(hi2s); +#else + HAL_I2S_ErrorCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + } + + if (hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + /* I2S in mode Transmitter -----------------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_TXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_UDR)) + { + hi2s->TxISR(hi2s); + } + + /* I2S Underrun error interrupt occurred --------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_UDR)) + { + /* Disable TXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_ERR)); + + /* Clear Underrun flag */ + __HAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); + /* Call user error callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->ErrorCallback(hi2s); +#else + HAL_I2S_ErrorCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + } + if (hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) + { + /* I2S in mode Transmitter -----------------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_DXP)) + { + hi2s->TxISR(hi2s); + hi2s->RxISR(hi2s); + } + /* I2S in mode Receiver ------------------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_RXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_DXP)) + { + hi2s->RxISR(hi2s); + } + /* I2S in mode Transmitter -----------------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_TXP) && HAL_IS_BIT_CLR(trigger, I2S_FLAG_DXP)) + { + hi2s->TxISR(hi2s); + } + + /* I2S Underrun error interrupt occurred --------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_UDR)) + { + /* Disable TXP, RXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_ERR)); + + /* Clear Underrun flag */ + __HAL_I2S_CLEAR_UDRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); + /* Call user error callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->ErrorCallback(hi2s); +#else + HAL_I2S_ErrorCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + + /* I2S Overrun error interrupt occurred -------------------------------------*/ + if (HAL_IS_BIT_SET(trigger, I2S_FLAG_OVR)) + { + /* Disable TXP, RXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_ERR)); + + /* Clear Overrun flag */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); + + /* Call user error callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->ErrorCallback(hi2s); +#else + HAL_I2S_ErrorCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Tx Transfer Half completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Transfer completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer half completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer half completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2SEx_TxRxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2SEx_TxRxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief I2S error callbacks + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi2s); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2S_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the I2S state + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL state + */ +HAL_I2S_StateTypeDef HAL_I2S_GetState(const I2S_HandleTypeDef *hi2s) +{ + return hi2s->State; +} + +/** + * @brief Return the I2S error code + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval I2S Error Code + */ +uint32_t HAL_I2S_GetError(const I2S_HandleTypeDef *hi2s) +{ + return hi2s->ErrorCode; +} +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup I2S_Private_Functions + * @{ + */ +/** + * @brief DMA I2S transmit process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* if DMA is configured in DMA_NORMAL Mode */ + if (hdma->Init.Mode == DMA_NORMAL) + { + /* Disable Tx DMA Request */ + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); + + hi2s->TxXferCount = (uint16_t) 0UL; + hi2s->State = HAL_I2S_STATE_READY; + } + /* Call user Tx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->TxCpltCallback(hi2s); +#else + HAL_I2S_TxCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S transmit process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Call user Tx half complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->TxHalfCpltCallback(hi2s); +#else + HAL_I2S_TxHalfCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S receive process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* if DMA is configured in DMA_NORMAL Mode */ + if (hdma->Init.Mode == DMA_NORMAL) + { + /* Disable Rx DMA Request */ + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); + hi2s->RxXferCount = (uint16_t)0UL; + hi2s->State = HAL_I2S_STATE_READY; + } + /* Call user Rx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->RxCpltCallback(hi2s); +#else + HAL_I2S_RxCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S receive process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Call user Rx half complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->RxHalfCpltCallback(hi2s); +#else + HAL_I2S_RxHalfCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S transmit receive process complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2SEx_DMATxRxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* if DMA is configured in DMA_NORMAL Mode */ + if (hdma->Init.Mode == DMA_NORMAL) + { + /* Disable Tx DMA Request */ + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_TXDMAEN); + hi2s->TxXferCount = (uint16_t) 0UL; + + /* Disable Rx DMA Request */ + CLEAR_BIT(hi2s->Instance->CFG1, SPI_CFG1_RXDMAEN); + hi2s->RxXferCount = (uint16_t)0UL; + + /* Updated HAL State */ + hi2s->State = HAL_I2S_STATE_READY; + } + + /* Call user TxRx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxCpltCallback(hi2s); +#else + HAL_I2SEx_TxRxCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S transmit receive process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2SEx_DMATxRxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Call user TxRx Half complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1U) + hi2s->TxRxHalfCpltCallback(hi2s); +#else + HAL_I2SEx_TxRxHalfCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA I2S communication error callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void I2S_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I2S_HandleTypeDef *hi2s = (I2S_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable Rx and Tx DMA Request */ + CLEAR_BIT(hi2s->Instance->CFG1, (SPI_CFG1_RXDMAEN | SPI_CFG1_TXDMAEN)); + hi2s->TxXferCount = (uint16_t) 0UL; + hi2s->RxXferCount = (uint16_t) 0UL; + + hi2s->State = HAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); + /* Call user error callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->ErrorCallback(hi2s); +#else + HAL_I2S_ErrorCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ +} + +/** + * @brief Manage the transmission 16-bit in Interrupt context + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_Transmit_16Bit_IT(I2S_HandleTypeDef *hi2s) +{ + /* Transmit data */ +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->TXDR)); + + *ptxdr_16bits = *((const uint16_t *)hi2s->pTxBuffPtr); +#else + *((__IO uint16_t *)&hi2s->Instance->TXDR) = *((const uint16_t *)hi2s->pTxBuffPtr); +#endif /* __GNUC__ */ + hi2s->pTxBuffPtr++; + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0UL) + { + /* Disable TXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_ERR)); + + if ((hi2s->Init.Mode == I2S_MODE_SLAVE_TX) || (hi2s->Init.Mode == I2S_MODE_MASTER_TX)) + { + hi2s->State = HAL_I2S_STATE_READY; + + /* Call user Tx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->TxCpltCallback(hi2s); +#else + HAL_I2S_TxCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Manage the transmission 32-bit in Interrupt context + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_Transmit_32Bit_IT(I2S_HandleTypeDef *hi2s) +{ + /* Transmit data */ + hi2s->Instance->TXDR = *((const uint32_t *)hi2s->pTxBuffPtr); + hi2s->pTxBuffPtr += 2; + hi2s->TxXferCount--; + + if (hi2s->TxXferCount == 0UL) + { + /* Disable TXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_ERR)); + + if ((hi2s->Init.Mode == I2S_MODE_SLAVE_TX) || (hi2s->Init.Mode == I2S_MODE_MASTER_TX)) + { + hi2s->State = HAL_I2S_STATE_READY; + + /* Call user Tx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + hi2s->TxCpltCallback(hi2s); +#else + HAL_I2S_TxCpltCallback(hi2s); +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Manage the reception 16-bit in Interrupt context + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_Receive_16Bit_IT(I2S_HandleTypeDef *hi2s) +{ + /* Receive data */ +#if defined (__GNUC__) + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hi2s->Instance->RXDR)); + + *((uint16_t *)hi2s->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hi2s->pRxBuffPtr) = *((__IO uint16_t *)&hi2s->Instance->RXDR); +#endif /* __GNUC__ */ + hi2s->pRxBuffPtr++; + hi2s->RxXferCount--; + + if (hi2s->RxXferCount == 0UL) + { + if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) + { + /* Disable TXP, RXP, DXP, ERR interrupts */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_DXP | I2S_IT_ERR)); + } + else + { + /* Disable RXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_ERR)); + } + + hi2s->State = HAL_I2S_STATE_READY; + /* Call user Rx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) + { + hi2s->TxRxCpltCallback(hi2s); + } + else + { + hi2s->RxCpltCallback(hi2s); + } +#else + if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) + { + HAL_I2SEx_TxRxCpltCallback(hi2s); + } + else + { + HAL_I2S_RxCpltCallback(hi2s); + } +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Manage the reception 32-bit in Interrupt context + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +static void I2S_Receive_32Bit_IT(I2S_HandleTypeDef *hi2s) +{ + /* Receive data */ + *((uint32_t *)hi2s->pRxBuffPtr) = hi2s->Instance->RXDR; + hi2s->pRxBuffPtr += 2; + hi2s->RxXferCount--; + + if (hi2s->RxXferCount == 0UL) + { + if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) + { + /* Disable TXP, RXP, DXP, ERR interrupts */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXP | I2S_IT_RXP | I2S_IT_DXP | I2S_IT_ERR)); + } + else + { + /* Disable RXP and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXP | I2S_IT_ERR)); + } + + hi2s->State = HAL_I2S_STATE_READY; + /* Call user Rx complete callback */ +#if (USE_HAL_I2S_REGISTER_CALLBACKS == 1UL) + if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) + { + hi2s->TxRxCpltCallback(hi2s); + } + else + { + hi2s->RxCpltCallback(hi2s); + } +#else + if (IS_I2S_FULLDUPLEX(hi2s->Init.Mode)) + { + HAL_I2SEx_TxRxCpltCallback(hi2s); + } + else + { + HAL_I2S_RxCpltCallback(hi2s); + } +#endif /* USE_HAL_I2S_REGISTER_CALLBACKS */ + } +} + +/** + * @brief This function handles I2S Communication Timeout. + * @param hi2s pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param Flag Flag checked + * @param State Value of the flag expected + * @param Tickstart Tick start value + * @param Timeout Duration of the timeout + * @retval HAL status + */ +static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, FlagStatus State, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set to status*/ + while (((__HAL_I2S_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) >= Timeout) || (Timeout == 0UL)) + { + /* 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 */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s_ex.c index 081dfce91..e32193492 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i2s_ex.c @@ -1,31 +1,27 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_i2s_ex.c - * @author MCD Application Team - * @brief I2S HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of I2S extension peripheral: - * + Extension features Functions - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/** - ****************************************************************************** - ===== I2S FULL DUPLEX FEATURE ===== - I2S Full Duplex APIs are available in stm32h7rsxx_hal_i2s.c/.h - ****************************************************************************** - */ - - - - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_i2s_ex.c + * @author MCD Application Team + * @brief I2S HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of I2S extension peripheral: + * + Extension features Functions + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/** + ****************************************************************************** + ===== I2S FULL DUPLEX FEATURE ===== + I2S Full Duplex APIs are available in stm32h7rsxx_hal_i2s.c/.h + ****************************************************************************** + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i3c.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i3c.c index 7f5c09dbd..df4906b93 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i3c.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_i3c.c @@ -1,9623 +1,9847 @@ -/** - ********************************************************************************************************************** - * @file stm32h7rsxx_hal_i3c.c - * @author MCD Application Team - * @brief I3C HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Improvement Inter Integrated Circuit (I3C) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State and Errors functions - * - ********************************************************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ********************************************************************************************************************** - @verbatim - ====================================================================================================================== - ##### How to use this driver ##### - ====================================================================================================================== - [..] - The I3C HAL driver can be used as follows: - - (#) Declare a I3C_HandleTypeDef handle structure, for example: - I3C_HandleTypeDef hi3c; - - (#) Declare a I3C_XferTypeDef transfer descriptor structure, for example: - I3C_XferTypeDef ContextBuffers; - - (#)Initialize the I3C low level resources by implementing the HAL_I3C_MspInit() API: - (##) Enable the I3Cx interface clock - (##) I3C pins configuration - (+++) Enable the clock for the I3C GPIOs - (+++) Configure I3C pins as alternate function push-pull with no-pull - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the I3Cx interrupt priority - (+++) Enable the NVIC I3C IRQ Channel - (##) DMA Configuration if you need to use DMA process - (+++) Declare a DMA_HandleTypeDef handle structure for - the Command Common Code (CCC) management channel - (+++) Declare a DMA_HandleTypeDef handle structure for - the transmit channel - (+++) Declare a DMA_HandleTypeDef handle structure for - the receive channel - (+++) Declare a DMA_HandleTypeDef handle structure for - the status channel - (+++) Enable the DMAx interface clock - (+++) Configure the DMA handle parameters - (+++) Configure the DMA Command Common Code (CCC) channel - (+++) Configure the DMA Tx channel - (+++) Configure the DMA Rx channel - (+++) Configure the DMA Status channel - (+++) Associate the initialized DMA handle to the hi3c DMA CCC, Tx, Rx or Status handle as necessary - (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on - the DMA CCC, Tx, Rx or Status instance - - (#) Configure the HAL I3C Communication Mode as Controller or Target in the hi3c Init structure. - - (#) Configure the Controller Communication Bus characterics for Controller mode. - This mean, configure the parameters SDAHoldTime, WaitTime, SCLPPLowDuration, - SCLI3CHighDuration, SCLODLowDuration, SCLI2CHighDuration, BusFreeDuration, - BusIdleDuration in the LL_I3C_CtrlBusConfTypeDef structure through h3c Init structure. - - (#) Configure the Target Communication Bus characterics for Target mode. - This mean, configure the parameter BusAvailableDuration in the LL_I3C_TgtBusConfTypeDef structure - through h3c Init structure. - - All these parameters for Controller or Target can be configured directly in user code or - by using CubeMx generation. - To help the computation of the different parameters, the recommendation is to use CubeMx. - - Those parameters can be modified after the hi3c initialization by using - HAL_I3C_Ctrl_BusCharacteristicConfig() for controller and - HAL_I3C_Tgt_BusCharacteristicConfig() for target. - - (#) Initialize the I3C registers by calling the HAL_I3C_Init(), configures also the low level Hardware - (GPIO, CLOCK, NVIC...etc) by calling the customized HAL_I3C_MspInit(&hi3c) API. - - (#) Configure the different FIFO parameters in I3C_FifoConfTypeDef structure as RxFifoThreshold, TxFifoThreshold - for Controller or Target mode. - And enable/disable the Control or Status FIFO only for Controller Mode. - Use HAL_I3C_SetConfigFifo() function to finalize the configuration, and HAL_I3C_GetConfigFifo() to retrieve - FIFO configuration. - Possibility to clear the FIFO configuration by using HAL_I3C_ClearConfigFifo() which reset the configuration - FIFO to their default hardware value - - (#) Configure the different additional Controller configuration in I3C_CtrlConfTypeDef structure as DynamicAddr, - StallTime, HotJoinAllowed, ACKStallState, CCCStallState, TxStallState, RxStallState, HighKeeperSDA. - Use HAL_I3C_Ctrl_Config() function to finalize the Controller configuration. - - (#) Configure the different additional Target configuration in I3C_TgtConfTypeDef structure as Identifier, - MIPIIdentifier, CtrlRoleRequest, HotJoinRequest, IBIRequest, IBIPayload, IBIPayloadSize, MaxReadDataSize, - MaxWriteDataSize, CtrlCapability, GroupAddrCapability, DataTurnAroundDuration, MaxReadTurnAround, - MaxDataSpeed, MaxSpeedLimitation, HandOffActivityState, HandOffDelay, PendingReadMDB. - Use HAL_I3C_Tgt_Config() function to finalize the Target configuration. - - (#) Before initiate any IO operation, the application must launch an assignment of the different - Target dynamic address by using HAL_I3C_Ctrl_DynAddrAssign() in polling mode or - HAL_I3C_Ctrl_DynAddrAssign_IT() in interrupt mode. - This procedure is named Enter Dynamic Address Assignment (ENTDAA CCC command). - For the initiation of ENTDAA procedure from the controller, each target connected and powered on the I3C bus - must repond to this particular Command Common Code by sending its proper Payload (a amount of 48bits which - contain the target characteristics) - Each time a target responds to ENTDAA sequence, the application is informed through - HAL_I3C_TgtReqDynamicAddrCallback() of the reception of the target paylaod. - And then application must send a associated dynamic address through HAL_I3C_Ctrl_SetDynAddr(). - This procedure in loop automatically in hardware side until a target respond to repeated ENTDAA sequence. - The application is informed of the end of the procedure at reception of HAL_I3C_CtrlDAACpltCallback(). - Then application can easily retrieve ENTDAA payload information through HAL_I3C_Get_ENTDAA_Payload_Info() - function. - At the end of procedure, the function HAL_I3C_Ctrl_ConfigBusDevices() must be called to store in hardware - register part the target capabilities as Dynamic address, IBI support with or without additional data byte, - Controller role request support, Controller stop transfer after IBI through I3C_DeviceConfTypeDef structure. - - (#) Other action to be done, before initiate any IO operation, the application must prepare the different frame - descriptor with its associated buffer allocation in their side. - Configure the different information related to CCC transfer through I3C_CCCTypeDef structure - Configure the different information related to Private or I2C transfer through I3C_PrivateTypeDef structure - Configure the different buffer pointers and associated size needed for the driver communication - through I3C_XferTypeDef structure - The I3C_XferTypeDef structure contains different parameters about Control, Status buffer, - and Transmit and Receive buffer. - Use HAL_I3C_AddDescToFrame() function each time application add a descriptor in the frame before call - an IO operation interface - One element of the frame descriptor correspond to one frame to manage through IO operation. - - (#) To check if I3C target device is ready for communication, use the function HAL_I3C_Ctrl_IsDeviceI3C_Ready() - - (#) To check if I2C target device is ready for communication, use the function HAL_I3C_Ctrl_IsDeviceI2C_Ready() - - (#) For I3C IO operations, three operation modes are available within this driver : - - *** Polling mode IO operation *** - ================================= - [..] - (+) Activate asynchronous event in controller or target mode a Common Command Code in a broadcast - or a direct communication in blocking mode using HAL_I3C_Ctrl_TransmitCCC() - (+) Transmit in controller mode a Common Command Code in a broadcast or a direct communication in blocking mode - using HAL_I3C_Ctrl_TransmitCCC() - (+) Receive in controller mode a Common Command Code in a direct communication in blocking mode - using HAL_I3C_Ctrl_ReceiveCCC() - (+) Transmit in controller mode an amount of private data in an I3C or an I2C communication in blocking mode - using HAL_I3C_Ctrl_Transmit() - (+) Receive in controller mode an amount of private data in an I3C or an I2C communication in blocking mode - using HAL_I3C_Ctrl_Receive() - (+) Transmit in target mode an amount of private data in an I3C communication in blocking mode - using HAL_I3C_Tgt_Transmit() - (+) Receive in target mode an amount of private data in an I3C communication in blocking mode - using HAL_I3C_Tgt_Receive() - (+) At the end of a transfer, the different FIFO can be flushed if necessary by using HAL_I3C_FlushAllFifo() for - flush all the FIFO, or flush individually y using HAL_I3C_FlushTxFifo(), HAL_I3C_FlushRxFifo(), - HAL_I3C_FlushControlFifo(), HAL_I3C_FlushStatusFifo(). - (+) Request a HotJoin in target mode in blocking mode using HAL_I3C_Tgt_HotJoinReq() - (+) Request a In Band Interrupt in target mode in blocking mode using HAL_I3C_Tgt_IBIReq() - (+) Request a Controller Role in target mode in blocking mode using HAL_I3C_Tgt_ControlRoleReq() - - - *** DMA and Interrupt mode IO operation *** - =================================== - [..] - (+) Transmit in controller mode a Common Command Code in a broadcast or a direct communication in non-blocking - mode using HAL_I3C_Ctrl_TransmitCCC_IT() or HAL_I3C_Ctrl_TransmitCCC_DMA() - (+) At transmission end of transfer, HAL_I3C_CtrlTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_CtrlTxCpltCallback() - (+) Receive in controller mode a Common Command Code in a direct communication in non-blocking - mode using HAL_I3C_Ctrl_ReceiveCCC_IT() or HAL_I3C_Ctrl_ReceiveCCC_DMA() - (+) At reception end of transfer, HAL_I3C_CtrlRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_CtrlRxCpltCallback() - (+) Transmit in controller mode an amount of private data in an I3C or an I2C communication in non-blocking mode - using HAL_I3C_Ctrl_Transmit_IT() or HAL_I3C_Ctrl_Transmit_DMA() - (+) At transmission end of transfer, HAL_I3C_CtrlTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_CtrlTxCpltCallback() - (+) Receive in controller mode an amount of private data in an I3C or an I2C communication in non-blocking mode - using HAL_I3C_Ctrl_Receive_IT() or HAL_I3C_Ctrl_Receive_DMA() - (+) At reception end of transfer, HAL_I3C_CtrlRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_CtrlRxCpltCallback() - (+) Transfer in multiple direction (transmit/receive) in controller mode a Common Command Code in a direct - communication or an amount of private data in an I2C or I3C communication in non-blocking mode using - HAL_I3C_Ctrl_MultipleTransfer_IT() or HAL_I3C_Ctrl_MultipleTransfer_DMA() - (+) At the end of transfer, HAL_I3C_CtrlMultipleXferCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_CtrlMultipleXferCpltCallback() - (+) Transmit in target mode an amount of private data in an I3C communication in non-blocking mode - using HAL_I3C_Tgt_Transmit_IT() or HAL_I3C_Tgt_Transmit_DMA() - (+) At transmission end of transfer, HAL_I3C_TgtTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_TgtTxCpltCallback() - (+) Receive in target mode an amount of private data in an I3C communication in non-blocking mode - using HAL_I3C_Tgt_Receive_IT() or HAL_I3C_Tgt_Receive_DMA() - (+) At reception end of transfer, HAL_I3C_TgtRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_TgtRxCpltCallback() - (+) To treat asynchronous event, HAL_I3C_ActivateNotification() or HAL_I3C_DeactivateNotification() function is - used for enable or disable one or more notification related to specific asynchronous event. - Each time one or more event detected by hardware the associated HAL_I3C_NotifyCallback() is executed - and users can add their own code by customization of function pointer HAL_I3C_NotifyCallback(). - Then application can easily retrieve some specific associated event data through HAL_I3C_GetCCCInfo() function - (+) At the end of a transfer, the different FIFO can be flushed if necessary by using HAL_I3C_FlushAllFifo() for - flush all the FIFO, or flush individually y using HAL_I3C_FlushTxFifo(), HAL_I3C_FlushRxFifo(), - HAL_I3C_FlushControlFifo(), HAL_I3C_FlushStatusFifo(). - (+) Request a HotJoin in target mode in non-blocking mode using HAL_I3C_Tgt_HotJoinReq_IT - (+) At completion, HAL_I3C_TgtHotJoinCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_TgtHotJoinCallback() - (+) Request an In Band Interrupt in target mode in non-blocking mode using HAL_I3C_Tgt_IBIReq_IT() - (+) At completion, HAL_I3C_NotifyCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_NotifyCallback() - (+) Request a Controller Role in target mode in non-blocking mode using HAL_I3C_Tgt_ControlRoleReq_IT() - (+) At completion, HAL_I3C_NotifyCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_NotifyCallback() - (+) To manage the wakeup capability, HAL_I3C_ActivateNotification() or HAL_I3C_DeactivateNotification() function - is used for enable or disable Wake Up interrupt. - At wakeup detection the associated HAL_I3C_NotifyCallback() is executed. - (+) In case of transfer Error, HAL_I3C_ErrorCallback() function is executed and users can - add their own code by customization of function pointer HAL_I3C_ErrorCallback() - (+) Abort an I3C process communication with Interrupt using HAL_I3C_Abort_IT() - (+) End of abort process, HAL_I3C_AbortCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_I3C_AbortCpltCallback() - - - *** I3C HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in I3C HAL driver. - - (+) __HAL_I3C_ENABLE: Enable the I3C peripheral - (+) __HAL_I3C_DISABLE: Disable the I3C peripheral - (+) __HAL_I3C_RESET_HANDLE_STATE: Reset the I3C handle state - (+) __HAL_I3C_GET_FLAG: Check whether the specified I3C flag is set or not - - *** Callback registration *** - ============================================= - [..] - The compilation flag USE_HAL_I3C_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_I3C_RegisterCallback() or HAL_I3C_RegisterNotifyCallback() - or HAL_I3C_RegisterTgtReqDynamicAddrCallback() or HAL_I3C_RegisterTgtHotJoinCallback() - to register an interrupt callback. - [..] - Function HAL_I3C_RegisterCallback() allows to register following callbacks: - (+) CtrlTxCpltCallback : callback for Controller transmission CCC, I3C private or I2C end of transfer. - (+) CtrlRxCpltCallback : callback for Controller reception CCC, I3C private or I2C end of transfer. - (+) CtrlMultipleXferCpltCallback : callback for Controller multiple Direct CCC, I3C private or I2C - end of transfer. - (+) CtrlDAACpltCallback : callback for Controller Enter Dynamic Address Assignment end of transfer. - (+) TgtTxCpltCallback : callback for Target transmission I3C private end of transfer. - (+) TgtRxCpltCallback : callback for Target reception I3C private end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - [..] - For specific callback NotifyCallback - use dedicated register callbacks : HAL_I3C_RegisterNotifyCallback(). - [..] - For specific callback TgtReqDynamicAddrCallback - use dedicated register callbacks : HAL_I3C_RegisterTgtReqDynamicAddrCallback(). - [..] - For specific callback TgtHotJoinCallback - use dedicated register callbacks : HAL_I3C_RegisterTgtHotJoinCallback(). - [..] - Use function HAL_I3C_UnRegisterCallback to reset a callback to the default - weak function. - HAL_I3C_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) CtrlTxCpltCallback : callback for Controller transmission CCC, I3C private or I2C end of transfer. - (+) CtrlRxCpltCallback : callback for Controller reception CCC, I3C private or I2C end of transfer. - (+) CtrlMultipleXferCpltCallback : callback for Controller multiple Direct CCC, I3C private or I2C - end of transfer. - (+) CtrlDAACpltCallback : callback for Controller Enter Dynamic Address Assignment end of transfer. - (+) TgtTxCpltCallback : callback for Target transmission I3C private end of transfer. - (+) TgtRxCpltCallback : callback for Target reception I3C private end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - (+) NotifyCallback : callback for Controller and Target notification process. - (+) TgtReqDynamicAddrCallback : callback for controller application - when a target sent its payload to the controller during Dynamic Address Assignment process. - (+) TgtHotJoinCallback : callback for Target Hotjoin completion process. - [..] - By default, after the HAL_I3C_Init() and when the state is HAL_I3C_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_I3C_CtrlTxCpltCallback(), HAL_I3C_CtrlRxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the HAL_I3C_Init()/ HAL_I3C_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the HAL_I3C_Init()/ HAL_I3C_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - [..] - Callbacks can be registered/unregistered in HAL_I3C_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in HAL_I3C_STATE_READY or HAL_I3C_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using HAL_I3C_RegisterCallback() before calling HAL_I3C_DeInit() - or HAL_I3C_Init() function. - [..] - When the compilation flag USE_HAL_I3C_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - [..] - (@) You can refer to the I3C HAL driver header file for more useful macros - - @endverbatim - ********************************************************************************************************************** - */ - -/* Includes ----------------------------------------------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup I3C I3C - * @brief I3C HAL module driver - * @{ - */ - -#ifdef HAL_I3C_MODULE_ENABLED - -/* Private typedef ---------------------------------------------------------------------------------------------------*/ -/* Private define ----------------------------------------------------------------------------------------------------*/ -/** @defgroup I3C_Private_Define I3C Private Define - * @{ - */ - -/* Private define to centralize the enable/disable of Interrupts */ -#define I3C_XFER_LISTEN_IT (0x00000001U) -#define I3C_XFER_TARGET_TX_IT (0x00000002U) -#define I3C_XFER_TARGET_RX_IT (0x00000004U) -#define I3C_XFER_DMA (0x00000008U) -#define I3C_XFER_TARGET_CTRLROLE (0x00000010U) -#define I3C_XFER_TARGET_HOTJOIN (0x00000020U) -#define I3C_XFER_TARGET_IBI (0x00000040U) -#define I3C_XFER_CONTROLLER_TX_IT (0x00000080U) -#define I3C_XFER_CONTROLLER_RX_IT (0x00000100U) -#define I3C_XFER_CONTROLLER_RX_CCC_IT (0x00000400U) -#define I3C_XFER_CONTROLLER_DAA_IT (0x00001000U) - -/* Private defines for control buffer prior preparation */ -#define I3C_OPERATION_TYPE_MASK (0x78000000U) -#define I3C_RESTART_STOP_MASK (0x80000000U) -#define I3C_ARBITRATION_HEADER_MASK (0x00000004U) -#define I3C_DEFINE_BYTE_MASK (0x00000001U) - -/* Private define for CCC command */ -#define I3C_BROADCAST_RSTDAA (0x00000006U) -#define I3C_BROADCAST_ENTDAA (0x00000007U) - -/* Private define to split ENTDAA payload */ -#define I3C_DCR_IN_PAYLOAD_SHIFT 56 -#define I3C_PID_IN_PAYLOAD_MASK 0xFFFFFFFFFFFFU - -/* Private define to split PID */ -/* Bits[47:33]: MIPI Manufacturer ID */ -#define I3C_MIPIMID_PID_SHIFT 33 -#define I3C_MIPIMID_PID_MASK 0x7FFFU - -/* Bit[32]: Provisioned ID Type Selector */ -#define I3C_IDTSEL_PID_SHIFT 32 -#define I3C_IDTSEL_PID_MASK 0x01U - -/* Bits[31:16]: Part ID */ -#define I3C_PART_ID_PID_SHIFT 16 -#define I3C_PART_ID_PID_MASK 0xFFFFU - -/* Bits[15:12]: MIPI Instance ID */ -#define I3C_MIPIID_PID_SHIFT 12 -#define I3C_MIPIID_PID_MASK 0xFU -/** - * @} - */ - -/* Private macro -----------------------------------------------------------------------------------------------------*/ - -/** @brief Get Provisioned ID in payload (64bits) receive during ENTDAA procedure. - * @param __PAYLOAD__ specifies the Device Characteristics capabilities retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFFFFFF. - * @retval The value of PID Return value between Min_Data=0x00 and Max_Data=0xFFFFFFFFFFFF. - */ -#define I3C_GET_PID(__PAYLOAD__) ((uint64_t)(__PAYLOAD__) & I3C_PID_IN_PAYLOAD_MASK) - -/** @brief Get MIPI Manufacturer ID in PID (48bits). - * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. - * @retval The value of MIPI ID Return value between Min_Data=0x00 and Max_Data=0x7FFF. - */ -#define I3C_GET_MIPIMID(__PID__) ((uint16_t)((uint64_t)(__PID__) >> I3C_MIPIMID_PID_SHIFT) & \ - I3C_MIPIMID_PID_MASK) - -/** @brief Get Type Selector in PID (48bits). - * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. - * @retval The value of Type Selector Return 0 or 1. - */ -#define I3C_GET_IDTSEL(__PID__) ((uint8_t)((uint64_t)(__PID__) >> I3C_IDTSEL_PID_SHIFT) & \ - I3C_IDTSEL_PID_MASK) - -/** @brief Get Part ID in PID (48bits). - * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. - * @retval The value of Part ID Return value between Min_Data=0x00 and Max_Data=0xFFFF. - */ -#define I3C_GET_PART_ID(__PID__) ((uint16_t)((uint64_t)(__PID__) >> I3C_PART_ID_PID_SHIFT) & \ - I3C_PART_ID_PID_MASK) - -/** @brief Get Instance ID in PID (48bits). - * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. - * @retval The value of Instance ID Return value between Min_Data=0x00 and Max_Data=0xF. - */ -#define I3C_GET_MIPIID(__PID__) ((uint8_t)((uint64_t)(__PID__) >> I3C_MIPIID_PID_SHIFT) & \ - I3C_MIPIID_PID_MASK) - -/** @brief Get Device Characterics in payload (64bits) receive during ENTDAA procedure. - * @param __PAYLOAD__ specifies the Device Characteristics capabilities retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFFFFFFFF. - * @retval The value of BCR Return value between Min_Data=0x00 and Max_Data=0xFF. - */ -#define I3C_GET_DCR(__PAYLOAD__) (((uint32_t)((uint64_t)(__PAYLOAD__) >> I3C_DCR_IN_PAYLOAD_SHIFT)) & \ - I3C_DCR_DCR) - -/** @brief Get Advanced Capabilities. - * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. - * @retval The value of advanced capabilities: - * ENABLE: supports optional advanced capabilities. - * DISABLE: not supports optional advanced capabilities. - */ -#define I3C_GET_ADVANCED_CAPABLE(__BCR__) (((((__BCR__) & I3C_BCR_BCR5_Msk) >> \ - I3C_BCR_BCR5_Pos) == 1U) ? ENABLE : DISABLE) - -/** @brief Get virtual target support. - * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. - * @retval The value of offline capable: - * ENABLE: is a Virtual Target - * DISABLE: is not a Virtual Target - */ -#define I3C_GET_VIRTUAL_TGT(__BCR__) (((((__BCR__) & I3C_BCR_BCR4_Msk) >> \ - I3C_BCR_BCR4_Pos) == 1U) ? ENABLE : DISABLE) - -/** @brief Get offline capable. - * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. - * @retval The value of offline capable - * ENABLE: Device will not always respond to I3C Bus commands - * DISABLE: Device will always respond to I3C Bus commands - */ -#define I3C_GET_OFFLINE_CAPABLE(__BCR__) (((((__BCR__) & I3C_BCR_BCR3_Msk) >> \ - I3C_BCR_BCR3_Pos) == 1U) ? ENABLE : DISABLE) - -/** @brief Get Max data speed limitation. - * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. - * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. - * @retval The value of offline capable: - * ENABLE: Limitation - * DISABLE: No Limitation - */ -#define I3C_GET_MAX_DATA_SPEED_LIMIT(__BCR__) (((((__BCR__) & I3C_BCR_BCR0_Msk) >> \ - I3C_BCR_BCR0_Pos) == 1U) ? ENABLE : DISABLE) - -/** @brief Change uint32_t variable form big endian to little endian. - * @param __DATA__ .uint32_t variable in big endian. - * This parameter must be a number between Min_Data=0x00(uint32_t) and Max_Data=0xFFFFFFFF. - * @retval uint32_t variable in little endian. - */ -#define I3C_BIG_TO_LITTLE_ENDIAN(__DATA__) ((uint32_t)((((__DATA__) & 0xff000000U) >> 24) | \ - (((__DATA__) & 0x00ff0000U) >> 8) | \ - (((__DATA__) & 0x0000ff00U) << 8) | \ - (((__DATA__) & 0x000000ffU) << 24))) - -/* Private variables -------------------------------------------------------------------------------------------------*/ -/** @addtogroup I3C_Private_Variables - * @{ - */ -/* Structure containing address device and message type used for the private function I3C_Ctrl_IsDevice_Ready() */ -typedef struct -{ - uint8_t Address; /* Dynamic or Static target Address */ - uint32_t MessageType; /* Message Type */ - -} I3C_DeviceTypeDef; -/** - * @} - */ - -/* Private function prototypes ---------------------------------------------------------------------------------------*/ -/** @addtogroup I3C_Private_Functions - * @{ - */ -static HAL_StatusTypeDef I3C_Tgt_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Tgt_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Tgt_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -#if defined(HAL_DMA_MODULE_ENABLED) -static HAL_StatusTypeDef I3C_Tgt_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Tgt_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -#endif /* HAL_DMA_MODULE_ENABLED */ -static HAL_StatusTypeDef I3C_Tgt_HotJoin_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Tgt_CtrlRole_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Tgt_IBI_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Tx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Rx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -#if defined(HAL_DMA_MODULE_ENABLED) -static HAL_StatusTypeDef I3C_Ctrl_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -#endif /* HAL_DMA_MODULE_ENABLED */ -static HAL_StatusTypeDef I3C_Ctrl_DAA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); -static HAL_StatusTypeDef I3C_Abort_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); - -static HAL_StatusTypeDef I3C_WaitOnDAAUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t timeout, uint32_t tickstart); -static HAL_StatusTypeDef I3C_WaitOnFlagUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t flag, FlagStatus flagstatus, - uint32_t timeout, uint32_t tickstart); -static void I3C_TransmitByteTreatment(I3C_HandleTypeDef *hi3c); -static void I3C_TransmitWordTreatment(I3C_HandleTypeDef *hi3c); -static void I3C_ReceiveByteTreatment(I3C_HandleTypeDef *hi3c); -static void I3C_ReceiveWordTreatment(I3C_HandleTypeDef *hi3c); -static void I3C_ControlDataTreatment(I3C_HandleTypeDef *hi3c); -static void I3C_ErrorTreatment(I3C_HandleTypeDef *hi3c); -static void I3C_GetErrorSources(I3C_HandleTypeDef *hi3c); -static void I3C_StateUpdate(I3C_HandleTypeDef *hi3c); -#if defined(HAL_DMA_MODULE_ENABLED) -static void I3C_DMAAbort(DMA_HandleTypeDef *hdma); -static void I3C_DMAControlTransmitCplt(DMA_HandleTypeDef *hdma); -static void I3C_DMADataTransmitCplt(DMA_HandleTypeDef *hdma); -static void I3C_DMADataReceiveCplt(DMA_HandleTypeDef *hdma); -static void I3C_DMAError(DMA_HandleTypeDef *hdma); -#endif /* HAL_DMA_MODULE_ENABLED */ -static void I3C_Enable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest); -static void I3C_Disable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest); -static HAL_StatusTypeDef I3C_Xfer_PriorPreparation(I3C_HandleTypeDef *hi3c, uint8_t counter, uint32_t option); -static uint32_t I3C_FillTxBuffer_CCC(I3C_HandleTypeDef *hi3c, - uint32_t indexDesc, - uint32_t txSize, - uint32_t txCurrentIndex); -static uint32_t I3C_FillTxBuffer_Private(I3C_HandleTypeDef *hi3c, - uint32_t indexDesc, - uint32_t txSize, - uint32_t txCurrentIndex); -static HAL_StatusTypeDef I3C_ControlBuffer_PriorPreparation(I3C_HandleTypeDef *hi3c, - uint8_t counter, - uint32_t option); -static HAL_StatusTypeDef I3C_Ctrl_IsDevice_Ready(I3C_HandleTypeDef *hi3c, - const I3C_DeviceTypeDef *pDevice, - uint32_t trials, - uint32_t timeout); -static void I3C_TreatErrorCallback(I3C_HandleTypeDef *hi3c); -/** - * @} - */ - -/* Exported functions ------------------------------------------------------------------------------------------------*/ -/** @addtogroup I3C_Exported_Functions I3C Exported Functions - * @{ - */ - -/** @defgroup I3C_Exported_Functions_Group1 Initialization and de-initialization functions. - * @brief I3C initialization and de-initialization functions - * -@verbatim - ======================================================================================================================= - ##### Initialization and de-initialization functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to initialize and deinitialize the I3Cx peripheral: - - (+) Users must implement HAL_I3C_MspInit() function in which they configure all related peripherals - resources (APB and Kernel CLOCK, GPIO, DMA, IT and NVIC). - - (+) Call the function HAL_I3C_Init() to configure the bus characteristic depends on the device mode - with the selected configuration below: - - (++) Controller mode, Serial source clock wave form configuration: - (+++) SCL push pull low duration - (+++) SCL I3C high duration - (+++) SCL open drain low duration - (+++) SCL I2C high duration - - (++) Controller mode, Bus timing configuration: - (+++) SDA hold time - (+++) Wait time - (+++) Bus free duration - (+++) Bus available duration - - (++) Target mode, Bus timing configuration: - (+++) Bus available duration - - (+) Call the function HAL_I3C_DeInit() to restore the default configuration of the selected I3Cx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the I3C instance by activating the low-level hardware and configuring the bus - * characteristic according to the specified parameters in the I3C_InitTypeDef. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Init(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t waveform_value; - uint32_t timing_value; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state */ - if (hi3c->State == HAL_I3C_STATE_RESET) - { -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Init the I3C Callback settings */ - /* Legacy weak CtrlTxCpltCallback */ - hi3c->CtrlTxCpltCallback = HAL_I3C_CtrlTxCpltCallback; - /* Legacy weak CtrlRxCpltCallback */ - hi3c->CtrlRxCpltCallback = HAL_I3C_CtrlRxCpltCallback; - /* Legacy weak CtrlMultipleXferCpltCallback */ - hi3c->CtrlMultipleXferCpltCallback = HAL_I3C_CtrlMultipleXferCpltCallback; - /* Legacy weak CtrlDAACpltCallback */ - hi3c->CtrlDAACpltCallback = HAL_I3C_CtrlDAACpltCallback; - /* Legacy weak TgtReqDynamicAddrCallback */ - hi3c->TgtReqDynamicAddrCallback = HAL_I3C_TgtReqDynamicAddrCallback; - /* Legacy weak TgtTxCpltCallback */ - hi3c->TgtTxCpltCallback = HAL_I3C_TgtTxCpltCallback; - /* Legacy weak TgtRxCpltCallback */ - hi3c->TgtRxCpltCallback = HAL_I3C_TgtRxCpltCallback; - /* Legacy weak TgtHotJoinCallback */ - hi3c->TgtHotJoinCallback = HAL_I3C_TgtHotJoinCallback; - /* Legacy weak NotifyCallback */ - hi3c->NotifyCallback = HAL_I3C_NotifyCallback; - /* Legacy weak ErrorCallback */ - hi3c->ErrorCallback = HAL_I3C_ErrorCallback; - /* Legacy weak AbortCpltCallback */ - hi3c->AbortCpltCallback = HAL_I3C_AbortCpltCallback; - - /* Check on the MSP init callback */ - if (hi3c->MspInitCallback == NULL) - { - /* Legacy weak MspInit */ - hi3c->MspInitCallback = HAL_I3C_MspInit; - } - - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - hi3c->MspInitCallback(hi3c); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_I3C_MspInit(hi3c); - -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ - } - - /* Update the I3C state to busy */ - hi3c->State = HAL_I3C_STATE_BUSY; - - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(hi3c->Instance); - - /* Check on the I3C mode: initialization depends on the mode */ - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Check the parameters */ - assert_param(IS_I3C_SDAHOLDTIME_VALUE(hi3c->Init.CtrlBusCharacteristic.SDAHoldTime)); - assert_param(IS_I3C_WAITTIME_VALUE(hi3c->Init.CtrlBusCharacteristic.WaitTime)); - - /* Set Controller mode */ - LL_I3C_SetMode(hi3c->Instance, LL_I3C_MODE_CONTROLLER); - - /*----------------- SCL signal waveform configuration : I3C timing register 0 (I3C_TIMINGR0) ------------------ */ - /* Set the controller SCL waveform */ - waveform_value = ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLPPLowDuration | - ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLI3CHighDuration << I3C_TIMINGR0_SCLH_I3C_Pos) | - ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLODLowDuration << I3C_TIMINGR0_SCLL_OD_Pos) | - ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLI2CHighDuration << I3C_TIMINGR0_SCLH_I2C_Pos)); - - LL_I3C_ConfigClockWaveForm(hi3c->Instance, waveform_value); - - /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------ */ - /* Set SDA hold time, activity state, bus free duration and bus available duration */ - timing_value = ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SDAHoldTime | - (uint32_t)hi3c->Init.CtrlBusCharacteristic.WaitTime | - ((uint32_t)hi3c->Init.CtrlBusCharacteristic.BusFreeDuration << I3C_TIMINGR1_FREE_Pos) | - (uint32_t)hi3c->Init.CtrlBusCharacteristic.BusIdleDuration); - - LL_I3C_SetCtrlBusCharacteristic(hi3c->Instance, timing_value); - } - else - { - /* Set target mode */ - LL_I3C_SetMode(hi3c->Instance, LL_I3C_MODE_TARGET); - - /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------ */ - /* Set the number of kernel clocks cycles for the bus available condition time */ - LL_I3C_SetAvalTiming(hi3c->Instance, hi3c->Init.TgtBusCharacteristic.BusAvailableDuration); - } - - /* Enable the selected I3C peripheral */ - LL_I3C_Enable(hi3c->Instance); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Update I3C state */ - hi3c->State = HAL_I3C_STATE_READY; - hi3c->PreviousState = HAL_I3C_STATE_READY; - } - - return status; -} - -/** - * @brief DeInitialize the I3C peripheral. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_DeInit(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - - /* Update the I3C state to busy */ - hi3c->State = HAL_I3C_STATE_BUSY; - - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Check on the MSP init callback */ - if (hi3c->MspDeInitCallback == NULL) - { - /* Legacy weak MspDeInit */ - hi3c->MspDeInitCallback = HAL_I3C_MspDeInit; - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - hi3c->MspDeInitCallback(hi3c); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_I3C_MspDeInit(hi3c); - -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ - - /* Update the I3C Error code, state and mode */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_RESET; - hi3c->PreviousState = HAL_I3C_STATE_RESET; - hi3c->Mode = HAL_I3C_MODE_NONE; - } - - return status; -} - -/** - * @brief Initialize the I3C MSP. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_MspInit(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I3C_MspInit could be implemented in the user file */ -} - -/** - * @brief DeInitialize the I3C MSP. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_MspDeInit(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I3C_MspDeInit could be implemented in the user file */ -} -/** - * @} - */ - -/** @defgroup I3C_Exported_Functions_Group2 Interrupt and callback functions. - * @brief I3C interrupt and callback functions. - * -@verbatim - ======================================================================================================================= - ##### Interrupt and callback functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to manage callbacks and interrupts request: - - (+) Register/Unregister callback function: - (++) Call the function HAL_I3C_RegisterCallback() to register an I3C user callback. - (++) Call the function HAL_I3C_RegisterNotifyCallback() to register an I3C user notification callback. - (++) Call the function HAL_I3C_RegisterDynamicAddrCallback() to register an I3C user address callback. - (++) Call the function HAL_I3C_RegisterHotJoinCallback() to register an I3C user hot join callback. - (++) Call the function HAL_I3C_UnRegisterCallback() to unregister an I3C user callback. - - (+) Notification management function: - (++) Call the function HAL_I3C_ActivateNotification() to activate the I3C notifications. - (++) Call the function HAL_I3C_DeactivateNotification() to deactivate the I3C notifications. - - (+) Controller callback functions: - (++) Users must implement HAL_I3C_CtrlTxCpltCallback() function when the transmission of private data or - Tx CCC transfer is completed. - (++) Users must implement HAL_I3C_CtrlRxCpltCallback() function when the reception of private data or - Rx CCC transfer is completed. - (++) Users must implement HAL_I3C_CtrlMultipleXferCpltCallback() function when the multiple - transfer of CCC, I3C private or I2C transfer is completed. - (++) Users must implement HAL_I3C_CtrlDAACpltCallback() function when Dynamic Address Assignment - procedure is completed. - (++) Users must implement HAL_I3C_TgtReqDynamicAddrCallback() function in the controller application - when a target sent its payload to the controller during Dynamic Address Assignment procedure. - - (+) Target callback functions: - (++) Users must implement HAL_I3C_TgtTxCpltCallback() function when the transmission of private - data is completed. - (++) Users must implement HAL_I3C_TgtRxCpltCallback() function when the reception of private - data is completed. - (++) Users must implement HAL_I3C_TgtHotJoinCallback() function when a target hot join process - is completed. - - (+) Common callback functions: - (++) Users must implement HAL_I3C_NotifyCallback() function when the device receives - an asynchronous event like IBI, a Hot-join, CCC command for target... - (++) Users must implement HAL_I3C_AbortCpltCallback() function when an abort process is completed. - (++) Users must implement HAL_I3C_ErrorCallback() function when an error is occurred. - - (+) Interrupt and event function: - (++) Call the function HAL_I3C_ER_IRQHandler() in the ISR file to handle I3C error interrupts request. - (++) Call the function HAL_I3C_EV_IRQHandler() in the ISR file to handle I3C event interrupts request. -@endverbatim - * @{ - */ - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a User I3C Callback to be used instead of the weak predefined callback. - * @note The HAL_I3C_RegisterCallback() may be called before HAL_I3C_Init() in HAL_I3C_STATE_RESET - * to register callbacks for HAL_I3C_MSPINIT_CB_ID and HAL_I3C_MSPDEINIT_CB_ID - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param callbackID : [IN] ID of the callback to be registered. - * This parameter can be one of the following values: - * @arg @ref HAL_I3C_CTRL_TX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_CTRL_RX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID - * @arg @ref HAL_I3C_CTRL_DAA_COMPLETE_CB_ID - * @arg @ref HAL_I3C_TGT_TX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_TGT_RX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_ERROR_CB_ID - * @arg @ref HAL_I3C_ABORT_CB_ID - * @arg @ref HAL_I3C_MSPINIT_CB_ID - * @arg @ref HAL_I3C_MSPDEINIT_CB_ID - * @param pCallback : [IN] Pointer to the Callback function. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_RegisterCallback(I3C_HandleTypeDef *hi3c, - HAL_I3C_CallbackIDTypeDef callbackID, - pI3C_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the user callback allocation */ - if (pCallback == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else if (HAL_I3C_STATE_READY == hi3c->State) - { - switch (callbackID) - { - case HAL_I3C_CTRL_TX_COMPLETE_CB_ID : - hi3c->CtrlTxCpltCallback = pCallback; - break; - - case HAL_I3C_CTRL_RX_COMPLETE_CB_ID : - hi3c->CtrlRxCpltCallback = pCallback; - break; - - case HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID : - hi3c->CtrlMultipleXferCpltCallback = pCallback; - break; - - case HAL_I3C_CTRL_DAA_COMPLETE_CB_ID : - hi3c->CtrlDAACpltCallback = pCallback; - break; - - case HAL_I3C_TGT_TX_COMPLETE_CB_ID : - hi3c->TgtTxCpltCallback = pCallback; - break; - - case HAL_I3C_TGT_RX_COMPLETE_CB_ID : - hi3c->TgtRxCpltCallback = pCallback; - break; - - case HAL_I3C_ERROR_CB_ID : - hi3c->ErrorCallback = pCallback; - break; - - case HAL_I3C_ABORT_CB_ID : - hi3c->AbortCpltCallback = pCallback; - break; - - case HAL_I3C_MSPINIT_CB_ID : - hi3c->MspInitCallback = pCallback; - break; - - case HAL_I3C_MSPDEINIT_CB_ID : - hi3c->MspDeInitCallback = pCallback; - break; - - default : - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (HAL_I3C_STATE_RESET == hi3c->State) - { - switch (callbackID) - { - case HAL_I3C_MSPINIT_CB_ID : - hi3c->MspInitCallback = pCallback; - break; - - case HAL_I3C_MSPDEINIT_CB_ID : - hi3c->MspDeInitCallback = pCallback; - break; - - default : - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief Register a User I3C Notify Callback to be used instead of the weak predefined callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pNotifyCallback : [IN] Pointer to the Callback function. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_RegisterNotifyCallback(I3C_HandleTypeDef *hi3c, pI3C_NotifyCallbackTypeDef pNotifyCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the user callback allocation */ - if (pNotifyCallback == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else if (HAL_I3C_STATE_READY == hi3c->State) - { - hi3c->NotifyCallback = pNotifyCallback; - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief Register a User I3C dynamic address Callback to be used instead of the weak predefined callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pTgtReqAddrCallback : [IN] Pointer to the Callback function. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_RegisterTgtReqDynamicAddrCallback(I3C_HandleTypeDef *hi3c, - pI3C_TgtReqDynamicAddrCallbackTypeDef pTgtReqAddrCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the user callback allocation */ - if (pTgtReqAddrCallback == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else if (HAL_I3C_STATE_READY == hi3c->State) - { - hi3c->TgtReqDynamicAddrCallback = pTgtReqAddrCallback; - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief Register a User I3C hot join Callback to be used instead of the weak predefined callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pTgtHotJoinCallback : [IN] Pointer to the Callback function. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_RegisterTgtHotJoinCallback(I3C_HandleTypeDef *hi3c, - pI3C_TgtHotJoinCallbackTypeDef pTgtHotJoinCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the user callback allocation */ - if (pTgtHotJoinCallback == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else if (HAL_I3C_STATE_READY == hi3c->State) - { - hi3c->TgtHotJoinCallback = pTgtHotJoinCallback; - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief Unregister a user I3C Callback. - * The I3C callback is redirected to the weak predefined callback - * @note The HAL_I3C_UnRegisterCallback() may be called before HAL_I3C_Init() in HAL_I3C_STATE_RESET - * to un-register callbacks for HAL_I3C_MSPINIT_CB_ID and HAL_I3C_MSPDEINIT_CB_ID - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param callbackID : [IN] ID of the callback to be unregistered. - * This parameter can be one of the following values: - * @arg @ref HAL_I3C_CTRL_TX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_CTRL_RX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID - * @arg @ref HAL_I3C_CTRL_DAA_COMPLETE_CB_ID - * @arg @ref HAL_I3C_TGT_REQ_DYNAMIC_ADDR_CB_ID - * @arg @ref HAL_I3C_TGT_TX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_TGT_RX_COMPLETE_CB_ID - * @arg @ref HAL_I3C_TGT_HOTJOIN_CB_ID - * @arg @ref HAL_I3C_NOTIFY_CB_ID - * @arg @ref HAL_I3C_ERROR_CB_ID - * @arg @ref HAL_I3C_ABORT_CB_ID - * @arg @ref HAL_I3C_MSPINIT_CB_ID - * @arg @ref HAL_I3C_MSPDEINIT_CB_ID - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_UnRegisterCallback(I3C_HandleTypeDef *hi3c, HAL_I3C_CallbackIDTypeDef callbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - if (HAL_I3C_STATE_READY == hi3c->State) - { - switch (callbackID) - { - case HAL_I3C_CTRL_TX_COMPLETE_CB_ID : - /* Legacy weak CtrlTxCpltCallback */ - hi3c->CtrlTxCpltCallback = HAL_I3C_CtrlTxCpltCallback; - break; - - case HAL_I3C_CTRL_RX_COMPLETE_CB_ID : - /* Legacy weak CtrlRxCpltCallback */ - hi3c->CtrlRxCpltCallback = HAL_I3C_CtrlRxCpltCallback; - break; - - case HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID : - /* Legacy weak CtrlMultipleXferCpltCallback */ - hi3c->CtrlMultipleXferCpltCallback = HAL_I3C_CtrlMultipleXferCpltCallback; - break; - - case HAL_I3C_CTRL_DAA_COMPLETE_CB_ID : - /* Legacy weak CtrlDAACpltCallback */ - hi3c->CtrlDAACpltCallback = HAL_I3C_CtrlDAACpltCallback; - break; - - case HAL_I3C_TGT_REQ_DYNAMIC_ADDR_CB_ID : - /*Legacy weak TgtReqDynamicAddrCallback */ - hi3c->TgtReqDynamicAddrCallback = HAL_I3C_TgtReqDynamicAddrCallback; - break; - - case HAL_I3C_TGT_TX_COMPLETE_CB_ID : - /* Legacy weak TgtTxCpltCallback */ - hi3c->TgtTxCpltCallback = HAL_I3C_TgtTxCpltCallback; - break; - - case HAL_I3C_TGT_RX_COMPLETE_CB_ID : - /* Legacy weak TgtRxCpltCallback */ - hi3c->TgtRxCpltCallback = HAL_I3C_TgtRxCpltCallback; - break; - - case HAL_I3C_TGT_HOTJOIN_CB_ID : - /* Legacy weak TgtHotJoinCallback */ - hi3c->TgtHotJoinCallback = HAL_I3C_TgtHotJoinCallback; - break; - - case HAL_I3C_NOTIFY_CB_ID : - /* Legacy weak NotifyCallback */ - hi3c->NotifyCallback = HAL_I3C_NotifyCallback; - break; - - case HAL_I3C_ERROR_CB_ID : - /* Legacy weak ErrorCallback */ - hi3c->ErrorCallback = HAL_I3C_ErrorCallback; - break; - - case HAL_I3C_ABORT_CB_ID : - /* Legacy weak AbortCpltCallback */ - hi3c->AbortCpltCallback = HAL_I3C_AbortCpltCallback; - break; - - case HAL_I3C_MSPINIT_CB_ID : - /* Legacy weak MspInit */ - hi3c->MspInitCallback = HAL_I3C_MspInit; - break; - - case HAL_I3C_MSPDEINIT_CB_ID : - /* Legacy weak MspDeInit */ - hi3c->MspDeInitCallback = HAL_I3C_MspDeInit; - break; - - default : - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (HAL_I3C_STATE_RESET == hi3c->State) - { - switch (callbackID) - { - case HAL_I3C_MSPINIT_CB_ID : - /* Legacy weak MspInit */ - hi3c->MspInitCallback = HAL_I3C_MspInit; - break; - - case HAL_I3C_MSPDEINIT_CB_ID : - /* Legacy weak MspDeInit */ - hi3c->MspDeInitCallback = HAL_I3C_MspDeInit; - break; - - default : - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - return status; -} -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - -/** - * @brief This function permits to activate the I3C notifications. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pXferData : [IN/OUT] Pointer to an I3C_XferTypeDef structure that contains the reception buffer to - * retrieve data during broadcast CCC DEFTGTS and DEFGRPA when Target mode only. - * @param interruptMask : [IN] Parameter indicates which interrupts will be enabled. - * This parameter can be any combination of @arg I3C_TARGET_INTERRUPT when - * the I3C is in target mode or a combination of @arg I3C_CONTROLLER_INTERRUPT - * when it is in controller mode. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_ActivateNotification(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData, - uint32_t interruptMask) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - assert_param(IS_I3C_INTERRUPTMASK(hi3c->Mode, interruptMask)); - - /* Check the I3C state and mode */ - if ((hi3c->State == HAL_I3C_STATE_RESET) || - ((hi3c->Mode != HAL_I3C_MODE_CONTROLLER) && (hi3c->Mode != HAL_I3C_MODE_TARGET))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Check the I3C mode */ - else if ((hi3c->Mode == HAL_I3C_MODE_TARGET) && - ((interruptMask & (HAL_I3C_IT_DEFIE | HAL_I3C_IT_GRPIE)) != 0U) && - (pXferData == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Check the I3C mode */ - if (hi3c->Mode == HAL_I3C_MODE_TARGET) - { - if ((interruptMask & (HAL_I3C_IT_DEFIE | HAL_I3C_IT_GRPIE)) != 0U) - { - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - } - /* Store the target event treatment function */ - hi3c->XferISR = I3C_Tgt_Event_ISR; - } - else - { - /* Store the controller event treatment function */ - hi3c->XferISR = I3C_Ctrl_Event_ISR; - } - - /* Update handle parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_LISTEN; - hi3c->PreviousState = HAL_I3C_STATE_LISTEN; - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - /* Enable selected notifications */ - I3C_Enable_IRQ(hi3c, (interruptMask | I3C_XFER_LISTEN_IT)); - } - } - - return status; -} - -/** - * @brief This function permits to deactivate the I3C notifications. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param interruptMask : [IN] Parameter indicates which interrupts will be disabled. - * This parameter can be any combination of @arg I3C_TARGET_INTERRUPT when - * the I3C is in target mode or a combination of @arg I3C_CONTROLLER_INTERRUPT - * when it is in controller mode. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_DeactivateNotification(I3C_HandleTypeDef *hi3c, uint32_t interruptMask) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance parameter */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - - /* Check on the State */ - if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Disable selected notifications */ - I3C_Disable_IRQ(hi3c, (interruptMask | I3C_XFER_LISTEN_IT)); - - if (READ_REG(hi3c->Instance->IER) == 0U) - { - /* Update the XferISR pointer */ - hi3c->XferISR = NULL; - - /* Update I3C state */ - hi3c->State = HAL_I3C_STATE_READY; - hi3c->PreviousState = HAL_I3C_STATE_READY; - } - } - } - - return status; -} - -/** - * @brief Controller Transmission Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_CtrlTxCpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_CtrlTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Controller Reception Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_CtrlRxCpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_CtrlRxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Controller multiple Direct CCC Command, I3C private or I2C transfer Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_CtrlMultipleXferCpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_CtrlMultipleXferCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Controller dynamic address assignment Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_CtrlDAACpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_CtrlDAACpltCallback could be implemented in the user file - */ -} - -/** - * @brief Target Request Dynamic Address callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param targetPayload : [IN] Parameter indicates the target payload. - * @retval None - */ -__weak void HAL_I3C_TgtReqDynamicAddrCallback(I3C_HandleTypeDef *hi3c, uint64_t targetPayload) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - UNUSED(targetPayload); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_TgtReqDynamicAddrCallback could be implemented in the user file - */ -} - -/** - * @brief Target Transmission Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_TgtTxCpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_TgtTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Target Reception Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_TgtRxCpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_TgtRxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Target Hot join process Complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param dynamicAddress : [IN] The returned dynamic address value after the hot join process. - * @retval None - */ -__weak void HAL_I3C_TgtHotJoinCallback(I3C_HandleTypeDef *hi3c, uint8_t dynamicAddress) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - UNUSED(dynamicAddress); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_TgtHotJoinCallback could be implemented in the user file - */ -} - -/** - * @brief Target/Controller Notification event callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param eventId : [IN] Parameter indicates which notification is signaled. - * It can be a combination value of @ref HAL_I3C_Notification_ID_definition. - * @retval None - */ -__weak void HAL_I3C_NotifyCallback(I3C_HandleTypeDef *hi3c, uint32_t eventId) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - UNUSED(eventId); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_NotifyCallback could be implemented in the user file - */ -} - -/** - * @brief Abort complete callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_AbortCpltCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_AbortCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Error callback. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -__weak void HAL_I3C_ErrorCallback(I3C_HandleTypeDef *hi3c) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi3c); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I3C_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief This function handles I3C error interrupt request. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -void HAL_I3C_ER_IRQHandler(I3C_HandleTypeDef *hi3c) -{ - uint32_t it_flag = READ_REG(hi3c->Instance->EVR); - uint32_t it_source = READ_REG(hi3c->Instance->IER); - - /* Check on the error interrupt flag and source */ - if ((I3C_CHECK_FLAG(it_flag, HAL_I3C_FLAG_ERRF) != RESET) && - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_ERRIE) != RESET)) - { - /* Clear the error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - if (hi3c->State != HAL_I3C_STATE_ABORT) - { - /* Get error sources */ - I3C_GetErrorSources(hi3c); - } - - /* Errors treatment */ - I3C_ErrorTreatment(hi3c); - } -} - -/** - * @brief This function handles I3C event interrupt request. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval None - */ -void HAL_I3C_EV_IRQHandler(I3C_HandleTypeDef *hi3c) /* Derogation MISRAC2012-Rule-8.13 */ -{ - uint32_t it_flags = READ_REG(hi3c->Instance->EVR); - uint32_t it_sources = READ_REG(hi3c->Instance->IER); - - uint32_t it_masks = (uint32_t)(it_flags & it_sources); - - /* I3C events treatment */ - if (hi3c->XferISR != NULL) - { - hi3c->XferISR(hi3c, it_masks); - } -} -/** - * @} - */ - -/** @defgroup I3C_Exported_Functions_Group3 Configuration functions. - * @brief I3C configuration functions. - * -@verbatim - ======================================================================================================================= - ##### Configuration functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to configure the I3C instances. - - (+) Call the function HAL_I3C_Ctrl_BusCharacteristicConfig() to modify the controller Bus Characteristics - after initialize the bus through HAL_I3C_Init. - - (+) Call the function HAL_I3C_Tgt_BusCharacteristicConfig() to modify the target Bus Characteristics - after initialize the bus through HAL_I3C_Init. - - (+) Call the function HAL_I3C_SetConfigFifo() to set FIFOs configuration (enabled FIFOs and - threshold level) with the selected parameters in the configuration structure I3C_FifoConfTypeDef. - - (+) Call the function HAL_I3C_Ctrl_Config() to configure the I3C Controller instances with the selected - parameters in the configuration structure I3C_CtrlConfTypeDef. - This function is called only when mode is Controller. - - (+) Call the function HAL_I3C_Tgt_Config() to configure the I3C Target instances with the selected - parameters in the configuration structure I3C_TgtConfTypeDef. - This function is called only when mode is Target. - - (+) Call the function HAL_I3C_Ctrl_ConfigBusDevices() to configure Hardware device characteristics register - with Devices capabilities present on the Bus. - All different characteristics must be fill through structure I3C_DeviceConfTypeDef. - This function is called only when mode is Controller. - - (+) Call the function HAL_I3C_AddDescToFrame() to prepare the full transfer usecase in a transfer descriptor - which contained different buffer pointers and their associated size through I3C_XferTypeDef. - This function must be called before initiate any communication transfer. - [..] - (@) Users must call all above functions after I3C initialization. - -@endverbatim - * @{ - */ - -/** - * @brief Configure the Controller Bus characterics. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pConfig : [IN] Pointer to an LL_I3C_CtrlBusConfTypeDef structure contains controller bus configuration. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_BusCharacteristicConfig(I3C_HandleTypeDef *hi3c, - const LL_I3C_CtrlBusConfTypeDef *pConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t waveform_value; - uint32_t timing_value; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check on user parameters */ - if (pConfig == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state and mode */ - else if ((hi3c->State != HAL_I3C_STATE_READY) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Check the parameters */ - assert_param(IS_I3C_SDAHOLDTIME_VALUE(pConfig->SDAHoldTime)); - assert_param(IS_I3C_WAITTIME_VALUE(pConfig->WaitTime)); - - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(hi3c->Instance); - - /*----------------- SCL signal waveform configuration : I3C timing register 0 (I3C_TIMINGR0) ------------------ */ - /* Set the controller SCL waveform */ - waveform_value = ((uint32_t)pConfig->SCLPPLowDuration | - ((uint32_t)pConfig->SCLI3CHighDuration << I3C_TIMINGR0_SCLH_I3C_Pos) | - ((uint32_t)pConfig->SCLODLowDuration << I3C_TIMINGR0_SCLL_OD_Pos) | - ((uint32_t)pConfig->SCLI2CHighDuration << I3C_TIMINGR0_SCLH_I2C_Pos)); - - LL_I3C_ConfigClockWaveForm(hi3c->Instance, waveform_value); - - /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------ */ - /* Set SDA hold time, activity state, bus free duration and bus available duration */ - timing_value = ((uint32_t)pConfig->SDAHoldTime | - (uint32_t)pConfig->WaitTime | - ((uint32_t)pConfig->BusFreeDuration << I3C_TIMINGR1_FREE_Pos) | - (uint32_t)pConfig->BusIdleDuration); - - LL_I3C_SetCtrlBusCharacteristic(hi3c->Instance, timing_value); - - /* Enable the selected I3C peripheral */ - LL_I3C_Enable(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Configure the target Bus characterics. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pConfig : [IN] Pointer to an LL_I3C_TgtBusConfTypeDef structure contains target bus configuration. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_BusCharacteristicConfig(I3C_HandleTypeDef *hi3c, - const LL_I3C_TgtBusConfTypeDef *pConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check on user parameters */ - if (pConfig == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state and mode */ - if ((hi3c->State != HAL_I3C_STATE_READY) || (hi3c->Mode != HAL_I3C_MODE_TARGET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(hi3c->Instance); - - /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ---------------------------- */ - /* Set the number of kernel clocks cycles for the bus available condition time */ - LL_I3C_SetAvalTiming(hi3c->Instance, pConfig->BusAvailableDuration); - - /* Enable the selected I3C peripheral */ - LL_I3C_Enable(hi3c->Instance); - } - } - } - - return status; -} - -/** - * @brief Set I3C FIFOs configuration. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pConfig : [IN] Pointer to an I3C_FifoConfTypeDef structure contains FIFOs configuration. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_SetConfigFifo(I3C_HandleTypeDef *hi3c, const I3C_FifoConfTypeDef *pConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t cfgr_value; - uint32_t cfgr_mask; - - /* Check the I3C handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check on user parameters */ - if (pConfig == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state */ - else if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check configuration parameters */ - assert_param(IS_I3C_TXFIFOTHRESHOLD_VALUE(pConfig->TxFifoThreshold)); - assert_param(IS_I3C_RXFIFOTHRESHOLD_VALUE(pConfig->RxFifoThreshold)); - - /* Set Tx and Rx Fifo threshold */ - cfgr_value = (pConfig->TxFifoThreshold | pConfig->RxFifoThreshold); - cfgr_mask = (I3C_CFGR_TXTHRES | I3C_CFGR_RXTHRES); - - /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Check configuration parameters */ - assert_param(IS_I3C_CONTROLFIFOSTATE_VALUE(pConfig->ControlFifo)); - assert_param(IS_I3C_STATUSFIFOSTATE_VALUE(pConfig->StatusFifo)); - - /* Set Control and Status Fifo states */ - cfgr_value |= (pConfig->StatusFifo | pConfig->ControlFifo); - cfgr_mask |= (I3C_CFGR_TMODE | I3C_CFGR_SMODE); - } - - /* Set configuration in the CFGR register */ - MODIFY_REG(hi3c->Instance->CFGR, cfgr_mask, cfgr_value); - } - } - - return status; -} - -/** - * @brief Set I3C controller configuration. - * @note This function is called only when the I3C instance is initialized as controller. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pConfig : [IN] Pointer to an I3C_CtrlConfTypeDef structure that contains controller configuration. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Config(I3C_HandleTypeDef *hi3c, const I3C_CtrlConfTypeDef *pConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t timing2_value; - uint32_t cfgr_value; - - /* Check the I3C handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check on user parameters */ - if (pConfig == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state and mode */ - else if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Check configuration parameters values */ - assert_param(IS_I3C_DYNAMICADDRESS_VALUE(pConfig->DynamicAddr)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HighKeeperSDA)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HotJoinAllowed)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->ACKStallState)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->CCCStallState)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->TxStallState)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->RxStallState)); - - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(hi3c->Instance); - - /* Calculate value to be written in timing register 2 */ - timing2_value = (((uint32_t)pConfig->StallTime << I3C_TIMINGR2_STALL_Pos) | - ((uint32_t)pConfig->ACKStallState << I3C_TIMINGR2_STALLA_Pos) | - ((uint32_t)pConfig->CCCStallState << I3C_TIMINGR2_STALLC_Pos) | - ((uint32_t)pConfig->TxStallState << I3C_TIMINGR2_STALLD_Pos) | - ((uint32_t)pConfig->RxStallState << I3C_TIMINGR2_STALLT_Pos)); - - /* Set value in timing 2 register */ - WRITE_REG(hi3c->Instance->TIMINGR2, timing2_value); - - /* Calculate value to be written in CFGR register */ - cfgr_value = (((uint32_t)pConfig->HighKeeperSDA << I3C_CFGR_HKSDAEN_Pos) | - ((uint32_t)pConfig->HotJoinAllowed << I3C_CFGR_HJACK_Pos)); - - /* Set hot join acknowledge and high keeper values */ - MODIFY_REG(hi3c->Instance->CFGR, I3C_CFGR_HKSDAEN | I3C_CFGR_HJACK, cfgr_value); - - /* Set dynamic address value */ - LL_I3C_SetOwnDynamicAddress(hi3c->Instance, pConfig->DynamicAddr); - - /* Validate the controller dynamic address */ - LL_I3C_EnableOwnDynAddress(hi3c->Instance); - - /* Enable the selected I3C peripheral */ - LL_I3C_Enable(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Set I3C target configuration. - * @note This function is called only when the I3C instance is initialized as target. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pConfig : [IN] Pointer to an I3C_TgtConfTypeDef structure that contains target configuration. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Config(I3C_HandleTypeDef *hi3c, const I3C_TgtConfTypeDef *pConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t getmxdsr_value; - uint32_t maxrlr_value; - uint32_t crccapr_value; - uint32_t bcr_value; - uint32_t devr0_value; - - /* Check the I3C handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check on user parameters */ - if (pConfig == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state and mode */ - else if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_TARGET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Check configuration parameters values */ - assert_param(IS_I3C_HANDOFFACTIVITYSTATE_VALUE(pConfig->HandOffActivityState)); - assert_param(IS_I3C_TSCOTIME_VALUE(pConfig->DataTurnAroundDuration)); - assert_param(IS_I3C_MAXSPEEDDATA_VALUE(pConfig->MaxDataSpeed)); - assert_param(IS_I3C_IBIPAYLOADSIZE_VALUE(pConfig->IBIPayloadSize)); - assert_param(IS_I3C_MIPIIDENTIFIER_VALUE(pConfig->MIPIIdentifier)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HandOffDelay)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->GroupAddrCapability)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->PendingReadMDB)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->IBIPayload)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->MaxSpeedLimitation)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->CtrlCapability)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->IBIRequest)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->CtrlRoleRequest)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HotJoinRequest)); - - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(hi3c->Instance); - - /* Calculate value to be written in the GETMXDSR register */ - getmxdsr_value = (pConfig->HandOffActivityState | pConfig->MaxDataSpeed | pConfig->DataTurnAroundDuration | - ((uint32_t)pConfig->MaxReadTurnAround << I3C_GETMXDSR_RDTURN_Pos)); - - /* Set value in GETMXDSR register */ - WRITE_REG(hi3c->Instance->GETMXDSR, getmxdsr_value); - - /* Calculate value to be written in MAXRLR register */ - maxrlr_value = (pConfig->IBIPayloadSize | (pConfig->MaxReadDataSize & I3C_MAXRLR_MRL)); - - /* Set payload size and max read data size in MAXRLR register */ - WRITE_REG(hi3c->Instance->MAXRLR, maxrlr_value); - - /* Set max write data size in MAXWLR register */ - LL_I3C_SetMaxWriteLength(hi3c->Instance, pConfig->MaxWriteDataSize); - - /* Set MIPI identifier value in EPIDR register */ - LL_I3C_SetMIPIInstanceID(hi3c->Instance, pConfig->MIPIIdentifier); - - /* Set identifier value in DCR register */ - LL_I3C_SetDeviceCharacteristics(hi3c->Instance, pConfig->Identifier); - - /* Calculate value to be written in CRCCAPR register */ - crccapr_value = (((uint32_t)pConfig->HandOffDelay << I3C_CRCAPR_CAPDHOFF_Pos) | - ((uint32_t)pConfig->GroupAddrCapability << I3C_CRCAPR_CAPGRP_Pos)); - - /* Set hand off dealy and group address capability in CRCCAPR register */ - WRITE_REG(hi3c->Instance->CRCAPR, crccapr_value); - - /* Set pending read MDB notification value in GETCAPR register */ - LL_I3C_SetPendingReadMDB(hi3c->Instance, ((uint32_t)pConfig->PendingReadMDB << I3C_GETCAPR_CAPPEND_Pos)); - - /* Calculate value to be written in BCR register */ - bcr_value = (((uint32_t)pConfig->MaxSpeedLimitation << I3C_BCR_BCR0_Pos) | - ((uint32_t)pConfig->IBIPayload << I3C_BCR_BCR2_Pos) | - ((uint32_t)pConfig->CtrlCapability << I3C_BCR_BCR6_Pos)); - - /* Set control capability, IBI payload support and max speed limitation in BCR register */ - WRITE_REG(hi3c->Instance->BCR, bcr_value); - - /* Calculate value to be written in CFGR register */ - devr0_value = (((uint32_t)pConfig->IBIRequest << I3C_DEVR0_IBIEN_Pos) | - ((uint32_t)pConfig->CtrlRoleRequest << I3C_DEVR0_CREN_Pos) | - ((uint32_t)pConfig->HotJoinRequest << I3C_DEVR0_HJEN_Pos)); - - /* Set IBI request, control role request and hot join request in DEVR0 register */ - MODIFY_REG(hi3c->Instance->DEVR0, (I3C_DEVR0_HJEN | I3C_DEVR0_IBIEN | I3C_DEVR0_CREN), devr0_value); - - /* Enable the selected I3C peripheral */ - LL_I3C_Enable(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Set I3C bus devices configuration. - * @note This function is called only when the I3C instance is initialized as controller. - * This function can be called by the controller application to help the automatic treatment when target have - * capability of IBI and/or Control-Role. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pDesc : [IN] Pointer to an I3C_DeviceConfTypeDef descriptor that contains the bus devices - * configurations. - * @param nbDevice : [IN] Value specifies the number of devices to be treated. - * This parameter must be a number between Min_Data=1U and Max_Data=4U. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_ConfigBusDevices(I3C_HandleTypeDef *hi3c, - const I3C_DeviceConfTypeDef *pDesc, - uint8_t nbDevice) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t write_value; - - /* Check the I3C handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check on user parameters */ - if (pDesc == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state and mode */ - else if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - assert_param(IS_I3C_DEVICE_VALUE(nbDevice)); - - /* Loop on the nbDevice to be treated */ - for (uint32_t index = 0U; index < nbDevice; index++) - { - /* Check configuration parameters values */ - assert_param(IS_I3C_DEVICE_VALUE(pDesc[index].DeviceIndex)); - assert_param(IS_I3C_DYNAMICADDRESS_VALUE(pDesc[index].TargetDynamicAddr)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].IBIAck)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].CtrlRoleReqAck)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].CtrlStopTransfer)); - assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].IBIPayload)); - - /* Set value to be written */ - write_value = (((uint32_t)pDesc[index].TargetDynamicAddr << I3C_DEVRX_DA_Pos) | - ((uint32_t)pDesc[index].IBIAck << I3C_DEVRX_IBIACK_Pos) | - ((uint32_t)pDesc[index].CtrlRoleReqAck << I3C_DEVRX_CRACK_Pos) | - ((uint32_t)pDesc[index].CtrlStopTransfer << I3C_DEVRX_SUSP_Pos) | - ((uint32_t)pDesc[index].IBIPayload << I3C_DEVRX_IBIDEN_Pos)); - - /* Write configuration in the DEVRx register */ - WRITE_REG(hi3c->Instance->DEVRX[(pDesc[index].DeviceIndex - 1U)], write_value); - } - } - } - - return status; -} - -/** - * @brief Add Private or CCC descriptor in the user data transfer descriptor. - * @note This function must be called before initiate any communication transfer. This function help the preparation - * of the full transfer usecase in a transfer descriptor which contained different buffer pointers - * and their associated size through I3C_XferTypeDef. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pCCCDesc : [IN] Pointer to an I3C_CCCTypeDef structure that contains the CCC descriptor information. - * @param pPrivateDesc : [IN] Pointer to an I3C_PrivateTypeDef structure that contains the transfer descriptor. - * @param pXferData : [IN/OUT] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * @param nbFrame : [IN] The number of CCC commands or the number of device to treat. - * @param option : [IN] Value indicates the transfer option. It can be one value of @ref I3C_OPTION_DEFINITION - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_AddDescToFrame(I3C_HandleTypeDef *hi3c, - const I3C_CCCTypeDef *pCCCDesc, - const I3C_PrivateTypeDef *pPrivateDesc, - I3C_XferTypeDef *pXferData, - uint8_t nbFrame, - uint32_t option) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->pCCCDesc = pCCCDesc; - hi3c->pPrivateDesc = pPrivateDesc; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = 0; - hi3c->TxXferCount = 0; - - /* Prepare Direction, and Check on user parameters */ - if (((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_CCC) || - ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_DIRECT)) - { - /* Check on user parameters */ - if ((pCCCDesc == NULL) || - (pXferData == NULL) || - (nbFrame < 1U) || - (((option & (I3C_OPERATION_TYPE_MASK | I3C_DEFINE_BYTE_MASK)) == \ - (LL_I3C_CONTROLLER_MTYPE_DIRECT | I3C_DEFINE_BYTE_MASK)) && (pCCCDesc->CCCBuf.Size == 0U))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - } - else - { - /* Check on user parameters */ - if ((pPrivateDesc == NULL) || (pXferData == NULL) || (nbFrame <= 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* check on the State */ - if ((handle_state == HAL_I3C_STATE_READY) || (handle_state == HAL_I3C_STATE_LISTEN)) - { - /* I3C control buffer prior preparation */ - if (I3C_ControlBuffer_PriorPreparation(hi3c, nbFrame, option) != HAL_OK) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - - /* I3C Tx Buffer prior preparation, set and check RxCount */ - if (I3C_Xfer_PriorPreparation(hi3c, nbFrame, option) != HAL_OK) - { - status = HAL_ERROR; - } - } - else - { - status = HAL_BUSY; - } - } - } - - return status; -} - -/** - * @} - */ - -/** @defgroup I3C_Exported_Functions_Group4 FIFO Management functions. - * @brief I3C FIFO management functions. - * -@verbatim - ======================================================================================================================= - ##### FIFO Management functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to manage I3C FIFOs. - - (+) Call the function HAL_I3C_FlushAllFifo() to flush the content of all used FIFOs (Control, Status, - Tx and Rx FIFO). - (+) Call the function HAL_I3C_FlushTxFifo() to flush only the content of Tx FIFO. - (+) Call the function HAL_I3C_FlushRxFifo() to flush only the content of Rx FIFO. - (+) Call the function HAL_I3C_FlushControlFifo() to flush only the content of Control FIFO. - This function is called only when mode is controller. - (+) Call the function HAL_I3C_FlushStatusFifo() to flush only the content of Status FIFO. - This function is called only when mode is controller. - (+) Call the function HAL_I3C_ClearConfigFifo() to clear the FIFOs configuration and set it to default values. - (+) Call the function HAL_I3C_GetConfigFifo() to get the current FIFOs configuration (enabled FIFOs and - threshold level). - - (+) Users must not call all above functions before I3C initialization. - - (+) Users should call Flush APIs after an end of process, before starting a transfer or in case of bus - failure and error detection. - -@endverbatim - * @{ - */ - -/** - * @brief Flush all I3C FIFOs content. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_FlushAllFifo(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t cfgr_value; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state */ - if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Flush the content of Tx and Rx Fifo */ - cfgr_value = (I3C_CFGR_TXFLUSH | I3C_CFGR_RXFLUSH); - - /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Flush the content of Control and Status Fifo */ - cfgr_value = (I3C_CFGR_SFLUSH | I3C_CFGR_CFLUSH); - } - - /* Set configuration in the CFGR register */ - MODIFY_REG(hi3c->Instance->CFGR, cfgr_value, cfgr_value); - } - } - - return status; -} - -/** - * @brief Flush I3C Tx FIFO content. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_FlushTxFifo(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state */ - if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Flush the content of Tx Fifo */ - LL_I3C_RequestTxFIFOFlush(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Flush I3C Rx FIFO content. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_FlushRxFifo(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state */ - if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Flush the content of Rx Fifo */ - LL_I3C_RequestRxFIFOFlush(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Flush I3C control FIFO content. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_FlushControlFifo(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state and mode */ - if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Flush the content of Control Fifo */ - LL_I3C_RequestControlFIFOFlush(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Flush I3C status FIFO content. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_FlushStatusFifo(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state and mode */ - if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Flush the content of Control Fifo */ - LL_I3C_RequestStatusFIFOFlush(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Clear I3C FIFOs configuration and set it to default values. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_ClearConfigFifo(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t cfgr_value; - uint32_t cfgr_mask; - - /* Check the I3C handle allocation */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check the I3C state */ - if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Clear Tx Fifo and Rx Fifo threshold and set it to default value */ - cfgr_value = (LL_I3C_TXFIFO_THRESHOLD_1_4 | LL_I3C_RXFIFO_THRESHOLD_1_4); - cfgr_mask = (I3C_CFGR_TXTHRES | I3C_CFGR_RXTHRES); - - /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Disable the status and Control Fifo state */ - cfgr_value |= (HAL_I3C_STATUSFIFO_DISABLE | HAL_I3C_CONTROLFIFO_DISABLE); - cfgr_mask |= (I3C_CFGR_TMODE | I3C_CFGR_SMODE); - } - - /* Set configuration in the CFGR register */ - MODIFY_REG(hi3c->Instance->CFGR, cfgr_mask, cfgr_value); - } - } - - return status; -} - -/** - * @brief Get I3C FIFOs current configuration. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pConfig : [IN/OUT] Pointer to an I3C_FifoConfTypeDef structure that returns current FIFOs configuration. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_GetConfigFifo(I3C_HandleTypeDef *hi3c, I3C_FifoConfTypeDef *pConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the I3C handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Check on user parameters */ - if (pConfig == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state */ - else if (hi3c->State == HAL_I3C_STATE_RESET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Get Tx Fifo threshold */ - pConfig->TxFifoThreshold = LL_I3C_GetTxFIFOThreshold(hi3c->Instance); - - /* Get Rx Fifo threshold */ - pConfig->RxFifoThreshold = LL_I3C_GetRxFIFOThreshold(hi3c->Instance); - - /* Get the Control Fifo state */ - pConfig->ControlFifo = (uint32_t)(LL_I3C_IsEnabledControlFIFO(hi3c->Instance) << I3C_CFGR_TMODE_Pos); - - /* Get the status Fifo state */ - pConfig->StatusFifo = (uint32_t)(LL_I3C_IsEnabledStatusFIFO(hi3c->Instance) << I3C_CFGR_SMODE_Pos); - } - } - - return status; -} -/** - * @} - */ - -/** @defgroup I3C_Exported_Functions_Group5 Controller operational functions. - * @brief I3C controller operational functions. - * -@verbatim - ======================================================================================================================= - ##### Controller operational functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to manage controller I3C operation. - - (+) Call the function HAL_I3C_Ctrl_TransmitCCC() to transmit direct write or a broadcast - CCC command in polling mode. - (+) Call the function HAL_I3C_Ctrl_TransmitCCC_IT() to transmit direct write or a broadcast - CCC command in interrupt mode. - (+) Call the function HAL_I3C_Ctrl_TransmitCCC_DMA() to transmit direct write or a broadcast - CCC command in DMA mode. - (+) Call the function HAL_I3C_Ctrl_ReceiveCCC() to transmit direct read CCC command in polling mode. - (+) Call the function HAL_I3C_Ctrl_ReceiveCCC_IT() to transmit direct read CCC command in interrupt mode. - (+) Call the function HAL_I3C_Ctrl_ReceiveCCC_DMA() to transmit direct read CCC command in DMA mode. - (+) Call the function HAL_I3C_Ctrl_Transmit() to transmit private data in polling mode. - (+) Call the function HAL_I3C_Ctrl_Transmit_IT() to transmit private data in interrupt mode. - (+) Call the function HAL_I3C_Ctrl_Transmit_DMA() to transmit private data in DMA mode. - (+) Call the function HAL_I3C_Ctrl_Receive() to receive private data in polling mode. - (+) Call the function HAL_I3C_Ctrl_Receive_IT() to receive private data in interrupt mode. - (+) Call the function HAL_I3C_Ctrl_Receive_DMA() to receive private data in DMA mode. - (+) Call the function HAL_I3C_Ctrl_MultipleTransfer_IT() to transfer I3C or I2C private data or CCC command - in multiple direction in interrupt mode. - (+) Call the function HAL_I3C_Ctrl_MultipleTransfer_DMA() to transfer I3C or I2C private data or CCC command - in multiple direction in DMA mode. - (+) Call the function HAL_I3C_Ctrl_DynAddrAssign() to send a broadcast ENTDAA CCC - command in polling mode. - (+) Call the function HAL_I3C_Ctrl_DynAddrAssign_IT() to send a broadcast ENTDAA CCC - command in interrupt mode. - (+) Call the function HAL_I3C_Ctrl_SetDynAddr() to set, asscociate the target dynamic address - during the Dynamic Address Assignment processus. - (+) Call the function HAL_I3C_Ctrl_IsDeviceI3C_Ready() to check if I3C target device is ready. - (+) Call the function HAL_I3C_Ctrl_IsDeviceI2C_Ready() to check if I2C target device is ready. - - (+) Those functions are called only when mode is Controller. - -@endverbatim - * @{ - */ - -/** - * @brief Controller transmit direct write or a broadcast CCC command in polling mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_TransmitCCC(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData, - uint32_t timeout) -{ - uint32_t tickstart; - uint32_t exit_condition; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - /* Update returned status value */ - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - hi3c->pXferData = pXferData; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check on control FIFO enable/disable state */ - if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) - { - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Decrement remaining control buffer data counter */ - hi3c->ControlXferCount--; - - /* Initiate a start condition by writing in the CR register */ - WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); - - /* Increment Buffer pointer */ - hi3c->pXferData->CtrlBuf.pBuffer++; - } - - /* Do while until FC (Frame Complete) is set or timeout */ - do - { - /* Check if hardware asks for control data */ - if (hi3c->ControlXferCount > 0U) - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - } - - /* Check if hardware asks for Tx data */ - if (hi3c->TxXferCount > 0U) - { - /* Call transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - } - - /* Check for the timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - break; - } - } - - if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - - /* Calculate exit_condition value based on Frame complete and error flags */ - exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); - } while ((exit_condition == 0U) || - ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update returned status value */ - status = HAL_ERROR; - } - - /* At the end of Tx process update state to Previous state */ - I3C_StateUpdate(hi3c); - } - } - - return status; -} - -/** - * @brief Controller transmit direct write or a broadcast CCC command in interrupt mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_TransmitCCC_IT(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - if (handle_state == HAL_I3C_STATE_LISTEN) - { - hi3c->XferISR = I3C_Ctrl_Tx_Listen_Event_ISR; - } - else - { - hi3c->XferISR = I3C_Ctrl_Tx_ISR; - } - - hi3c->pXferData = pXferData; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Controller transmit direct write or a broadcast CCC command in DMA mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_TransmitCCC_DMA(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_StatusTypeDef control_dma_status; - HAL_StatusTypeDef tx_dma_status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t size_align_word; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmatx and hdmacr handle */ - else if ((hi3c->hdmatx == NULL) || (hi3c->hdmacr == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->XferISR = I3C_Ctrl_Tx_DMA_ISR; - hi3c->pXferData = pXferData; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - - /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmacr->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmacr->XferHalfCpltCallback = NULL; - hi3c->hdmacr->XferAbortCallback = NULL; - - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); - - /* Enable the control data DMA channel */ - control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, - (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); - - /*------------------------------------ I3C DMA channel for the Tx Data -----------------------------------------*/ - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmatx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmatx->XferHalfCpltCallback = NULL; - hi3c->hdmatx->XferAbortCallback = NULL; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->TxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); - } - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDWR, size_align_word); - } - } - - /* Check if DMA process is well started */ - if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK)) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->ControlXferCount = 0U; - - /* Enable control DMA Request */ - LL_I3C_EnableDMAReq_Control(hi3c->Instance); - - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Enable Tx data DMA Request */ - LL_I3C_EnableDMAReq_TX(hi3c->Instance); - } - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) - { - hi3c->hdmacr->XferCpltCallback = NULL; - hi3c->hdmacr->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) - { - hi3c->hdmatx->XferCpltCallback = NULL; - hi3c->hdmatx->XferErrorCallback = NULL; - } - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - } - - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Controller transmit direct read CCC command in polling mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_ReceiveCCC(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData, - uint32_t timeout) -{ - uint32_t tickstart; - uint32_t exit_condition; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - (pXferData->RxBuf.pBuffer == NULL) || - ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - - /* Check on CCC defining byte */ - if (hi3c->TxXferCount != 0U) - { - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - } - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check on control FIFO enable/disable state */ - if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) - { - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Decrement remaining control buffer data counter */ - hi3c->ControlXferCount--; - - /* Initiate a start condition by writing in the CR register */ - WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); - - /* Increment Buffer pointer */ - hi3c->pXferData->CtrlBuf.pBuffer++; - } - - /* Do while until FC (Frame Complete) is set or timeout */ - do - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - - if (hi3c->TxXferCount != 0U) - { - /* Call transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - } - - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - - /* Check for the timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - - break; - } - } - - if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - - /* Calculate exit_condition value based on Frame complete and error flags */ - exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); - } while ((exit_condition == 0U) || - ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check if all data bytes are received */ - if ((hi3c->RxXferCount != 0U) && (status == HAL_OK)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - status = HAL_ERROR; - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update returned status value */ - status = HAL_ERROR; - } - - /* At the end of Rx process update state to Previous state */ - I3C_StateUpdate(hi3c); - } - } - - return status; -} - -/** - * @brief Controller transmit direct read CCC command in interrupt mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_ReceiveCCC_IT(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - (pXferData->RxBuf.pBuffer == NULL) || - ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - if (handle_state == HAL_I3C_STATE_LISTEN) - { - hi3c->XferISR = I3C_Ctrl_Rx_Listen_Event_ISR; - } - else - { - hi3c->XferISR = I3C_Ctrl_Rx_ISR; - } - hi3c->pXferData = pXferData; - hi3c->RxXferCount = pXferData->RxBuf.Size; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - - /* Check on CCC defining byte */ - if (hi3c->TxXferCount != 0U) - { - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - } - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Rx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - - } - } - - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Controller transmit direct read CCC command in DMA mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_ReceiveCCC_DMA(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - HAL_StatusTypeDef control_dma_status; - HAL_StatusTypeDef tx_dma_status = HAL_OK; - HAL_StatusTypeDef rx_dma_status = HAL_OK; - uint32_t size_align_word; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - (pXferData->RxBuf.pBuffer == NULL) || - ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmarx and hdmacr handle */ - else if ((hi3c->hdmarx == NULL) || (hi3c->hdmacr == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - else if ((hi3c->TxXferCount != 0U) && (hi3c->hdmatx == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->XferISR = I3C_Ctrl_Rx_DMA_ISR; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - - /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmacr->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmacr->XferHalfCpltCallback = NULL; - hi3c->hdmacr->XferAbortCallback = NULL; - - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); - - /* Enable the control data DMA channel */ - control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, - (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); - - /*------------------------------------ I3C DMA channel for defining byte ---------------------------------------*/ - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmatx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmatx->XferHalfCpltCallback = NULL; - hi3c->hdmatx->XferAbortCallback = NULL; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDWR, size_align_word); - } - } - /*------------------------------------ I3C DMA channel for the Rx Data -----------------------------------------*/ - /* Check if Rx counter different from zero */ - if (hi3c->RxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; - - /* Set the DMA error callback */ - hi3c->hdmarx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmarx->XferHalfCpltCallback = NULL; - hi3c->hdmarx->XferAbortCallback = NULL; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->RxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); - } - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); - } - } - - /* Check if DMA process is well started */ - if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK) && (rx_dma_status == HAL_OK)) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Rx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->ControlXferCount = 0U; - - /* Enable control DMA Request */ - LL_I3C_EnableDMAReq_Control(hi3c->Instance); - - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Enable Tx data DMA Request */ - LL_I3C_EnableDMAReq_TX(hi3c->Instance); - } - - /* Check if Rx counter different from zero */ - if (hi3c->RxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Enable Rx data DMA Request */ - LL_I3C_EnableDMAReq_RX(hi3c->Instance); - } - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) - { - hi3c->hdmacr->XferCpltCallback = NULL; - hi3c->hdmacr->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) - { - hi3c->hdmatx->XferCpltCallback = NULL; - hi3c->hdmatx->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmarx) == HAL_OK) - { - hi3c->hdmarx->XferCpltCallback = NULL; - hi3c->hdmarx->XferErrorCallback = NULL; - } - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - } - - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Controller private write in polling mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Transmit(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData, - uint32_t timeout) -{ - uint32_t tickstart; - uint32_t exit_condition; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - hi3c->pXferData = pXferData; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check on control FIFO enable/disable state */ - if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) - { - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Decrement remaining control buffer data counter */ - hi3c->ControlXferCount--; - - /* Initiate a start condition by writing in the CR register */ - WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); - - /* Increment Buffer pointer */ - hi3c->pXferData->CtrlBuf.pBuffer++; - } - - /* Do while until FC (Frame Complete) is set or timeout */ - do - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - - /* Call transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - - /* Check for the timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - - break; - } - } - - if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - - /* Calculate exit_condition value based on Frame complete and error flags */ - exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); - } while ((exit_condition == 0U) || - ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check if all data bytes are transmitted */ - if ((hi3c->TxXferCount != 0U) && (status == HAL_OK)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - status = HAL_ERROR; - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update returned status value */ - status = HAL_ERROR; - } - - /* At the end of Tx process update state to Previous state */ - I3C_StateUpdate(hi3c); - } - } - - return status; -} - -/** - * @brief Controller private write in interrupt mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Transmit_IT(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - if (handle_state == HAL_I3C_STATE_LISTEN) - { - hi3c->XferISR = I3C_Ctrl_Tx_Listen_Event_ISR; - } - else - { - hi3c->XferISR = I3C_Ctrl_Tx_ISR; - } - hi3c->pXferData = pXferData; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Controller private write in DMA mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Transmit_DMA(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_StatusTypeDef control_dma_status; - HAL_StatusTypeDef tx_dma_status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t size_align_word; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmatx and hdmacr handle */ - else if ((hi3c->hdmatx == NULL) || (hi3c->hdmacr == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->XferISR = I3C_Ctrl_Tx_DMA_ISR; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - hi3c->pXferData = pXferData; - - /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmacr->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmacr->XferHalfCpltCallback = NULL; - hi3c->hdmacr->XferAbortCallback = NULL; - - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); - - /* Enable the control data DMA channel */ - control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, - (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); - - /*------------------------------------ I3C DMA channel for the Tx Data -----------------------------------------*/ - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmatx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmatx->XferHalfCpltCallback = NULL; - hi3c->hdmatx->XferAbortCallback = NULL; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->TxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); - } - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDWR, size_align_word); - } - } - - /* Check if DMA process is well started */ - if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK)) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->ControlXferCount = 0U; - - /* Enable control DMA Request */ - LL_I3C_EnableDMAReq_Control(hi3c->Instance); - - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Enable Tx data DMA Request */ - LL_I3C_EnableDMAReq_TX(hi3c->Instance); - } - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) - { - hi3c->hdmacr->XferCpltCallback = NULL; - hi3c->hdmacr->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) - { - hi3c->hdmatx->XferCpltCallback = NULL; - hi3c->hdmatx->XferErrorCallback = NULL; - } - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - } - - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Controller private read in polling mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Receive(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData, - uint32_t timeout) -{ - uint32_t tickstart; - uint32_t exit_condition; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check on control FIFO enable/disable state */ - if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) - { - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Decrement remaining control buffer data counter */ - hi3c->ControlXferCount--; - - /* Initiate a start condition by writing in the CR register */ - WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); - - /* Increment Buffer pointer */ - hi3c->pXferData->CtrlBuf.pBuffer++; - } - - /* Do while until FC (Frame Complete) is set or timeout */ - do - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - - /* Check for the timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - - break; - } - } - - if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - - /* Calculate exit_condition value based on Frame complete and error flags */ - exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); - } while ((exit_condition == 0U) || - ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check if all data bytes are received */ - if ((hi3c->RxXferCount != 0U) && (status == HAL_OK)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - status = HAL_ERROR; - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update returned status value */ - status = HAL_ERROR; - } - - /* At the end of Rx process update state to Previous state */ - I3C_StateUpdate(hi3c); - } - } - - return status; -} - -/** - * @brief Controller private read in interrupt mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Receive_IT(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - if (handle_state == HAL_I3C_STATE_LISTEN) - { - hi3c->XferISR = I3C_Ctrl_Rx_Listen_Event_ISR; - } - else - { - hi3c->XferISR = I3C_Ctrl_Rx_ISR; - } - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Rx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_IT); - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Controller private read in DMA mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers - * (control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_Receive_DMA(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_StatusTypeDef control_dma_status; - HAL_StatusTypeDef rx_dma_status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t size_align_word; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmarx and hdmacr handle */ - else if ((hi3c->hdmarx == NULL) || (hi3c->hdmacr == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->XferISR = I3C_Ctrl_Rx_DMA_ISR; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - - /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmacr->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmacr->XferHalfCpltCallback = NULL; - hi3c->hdmacr->XferAbortCallback = NULL; - - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); - - /* Enable the control data DMA channel */ - control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, - (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); - - /*------------------------------------ I3C DMA channel for the Rx Data -----------------------------------------*/ - /* Check if Rx counter different from zero */ - if (hi3c->RxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; - - /* Set the DMA error callback */ - hi3c->hdmarx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmarx->XferHalfCpltCallback = NULL; - hi3c->hdmarx->XferAbortCallback = NULL; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->RxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); - } - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); - } - } - - /* Check if DMA process is well started */ - if ((control_dma_status == HAL_OK) && (rx_dma_status == HAL_OK)) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Rx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->ControlXferCount = 0U; - - /* Enable control DMA Request */ - LL_I3C_EnableDMAReq_Control(hi3c->Instance); - - /* Check if Rx counter different from zero */ - if (hi3c->RxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Enable Rx data DMA Request */ - LL_I3C_EnableDMAReq_RX(hi3c->Instance); - } - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) - { - hi3c->hdmacr->XferCpltCallback = NULL; - hi3c->hdmacr->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmarx) == HAL_OK) - { - hi3c->hdmarx->XferCpltCallback = NULL; - hi3c->hdmarx->XferErrorCallback = NULL; - } - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - - } - } - - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Controller multiple Direct CCC Command, I3C private or I2C transfer in interrupt mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @note This function must be called to transfer read/write I3C or I2C private data or a direct read/write CCC. - * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmit and receive - * buffers (control buffer, data buffers and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_MultipleTransfer_IT(I3C_HandleTypeDef *hi3c, - I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((pXferData->RxBuf.pBuffer == NULL) && (hi3c->RxXferCount != 0U)) || - ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - if (handle_state == HAL_I3C_STATE_LISTEN) - { - hi3c->XferISR = I3C_Ctrl_Multiple_Xfer_Listen_Event_ISR; - } - else - { - hi3c->XferISR = I3C_Ctrl_Multiple_Xfer_ISR; - } - hi3c->pXferData = pXferData; - hi3c->TxXferCount = hi3c->pXferData->TxBuf.Size; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - hi3c->State = HAL_I3C_STATE_BUSY_TX_RX; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx and Rx process interrupts */ - I3C_Enable_IRQ(hi3c, (I3C_XFER_CONTROLLER_TX_IT | I3C_XFER_CONTROLLER_RX_IT)); - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Controller multiple Direct CCC Command, I3C private or I2C transfer in DMA mode. - * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. - * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - * multiple transmission frames. - * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. - * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. - * @note This function must be called to transfer read/write private data or a direct read/write CCC command. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmit and receive - * buffers(control buffer, data buffer and status buffer). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_MultipleTransfer_DMA(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) -{ - HAL_StatusTypeDef control_dma_status; - HAL_StatusTypeDef tx_dma_status = HAL_OK; - HAL_StatusTypeDef rx_dma_status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t size_align_word; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || - ((pXferData->RxBuf.pBuffer == NULL) && (hi3c->RxXferCount != 0U)) || - ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmatx, hdmarx and hdmacr handle */ - else if ((hi3c->hdmatx == NULL) || (hi3c->hdmacr == NULL) || (hi3c->hdmarx == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->XferISR = I3C_Ctrl_Multiple_Xfer_DMA_ISR; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; - hi3c->TxXferCount = hi3c->pXferData->TxBuf.Size; - hi3c->State = HAL_I3C_STATE_BUSY_TX_RX; - - /*------------------------------------ I3C DMA channel for Control Data -------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmacr->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmacr->XferHalfCpltCallback = NULL; - hi3c->hdmacr->XferAbortCallback = NULL; - - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); - - /* Enable the control data DMA channel */ - control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, - (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); - - /*------------------------------------ I3C DMA channel for the Rx Data --------------------------------*/ - /* Check if Rx counter different from zero */ - if (hi3c->RxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; - - /* Set the DMA error callback */ - hi3c->hdmarx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmarx->XferHalfCpltCallback = NULL; - hi3c->hdmarx->XferAbortCallback = NULL; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->RxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); - } - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); - } - } - - /*------------------------------------ I3C DMA channel for the Tx Data --------------------------------*/ - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmatx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmatx->XferHalfCpltCallback = NULL; - hi3c->hdmatx->XferAbortCallback = NULL; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->TxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); - } - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDWR, size_align_word); - } - } - - /* Check if DMA process is well started */ - if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK) && (rx_dma_status == HAL_OK)) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->ControlXferCount = 0U; - - /* Enable control DMA Request */ - LL_I3C_EnableDMAReq_Control(hi3c->Instance); - - /* Check if Rx counter different from zero */ - if (hi3c->RxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Enable Rx data DMA Request */ - LL_I3C_EnableDMAReq_RX(hi3c->Instance); - } - - /* Check if Tx counter different from zero */ - if (hi3c->TxXferCount != 0U) - { - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Enable Tx data DMA Request */ - LL_I3C_EnableDMAReq_TX(hi3c->Instance); - } - - /* Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) - { - hi3c->hdmacr->XferCpltCallback = NULL; - hi3c->hdmacr->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) - { - hi3c->hdmatx->XferCpltCallback = NULL; - hi3c->hdmatx->XferErrorCallback = NULL; - } - - /* Set callback to NULL if DMA started */ - if (HAL_DMA_Abort(hi3c->hdmarx) == HAL_OK) - { - hi3c->hdmarx->XferCpltCallback = NULL; - hi3c->hdmarx->XferErrorCallback = NULL; - } - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - } - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Controller assign dynamic address (send a broadcast ENTDAA CCC command) in polling mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param target_payload : [IN/OUT] Pointer to the returned target payload value. - * @param dynOption : [IN] Parameter indicates the Dynamic address assignment option. - * It can be one value of @ref I3C_DYNAMIC_ADDRESS_OPTION_DEFINITION. - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_DynAddrAssign(I3C_HandleTypeDef *hi3c, - uint64_t *target_payload, - uint32_t dynOption, - uint32_t timeout) -{ - uint32_t tickstart; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on parameters */ - assert_param(IS_I3C_ENTDAA_OPTION(dynOption)); - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - if (target_payload == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Launch a RSTDAA procedure before launch ENTDAA */ - if ((dynOption == I3C_RSTDAA_THEN_ENTDAA) && - ((handle_state == HAL_I3C_STATE_READY) || (handle_state == HAL_I3C_STATE_LISTEN))) - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_DAA; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Enable arbitration header */ - LL_I3C_EnableArbitrationHeader(hi3c->Instance); - - /* Write CCC information in the control register */ - LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_RSTDAA, 0U, LL_I3C_GENERATE_STOP); - - /* Wait Frame completion flag */ - status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_FCF, RESET, timeout, tickstart); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - status = HAL_ERROR; - } - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - - if (status == HAL_OK) - { - /* check on the State */ - if ((handle_state == HAL_I3C_STATE_READY) || (handle_state == HAL_I3C_STATE_LISTEN) || - (handle_state == HAL_I3C_STATE_BUSY_DAA)) - { - /* Check on the state */ - if (handle_state != HAL_I3C_STATE_BUSY_DAA) - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_DAA; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Enable arbitration header */ - LL_I3C_EnableArbitrationHeader(hi3c->Instance); - - /* Write CCC information in the control register */ - LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_ENTDAA, 0U, LL_I3C_GENERATE_STOP); - } - else - { - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - } - - /* Wait frame complete flag or TX FIFO not full flag until timeout */ - status = I3C_WaitOnDAAUntilTimeout(hi3c, timeout, tickstart); - - /* Check TX FIFO not full flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) - { - /* Check on the Rx FIFO threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* For loop to get target payload */ - for (uint32_t index = 0U; index < 8U; index++) - { - /* Retrieve payload byte by byte */ - *target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData8(hi3c->Instance) << (index * 8U)); - } - } - else - { - /* Retrieve first 32 bits payload */ - *target_payload = (uint64_t)LL_I3C_ReceiveData32(hi3c->Instance); - - /* Retrieve second 32 bits payload */ - *target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData32(hi3c->Instance) << 32U); - } - - status = HAL_BUSY; - } - /* Check on frame complete flag */ - else - { - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - } - } - - return status; -} - -/** - * @brief Controller assign dynamic address (send a broadcast ENTDAA CCC command) in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param dynOption : [IN] Parameter indicates the Dynamic address assignment option. - * It can be one value of @ref I3C_DYNAMIC_ADDRESS_OPTION_DEFINITION. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_DynAddrAssign_IT(I3C_HandleTypeDef *hi3c, uint32_t dynOption) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on parameters */ - assert_param(IS_I3C_ENTDAA_OPTION(dynOption)); - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_DAA; - hi3c->XferISR = I3C_Ctrl_DAA_ISR; - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Dynamic Address Assignment process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_DAA_IT); - - /* Enable arbitration header */ - LL_I3C_EnableArbitrationHeader(hi3c->Instance); - - /* Launch a RSTDAA procedure before launch ENTDAA */ - if (dynOption == I3C_RSTDAA_THEN_ENTDAA) - { - /* Write RSTDAA CCC information in the control register */ - LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_RSTDAA, 0U, LL_I3C_GENERATE_RESTART); - } - else - { - /* Write ENTDAA CCC information in the control register */ - LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_ENTDAA, 0U, LL_I3C_GENERATE_STOP); - } - } - } - - return status; -} - -/** - * @brief Controller set dynamic address. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param devAddress : [IN] Value of the dynamic address to be assigned. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_SetDynAddr(I3C_HandleTypeDef *hi3c, uint8_t devAddress) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check if Tx FIFO requests data */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) - { - /* Write device address in the TDR register */ - LL_I3C_TransmitData8(hi3c->Instance, devAddress); - } - else - { - status = HAL_ERROR; - } - } - - return status; -} - -/** - * @brief Check if I3C target device is ready for communication. - * @param hi3c : [IN] Pointer to a I3C_HandleTypeDef structure that contains - * the configuration information for the specified I3C. - * @param devAddress : [IN] Value of the device dynamic address. - * @param trials : [IN] Number of trials - * @param timeout : [IN] Timeout duration - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_IsDeviceI3C_Ready(I3C_HandleTypeDef *hi3c, - uint8_t devAddress, - uint32_t trials, - uint32_t timeout) -{ - I3C_DeviceTypeDef device; - HAL_StatusTypeDef status; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Initiate a device address */ - device.Address = devAddress; - - /* Initiate a message type */ - device.MessageType = LL_I3C_CONTROLLER_MTYPE_PRIVATE; - - /* Check if the device is ready*/ - status = I3C_Ctrl_IsDevice_Ready(hi3c, &device, trials, timeout); - } - - return status; -} - -/** - * @brief Check if I2C target device is ready for communication. - * @param hi3c : [IN] Pointer to a I3C_HandleTypeDef structure that contains - * the configuration information for the specified I3C. - * @param devAddress : [IN] Value of the device dynamic address. - * @param trials : [IN] Number of trials - * @param timeout : [IN] Timeout duration - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Ctrl_IsDeviceI2C_Ready(I3C_HandleTypeDef *hi3c, - uint8_t devAddress, - uint32_t trials, - uint32_t timeout) -{ - I3C_DeviceTypeDef device; - HAL_StatusTypeDef status; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Initiate a device address */ - device.Address = devAddress; - - /* Initiate a message type */ - device.MessageType = LL_I3C_CONTROLLER_MTYPE_LEGACY_I2C; - - /* Check if the device is ready*/ - status = I3C_Ctrl_IsDevice_Ready(hi3c, &device, trials, timeout); - } - - return status; -} -/** - * @} - */ - -/** @defgroup I3C_Exported_Functions_Group6 Target operational functions. - * @brief I3C target operational functions. - * -@verbatim - ======================================================================================================================= - ##### Target operational functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to manage target I3C operation. - - (+) Call the function HAL_I3C_Tgt_Transmit() to transmit private data in polling mode. - (+) Call the function HAL_I3C_Tgt_Transmit_IT() to transmit private data in interrupt mode. - (+) Call the function HAL_I3C_Tgt_Transmit_DMA() to transmit private data in DMA mode. - (+) Call the function HAL_I3C_Tgt_Receive() to receive private data in polling mode. - (+) Call the function HAL_I3C_Tgt_Receive_IT() to receive private data in interrupt mode. - (+) Call the function HAL_I3C_Tgt_Receive_DMA() to receive private data in DMA mode. - (+) Call the function HAL_I3C_Tgt_ControlRoleReq() to send a control-role request in polling mode. - (+) Call the function HAL_I3C_Tgt_ControlRoleReq_IT() to send a control-role request in interrupt mode. - (+) Call the function HAL_I3C_Tgt_HotJoinReq() to send a Hot-Join request in polling mode. - (+) Call the function HAL_I3C_Tgt_HotJoinReq_IT() to send a Hot-Join request in interrupt mode. - (+) Call the function HAL_I3C_Tgt_IBIReq() to send an IBI request in polling mode. - (+) Call the function HAL_I3C_Tgt_IBIReq_IT() to send an IBI request in interrupt mode. - - (+) Those functions are called only when mode is Target. - -@endverbatim - * @{ - */ - -/** - * @brief Target transmit private data in polling mode. - * @note Target FIFO preload data is forced within this API for timing purpose. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * information (Pointer to the Tx buffer (TxBuf.pBuffer) and size of data - * to transmit in bytes (TxBuf.Size)). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Transmit(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData, uint32_t timeout) -{ - uint32_t tickstart; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - uint32_t it_source; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - it_source = READ_REG(hi3c->Instance->IER); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->TxBuf.pBuffer == NULL) || (pXferData->TxBuf.Size == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* check if DEF or GRP CCC notifications are enabled */ - else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - hi3c->pXferData = pXferData; - hi3c->TxXferCount = pXferData->TxBuf.Size; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Set Preload information */ - LL_I3C_ConfigTxPreload(hi3c->Instance, (uint16_t)hi3c->pXferData->TxBuf.Size); - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Do while until FC (Frame Complete) is set or timeout */ - do - { - /* Call transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - - /* Check for the Timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - - break; - } - } - /* Exit loop on Frame complete or error flags */ - } while ((READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)) == 0U); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check if all data bytes are transmitted */ - if ((LL_I3C_GetXferDataCount(hi3c->Instance) != hi3c->pXferData->TxBuf.Size) && (status == HAL_OK)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - status = HAL_ERROR; - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update returned status value */ - status = HAL_ERROR; - } - - /* At the end of Tx process update state to Previous state */ - I3C_StateUpdate(hi3c); - } - } - - return status; -} - -/** - * @brief Target transmit private data in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * information (Pointer to the Tx buffer (TxBuf.pBuffer) and size of data - * to transmit in bytes (TxBuf.Size)). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Transmit_IT(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t it_source; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - it_source = READ_REG(hi3c->Instance->IER); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->TxBuf.pBuffer == NULL) || (pXferData->TxBuf.Size == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* check if DEF and GRP CCC notifications are enabled */ - else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - - status = HAL_ERROR; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - hi3c->pXferData = pXferData; - hi3c->TxXferCount = pXferData->TxBuf.Size; - hi3c->XferISR = I3C_Tgt_Tx_ISR; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; - } - - /* Set Preload information */ - LL_I3C_ConfigTxPreload(hi3c->Instance, (uint16_t)hi3c->pXferData->TxBuf.Size); - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_TX_IT); - } - } - - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Target transmit private data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers - * information (Pointer to the Tx buffer (TxBuf.pBuffer) and size of data - * to transmit in bytes (TxBuf.Size)). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Transmit_DMA(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) -{ - HAL_StatusTypeDef tx_dma_status; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t size_align_word; - uint32_t it_source; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - it_source = READ_REG(hi3c->Instance->IER); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->TxBuf.pBuffer == NULL) || (pXferData->TxBuf.Size == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmatx handle */ - else if (hi3c->hdmatx == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* check if DEF and GRP CCC notifications are enabled */ - else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_TX; - hi3c->pXferData = pXferData; - hi3c->TxXferCount = pXferData->TxBuf.Size; - hi3c->XferISR = I3C_Tgt_Tx_DMA_ISR; - - /* Set Preload information */ - LL_I3C_ConfigTxPreload(hi3c->Instance, (uint16_t)hi3c->pXferData->TxBuf.Size); - - /*------------------------------------ I3C DMA channel for the Tx Data -----------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; - - /* Set the DMA error callback */ - hi3c->hdmatx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmatx->XferHalfCpltCallback = NULL; - hi3c->hdmatx->XferAbortCallback = NULL; - - /* Check on the Tx threshold to know the Tx treatment process : byte or word */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->TxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); - } - - /* Enable the Tx data DMA channel */ - tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, - (uint32_t)&hi3c->Instance->TDWR, size_align_word); - } - - /* Check if DMA process is well started */ - if (tx_dma_status == HAL_OK) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Tx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Enable Tx data DMA Request */ - LL_I3C_EnableDMAReq_TX(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - hi3c->hdmatx->XferCpltCallback = NULL; - hi3c->hdmatx->XferErrorCallback = NULL; - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - } - - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Target receive private data in polling mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers - * information (Pointer to the Rx buffer (RxBuf.pBuffer) and size of data - * to be received in bytes (RxBuf.Size)). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Receive(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData, uint32_t timeout) -{ - uint32_t tickstart; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - uint32_t it_source; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - it_source = READ_REG(hi3c->Instance->IER); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL) || (pXferData->RxBuf.Size == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* check if DEF and GRP CCC notifications are enabled */ - else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = pXferData->RxBuf.Size; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Do while until FC (Frame Complete) is set or timeout */ - do - { - if (hi3c->RxXferCount > 0U) - { - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - } - - /* Check for the Timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - - break; - } - } - /* Exit loop on Frame complete or error flags */ - } while ((READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)) == 0U); - - /* Clear frame complete flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) - { - LL_I3C_ClearFlag_FC(hi3c->Instance); - } - - /* Check if all data bytes are received */ - if ((LL_I3C_GetXferDataCount(hi3c->Instance) != hi3c->pXferData->RxBuf.Size) && (status == HAL_OK)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - status = HAL_ERROR; - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - status = HAL_ERROR; - } - - /* At the end of Rx process update state to previous state */ - I3C_StateUpdate(hi3c); - } - } - - return status; -} - -/** - * @brief Target receive private data in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers - * information (Pointer to the Rx buffer (RxBuf.pBuffer) and size of data - * to be received in bytes (RxBuf.Size)). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Receive_IT(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t it_source; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - it_source = READ_REG(hi3c->Instance->IER); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL) || (pXferData->RxBuf.Size == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* check if DEF and GRP CCC notifications are enabled */ - else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = pXferData->RxBuf.Size; - hi3c->XferISR = I3C_Tgt_Rx_ISR; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* Set byte treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; - } - else - { - /* Set word treatment function pointer */ - hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; - } - - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Rx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_RX_IT); - } - } - - return status; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Target receive private data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers - * information (Pointer to the Rx buffer (RxBuf.pBuffer) and size of data - * to be received in bytes (RxBuf.Size)). - * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_Receive_DMA(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) -{ - HAL_StatusTypeDef rx_dma_status; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - uint32_t size_align_word; - uint32_t it_source; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - it_source = READ_REG(hi3c->Instance->IER); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on user parameters */ - if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL) || (pXferData->RxBuf.Size == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on hdmarx handle */ - else if (hi3c->hdmarx == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - /* check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* check if DEF and GRP CCC notifications are enabled */ - else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || - (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY_RX; - hi3c->pXferData = pXferData; - hi3c->RxXferCount = pXferData->RxBuf.Size; - hi3c->XferISR = I3C_Tgt_Rx_DMA_ISR; - - /*------------------------------------ I3C DMA channel for the Rx Data ---------------------------------------*/ - /* Set the I3C DMA transfer complete callback */ - hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; - - /* Set the DMA error callback */ - hi3c->hdmarx->XferErrorCallback = I3C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi3c->hdmarx->XferHalfCpltCallback = NULL; - hi3c->hdmarx->XferAbortCallback = NULL; - - /* Check on the Rx threshold to know the Rx treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* assert that DMA source and destination width are configured in byte */ - assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); - } - else - { - /* assert that DMA source and destination width are configured in word */ - assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); - assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); - - /* Check to align data size in words */ - if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) - { - /* Keep the same size */ - size_align_word = hi3c->pXferData->RxBuf.Size; - } - else - { - /* Modify size to be multiple of 4 */ - size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); - } - - /* Enable the Rx data DMA channel */ - rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, - (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); - } - - if (rx_dma_status == HAL_OK) - { - /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk - of I3C interrupt handle execution before current process unlock */ - - /* Enable Rx process interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Enable Rx data DMA Request */ - LL_I3C_EnableDMAReq_RX(hi3c->Instance); - } - else - { - /* Set callback to NULL if DMA started */ - hi3c->hdmarx->XferCpltCallback = NULL; - hi3c->hdmarx->XferErrorCallback = NULL; - - hi3c->ErrorCode = HAL_I3C_ERROR_DMA; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - } - } - - return status; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Target send control role request in polling mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_ControlRoleReq(I3C_HandleTypeDef *hi3c, uint32_t timeout) -{ - uint32_t tickstart; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Verify if control role request feature is enabled */ - if (LL_I3C_IsEnabledControllerRoleReq(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Request Controllership */ - LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_CONTROLLER_ROLE_REQ, 0U); - - /* Wait Controllership completion confirmation flag */ - status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_CRUPDF, RESET, timeout, tickstart); - - /* Clear Control role request flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_CRUPDF) == SET) - { - LL_I3C_ClearFlag_CRUPD(hi3c->Instance); - } - - /* Check on error flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - - status = HAL_ERROR; - } - else - { - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - } - } - } - - return status; -} - -/** - * @brief Target send control role request in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_ControlRoleReq_IT(I3C_HandleTypeDef *hi3c) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Verify if control role request feature is enabled */ - if (LL_I3C_IsEnabledControllerRoleReq(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Update handle parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - hi3c->XferISR = I3C_Tgt_CtrlRole_ISR; - - /* Enable controller-role update and error interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_CTRLROLE); - - /* Request Controllership */ - LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_CONTROLLER_ROLE_REQ, 0U); - } - } - - return status; -} - -/** - * @brief Target send hot join request in polling mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pAddress : [IN/OUT] Pointer to the target own dynamic address assigned by the controller. - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_HotJoinReq(I3C_HandleTypeDef *hi3c, uint8_t *pAddress, uint32_t timeout) -{ - uint32_t tickstart; - HAL_I3C_StateTypeDef handle_state; - uint32_t valid_dynamic_address; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on the pAddress value */ - if (pAddress == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check on the Mode */ - else if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Check on the hot join request feature */ - if (LL_I3C_IsEnabledHotJoin(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Request hot join */ - LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_HOT_JOIN, 0U); - - /* Wait hot join completion confirmation flag */ - status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_DAUPDF, RESET, timeout, tickstart); - - /* Clear dynamic address update flag */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_DAUPDF) == SET) - { - LL_I3C_ClearFlag_DAUPD(hi3c->Instance); - } - - /* Get dynamic address validity flag */ - valid_dynamic_address = LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance); - - /* Check the validity of the own dynamic address */ - if (valid_dynamic_address == 0U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_DYNAMIC_ADDR; - status = HAL_ERROR; - - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - } - /* Check on error flag */ - else if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - - status = HAL_ERROR; - } - else - { - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - - /* Get assigned dynamic address */ - *pAddress = LL_I3C_GetOwnDynamicAddress(hi3c->Instance); - } - } - } - - return status; -} - -/** - * @brief Target send hot join request in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_HotJoinReq_IT(I3C_HandleTypeDef *hi3c) -{ - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* Check on the hot join request feature */ - else if (LL_I3C_IsEnabledHotJoin(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Update handle parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - hi3c->XferISR = I3C_Tgt_HotJoin_ISR; - - /* Enable dynamic address update and error interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_HOTJOIN); - - /* Request hot join */ - LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_HOT_JOIN, 0U); - } - } - - return status; -} - -/** - * @brief Target send IBI request in polling mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pPayload : [IN] Pointer to the buffer contains the payload data. - * @param payloadSize : [IN] Payload buffer size in bytes. - * @param timeout : [IN] Timeout duration in millisecond. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_IBIReq(I3C_HandleTypeDef *hi3c, const uint8_t *pPayload, - uint8_t payloadSize, uint32_t timeout) -{ - uint32_t tickstart; - uint32_t payload_value = 0U; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Verify if IBI request feature is enabled*/ - if ((LL_I3C_IsEnabledIBI(hi3c->Instance) != 1U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Update handle parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - - /* Check on the IBI additional data */ - if (LL_I3C_GetDeviceIBIPayload(hi3c->Instance) == LL_I3C_IBI_ADDITIONAL_DATA) - { - /* Check on the pPayload and payloadSize values */ - if ((pPayload == NULL) || (payloadSize == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - else - { - /* For loop to calculate the payload value */ - for (uint32_t index = 0U; index < payloadSize; index++) - { - payload_value |= ((uint32_t)pPayload[index] << (index * 8U)); - } - - /* Load IBI payload data */ - LL_I3C_SetIBIPayload(hi3c->Instance, payload_value); - } - } - - if (status == HAL_OK) - { - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Request IBI */ - LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_IBI, payloadSize); - - /* Wait IBI completion confirmation flag */ - status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_IBIENDF, RESET, timeout, tickstart); - - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_IBIENDF) == SET) - { - /* Clear IBI end process flag */ - LL_I3C_ClearFlag_IBIEND(hi3c->Instance); - } - - /* Check on error flag value */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - - status = HAL_ERROR; - } - else - { - /* Update handle state parameter to previous state */ - I3C_StateUpdate(hi3c); - } - } - } - } - - return status; -} - -/** - * @brief Target send IBI request in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param pPayload : [IN] Pointer to the buffer contains the payload data. - * @param payloadSize : [IN] Payload buffer size in bytes. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Tgt_IBIReq_IT(I3C_HandleTypeDef *hi3c, const uint8_t *pPayload, uint8_t payloadSize) -{ - uint32_t payload_value = 0U; - HAL_I3C_StateTypeDef handle_state; - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check the instance and the mode parameters */ - assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); - assert_param(IS_I3C_MODE(hi3c->Mode)); - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* Check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_TARGET) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - /* Verify the dynamic address validity */ - else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Verify if IBI request feature is enabled */ - if (LL_I3C_IsEnabledIBI(hi3c->Instance) != 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Update handle parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - hi3c->XferISR = I3C_Tgt_IBI_ISR; - - /* Check on the IBI additional data */ - if (LL_I3C_GetDeviceIBIPayload(hi3c->Instance) == LL_I3C_IBI_ADDITIONAL_DATA) - { - /* Check on the pPayload and payloadSize values */ - if ((pPayload == NULL) || (payloadSize == 0U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - } - else - { - /* For loop to calculate the payload value */ - for (uint32_t index = 0U; index < payloadSize; index++) - { - payload_value |= ((uint32_t)pPayload[index] << (index * 8U)); - } - - /* Load IBI payload data */ - LL_I3C_SetIBIPayload(hi3c->Instance, payload_value); - } - } - - /* Enable IBI end and error interrupts */ - I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_IBI); - - /* Request IBI */ - LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_IBI, payloadSize); - } - } - - return status; -} -/** - * @} - */ - -/** @defgroup I3C_Exported_Functions_Group7 Generic and Common functions. - * @brief I3C generic and common functions. - * -@verbatim - ======================================================================================================================= - ##### Generic and Common functions ##### - ======================================================================================================================= - [..] This subsection provides a set of functions allowing to Abort transfer or to get in run-time the status - of the peripheral. - - (+) Call the function HAL_I3C_Abort_IT() to abort the current transfer either in DMA or IT. - (+) Call the function HAL_I3C_GetState() to get the I3C handle state. - (+) Call the function HAL_I3C_GetMode() to get the I3C handle mode. - (+) Call the function HAL_I3C_GetError() to get the error code. - -@endverbatim - * @{ - */ - -/** - * @brief Abort an I3C IT or DMA process communication with Interrupt. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Abort_IT(I3C_HandleTypeDef *hi3c) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - if (hi3c->State != HAL_I3C_STATE_ABORT) - { - /* Set State at HAL_I3C_STATE_ABORT */ - hi3c->State = HAL_I3C_STATE_ABORT; - - /* Disable Error Interrupts */ - __HAL_I3C_DISABLE_IT(hi3c, HAL_I3C_IT_ERRIE); - - hi3c->XferISR = I3C_Abort_ISR; - - /* Flush the different Fifos to generate an automatic stop mode link to underflow or overflow detection timeout */ - /* Flush the content of Tx Fifo */ - LL_I3C_RequestTxFIFOFlush(hi3c->Instance); - - /* Flush the content of Rx Fifo */ - LL_I3C_RequestRxFIFOFlush(hi3c->Instance); - - /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Flush the content of Control Fifo */ - LL_I3C_RequestControlFIFOFlush(hi3c->Instance); - - /* Flush the content of Status Fifo */ - LL_I3C_RequestStatusFIFOFlush(hi3c->Instance); - } - - /* Disable all DMA Requests */ - LL_I3C_DisableDMAReq_Control(hi3c->Instance); - LL_I3C_DisableDMAReq_RX(hi3c->Instance); - LL_I3C_DisableDMAReq_TX(hi3c->Instance); - LL_I3C_DisableDMAReq_Status(hi3c->Instance); - - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Note : The I3C interrupts must be enabled after unlocking current process - to avoid the risk of I3C interrupt handle execution before current - process unlock */ - I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); - } - else - { - /* Note : The I3C interrupts must be enabled after unlocking current process - to avoid the risk of I3C interrupt handle execution before current - process unlock */ - I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_RX_IT); - } - } - else - { - return HAL_BUSY; - } - } - - return status; -} - -/** - * @brief Return the I3C handle state. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval HAL State : [OUT] Value from HAL_I3C_StateTypeDef enumeration. - */ -HAL_I3C_StateTypeDef HAL_I3C_GetState(const I3C_HandleTypeDef *hi3c) -{ - return hi3c->State; -} - -/** - * @brief Returns the I3C handle mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval HAL Mode : [OUT] Value from HAL_I3C_ModeTypeDef enumeration. - */ -HAL_I3C_ModeTypeDef HAL_I3C_GetMode(const I3C_HandleTypeDef *hi3c) -{ - return hi3c->Mode; -} - -/** - * @brief Return the I3C error code. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval I3C Error Code : [OUT] Value from @ref I3C_ERROR_CODE_DEFINITION. - */ -uint32_t HAL_I3C_GetError(const I3C_HandleTypeDef *hi3c) -{ - return hi3c->ErrorCode; -} - -/** - * @brief Target/Controller Get Common Command Code Information updated after event. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param notifyId : [IN] Parameter indicates which notification is signaled. - * It can be a combination of value of @ref HAL_I3C_Notification_ID_definition. - * @param pCCCInfo : [IN/OUT] Pointer to an I3C_CCCInfoTypeDef structure that contains the CCC information - * updated after CCC event. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_GetCCCInfo(I3C_HandleTypeDef *hi3c, - uint32_t notifyId, - I3C_CCCInfoTypeDef *pCCCInfo) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check on user parameters */ - if (pCCCInfo == NULL) - { - /* Update handle error code parameter */ - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - /* Check the I3C state */ - else if (hi3c->State == HAL_I3C_STATE_RESET) - { - /* Update handle error code parameter */ - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - else - { - /* Retrieve Target Dynamic Address value and Validity (target/controller) */ - if ((notifyId & EVENT_ID_DAU) == EVENT_ID_DAU) - { - pCCCInfo->DynamicAddrValid = LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance); - pCCCInfo->DynamicAddr = LL_I3C_GetOwnDynamicAddress(hi3c->Instance); - } - - /* Retrieve Maximum Write Data Length (target) */ - if ((notifyId & EVENT_ID_SETMWL) == EVENT_ID_SETMWL) - { - pCCCInfo->MaxWriteLength = LL_I3C_GetMaxWriteLength(hi3c->Instance); - } - - /* Retrieve Maximum Read Data Length (target) */ - if ((notifyId & EVENT_ID_SETMRL) == EVENT_ID_SETMRL) - { - pCCCInfo->MaxReadLength = LL_I3C_GetMaxReadLength(hi3c->Instance); - } - - /* Retrieve Reset Action/Level on received reset pattern (target) */ - if ((notifyId & EVENT_ID_RSTACT) == EVENT_ID_RSTACT) - { - pCCCInfo->ResetAction = LL_I3C_GetResetAction(hi3c->Instance); - } - - /* Retrieve Activity State (target) */ - if ((notifyId & EVENT_ID_ENTASx) == EVENT_ID_ENTASx) - { - pCCCInfo->ActivityState = LL_I3C_GetActivityState(hi3c->Instance); - } - - /* Retrieve Interrupt allowed status (target) */ - if ((notifyId & EVENT_ID_ENEC_DISEC) == EVENT_ID_ENEC_DISEC) - { - pCCCInfo->HotJoinAllowed = LL_I3C_IsEnabledHotJoin(hi3c->Instance); - pCCCInfo->InBandAllowed = LL_I3C_IsEnabledIBI(hi3c->Instance); - pCCCInfo->CtrlRoleAllowed = LL_I3C_IsEnabledControllerRoleReq(hi3c->Instance); - } - - /* Retrieve In Band Interrupt information (controller) */ - if ((notifyId & EVENT_ID_IBI) == EVENT_ID_IBI) - { - pCCCInfo->IBICRTgtAddr = LL_I3C_GetIBITargetAddr(hi3c->Instance); - pCCCInfo->IBITgtNbPayload = LL_I3C_GetNbIBIAddData(hi3c->Instance); - pCCCInfo->IBITgtPayload = LL_I3C_GetIBIPayload(hi3c->Instance); - } - - /* Retrieve Controller role request Interrupt information (controller) */ - if ((notifyId & EVENT_ID_CR) == EVENT_ID_CR) - { - pCCCInfo->IBICRTgtAddr = LL_I3C_GetIBITargetAddr(hi3c->Instance); - } - } - } - - return status; -} - -/** - * @brief Get BCR, DCR and PID information after ENTDAA. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param ENTDAA_payload :[IN] Payload received after ENTDAA - * @param pENTDAA_payload :[OUT] Pointer to an I3C_ENTDAAPayloadTypeDef structure that contains the BCR, DCR and PID - * information. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -HAL_StatusTypeDef HAL_I3C_Get_ENTDAA_Payload_Info(I3C_HandleTypeDef *hi3c, - uint64_t ENTDAA_payload, - I3C_ENTDAAPayloadTypeDef *pENTDAA_payload) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t BCR; - uint64_t PID; - - /* check on the handle */ - if (hi3c == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check on user parameters */ - if (pENTDAA_payload == NULL) - { - /* Update handle error code parameter */ - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Get Bus Characterics */ - BCR = __HAL_I3C_GET_BCR(ENTDAA_payload); - - /* Retrieve BCR information */ - pENTDAA_payload->BCR.IBIPayload = __HAL_I3C_GET_IBI_PAYLOAD(BCR); - pENTDAA_payload->BCR.IBIRequestCapable = __HAL_I3C_GET_IBI_CAPABLE(BCR); - pENTDAA_payload->BCR.DeviceRole = __HAL_I3C_GET_CR_CAPABLE(BCR); - pENTDAA_payload->BCR.AdvancedCapabilities = I3C_GET_ADVANCED_CAPABLE(BCR); - pENTDAA_payload->BCR.OfflineCapable = I3C_GET_OFFLINE_CAPABLE(BCR); - pENTDAA_payload->BCR.VirtualTargetSupport = I3C_GET_VIRTUAL_TGT(BCR); - pENTDAA_payload->BCR.MaxDataSpeedLimitation = I3C_GET_MAX_DATA_SPEED_LIMIT(BCR); - - /* Get Device Characterics */ - pENTDAA_payload->DCR = I3C_GET_DCR(ENTDAA_payload); - - /* Get Provisioned ID */ - PID = I3C_GET_PID(ENTDAA_payload); - - /* Change PID from BigEndian to litlleEndian */ - PID = (uint64_t)((((uint64_t)I3C_BIG_TO_LITTLE_ENDIAN((uint32_t) PID) << 32) | - ((uint64_t)I3C_BIG_TO_LITTLE_ENDIAN((uint32_t)(PID >> 32)))) >> 16); - - /* Retrieve PID information*/ - pENTDAA_payload->PID.MIPIMID = I3C_GET_MIPIMID(PID); - pENTDAA_payload->PID.IDTSEL = I3C_GET_IDTSEL(PID); - pENTDAA_payload->PID.PartID = I3C_GET_PART_ID(PID); - pENTDAA_payload->PID.MIPIID = I3C_GET_MIPIID(PID); - } - } - - return status; -} - -/** - * @} - */ - -/** - * @} - */ - -/* Private functions -------------------------------------------------------------------------------------------------*/ -/** @defgroup I3C_Private_Functions I3C Private Functions - * @{ - */ - -/** - * @brief Interrupt Sub-Routine which handles target received events. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - uint32_t tmpevent = 0U; - - /* I3C Rx FIFO not empty interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) - { - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - } - - /* I3C target complete controller-role hand-off procedure (direct GETACCR CCC) event management --------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRUPDF) != RESET) - { - /* Clear controller-role update flag */ - LL_I3C_ClearFlag_CRUPD(hi3c->Instance); - - /* Set Identifier EVENT_ID_GETACCCR */ - tmpevent |= EVENT_ID_GETACCCR; - } - - /* I3C target receive any direct GETxxx CCC event management -------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_GETF) != RESET) - { - /* Clear GETxxx CCC flag */ - LL_I3C_ClearFlag_GET(hi3c->Instance); - - /* Set Identifier EVENT_ID_GETx */ - tmpevent |= EVENT_ID_GETx; - } - - /* I3C target receive get status command (direct GETSTATUS CCC) event management -----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_STAF) != RESET) - { - /* Clear GETSTATUS CCC flag */ - LL_I3C_ClearFlag_STA(hi3c->Instance); - - /* Set Identifier EVENT_ID_GETSTATUS */ - tmpevent |= EVENT_ID_GETSTATUS; - } - - /* I3C target receive a dynamic address update (ENTDAA/RSTDAA/SETNEWDA CCC) event management -----------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_DAUPDF) != RESET) - { - /* Clear dynamic address update flag */ - LL_I3C_ClearFlag_DAUPD(hi3c->Instance); - - /* Set Identifier EVENT_ID_DAU */ - tmpevent |= EVENT_ID_DAU; - } - - /* I3C target receive maximum write length update (direct SETMWL CCC) event management -----------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_MWLUPDF) != RESET) - { - /* Clear SETMWL CCC flag */ - LL_I3C_ClearFlag_MWLUPD(hi3c->Instance); - - /* Set Identifier EVENT_ID_SETMWL */ - tmpevent |= EVENT_ID_SETMWL; - } - - /* I3C target receive maximum read length update(direct SETMRL CCC) event management -------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_MRLUPDF) != RESET) - { - /* Clear SETMRL CCC flag */ - LL_I3C_ClearFlag_MRLUPD(hi3c->Instance); - - /* Set Identifier EVENT_ID_SETMRL */ - tmpevent |= EVENT_ID_SETMRL; - } - - /* I3C target detect reset pattern (broadcast or direct RSTACT CCC) event management -------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_RSTF) != RESET) - { - /* Clear reset pattern flag */ - LL_I3C_ClearFlag_RST(hi3c->Instance); - - /* Set Identifier EVENT_ID_RSTACT */ - tmpevent |= EVENT_ID_RSTACT; - } - - /* I3C target receive activity state update (direct or broadcast ENTASx) CCC event management ----------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_ASUPDF) != RESET) - { - /* Clear ENTASx CCC flag */ - LL_I3C_ClearFlag_ASUPD(hi3c->Instance); - - /* Set Identifier EVENT_ID_ENTASx */ - tmpevent |= EVENT_ID_ENTASx; - } - - /* I3C target receive a direct or broadcast ENEC/DISEC CCC event management ----------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_INTUPDF) != RESET) - { - /* Clear ENEC/DISEC CCC flag */ - LL_I3C_ClearFlag_INTUPD(hi3c->Instance); - - /* Set Identifier EVENT_ID_ENEC_DISEC */ - tmpevent |= EVENT_ID_ENEC_DISEC; - } - - /* I3C target receive a broadcast DEFTGTS CCC event management -----------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_DEFF) != RESET) - { - /* Clear DEFTGTS CCC flag */ - LL_I3C_ClearFlag_DEF(hi3c->Instance); - - /* Set Identifier EVENT_ID_DEFTGTS */ - tmpevent |= EVENT_ID_DEFTGTS; - } - - /* I3C target receive a group addressing (broadcast DEFGRPA CCC) event management ----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_GRPF) != RESET) - { - /* Clear DEFGRPA CCC flag */ - LL_I3C_ClearFlag_GRP(hi3c->Instance); - - /* Set Identifier EVENT_ID_DEFGRPA */ - tmpevent |= EVENT_ID_DEFGRPA; - } - - /* I3C target wakeup event management ----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) - { - /* Clear WKP flag */ - LL_I3C_ClearFlag_WKP(hi3c->Instance); - - /* Set Identifier EVENT_ID_WKP */ - tmpevent |= EVENT_ID_WKP; - } - - if (tmpevent != 0U) - { -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, tmpevent); -#else - /* Asynchronous receive CCC event Callback */ - HAL_I3C_NotifyCallback(hi3c, tmpevent); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles Controller received events. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) - { - /* Clear IBI request flag */ - LL_I3C_ClearFlag_IBI(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); -#else - /* Asynchronous IBI event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller controller-role request event management ---------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) - { - /* Clear controller-role request flag */ - LL_I3C_ClearFlag_CR(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_CR); -#else - /* Asynchronous controller-role event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller hot-join event management ------------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) - { - /* Clear hot-join flag */ - LL_I3C_ClearFlag_HJ(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); -#else - /* Asynchronous hot-join event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles target hot join event. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_HotJoin_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C target receive a dynamic address update event management */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_DAUPDF) != RESET) - { - /* Clear dynamic address update flag */ - LL_I3C_ClearFlag_DAUPD(hi3c->Instance); - - /* Disable dynamic address update and error interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_HOTJOIN); - - /* Check the validity of the own dynamic address */ - if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) == 1U) - { - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->TgtHotJoinCallback(hi3c, (uint8_t)LL_I3C_GetOwnDynamicAddress(hi3c->Instance)); -#else - /* Asynchronous receive ENTDAA/RSTDAA/SETNEWDA CCC event Callback */ - HAL_I3C_TgtHotJoinCallback(hi3c, (uint8_t)LL_I3C_GetOwnDynamicAddress(hi3c->Instance)); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_DYNAMIC_ADDR; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles target control role event. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_CtrlRole_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C target complete controller-role hand-off procedure (direct GETACCR CCC) event management -------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRUPDF) != RESET) - { - /* Clear controller-role update flag */ - LL_I3C_ClearFlag_CRUPD(hi3c->Instance); - - /* Disable controller-role update and error interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_CTRLROLE); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_GETACCCR); -#else - /* Asynchronous receive GETACCR CCC event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_GETACCCR); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles target IBI event. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_IBI_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C target IBI end process event management ---------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIENDF) != RESET) - { - /* Clear IBI end flag */ - LL_I3C_ClearFlag_IBIEND(hi3c->Instance); - - /* Disable IBI end and error interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_IBI); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_IBIEND); -#else - /* Asynchronous IBI end event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBIEND); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles target transmit data in Interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that a Tx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_TX) - { - /* I3C Tx FIFO not full interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) - { - if (hi3c->TxXferCount > 0U) - { - /* Call transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - } - } - - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Check if all data bytes are transmitted */ - if (LL_I3C_GetXferDataCount(hi3c->Instance) == hi3c->pXferData->TxBuf.Size) - { - /* Disable Tx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_TX_IT); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the transmit complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->TgtTxCpltCallback(hi3c); -#else - HAL_I3C_TgtTxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - - /* I3C target wakeup event management ----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) - { - /* Clear WKP flag */ - LL_I3C_ClearFlag_WKP(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); -#else - /* Asynchronous receive CCC event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - } - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles target receive data in Interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that an Rx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_RX) - { - /* I3C Rx FIFO not empty interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) - { - if (hi3c->RxXferCount > 0U) - { - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - } - } - - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Check if all data bytes are received */ - if (LL_I3C_GetXferDataCount(hi3c->Instance) == hi3c->pXferData->RxBuf.Size) - { - /* Disable Rx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_RX_IT); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the receive complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->TgtRxCpltCallback(hi3c); -#else - HAL_I3C_TgtRxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - - /* I3C target wakeup event management ----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) - { - /* Clear WKP flag */ - LL_I3C_ClearFlag_WKP(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); -#else - /* Asynchronous receive CCC event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - } - - return HAL_OK; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Interrupt Sub-Routine which handles target transmit data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that a Tx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_TX) - { - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Check if all data bytes are transmitted */ - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmatx) == 0U) - { - /* Disable Tx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Call target transmit complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->TgtTxCpltCallback(hi3c); -#else - HAL_I3C_TgtTxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - - /* I3C target wakeup event management ----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) - { - /* Clear WKP flag */ - LL_I3C_ClearFlag_WKP(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); -#else - /* Asynchronous receive CCC event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - } - - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles target receive data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Tgt_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that a Rx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_RX) - { - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Check if all data bytes are received */ - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmarx) == 0U) - { - /* Disable Rx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Call target receive complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->TgtRxCpltCallback(hi3c); -#else - HAL_I3C_TgtRxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - - /* I3C target wakeup event management ----------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) - { - /* Clear WKP flag */ - LL_I3C_ClearFlag_WKP(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); -#else - /* Asynchronous receive CCC event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - } - - return HAL_OK; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Interrupt Sub-Routine which handles controller transmission in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that a Tx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_TX) - { - /* Check if Control FIFO requests data */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) - { - if (hi3c->ControlXferCount > 0U) - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - } - } - - /* I3C Tx FIFO not full interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) - { - if (hi3c->TxXferCount > 0U) - { - /* Call Transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - } - } - - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - if (hi3c->ControlXferCount == 0U) - { - /* Disable Tx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the transmit complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlTxCpltCallback(hi3c); -#else - HAL_I3C_CtrlTxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the transmit complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlTxCpltCallback(hi3c); -#else - HAL_I3C_CtrlTxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - - } - } - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles controller reception in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that an Rx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_RX) - { - /* Check if Control FIFO requests data */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) - { - if (hi3c->ControlXferCount > 0U) - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - } - } - - /* I3C Rx FIFO not empty interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) - { - if (hi3c->RxXferCount > 0U) - { - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - } - } - - /* I3C Tx FIFO not full interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) - { - if (hi3c->TxXferCount > 0U) - { - /* Call Transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - } - } - - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - if (hi3c->ControlXferCount == 0U) - { - /* Disable Rx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the receive complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlRxCpltCallback(hi3c); -#else - HAL_I3C_CtrlRxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the receive complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlRxCpltCallback(hi3c); -#else - HAL_I3C_CtrlRxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles controller multiple transmission/reception in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that a Tx/Rx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_TX_RX) - { - /* Check if Control FIFO requests data */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) - { - if (hi3c->ControlXferCount > 0U) - { - /* Call control data treatment function */ - I3C_ControlDataTreatment(hi3c); - } - } - - /* I3C Tx FIFO not full interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) - { - if (hi3c->TxXferCount > 0U) - { - /* Call Transmit treatment function */ - hi3c->ptrTxFunc(hi3c); - } - } - - /* I3C Rx FIFO not empty interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) - { - if (hi3c->RxXferCount > 0U) - { - /* Call receive treatment function */ - hi3c->ptrRxFunc(hi3c); - } - } - - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - if (hi3c->ControlXferCount == 0U) - { - /* Disable Tx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); - - /* Disable Rx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the transmit, receive complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlMultipleXferCpltCallback(hi3c); -#else - HAL_I3C_CtrlMultipleXferCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles controller transmission and Controller received events - * in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Tx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) - { - /* Clear IBI request flag */ - LL_I3C_ClearFlag_IBI(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); -#else - /* Asynchronous IBI event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller controller-role request event management ---------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) - { - /* Clear controller-role request flag */ - LL_I3C_ClearFlag_CR(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_CR); -#else - /* Asynchronous controller-role event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller hot-join event management ------------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) - { - /* Clear hot-join flag */ - LL_I3C_ClearFlag_HJ(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); -#else - /* Asynchronous hot-join event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* ISR controller transmission */ - return (I3C_Ctrl_Tx_ISR(hi3c, itMasks)); -} - -/** - * @brief Interrupt Sub-Routine which handles controller reception and Controller received events in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Rx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) - { - /* Clear IBI request flag */ - LL_I3C_ClearFlag_IBI(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); -#else - /* Asynchronous IBI event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller controller-role request event management ---------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) - { - /* Clear controller-role request flag */ - LL_I3C_ClearFlag_CR(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_CR); -#else - /* Asynchronous controller-role event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller hot-join event management ------------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) - { - /* Clear hot-join flag */ - LL_I3C_ClearFlag_HJ(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); -#else - /* Asynchronous hot-join event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* ISR controller reception */ - return (I3C_Ctrl_Rx_ISR(hi3c, itMasks)); -} - -/** - * @brief Interrupt Sub-Routine which handles controller multiple transmission/reception and - * Controller received eventsin interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) - { - /* Clear IBI request flag */ - LL_I3C_ClearFlag_IBI(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); -#else - /* Asynchronous IBI event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller controller-role request event management ---------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) - { - /* Clear controller-role request flag */ - LL_I3C_ClearFlag_CR(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_CR); -#else - /* Asynchronous controller-role event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* I3C controller hot-join event management ------------------------------------------------------------------------*/ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) - { - /* Clear hot-join flag */ - LL_I3C_ClearFlag_HJ(hi3c->Instance); - -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - /* Call registered callback */ - hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); -#else - /* Asynchronous hot-join event Callback */ - HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - - /* ISR controller transmission/reception */ - return (I3C_Ctrl_Multiple_Xfer_ISR(hi3c, itMasks)); -} -/** - * @brief Interrupt Sub-Routine which handles controller CCC Dynamic Address Assignment command in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_DAA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - uint64_t target_payload = 0U; - - /* Check that a Dynamic Address Assignment process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_DAA) - { - /* I3C Control FIFO not full interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) - { - /* Write ENTDAA CCC information in the control register */ - LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_ENTDAA, 0U, LL_I3C_GENERATE_STOP); - } - - /* I3C Tx FIFO not full interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) - { - /* Check on the Rx FIFO threshold to know the Dynamic Address Assignment treatment process : byte or word */ - if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) - { - /* For loop to get target payload */ - for (uint32_t index = 0U; index < 8U; index++) - { - /* Retrieve payload byte by byte */ - target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData8(hi3c->Instance) << (index * 8U)); - } - } - else - { - /* Retrieve first 32 bits payload */ - target_payload = (uint64_t)LL_I3C_ReceiveData32(hi3c->Instance); - - /* Retrieve second 32 bits payload */ - target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData32(hi3c->Instance) << 32U); - } - - /* Call the corresponding callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->TgtReqDynamicAddrCallback(hi3c, target_payload); -#else - HAL_I3C_TgtReqDynamicAddrCallback(hi3c, target_payload); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ - } - - /* I3C frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Disable Dynamic Address Assignment process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_DAA_IT); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the Dynamic Address Assignment complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlDAACpltCallback(hi3c); -#else - HAL_I3C_CtrlDAACpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - } - return HAL_OK; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Interrupt Sub-Routine which handles controller transmit data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that a Tx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_TX) - { - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmacr) == 0U) - { - /* Check if all data bytes are transmitted */ - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmatx) == 0U) - { - /* Disable Tx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Call controller transmit complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlTxCpltCallback(hi3c); -#else - HAL_I3C_CtrlTxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the transmit complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlTxCpltCallback(hi3c); -#else - HAL_I3C_CtrlTxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles controller receive data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that an Rx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_RX) - { - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmacr) == 0U) - { - /* Check if all data bytes are received */ - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmarx) == 0U) - { - /* Disable Rx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Call controller receive complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlRxCpltCallback(hi3c); -#else - HAL_I3C_CtrlRxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Call the receive complete callback */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlRxCpltCallback(hi3c); -#else - HAL_I3C_CtrlRxCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - } - return HAL_OK; -} - -/** - * @brief Interrupt Sub-Routine which handles controller multiple receive and transmit data in DMA mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that an Rx or Tx process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_BUSY_TX_RX) - { - /* I3C target frame complete event Check */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmacr) == 0U) - { - /* Check if all data bytes are received or transmitted */ - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmarx) == 0U) - { - if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmatx) == 0U) - { - /* Disable transfer Tx/Rx process interrupts */ - I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); - - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Update the number of remaining data bytes */ - hi3c->RxXferCount = 0U; - - /* Update the number of remaining data bytes */ - hi3c->TxXferCount = 0U; - - /* Call controller transmit, receive complete callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) - hi3c->CtrlMultipleXferCpltCallback(hi3c); -#else - HAL_I3C_CtrlMultipleXferCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - else - { - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - - /* Then Initiate a Start condition */ - LL_I3C_RequestTransfer(hi3c->Instance); - } - } - } - return HAL_OK; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Interrupt Sub-Routine which handles abort process in interrupt mode. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information - * for the specified I3C. - * @param itMasks : [IN] Flag Interrupt Masks flags to handle. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Abort_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) -{ - /* Check that an Abort process is ongoing */ - if (hi3c->State == HAL_I3C_STATE_ABORT) - { - /* I3C Rx FIFO not empty interrupt Check */ - if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) - { - if (LL_I3C_IsActiveFlag_DOVR(hi3c->Instance) == 1U) - { - /* Flush remaining Rx data */ - LL_I3C_RequestRxFIFOFlush(hi3c->Instance); - } - } - - /* I3C Abort frame complete event Check */ - /* Evenif abort is called, the Frame completion can arrive if abort is requested at the end of the processus */ - /* Evenif completion occurs, treat this end of processus as abort completion process */ - if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Call error treatment function */ - I3C_ErrorTreatment(hi3c); - } - } - return HAL_OK; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief DMA I3C control transmit process complete callback. - * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA channel. - * @retval None - */ -static void I3C_DMAControlTransmitCplt(DMA_HandleTypeDef *hdma) -{ - /* Get the address of the I3C handle : Derogation MISRAC2012-Rule-11.5 */ - I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Disable control DMA Request */ - LL_I3C_DisableDMAReq_Control(hi3c->Instance); -} - -/** - * @brief DMA I3C transmit data process complete callback. - * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA channel. - * @retval None - */ -static void I3C_DMADataTransmitCplt(DMA_HandleTypeDef *hdma) -{ - /* Get the address of the I3C handle : Derogation MISRAC2012-Rule-11.5 */ - I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Disable Tx DMA Request */ - LL_I3C_DisableDMAReq_TX(hi3c->Instance); -} - -/** - * @brief DMA I3C receive data process complete callback. - * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA channel. - * @retval None - */ -static void I3C_DMADataReceiveCplt(DMA_HandleTypeDef *hdma) -{ - /* Get the address of the I3C handle : Derogation MISRAC2012-Rule-11.5 */ - I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Disable Rx DMA Request */ - LL_I3C_DisableDMAReq_RX(hi3c->Instance); -} - -/** - * @brief DMA I3C communication error callback. - * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA channel. - * @retval None - */ -static void I3C_DMAError(DMA_HandleTypeDef *hdma) -{ - /* Just to solve MisraC error then to be removed */ - /* Derogation MISRAC2012-Rule-11.5 */ - I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - hi3c->ErrorCode |= HAL_I3C_ERROR_DMA; -} - -/** - * @brief DMA I3C communication abort callback to be called at end of DMA Abort procedure. - * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information - * for the specified DMA channel. - * @retval None - */ -static void I3C_DMAAbort(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Reset Tx DMA AbortCpltCallback */ - if (hi3c->hdmatx != NULL) - { - hi3c->hdmatx->XferAbortCallback = NULL; - } - - /* Reset Rx DMA AbortCpltCallback */ - if (hi3c->hdmarx != NULL) - { - hi3c->hdmarx->XferAbortCallback = NULL; - } - - /* Reset control DMA AbortCpltCallback */ - if (hi3c->hdmacr != NULL) - { - hi3c->hdmacr->XferAbortCallback = NULL; - } - - I3C_TreatErrorCallback(hi3c); -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief This function handles I3C Communication Timeout. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param flag : [IN] Specifies the I3C flag to check. - * @param flagstatus : [IN] The new Flag status (SET or RESET). - * @param timeout : [IN] Timeout duration in millisecond. - * @param tickstart : [IN] Tick start value - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_WaitOnFlagUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t flag, FlagStatus flagstatus, - uint32_t timeout, uint32_t tickstart) -{ - HAL_StatusTypeDef status = HAL_OK; - - while ((__HAL_I3C_GET_FLAG(hi3c, flag) == flagstatus) && (status == HAL_OK)) - { - /* Check for the Timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - if (__HAL_I3C_GET_FLAG(hi3c, flag) == flagstatus) - { - hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - } - } - } - - /* Check if an error occurs during Flag waiting */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - status = HAL_ERROR; - } - } - return status; -} - -/** - * @brief This function handles I3C Dynamic Address Assignment timeout. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param timeout : [IN] Timeout duration in millisecond. - * @param tickstart : [IN] Tick start value - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_WaitOnDAAUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t timeout, uint32_t tickstart) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t active_flags = READ_REG(hi3c->Instance->EVR); - - while (((active_flags & (HAL_I3C_FLAG_FCF | HAL_I3C_FLAG_TXFNFF)) == 0U) && (status == HAL_OK)) - { - /* Check for the Timeout */ - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - if ((active_flags & (HAL_I3C_FLAG_FCF | HAL_I3C_FLAG_TXFNFF)) == 0U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - } - } - } - - /* Check if an error occurs during Flag waiting */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) - { - /* Clear error flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - - /* Update handle error code parameter */ - I3C_GetErrorSources(hi3c); - - status = HAL_ERROR; - } - - /* Read active flags from EVR register */ - active_flags = READ_REG(hi3c->Instance->EVR); - } - return status; -} - -/** - * @brief I3C transmit by byte. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_TransmitByteTreatment(I3C_HandleTypeDef *hi3c) -{ - /* Check TX FIFO not full flag */ - while ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) && (hi3c->TxXferCount > 0U)) - { - /* Write Tx buffer data to transmit register */ - LL_I3C_TransmitData8(hi3c->Instance, *hi3c->pXferData->TxBuf.pBuffer); - - /* Increment Buffer pointer */ - hi3c->pXferData->TxBuf.pBuffer++; - - /* Decrement remaining bytes counter */ - hi3c->TxXferCount--; - } -} - -/** - * @brief I3C transmit by word. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_TransmitWordTreatment(I3C_HandleTypeDef *hi3c) -{ - /* Check TX FIFO not full flag */ - while (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) - { - /* Write Tx buffer data to transmit register */ - LL_I3C_TransmitData32(hi3c->Instance, *((uint32_t *)hi3c->pXferData->TxBuf.pBuffer)); - - /* Increment Buffer pointer */ - hi3c->pXferData->TxBuf.pBuffer += sizeof(uint32_t); - - if (hi3c->TxXferCount < sizeof(uint32_t)) - { - hi3c->TxXferCount = 0U; - } - else - { - /* Decrement remaining bytes counter */ - hi3c->TxXferCount -= sizeof(uint32_t); - } - } -} - -/** - * @brief I3C receive by byte. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_ReceiveByteTreatment(I3C_HandleTypeDef *hi3c) -{ - /* Check RX FIFO not empty flag */ - while (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_RXFNEF) == SET) - { - /* Store received bytes in the Rx buffer */ - *hi3c->pXferData->RxBuf.pBuffer = LL_I3C_ReceiveData8(hi3c->Instance); - - /* Increment Buffer pointer */ - hi3c->pXferData->RxBuf.pBuffer++; - - /* Decrement remaining bytes counter */ - hi3c->RxXferCount--; - } -} - -/** - * @brief I3C receive by word. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_ReceiveWordTreatment(I3C_HandleTypeDef *hi3c) -{ - /* Check RX FIFO not empty flag */ - while (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_RXFNEF) == SET) - { - /* Store received bytes in the Rx buffer */ - *((uint32_t *)hi3c->pXferData->RxBuf.pBuffer) = LL_I3C_ReceiveData32(hi3c->Instance); - - /* Increment Buffer pointer */ - hi3c->pXferData->RxBuf.pBuffer += sizeof(uint32_t); - - if (hi3c->RxXferCount > sizeof(uint32_t)) - { - /* Decrement remaining bytes counter */ - hi3c->RxXferCount -= sizeof(uint32_t); - } - else - { - /* Reset counter as last modulo word Rx data received */ - hi3c->RxXferCount = 0U; - } - } -} - -/** - * @brief I3C Control data treatment. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_ControlDataTreatment(I3C_HandleTypeDef *hi3c) -{ - /* Check if Control FIFO requests data */ - if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_CFNFF) == SET) - { - /* Decrement remaining control buffer data counter */ - hi3c->ControlXferCount--; - - /* Write Control buffer data to control register */ - WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); - - /* Increment Buffer pointer */ - hi3c->pXferData->CtrlBuf.pBuffer++; - } -} - -/** - * @brief I3C state update. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_StateUpdate(I3C_HandleTypeDef *hi3c) -{ - /* Check on previous state */ - if (hi3c->PreviousState == HAL_I3C_STATE_LISTEN) - { - /* Set state to listen */ - hi3c->State = HAL_I3C_STATE_LISTEN; - - /* Check the I3C mode */ - if (hi3c->Mode == HAL_I3C_MODE_TARGET) - { - /* Store the target event treatment function */ - hi3c->XferISR = I3C_Tgt_Event_ISR; - } - else - { - /* Store the controller event treatment function */ - hi3c->XferISR = I3C_Ctrl_Event_ISR; - } - } - else - { - /* Set state to ready */ - hi3c->State = HAL_I3C_STATE_READY; - - /* Reset XferISR */ - hi3c->XferISR = NULL; - } -} - -/** - * @brief I3C get error source. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_GetErrorSources(I3C_HandleTypeDef *hi3c) -{ - /* Check on the I3C mode */ - switch (hi3c->Mode) - { - case HAL_I3C_MODE_CONTROLLER: - { - /* I3C data error during controller-role hand-off procedure */ - if (LL_I3C_IsActiveFlag_DERR(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_DATA_HAND_OFF; - } - - /* I3C data not acknowledged error */ - if (LL_I3C_IsActiveFlag_DNACK(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_DATA_NACK; - } - - /* I3C address not acknowledged error */ - if (LL_I3C_IsActiveFlag_ANACK(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_ADDRESS_NACK; - } - - /* I3C Status FIFO Over-Run or Control FIFO Under-Run error */ - if (LL_I3C_IsActiveFlag_COVR(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_COVR; - } - - break; - } - - case HAL_I3C_MODE_TARGET: - { - /* I3C SCL stall error */ - if (LL_I3C_IsActiveFlag_STALL(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_STALL; - } - - break; - } - - default: - { - break; - } - } - - /* I3C Rx FIFO Over-Run or Tx FIFO Under-Run error */ - if (LL_I3C_IsActiveFlag_DOVR(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= HAL_I3C_ERROR_DOVR; - } - - /* I3C Protocol error */ - if (LL_I3C_IsActiveFlag_PERR(hi3c->Instance) == 1U) - { - hi3c->ErrorCode |= (I3C_SER_PERR | LL_I3C_GetMessageErrorCode(hi3c->Instance)); - } -} - -/** - * @brief I3C transfer prior preparation. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param counter : [IN] Number of devices or commands to treat. - * @param option : [IN] Parameter indicates the transfer option. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Xfer_PriorPreparation(I3C_HandleTypeDef *hi3c, uint8_t counter, uint32_t option) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t current_tx_index = 0U; - uint32_t global_tx_size = 0U; - uint32_t global_rx_size = 0U; - uint32_t nb_tx_frame = 0U; - uint32_t direction; - - for (uint32_t descr_index = 0U; descr_index < counter; descr_index++) - { - /* Direct CCC command */ - if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_DIRECT) - { - /* Update direction of frame */ - direction = hi3c->pCCCDesc[descr_index].Direction; - - /* Direction read with Define byte */ - if (((option & I3C_DEFINE_BYTE_MASK) != 0U) && (direction == HAL_I3C_DIRECTION_READ)) - { - nb_tx_frame += 1U; - - global_tx_size += 1U; - - global_rx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size - 1U; - - /* Check on the global size and on the Tx buffer pointer */ - if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ - (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ - (hi3c->pXferData->TxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - - status = HAL_ERROR; - } - else - { - /* Fill global Tx buffer with data and update the current index of the Tx buffer */ - current_tx_index = I3C_FillTxBuffer_CCC(hi3c, descr_index, 1U, current_tx_index); - } - } - else if (direction == HAL_I3C_DIRECTION_WRITE) - { - nb_tx_frame += 1U; - - global_tx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size; - - /* Check on the global size and on the Tx buffer pointer */ - if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ - (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ - (hi3c->pXferData->TxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - - status = HAL_ERROR; - } - else - { - /* Fill global Tx buffer with data and update the current index of the Tx buffer */ - current_tx_index = I3C_FillTxBuffer_CCC(hi3c, - descr_index, - hi3c->pCCCDesc[descr_index].CCCBuf.Size, - current_tx_index); - } - } - /* Direction read without Define byte */ - else - { - global_rx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size; - } - } - /* Broadcast CCC command */ - else if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_CCC) - { - /* Update direction of frame */ - direction = hi3c->pCCCDesc[descr_index].Direction; - - if (direction == HAL_I3C_DIRECTION_WRITE) - { - nb_tx_frame += 1U; - - global_tx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size; - - /* Check on the global size and on the Tx buffer pointer */ - if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ - (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ - (hi3c->pXferData->TxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - - status = HAL_ERROR; - } - else - { - /* Fill global Tx buffer with data and update the current index of the Tx buffer */ - current_tx_index = I3C_FillTxBuffer_CCC(hi3c, - descr_index, - hi3c->pCCCDesc[descr_index].CCCBuf.Size, - current_tx_index); - } - } - else - { - status = HAL_ERROR; - } - } - /* Private */ - else - { - /* Update direction of frame */ - direction = hi3c->pPrivateDesc[descr_index].Direction; - - if (direction == HAL_I3C_DIRECTION_WRITE) - { - nb_tx_frame += 1U; - - global_tx_size += hi3c->pPrivateDesc[descr_index].TxBuf.Size; - - /* Check on the global size and on the Tx buffer pointer */ - if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ - (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ - (hi3c->pXferData->TxBuf.pBuffer == NULL)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - - status = HAL_ERROR; - } - else - { - /* Fill global Tx buffer with data and update the current index of the Tx buffer */ - current_tx_index = I3C_FillTxBuffer_Private(hi3c, - descr_index, - hi3c->pPrivateDesc[descr_index].TxBuf.Size, - current_tx_index); - } - } - else - { - global_rx_size += hi3c->pPrivateDesc[descr_index].RxBuf.Size; - } - } - - /* Check if there is an error in the Tx Buffer*/ - if (status == HAL_ERROR) - { - break; - } - } - - if (status == HAL_OK) - { - /* Check on the Tx threshold and the number of Tx frame */ - if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_4_4) - { - /* LL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains - multiple transmission frames */ - if (nb_tx_frame > 1U) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - } - } - - if (status == HAL_OK) - { - /* Check on the size Rx buffer */ - if (global_rx_size > hi3c->pXferData->RxBuf.Size) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - hi3c->RxXferCount = global_rx_size; - } - - /* Set handle transfer parameters */ - hi3c->TxXferCount = global_tx_size; - } - - return status; -} - -/** - * @brief I3C fill Tx Buffer with data from CCC Descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param indexDesc : [IN] Index of descriptor. - * @param txSize : [IN] Size of Tx data. - * @param txCurrentIndex : [IN] Current Index of TxBuffer. - * @retval index_tx : [OUT] New current Index of TxBuffer. - */ -static uint32_t I3C_FillTxBuffer_CCC(I3C_HandleTypeDef *hi3c, - uint32_t indexDesc, - uint32_t txSize, - uint32_t txCurrentIndex) -{ - uint32_t index_tx = txCurrentIndex; - - for (uint32_t index = 0U; index < txSize; index++) - { - hi3c->pXferData->TxBuf.pBuffer[index_tx] = hi3c->pCCCDesc[indexDesc].CCCBuf.pBuffer[index]; - - index_tx++; - } - - return index_tx; -} - -/** - * @brief I3C fill Tx Buffer with data from Private Descriptor. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param indexDesc : [IN] Index of descriptor. - * @param txSize : [IN] Size of Tx data. - * @param txCurrentIndex : [IN] Current Index of TxBuffer. - * @retval index_tx : [OUT] New current Index of TxBuffer. - */ -static uint32_t I3C_FillTxBuffer_Private(I3C_HandleTypeDef *hi3c, - uint32_t indexDesc, - uint32_t txSize, - uint32_t txCurrentIndex) -{ - uint32_t index_tx = txCurrentIndex; - - for (uint32_t index = 0U; index < txSize; index++) - { - hi3c->pXferData->TxBuf.pBuffer[index_tx] = hi3c->pPrivateDesc[indexDesc].TxBuf.pBuffer[index]; - - index_tx++; - } - - return index_tx; -} - -/** - * @brief I3C Control buffer prior preparation. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param counter : [IN] Number of devices or commands to treat. - * @param option : [IN] Parameter indicates the transfer option. - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_ControlBuffer_PriorPreparation(I3C_HandleTypeDef *hi3c, - uint8_t counter, - uint32_t option) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t nb_define_bytes; - uint32_t stop_condition; - uint32_t nb_data_bytes; - uint32_t index; - - /* Check on the control buffer pointer */ - if (hi3c->pXferData->CtrlBuf.pBuffer == NULL) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Extract from option required information */ - nb_define_bytes = (option & I3C_DEFINE_BYTE_MASK); - stop_condition = (option & I3C_RESTART_STOP_MASK); - - /* Check on the deactivation of the arbitration */ - if ((option & I3C_ARBITRATION_HEADER_MASK) == I3C_ARBITRATION_HEADER_MASK) - { - /* Disable arbitration header */ - LL_I3C_DisableArbitrationHeader(hi3c->Instance); - } - else - { - /* Enable arbitration header */ - LL_I3C_EnableArbitrationHeader(hi3c->Instance); - } - - /* Check on the operation type */ - if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_CCC) - { - /*------------------------------------------ Broadcast CCC -----------------------------------------------------*/ - /* Check on the control buffer size */ - if (hi3c->pXferData->CtrlBuf.Size < (uint32_t)counter) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Set remaining control buffer data counter */ - hi3c->ControlXferCount = (uint32_t)counter; - - /* For loop on the number of commands */ - for (index = 0U; index < ((uint32_t)counter - 1U); index++) - { - /* Update control buffer value */ - hi3c->pXferData->CtrlBuf.pBuffer[index] = ((uint32_t)hi3c->pCCCDesc[index].CCCBuf.Size | - ((uint32_t)hi3c->pCCCDesc[index].CCC << I3C_CR_CCC_Pos) | - LL_I3C_CONTROLLER_MTYPE_CCC | stop_condition); - } - - /* At the last device we should generate a stop condition */ - hi3c->pXferData->CtrlBuf.pBuffer[index] = ((uint32_t)hi3c->pCCCDesc[index].CCCBuf.Size | - ((uint32_t)hi3c->pCCCDesc[index].CCC << I3C_CR_CCC_Pos) | - LL_I3C_CONTROLLER_MTYPE_CCC | LL_I3C_GENERATE_STOP); - } - } - else if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_DIRECT) - { - /*------------------------------------------ Direct CCC --------------------------------------------------------*/ - /* Check on the control buffer size */ - if (hi3c->pXferData->CtrlBuf.Size < ((uint32_t)counter * 2U)) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Set remaining control buffer data counter */ - hi3c->ControlXferCount = ((uint32_t)counter * 2U); - - /* For loop on the number of (devices or commands) * 2 */ - for (index = 0U; index < (((uint32_t)counter * 2U) - 2U); index += 2U) - { - /* Step 1 : update control buffer value for the CCC command */ - hi3c->pXferData->CtrlBuf.pBuffer[index] = (nb_define_bytes | - ((uint32_t)hi3c->pCCCDesc[index / 2U].CCC << I3C_CR_CCC_Pos) | - LL_I3C_CONTROLLER_MTYPE_CCC | LL_I3C_GENERATE_RESTART); - - /* Step 2 : update control buffer value for target address */ - hi3c->pXferData->CtrlBuf.pBuffer[index + 1U] = - (((uint32_t)hi3c->pCCCDesc[index / 2U].CCCBuf.Size - nb_define_bytes) | - hi3c->pCCCDesc[index / 2U].Direction | - ((uint32_t)hi3c->pCCCDesc[index / 2U].TargetAddr << I3C_CR_ADD_Pos) | - LL_I3C_CONTROLLER_MTYPE_DIRECT | stop_condition); - } - - /* Update control buffer value for the last CCC command */ - hi3c->pXferData->CtrlBuf.pBuffer[index] = (nb_define_bytes | - ((uint32_t)hi3c->pCCCDesc[index / 2U].CCC << I3C_CR_CCC_Pos) | - LL_I3C_CONTROLLER_MTYPE_CCC | LL_I3C_GENERATE_RESTART); - - /* At the last device we should generate a stop condition */ - hi3c->pXferData->CtrlBuf.pBuffer[index + 1U] = - (((uint32_t)hi3c->pCCCDesc[index / 2U].CCCBuf.Size - nb_define_bytes) | - hi3c->pCCCDesc[index / 2U].Direction | - ((uint32_t)hi3c->pCCCDesc[index / 2U].TargetAddr << I3C_CR_ADD_Pos) | - LL_I3C_CONTROLLER_MTYPE_DIRECT | LL_I3C_GENERATE_STOP); - } - } - else - { - /*------------------------------------------ Private I3C/I2C ---------------------------------------------------*/ - /* Check on the control buffer size */ - if (hi3c->pXferData->CtrlBuf.Size < (uint32_t)counter) - { - hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - /* Set remaining control buffer data counter */ - hi3c->ControlXferCount = (uint32_t)counter; - - /* For loop on the number of devices */ - for (index = 0U; index < ((uint32_t)counter - 1U); index++) - { - /* Check on transfer direction */ - if (hi3c->pPrivateDesc[index].Direction == HAL_I3C_DIRECTION_READ) - { - nb_data_bytes = hi3c->pPrivateDesc[index].RxBuf.Size; - } - else - { - nb_data_bytes = hi3c->pPrivateDesc[index].TxBuf.Size; - } - - /* Update control buffer value */ - hi3c->pXferData->CtrlBuf.pBuffer[index] = - (nb_data_bytes | hi3c->pPrivateDesc[index].Direction | - ((uint32_t)hi3c->pPrivateDesc[index].TargetAddr << I3C_CR_ADD_Pos) | - (option & I3C_OPERATION_TYPE_MASK) | stop_condition); - } - - /* Check on transfer direction */ - if (hi3c->pPrivateDesc[index].Direction == HAL_I3C_DIRECTION_READ) - { - nb_data_bytes = hi3c->pPrivateDesc[index].RxBuf.Size; - } - else - { - nb_data_bytes = hi3c->pPrivateDesc[index].TxBuf.Size; - } - - /* At the last device we should generate a stop condition */ - hi3c->pXferData->CtrlBuf.pBuffer[index] = - (nb_data_bytes | hi3c->pPrivateDesc[index].Direction | - ((uint32_t)hi3c->pPrivateDesc[index].TargetAddr << I3C_CR_ADD_Pos) | - (option & I3C_OPERATION_TYPE_MASK) | LL_I3C_GENERATE_STOP); - } - } - } - - return status; -} - -/** - * @brief Check if target device is ready for communication. - * @param hi3c : Pointer to a I3C_HandleTypeDef structure that contains - * the configuration information for the specified I3C. - * @param pDevice : [IN] Structure to define the device address and the device type. - * @param trials : [IN] Number of trials - * @param timeout : [IN] Timeout duration - * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. - */ -static HAL_StatusTypeDef I3C_Ctrl_IsDevice_Ready(I3C_HandleTypeDef *hi3c, - const I3C_DeviceTypeDef *pDevice, - uint32_t trials, - uint32_t timeout) -{ - __IO uint32_t I3C_Trials = 0UL; - __IO uint32_t exit_condition; - uint32_t CR_tmp; - uint32_t tickstart; - HAL_StatusTypeDef status = HAL_OK; - HAL_I3C_StateTypeDef handle_state; - uint32_t arbitration_previous_state; - - /* Get I3C handle state */ - handle_state = hi3c->State; - - /* check on the Mode */ - if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) - { - hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; - status = HAL_ERROR; - } - /* check on the State */ - else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) - { - status = HAL_BUSY; - } - else - { - /* Set handle transfer parameters */ - hi3c->ErrorCode = HAL_I3C_ERROR_NONE; - hi3c->State = HAL_I3C_STATE_BUSY; - - /* Before modify the arbitration, get the current arbitration state */ - arbitration_previous_state = LL_I3C_IsEnabledArbitrationHeader(hi3c->Instance); - - /* Disable arbitration header */ - LL_I3C_DisableArbitrationHeader(hi3c->Instance); - - CR_tmp = (HAL_I3C_DIRECTION_WRITE | - ((uint32_t)pDevice->Address << I3C_CR_ADD_Pos) | - pDevice->MessageType | LL_I3C_GENERATE_STOP); - - do - { - /* Initiate a start condition by writing in the CR register */ - WRITE_REG(hi3c->Instance->CR, CR_tmp); - - /* Calculate exit_condition value based on Frame complete and error flags */ - exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); - - tickstart = HAL_GetTick(); - - while (exit_condition == 0U) - { - if (timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) - { - /* Update I3C error code */ - hi3c->ErrorCode |= HAL_I3C_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - - break; - } - } - /* Calculate exit_condition value based on Frame complete and error flags */ - exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); - } - - if (status == HAL_OK) - { - /* Check if the FCF flag has been set */ - if (__HAL_I3C_GET_FLAG(hi3c, I3C_EVR_FCF) == SET) - { - /* Clear frame complete flag */ - LL_I3C_ClearFlag_FC(hi3c->Instance); - - /* Device is ready */ - break; - } - else - { - /* Clear ERR flag */ - LL_I3C_ClearFlag_ERR(hi3c->Instance); - } - } - - /* Increment Trials */ - I3C_Trials++; - - } while ((I3C_Trials < trials) && (status == HAL_OK)); - - /* Device is not ready */ - if (trials == I3C_Trials) - { - hi3c->ErrorCode = HAL_I3C_ERROR_ADDRESS_NACK; - status = HAL_ERROR; - } - - /* update state to Previous state */ - I3C_StateUpdate(hi3c); - - /* Check if previous arbitration state is enabled */ - if (arbitration_previous_state == 1U) - { - LL_I3C_EnableArbitrationHeader(hi3c->Instance); - } - } - - return status; -} - -/** - * @brief Manage the enabling of Interrupts. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param InterruptRequest : [IN] Value of the interrupt request - * @retval None - */ -static void I3C_Enable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest) -{ - uint32_t tmpisr = 0U; - - /* Check if requested interrupts are related to listening mode */ - if ((InterruptRequest & I3C_XFER_LISTEN_IT) != 0U) - { - tmpisr |= ((InterruptRequest & (~I3C_XFER_LISTEN_IT)) | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target transmit in IT mode */ - if ((InterruptRequest & I3C_XFER_TARGET_TX_IT) != 0U) - { - /* Enable frame complete, transmit FIFO not full and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target receive in IT mode */ - if ((InterruptRequest & I3C_XFER_TARGET_RX_IT) != 0U) - { - /* Enable frame complete, receive FIFO not empty and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE) ; - } - - /* Check if requested interrupts are related to transmit/receive in DMA mode */ - if ((InterruptRequest & I3C_XFER_DMA) != 0U) - { - /* Enable frame complete and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target hot join */ - if ((InterruptRequest & I3C_XFER_TARGET_HOTJOIN) != 0U) - { - /* Enable dynamic address update and error interrupts */ - tmpisr |= (HAL_I3C_IT_DAUPDIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target control role */ - if ((InterruptRequest & I3C_XFER_TARGET_CTRLROLE) != 0U) - { - /* Enable control role update and error interrupts */ - tmpisr |= (HAL_I3C_IT_CRUPDIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target in band interrupt */ - if ((InterruptRequest & I3C_XFER_TARGET_IBI) != 0U) - { - /* Enable IBI end and error interrupts */ - tmpisr |= (HAL_I3C_IT_IBIENDIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller transmit in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_TX_IT) != 0U) - { - /* Enable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller receive in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_RX_IT) != 0U) - { - /* Enable frame complete, control FIFO not full, receive FIFO not empty and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller transmit read or a broadcast CCC in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_RX_CCC_IT) != 0U) - { - /* Enable frame complete, transmit FIFO not full, control FIFO not full, - receive FIFO not empty and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller transmit broadcast ENTDAA CCC in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_DAA_IT) != 0U) - { - /* Enable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); - } - - /* Enable requested interrupts */ - __HAL_I3C_ENABLE_IT(hi3c, tmpisr); -} - -/** - * @brief Manage the disabling of Interrupts. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @param InterruptRequest : [IN] Value of the interrupt request - * @retval None - */ -static void I3C_Disable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest) -{ - uint32_t tmpisr = 0U; - - /* Check if requested interrupts are related to listening mode */ - if ((InterruptRequest & I3C_XFER_LISTEN_IT) != 0U) - { - tmpisr |= ((InterruptRequest & (~I3C_XFER_LISTEN_IT)) | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target transmit mode */ - if ((InterruptRequest & I3C_XFER_TARGET_TX_IT) != 0U) - { - /* Disable frame complete, transmit FIFO not full and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target receive mode */ - if ((InterruptRequest & I3C_XFER_TARGET_RX_IT) != 0U) - { - /* Disable frame complete, receive FIFO not empty and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to transmit/receive in DMA mode */ - if ((InterruptRequest & I3C_XFER_DMA) != 0U) - { - /* Disable frame complete and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target hot join */ - if ((InterruptRequest & I3C_XFER_TARGET_HOTJOIN) != 0U) - { - /* Disable dynamic address update and error interrupts */ - tmpisr |= (HAL_I3C_IT_DAUPDIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target control role */ - if ((InterruptRequest & I3C_XFER_TARGET_CTRLROLE) != 0U) - { - /* Disable control role update and error interrupts */ - tmpisr |= (HAL_I3C_IT_CRUPDIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to target in band interrupt */ - if ((InterruptRequest & I3C_XFER_TARGET_IBI) != 0U) - { - /* Disable IBI end and error interrupts */ - tmpisr |= (HAL_I3C_IT_IBIENDIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller transmit in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_TX_IT) != 0U) - { - /* Disable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller transmit read or a broadcast CCC in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_RX_CCC_IT) != 0U) - { - /* Disable frame complete, transmit FIFO not full, control FIFO not full, - receive FIFO not empty and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); - } - - /* Check if requested interrupts are related to controller transmit broadcast ENTDAA CCC in IT mode */ - if ((InterruptRequest & I3C_XFER_CONTROLLER_DAA_IT) != 0U) - { - /* Disable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ - tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); - } - - /* Disable requested interrupts */ - __HAL_I3C_DISABLE_IT(hi3c, tmpisr); -} - -/** - * @brief I3C error treatment. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_ErrorTreatment(I3C_HandleTypeDef *hi3c) -{ - HAL_I3C_StateTypeDef tmpstate = hi3c->State; - uint32_t dmaabortongoing = 0U; - - /* Check on the state */ - if (tmpstate == HAL_I3C_STATE_BUSY) - { - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - /* Disable all interrupts related to busy state */ - I3C_Disable_IRQ(hi3c, (I3C_XFER_TARGET_IBI | I3C_XFER_TARGET_HOTJOIN | I3C_XFER_TARGET_CTRLROLE)); - } - else - { - /* Disable all interrupts related to busy Tx and Rx state */ - I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); - - /* Reset Tx counter */ - hi3c->TxXferCount = 0U; - - /* Reset Rx counter */ - hi3c->RxXferCount = 0U; - - /* Reset Control counter */ - hi3c->ControlXferCount = 0U; - - /* Reset Tx function pointer */ - hi3c->ptrTxFunc = NULL; - - /* Reset Rx function pointer */ - hi3c->ptrRxFunc = NULL; - - /* Reset Context pointer */ - hi3c->pXferData = NULL; - hi3c->pCCCDesc = NULL; - hi3c->pPrivateDesc = NULL; - - /* Flush all FIFOs */ - /* Flush the content of Tx Fifo */ - LL_I3C_RequestTxFIFOFlush(hi3c->Instance); - - /* Flush the content of Rx Fifo */ - LL_I3C_RequestRxFIFOFlush(hi3c->Instance); - - /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ - if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) - { - /* Flush the content of Control Fifo */ - LL_I3C_RequestControlFIFOFlush(hi3c->Instance); - - /* Flush the content of Status Fifo */ - LL_I3C_RequestStatusFIFOFlush(hi3c->Instance); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort control DMA transfer if any */ - if (hi3c->hdmacr != NULL) - { - /* Disable control DMA Request */ - LL_I3C_DisableDMAReq_Control(hi3c->Instance); - - /* Check DMA state */ - if (HAL_DMA_GetState(hi3c->hdmacr) != HAL_DMA_STATE_READY) - { - /* Set the I3C DMA Abort callback : will lead to call HAL_I3C_AbortCpltCallback() - at end of DMA abort procedure */ - - /* DMA abort on going */ - dmaabortongoing = 1U; - - /* Abort control DMA */ - if (HAL_DMA_Abort_IT(hi3c->hdmacr) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi3c->hdmacr->XferAbortCallback(hi3c->hdmacr); - } - } - } - - /* Abort RX DMA transfer if any */ - if (hi3c->hdmarx != NULL) - { - /* Disable Rx DMA Request */ - LL_I3C_DisableDMAReq_RX(hi3c->Instance); - - /* Check DMA state */ - if (HAL_DMA_GetState(hi3c->hdmarx) != HAL_DMA_STATE_READY) - { - /* Set the I3C DMA Abort callback : will lead to call HAL_I3C_AbortCpltCallback() - at end of DMA abort procedure */ - hi3c->hdmarx->XferAbortCallback = I3C_DMAAbort; - - /* DMA abort on going */ - dmaabortongoing = 1U; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi3c->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi3c->hdmarx->XferAbortCallback(hi3c->hdmarx); - } - } - } - - /* Abort TX DMA transfer if any */ - if (hi3c->hdmatx != NULL) - { - /* Disable Tx DMA Request */ - LL_I3C_DisableDMAReq_TX(hi3c->Instance); - - /* Check DMA state */ - if (HAL_DMA_GetState(hi3c->hdmatx) != HAL_DMA_STATE_READY) - { - /* Set the I3C DMA Abort callback : will lead to call HAL_I3C_AbortCpltCallback() - at end of DMA abort procedure */ - hi3c->hdmatx->XferAbortCallback = I3C_DMAAbort; - - /* DMA abort on going */ - dmaabortongoing = 1U; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi3c->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hi3c->hdmatx->XferAbortCallback(hi3c->hdmatx); - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - } - - /* Call Error callback if there is no DMA abort on going */ - if (dmaabortongoing == 0U) - { - I3C_TreatErrorCallback(hi3c); - } -} - -/** - * @brief I3C Error callback treatment. - * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration - * information for the specified I3C. - * @retval None - */ -static void I3C_TreatErrorCallback(I3C_HandleTypeDef *hi3c) -{ - if (hi3c->State == HAL_I3C_STATE_ABORT) - { - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1) - hi3c->AbortCpltCallback(hi3c); -#else - HAL_I3C_AbortCpltCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ - } - else - { - /* Update handle state parameter */ - I3C_StateUpdate(hi3c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1) - hi3c->ErrorCallback(hi3c); -#else - HAL_I3C_ErrorCallback(hi3c); -#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ - } -} - -/** - * @} - */ - -#endif /* HAL_I3C_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ********************************************************************************************************************** + * @file stm32h7rsxx_hal_i3c.c + * @author MCD Application Team + * @brief I3C HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Improvement Inter Integrated Circuit (I3C) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + ********************************************************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ********************************************************************************************************************** + @verbatim + ====================================================================================================================== + ##### How to use this driver ##### + ====================================================================================================================== + [..] + The I3C HAL driver can be used as follows: + + (#) Declare a I3C_HandleTypeDef handle structure, for example: + I3C_HandleTypeDef hi3c; + + (#) Declare a I3C_XferTypeDef transfer descriptor structure, for example: + I3C_XferTypeDef ContextBuffers; + + (#)Initialize the I3C low level resources by implementing the HAL_I3C_MspInit() API: + (##) Enable the I3Cx interface clock + (##) I3C pins configuration + (+++) Enable the clock for the I3C GPIOs + (+++) Configure I3C pins as alternate function push-pull with no-pull + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the I3Cx interrupt priority + (+++) Enable the NVIC I3C IRQ Channel + (##) DMA Configuration if you need to use DMA process + (+++) Declare a DMA_HandleTypeDef handle structure for + the Command Common Code (CCC) management channel + (+++) Declare a DMA_HandleTypeDef handle structure for + the transmit channel + (+++) Declare a DMA_HandleTypeDef handle structure for + the receive channel + (+++) Declare a DMA_HandleTypeDef handle structure for + the status channel + (+++) Enable the DMAx interface clock + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Command Common Code (CCC) channel + (+++) Configure the DMA Tx channel + (+++) Configure the DMA Rx channel + (+++) Configure the DMA Status channel + (+++) Associate the initialized DMA handle to the hi3c DMA CCC, Tx, Rx or Status handle as necessary + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on + the DMA CCC, Tx, Rx or Status instance + + (#) Configure the HAL I3C Communication Mode as Controller or Target in the hi3c Init structure. + + (#) Configure the Controller Communication Bus characterics for Controller mode. + This mean, configure the parameters SDAHoldTime, WaitTime, SCLPPLowDuration, + SCLI3CHighDuration, SCLODLowDuration, SCLI2CHighDuration, BusFreeDuration, + BusIdleDuration in the LL_I3C_CtrlBusConfTypeDef structure through h3c Init structure. + + (#) Configure the Target Communication Bus characterics for Target mode. + This mean, configure the parameter BusAvailableDuration in the LL_I3C_TgtBusConfTypeDef structure + through h3c Init structure. + + All these parameters for Controller or Target can be configured directly in user code or + by using CubeMx generation. + To help the computation of the different parameters, the recommendation is to use CubeMx. + + Those parameters can be modified after the hi3c initialization by using + HAL_I3C_Ctrl_BusCharacteristicConfig() for controller and + HAL_I3C_Tgt_BusCharacteristicConfig() for target. + + (#) Initialize the I3C registers by calling the HAL_I3C_Init(), configures also the low level Hardware + (GPIO, CLOCK, NVIC...etc) by calling the customized HAL_I3C_MspInit(&hi3c) API. + + (#) Configure the different FIFO parameters in I3C_FifoConfTypeDef structure as RxFifoThreshold, TxFifoThreshold + for Controller or Target mode. + And enable/disable the Control or Status FIFO only for Controller Mode. + Use HAL_I3C_SetConfigFifo() function to finalize the configuration, and HAL_I3C_GetConfigFifo() to retrieve + FIFO configuration. + Possibility to clear the FIFO configuration by using HAL_I3C_ClearConfigFifo() which reset the configuration + FIFO to their default hardware value + + (#) Configure the different additional Controller configuration in I3C_CtrlConfTypeDef structure as DynamicAddr, + StallTime, HotJoinAllowed, ACKStallState, CCCStallState, TxStallState, RxStallState, HighKeeperSDA. + Use HAL_I3C_Ctrl_Config() function to finalize the Controller configuration. + + (#) Configure the different additional Target configuration in I3C_TgtConfTypeDef structure as Identifier, + MIPIIdentifier, CtrlRoleRequest, HotJoinRequest, IBIRequest, IBIPayload, IBIPayloadSize, MaxReadDataSize, + MaxWriteDataSize, CtrlCapability, GroupAddrCapability, DataTurnAroundDuration, MaxReadTurnAround, + MaxDataSpeed, MaxSpeedLimitation, HandOffActivityState, HandOffDelay, PendingReadMDB. + Use HAL_I3C_Tgt_Config() function to finalize the Target configuration. + + (#) Before initiate any IO operation, the application must launch an assignment of the different + Target dynamic address by using HAL_I3C_Ctrl_DynAddrAssign() in polling mode or + HAL_I3C_Ctrl_DynAddrAssign_IT() in interrupt mode. + This procedure is named Enter Dynamic Address Assignment (ENTDAA CCC command). + For the initiation of ENTDAA procedure from the controller, each target connected and powered on the I3C bus + must repond to this particular Command Common Code by sending its proper Payload (a amount of 48bits which + contain the target characteristics) + Each time a target responds to ENTDAA sequence, the application is informed through + HAL_I3C_TgtReqDynamicAddrCallback() of the reception of the target paylaod. + And then application must send a associated dynamic address through HAL_I3C_Ctrl_SetDynAddr(). + This procedure in loop automatically in hardware side until a target respond to repeated ENTDAA sequence. + The application is informed of the end of the procedure at reception of HAL_I3C_CtrlDAACpltCallback(). + Then application can easily retrieve ENTDAA payload information through HAL_I3C_Get_ENTDAA_Payload_Info() + function. + At the end of procedure, the function HAL_I3C_Ctrl_ConfigBusDevices() must be called to store in hardware + register part the target capabilities as Dynamic address, IBI support with or without additional data byte, + Controller role request support, Controller stop transfer after IBI through I3C_DeviceConfTypeDef structure. + + (#) Other action to be done, before initiate any IO operation, the application must prepare the different frame + descriptor with its associated buffer allocation in their side. + Configure the different information related to CCC transfer through I3C_CCCTypeDef structure + Configure the different information related to Private or I2C transfer through I3C_PrivateTypeDef structure + Configure the different buffer pointers and associated size needed for the driver communication + through I3C_XferTypeDef structure + The I3C_XferTypeDef structure contains different parameters about Control, Status buffer, + and Transmit and Receive buffer. + Use HAL_I3C_AddDescToFrame() function each time application add a descriptor in the frame before call + an IO operation interface + One element of the frame descriptor correspond to one frame to manage through IO operation. + + (#) To check if I3C target device is ready for communication, use the function HAL_I3C_Ctrl_IsDeviceI3C_Ready() + + (#) To check if I2C target device is ready for communication, use the function HAL_I3C_Ctrl_IsDeviceI2C_Ready() + + (#) To send a message header {S + 0x7E + W + STOP}, use the function HAL_I3C_Ctrl_GenerateArbitration(). + (#) To insert a target reset pattern before the STOP of a transmitted frame containing a RSTACT CCC command, + the application must enable the reset pattern configuration using HAL_I3C_Ctrl_SetConfigResetPattern() + before calling HAL_I3C_Ctrl_TransmitCCC() or HAL_I3C_Ctrl_ReceiveCCC() interfaces. + + To have a standard STOP emitted at the end of a frame containing a RSTACT CCC command, the application must + disable the reset pattern configuration using HAL_I3C_Ctrl_SetConfigResetPattern() before calling + HAL_I3C_Ctrl_TransmitCCC() or HAL_I3C_Ctrl_ReceiveCCC() interfaces. + + Use HAL_I3C_Ctrl_SetConfigResetPattern() function to configure the insertion of the reset pattern at + the end of a Frame, and HAL_I3C_Ctrl_GetConfigResetPattern() to retrieve reset pattern configuration. + + (#) For I3C IO operations, three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Activate asynchronous event in controller or target mode a Common Command Code in a broadcast + or a direct communication in blocking mode using HAL_I3C_Ctrl_TransmitCCC() + (+) Transmit in controller mode a Common Command Code in a broadcast or a direct communication in blocking mode + using HAL_I3C_Ctrl_TransmitCCC() + (+) Receive in controller mode a Common Command Code in a direct communication in blocking mode + using HAL_I3C_Ctrl_ReceiveCCC() + (+) Transmit in controller mode an amount of private data in an I3C or an I2C communication in blocking mode + using HAL_I3C_Ctrl_Transmit() + (+) Receive in controller mode an amount of private data in an I3C or an I2C communication in blocking mode + using HAL_I3C_Ctrl_Receive() + (+) Transmit in target mode an amount of private data in an I3C communication in blocking mode + using HAL_I3C_Tgt_Transmit() + (+) Receive in target mode an amount of private data in an I3C communication in blocking mode + using HAL_I3C_Tgt_Receive() + (+) At the end of a transfer, the different FIFO can be flushed if necessary by using HAL_I3C_FlushAllFifo() for + flush all the FIFO, or flush individually y using HAL_I3C_FlushTxFifo(), HAL_I3C_FlushRxFifo(), + HAL_I3C_FlushControlFifo(), HAL_I3C_FlushStatusFifo(). + (+) Request a HotJoin in target mode in blocking mode using HAL_I3C_Tgt_HotJoinReq() + (+) Request a In Band Interrupt in target mode in blocking mode using HAL_I3C_Tgt_IBIReq() + (+) Request a Controller Role in target mode in blocking mode using HAL_I3C_Tgt_ControlRoleReq() + + + *** DMA and Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in controller mode a Common Command Code in a broadcast or a direct communication in non-blocking + mode using HAL_I3C_Ctrl_TransmitCCC_IT() or HAL_I3C_Ctrl_TransmitCCC_DMA() + (+) At transmission end of transfer, HAL_I3C_CtrlTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_CtrlTxCpltCallback() + (+) Receive in controller mode a Common Command Code in a direct communication in non-blocking + mode using HAL_I3C_Ctrl_ReceiveCCC_IT() or HAL_I3C_Ctrl_ReceiveCCC_DMA() + (+) At reception end of transfer, HAL_I3C_CtrlRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_CtrlRxCpltCallback() + (+) Transmit in controller mode an amount of private data in an I3C or an I2C communication in non-blocking mode + using HAL_I3C_Ctrl_Transmit_IT() or HAL_I3C_Ctrl_Transmit_DMA() + (+) At transmission end of transfer, HAL_I3C_CtrlTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_CtrlTxCpltCallback() + (+) Receive in controller mode an amount of private data in an I3C or an I2C communication in non-blocking mode + using HAL_I3C_Ctrl_Receive_IT() or HAL_I3C_Ctrl_Receive_DMA() + (+) At reception end of transfer, HAL_I3C_CtrlRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_CtrlRxCpltCallback() + (+) Transfer in multiple direction (transmit/receive) in controller mode a Common Command Code in a direct + communication or an amount of private data in an I2C or I3C communication in non-blocking mode using + HAL_I3C_Ctrl_MultipleTransfer_IT() or HAL_I3C_Ctrl_MultipleTransfer_DMA() + (+) At the end of transfer, HAL_I3C_CtrlMultipleXferCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_CtrlMultipleXferCpltCallback() + (+) Transmit in target mode an amount of private data in an I3C communication in non-blocking mode + using HAL_I3C_Tgt_Transmit_IT() or HAL_I3C_Tgt_Transmit_DMA() + (+) At transmission end of transfer, HAL_I3C_TgtTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_TgtTxCpltCallback() + (+) Receive in target mode an amount of private data in an I3C communication in non-blocking mode + using HAL_I3C_Tgt_Receive_IT() or HAL_I3C_Tgt_Receive_DMA() + (+) At reception end of transfer, HAL_I3C_TgtRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_TgtRxCpltCallback() + (+) To treat asynchronous event, HAL_I3C_ActivateNotification() or HAL_I3C_DeactivateNotification() function is + used for enable or disable one or more notification related to specific asynchronous event. + Each time one or more event detected by hardware the associated HAL_I3C_NotifyCallback() is executed + and users can add their own code by customization of function pointer HAL_I3C_NotifyCallback(). + Then application can easily retrieve some specific associated event data through HAL_I3C_GetCCCInfo() function + (+) At the end of a transfer, the different FIFO can be flushed if necessary by using HAL_I3C_FlushAllFifo() for + flush all the FIFO, or flush individually y using HAL_I3C_FlushTxFifo(), HAL_I3C_FlushRxFifo(), + HAL_I3C_FlushControlFifo(), HAL_I3C_FlushStatusFifo(). + (+) Request a HotJoin in target mode in non-blocking mode using HAL_I3C_Tgt_HotJoinReq_IT + (+) At completion, HAL_I3C_TgtHotJoinCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_TgtHotJoinCallback() + (+) Request an In Band Interrupt in target mode in non-blocking mode using HAL_I3C_Tgt_IBIReq_IT() + (+) At completion, HAL_I3C_NotifyCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_NotifyCallback() + (+) Request a Controller Role in target mode in non-blocking mode using HAL_I3C_Tgt_ControlRoleReq_IT() + (+) At completion, HAL_I3C_NotifyCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_NotifyCallback() + (+) To manage the wakeup capability, HAL_I3C_ActivateNotification() or HAL_I3C_DeactivateNotification() function + is used for enable or disable Wake Up interrupt. + At wakeup detection the associated HAL_I3C_NotifyCallback() is executed. + (+) In case of transfer Error, HAL_I3C_ErrorCallback() function is executed and users can + add their own code by customization of function pointer HAL_I3C_ErrorCallback() + (+) Abort an I3C process communication with Interrupt using HAL_I3C_Abort_IT() + (+) End of abort process, HAL_I3C_AbortCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_I3C_AbortCpltCallback() + + + *** I3C HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in I3C HAL driver. + + (+) __HAL_I3C_ENABLE: Enable the I3C peripheral + (+) __HAL_I3C_DISABLE: Disable the I3C peripheral + (+) __HAL_I3C_RESET_HANDLE_STATE: Reset the I3C handle state + (+) __HAL_I3C_GET_FLAG: Check whether the specified I3C flag is set or not + + *** Callback registration *** + ============================================= + [..] + The compilation flag USE_HAL_I3C_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_I3C_RegisterCallback() or HAL_I3C_RegisterNotifyCallback() + or HAL_I3C_RegisterTgtReqDynamicAddrCallback() or HAL_I3C_RegisterTgtHotJoinCallback() + to register an interrupt callback. + [..] + Function HAL_I3C_RegisterCallback() allows to register following callbacks: + (+) CtrlTxCpltCallback : callback for Controller transmission CCC, I3C private or I2C end of transfer. + (+) CtrlRxCpltCallback : callback for Controller reception CCC, I3C private or I2C end of transfer. + (+) CtrlMultipleXferCpltCallback : callback for Controller multiple Direct CCC, I3C private or I2C + end of transfer. + (+) CtrlDAACpltCallback : callback for Controller Enter Dynamic Address Assignment end of transfer. + (+) TgtTxCpltCallback : callback for Target transmission I3C private end of transfer. + (+) TgtRxCpltCallback : callback for Target reception I3C private end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + For specific callback NotifyCallback + use dedicated register callbacks : HAL_I3C_RegisterNotifyCallback(). + [..] + For specific callback TgtReqDynamicAddrCallback + use dedicated register callbacks : HAL_I3C_RegisterTgtReqDynamicAddrCallback(). + [..] + For specific callback TgtHotJoinCallback + use dedicated register callbacks : HAL_I3C_RegisterTgtHotJoinCallback(). + [..] + Use function HAL_I3C_UnRegisterCallback to reset a callback to the default + weak function. + HAL_I3C_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) CtrlTxCpltCallback : callback for Controller transmission CCC, I3C private or I2C end of transfer. + (+) CtrlRxCpltCallback : callback for Controller reception CCC, I3C private or I2C end of transfer. + (+) CtrlMultipleXferCpltCallback : callback for Controller multiple Direct CCC, I3C private or I2C + end of transfer. + (+) CtrlDAACpltCallback : callback for Controller Enter Dynamic Address Assignment end of transfer. + (+) TgtTxCpltCallback : callback for Target transmission I3C private end of transfer. + (+) TgtRxCpltCallback : callback for Target reception I3C private end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + (+) NotifyCallback : callback for Controller and Target notification process. + (+) TgtReqDynamicAddrCallback : callback for controller application + when a target sent its payload to the controller during Dynamic Address Assignment process. + (+) TgtHotJoinCallback : callback for Target Hotjoin completion process. + [..] + By default, after the HAL_I3C_Init() and when the state is HAL_I3C_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_I3C_CtrlTxCpltCallback(), HAL_I3C_CtrlRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the HAL_I3C_Init()/ HAL_I3C_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the HAL_I3C_Init()/ HAL_I3C_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + Callbacks can be registered/unregistered in HAL_I3C_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in HAL_I3C_STATE_READY or HAL_I3C_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using HAL_I3C_RegisterCallback() before calling HAL_I3C_DeInit() + or HAL_I3C_Init() function. + [..] + When the compilation flag USE_HAL_I3C_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + [..] + (@) You can refer to the I3C HAL driver header file for more useful macros + + @endverbatim + ********************************************************************************************************************** + */ + +/* Includes ----------------------------------------------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup I3C I3C + * @brief I3C HAL module driver + * @{ + */ + +#ifdef HAL_I3C_MODULE_ENABLED + +/* Private typedef ---------------------------------------------------------------------------------------------------*/ +/* Private define ----------------------------------------------------------------------------------------------------*/ +/** @defgroup I3C_Private_Define I3C Private Define + * @{ + */ + +/* Private define to centralize the enable/disable of Interrupts */ +#define I3C_XFER_LISTEN_IT (0x00000001U) +#define I3C_XFER_TARGET_TX_IT (0x00000002U) +#define I3C_XFER_TARGET_RX_IT (0x00000004U) +#define I3C_XFER_DMA (0x00000008U) +#define I3C_XFER_TARGET_CTRLROLE (0x00000010U) +#define I3C_XFER_TARGET_HOTJOIN (0x00000020U) +#define I3C_XFER_TARGET_IBI (0x00000040U) +#define I3C_XFER_CONTROLLER_TX_IT (0x00000080U) +#define I3C_XFER_CONTROLLER_RX_IT (0x00000100U) +#define I3C_XFER_CONTROLLER_RX_CCC_IT (0x00000400U) +#define I3C_XFER_CONTROLLER_DAA_IT (0x00001000U) + +/* Private defines for control buffer prior preparation */ +#define I3C_OPERATION_TYPE_MASK (0x78000000U) +#define I3C_RESTART_STOP_MASK (0x80000000U) +#define I3C_ARBITRATION_HEADER_MASK (0x00000004U) +#define I3C_DEFINE_BYTE_MASK (0x00000001U) + +/* Private define for CCC command */ +#define I3C_BROADCAST_RSTDAA (0x00000006U) +#define I3C_BROADCAST_ENTDAA (0x00000007U) + +/* Private define to split ENTDAA payload */ +#define I3C_DCR_IN_PAYLOAD_SHIFT 56 +#define I3C_PID_IN_PAYLOAD_MASK 0xFFFFFFFFFFFFU + +/* Private define to split PID */ +/* Bits[47:33]: MIPI Manufacturer ID */ +#define I3C_MIPIMID_PID_SHIFT 33 +#define I3C_MIPIMID_PID_MASK 0x7FFFU + +/* Bit[32]: Provisioned ID Type Selector */ +#define I3C_IDTSEL_PID_SHIFT 32 +#define I3C_IDTSEL_PID_MASK 0x01U + +/* Bits[31:16]: Part ID */ +#define I3C_PART_ID_PID_SHIFT 16 +#define I3C_PART_ID_PID_MASK 0xFFFFU + +/* Bits[15:12]: MIPI Instance ID */ +#define I3C_MIPIID_PID_SHIFT 12 +#define I3C_MIPIID_PID_MASK 0xFU +/** + * @} + */ + +/* Private macro -----------------------------------------------------------------------------------------------------*/ + +/** @brief Get Provisioned ID in payload (64bits) receive during ENTDAA procedure. + * @param __PAYLOAD__ specifies the Device Characteristics capabilities retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFFFFFF. + * @retval The value of PID Return value between Min_Data=0x00 and Max_Data=0xFFFFFFFFFFFF. + */ +#define I3C_GET_PID(__PAYLOAD__) ((uint64_t)(__PAYLOAD__) & I3C_PID_IN_PAYLOAD_MASK) + +/** @brief Get MIPI Manufacturer ID in PID (48bits). + * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. + * @retval The value of MIPI ID Return value between Min_Data=0x00 and Max_Data=0x7FFF. + */ +#define I3C_GET_MIPIMID(__PID__) ((uint16_t)((uint64_t)(__PID__) >> I3C_MIPIMID_PID_SHIFT) & \ + I3C_MIPIMID_PID_MASK) + +/** @brief Get Type Selector in PID (48bits). + * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. + * @retval The value of Type Selector Return 0 or 1. + */ +#define I3C_GET_IDTSEL(__PID__) ((uint8_t)((uint64_t)(__PID__) >> I3C_IDTSEL_PID_SHIFT) & \ + I3C_IDTSEL_PID_MASK) + +/** @brief Get Part ID in PID (48bits). + * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. + * @retval The value of Part ID Return value between Min_Data=0x00 and Max_Data=0xFFFF. + */ +#define I3C_GET_PART_ID(__PID__) ((uint16_t)((uint64_t)(__PID__) >> I3C_PART_ID_PID_SHIFT) & \ + I3C_PART_ID_PID_MASK) + +/** @brief Get Instance ID in PID (48bits). + * @param __PID__ specifies the Provisioned ID retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFF. + * @retval The value of Instance ID Return value between Min_Data=0x00 and Max_Data=0xF. + */ +#define I3C_GET_MIPIID(__PID__) ((uint8_t)((uint64_t)(__PID__) >> I3C_MIPIID_PID_SHIFT) & \ + I3C_MIPIID_PID_MASK) + +/** @brief Get Device Characterics in payload (64bits) receive during ENTDAA procedure. + * @param __PAYLOAD__ specifies the Device Characteristics capabilities retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00(uint64_t) and Max_Data=0xFFFFFFFFFFFFFFFFFF. + * @retval The value of BCR Return value between Min_Data=0x00 and Max_Data=0xFF. + */ +#define I3C_GET_DCR(__PAYLOAD__) (((uint32_t)((uint64_t)(__PAYLOAD__) >> I3C_DCR_IN_PAYLOAD_SHIFT)) & \ + I3C_DCR_DCR) + +/** @brief Get Advanced Capabilities. + * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. + * @retval The value of advanced capabilities: + * ENABLE: supports optional advanced capabilities. + * DISABLE: not supports optional advanced capabilities. + */ +#define I3C_GET_ADVANCED_CAPABLE(__BCR__) (((((__BCR__) & I3C_BCR_BCR5_Msk) >> \ + I3C_BCR_BCR5_Pos) == 1U) ? ENABLE : DISABLE) + +/** @brief Get virtual target support. + * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. + * @retval The value of offline capable: + * ENABLE: is a Virtual Target + * DISABLE: is not a Virtual Target + */ +#define I3C_GET_VIRTUAL_TGT(__BCR__) (((((__BCR__) & I3C_BCR_BCR4_Msk) >> \ + I3C_BCR_BCR4_Pos) == 1U) ? ENABLE : DISABLE) + +/** @brief Get offline capable. + * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. + * @retval The value of offline capable + * ENABLE: Device will not always respond to I3C Bus commands + * DISABLE: Device will always respond to I3C Bus commands + */ +#define I3C_GET_OFFLINE_CAPABLE(__BCR__) (((((__BCR__) & I3C_BCR_BCR3_Msk) >> \ + I3C_BCR_BCR3_Pos) == 1U) ? ENABLE : DISABLE) + +/** @brief Get Max data speed limitation. + * @param __BCR__ specifies the Bus Characteristics capabilities retrieve during ENTDAA procedure. + * This parameter must be a number between Min_Data=0x00 and Max_Data=0xFF. + * @retval The value of offline capable: + * ENABLE: Limitation + * DISABLE: No Limitation + */ +#define I3C_GET_MAX_DATA_SPEED_LIMIT(__BCR__) (((((__BCR__) & I3C_BCR_BCR0_Msk) >> \ + I3C_BCR_BCR0_Pos) == 1U) ? ENABLE : DISABLE) + +/** @brief Change uint32_t variable form big endian to little endian. + * @param __DATA__ .uint32_t variable in big endian. + * This parameter must be a number between Min_Data=0x00(uint32_t) and Max_Data=0xFFFFFFFF. + * @retval uint32_t variable in little endian. + */ +#define I3C_BIG_TO_LITTLE_ENDIAN(__DATA__) ((uint32_t)((((__DATA__) & 0xff000000U) >> 24) | \ + (((__DATA__) & 0x00ff0000U) >> 8) | \ + (((__DATA__) & 0x0000ff00U) << 8) | \ + (((__DATA__) & 0x000000ffU) << 24))) + +/* Private variables -------------------------------------------------------------------------------------------------*/ +/** @addtogroup I3C_Private_Variables + * @{ + */ +/* Structure containing address device and message type used for the private function I3C_Ctrl_IsDevice_Ready() */ +typedef struct +{ + uint8_t Address; /* Dynamic or Static target Address */ + uint32_t MessageType; /* Message Type */ + +} I3C_DeviceTypeDef; +/** + * @} + */ + +/* Private function prototypes ---------------------------------------------------------------------------------------*/ +/** @addtogroup I3C_Private_Functions + * @{ + */ +static HAL_StatusTypeDef I3C_Tgt_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Tgt_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Tgt_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +#if defined(HAL_DMA_MODULE_ENABLED) +static HAL_StatusTypeDef I3C_Tgt_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Tgt_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +#endif /* HAL_DMA_MODULE_ENABLED */ +static HAL_StatusTypeDef I3C_Tgt_HotJoin_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Tgt_CtrlRole_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Tgt_IBI_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Tx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Rx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +#if defined(HAL_DMA_MODULE_ENABLED) +static HAL_StatusTypeDef I3C_Ctrl_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +#endif /* HAL_DMA_MODULE_ENABLED */ +static HAL_StatusTypeDef I3C_Ctrl_DAA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); +static HAL_StatusTypeDef I3C_Abort_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks); + +static HAL_StatusTypeDef I3C_WaitOnDAAUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t timeout, uint32_t tickstart); +static HAL_StatusTypeDef I3C_WaitOnFlagUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t flag, FlagStatus flagstatus, + uint32_t timeout, uint32_t tickstart); +static void I3C_TransmitByteTreatment(I3C_HandleTypeDef *hi3c); +static void I3C_TransmitWordTreatment(I3C_HandleTypeDef *hi3c); +static void I3C_ReceiveByteTreatment(I3C_HandleTypeDef *hi3c); +static void I3C_ReceiveWordTreatment(I3C_HandleTypeDef *hi3c); +static void I3C_ControlDataTreatment(I3C_HandleTypeDef *hi3c); +static void I3C_ErrorTreatment(I3C_HandleTypeDef *hi3c); +static void I3C_GetErrorSources(I3C_HandleTypeDef *hi3c); +static void I3C_StateUpdate(I3C_HandleTypeDef *hi3c); +#if defined(HAL_DMA_MODULE_ENABLED) +static void I3C_DMAAbort(DMA_HandleTypeDef *hdma); +static void I3C_DMAControlTransmitCplt(DMA_HandleTypeDef *hdma); +static void I3C_DMADataTransmitCplt(DMA_HandleTypeDef *hdma); +static void I3C_DMADataReceiveCplt(DMA_HandleTypeDef *hdma); +static void I3C_DMAError(DMA_HandleTypeDef *hdma); +#endif /* HAL_DMA_MODULE_ENABLED */ +static void I3C_Enable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest); +static void I3C_Disable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest); +static HAL_StatusTypeDef I3C_Xfer_PriorPreparation(I3C_HandleTypeDef *hi3c, uint8_t counter, uint32_t option); +static uint32_t I3C_FillTxBuffer_CCC(I3C_HandleTypeDef *hi3c, + uint32_t indexDesc, + uint32_t txSize, + uint32_t txCurrentIndex); +static uint32_t I3C_FillTxBuffer_Private(I3C_HandleTypeDef *hi3c, + uint32_t indexDesc, + uint32_t txSize, + uint32_t txCurrentIndex); +static HAL_StatusTypeDef I3C_ControlBuffer_PriorPreparation(I3C_HandleTypeDef *hi3c, + uint8_t counter, + uint32_t option); +static HAL_StatusTypeDef I3C_Ctrl_IsDevice_Ready(I3C_HandleTypeDef *hi3c, + const I3C_DeviceTypeDef *pDevice, + uint32_t trials, + uint32_t timeout); +static void I3C_TreatErrorCallback(I3C_HandleTypeDef *hi3c); +/** + * @} + */ + +/* Exported functions ------------------------------------------------------------------------------------------------*/ +/** @addtogroup I3C_Exported_Functions I3C Exported Functions + * @{ + */ + +/** @defgroup I3C_Exported_Functions_Group1 Initialization and de-initialization functions. + * @brief I3C initialization and de-initialization functions + * +@verbatim + ======================================================================================================================= + ##### Initialization and de-initialization functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to initialize and deinitialize the I3Cx peripheral: + + (+) Users must implement HAL_I3C_MspInit() function in which they configure all related peripherals + resources (APB and Kernel CLOCK, GPIO, DMA, IT and NVIC). + + (+) Call the function HAL_I3C_Init() to configure the bus characteristic depends on the device mode + with the selected configuration below: + + (++) Controller mode, Serial source clock wave form configuration: + (+++) SCL push pull low duration + (+++) SCL I3C high duration + (+++) SCL open drain low duration + (+++) SCL I2C high duration + + (++) Controller mode, Bus timing configuration: + (+++) SDA hold time + (+++) Wait time + (+++) Bus free duration + (+++) Bus available duration + + (++) Target mode, Bus timing configuration: + (+++) Bus available duration + + (+) Call the function HAL_I3C_DeInit() to restore the default configuration of the selected I3Cx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the I3C instance by activating the low-level hardware and configuring the bus + * characteristic according to the specified parameters in the I3C_InitTypeDef. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Init(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t waveform_value; + uint32_t timing_value; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state */ + if (hi3c->State == HAL_I3C_STATE_RESET) + { +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Init the I3C Callback settings */ + /* Legacy weak CtrlTxCpltCallback */ + hi3c->CtrlTxCpltCallback = HAL_I3C_CtrlTxCpltCallback; + /* Legacy weak CtrlRxCpltCallback */ + hi3c->CtrlRxCpltCallback = HAL_I3C_CtrlRxCpltCallback; + /* Legacy weak CtrlMultipleXferCpltCallback */ + hi3c->CtrlMultipleXferCpltCallback = HAL_I3C_CtrlMultipleXferCpltCallback; + /* Legacy weak CtrlDAACpltCallback */ + hi3c->CtrlDAACpltCallback = HAL_I3C_CtrlDAACpltCallback; + /* Legacy weak TgtReqDynamicAddrCallback */ + hi3c->TgtReqDynamicAddrCallback = HAL_I3C_TgtReqDynamicAddrCallback; + /* Legacy weak TgtTxCpltCallback */ + hi3c->TgtTxCpltCallback = HAL_I3C_TgtTxCpltCallback; + /* Legacy weak TgtRxCpltCallback */ + hi3c->TgtRxCpltCallback = HAL_I3C_TgtRxCpltCallback; + /* Legacy weak TgtHotJoinCallback */ + hi3c->TgtHotJoinCallback = HAL_I3C_TgtHotJoinCallback; + /* Legacy weak NotifyCallback */ + hi3c->NotifyCallback = HAL_I3C_NotifyCallback; + /* Legacy weak ErrorCallback */ + hi3c->ErrorCallback = HAL_I3C_ErrorCallback; + /* Legacy weak AbortCpltCallback */ + hi3c->AbortCpltCallback = HAL_I3C_AbortCpltCallback; + + /* Check on the MSP init callback */ + if (hi3c->MspInitCallback == NULL) + { + /* Legacy weak MspInit */ + hi3c->MspInitCallback = HAL_I3C_MspInit; + } + + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + hi3c->MspInitCallback(hi3c); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I3C_MspInit(hi3c); + +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ + } + + /* Update the I3C state to busy */ + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(hi3c->Instance); + + /* Check on the I3C mode: initialization depends on the mode */ + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Check the parameters */ + assert_param(IS_I3C_SDAHOLDTIME_VALUE(hi3c->Init.CtrlBusCharacteristic.SDAHoldTime)); + assert_param(IS_I3C_WAITTIME_VALUE(hi3c->Init.CtrlBusCharacteristic.WaitTime)); + + /* Set Controller mode */ + LL_I3C_SetMode(hi3c->Instance, LL_I3C_MODE_CONTROLLER); + + /*----------------- SCL signal waveform configuration : I3C timing register 0 (I3C_TIMINGR0) ------------------ */ + /* Set the controller SCL waveform */ + waveform_value = ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLPPLowDuration | + ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLI3CHighDuration << I3C_TIMINGR0_SCLH_I3C_Pos) | + ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLODLowDuration << I3C_TIMINGR0_SCLL_OD_Pos) | + ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SCLI2CHighDuration << I3C_TIMINGR0_SCLH_I2C_Pos)); + + LL_I3C_ConfigClockWaveForm(hi3c->Instance, waveform_value); + + /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------ */ + /* Set SDA hold time, activity state, bus free duration and bus available duration */ + timing_value = ((uint32_t)hi3c->Init.CtrlBusCharacteristic.SDAHoldTime | + (uint32_t)hi3c->Init.CtrlBusCharacteristic.WaitTime | + ((uint32_t)hi3c->Init.CtrlBusCharacteristic.BusFreeDuration << I3C_TIMINGR1_FREE_Pos) | + (uint32_t)hi3c->Init.CtrlBusCharacteristic.BusIdleDuration); + + LL_I3C_SetCtrlBusCharacteristic(hi3c->Instance, timing_value); + } + else + { + /* Set target mode */ + LL_I3C_SetMode(hi3c->Instance, LL_I3C_MODE_TARGET); + + /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------ */ + /* Set the number of kernel clocks cycles for the bus available condition time */ + LL_I3C_SetAvalTiming(hi3c->Instance, hi3c->Init.TgtBusCharacteristic.BusAvailableDuration); + } + + /* Enable the selected I3C peripheral */ + LL_I3C_Enable(hi3c->Instance); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Update I3C state */ + hi3c->State = HAL_I3C_STATE_READY; + hi3c->PreviousState = HAL_I3C_STATE_READY; + } + + return status; +} + +/** + * @brief DeInitialize the I3C peripheral. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_DeInit(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + + /* Update the I3C state to busy */ + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Check on the MSP init callback */ + if (hi3c->MspDeInitCallback == NULL) + { + /* Legacy weak MspDeInit */ + hi3c->MspDeInitCallback = HAL_I3C_MspDeInit; + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hi3c->MspDeInitCallback(hi3c); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_I3C_MspDeInit(hi3c); + +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ + + /* Update the I3C Error code, state and mode */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_RESET; + hi3c->PreviousState = HAL_I3C_STATE_RESET; + hi3c->Mode = HAL_I3C_MODE_NONE; + } + + return status; +} + +/** + * @brief Initialize the I3C MSP. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_MspInit(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I3C_MspInit could be implemented in the user file */ +} + +/** + * @brief DeInitialize the I3C MSP. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_MspDeInit(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_I3C_MspDeInit could be implemented in the user file */ +} +/** + * @} + */ + +/** @defgroup I3C_Exported_Functions_Group2 Interrupt and callback functions. + * @brief I3C interrupt and callback functions. + * +@verbatim + ======================================================================================================================= + ##### Interrupt and callback functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to manage callbacks and interrupts request: + + (+) Register/Unregister callback function: + (++) Call the function HAL_I3C_RegisterCallback() to register an I3C user callback. + (++) Call the function HAL_I3C_RegisterNotifyCallback() to register an I3C user notification callback. + (++) Call the function HAL_I3C_RegisterDynamicAddrCallback() to register an I3C user address callback. + (++) Call the function HAL_I3C_RegisterHotJoinCallback() to register an I3C user hot join callback. + (++) Call the function HAL_I3C_UnRegisterCallback() to unregister an I3C user callback. + + (+) Notification management function: + (++) Call the function HAL_I3C_ActivateNotification() to activate the I3C notifications. + (++) Call the function HAL_I3C_DeactivateNotification() to deactivate the I3C notifications. + + (+) Controller callback functions: + (++) Users must implement HAL_I3C_CtrlTxCpltCallback() function when the transmission of private data or + Tx CCC transfer is completed. + (++) Users must implement HAL_I3C_CtrlRxCpltCallback() function when the reception of private data or + Rx CCC transfer is completed. + (++) Users must implement HAL_I3C_CtrlMultipleXferCpltCallback() function when the multiple + transfer of CCC, I3C private or I2C transfer is completed. + (++) Users must implement HAL_I3C_CtrlDAACpltCallback() function when Dynamic Address Assignment + procedure is completed. + (++) Users must implement HAL_I3C_TgtReqDynamicAddrCallback() function in the controller application + when a target sent its payload to the controller during Dynamic Address Assignment procedure. + + (+) Target callback functions: + (++) Users must implement HAL_I3C_TgtTxCpltCallback() function when the transmission of private + data is completed. + (++) Users must implement HAL_I3C_TgtRxCpltCallback() function when the reception of private + data is completed. + (++) Users must implement HAL_I3C_TgtHotJoinCallback() function when a target hot join process + is completed. + + (+) Common callback functions: + (++) Users must implement HAL_I3C_NotifyCallback() function when the device receives + an asynchronous event like IBI, a Hot-join, CCC command for target... + (++) Users must implement HAL_I3C_AbortCpltCallback() function when an abort process is completed. + (++) Users must implement HAL_I3C_ErrorCallback() function when an error is occurred. + + (+) Interrupt and event function: + (++) Call the function HAL_I3C_ER_IRQHandler() in the ISR file to handle I3C error interrupts request. + (++) Call the function HAL_I3C_EV_IRQHandler() in the ISR file to handle I3C event interrupts request. +@endverbatim + * @{ + */ + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User I3C Callback to be used instead of the weak predefined callback. + * @note The HAL_I3C_RegisterCallback() may be called before HAL_I3C_Init() in HAL_I3C_STATE_RESET + * to register callbacks for HAL_I3C_MSPINIT_CB_ID and HAL_I3C_MSPDEINIT_CB_ID + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param callbackID : [IN] ID of the callback to be registered. + * This parameter can be one of the following values: + * @arg @ref HAL_I3C_CTRL_TX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_CTRL_RX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID + * @arg @ref HAL_I3C_CTRL_DAA_COMPLETE_CB_ID + * @arg @ref HAL_I3C_TGT_TX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_TGT_RX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_ERROR_CB_ID + * @arg @ref HAL_I3C_ABORT_CB_ID + * @arg @ref HAL_I3C_MSPINIT_CB_ID + * @arg @ref HAL_I3C_MSPDEINIT_CB_ID + * @param pCallback : [IN] Pointer to the Callback function. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_RegisterCallback(I3C_HandleTypeDef *hi3c, + HAL_I3C_CallbackIDTypeDef callbackID, + pI3C_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the user callback allocation */ + if (pCallback == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else if (HAL_I3C_STATE_READY == hi3c->State) + { + switch (callbackID) + { + case HAL_I3C_CTRL_TX_COMPLETE_CB_ID : + hi3c->CtrlTxCpltCallback = pCallback; + break; + + case HAL_I3C_CTRL_RX_COMPLETE_CB_ID : + hi3c->CtrlRxCpltCallback = pCallback; + break; + + case HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID : + hi3c->CtrlMultipleXferCpltCallback = pCallback; + break; + + case HAL_I3C_CTRL_DAA_COMPLETE_CB_ID : + hi3c->CtrlDAACpltCallback = pCallback; + break; + + case HAL_I3C_TGT_TX_COMPLETE_CB_ID : + hi3c->TgtTxCpltCallback = pCallback; + break; + + case HAL_I3C_TGT_RX_COMPLETE_CB_ID : + hi3c->TgtRxCpltCallback = pCallback; + break; + + case HAL_I3C_ERROR_CB_ID : + hi3c->ErrorCallback = pCallback; + break; + + case HAL_I3C_ABORT_CB_ID : + hi3c->AbortCpltCallback = pCallback; + break; + + case HAL_I3C_MSPINIT_CB_ID : + hi3c->MspInitCallback = pCallback; + break; + + case HAL_I3C_MSPDEINIT_CB_ID : + hi3c->MspDeInitCallback = pCallback; + break; + + default : + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (HAL_I3C_STATE_RESET == hi3c->State) + { + switch (callbackID) + { + case HAL_I3C_MSPINIT_CB_ID : + hi3c->MspInitCallback = pCallback; + break; + + case HAL_I3C_MSPDEINIT_CB_ID : + hi3c->MspDeInitCallback = pCallback; + break; + + default : + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Register a User I3C Notify Callback to be used instead of the weak predefined callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pNotifyCallback : [IN] Pointer to the Callback function. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_RegisterNotifyCallback(I3C_HandleTypeDef *hi3c, pI3C_NotifyCallbackTypeDef pNotifyCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the user callback allocation */ + if (pNotifyCallback == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else if (HAL_I3C_STATE_READY == hi3c->State) + { + hi3c->NotifyCallback = pNotifyCallback; + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Register a User I3C dynamic address Callback to be used instead of the weak predefined callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pTgtReqAddrCallback : [IN] Pointer to the Callback function. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_RegisterTgtReqDynamicAddrCallback(I3C_HandleTypeDef *hi3c, + pI3C_TgtReqDynamicAddrCallbackTypeDef pTgtReqAddrCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the user callback allocation */ + if (pTgtReqAddrCallback == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else if (HAL_I3C_STATE_READY == hi3c->State) + { + hi3c->TgtReqDynamicAddrCallback = pTgtReqAddrCallback; + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Register a User I3C hot join Callback to be used instead of the weak predefined callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pTgtHotJoinCallback : [IN] Pointer to the Callback function. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_RegisterTgtHotJoinCallback(I3C_HandleTypeDef *hi3c, + pI3C_TgtHotJoinCallbackTypeDef pTgtHotJoinCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the user callback allocation */ + if (pTgtHotJoinCallback == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else if (HAL_I3C_STATE_READY == hi3c->State) + { + hi3c->TgtHotJoinCallback = pTgtHotJoinCallback; + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Unregister a user I3C Callback. + * The I3C callback is redirected to the weak predefined callback + * @note The HAL_I3C_UnRegisterCallback() may be called before HAL_I3C_Init() in HAL_I3C_STATE_RESET + * to un-register callbacks for HAL_I3C_MSPINIT_CB_ID and HAL_I3C_MSPDEINIT_CB_ID + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param callbackID : [IN] ID of the callback to be unregistered. + * This parameter can be one of the following values: + * @arg @ref HAL_I3C_CTRL_TX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_CTRL_RX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID + * @arg @ref HAL_I3C_CTRL_DAA_COMPLETE_CB_ID + * @arg @ref HAL_I3C_TGT_REQ_DYNAMIC_ADDR_CB_ID + * @arg @ref HAL_I3C_TGT_TX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_TGT_RX_COMPLETE_CB_ID + * @arg @ref HAL_I3C_TGT_HOTJOIN_CB_ID + * @arg @ref HAL_I3C_NOTIFY_CB_ID + * @arg @ref HAL_I3C_ERROR_CB_ID + * @arg @ref HAL_I3C_ABORT_CB_ID + * @arg @ref HAL_I3C_MSPINIT_CB_ID + * @arg @ref HAL_I3C_MSPDEINIT_CB_ID + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_UnRegisterCallback(I3C_HandleTypeDef *hi3c, HAL_I3C_CallbackIDTypeDef callbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + if (HAL_I3C_STATE_READY == hi3c->State) + { + switch (callbackID) + { + case HAL_I3C_CTRL_TX_COMPLETE_CB_ID : + /* Legacy weak CtrlTxCpltCallback */ + hi3c->CtrlTxCpltCallback = HAL_I3C_CtrlTxCpltCallback; + break; + + case HAL_I3C_CTRL_RX_COMPLETE_CB_ID : + /* Legacy weak CtrlRxCpltCallback */ + hi3c->CtrlRxCpltCallback = HAL_I3C_CtrlRxCpltCallback; + break; + + case HAL_I3C_CTRL_MULTIPLE_XFER_COMPLETE_CB_ID : + /* Legacy weak CtrlMultipleXferCpltCallback */ + hi3c->CtrlMultipleXferCpltCallback = HAL_I3C_CtrlMultipleXferCpltCallback; + break; + + case HAL_I3C_CTRL_DAA_COMPLETE_CB_ID : + /* Legacy weak CtrlDAACpltCallback */ + hi3c->CtrlDAACpltCallback = HAL_I3C_CtrlDAACpltCallback; + break; + + case HAL_I3C_TGT_REQ_DYNAMIC_ADDR_CB_ID : + /*Legacy weak TgtReqDynamicAddrCallback */ + hi3c->TgtReqDynamicAddrCallback = HAL_I3C_TgtReqDynamicAddrCallback; + break; + + case HAL_I3C_TGT_TX_COMPLETE_CB_ID : + /* Legacy weak TgtTxCpltCallback */ + hi3c->TgtTxCpltCallback = HAL_I3C_TgtTxCpltCallback; + break; + + case HAL_I3C_TGT_RX_COMPLETE_CB_ID : + /* Legacy weak TgtRxCpltCallback */ + hi3c->TgtRxCpltCallback = HAL_I3C_TgtRxCpltCallback; + break; + + case HAL_I3C_TGT_HOTJOIN_CB_ID : + /* Legacy weak TgtHotJoinCallback */ + hi3c->TgtHotJoinCallback = HAL_I3C_TgtHotJoinCallback; + break; + + case HAL_I3C_NOTIFY_CB_ID : + /* Legacy weak NotifyCallback */ + hi3c->NotifyCallback = HAL_I3C_NotifyCallback; + break; + + case HAL_I3C_ERROR_CB_ID : + /* Legacy weak ErrorCallback */ + hi3c->ErrorCallback = HAL_I3C_ErrorCallback; + break; + + case HAL_I3C_ABORT_CB_ID : + /* Legacy weak AbortCpltCallback */ + hi3c->AbortCpltCallback = HAL_I3C_AbortCpltCallback; + break; + + case HAL_I3C_MSPINIT_CB_ID : + /* Legacy weak MspInit */ + hi3c->MspInitCallback = HAL_I3C_MspInit; + break; + + case HAL_I3C_MSPDEINIT_CB_ID : + /* Legacy weak MspDeInit */ + hi3c->MspDeInitCallback = HAL_I3C_MspDeInit; + break; + + default : + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (HAL_I3C_STATE_RESET == hi3c->State) + { + switch (callbackID) + { + case HAL_I3C_MSPINIT_CB_ID : + /* Legacy weak MspInit */ + hi3c->MspInitCallback = HAL_I3C_MspInit; + break; + + case HAL_I3C_MSPDEINIT_CB_ID : + /* Legacy weak MspDeInit */ + hi3c->MspDeInitCallback = HAL_I3C_MspDeInit; + break; + + default : + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + return status; +} +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + +/** + * @brief This function permits to activate the I3C notifications. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pXferData : [IN/OUT] Pointer to an I3C_XferTypeDef structure that contains the reception buffer to + * retrieve data during broadcast CCC DEFTGTS and DEFGRPA when Target mode only. + * @param interruptMask : [IN] Parameter indicates which interrupts will be enabled. + * This parameter can be any combination of @arg I3C_TARGET_INTERRUPT when + * the I3C is in target mode or a combination of @arg I3C_CONTROLLER_INTERRUPT + * when it is in controller mode. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_ActivateNotification(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData, + uint32_t interruptMask) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + assert_param(IS_I3C_INTERRUPTMASK(hi3c->Mode, interruptMask)); + + /* Check the I3C state and mode */ + if ((hi3c->State == HAL_I3C_STATE_RESET) || + ((hi3c->Mode != HAL_I3C_MODE_CONTROLLER) && (hi3c->Mode != HAL_I3C_MODE_TARGET))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Check the I3C mode */ + else if ((hi3c->Mode == HAL_I3C_MODE_TARGET) && + ((interruptMask & (HAL_I3C_IT_DEFIE | HAL_I3C_IT_GRPIE)) != 0U) && + (pXferData == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Check the I3C mode */ + if (hi3c->Mode == HAL_I3C_MODE_TARGET) + { + if ((interruptMask & (HAL_I3C_IT_DEFIE | HAL_I3C_IT_GRPIE)) != 0U) + { + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + } + /* Store the target event treatment function */ + hi3c->XferISR = I3C_Tgt_Event_ISR; + } + else + { + /* Store the controller event treatment function */ + hi3c->XferISR = I3C_Ctrl_Event_ISR; + } + + /* Update handle parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_LISTEN; + hi3c->PreviousState = HAL_I3C_STATE_LISTEN; + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + /* Enable selected notifications */ + I3C_Enable_IRQ(hi3c, (interruptMask | I3C_XFER_LISTEN_IT)); + } + } + + return status; +} + +/** + * @brief This function permits to deactivate the I3C notifications. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param interruptMask : [IN] Parameter indicates which interrupts will be disabled. + * This parameter can be any combination of @arg I3C_TARGET_INTERRUPT when + * the I3C is in target mode or a combination of @arg I3C_CONTROLLER_INTERRUPT + * when it is in controller mode. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_DeactivateNotification(I3C_HandleTypeDef *hi3c, uint32_t interruptMask) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance parameter */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + + /* Check on the State */ + if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Disable selected notifications */ + I3C_Disable_IRQ(hi3c, (interruptMask | I3C_XFER_LISTEN_IT)); + + if (READ_REG(hi3c->Instance->IER) == 0U) + { + /* Update the XferISR pointer */ + hi3c->XferISR = NULL; + + /* Update I3C state */ + hi3c->State = HAL_I3C_STATE_READY; + hi3c->PreviousState = HAL_I3C_STATE_READY; + } + } + } + + return status; +} + +/** + * @brief Controller Transmission Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_CtrlTxCpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_CtrlTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Controller Reception Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_CtrlRxCpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_CtrlRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Controller multiple Direct CCC Command, I3C private or I2C transfer Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_CtrlMultipleXferCpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_CtrlMultipleXferCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Controller dynamic address assignment Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_CtrlDAACpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_CtrlDAACpltCallback could be implemented in the user file + */ +} + +/** + * @brief Target Request Dynamic Address callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param targetPayload : [IN] Parameter indicates the target payload. + * @retval None + */ +__weak void HAL_I3C_TgtReqDynamicAddrCallback(I3C_HandleTypeDef *hi3c, uint64_t targetPayload) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + UNUSED(targetPayload); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_TgtReqDynamicAddrCallback could be implemented in the user file + */ +} + +/** + * @brief Target Transmission Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_TgtTxCpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_TgtTxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Target Reception Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_TgtRxCpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_TgtRxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Target Hot join process Complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param dynamicAddress : [IN] The returned dynamic address value after the hot join process. + * @retval None + */ +__weak void HAL_I3C_TgtHotJoinCallback(I3C_HandleTypeDef *hi3c, uint8_t dynamicAddress) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + UNUSED(dynamicAddress); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_TgtHotJoinCallback could be implemented in the user file + */ +} + +/** + * @brief Target/Controller Notification event callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param eventId : [IN] Parameter indicates which notification is signaled. + * It can be a combination value of @ref HAL_I3C_Notification_ID_definition. + * @retval None + */ +__weak void HAL_I3C_NotifyCallback(I3C_HandleTypeDef *hi3c, uint32_t eventId) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + UNUSED(eventId); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_NotifyCallback could be implemented in the user file + */ +} + +/** + * @brief Abort complete callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_AbortCpltCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Error callback. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +__weak void HAL_I3C_ErrorCallback(I3C_HandleTypeDef *hi3c) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hi3c); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I3C_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief This function handles I3C error interrupt request. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +void HAL_I3C_ER_IRQHandler(I3C_HandleTypeDef *hi3c) +{ + uint32_t it_flag = READ_REG(hi3c->Instance->EVR); + uint32_t it_source = READ_REG(hi3c->Instance->IER); + + /* Check on the error interrupt flag and source */ + if ((I3C_CHECK_FLAG(it_flag, HAL_I3C_FLAG_ERRF) != RESET) && + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_ERRIE) != RESET)) + { + /* Clear the error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + if (hi3c->State != HAL_I3C_STATE_ABORT) + { + /* Get error sources */ + I3C_GetErrorSources(hi3c); + } + + /* Errors treatment */ + I3C_ErrorTreatment(hi3c); + } +} + +/** + * @brief This function handles I3C event interrupt request. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval None + */ +void HAL_I3C_EV_IRQHandler(I3C_HandleTypeDef *hi3c) /* Derogation MISRAC2012-Rule-8.13 */ +{ + uint32_t it_flags = READ_REG(hi3c->Instance->EVR); + uint32_t it_sources = READ_REG(hi3c->Instance->IER); + + uint32_t it_masks = (uint32_t)(it_flags & it_sources); + + /* I3C events treatment */ + if (hi3c->XferISR != NULL) + { + hi3c->XferISR(hi3c, it_masks); + } +} +/** + * @} + */ + +/** @defgroup I3C_Exported_Functions_Group3 Configuration functions. + * @brief I3C configuration functions. + * +@verbatim + ======================================================================================================================= + ##### Configuration functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to configure the I3C instances. + + (+) Call the function HAL_I3C_Ctrl_BusCharacteristicConfig() to modify the controller Bus Characteristics + after initialize the bus through HAL_I3C_Init. + + (+) Call the function HAL_I3C_Tgt_BusCharacteristicConfig() to modify the target Bus Characteristics + after initialize the bus through HAL_I3C_Init. + + (+) Call the function HAL_I3C_SetConfigFifo() to set FIFOs configuration (enabled FIFOs and + threshold level) with the selected parameters in the configuration structure I3C_FifoConfTypeDef. + + (+) Call the function HAL_I3C_Ctrl_Config() to configure the I3C Controller instances with the selected + parameters in the configuration structure I3C_CtrlConfTypeDef. + This function is called only when mode is Controller. + + (+) Call the function HAL_I3C_Tgt_Config() to configure the I3C Target instances with the selected + parameters in the configuration structure I3C_TgtConfTypeDef. + This function is called only when mode is Target. + + (+) Call the function HAL_I3C_Ctrl_ConfigBusDevices() to configure Hardware device characteristics register + with Devices capabilities present on the Bus. + All different characteristics must be fill through structure I3C_DeviceConfTypeDef. + This function is called only when mode is Controller. + + (+) Call the function HAL_I3C_AddDescToFrame() to prepare the full transfer usecase in a transfer descriptor + which contained different buffer pointers and their associated size through I3C_XferTypeDef. + This function must be called before initiate any communication transfer. + (+) Call the function HAL_I3C_Ctrl_SetConfigResetPattern() to configure the insertion of the reset pattern + at the end of a Frame. + (+) Call the function HAL_I3C_Ctrl_GetConfigResetPattern() to get the current reset pattern configuration + + [..] + (@) Users must call all above functions after I3C initialization. + +@endverbatim + * @{ + */ + +/** + * @brief Configure the Controller Bus characterics. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pConfig : [IN] Pointer to an LL_I3C_CtrlBusConfTypeDef structure contains controller bus configuration. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_BusCharacteristicConfig(I3C_HandleTypeDef *hi3c, + const LL_I3C_CtrlBusConfTypeDef *pConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t waveform_value; + uint32_t timing_value; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check on user parameters */ + if (pConfig == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state and mode */ + else if ((hi3c->State != HAL_I3C_STATE_READY) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Check the parameters */ + assert_param(IS_I3C_SDAHOLDTIME_VALUE(pConfig->SDAHoldTime)); + assert_param(IS_I3C_WAITTIME_VALUE(pConfig->WaitTime)); + + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(hi3c->Instance); + + /*----------------- SCL signal waveform configuration : I3C timing register 0 (I3C_TIMINGR0) ------------------ */ + /* Set the controller SCL waveform */ + waveform_value = ((uint32_t)pConfig->SCLPPLowDuration | + ((uint32_t)pConfig->SCLI3CHighDuration << I3C_TIMINGR0_SCLH_I3C_Pos) | + ((uint32_t)pConfig->SCLODLowDuration << I3C_TIMINGR0_SCLL_OD_Pos) | + ((uint32_t)pConfig->SCLI2CHighDuration << I3C_TIMINGR0_SCLH_I2C_Pos)); + + LL_I3C_ConfigClockWaveForm(hi3c->Instance, waveform_value); + + /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------ */ + /* Set SDA hold time, activity state, bus free duration and bus available duration */ + timing_value = ((uint32_t)pConfig->SDAHoldTime | + (uint32_t)pConfig->WaitTime | + ((uint32_t)pConfig->BusFreeDuration << I3C_TIMINGR1_FREE_Pos) | + (uint32_t)pConfig->BusIdleDuration); + + LL_I3C_SetCtrlBusCharacteristic(hi3c->Instance, timing_value); + + /* Enable the selected I3C peripheral */ + LL_I3C_Enable(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Configure the target Bus characterics. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pConfig : [IN] Pointer to an LL_I3C_TgtBusConfTypeDef structure contains target bus configuration. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_BusCharacteristicConfig(I3C_HandleTypeDef *hi3c, + const LL_I3C_TgtBusConfTypeDef *pConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check on user parameters */ + if (pConfig == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state and mode */ + if ((hi3c->State != HAL_I3C_STATE_READY) || (hi3c->Mode != HAL_I3C_MODE_TARGET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(hi3c->Instance); + + /*------------------ Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ---------------------------- */ + /* Set the number of kernel clocks cycles for the bus available condition time */ + LL_I3C_SetAvalTiming(hi3c->Instance, pConfig->BusAvailableDuration); + + /* Enable the selected I3C peripheral */ + LL_I3C_Enable(hi3c->Instance); + } + } + } + + return status; +} + +/** + * @brief Set I3C FIFOs configuration. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pConfig : [IN] Pointer to an I3C_FifoConfTypeDef structure contains FIFOs configuration. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_SetConfigFifo(I3C_HandleTypeDef *hi3c, const I3C_FifoConfTypeDef *pConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t cfgr_value; + uint32_t cfgr_mask; + + /* Check the I3C handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check on user parameters */ + if (pConfig == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state */ + else if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check configuration parameters */ + assert_param(IS_I3C_TXFIFOTHRESHOLD_VALUE(pConfig->TxFifoThreshold)); + assert_param(IS_I3C_RXFIFOTHRESHOLD_VALUE(pConfig->RxFifoThreshold)); + + /* Set Tx and Rx Fifo threshold */ + cfgr_value = (pConfig->TxFifoThreshold | pConfig->RxFifoThreshold); + cfgr_mask = (I3C_CFGR_TXTHRES | I3C_CFGR_RXTHRES); + + /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Check configuration parameters */ + assert_param(IS_I3C_CONTROLFIFOSTATE_VALUE(pConfig->ControlFifo)); + assert_param(IS_I3C_STATUSFIFOSTATE_VALUE(pConfig->StatusFifo)); + + /* Set Control and Status Fifo states */ + cfgr_value |= (pConfig->StatusFifo | pConfig->ControlFifo); + cfgr_mask |= (I3C_CFGR_TMODE | I3C_CFGR_SMODE); + } + + /* Set configuration in the CFGR register */ + MODIFY_REG(hi3c->Instance->CFGR, cfgr_mask, cfgr_value); + } + } + + return status; +} + +/** + * @brief Set I3C controller configuration. + * @note This function is called only when the I3C instance is initialized as controller. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pConfig : [IN] Pointer to an I3C_CtrlConfTypeDef structure that contains controller configuration. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Config(I3C_HandleTypeDef *hi3c, const I3C_CtrlConfTypeDef *pConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t timing2_value; + uint32_t cfgr_value; + + /* Check the I3C handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check on user parameters */ + if (pConfig == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state and mode */ + else if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Check configuration parameters values */ + assert_param(IS_I3C_DYNAMICADDRESS_VALUE(pConfig->DynamicAddr)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HighKeeperSDA)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HotJoinAllowed)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->ACKStallState)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->CCCStallState)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->TxStallState)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->RxStallState)); + + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(hi3c->Instance); + + /* Calculate value to be written in timing register 2 */ + timing2_value = (((uint32_t)pConfig->StallTime << I3C_TIMINGR2_STALL_Pos) | + ((uint32_t)pConfig->ACKStallState << I3C_TIMINGR2_STALLA_Pos) | + ((uint32_t)pConfig->CCCStallState << I3C_TIMINGR2_STALLC_Pos) | + ((uint32_t)pConfig->TxStallState << I3C_TIMINGR2_STALLD_Pos) | + ((uint32_t)pConfig->RxStallState << I3C_TIMINGR2_STALLT_Pos)); + + /* Set value in timing 2 register */ + WRITE_REG(hi3c->Instance->TIMINGR2, timing2_value); + + /* Calculate value to be written in CFGR register */ + cfgr_value = (((uint32_t)pConfig->HighKeeperSDA << I3C_CFGR_HKSDAEN_Pos) | + ((uint32_t)pConfig->HotJoinAllowed << I3C_CFGR_HJACK_Pos)); + + /* Set hot join acknowledge and high keeper values */ + MODIFY_REG(hi3c->Instance->CFGR, I3C_CFGR_HKSDAEN | I3C_CFGR_HJACK, cfgr_value); + + /* Set dynamic address value */ + LL_I3C_SetOwnDynamicAddress(hi3c->Instance, pConfig->DynamicAddr); + + /* Validate the controller dynamic address */ + LL_I3C_EnableOwnDynAddress(hi3c->Instance); + + /* Enable the selected I3C peripheral */ + LL_I3C_Enable(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Set I3C target configuration. + * @note This function is called only when the I3C instance is initialized as target. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pConfig : [IN] Pointer to an I3C_TgtConfTypeDef structure that contains target configuration. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Config(I3C_HandleTypeDef *hi3c, const I3C_TgtConfTypeDef *pConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t getmxdsr_value; + uint32_t maxrlr_value; + uint32_t crccapr_value; + uint32_t bcr_value; + uint32_t devr0_value; + + /* Check the I3C handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check on user parameters */ + if (pConfig == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state and mode */ + else if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_TARGET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Check configuration parameters values */ + assert_param(IS_I3C_HANDOFFACTIVITYSTATE_VALUE(pConfig->HandOffActivityState)); + assert_param(IS_I3C_TSCOTIME_VALUE(pConfig->DataTurnAroundDuration)); + assert_param(IS_I3C_MAXSPEEDDATA_VALUE(pConfig->MaxDataSpeed)); + assert_param(IS_I3C_IBIPAYLOADSIZE_VALUE(pConfig->IBIPayloadSize)); + assert_param(IS_I3C_MIPIIDENTIFIER_VALUE(pConfig->MIPIIdentifier)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HandOffDelay)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->GroupAddrCapability)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->PendingReadMDB)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->IBIPayload)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->MaxSpeedLimitation)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->CtrlCapability)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->IBIRequest)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->CtrlRoleRequest)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pConfig->HotJoinRequest)); + + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(hi3c->Instance); + + /* Calculate value to be written in the GETMXDSR register */ + getmxdsr_value = (pConfig->HandOffActivityState | pConfig->MaxDataSpeed | pConfig->DataTurnAroundDuration | + ((uint32_t)pConfig->MaxReadTurnAround << I3C_GETMXDSR_RDTURN_Pos)); + + /* Set value in GETMXDSR register */ + WRITE_REG(hi3c->Instance->GETMXDSR, getmxdsr_value); + + /* Calculate value to be written in MAXRLR register */ + maxrlr_value = (pConfig->IBIPayloadSize | (pConfig->MaxReadDataSize & I3C_MAXRLR_MRL)); + + /* Set payload size and max read data size in MAXRLR register */ + WRITE_REG(hi3c->Instance->MAXRLR, maxrlr_value); + + /* Set max write data size in MAXWLR register */ + LL_I3C_SetMaxWriteLength(hi3c->Instance, pConfig->MaxWriteDataSize); + + /* Set MIPI identifier value in EPIDR register */ + LL_I3C_SetMIPIInstanceID(hi3c->Instance, pConfig->MIPIIdentifier); + + /* Set identifier value in DCR register */ + LL_I3C_SetDeviceCharacteristics(hi3c->Instance, pConfig->Identifier); + + /* Calculate value to be written in CRCCAPR register */ + crccapr_value = (((uint32_t)pConfig->HandOffDelay << I3C_CRCAPR_CAPDHOFF_Pos) | + ((uint32_t)pConfig->GroupAddrCapability << I3C_CRCAPR_CAPGRP_Pos)); + + /* Set hand off dealy and group address capability in CRCCAPR register */ + WRITE_REG(hi3c->Instance->CRCAPR, crccapr_value); + + /* Set pending read MDB notification value in GETCAPR register */ + LL_I3C_SetPendingReadMDB(hi3c->Instance, ((uint32_t)pConfig->PendingReadMDB << I3C_GETCAPR_CAPPEND_Pos)); + + /* Calculate value to be written in BCR register */ + bcr_value = (((uint32_t)pConfig->MaxSpeedLimitation << I3C_BCR_BCR0_Pos) | + ((uint32_t)pConfig->IBIPayload << I3C_BCR_BCR2_Pos) | + ((uint32_t)pConfig->CtrlCapability << I3C_BCR_BCR6_Pos)); + + /* Set control capability, IBI payload support and max speed limitation in BCR register */ + WRITE_REG(hi3c->Instance->BCR, bcr_value); + + /* Calculate value to be written in CFGR register */ + devr0_value = (((uint32_t)pConfig->IBIRequest << I3C_DEVR0_IBIEN_Pos) | + ((uint32_t)pConfig->CtrlRoleRequest << I3C_DEVR0_CREN_Pos) | + ((uint32_t)pConfig->HotJoinRequest << I3C_DEVR0_HJEN_Pos)); + + /* Set IBI request, control role request and hot join request in DEVR0 register */ + MODIFY_REG(hi3c->Instance->DEVR0, (I3C_DEVR0_HJEN | I3C_DEVR0_IBIEN | I3C_DEVR0_CREN), devr0_value); + + /* Enable the selected I3C peripheral */ + LL_I3C_Enable(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Set I3C bus devices configuration. + * @note This function is called only when the I3C instance is initialized as controller. + * This function can be called by the controller application to help the automatic treatment when target have + * capability of IBI and/or Control-Role. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pDesc : [IN] Pointer to an I3C_DeviceConfTypeDef descriptor that contains the bus devices + * configurations. + * @param nbDevice : [IN] Value specifies the number of devices to be treated. + * This parameter must be a number between Min_Data=1U and Max_Data=4U. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_ConfigBusDevices(I3C_HandleTypeDef *hi3c, + const I3C_DeviceConfTypeDef *pDesc, + uint8_t nbDevice) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t write_value; + + /* Check the I3C handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check on user parameters */ + if (pDesc == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state and mode */ + else if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + assert_param(IS_I3C_DEVICE_VALUE(nbDevice)); + + /* Loop on the nbDevice to be treated */ + for (uint32_t index = 0U; index < nbDevice; index++) + { + /* Check configuration parameters values */ + assert_param(IS_I3C_DEVICE_VALUE(pDesc[index].DeviceIndex)); + assert_param(IS_I3C_DYNAMICADDRESS_VALUE(pDesc[index].TargetDynamicAddr)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].IBIAck)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].CtrlRoleReqAck)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].CtrlStopTransfer)); + assert_param(IS_I3C_FUNCTIONALSTATE_VALUE(pDesc[index].IBIPayload)); + + /* Set value to be written */ + write_value = (((uint32_t)pDesc[index].TargetDynamicAddr << I3C_DEVRX_DA_Pos) | + ((uint32_t)pDesc[index].IBIAck << I3C_DEVRX_IBIACK_Pos) | + ((uint32_t)pDesc[index].CtrlRoleReqAck << I3C_DEVRX_CRACK_Pos) | + ((uint32_t)pDesc[index].CtrlStopTransfer << I3C_DEVRX_SUSP_Pos) | + ((uint32_t)pDesc[index].IBIPayload << I3C_DEVRX_IBIDEN_Pos)); + + /* Write configuration in the DEVRx register */ + WRITE_REG(hi3c->Instance->DEVRX[(pDesc[index].DeviceIndex - 1U)], write_value); + } + } + } + + return status; +} + +/** + * @brief Add Private or CCC descriptor in the user data transfer descriptor. + * @note This function must be called before initiate any communication transfer. This function help the preparation + * of the full transfer usecase in a transfer descriptor which contained different buffer pointers + * and their associated size through I3C_XferTypeDef. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pCCCDesc : [IN] Pointer to an I3C_CCCTypeDef structure that contains the CCC descriptor information. + * @param pPrivateDesc : [IN] Pointer to an I3C_PrivateTypeDef structure that contains the transfer descriptor. + * @param pXferData : [IN/OUT] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * @param nbFrame : [IN] The number of CCC commands or the number of device to treat. + * @param option : [IN] Value indicates the transfer option. It can be one value of @ref I3C_OPTION_DEFINITION + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_AddDescToFrame(I3C_HandleTypeDef *hi3c, + const I3C_CCCTypeDef *pCCCDesc, + const I3C_PrivateTypeDef *pPrivateDesc, + I3C_XferTypeDef *pXferData, + uint8_t nbFrame, + uint32_t option) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->pCCCDesc = pCCCDesc; + hi3c->pPrivateDesc = pPrivateDesc; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = 0; + hi3c->TxXferCount = 0; + + /* Prepare Direction, and Check on user parameters */ + if (((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_CCC) || + ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_DIRECT)) + { + /* Check on user parameters */ + if ((pCCCDesc == NULL) || + (pXferData == NULL) || + (nbFrame < 1U) || + (((option & (I3C_OPERATION_TYPE_MASK | I3C_DEFINE_BYTE_MASK)) == \ + (LL_I3C_CONTROLLER_MTYPE_DIRECT | I3C_DEFINE_BYTE_MASK)) && (pCCCDesc->CCCBuf.Size == 0U))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + } + else + { + /* Check on user parameters */ + if ((pPrivateDesc == NULL) || (pXferData == NULL) || (nbFrame <= 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* check on the State */ + if ((handle_state == HAL_I3C_STATE_READY) || (handle_state == HAL_I3C_STATE_LISTEN)) + { + /* I3C control buffer prior preparation */ + if (I3C_ControlBuffer_PriorPreparation(hi3c, nbFrame, option) != HAL_OK) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + + /* I3C Tx Buffer prior preparation, set and check RxCount */ + if (I3C_Xfer_PriorPreparation(hi3c, nbFrame, option) != HAL_OK) + { + status = HAL_ERROR; + } + } + else + { + status = HAL_BUSY; + } + } + } + + return status; +} + +/** + * @brief Set the configuration of the inserted reset pattern at the end of a Frame. + * @note When the transfer descriptor contains multiple frames with RESTART option, the reset pattern at the end of + * RSTACT CCC frame is not possible. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains + * the configuration information for the specified I3C. + * @param resetPattern : [IN] Specifies the reset pattern configuration. + * It can be a value of @ref I3C_RESET_PATTERN + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_SetConfigResetPattern(I3C_HandleTypeDef *hi3c, uint32_t resetPattern) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + assert_param(IS_I3C_RESET_PATTERN(resetPattern)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + hi3c->State = HAL_I3C_STATE_BUSY; + + if (resetPattern == HAL_I3C_RESET_PATTERN_ENABLE) + { + LL_I3C_EnableResetPattern(hi3c->Instance); + } + else + { + LL_I3C_DisableResetPattern(hi3c->Instance); + } + + /* At the end of process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Get the configuration of the inserted reset pattern at the end of a Frame. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains + * the configuration information for the specified I3C. + * @param pResetPattern : [OUT] Pointer to the current reset pattern configuration. + * It can be a value of @ref I3C_RESET_PATTERN + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_GetConfigResetPattern(I3C_HandleTypeDef *hi3c, uint32_t *pResetPattern) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + /* Check on user parameters */ + else if (pResetPattern == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check if the reset pattern configuration is enabled */ + if (LL_I3C_IsEnabledResetPattern(hi3c->Instance) == 1U) + { + *pResetPattern = HAL_I3C_RESET_PATTERN_ENABLE; + } + else + { + *pResetPattern = HAL_I3C_RESET_PATTERN_DISABLE; + } + } + + return status; +} + +/** + * @} + */ + +/** @defgroup I3C_Exported_Functions_Group4 FIFO Management functions. + * @brief I3C FIFO management functions. + * +@verbatim + ======================================================================================================================= + ##### FIFO Management functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to manage I3C FIFOs. + + (+) Call the function HAL_I3C_FlushAllFifo() to flush the content of all used FIFOs (Control, Status, + Tx and Rx FIFO). + (+) Call the function HAL_I3C_FlushTxFifo() to flush only the content of Tx FIFO. + (+) Call the function HAL_I3C_FlushRxFifo() to flush only the content of Rx FIFO. + (+) Call the function HAL_I3C_FlushControlFifo() to flush only the content of Control FIFO. + This function is called only when mode is controller. + (+) Call the function HAL_I3C_FlushStatusFifo() to flush only the content of Status FIFO. + This function is called only when mode is controller. + (+) Call the function HAL_I3C_ClearConfigFifo() to clear the FIFOs configuration and set it to default values. + (+) Call the function HAL_I3C_GetConfigFifo() to get the current FIFOs configuration (enabled FIFOs and + threshold level). + + (+) Users must not call all above functions before I3C initialization. + + (+) Users should call Flush APIs after an end of process, before starting a transfer or in case of bus + failure and error detection. + +@endverbatim + * @{ + */ + +/** + * @brief Flush all I3C FIFOs content. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_FlushAllFifo(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t cfgr_value; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state */ + if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Flush the content of Tx and Rx Fifo */ + cfgr_value = (I3C_CFGR_TXFLUSH | I3C_CFGR_RXFLUSH); + + /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Flush the content of Control and Status Fifo */ + cfgr_value = (I3C_CFGR_SFLUSH | I3C_CFGR_CFLUSH); + } + + /* Set configuration in the CFGR register */ + MODIFY_REG(hi3c->Instance->CFGR, cfgr_value, cfgr_value); + } + } + + return status; +} + +/** + * @brief Flush I3C Tx FIFO content. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_FlushTxFifo(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state */ + if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Flush the content of Tx Fifo */ + LL_I3C_RequestTxFIFOFlush(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Flush I3C Rx FIFO content. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_FlushRxFifo(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state */ + if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Flush the content of Rx Fifo */ + LL_I3C_RequestRxFIFOFlush(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Flush I3C control FIFO content. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_FlushControlFifo(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state and mode */ + if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Flush the content of Control Fifo */ + LL_I3C_RequestControlFIFOFlush(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Flush I3C status FIFO content. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_FlushStatusFifo(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state and mode */ + if ((hi3c->State == HAL_I3C_STATE_RESET) || (hi3c->Mode != HAL_I3C_MODE_CONTROLLER)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Flush the content of Control Fifo */ + LL_I3C_RequestStatusFIFOFlush(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Clear I3C FIFOs configuration and set it to default values. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_ClearConfigFifo(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t cfgr_value; + uint32_t cfgr_mask; + + /* Check the I3C handle allocation */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check the I3C state */ + if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Clear Tx Fifo and Rx Fifo threshold and set it to default value */ + cfgr_value = (LL_I3C_TXFIFO_THRESHOLD_1_4 | LL_I3C_RXFIFO_THRESHOLD_1_4); + cfgr_mask = (I3C_CFGR_TXTHRES | I3C_CFGR_RXTHRES); + + /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Disable the status and Control Fifo state */ + cfgr_value |= (HAL_I3C_STATUSFIFO_DISABLE | HAL_I3C_CONTROLFIFO_DISABLE); + cfgr_mask |= (I3C_CFGR_TMODE | I3C_CFGR_SMODE); + } + + /* Set configuration in the CFGR register */ + MODIFY_REG(hi3c->Instance->CFGR, cfgr_mask, cfgr_value); + } + } + + return status; +} + +/** + * @brief Get I3C FIFOs current configuration. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pConfig : [IN/OUT] Pointer to an I3C_FifoConfTypeDef structure that returns current FIFOs configuration. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_GetConfigFifo(I3C_HandleTypeDef *hi3c, I3C_FifoConfTypeDef *pConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the I3C handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Check on user parameters */ + if (pConfig == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state */ + else if (hi3c->State == HAL_I3C_STATE_RESET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Get Tx Fifo threshold */ + pConfig->TxFifoThreshold = LL_I3C_GetTxFIFOThreshold(hi3c->Instance); + + /* Get Rx Fifo threshold */ + pConfig->RxFifoThreshold = LL_I3C_GetRxFIFOThreshold(hi3c->Instance); + + /* Get the Control Fifo state */ + pConfig->ControlFifo = (uint32_t)(LL_I3C_IsEnabledControlFIFO(hi3c->Instance) << I3C_CFGR_TMODE_Pos); + + /* Get the status Fifo state */ + pConfig->StatusFifo = (uint32_t)(LL_I3C_IsEnabledStatusFIFO(hi3c->Instance) << I3C_CFGR_SMODE_Pos); + } + } + + return status; +} +/** + * @} + */ + +/** @defgroup I3C_Exported_Functions_Group5 Controller operational functions. + * @brief I3C controller operational functions. + * +@verbatim + ======================================================================================================================= + ##### Controller operational functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to manage controller I3C operation. + + (+) Call the function HAL_I3C_Ctrl_TransmitCCC() to transmit direct write or a broadcast + CCC command in polling mode. + (+) Call the function HAL_I3C_Ctrl_TransmitCCC_IT() to transmit direct write or a broadcast + CCC command in interrupt mode. + (+) Call the function HAL_I3C_Ctrl_TransmitCCC_DMA() to transmit direct write or a broadcast + CCC command in DMA mode. + (+) Call the function HAL_I3C_Ctrl_ReceiveCCC() to transmit direct read CCC command in polling mode. + (+) Call the function HAL_I3C_Ctrl_ReceiveCCC_IT() to transmit direct read CCC command in interrupt mode. + (+) Call the function HAL_I3C_Ctrl_ReceiveCCC_DMA() to transmit direct read CCC command in DMA mode. + (+) Call the function HAL_I3C_Ctrl_Transmit() to transmit private data in polling mode. + (+) Call the function HAL_I3C_Ctrl_Transmit_IT() to transmit private data in interrupt mode. + (+) Call the function HAL_I3C_Ctrl_Transmit_DMA() to transmit private data in DMA mode. + (+) Call the function HAL_I3C_Ctrl_Receive() to receive private data in polling mode. + (+) Call the function HAL_I3C_Ctrl_Receive_IT() to receive private data in interrupt mode. + (+) Call the function HAL_I3C_Ctrl_Receive_DMA() to receive private data in DMA mode. + (+) Call the function HAL_I3C_Ctrl_MultipleTransfer_IT() to transfer I3C or I2C private data or CCC command + in multiple direction in interrupt mode. + (+) Call the function HAL_I3C_Ctrl_MultipleTransfer_DMA() to transfer I3C or I2C private data or CCC command + in multiple direction in DMA mode. + (+) Call the function HAL_I3C_Ctrl_DynAddrAssign() to send a broadcast ENTDAA CCC + command in polling mode. + (+) Call the function HAL_I3C_Ctrl_DynAddrAssign_IT() to send a broadcast ENTDAA CCC + command in interrupt mode. + (+) Call the function HAL_I3C_Ctrl_SetDynAddr() to set, asscociate the target dynamic address + during the Dynamic Address Assignment processus. + (+) Call the function HAL_I3C_Ctrl_IsDeviceI3C_Ready() to check if I3C target device is ready. + (+) Call the function HAL_I3C_Ctrl_IsDeviceI2C_Ready() to check if I2C target device is ready. + (+) Call the function HAL_I3C_Ctrl_GenerateArbitration to send arbitration + (message header {S + 0x7E + W + STOP}) in polling mode + + (+) Those functions are called only when mode is Controller. + +@endverbatim + * @{ + */ + +/** + * @brief Controller transmit direct write or a broadcast CCC command in polling mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_TransmitCCC(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData, + uint32_t timeout) +{ + uint32_t tickstart; + uint32_t exit_condition; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + /* Update returned status value */ + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + hi3c->pXferData = pXferData; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check on control FIFO enable/disable state */ + if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) + { + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Decrement remaining control buffer data counter */ + hi3c->ControlXferCount--; + + /* Initiate a start condition by writing in the CR register */ + WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); + + /* Increment Buffer pointer */ + hi3c->pXferData->CtrlBuf.pBuffer++; + } + + /* Do while until FC (Frame Complete) is set or timeout */ + do + { + /* Check if hardware asks for control data */ + if (hi3c->ControlXferCount > 0U) + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + } + + /* Check if hardware asks for Tx data */ + if (hi3c->TxXferCount > 0U) + { + /* Call transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + } + + /* Check for the timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + break; + } + } + + if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + } while ((exit_condition == 0U) || + ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update returned status value */ + status = HAL_ERROR; + } + + /* At the end of Tx process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Controller transmit direct write or a broadcast CCC command in interrupt mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_TransmitCCC_IT(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + if (handle_state == HAL_I3C_STATE_LISTEN) + { + hi3c->XferISR = I3C_Ctrl_Tx_Listen_Event_ISR; + } + else + { + hi3c->XferISR = I3C_Ctrl_Tx_ISR; + } + + hi3c->pXferData = pXferData; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Controller transmit direct write or a broadcast CCC command in DMA mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_TransmitCCC_DMA(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_StatusTypeDef control_dma_status; + HAL_StatusTypeDef tx_dma_status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t size_align_word; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmatx and hdmacr handle */ + else if ((hi3c->hdmatx == NULL) || (hi3c->hdmacr == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->XferISR = I3C_Ctrl_Tx_DMA_ISR; + hi3c->pXferData = pXferData; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + + /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmacr->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmacr->XferHalfCpltCallback = NULL; + hi3c->hdmacr->XferAbortCallback = NULL; + + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); + + /* Enable the control data DMA channel */ + control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, + (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); + + /*------------------------------------ I3C DMA channel for the Tx Data -----------------------------------------*/ + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmatx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmatx->XferHalfCpltCallback = NULL; + hi3c->hdmatx->XferAbortCallback = NULL; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->TxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); + } + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDWR, size_align_word); + } + } + + /* Check if DMA process is well started */ + if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK)) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->ControlXferCount = 0U; + + /* Enable control DMA Request */ + LL_I3C_EnableDMAReq_Control(hi3c->Instance); + + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Enable Tx data DMA Request */ + LL_I3C_EnableDMAReq_TX(hi3c->Instance); + } + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) + { + hi3c->hdmacr->XferCpltCallback = NULL; + hi3c->hdmacr->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) + { + hi3c->hdmatx->XferCpltCallback = NULL; + hi3c->hdmatx->XferErrorCallback = NULL; + } + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + } + + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Controller transmit direct read CCC command in polling mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_ReceiveCCC(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData, + uint32_t timeout) +{ + uint32_t tickstart; + uint32_t exit_condition; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + (pXferData->RxBuf.pBuffer == NULL) || + ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + + /* Check on CCC defining byte */ + if (hi3c->TxXferCount != 0U) + { + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + } + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check on control FIFO enable/disable state */ + if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) + { + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Decrement remaining control buffer data counter */ + hi3c->ControlXferCount--; + + /* Initiate a start condition by writing in the CR register */ + WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); + + /* Increment Buffer pointer */ + hi3c->pXferData->CtrlBuf.pBuffer++; + } + + /* Do while until FC (Frame Complete) is set or timeout */ + do + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + + if (hi3c->TxXferCount != 0U) + { + /* Call transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + } + + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + + /* Check for the timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + + if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + } while ((exit_condition == 0U) || + ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check if all data bytes are received */ + if ((hi3c->RxXferCount != 0U) && (status == HAL_OK)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + status = HAL_ERROR; + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update returned status value */ + status = HAL_ERROR; + } + + /* At the end of Rx process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Controller transmit direct read CCC command in interrupt mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_ReceiveCCC_IT(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + (pXferData->RxBuf.pBuffer == NULL) || + ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + if (handle_state == HAL_I3C_STATE_LISTEN) + { + hi3c->XferISR = I3C_Ctrl_Rx_Listen_Event_ISR; + } + else + { + hi3c->XferISR = I3C_Ctrl_Rx_ISR; + } + hi3c->pXferData = pXferData; + hi3c->RxXferCount = pXferData->RxBuf.Size; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + + /* Check on CCC defining byte */ + if (hi3c->TxXferCount != 0U) + { + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + } + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Rx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + + } + } + + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Controller transmit direct read CCC command in DMA mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_ReceiveCCC_DMA(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + HAL_StatusTypeDef control_dma_status; + HAL_StatusTypeDef tx_dma_status = HAL_OK; + HAL_StatusTypeDef rx_dma_status = HAL_OK; + uint32_t size_align_word; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + (pXferData->RxBuf.pBuffer == NULL) || + ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmarx and hdmacr handle */ + else if ((hi3c->hdmarx == NULL) || (hi3c->hdmacr == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + else if ((hi3c->TxXferCount != 0U) && (hi3c->hdmatx == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->XferISR = I3C_Ctrl_Rx_DMA_ISR; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + + /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmacr->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmacr->XferHalfCpltCallback = NULL; + hi3c->hdmacr->XferAbortCallback = NULL; + + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); + + /* Enable the control data DMA channel */ + control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, + (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); + + /*------------------------------------ I3C DMA channel for defining byte ---------------------------------------*/ + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmatx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmatx->XferHalfCpltCallback = NULL; + hi3c->hdmatx->XferAbortCallback = NULL; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDWR, size_align_word); + } + } + /*------------------------------------ I3C DMA channel for the Rx Data -----------------------------------------*/ + /* Check if Rx counter different from zero */ + if (hi3c->RxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; + + /* Set the DMA error callback */ + hi3c->hdmarx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmarx->XferHalfCpltCallback = NULL; + hi3c->hdmarx->XferAbortCallback = NULL; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->RxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); + } + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); + } + } + + /* Check if DMA process is well started */ + if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK) && (rx_dma_status == HAL_OK)) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Rx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->ControlXferCount = 0U; + + /* Enable control DMA Request */ + LL_I3C_EnableDMAReq_Control(hi3c->Instance); + + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Enable Tx data DMA Request */ + LL_I3C_EnableDMAReq_TX(hi3c->Instance); + } + + /* Check if Rx counter different from zero */ + if (hi3c->RxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Enable Rx data DMA Request */ + LL_I3C_EnableDMAReq_RX(hi3c->Instance); + } + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) + { + hi3c->hdmacr->XferCpltCallback = NULL; + hi3c->hdmacr->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) + { + hi3c->hdmatx->XferCpltCallback = NULL; + hi3c->hdmatx->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmarx) == HAL_OK) + { + hi3c->hdmarx->XferCpltCallback = NULL; + hi3c->hdmarx->XferErrorCallback = NULL; + } + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + } + + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Controller private write in polling mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Transmit(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData, + uint32_t timeout) +{ + uint32_t tickstart; + uint32_t exit_condition; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + hi3c->pXferData = pXferData; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check on control FIFO enable/disable state */ + if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) + { + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Decrement remaining control buffer data counter */ + hi3c->ControlXferCount--; + + /* Initiate a start condition by writing in the CR register */ + WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); + + /* Increment Buffer pointer */ + hi3c->pXferData->CtrlBuf.pBuffer++; + } + + /* Do while until FC (Frame Complete) is set or timeout */ + do + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + + /* Call transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + + /* Check for the timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + + if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + } while ((exit_condition == 0U) || + ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check if all data bytes are transmitted */ + if ((hi3c->TxXferCount != 0U) && (status == HAL_OK)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + status = HAL_ERROR; + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update returned status value */ + status = HAL_ERROR; + } + + /* At the end of Tx process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Controller private write in interrupt mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Transmit_IT(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + if (handle_state == HAL_I3C_STATE_LISTEN) + { + hi3c->XferISR = I3C_Ctrl_Tx_Listen_Event_ISR; + } + else + { + hi3c->XferISR = I3C_Ctrl_Tx_ISR; + } + hi3c->pXferData = pXferData; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Controller private write in DMA mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Transmit_DMA(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_StatusTypeDef control_dma_status; + HAL_StatusTypeDef tx_dma_status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t size_align_word; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((hi3c->TxXferCount != 0U) && (pXferData->TxBuf.pBuffer == NULL))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmatx and hdmacr handle */ + else if ((hi3c->hdmatx == NULL) || (hi3c->hdmacr == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->XferISR = I3C_Ctrl_Tx_DMA_ISR; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + hi3c->pXferData = pXferData; + + /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmacr->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmacr->XferHalfCpltCallback = NULL; + hi3c->hdmacr->XferAbortCallback = NULL; + + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); + + /* Enable the control data DMA channel */ + control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, + (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); + + /*------------------------------------ I3C DMA channel for the Tx Data -----------------------------------------*/ + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmatx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmatx->XferHalfCpltCallback = NULL; + hi3c->hdmatx->XferAbortCallback = NULL; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->TxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); + } + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDWR, size_align_word); + } + } + + /* Check if DMA process is well started */ + if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK)) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->ControlXferCount = 0U; + + /* Enable control DMA Request */ + LL_I3C_EnableDMAReq_Control(hi3c->Instance); + + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Enable Tx data DMA Request */ + LL_I3C_EnableDMAReq_TX(hi3c->Instance); + } + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) + { + hi3c->hdmacr->XferCpltCallback = NULL; + hi3c->hdmacr->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) + { + hi3c->hdmatx->XferCpltCallback = NULL; + hi3c->hdmatx->XferErrorCallback = NULL; + } + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + } + + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Controller private read in polling mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Receive(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData, + uint32_t timeout) +{ + uint32_t tickstart; + uint32_t exit_condition; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check on control FIFO enable/disable state */ + if (LL_I3C_IsEnabledControlFIFO(hi3c->Instance) == 1U) + { + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Decrement remaining control buffer data counter */ + hi3c->ControlXferCount--; + + /* Initiate a start condition by writing in the CR register */ + WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); + + /* Increment Buffer pointer */ + hi3c->pXferData->CtrlBuf.pBuffer++; + } + + /* Do while until FC (Frame Complete) is set or timeout */ + do + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + + /* Check for the timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + + if ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) && (hi3c->ControlXferCount > 0U)) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + } while ((exit_condition == 0U) || + ((exit_condition == I3C_EVR_FCF) && (hi3c->ControlXferCount > 0U))); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check if all data bytes are received */ + if ((hi3c->RxXferCount != 0U) && (status == HAL_OK)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + status = HAL_ERROR; + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update returned status value */ + status = HAL_ERROR; + } + + /* At the end of Rx process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Controller private read in interrupt mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Receive_IT(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + if (handle_state == HAL_I3C_STATE_LISTEN) + { + hi3c->XferISR = I3C_Ctrl_Rx_Listen_Event_ISR; + } + else + { + hi3c->XferISR = I3C_Ctrl_Rx_ISR; + } + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Rx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_IT); + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Controller private read in DMA mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers + * (control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_Receive_DMA(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_StatusTypeDef control_dma_status; + HAL_StatusTypeDef rx_dma_status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t size_align_word; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmarx and hdmacr handle */ + else if ((hi3c->hdmarx == NULL) || (hi3c->hdmacr == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->XferISR = I3C_Ctrl_Rx_DMA_ISR; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + + /*------------------------------------ I3C DMA channel for Control Data ----------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmacr->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmacr->XferHalfCpltCallback = NULL; + hi3c->hdmacr->XferAbortCallback = NULL; + + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); + + /* Enable the control data DMA channel */ + control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, + (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); + + /*------------------------------------ I3C DMA channel for the Rx Data -----------------------------------------*/ + /* Check if Rx counter different from zero */ + if (hi3c->RxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; + + /* Set the DMA error callback */ + hi3c->hdmarx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmarx->XferHalfCpltCallback = NULL; + hi3c->hdmarx->XferAbortCallback = NULL; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->RxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); + } + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); + } + } + + /* Check if DMA process is well started */ + if ((control_dma_status == HAL_OK) && (rx_dma_status == HAL_OK)) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Rx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->ControlXferCount = 0U; + + /* Enable control DMA Request */ + LL_I3C_EnableDMAReq_Control(hi3c->Instance); + + /* Check if Rx counter different from zero */ + if (hi3c->RxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Enable Rx data DMA Request */ + LL_I3C_EnableDMAReq_RX(hi3c->Instance); + } + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) + { + hi3c->hdmacr->XferCpltCallback = NULL; + hi3c->hdmacr->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmarx) == HAL_OK) + { + hi3c->hdmarx->XferCpltCallback = NULL; + hi3c->hdmarx->XferErrorCallback = NULL; + } + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + + } + } + + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Controller multiple Direct CCC Command, I3C private or I2C transfer in interrupt mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @note This function must be called to transfer read/write I3C or I2C private data or a direct read/write CCC. + * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmit and receive + * buffers (control buffer, data buffers and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_MultipleTransfer_IT(I3C_HandleTypeDef *hi3c, + I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((pXferData->RxBuf.pBuffer == NULL) && (hi3c->RxXferCount != 0U)) || + ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + if (handle_state == HAL_I3C_STATE_LISTEN) + { + hi3c->XferISR = I3C_Ctrl_Multiple_Xfer_Listen_Event_ISR; + } + else + { + hi3c->XferISR = I3C_Ctrl_Multiple_Xfer_ISR; + } + hi3c->pXferData = pXferData; + hi3c->TxXferCount = hi3c->pXferData->TxBuf.Size; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + hi3c->State = HAL_I3C_STATE_BUSY_TX_RX; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx and Rx process interrupts */ + I3C_Enable_IRQ(hi3c, (I3C_XFER_CONTROLLER_TX_IT | I3C_XFER_CONTROLLER_RX_IT)); + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Controller multiple Direct CCC Command, I3C private or I2C transfer in DMA mode. + * @note The function @ref HAL_I3C_AddDescToFrame() must be called before initiate a transfer. + * @note The Tx FIFO threshold @ref HAL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + * multiple transmission frames. + * @note The TxBuf.Size must be equal to the sum of all TxBuf.Size exist in the descriptor. + * @note The RxBuf.Size must be equal to the sum of all RxBuf.Size exist in the descriptor. + * @note This function must be called to transfer read/write private data or a direct read/write CCC command. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmit and receive + * buffers(control buffer, data buffer and status buffer). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_MultipleTransfer_DMA(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) +{ + HAL_StatusTypeDef control_dma_status; + HAL_StatusTypeDef tx_dma_status = HAL_OK; + HAL_StatusTypeDef rx_dma_status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t size_align_word; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || + ((pXferData->RxBuf.pBuffer == NULL) && (hi3c->RxXferCount != 0U)) || + ((pXferData->TxBuf.pBuffer == NULL) && (hi3c->TxXferCount != 0U))) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmatx, hdmarx and hdmacr handle */ + else if ((hi3c->hdmatx == NULL) || (hi3c->hdmacr == NULL) || (hi3c->hdmarx == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->XferISR = I3C_Ctrl_Multiple_Xfer_DMA_ISR; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = hi3c->pXferData->RxBuf.Size; + hi3c->TxXferCount = hi3c->pXferData->TxBuf.Size; + hi3c->State = HAL_I3C_STATE_BUSY_TX_RX; + + /*------------------------------------ I3C DMA channel for Control Data -------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmacr->XferCpltCallback = I3C_DMAControlTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmacr->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmacr->XferHalfCpltCallback = NULL; + hi3c->hdmacr->XferAbortCallback = NULL; + + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmacr->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmacr->Init.DestDataWidth)); + + /* Enable the control data DMA channel */ + control_dma_status = HAL_DMA_Start_IT(hi3c->hdmacr, (uint32_t)hi3c->pXferData->CtrlBuf.pBuffer, + (uint32_t)&hi3c->Instance->CR, (hi3c->ControlXferCount * 4U)); + + /*------------------------------------ I3C DMA channel for the Rx Data --------------------------------*/ + /* Check if Rx counter different from zero */ + if (hi3c->RxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; + + /* Set the DMA error callback */ + hi3c->hdmarx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmarx->XferHalfCpltCallback = NULL; + hi3c->hdmarx->XferAbortCallback = NULL; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->RxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); + } + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); + } + } + + /*------------------------------------ I3C DMA channel for the Tx Data --------------------------------*/ + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmatx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmatx->XferHalfCpltCallback = NULL; + hi3c->hdmatx->XferAbortCallback = NULL; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->TxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); + } + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDWR, size_align_word); + } + } + + /* Check if DMA process is well started */ + if ((control_dma_status == HAL_OK) && (tx_dma_status == HAL_OK) && (rx_dma_status == HAL_OK)) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->ControlXferCount = 0U; + + /* Enable control DMA Request */ + LL_I3C_EnableDMAReq_Control(hi3c->Instance); + + /* Check if Rx counter different from zero */ + if (hi3c->RxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Enable Rx data DMA Request */ + LL_I3C_EnableDMAReq_RX(hi3c->Instance); + } + + /* Check if Tx counter different from zero */ + if (hi3c->TxXferCount != 0U) + { + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Enable Tx data DMA Request */ + LL_I3C_EnableDMAReq_TX(hi3c->Instance); + } + + /* Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmacr) == HAL_OK) + { + hi3c->hdmacr->XferCpltCallback = NULL; + hi3c->hdmacr->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmatx) == HAL_OK) + { + hi3c->hdmatx->XferCpltCallback = NULL; + hi3c->hdmatx->XferErrorCallback = NULL; + } + + /* Set callback to NULL if DMA started */ + if (HAL_DMA_Abort(hi3c->hdmarx) == HAL_OK) + { + hi3c->hdmarx->XferCpltCallback = NULL; + hi3c->hdmarx->XferErrorCallback = NULL; + } + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + } + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Controller assign dynamic address (send a broadcast ENTDAA CCC command) in polling mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param target_payload : [IN/OUT] Pointer to the returned target payload value. + * @param dynOption : [IN] Parameter indicates the Dynamic address assignment option. + * It can be one value of @ref I3C_DYNAMIC_ADDRESS_OPTION_DEFINITION. + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_DynAddrAssign(I3C_HandleTypeDef *hi3c, + uint64_t *target_payload, + uint32_t dynOption, + uint32_t timeout) +{ + uint32_t tickstart; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on parameters */ + assert_param(IS_I3C_ENTDAA_OPTION(dynOption)); + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + if (target_payload == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Launch a RSTDAA procedure before launch ENTDAA */ + if ((dynOption == I3C_RSTDAA_THEN_ENTDAA) && + ((handle_state == HAL_I3C_STATE_READY) || (handle_state == HAL_I3C_STATE_LISTEN))) + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_DAA; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Enable arbitration header */ + LL_I3C_EnableArbitrationHeader(hi3c->Instance); + + /* Write CCC information in the control register */ + LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_RSTDAA, 0U, LL_I3C_GENERATE_STOP); + + /* Wait Frame completion flag */ + status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_FCF, RESET, timeout, tickstart); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + status = HAL_ERROR; + } + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + + if (status == HAL_OK) + { + /* check on the State */ + if ((handle_state == HAL_I3C_STATE_READY) || (handle_state == HAL_I3C_STATE_LISTEN) || + (handle_state == HAL_I3C_STATE_BUSY_DAA)) + { + /* Check on the state */ + if (handle_state != HAL_I3C_STATE_BUSY_DAA) + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_DAA; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Enable arbitration header */ + LL_I3C_EnableArbitrationHeader(hi3c->Instance); + + /* Write CCC information in the control register */ + LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_ENTDAA, 0U, LL_I3C_GENERATE_STOP); + } + else + { + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + } + + /* Wait frame complete flag or TX FIFO not full flag until timeout */ + status = I3C_WaitOnDAAUntilTimeout(hi3c, timeout, tickstart); + + /* Check TX FIFO not full flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) + { + /* Check on the Rx FIFO threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* For loop to get target payload */ + for (uint32_t index = 0U; index < 8U; index++) + { + /* Retrieve payload byte by byte */ + *target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData8(hi3c->Instance) << (index * 8U)); + } + } + else + { + /* Retrieve first 32 bits payload */ + *target_payload = (uint64_t)LL_I3C_ReceiveData32(hi3c->Instance); + + /* Retrieve second 32 bits payload */ + *target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData32(hi3c->Instance) << 32U); + } + + status = HAL_BUSY; + } + /* Check on frame complete flag */ + else + { + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + } + } + + return status; +} + +/** + * @brief Controller assign dynamic address (send a broadcast ENTDAA CCC command) in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param dynOption : [IN] Parameter indicates the Dynamic address assignment option. + * It can be one value of @ref I3C_DYNAMIC_ADDRESS_OPTION_DEFINITION. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_DynAddrAssign_IT(I3C_HandleTypeDef *hi3c, uint32_t dynOption) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on parameters */ + assert_param(IS_I3C_ENTDAA_OPTION(dynOption)); + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_DAA; + hi3c->XferISR = I3C_Ctrl_DAA_ISR; + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Dynamic Address Assignment process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_DAA_IT); + + /* Enable arbitration header */ + LL_I3C_EnableArbitrationHeader(hi3c->Instance); + + /* Launch a RSTDAA procedure before launch ENTDAA */ + if (dynOption == I3C_RSTDAA_THEN_ENTDAA) + { + /* Write RSTDAA CCC information in the control register */ + LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_RSTDAA, 0U, LL_I3C_GENERATE_RESTART); + } + else + { + /* Write ENTDAA CCC information in the control register */ + LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_ENTDAA, 0U, LL_I3C_GENERATE_STOP); + } + } + } + + return status; +} + +/** + * @brief Controller set dynamic address. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param devAddress : [IN] Value of the dynamic address to be assigned. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_SetDynAddr(I3C_HandleTypeDef *hi3c, uint8_t devAddress) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check if Tx FIFO requests data */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) + { + /* Write device address in the TDR register */ + LL_I3C_TransmitData8(hi3c->Instance, devAddress); + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Check if I3C target device is ready for communication. + * @param hi3c : [IN] Pointer to a I3C_HandleTypeDef structure that contains + * the configuration information for the specified I3C. + * @param devAddress : [IN] Value of the device dynamic address. + * @param trials : [IN] Number of trials + * @param timeout : [IN] Timeout duration + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_IsDeviceI3C_Ready(I3C_HandleTypeDef *hi3c, + uint8_t devAddress, + uint32_t trials, + uint32_t timeout) +{ + I3C_DeviceTypeDef device; + HAL_StatusTypeDef status; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Initiate a device address */ + device.Address = devAddress; + + /* Initiate a message type */ + device.MessageType = LL_I3C_CONTROLLER_MTYPE_PRIVATE; + + /* Check if the device is ready*/ + status = I3C_Ctrl_IsDevice_Ready(hi3c, &device, trials, timeout); + } + + return status; +} + +/** + * @brief Check if I2C target device is ready for communication. + * @param hi3c : [IN] Pointer to a I3C_HandleTypeDef structure that contains + * the configuration information for the specified I3C. + * @param devAddress : [IN] Value of the device dynamic address. + * @param trials : [IN] Number of trials + * @param timeout : [IN] Timeout duration + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_IsDeviceI2C_Ready(I3C_HandleTypeDef *hi3c, + uint8_t devAddress, + uint32_t trials, + uint32_t timeout) +{ + I3C_DeviceTypeDef device; + HAL_StatusTypeDef status; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Initiate a device address */ + device.Address = devAddress; + + /* Initiate a message type */ + device.MessageType = LL_I3C_CONTROLLER_MTYPE_LEGACY_I2C; + + /* Check if the device is ready*/ + status = I3C_Ctrl_IsDevice_Ready(hi3c, &device, trials, timeout); + } + + return status; +} + +/** + * @brief Controller generates arbitration (message header {S/Sr + 0x7E addr + W}) in polling mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains + * the configuration information for the specified I3C. + * @param timeout : [IN] Timeout duration + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Ctrl_GenerateArbitration(I3C_HandleTypeDef *hi3c, uint32_t timeout) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + __IO uint32_t exit_condition; + uint32_t tickstart; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Disable exit pattern */ + LL_I3C_DisableExitPattern(hi3c->Instance); + /* Disable reset pattern */ + LL_I3C_DisableResetPattern(hi3c->Instance); + + /* Write message control register */ + WRITE_REG(hi3c->Instance->CR, LL_I3C_CONTROLLER_MTYPE_HEADER | LL_I3C_GENERATE_STOP); + + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + + tickstart = HAL_GetTick(); + + while (exit_condition == 0U) + { + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + /* Update I3C error code */ + hi3c->ErrorCode |= HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + } + + if (status == HAL_OK) + { + /* Check if the FCF flag has been set */ + if (__HAL_I3C_GET_FLAG(hi3c, I3C_EVR_FCF) == SET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + else + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update returned status value */ + status = HAL_ERROR; + } + } + + /* At the end of Rx process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @} + */ + +/** @defgroup I3C_Exported_Functions_Group6 Target operational functions. + * @brief I3C target operational functions. + * +@verbatim + ======================================================================================================================= + ##### Target operational functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to manage target I3C operation. + + (+) Call the function HAL_I3C_Tgt_Transmit() to transmit private data in polling mode. + (+) Call the function HAL_I3C_Tgt_Transmit_IT() to transmit private data in interrupt mode. + (+) Call the function HAL_I3C_Tgt_Transmit_DMA() to transmit private data in DMA mode. + (+) Call the function HAL_I3C_Tgt_Receive() to receive private data in polling mode. + (+) Call the function HAL_I3C_Tgt_Receive_IT() to receive private data in interrupt mode. + (+) Call the function HAL_I3C_Tgt_Receive_DMA() to receive private data in DMA mode. + (+) Call the function HAL_I3C_Tgt_ControlRoleReq() to send a control-role request in polling mode. + (+) Call the function HAL_I3C_Tgt_ControlRoleReq_IT() to send a control-role request in interrupt mode. + (+) Call the function HAL_I3C_Tgt_HotJoinReq() to send a Hot-Join request in polling mode. + (+) Call the function HAL_I3C_Tgt_HotJoinReq_IT() to send a Hot-Join request in interrupt mode. + (+) Call the function HAL_I3C_Tgt_IBIReq() to send an IBI request in polling mode. + (+) Call the function HAL_I3C_Tgt_IBIReq_IT() to send an IBI request in interrupt mode. + + (+) Those functions are called only when mode is Target. + +@endverbatim + * @{ + */ + +/** + * @brief Target transmit private data in polling mode. + * @note Target FIFO preload data is forced within this API for timing purpose. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * information (Pointer to the Tx buffer (TxBuf.pBuffer) and size of data + * to transmit in bytes (TxBuf.Size)). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Transmit(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData, uint32_t timeout) +{ + uint32_t tickstart; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + uint32_t it_source; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + it_source = READ_REG(hi3c->Instance->IER); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->TxBuf.pBuffer == NULL) || (pXferData->TxBuf.Size == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* check if DEF or GRP CCC notifications are enabled */ + else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + hi3c->pXferData = pXferData; + hi3c->TxXferCount = pXferData->TxBuf.Size; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Set Preload information */ + LL_I3C_ConfigTxPreload(hi3c->Instance, (uint16_t)hi3c->pXferData->TxBuf.Size); + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Do while until FC (Frame Complete) is set or timeout */ + do + { + /* Call transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + + /* Check for the Timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + /* Exit loop on Frame complete or error flags */ + } while ((READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)) == 0U); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check if all data bytes are transmitted */ + if ((LL_I3C_GetXferDataCount(hi3c->Instance) != hi3c->pXferData->TxBuf.Size) && (status == HAL_OK)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + status = HAL_ERROR; + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update returned status value */ + status = HAL_ERROR; + } + + /* At the end of Tx process update state to Previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Target transmit private data in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * information (Pointer to the Tx buffer (TxBuf.pBuffer) and size of data + * to transmit in bytes (TxBuf.Size)). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Transmit_IT(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t it_source; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + it_source = READ_REG(hi3c->Instance->IER); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->TxBuf.pBuffer == NULL) || (pXferData->TxBuf.Size == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* check if DEF and GRP CCC notifications are enabled */ + else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + + status = HAL_ERROR; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + hi3c->pXferData = pXferData; + hi3c->TxXferCount = pXferData->TxBuf.Size; + hi3c->XferISR = I3C_Tgt_Tx_ISR; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrTxFunc = &I3C_TransmitWordTreatment; + } + + /* Set Preload information */ + LL_I3C_ConfigTxPreload(hi3c->Instance, (uint16_t)hi3c->pXferData->TxBuf.Size); + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_TX_IT); + } + } + + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Target transmit private data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required transmission buffers + * information (Pointer to the Tx buffer (TxBuf.pBuffer) and size of data + * to transmit in bytes (TxBuf.Size)). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Transmit_DMA(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) +{ + HAL_StatusTypeDef tx_dma_status; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t size_align_word; + uint32_t it_source; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + it_source = READ_REG(hi3c->Instance->IER); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->TxBuf.pBuffer == NULL) || (pXferData->TxBuf.Size == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmatx handle */ + else if (hi3c->hdmatx == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* check if DEF and GRP CCC notifications are enabled */ + else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_TX; + hi3c->pXferData = pXferData; + hi3c->TxXferCount = pXferData->TxBuf.Size; + hi3c->XferISR = I3C_Tgt_Tx_DMA_ISR; + + /* Set Preload information */ + LL_I3C_ConfigTxPreload(hi3c->Instance, (uint16_t)hi3c->pXferData->TxBuf.Size); + + /*------------------------------------ I3C DMA channel for the Tx Data -----------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmatx->XferCpltCallback = I3C_DMADataTransmitCplt; + + /* Set the DMA error callback */ + hi3c->hdmatx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmatx->XferHalfCpltCallback = NULL; + hi3c->hdmatx->XferAbortCallback = NULL; + + /* Check on the Tx threshold to know the Tx treatment process : byte or word */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDR, hi3c->pXferData->TxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmatx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmatx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->TxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->TxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->TxBuf.Size + 4U) - (hi3c->pXferData->TxBuf.Size % 4U)); + } + + /* Enable the Tx data DMA channel */ + tx_dma_status = HAL_DMA_Start_IT(hi3c->hdmatx, (uint32_t)hi3c->pXferData->TxBuf.pBuffer, + (uint32_t)&hi3c->Instance->TDWR, size_align_word); + } + + /* Check if DMA process is well started */ + if (tx_dma_status == HAL_OK) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Tx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Enable Tx data DMA Request */ + LL_I3C_EnableDMAReq_TX(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + hi3c->hdmatx->XferCpltCallback = NULL; + hi3c->hdmatx->XferErrorCallback = NULL; + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + } + + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Target receive private data in polling mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers + * information (Pointer to the Rx buffer (RxBuf.pBuffer) and size of data + * to be received in bytes (RxBuf.Size)). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Receive(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData, uint32_t timeout) +{ + uint32_t tickstart; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + uint32_t it_source; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + it_source = READ_REG(hi3c->Instance->IER); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL) || (pXferData->RxBuf.Size == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* check if DEF and GRP CCC notifications are enabled */ + else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = pXferData->RxBuf.Size; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Do while until FC (Frame Complete) is set or timeout */ + do + { + if (hi3c->RxXferCount > 0U) + { + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + } + + /* Check for the Timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + /* Exit loop on Frame complete or error flags */ + } while ((READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)) == 0U); + + /* Clear frame complete flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_FCF) == SET) + { + LL_I3C_ClearFlag_FC(hi3c->Instance); + } + + /* Check if all data bytes are received */ + if ((LL_I3C_GetXferDataCount(hi3c->Instance) != hi3c->pXferData->RxBuf.Size) && (status == HAL_OK)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + status = HAL_ERROR; + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + status = HAL_ERROR; + } + + /* At the end of Rx process update state to previous state */ + I3C_StateUpdate(hi3c); + } + } + + return status; +} + +/** + * @brief Target receive private data in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers + * information (Pointer to the Rx buffer (RxBuf.pBuffer) and size of data + * to be received in bytes (RxBuf.Size)). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Receive_IT(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t it_source; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + it_source = READ_REG(hi3c->Instance->IER); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL) || (pXferData->RxBuf.Size == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* check if DEF and GRP CCC notifications are enabled */ + else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = pXferData->RxBuf.Size; + hi3c->XferISR = I3C_Tgt_Rx_ISR; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* Set byte treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveByteTreatment; + } + else + { + /* Set word treatment function pointer */ + hi3c->ptrRxFunc = &I3C_ReceiveWordTreatment; + } + + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Rx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_RX_IT); + } + } + + return status; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Target receive private data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param pXferData : [IN] Pointer to an I3C_XferTypeDef structure that contains required reception buffers + * information (Pointer to the Rx buffer (RxBuf.pBuffer) and size of data + * to be received in bytes (RxBuf.Size)). + * This value contain transfer data after called @ref HAL_I3C_AddDescToFrame(). + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_Receive_DMA(I3C_HandleTypeDef *hi3c, I3C_XferTypeDef *pXferData) +{ + HAL_StatusTypeDef rx_dma_status; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + uint32_t size_align_word; + uint32_t it_source; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + it_source = READ_REG(hi3c->Instance->IER); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on user parameters */ + if ((pXferData == NULL) || (pXferData->RxBuf.pBuffer == NULL) || (pXferData->RxBuf.Size == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on hdmarx handle */ + else if (hi3c->hdmarx == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DMA_PARAM; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + /* check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* check if DEF and GRP CCC notifications are enabled */ + else if ((I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_DEFIE) != RESET) || + (I3C_CHECK_IT_SOURCE(it_source, HAL_I3C_IT_GRPIE) != RESET)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY_RX; + hi3c->pXferData = pXferData; + hi3c->RxXferCount = pXferData->RxBuf.Size; + hi3c->XferISR = I3C_Tgt_Rx_DMA_ISR; + + /*------------------------------------ I3C DMA channel for the Rx Data ---------------------------------------*/ + /* Set the I3C DMA transfer complete callback */ + hi3c->hdmarx->XferCpltCallback = I3C_DMADataReceiveCplt; + + /* Set the DMA error callback */ + hi3c->hdmarx->XferErrorCallback = I3C_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hi3c->hdmarx->XferHalfCpltCallback = NULL; + hi3c->hdmarx->XferAbortCallback = NULL; + + /* Check on the Rx threshold to know the Rx treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* assert that DMA source and destination width are configured in byte */ + assert_param(IS_I3C_DMASOURCEBYTE_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONBYTE_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, hi3c->pXferData->RxBuf.Size); + } + else + { + /* assert that DMA source and destination width are configured in word */ + assert_param(IS_I3C_DMASOURCEWORD_VALUE(hi3c->hdmarx->Init.SrcDataWidth)); + assert_param(IS_I3C_DMADESTINATIONWORD_VALUE(hi3c->hdmarx->Init.DestDataWidth)); + + /* Check to align data size in words */ + if ((hi3c->pXferData->RxBuf.Size % 4U) == 0U) + { + /* Keep the same size */ + size_align_word = hi3c->pXferData->RxBuf.Size; + } + else + { + /* Modify size to be multiple of 4 */ + size_align_word = ((hi3c->pXferData->RxBuf.Size + 4U) - (hi3c->pXferData->RxBuf.Size % 4U)); + } + + /* Enable the Rx data DMA channel */ + rx_dma_status = HAL_DMA_Start_IT(hi3c->hdmarx, (uint32_t)&hi3c->Instance->RDWR, + (uint32_t)hi3c->pXferData->RxBuf.pBuffer, size_align_word); + } + + if (rx_dma_status == HAL_OK) + { + /* Note : The I3C interrupts must be enabled after unlocking current process to avoid the risk + of I3C interrupt handle execution before current process unlock */ + + /* Enable Rx process interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Enable Rx data DMA Request */ + LL_I3C_EnableDMAReq_RX(hi3c->Instance); + } + else + { + /* Set callback to NULL if DMA started */ + hi3c->hdmarx->XferCpltCallback = NULL; + hi3c->hdmarx->XferErrorCallback = NULL; + + hi3c->ErrorCode = HAL_I3C_ERROR_DMA; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + } + } + + return status; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Target send control role request in polling mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_ControlRoleReq(I3C_HandleTypeDef *hi3c, uint32_t timeout) +{ + uint32_t tickstart; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Verify if control role request feature is enabled */ + if (LL_I3C_IsEnabledControllerRoleReq(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Request Controllership */ + LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_CONTROLLER_ROLE_REQ, 0U); + + /* Wait Controllership completion confirmation flag */ + status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_CRUPDF, RESET, timeout, tickstart); + + /* Clear Control role request flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_CRUPDF) == SET) + { + LL_I3C_ClearFlag_CRUPD(hi3c->Instance); + } + + /* Check on error flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + + status = HAL_ERROR; + } + else + { + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + } + } + } + + return status; +} + +/** + * @brief Target send control role request in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_ControlRoleReq_IT(I3C_HandleTypeDef *hi3c) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Verify if control role request feature is enabled */ + if (LL_I3C_IsEnabledControllerRoleReq(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Update handle parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + hi3c->XferISR = I3C_Tgt_CtrlRole_ISR; + + /* Enable controller-role update and error interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_CTRLROLE); + + /* Request Controllership */ + LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_CONTROLLER_ROLE_REQ, 0U); + } + } + + return status; +} + +/** + * @brief Target send hot join request in polling mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pAddress : [IN/OUT] Pointer to the target own dynamic address assigned by the controller. + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_HotJoinReq(I3C_HandleTypeDef *hi3c, uint8_t *pAddress, uint32_t timeout) +{ + uint32_t tickstart; + HAL_I3C_StateTypeDef handle_state; + uint32_t valid_dynamic_address; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on the pAddress value */ + if (pAddress == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check on the Mode */ + else if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Check on the hot join request feature */ + if (LL_I3C_IsEnabledHotJoin(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Request hot join */ + LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_HOT_JOIN, 0U); + + /* Wait hot join completion confirmation flag */ + status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_DAUPDF, RESET, timeout, tickstart); + + /* Clear dynamic address update flag */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_DAUPDF) == SET) + { + LL_I3C_ClearFlag_DAUPD(hi3c->Instance); + } + + /* Get dynamic address validity flag */ + valid_dynamic_address = LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance); + + /* Check the validity of the own dynamic address */ + if (valid_dynamic_address == 0U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_DYNAMIC_ADDR; + status = HAL_ERROR; + + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + } + /* Check on error flag */ + else if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + + status = HAL_ERROR; + } + else + { + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + + /* Get assigned dynamic address */ + *pAddress = LL_I3C_GetOwnDynamicAddress(hi3c->Instance); + } + } + } + + return status; +} + +/** + * @brief Target send hot join request in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_HotJoinReq_IT(I3C_HandleTypeDef *hi3c) +{ + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* Check on the hot join request feature */ + else if (LL_I3C_IsEnabledHotJoin(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Update handle parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + hi3c->XferISR = I3C_Tgt_HotJoin_ISR; + + /* Enable dynamic address update and error interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_HOTJOIN); + + /* Request hot join */ + LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_HOT_JOIN, 0U); + } + } + + return status; +} + +/** + * @brief Target send IBI request in polling mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pPayload : [IN] Pointer to the buffer contains the payload data. + * @param payloadSize : [IN] Payload buffer size in bytes. + * @param timeout : [IN] Timeout duration in millisecond. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_IBIReq(I3C_HandleTypeDef *hi3c, const uint8_t *pPayload, + uint8_t payloadSize, uint32_t timeout) +{ + uint32_t tickstart; + uint32_t payload_value = 0U; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Verify if IBI request feature is enabled*/ + if ((LL_I3C_IsEnabledIBI(hi3c->Instance) != 1U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Update handle parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Check on the IBI additional data */ + if (LL_I3C_GetDeviceIBIPayload(hi3c->Instance) == LL_I3C_IBI_ADDITIONAL_DATA) + { + /* Check on the pPayload and payloadSize values */ + if ((pPayload == NULL) || (payloadSize == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + else + { + /* For loop to calculate the payload value */ + for (uint32_t index = 0U; index < payloadSize; index++) + { + payload_value |= ((uint32_t)pPayload[index] << (index * 8U)); + } + + /* Load IBI payload data */ + LL_I3C_SetIBIPayload(hi3c->Instance, payload_value); + } + } + + if (status == HAL_OK) + { + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Request IBI */ + LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_IBI, payloadSize); + + /* Wait IBI completion confirmation flag */ + status = I3C_WaitOnFlagUntilTimeout(hi3c, HAL_I3C_FLAG_IBIENDF, RESET, timeout, tickstart); + + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_IBIENDF) == SET) + { + /* Clear IBI end process flag */ + LL_I3C_ClearFlag_IBIEND(hi3c->Instance); + } + + /* Check on error flag value */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + + status = HAL_ERROR; + } + else + { + /* Update handle state parameter to previous state */ + I3C_StateUpdate(hi3c); + } + } + } + } + + return status; +} + +/** + * @brief Target send IBI request in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param pPayload : [IN] Pointer to the buffer contains the payload data. + * @param payloadSize : [IN] Payload buffer size in bytes. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Tgt_IBIReq_IT(I3C_HandleTypeDef *hi3c, const uint8_t *pPayload, uint8_t payloadSize) +{ + uint32_t payload_value = 0U; + HAL_I3C_StateTypeDef handle_state; + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check the instance and the mode parameters */ + assert_param(IS_I3C_ALL_INSTANCE(hi3c->Instance)); + assert_param(IS_I3C_MODE(hi3c->Mode)); + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* Check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_TARGET) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + /* Verify the dynamic address validity */ + else if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Verify if IBI request feature is enabled */ + if (LL_I3C_IsEnabledIBI(hi3c->Instance) != 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Update handle parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + hi3c->XferISR = I3C_Tgt_IBI_ISR; + + /* Check on the IBI additional data */ + if (LL_I3C_GetDeviceIBIPayload(hi3c->Instance) == LL_I3C_IBI_ADDITIONAL_DATA) + { + /* Check on the pPayload and payloadSize values */ + if ((pPayload == NULL) || (payloadSize == 0U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + } + else + { + /* For loop to calculate the payload value */ + for (uint32_t index = 0U; index < payloadSize; index++) + { + payload_value |= ((uint32_t)pPayload[index] << (index * 8U)); + } + + /* Load IBI payload data */ + LL_I3C_SetIBIPayload(hi3c->Instance, payload_value); + } + } + + /* Enable IBI end and error interrupts */ + I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_IBI); + + /* Request IBI */ + LL_I3C_TargetHandleMessage(hi3c->Instance, LL_I3C_TARGET_MTYPE_IBI, payloadSize); + } + } + + return status; +} +/** + * @} + */ + +/** @defgroup I3C_Exported_Functions_Group7 Generic and Common functions. + * @brief I3C generic and common functions. + * +@verbatim + ======================================================================================================================= + ##### Generic and Common functions ##### + ======================================================================================================================= + [..] This subsection provides a set of functions allowing to Abort transfer or to get in run-time the status + of the peripheral. + + (+) Call the function HAL_I3C_Abort_IT() to abort the current transfer either in DMA or IT. + (+) Call the function HAL_I3C_GetState() to get the I3C handle state. + (+) Call the function HAL_I3C_GetMode() to get the I3C handle mode. + (+) Call the function HAL_I3C_GetError() to get the error code. + (+) Call the function HAL_I3C_Get_ENTDAA_Payload_Info() to get BCR, DCR and PID information after ENTDAA. + +@endverbatim + * @{ + */ + +/** + * @brief Abort an I3C IT or DMA process communication with Interrupt. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Abort_IT(I3C_HandleTypeDef *hi3c) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + if (hi3c->State != HAL_I3C_STATE_ABORT) + { + /* Set State at HAL_I3C_STATE_ABORT */ + hi3c->State = HAL_I3C_STATE_ABORT; + + /* Disable Error Interrupts */ + __HAL_I3C_DISABLE_IT(hi3c, HAL_I3C_IT_ERRIE); + + hi3c->XferISR = I3C_Abort_ISR; + + /* Flush the different Fifos to generate an automatic stop mode link to underflow or overflow detection timeout */ + /* Flush the content of Tx Fifo */ + LL_I3C_RequestTxFIFOFlush(hi3c->Instance); + + /* Flush the content of Rx Fifo */ + LL_I3C_RequestRxFIFOFlush(hi3c->Instance); + + /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Flush the content of Control Fifo */ + LL_I3C_RequestControlFIFOFlush(hi3c->Instance); + + /* Flush the content of Status Fifo */ + LL_I3C_RequestStatusFIFOFlush(hi3c->Instance); + } + + /* Disable all DMA Requests */ + LL_I3C_DisableDMAReq_Control(hi3c->Instance); + LL_I3C_DisableDMAReq_RX(hi3c->Instance); + LL_I3C_DisableDMAReq_TX(hi3c->Instance); + LL_I3C_DisableDMAReq_Status(hi3c->Instance); + + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Note : The I3C interrupts must be enabled after unlocking current process + to avoid the risk of I3C interrupt handle execution before current + process unlock */ + I3C_Enable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); + } + else + { + /* Note : The I3C interrupts must be enabled after unlocking current process + to avoid the risk of I3C interrupt handle execution before current + process unlock */ + I3C_Enable_IRQ(hi3c, I3C_XFER_TARGET_RX_IT); + } + } + else + { + return HAL_BUSY; + } + } + + return status; +} + +/** + * @brief Return the I3C handle state. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval HAL State : [OUT] Value from HAL_I3C_StateTypeDef enumeration. + */ +HAL_I3C_StateTypeDef HAL_I3C_GetState(const I3C_HandleTypeDef *hi3c) +{ + return hi3c->State; +} + +/** + * @brief Returns the I3C handle mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval HAL Mode : [OUT] Value from HAL_I3C_ModeTypeDef enumeration. + */ +HAL_I3C_ModeTypeDef HAL_I3C_GetMode(const I3C_HandleTypeDef *hi3c) +{ + return hi3c->Mode; +} + +/** + * @brief Return the I3C error code. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval I3C Error Code : [OUT] Value from @ref I3C_ERROR_CODE_DEFINITION. + */ +uint32_t HAL_I3C_GetError(const I3C_HandleTypeDef *hi3c) +{ + return hi3c->ErrorCode; +} + +/** + * @brief Target/Controller Get Common Command Code Information updated after event. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param notifyId : [IN] Parameter indicates which notification is signaled. + * It can be a combination of value of @ref HAL_I3C_Notification_ID_definition. + * @param pCCCInfo : [IN/OUT] Pointer to an I3C_CCCInfoTypeDef structure that contains the CCC information + * updated after CCC event. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_GetCCCInfo(I3C_HandleTypeDef *hi3c, + uint32_t notifyId, + I3C_CCCInfoTypeDef *pCCCInfo) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check on user parameters */ + if (pCCCInfo == NULL) + { + /* Update handle error code parameter */ + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + /* Check the I3C state */ + else if (hi3c->State == HAL_I3C_STATE_RESET) + { + /* Update handle error code parameter */ + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + else + { + /* Retrieve Target Dynamic Address value and Validity (target/controller) */ + if ((notifyId & EVENT_ID_DAU) == EVENT_ID_DAU) + { + pCCCInfo->DynamicAddrValid = LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance); + pCCCInfo->DynamicAddr = LL_I3C_GetOwnDynamicAddress(hi3c->Instance); + } + + /* Retrieve Maximum Write Data Length (target) */ + if ((notifyId & EVENT_ID_SETMWL) == EVENT_ID_SETMWL) + { + pCCCInfo->MaxWriteLength = LL_I3C_GetMaxWriteLength(hi3c->Instance); + } + + /* Retrieve Maximum Read Data Length (target) */ + if ((notifyId & EVENT_ID_SETMRL) == EVENT_ID_SETMRL) + { + pCCCInfo->MaxReadLength = LL_I3C_GetMaxReadLength(hi3c->Instance); + } + + /* Retrieve Reset Action/Level on received reset pattern (target) */ + if ((notifyId & EVENT_ID_RSTACT) == EVENT_ID_RSTACT) + { + pCCCInfo->ResetAction = LL_I3C_GetResetAction(hi3c->Instance); + } + + /* Retrieve Activity State (target) */ + if ((notifyId & EVENT_ID_ENTASx) == EVENT_ID_ENTASx) + { + pCCCInfo->ActivityState = LL_I3C_GetActivityState(hi3c->Instance); + } + + /* Retrieve Interrupt allowed status (target) */ + if ((notifyId & EVENT_ID_ENEC_DISEC) == EVENT_ID_ENEC_DISEC) + { + pCCCInfo->HotJoinAllowed = LL_I3C_IsEnabledHotJoin(hi3c->Instance); + pCCCInfo->InBandAllowed = LL_I3C_IsEnabledIBI(hi3c->Instance); + pCCCInfo->CtrlRoleAllowed = LL_I3C_IsEnabledControllerRoleReq(hi3c->Instance); + } + + /* Retrieve In Band Interrupt information (controller) */ + if ((notifyId & EVENT_ID_IBI) == EVENT_ID_IBI) + { + pCCCInfo->IBICRTgtAddr = LL_I3C_GetIBITargetAddr(hi3c->Instance); + pCCCInfo->IBITgtNbPayload = LL_I3C_GetNbIBIAddData(hi3c->Instance); + pCCCInfo->IBITgtPayload = LL_I3C_GetIBIPayload(hi3c->Instance); + } + + /* Retrieve Controller role request Interrupt information (controller) */ + if ((notifyId & EVENT_ID_CR) == EVENT_ID_CR) + { + pCCCInfo->IBICRTgtAddr = LL_I3C_GetIBITargetAddr(hi3c->Instance); + } + } + } + + return status; +} + +/** + * @brief Get BCR, DCR and PID information after ENTDAA. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param ENTDAA_payload :[IN] Payload received after ENTDAA + * @param pENTDAA_payload :[OUT] Pointer to an I3C_ENTDAAPayloadTypeDef structure that contains the BCR, DCR and PID + * information. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +HAL_StatusTypeDef HAL_I3C_Get_ENTDAA_Payload_Info(I3C_HandleTypeDef *hi3c, + uint64_t ENTDAA_payload, + I3C_ENTDAAPayloadTypeDef *pENTDAA_payload) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t BCR; + uint64_t PID; + + /* check on the handle */ + if (hi3c == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check on user parameters */ + if (pENTDAA_payload == NULL) + { + /* Update handle error code parameter */ + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Get Bus Characterics */ + BCR = __HAL_I3C_GET_BCR(ENTDAA_payload); + + /* Retrieve BCR information */ + pENTDAA_payload->BCR.IBIPayload = __HAL_I3C_GET_IBI_PAYLOAD(BCR); + pENTDAA_payload->BCR.IBIRequestCapable = __HAL_I3C_GET_IBI_CAPABLE(BCR); + pENTDAA_payload->BCR.DeviceRole = __HAL_I3C_GET_CR_CAPABLE(BCR); + pENTDAA_payload->BCR.AdvancedCapabilities = I3C_GET_ADVANCED_CAPABLE(BCR); + pENTDAA_payload->BCR.OfflineCapable = I3C_GET_OFFLINE_CAPABLE(BCR); + pENTDAA_payload->BCR.VirtualTargetSupport = I3C_GET_VIRTUAL_TGT(BCR); + pENTDAA_payload->BCR.MaxDataSpeedLimitation = I3C_GET_MAX_DATA_SPEED_LIMIT(BCR); + + /* Get Device Characterics */ + pENTDAA_payload->DCR = I3C_GET_DCR(ENTDAA_payload); + + /* Get Provisioned ID */ + PID = I3C_GET_PID(ENTDAA_payload); + + /* Change PID from BigEndian to litlleEndian */ + PID = (uint64_t)((((uint64_t)I3C_BIG_TO_LITTLE_ENDIAN((uint32_t) PID) << 32) | + ((uint64_t)I3C_BIG_TO_LITTLE_ENDIAN((uint32_t)(PID >> 32)))) >> 16); + + /* Retrieve PID information*/ + pENTDAA_payload->PID.MIPIMID = I3C_GET_MIPIMID(PID); + pENTDAA_payload->PID.IDTSEL = I3C_GET_IDTSEL(PID); + pENTDAA_payload->PID.PartID = I3C_GET_PART_ID(PID); + pENTDAA_payload->PID.MIPIID = I3C_GET_MIPIID(PID); + } + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private functions -------------------------------------------------------------------------------------------------*/ +/** @defgroup I3C_Private_Functions I3C Private Functions + * @{ + */ + +/** + * @brief Interrupt Sub-Routine which handles target received events. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + uint32_t tmpevent = 0U; + + /* I3C Rx FIFO not empty interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) + { + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + } + + /* I3C target complete controller-role hand-off procedure (direct GETACCR CCC) event management --------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRUPDF) != RESET) + { + /* Clear controller-role update flag */ + LL_I3C_ClearFlag_CRUPD(hi3c->Instance); + + /* Set Identifier EVENT_ID_GETACCCR */ + tmpevent |= EVENT_ID_GETACCCR; + } + + /* I3C target receive any direct GETxxx CCC event management -------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_GETF) != RESET) + { + /* Clear GETxxx CCC flag */ + LL_I3C_ClearFlag_GET(hi3c->Instance); + + /* Set Identifier EVENT_ID_GETx */ + tmpevent |= EVENT_ID_GETx; + } + + /* I3C target receive get status command (direct GETSTATUS CCC) event management -----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_STAF) != RESET) + { + /* Clear GETSTATUS CCC flag */ + LL_I3C_ClearFlag_STA(hi3c->Instance); + + /* Set Identifier EVENT_ID_GETSTATUS */ + tmpevent |= EVENT_ID_GETSTATUS; + } + + /* I3C target receive a dynamic address update (ENTDAA/RSTDAA/SETNEWDA CCC) event management -----------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_DAUPDF) != RESET) + { + /* Clear dynamic address update flag */ + LL_I3C_ClearFlag_DAUPD(hi3c->Instance); + + /* Set Identifier EVENT_ID_DAU */ + tmpevent |= EVENT_ID_DAU; + } + + /* I3C target receive maximum write length update (direct SETMWL CCC) event management -----------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_MWLUPDF) != RESET) + { + /* Clear SETMWL CCC flag */ + LL_I3C_ClearFlag_MWLUPD(hi3c->Instance); + + /* Set Identifier EVENT_ID_SETMWL */ + tmpevent |= EVENT_ID_SETMWL; + } + + /* I3C target receive maximum read length update(direct SETMRL CCC) event management -------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_MRLUPDF) != RESET) + { + /* Clear SETMRL CCC flag */ + LL_I3C_ClearFlag_MRLUPD(hi3c->Instance); + + /* Set Identifier EVENT_ID_SETMRL */ + tmpevent |= EVENT_ID_SETMRL; + } + + /* I3C target detect reset pattern (broadcast or direct RSTACT CCC) event management -------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_RSTF) != RESET) + { + /* Clear reset pattern flag */ + LL_I3C_ClearFlag_RST(hi3c->Instance); + + /* Set Identifier EVENT_ID_RSTACT */ + tmpevent |= EVENT_ID_RSTACT; + } + + /* I3C target receive activity state update (direct or broadcast ENTASx) CCC event management ----------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_ASUPDF) != RESET) + { + /* Clear ENTASx CCC flag */ + LL_I3C_ClearFlag_ASUPD(hi3c->Instance); + + /* Set Identifier EVENT_ID_ENTASx */ + tmpevent |= EVENT_ID_ENTASx; + } + + /* I3C target receive a direct or broadcast ENEC/DISEC CCC event management ----------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_INTUPDF) != RESET) + { + /* Clear ENEC/DISEC CCC flag */ + LL_I3C_ClearFlag_INTUPD(hi3c->Instance); + + /* Set Identifier EVENT_ID_ENEC_DISEC */ + tmpevent |= EVENT_ID_ENEC_DISEC; + } + + /* I3C target receive a broadcast DEFTGTS CCC event management -----------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_DEFF) != RESET) + { + /* Clear DEFTGTS CCC flag */ + LL_I3C_ClearFlag_DEF(hi3c->Instance); + + /* Set Identifier EVENT_ID_DEFTGTS */ + tmpevent |= EVENT_ID_DEFTGTS; + } + + /* I3C target receive a group addressing (broadcast DEFGRPA CCC) event management ----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_GRPF) != RESET) + { + /* Clear DEFGRPA CCC flag */ + LL_I3C_ClearFlag_GRP(hi3c->Instance); + + /* Set Identifier EVENT_ID_DEFGRPA */ + tmpevent |= EVENT_ID_DEFGRPA; + } + + /* I3C target wakeup event management ----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) + { + /* Clear WKP flag */ + LL_I3C_ClearFlag_WKP(hi3c->Instance); + + /* Set Identifier EVENT_ID_WKP */ + tmpevent |= EVENT_ID_WKP; + } + + if (tmpevent != 0U) + { +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, tmpevent); +#else + /* Asynchronous receive CCC event Callback */ + HAL_I3C_NotifyCallback(hi3c, tmpevent); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles Controller received events. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) + { + /* Clear IBI request flag */ + LL_I3C_ClearFlag_IBI(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); +#else + /* Asynchronous IBI event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller controller-role request event management ---------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) + { + /* Clear controller-role request flag */ + LL_I3C_ClearFlag_CR(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_CR); +#else + /* Asynchronous controller-role event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller hot-join event management ------------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) + { + /* Clear hot-join flag */ + LL_I3C_ClearFlag_HJ(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); +#else + /* Asynchronous hot-join event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles target hot join event. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_HotJoin_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C target receive a dynamic address update event management */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_DAUPDF) != RESET) + { + /* Clear dynamic address update flag */ + LL_I3C_ClearFlag_DAUPD(hi3c->Instance); + + /* Disable dynamic address update and error interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_HOTJOIN); + + /* Check the validity of the own dynamic address */ + if (LL_I3C_IsEnabledOwnDynAddress(hi3c->Instance) == 1U) + { + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->TgtHotJoinCallback(hi3c, (uint8_t)LL_I3C_GetOwnDynamicAddress(hi3c->Instance)); +#else + /* Asynchronous receive ENTDAA/RSTDAA/SETNEWDA CCC event Callback */ + HAL_I3C_TgtHotJoinCallback(hi3c, (uint8_t)LL_I3C_GetOwnDynamicAddress(hi3c->Instance)); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_DYNAMIC_ADDR; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles target control role event. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_CtrlRole_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C target complete controller-role hand-off procedure (direct GETACCR CCC) event management -------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRUPDF) != RESET) + { + /* Clear controller-role update flag */ + LL_I3C_ClearFlag_CRUPD(hi3c->Instance); + + /* Disable controller-role update and error interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_CTRLROLE); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_GETACCCR); +#else + /* Asynchronous receive GETACCR CCC event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_GETACCCR); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles target IBI event. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_IBI_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C target IBI end process event management ---------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIENDF) != RESET) + { + /* Clear IBI end flag */ + LL_I3C_ClearFlag_IBIEND(hi3c->Instance); + + /* Disable IBI end and error interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_IBI); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_IBIEND); +#else + /* Asynchronous IBI end event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBIEND); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles target transmit data in Interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that a Tx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_TX) + { + /* I3C Tx FIFO not full interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) + { + if (hi3c->TxXferCount > 0U) + { + /* Call transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + } + } + + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Check if all data bytes are transmitted */ + if (LL_I3C_GetXferDataCount(hi3c->Instance) == hi3c->pXferData->TxBuf.Size) + { + /* Disable Tx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_TX_IT); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the transmit complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->TgtTxCpltCallback(hi3c); +#else + HAL_I3C_TgtTxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + + /* I3C target wakeup event management ----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) + { + /* Clear WKP flag */ + LL_I3C_ClearFlag_WKP(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); +#else + /* Asynchronous receive CCC event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + } + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles target receive data in Interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that an Rx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_RX) + { + /* I3C Rx FIFO not empty interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) + { + if (hi3c->RxXferCount > 0U) + { + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + } + } + + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Check if all data bytes are received */ + if (LL_I3C_GetXferDataCount(hi3c->Instance) == hi3c->pXferData->RxBuf.Size) + { + /* Disable Rx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_TARGET_RX_IT); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the receive complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->TgtRxCpltCallback(hi3c); +#else + HAL_I3C_TgtRxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + + /* I3C target wakeup event management ----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) + { + /* Clear WKP flag */ + LL_I3C_ClearFlag_WKP(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); +#else + /* Asynchronous receive CCC event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + } + + return HAL_OK; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Interrupt Sub-Routine which handles target transmit data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that a Tx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_TX) + { + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Check if all data bytes are transmitted */ + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmatx) == 0U) + { + /* Disable Tx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Call target transmit complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->TgtTxCpltCallback(hi3c); +#else + HAL_I3C_TgtTxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + + /* I3C target wakeup event management ----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) + { + /* Clear WKP flag */ + LL_I3C_ClearFlag_WKP(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); +#else + /* Asynchronous receive CCC event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + } + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles target receive data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Tgt_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that a Rx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_RX) + { + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Check if all data bytes are received */ + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmarx) == 0U) + { + /* Disable Rx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Call target receive complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->TgtRxCpltCallback(hi3c); +#else + HAL_I3C_TgtRxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + + /* I3C target wakeup event management ----------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_WKPF) != RESET) + { + /* Clear WKP flag */ + LL_I3C_ClearFlag_WKP(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_WKP); +#else + /* Asynchronous receive CCC event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_WKP); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + } + + return HAL_OK; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Interrupt Sub-Routine which handles controller transmission in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Tx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that a Tx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_TX) + { + /* Check if Control FIFO requests data */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) + { + if (hi3c->ControlXferCount > 0U) + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + } + } + + /* I3C Tx FIFO not full interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) + { + if (hi3c->TxXferCount > 0U) + { + /* Call Transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + } + } + + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + if (hi3c->ControlXferCount == 0U) + { + /* Disable Tx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the transmit complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlTxCpltCallback(hi3c); +#else + HAL_I3C_CtrlTxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the transmit complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlTxCpltCallback(hi3c); +#else + HAL_I3C_CtrlTxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + + } + } + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles controller reception in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Rx_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that an Rx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_RX) + { + /* Check if Control FIFO requests data */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) + { + if (hi3c->ControlXferCount > 0U) + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + } + } + + /* I3C Rx FIFO not empty interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) + { + if (hi3c->RxXferCount > 0U) + { + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + } + } + + /* I3C Tx FIFO not full interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) + { + if (hi3c->TxXferCount > 0U) + { + /* Call Transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + } + } + + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + if (hi3c->ControlXferCount == 0U) + { + /* Disable Rx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the receive complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlRxCpltCallback(hi3c); +#else + HAL_I3C_CtrlRxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the receive complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlRxCpltCallback(hi3c); +#else + HAL_I3C_CtrlRxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles controller multiple transmission/reception in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that a Tx/Rx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_TX_RX) + { + /* Check if Control FIFO requests data */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) + { + if (hi3c->ControlXferCount > 0U) + { + /* Call control data treatment function */ + I3C_ControlDataTreatment(hi3c); + } + } + + /* I3C Tx FIFO not full interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) + { + if (hi3c->TxXferCount > 0U) + { + /* Call Transmit treatment function */ + hi3c->ptrTxFunc(hi3c); + } + } + + /* I3C Rx FIFO not empty interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) + { + if (hi3c->RxXferCount > 0U) + { + /* Call receive treatment function */ + hi3c->ptrRxFunc(hi3c); + } + } + + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + if (hi3c->ControlXferCount == 0U) + { + /* Disable Tx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_TX_IT); + + /* Disable Rx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the transmit, receive complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlMultipleXferCpltCallback(hi3c); +#else + HAL_I3C_CtrlMultipleXferCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles controller transmission and Controller received events + * in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Tx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) + { + /* Clear IBI request flag */ + LL_I3C_ClearFlag_IBI(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); +#else + /* Asynchronous IBI event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller controller-role request event management ---------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) + { + /* Clear controller-role request flag */ + LL_I3C_ClearFlag_CR(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_CR); +#else + /* Asynchronous controller-role event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller hot-join event management ------------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) + { + /* Clear hot-join flag */ + LL_I3C_ClearFlag_HJ(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); +#else + /* Asynchronous hot-join event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* ISR controller transmission */ + return (I3C_Ctrl_Tx_ISR(hi3c, itMasks)); +} + +/** + * @brief Interrupt Sub-Routine which handles controller reception and Controller received events in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Rx_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) + { + /* Clear IBI request flag */ + LL_I3C_ClearFlag_IBI(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); +#else + /* Asynchronous IBI event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller controller-role request event management ---------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) + { + /* Clear controller-role request flag */ + LL_I3C_ClearFlag_CR(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_CR); +#else + /* Asynchronous controller-role event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller hot-join event management ------------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) + { + /* Clear hot-join flag */ + LL_I3C_ClearFlag_HJ(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); +#else + /* Asynchronous hot-join event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* ISR controller reception */ + return (I3C_Ctrl_Rx_ISR(hi3c, itMasks)); +} + +/** + * @brief Interrupt Sub-Routine which handles controller multiple transmission/reception and + * Controller received eventsin interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_Listen_Event_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* I3C controller receive IBI event management ---------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_IBIF) != RESET) + { + /* Clear IBI request flag */ + LL_I3C_ClearFlag_IBI(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_IBI); +#else + /* Asynchronous IBI event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_IBI); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller controller-role request event management ---------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CRF) != RESET) + { + /* Clear controller-role request flag */ + LL_I3C_ClearFlag_CR(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_CR); +#else + /* Asynchronous controller-role event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_CR); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* I3C controller hot-join event management ------------------------------------------------------------------------*/ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_HJF) != RESET) + { + /* Clear hot-join flag */ + LL_I3C_ClearFlag_HJ(hi3c->Instance); + +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + /* Call registered callback */ + hi3c->NotifyCallback(hi3c, EVENT_ID_HJ); +#else + /* Asynchronous hot-join event Callback */ + HAL_I3C_NotifyCallback(hi3c, EVENT_ID_HJ); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + + /* ISR controller transmission/reception */ + return (I3C_Ctrl_Multiple_Xfer_ISR(hi3c, itMasks)); +} +/** + * @brief Interrupt Sub-Routine which handles controller CCC Dynamic Address Assignment command in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_DAA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + uint64_t target_payload = 0U; + + /* Check that a Dynamic Address Assignment process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_DAA) + { + /* I3C Control FIFO not full interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_CFNFF) != RESET) + { + /* Write ENTDAA CCC information in the control register */ + LL_I3C_ControllerHandleCCC(hi3c->Instance, I3C_BROADCAST_ENTDAA, 0U, LL_I3C_GENERATE_STOP); + } + + /* I3C Tx FIFO not full interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_TXFNFF) != RESET) + { + /* Check on the Rx FIFO threshold to know the Dynamic Address Assignment treatment process : byte or word */ + if (LL_I3C_GetRxFIFOThreshold(hi3c->Instance) == LL_I3C_RXFIFO_THRESHOLD_1_4) + { + /* For loop to get target payload */ + for (uint32_t index = 0U; index < 8U; index++) + { + /* Retrieve payload byte by byte */ + target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData8(hi3c->Instance) << (index * 8U)); + } + } + else + { + /* Retrieve first 32 bits payload */ + target_payload = (uint64_t)LL_I3C_ReceiveData32(hi3c->Instance); + + /* Retrieve second 32 bits payload */ + target_payload |= (uint64_t)((uint64_t)LL_I3C_ReceiveData32(hi3c->Instance) << 32U); + } + + /* Call the corresponding callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->TgtReqDynamicAddrCallback(hi3c, target_payload); +#else + HAL_I3C_TgtReqDynamicAddrCallback(hi3c, target_payload); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ + } + + /* I3C frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Disable Dynamic Address Assignment process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_DAA_IT); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the Dynamic Address Assignment complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlDAACpltCallback(hi3c); +#else + HAL_I3C_CtrlDAACpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + } + return HAL_OK; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Interrupt Sub-Routine which handles controller transmit data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Tx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that a Tx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_TX) + { + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmacr) == 0U) + { + /* Check if all data bytes are transmitted */ + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmatx) == 0U) + { + /* Disable Tx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Call controller transmit complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlTxCpltCallback(hi3c); +#else + HAL_I3C_CtrlTxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the transmit complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlTxCpltCallback(hi3c); +#else + HAL_I3C_CtrlTxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles controller receive data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Rx_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that an Rx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_RX) + { + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmacr) == 0U) + { + /* Check if all data bytes are received */ + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmarx) == 0U) + { + /* Disable Rx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Call controller receive complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlRxCpltCallback(hi3c); +#else + HAL_I3C_CtrlRxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Call the receive complete callback */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlRxCpltCallback(hi3c); +#else + HAL_I3C_CtrlRxCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + } + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handles controller multiple receive and transmit data in DMA mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_Multiple_Xfer_DMA_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that an Rx or Tx process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_BUSY_TX_RX) + { + /* I3C target frame complete event Check */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmacr) == 0U) + { + /* Check if all data bytes are received or transmitted */ + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmarx) == 0U) + { + if (I3C_GET_DMA_REMAIN_DATA(hi3c->hdmatx) == 0U) + { + /* Disable transfer Tx/Rx process interrupts */ + I3C_Disable_IRQ(hi3c, I3C_XFER_DMA); + + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Update the number of remaining data bytes */ + hi3c->RxXferCount = 0U; + + /* Update the number of remaining data bytes */ + hi3c->TxXferCount = 0U; + + /* Call controller transmit, receive complete callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1U) + hi3c->CtrlMultipleXferCpltCallback(hi3c); +#else + HAL_I3C_CtrlMultipleXferCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS == 1U */ + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_SIZE; + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + else + { + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + + /* Then Initiate a Start condition */ + LL_I3C_RequestTransfer(hi3c->Instance); + } + } + } + return HAL_OK; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Interrupt Sub-Routine which handles abort process in interrupt mode. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration information + * for the specified I3C. + * @param itMasks : [IN] Flag Interrupt Masks flags to handle. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Abort_ISR(struct __I3C_HandleTypeDef *hi3c, uint32_t itMasks) +{ + /* Check that an Abort process is ongoing */ + if (hi3c->State == HAL_I3C_STATE_ABORT) + { + /* I3C Rx FIFO not empty interrupt Check */ + if (I3C_CHECK_FLAG(itMasks, HAL_I3C_FLAG_RXFNEF) != RESET) + { + if (LL_I3C_IsActiveFlag_DOVR(hi3c->Instance) == 1U) + { + /* Flush remaining Rx data */ + LL_I3C_RequestRxFIFOFlush(hi3c->Instance); + } + } + + /* I3C Abort frame complete event Check */ + /* Evenif abort is called, the Frame completion can arrive if abort is requested at the end of the processus */ + /* Evenif completion occurs, treat this end of processus as abort completion process */ + if (I3C_CHECK_FLAG(itMasks, I3C_EVR_FCF) != RESET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Call error treatment function */ + I3C_ErrorTreatment(hi3c); + } + } + return HAL_OK; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief DMA I3C control transmit process complete callback. + * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA channel. + * @retval None + */ +static void I3C_DMAControlTransmitCplt(DMA_HandleTypeDef *hdma) +{ + /* Get the address of the I3C handle : Derogation MISRAC2012-Rule-11.5 */ + I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Disable control DMA Request */ + LL_I3C_DisableDMAReq_Control(hi3c->Instance); +} + +/** + * @brief DMA I3C transmit data process complete callback. + * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA channel. + * @retval None + */ +static void I3C_DMADataTransmitCplt(DMA_HandleTypeDef *hdma) +{ + /* Get the address of the I3C handle : Derogation MISRAC2012-Rule-11.5 */ + I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Disable Tx DMA Request */ + LL_I3C_DisableDMAReq_TX(hi3c->Instance); +} + +/** + * @brief DMA I3C receive data process complete callback. + * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA channel. + * @retval None + */ +static void I3C_DMADataReceiveCplt(DMA_HandleTypeDef *hdma) +{ + /* Get the address of the I3C handle : Derogation MISRAC2012-Rule-11.5 */ + I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Disable Rx DMA Request */ + LL_I3C_DisableDMAReq_RX(hi3c->Instance); +} + +/** + * @brief DMA I3C communication error callback. + * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA channel. + * @retval None + */ +static void I3C_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Just to solve MisraC error then to be removed */ + /* Derogation MISRAC2012-Rule-11.5 */ + I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + hi3c->ErrorCode |= HAL_I3C_ERROR_DMA; +} + +/** + * @brief DMA I3C communication abort callback to be called at end of DMA Abort procedure. + * @param hdma : [IN] Pointer to a DMA_HandleTypeDef structure that contains the configuration information + * for the specified DMA channel. + * @retval None + */ +static void I3C_DMAAbort(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + I3C_HandleTypeDef *hi3c = (I3C_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Reset Tx DMA AbortCpltCallback */ + if (hi3c->hdmatx != NULL) + { + hi3c->hdmatx->XferAbortCallback = NULL; + } + + /* Reset Rx DMA AbortCpltCallback */ + if (hi3c->hdmarx != NULL) + { + hi3c->hdmarx->XferAbortCallback = NULL; + } + + /* Reset control DMA AbortCpltCallback */ + if (hi3c->hdmacr != NULL) + { + hi3c->hdmacr->XferAbortCallback = NULL; + } + + I3C_TreatErrorCallback(hi3c); +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief This function handles I3C Communication Timeout. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param flag : [IN] Specifies the I3C flag to check. + * @param flagstatus : [IN] The new Flag status (SET or RESET). + * @param timeout : [IN] Timeout duration in millisecond. + * @param tickstart : [IN] Tick start value + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_WaitOnFlagUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t flag, FlagStatus flagstatus, + uint32_t timeout, uint32_t tickstart) +{ + HAL_StatusTypeDef status = HAL_OK; + + while ((__HAL_I3C_GET_FLAG(hi3c, flag) == flagstatus) && (status == HAL_OK)) + { + /* Check for the Timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + if (__HAL_I3C_GET_FLAG(hi3c, flag) == flagstatus) + { + hi3c->ErrorCode = HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + } + } + } + + /* Check if an error occurs during Flag waiting */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + status = HAL_ERROR; + } + } + return status; +} + +/** + * @brief This function handles I3C Dynamic Address Assignment timeout. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param timeout : [IN] Timeout duration in millisecond. + * @param tickstart : [IN] Tick start value + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_WaitOnDAAUntilTimeout(I3C_HandleTypeDef *hi3c, uint32_t timeout, uint32_t tickstart) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t active_flags = READ_REG(hi3c->Instance->EVR); + + while (((active_flags & (HAL_I3C_FLAG_FCF | HAL_I3C_FLAG_TXFNFF)) == 0U) && (status == HAL_OK)) + { + /* Check for the Timeout */ + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + if ((active_flags & (HAL_I3C_FLAG_FCF | HAL_I3C_FLAG_TXFNFF)) == 0U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + } + } + } + + /* Check if an error occurs during Flag waiting */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_ERRF) == SET) + { + /* Clear error flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + + /* Update handle error code parameter */ + I3C_GetErrorSources(hi3c); + + status = HAL_ERROR; + } + + /* Read active flags from EVR register */ + active_flags = READ_REG(hi3c->Instance->EVR); + } + return status; +} + +/** + * @brief I3C transmit by byte. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_TransmitByteTreatment(I3C_HandleTypeDef *hi3c) +{ + /* Check TX FIFO not full flag */ + while ((__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) && (hi3c->TxXferCount > 0U)) + { + /* Write Tx buffer data to transmit register */ + LL_I3C_TransmitData8(hi3c->Instance, *hi3c->pXferData->TxBuf.pBuffer); + + /* Increment Buffer pointer */ + hi3c->pXferData->TxBuf.pBuffer++; + + /* Decrement remaining bytes counter */ + hi3c->TxXferCount--; + } +} + +/** + * @brief I3C transmit by word. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_TransmitWordTreatment(I3C_HandleTypeDef *hi3c) +{ + /* Check TX FIFO not full flag */ + while (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_TXFNFF) == SET) + { + /* Write Tx buffer data to transmit register */ + LL_I3C_TransmitData32(hi3c->Instance, *((uint32_t *)hi3c->pXferData->TxBuf.pBuffer)); + + /* Increment Buffer pointer */ + hi3c->pXferData->TxBuf.pBuffer += sizeof(uint32_t); + + if (hi3c->TxXferCount < sizeof(uint32_t)) + { + hi3c->TxXferCount = 0U; + } + else + { + /* Decrement remaining bytes counter */ + hi3c->TxXferCount -= sizeof(uint32_t); + } + } +} + +/** + * @brief I3C receive by byte. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_ReceiveByteTreatment(I3C_HandleTypeDef *hi3c) +{ + /* Check RX FIFO not empty flag */ + while (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_RXFNEF) == SET) + { + /* Store received bytes in the Rx buffer */ + *hi3c->pXferData->RxBuf.pBuffer = LL_I3C_ReceiveData8(hi3c->Instance); + + /* Increment Buffer pointer */ + hi3c->pXferData->RxBuf.pBuffer++; + + /* Decrement remaining bytes counter */ + hi3c->RxXferCount--; + } +} + +/** + * @brief I3C receive by word. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_ReceiveWordTreatment(I3C_HandleTypeDef *hi3c) +{ + /* Check RX FIFO not empty flag */ + while (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_RXFNEF) == SET) + { + /* Store received bytes in the Rx buffer */ + *((uint32_t *)hi3c->pXferData->RxBuf.pBuffer) = LL_I3C_ReceiveData32(hi3c->Instance); + + /* Increment Buffer pointer */ + hi3c->pXferData->RxBuf.pBuffer += sizeof(uint32_t); + + if (hi3c->RxXferCount > sizeof(uint32_t)) + { + /* Decrement remaining bytes counter */ + hi3c->RxXferCount -= sizeof(uint32_t); + } + else + { + /* Reset counter as last modulo word Rx data received */ + hi3c->RxXferCount = 0U; + } + } +} + +/** + * @brief I3C Control data treatment. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_ControlDataTreatment(I3C_HandleTypeDef *hi3c) +{ + /* Check if Control FIFO requests data */ + if (__HAL_I3C_GET_FLAG(hi3c, HAL_I3C_FLAG_CFNFF) == SET) + { + /* Decrement remaining control buffer data counter */ + hi3c->ControlXferCount--; + + /* Write Control buffer data to control register */ + WRITE_REG(hi3c->Instance->CR, *hi3c->pXferData->CtrlBuf.pBuffer); + + /* Increment Buffer pointer */ + hi3c->pXferData->CtrlBuf.pBuffer++; + } +} + +/** + * @brief I3C state update. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_StateUpdate(I3C_HandleTypeDef *hi3c) +{ + /* Check on previous state */ + if (hi3c->PreviousState == HAL_I3C_STATE_LISTEN) + { + /* Set state to listen */ + hi3c->State = HAL_I3C_STATE_LISTEN; + + /* Check the I3C mode */ + if (hi3c->Mode == HAL_I3C_MODE_TARGET) + { + /* Store the target event treatment function */ + hi3c->XferISR = I3C_Tgt_Event_ISR; + } + else + { + /* Store the controller event treatment function */ + hi3c->XferISR = I3C_Ctrl_Event_ISR; + } + } + else + { + /* Set state to ready */ + hi3c->State = HAL_I3C_STATE_READY; + + /* Reset XferISR */ + hi3c->XferISR = NULL; + } +} + +/** + * @brief I3C get error source. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_GetErrorSources(I3C_HandleTypeDef *hi3c) +{ + /* Check on the I3C mode */ + switch (hi3c->Mode) + { + case HAL_I3C_MODE_CONTROLLER: + { + /* I3C data error during controller-role hand-off procedure */ + if (LL_I3C_IsActiveFlag_DERR(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_DATA_HAND_OFF; + } + + /* I3C data not acknowledged error */ + if (LL_I3C_IsActiveFlag_DNACK(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_DATA_NACK; + } + + /* I3C address not acknowledged error */ + if (LL_I3C_IsActiveFlag_ANACK(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_ADDRESS_NACK; + } + + /* I3C Status FIFO Over-Run or Control FIFO Under-Run error */ + if (LL_I3C_IsActiveFlag_COVR(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_COVR; + } + + break; + } + + case HAL_I3C_MODE_TARGET: + { + /* I3C SCL stall error */ + if (LL_I3C_IsActiveFlag_STALL(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_STALL; + } + + break; + } + + default: + { + break; + } + } + + /* I3C Rx FIFO Over-Run or Tx FIFO Under-Run error */ + if (LL_I3C_IsActiveFlag_DOVR(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= HAL_I3C_ERROR_DOVR; + } + + /* I3C Protocol error */ + if (LL_I3C_IsActiveFlag_PERR(hi3c->Instance) == 1U) + { + hi3c->ErrorCode |= (I3C_SER_PERR | LL_I3C_GetMessageErrorCode(hi3c->Instance)); + } +} + +/** + * @brief I3C transfer prior preparation. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param counter : [IN] Number of devices or commands to treat. + * @param option : [IN] Parameter indicates the transfer option. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Xfer_PriorPreparation(I3C_HandleTypeDef *hi3c, uint8_t counter, uint32_t option) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t current_tx_index = 0U; + uint32_t global_tx_size = 0U; + uint32_t global_rx_size = 0U; + uint32_t nb_tx_frame = 0U; + uint32_t direction; + + for (uint32_t descr_index = 0U; descr_index < counter; descr_index++) + { + /* Direct CCC command */ + if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_DIRECT) + { + /* Update direction of frame */ + direction = hi3c->pCCCDesc[descr_index].Direction; + + /* Direction read with Define byte */ + if (((option & I3C_DEFINE_BYTE_MASK) != 0U) && (direction == HAL_I3C_DIRECTION_READ)) + { + nb_tx_frame += 1U; + + global_tx_size += 1U; + + global_rx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size - 1U; + + /* Check on the global size and on the Tx buffer pointer */ + if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ + (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ + (hi3c->pXferData->TxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + + status = HAL_ERROR; + } + else + { + /* Fill global Tx buffer with data and update the current index of the Tx buffer */ + current_tx_index = I3C_FillTxBuffer_CCC(hi3c, descr_index, 1U, current_tx_index); + } + } + else if (direction == HAL_I3C_DIRECTION_WRITE) + { + nb_tx_frame += 1U; + + global_tx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size; + + /* Check on the global size and on the Tx buffer pointer */ + if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ + (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ + (hi3c->pXferData->TxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + + status = HAL_ERROR; + } + else + { + /* Fill global Tx buffer with data and update the current index of the Tx buffer */ + current_tx_index = I3C_FillTxBuffer_CCC(hi3c, + descr_index, + hi3c->pCCCDesc[descr_index].CCCBuf.Size, + current_tx_index); + } + } + /* Direction read without Define byte */ + else + { + global_rx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size; + } + } + /* Broadcast CCC command */ + else if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_CCC) + { + /* Update direction of frame */ + direction = hi3c->pCCCDesc[descr_index].Direction; + + if (direction == HAL_I3C_DIRECTION_WRITE) + { + nb_tx_frame += 1U; + + global_tx_size += hi3c->pCCCDesc[descr_index].CCCBuf.Size; + + /* Check on the global size and on the Tx buffer pointer */ + if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ + (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ + (hi3c->pXferData->TxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + + status = HAL_ERROR; + } + else + { + /* Fill global Tx buffer with data and update the current index of the Tx buffer */ + current_tx_index = I3C_FillTxBuffer_CCC(hi3c, + descr_index, + hi3c->pCCCDesc[descr_index].CCCBuf.Size, + current_tx_index); + } + } + else + { + status = HAL_ERROR; + } + } + /* Private */ + else + { + /* Update direction of frame */ + direction = hi3c->pPrivateDesc[descr_index].Direction; + + if (direction == HAL_I3C_DIRECTION_WRITE) + { + nb_tx_frame += 1U; + + global_tx_size += hi3c->pPrivateDesc[descr_index].TxBuf.Size; + + /* Check on the global size and on the Tx buffer pointer */ + if ((global_tx_size > hi3c->pXferData->TxBuf.Size) || \ + (current_tx_index > hi3c->pXferData->TxBuf.Size) || \ + (hi3c->pXferData->TxBuf.pBuffer == NULL)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + + status = HAL_ERROR; + } + else + { + /* Fill global Tx buffer with data and update the current index of the Tx buffer */ + current_tx_index = I3C_FillTxBuffer_Private(hi3c, + descr_index, + hi3c->pPrivateDesc[descr_index].TxBuf.Size, + current_tx_index); + } + } + else + { + global_rx_size += hi3c->pPrivateDesc[descr_index].RxBuf.Size; + } + } + + /* Check if there is an error in the Tx Buffer*/ + if (status == HAL_ERROR) + { + break; + } + } + + if (status == HAL_OK) + { + /* Check on the Tx threshold and the number of Tx frame */ + if (LL_I3C_GetTxFIFOThreshold(hi3c->Instance) == LL_I3C_TXFIFO_THRESHOLD_4_4) + { + /* LL_I3C_TXFIFO_THRESHOLD_4_4 is not allowed when the transfer descriptor contains + multiple transmission frames */ + if (nb_tx_frame > 1U) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + } + } + + if (status == HAL_OK) + { + /* Check on the size Rx buffer */ + if (global_rx_size > hi3c->pXferData->RxBuf.Size) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + hi3c->RxXferCount = global_rx_size; + } + + /* Set handle transfer parameters */ + hi3c->TxXferCount = global_tx_size; + } + + return status; +} + +/** + * @brief I3C fill Tx Buffer with data from CCC Descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param indexDesc : [IN] Index of descriptor. + * @param txSize : [IN] Size of Tx data. + * @param txCurrentIndex : [IN] Current Index of TxBuffer. + * @retval index_tx : [OUT] New current Index of TxBuffer. + */ +static uint32_t I3C_FillTxBuffer_CCC(I3C_HandleTypeDef *hi3c, + uint32_t indexDesc, + uint32_t txSize, + uint32_t txCurrentIndex) +{ + uint32_t index_tx = txCurrentIndex; + + for (uint32_t index = 0U; index < txSize; index++) + { + hi3c->pXferData->TxBuf.pBuffer[index_tx] = hi3c->pCCCDesc[indexDesc].CCCBuf.pBuffer[index]; + + index_tx++; + } + + return index_tx; +} + +/** + * @brief I3C fill Tx Buffer with data from Private Descriptor. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param indexDesc : [IN] Index of descriptor. + * @param txSize : [IN] Size of Tx data. + * @param txCurrentIndex : [IN] Current Index of TxBuffer. + * @retval index_tx : [OUT] New current Index of TxBuffer. + */ +static uint32_t I3C_FillTxBuffer_Private(I3C_HandleTypeDef *hi3c, + uint32_t indexDesc, + uint32_t txSize, + uint32_t txCurrentIndex) +{ + uint32_t index_tx = txCurrentIndex; + + for (uint32_t index = 0U; index < txSize; index++) + { + hi3c->pXferData->TxBuf.pBuffer[index_tx] = hi3c->pPrivateDesc[indexDesc].TxBuf.pBuffer[index]; + + index_tx++; + } + + return index_tx; +} + +/** + * @brief I3C Control buffer prior preparation. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param counter : [IN] Number of devices or commands to treat. + * @param option : [IN] Parameter indicates the transfer option. + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_ControlBuffer_PriorPreparation(I3C_HandleTypeDef *hi3c, + uint8_t counter, + uint32_t option) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t nb_define_bytes; + uint32_t stop_condition; + uint32_t nb_data_bytes; + uint32_t index; + + /* Check on the control buffer pointer */ + if (hi3c->pXferData->CtrlBuf.pBuffer == NULL) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Extract from option required information */ + nb_define_bytes = (option & I3C_DEFINE_BYTE_MASK); + stop_condition = (option & I3C_RESTART_STOP_MASK); + + /* Check on the deactivation of the arbitration */ + if ((option & I3C_ARBITRATION_HEADER_MASK) == I3C_ARBITRATION_HEADER_MASK) + { + /* Disable arbitration header */ + LL_I3C_DisableArbitrationHeader(hi3c->Instance); + } + else + { + /* Enable arbitration header */ + LL_I3C_EnableArbitrationHeader(hi3c->Instance); + } + + /* Check on the operation type */ + if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_CCC) + { + /*------------------------------------------ Broadcast CCC -----------------------------------------------------*/ + /* Check on the control buffer size */ + if (hi3c->pXferData->CtrlBuf.Size < (uint32_t)counter) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Set remaining control buffer data counter */ + hi3c->ControlXferCount = (uint32_t)counter; + + /* For loop on the number of commands */ + for (index = 0U; index < ((uint32_t)counter - 1U); index++) + { + /* Update control buffer value */ + hi3c->pXferData->CtrlBuf.pBuffer[index] = ((uint32_t)hi3c->pCCCDesc[index].CCCBuf.Size | + ((uint32_t)hi3c->pCCCDesc[index].CCC << I3C_CR_CCC_Pos) | + LL_I3C_CONTROLLER_MTYPE_CCC | stop_condition); + } + + /* At the last device we should generate a stop condition */ + hi3c->pXferData->CtrlBuf.pBuffer[index] = ((uint32_t)hi3c->pCCCDesc[index].CCCBuf.Size | + ((uint32_t)hi3c->pCCCDesc[index].CCC << I3C_CR_CCC_Pos) | + LL_I3C_CONTROLLER_MTYPE_CCC | LL_I3C_GENERATE_STOP); + } + } + else if ((option & I3C_OPERATION_TYPE_MASK) == LL_I3C_CONTROLLER_MTYPE_DIRECT) + { + /*------------------------------------------ Direct CCC --------------------------------------------------------*/ + /* Check on the control buffer size */ + if (hi3c->pXferData->CtrlBuf.Size < ((uint32_t)counter * 2U)) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Set remaining control buffer data counter */ + hi3c->ControlXferCount = ((uint32_t)counter * 2U); + + /* For loop on the number of (devices or commands) * 2 */ + for (index = 0U; index < (((uint32_t)counter * 2U) - 2U); index += 2U) + { + /* Step 1 : update control buffer value for the CCC command */ + hi3c->pXferData->CtrlBuf.pBuffer[index] = (nb_define_bytes | + ((uint32_t)hi3c->pCCCDesc[index / 2U].CCC << I3C_CR_CCC_Pos) | + LL_I3C_CONTROLLER_MTYPE_CCC | LL_I3C_GENERATE_RESTART); + + /* Step 2 : update control buffer value for target address */ + hi3c->pXferData->CtrlBuf.pBuffer[index + 1U] = + (((uint32_t)hi3c->pCCCDesc[index / 2U].CCCBuf.Size - nb_define_bytes) | + hi3c->pCCCDesc[index / 2U].Direction | + ((uint32_t)hi3c->pCCCDesc[index / 2U].TargetAddr << I3C_CR_ADD_Pos) | + LL_I3C_CONTROLLER_MTYPE_DIRECT | stop_condition); + } + + /* Update control buffer value for the last CCC command */ + hi3c->pXferData->CtrlBuf.pBuffer[index] = (nb_define_bytes | + ((uint32_t)hi3c->pCCCDesc[index / 2U].CCC << I3C_CR_CCC_Pos) | + LL_I3C_CONTROLLER_MTYPE_CCC | LL_I3C_GENERATE_RESTART); + + /* At the last device we should generate a stop condition */ + hi3c->pXferData->CtrlBuf.pBuffer[index + 1U] = + (((uint32_t)hi3c->pCCCDesc[index / 2U].CCCBuf.Size - nb_define_bytes) | + hi3c->pCCCDesc[index / 2U].Direction | + ((uint32_t)hi3c->pCCCDesc[index / 2U].TargetAddr << I3C_CR_ADD_Pos) | + LL_I3C_CONTROLLER_MTYPE_DIRECT | LL_I3C_GENERATE_STOP); + } + } + else + { + /*------------------------------------------ Private I3C/I2C ---------------------------------------------------*/ + /* Check on the control buffer size */ + if (hi3c->pXferData->CtrlBuf.Size < (uint32_t)counter) + { + hi3c->ErrorCode = HAL_I3C_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + /* Set remaining control buffer data counter */ + hi3c->ControlXferCount = (uint32_t)counter; + + /* For loop on the number of devices */ + for (index = 0U; index < ((uint32_t)counter - 1U); index++) + { + /* Check on transfer direction */ + if (hi3c->pPrivateDesc[index].Direction == HAL_I3C_DIRECTION_READ) + { + nb_data_bytes = hi3c->pPrivateDesc[index].RxBuf.Size; + } + else + { + nb_data_bytes = hi3c->pPrivateDesc[index].TxBuf.Size; + } + + /* Update control buffer value */ + hi3c->pXferData->CtrlBuf.pBuffer[index] = + (nb_data_bytes | hi3c->pPrivateDesc[index].Direction | + ((uint32_t)hi3c->pPrivateDesc[index].TargetAddr << I3C_CR_ADD_Pos) | + (option & I3C_OPERATION_TYPE_MASK) | stop_condition); + } + + /* Check on transfer direction */ + if (hi3c->pPrivateDesc[index].Direction == HAL_I3C_DIRECTION_READ) + { + nb_data_bytes = hi3c->pPrivateDesc[index].RxBuf.Size; + } + else + { + nb_data_bytes = hi3c->pPrivateDesc[index].TxBuf.Size; + } + + /* At the last device we should generate a stop condition */ + hi3c->pXferData->CtrlBuf.pBuffer[index] = + (nb_data_bytes | hi3c->pPrivateDesc[index].Direction | + ((uint32_t)hi3c->pPrivateDesc[index].TargetAddr << I3C_CR_ADD_Pos) | + (option & I3C_OPERATION_TYPE_MASK) | LL_I3C_GENERATE_STOP); + } + } + } + + return status; +} + +/** + * @brief Check if target device is ready for communication. + * @param hi3c : Pointer to a I3C_HandleTypeDef structure that contains + * the configuration information for the specified I3C. + * @param pDevice : [IN] Structure to define the device address and the device type. + * @param trials : [IN] Number of trials + * @param timeout : [IN] Timeout duration + * @retval HAL Status : Value from HAL_StatusTypeDef enumeration. + */ +static HAL_StatusTypeDef I3C_Ctrl_IsDevice_Ready(I3C_HandleTypeDef *hi3c, + const I3C_DeviceTypeDef *pDevice, + uint32_t trials, + uint32_t timeout) +{ + __IO uint32_t I3C_Trials = 0UL; + __IO uint32_t exit_condition; + uint32_t CR_tmp; + uint32_t tickstart; + HAL_StatusTypeDef status = HAL_OK; + HAL_I3C_StateTypeDef handle_state; + uint32_t arbitration_previous_state; + + /* Get I3C handle state */ + handle_state = hi3c->State; + + /* check on the Mode */ + if (hi3c->Mode != HAL_I3C_MODE_CONTROLLER) + { + hi3c->ErrorCode = HAL_I3C_ERROR_NOT_ALLOWED; + status = HAL_ERROR; + } + /* check on the State */ + else if ((handle_state != HAL_I3C_STATE_READY) && (handle_state != HAL_I3C_STATE_LISTEN)) + { + status = HAL_BUSY; + } + else + { + /* Set handle transfer parameters */ + hi3c->ErrorCode = HAL_I3C_ERROR_NONE; + hi3c->State = HAL_I3C_STATE_BUSY; + + /* Before modify the arbitration, get the current arbitration state */ + arbitration_previous_state = LL_I3C_IsEnabledArbitrationHeader(hi3c->Instance); + + /* Disable arbitration header */ + LL_I3C_DisableArbitrationHeader(hi3c->Instance); + + CR_tmp = (HAL_I3C_DIRECTION_WRITE | + ((uint32_t)pDevice->Address << I3C_CR_ADD_Pos) | + pDevice->MessageType | LL_I3C_GENERATE_STOP); + + do + { + /* Initiate a start condition by writing in the CR register */ + WRITE_REG(hi3c->Instance->CR, CR_tmp); + + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + + tickstart = HAL_GetTick(); + + while (exit_condition == 0U) + { + if (timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > timeout) || (timeout == 0U)) + { + /* Update I3C error code */ + hi3c->ErrorCode |= HAL_I3C_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + + break; + } + } + /* Calculate exit_condition value based on Frame complete and error flags */ + exit_condition = (READ_REG(hi3c->Instance->EVR) & (I3C_EVR_FCF | I3C_EVR_ERRF)); + } + + if (status == HAL_OK) + { + /* Check if the FCF flag has been set */ + if (__HAL_I3C_GET_FLAG(hi3c, I3C_EVR_FCF) == SET) + { + /* Clear frame complete flag */ + LL_I3C_ClearFlag_FC(hi3c->Instance); + + /* Device is ready */ + break; + } + else + { + /* Clear ERR flag */ + LL_I3C_ClearFlag_ERR(hi3c->Instance); + } + } + + /* Increment Trials */ + I3C_Trials++; + + } while ((I3C_Trials < trials) && (status == HAL_OK)); + + /* Device is not ready */ + if (trials == I3C_Trials) + { + hi3c->ErrorCode = HAL_I3C_ERROR_ADDRESS_NACK; + status = HAL_ERROR; + } + + /* update state to Previous state */ + I3C_StateUpdate(hi3c); + + /* Check if previous arbitration state is enabled */ + if (arbitration_previous_state == 1U) + { + LL_I3C_EnableArbitrationHeader(hi3c->Instance); + } + } + + return status; +} + +/** + * @brief Manage the enabling of Interrupts. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param InterruptRequest : [IN] Value of the interrupt request + * @retval None + */ +static void I3C_Enable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest) +{ + uint32_t tmpisr = 0U; + + /* Check if requested interrupts are related to listening mode */ + if ((InterruptRequest & I3C_XFER_LISTEN_IT) != 0U) + { + tmpisr |= ((InterruptRequest & (~I3C_XFER_LISTEN_IT)) | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target transmit in IT mode */ + if ((InterruptRequest & I3C_XFER_TARGET_TX_IT) != 0U) + { + /* Enable frame complete, transmit FIFO not full and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target receive in IT mode */ + if ((InterruptRequest & I3C_XFER_TARGET_RX_IT) != 0U) + { + /* Enable frame complete, receive FIFO not empty and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE) ; + } + + /* Check if requested interrupts are related to transmit/receive in DMA mode */ + if ((InterruptRequest & I3C_XFER_DMA) != 0U) + { + /* Enable frame complete and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target hot join */ + if ((InterruptRequest & I3C_XFER_TARGET_HOTJOIN) != 0U) + { + /* Enable dynamic address update and error interrupts */ + tmpisr |= (HAL_I3C_IT_DAUPDIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target control role */ + if ((InterruptRequest & I3C_XFER_TARGET_CTRLROLE) != 0U) + { + /* Enable control role update and error interrupts */ + tmpisr |= (HAL_I3C_IT_CRUPDIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target in band interrupt */ + if ((InterruptRequest & I3C_XFER_TARGET_IBI) != 0U) + { + /* Enable IBI end and error interrupts */ + tmpisr |= (HAL_I3C_IT_IBIENDIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller transmit in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_TX_IT) != 0U) + { + /* Enable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller receive in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_RX_IT) != 0U) + { + /* Enable frame complete, control FIFO not full, receive FIFO not empty and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller transmit read or a broadcast CCC in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_RX_CCC_IT) != 0U) + { + /* Enable frame complete, transmit FIFO not full, control FIFO not full, + receive FIFO not empty and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller transmit broadcast ENTDAA CCC in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_DAA_IT) != 0U) + { + /* Enable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); + } + + /* Enable requested interrupts */ + __HAL_I3C_ENABLE_IT(hi3c, tmpisr); +} + +/** + * @brief Manage the disabling of Interrupts. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @param InterruptRequest : [IN] Value of the interrupt request + * @retval None + */ +static void I3C_Disable_IRQ(I3C_HandleTypeDef *hi3c, uint32_t InterruptRequest) +{ + uint32_t tmpisr = 0U; + + /* Check if requested interrupts are related to listening mode */ + if ((InterruptRequest & I3C_XFER_LISTEN_IT) != 0U) + { + tmpisr |= ((InterruptRequest & (~I3C_XFER_LISTEN_IT)) | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target transmit mode */ + if ((InterruptRequest & I3C_XFER_TARGET_TX_IT) != 0U) + { + /* Disable frame complete, transmit FIFO not full and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target receive mode */ + if ((InterruptRequest & I3C_XFER_TARGET_RX_IT) != 0U) + { + /* Disable frame complete, receive FIFO not empty and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to transmit/receive in DMA mode */ + if ((InterruptRequest & I3C_XFER_DMA) != 0U) + { + /* Disable frame complete and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target hot join */ + if ((InterruptRequest & I3C_XFER_TARGET_HOTJOIN) != 0U) + { + /* Disable dynamic address update and error interrupts */ + tmpisr |= (HAL_I3C_IT_DAUPDIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target control role */ + if ((InterruptRequest & I3C_XFER_TARGET_CTRLROLE) != 0U) + { + /* Disable control role update and error interrupts */ + tmpisr |= (HAL_I3C_IT_CRUPDIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to target in band interrupt */ + if ((InterruptRequest & I3C_XFER_TARGET_IBI) != 0U) + { + /* Disable IBI end and error interrupts */ + tmpisr |= (HAL_I3C_IT_IBIENDIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller transmit in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_TX_IT) != 0U) + { + /* Disable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller transmit read or a broadcast CCC in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_RX_CCC_IT) != 0U) + { + /* Disable frame complete, transmit FIFO not full, control FIFO not full, + receive FIFO not empty and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_RXFNEIE | HAL_I3C_IT_ERRIE); + } + + /* Check if requested interrupts are related to controller transmit broadcast ENTDAA CCC in IT mode */ + if ((InterruptRequest & I3C_XFER_CONTROLLER_DAA_IT) != 0U) + { + /* Disable frame complete, control FIFO not full, transmit FIFO not full and error interrupts */ + tmpisr |= (HAL_I3C_IT_FCIE | HAL_I3C_IT_CFNFIE | HAL_I3C_IT_TXFNFIE | HAL_I3C_IT_ERRIE); + } + + /* Disable requested interrupts */ + __HAL_I3C_DISABLE_IT(hi3c, tmpisr); +} + +/** + * @brief I3C error treatment. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_ErrorTreatment(I3C_HandleTypeDef *hi3c) +{ + HAL_I3C_StateTypeDef tmpstate = hi3c->State; + uint32_t dmaabortongoing = 0U; + + /* Check on the state */ + if (tmpstate == HAL_I3C_STATE_BUSY) + { + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + /* Disable all interrupts related to busy state */ + I3C_Disable_IRQ(hi3c, (I3C_XFER_TARGET_IBI | I3C_XFER_TARGET_HOTJOIN | I3C_XFER_TARGET_CTRLROLE)); + } + else + { + /* Disable all interrupts related to busy Tx and Rx state */ + I3C_Disable_IRQ(hi3c, I3C_XFER_CONTROLLER_RX_CCC_IT); + + /* Reset Tx counter */ + hi3c->TxXferCount = 0U; + + /* Reset Rx counter */ + hi3c->RxXferCount = 0U; + + /* Reset Control counter */ + hi3c->ControlXferCount = 0U; + + /* Reset Tx function pointer */ + hi3c->ptrTxFunc = NULL; + + /* Reset Rx function pointer */ + hi3c->ptrRxFunc = NULL; + + /* Reset Context pointer */ + hi3c->pXferData = NULL; + hi3c->pCCCDesc = NULL; + hi3c->pPrivateDesc = NULL; + + /* Flush all FIFOs */ + /* Flush the content of Tx Fifo */ + LL_I3C_RequestTxFIFOFlush(hi3c->Instance); + + /* Flush the content of Rx Fifo */ + LL_I3C_RequestRxFIFOFlush(hi3c->Instance); + + /* Check on the I3C mode: Control and status FIFOs available only with controller mode */ + if (hi3c->Mode == HAL_I3C_MODE_CONTROLLER) + { + /* Flush the content of Control Fifo */ + LL_I3C_RequestControlFIFOFlush(hi3c->Instance); + + /* Flush the content of Status Fifo */ + LL_I3C_RequestStatusFIFOFlush(hi3c->Instance); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort control DMA transfer if any */ + if (hi3c->hdmacr != NULL) + { + /* Disable control DMA Request */ + LL_I3C_DisableDMAReq_Control(hi3c->Instance); + + /* Check DMA state */ + if (HAL_DMA_GetState(hi3c->hdmacr) != HAL_DMA_STATE_READY) + { + /* Set the I3C DMA Abort callback : will lead to call HAL_I3C_AbortCpltCallback() + at end of DMA abort procedure */ + + /* DMA abort on going */ + dmaabortongoing = 1U; + + /* Abort control DMA */ + if (HAL_DMA_Abort_IT(hi3c->hdmacr) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi3c->hdmacr->XferAbortCallback(hi3c->hdmacr); + } + } + } + + /* Abort RX DMA transfer if any */ + if (hi3c->hdmarx != NULL) + { + /* Disable Rx DMA Request */ + LL_I3C_DisableDMAReq_RX(hi3c->Instance); + + /* Check DMA state */ + if (HAL_DMA_GetState(hi3c->hdmarx) != HAL_DMA_STATE_READY) + { + /* Set the I3C DMA Abort callback : will lead to call HAL_I3C_AbortCpltCallback() + at end of DMA abort procedure */ + hi3c->hdmarx->XferAbortCallback = I3C_DMAAbort; + + /* DMA abort on going */ + dmaabortongoing = 1U; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hi3c->hdmarx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi3c->hdmarx->XferAbortCallback(hi3c->hdmarx); + } + } + } + + /* Abort TX DMA transfer if any */ + if (hi3c->hdmatx != NULL) + { + /* Disable Tx DMA Request */ + LL_I3C_DisableDMAReq_TX(hi3c->Instance); + + /* Check DMA state */ + if (HAL_DMA_GetState(hi3c->hdmatx) != HAL_DMA_STATE_READY) + { + /* Set the I3C DMA Abort callback : will lead to call HAL_I3C_AbortCpltCallback() + at end of DMA abort procedure */ + hi3c->hdmatx->XferAbortCallback = I3C_DMAAbort; + + /* DMA abort on going */ + dmaabortongoing = 1U; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hi3c->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hi3c->hdmatx->XferAbortCallback(hi3c->hdmatx); + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + } + + /* Call Error callback if there is no DMA abort on going */ + if (dmaabortongoing == 0U) + { + I3C_TreatErrorCallback(hi3c); + } +} + +/** + * @brief I3C Error callback treatment. + * @param hi3c : [IN] Pointer to an I3C_HandleTypeDef structure that contains the configuration + * information for the specified I3C. + * @retval None + */ +static void I3C_TreatErrorCallback(I3C_HandleTypeDef *hi3c) +{ + if (hi3c->State == HAL_I3C_STATE_ABORT) + { + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1) + hi3c->AbortCpltCallback(hi3c); +#else + HAL_I3C_AbortCpltCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ + } + else + { + /* Update handle state parameter */ + I3C_StateUpdate(hi3c); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_I3C_REGISTER_CALLBACKS == 1) + hi3c->ErrorCallback(hi3c); +#else + HAL_I3C_ErrorCallback(hi3c); +#endif /* USE_HAL_I3C_REGISTER_CALLBACKS */ + } +} + +/** + * @} + */ + +#endif /* HAL_I3C_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_icache.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_icache.c index 984e94337..e46b8a057 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_icache.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_icache.c @@ -1,512 +1,512 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_icache.c - * @author MCD Application Team - * @brief ICACHE HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Instruction Cache (ICACHE). - * + Initialization and Configuration - * + Invalidate functions - * + Monitoring management - * + Memory address remap management - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### ICACHE main features ##### - ============================================================================== - [..] - The Texture Cache (ICACHE) is introduced on AXI read-only texture port of - the GPU2D to improve performance when reading texture data from internal and - external memories. - - =============================================================================== - ##### How to use this driver ##### - =============================================================================== - [..] - The ICACHE HAL driver can be used as follows: - - (#) Optionally configure the Instruction Cache mode with - HAL_ICACHE_ConfigAssociativityMode() if the default configuration - does not suit the application requirements. - - (#) Enable and disable the Instruction Cache with respectively - HAL_ICACHE_Enable() and HAL_ICACHE_Disable(). - Use HAL_ICACHE_IsEnabled() to get the Instruction Cache status. - To ensure a deterministic cache behavior after power on, system reset or after - a call to @ref HAL_ICACHE_Disable(), the application must call - @ref HAL_ICACHE_WaitForInvalidateComplete(). Indeed on power on, system reset - or cache disable, an automatic cache invalidation procedure is launched and the - cache is bypassed until the operation completes. - - (#) Initiate the cache maintenance invalidation procedure with either - HAL_ICACHE_Invalidate() (blocking mode) or HAL_ICACHE_Invalidate_IT() - (interrupt mode). When interrupt mode is used, the callback function - HAL_ICACHE_InvalidateCompleteCallback() is called when the invalidate - procedure is complete. The function HAL_ICACHE_WaitForInvalidateComplete() - may be called to wait for the end of the invalidate procedure automatically - initiated when disabling the Instruction Cache with HAL_ICACHE_Disable(). - The cache operation is bypassed during the invalidation procedure. - - (#) Use the performance monitoring counters for Hit and Miss with the following - functions: HAL_ICACHE_Monitor_Start(), HAL_ICACHE_Monitor_Stop(), - HAL_ICACHE_Monitor_Reset(), HAL_ICACHE_Monitor_GetHitValue() and - HAL_ICACHE_Monitor_GetMissValue() - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup ICACHE ICACHE - * @brief HAL ICACHE module driver - * @{ - */ -#if defined(ICACHE) && defined (HAL_ICACHE_MODULE_ENABLED) - -/* Private typedef -----------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup ICACHE_Private_Constants ICACHE Private Constants - * @{ - */ -#define ICACHE_INVALIDATE_TIMEOUT_VALUE 1U /* 1ms */ -#define ICACHE_DISABLE_TIMEOUT_VALUE 1U /* 1ms */ - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup ICACHE_Private_Macros ICACHE Private Macros - * @{ - */ - -#define IS_ICACHE_ASSOCIATIVITY_MODE(__MODE__) (((__MODE__) == ICACHE_1WAY) || \ - ((__MODE__) == ICACHE_4WAYS)) - -#define IS_ICACHE_MONITOR_TYPE(__TYPE__) (((__TYPE__) == ICACHE_MONITOR_HIT_MISS) || \ - ((__TYPE__) == ICACHE_MONITOR_HIT) || \ - ((__TYPE__) == ICACHE_MONITOR_MISS)) - -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup ICACHE_Exported_Functions ICACHE Exported Functions - * @{ - */ - -/** @defgroup ICACHE_Exported_Functions_Group1 Initialization and control functions - * @brief Initialization and control functions - * - @verbatim - ============================================================================== - ##### Initialization and control functions ##### - ============================================================================== - [..] - This section provides functions allowing to initialize and control the - Instruction Cache (mode, invalidate procedure, performance counters). - @endverbatim - * @{ - */ - -/** - * @brief Configure the Instruction Cache cache associativity mode selection. - * @param AssociativityMode Associativity mode selection - * This parameter can be one of the following values: - * @arg ICACHE_1WAY 1-way cache (direct mapped cache) - * @arg ICACHE_4WAYS 4-ways set associative cache (default) - * @retval HAL status (HAL_OK/HAL_ERROR) - */ -HAL_StatusTypeDef HAL_ICACHE_ConfigAssociativityMode(uint32_t AssociativityMode) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_ICACHE_ASSOCIATIVITY_MODE(AssociativityMode)); - - /* Check cache is not enabled */ - if (READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) - { - status = HAL_ERROR; - } - else - { - MODIFY_REG(ICACHE->CR, ICACHE_CR_WAYSEL, AssociativityMode); - } - - return status; -} - -/** - * @brief DeInitialize the Instruction Cache. - * @retval HAL status (HAL_OK) - */ -HAL_StatusTypeDef HAL_ICACHE_DeInit(void) -{ - /* Reset interrupt enable value */ - WRITE_REG(ICACHE->IER, 0U); - - /* Clear any pending flags */ - WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF | ICACHE_FCR_CERRF); - - /* Disable cache then set default associative mode value */ - CLEAR_BIT(ICACHE->CR, ICACHE_CR_EN); - WRITE_REG(ICACHE->CR, ICACHE_CR_WAYSEL); - - /* Stop monitor and reset monitor values */ - CLEAR_BIT(ICACHE->CR, ICACHE_MONITOR_HIT_MISS); - SET_BIT(ICACHE->CR, (ICACHE_MONITOR_HIT_MISS << 2U)); - CLEAR_BIT(ICACHE->CR, (ICACHE_MONITOR_HIT_MISS << 2U)); - - - return HAL_OK; -} - -/** - * @brief Enable the Instruction Cache. - * @note This function always returns HAL_OK even if there is any ongoing - * cache operation. The Instruction Cache is bypassed until the - * cache operation completes. - * @retval HAL status (HAL_OK) - */ -HAL_StatusTypeDef HAL_ICACHE_Enable(void) -{ - SET_BIT(ICACHE->CR, ICACHE_CR_EN); - - return HAL_OK; -} - -/** - * @brief Disable the Instruction Cache. - * @note This function waits for the cache being disabled but - * not for the end of the automatic cache invalidation procedure. - * @retval HAL status (HAL_OK/HAL_TIMEOUT) - */ -HAL_StatusTypeDef HAL_ICACHE_Disable(void) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tickstart; - - /* Make sure BSYENDF is reset before to disable the instruction cache */ - /* as it automatically starts a cache invalidation procedure */ - WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); - - CLEAR_BIT(ICACHE->CR, ICACHE_CR_EN); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait for instruction cache being disabled */ - while (READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) - { - if ((HAL_GetTick() - tickstart) > ICACHE_DISABLE_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) - { - status = HAL_TIMEOUT; - break; - } - } - } - - return status; -} - -/** - * @brief Check whether the Instruction Cache is enabled or not. - * @retval Status (0: disabled, 1: enabled) - */ -uint32_t HAL_ICACHE_IsEnabled(void) -{ - return ((READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) ? 1UL : 0UL); -} - -/** - * @brief Invalidate the Instruction Cache. - * @note This function waits for the end of cache invalidation procedure - * and clears the associated BSYENDF flag. - * @retval HAL status (HAL_OK/HAL_ERROR/HAL_TIMEOUT) - */ -HAL_StatusTypeDef HAL_ICACHE_Invalidate(void) -{ - HAL_StatusTypeDef status; - - /* Check if no ongoing operation */ - if (READ_BIT(ICACHE->SR, ICACHE_SR_BUSYF) == 0U) - { - /* Launch cache invalidation */ - SET_BIT(ICACHE->CR, ICACHE_CR_CACHEINV); - } - - status = HAL_ICACHE_WaitForInvalidateComplete(); - - return status; -} - -/** - * @brief Invalidate the Instruction Cache with interrupt. - * @note This function launches cache invalidation and returns. - * User application shall resort to interrupt generation to check - * the end of the cache invalidation with the BSYENDF flag and the - * HAL_ICACHE_InvalidateCompleteCallback() callback. - * @retval HAL status (HAL_OK/HAL_ERROR) - */ -HAL_StatusTypeDef HAL_ICACHE_Invalidate_IT(void) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check no ongoing operation */ - if (READ_BIT(ICACHE->SR, ICACHE_SR_BUSYF) != 0U) - { - status = HAL_ERROR; - } - else - { - /* Make sure BSYENDF is reset before to start cache invalidation */ - WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); - - /* Enable end of cache invalidation interrupt */ - SET_BIT(ICACHE->IER, ICACHE_IER_BSYENDIE); - - /* Launch cache invalidation */ - SET_BIT(ICACHE->CR, ICACHE_CR_CACHEINV); - } - - return status; -} - -/** - * @brief Wait for the end of the Instruction Cache invalidate procedure. - * @note This function checks and clears the BSYENDF flag when set. - * @retval HAL status (HAL_OK/HAL_TIMEOUT) - */ -HAL_StatusTypeDef HAL_ICACHE_WaitForInvalidateComplete(void) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tickstart; - - /* Check if ongoing invalidation operation */ - if (READ_BIT(ICACHE->SR, ICACHE_SR_BUSYF) != 0U) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait for end of cache invalidation */ - while (READ_BIT(ICACHE->SR, ICACHE_SR_BSYENDF) == 0U) - { - if ((HAL_GetTick() - tickstart) > ICACHE_INVALIDATE_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(ICACHE->SR, ICACHE_SR_BSYENDF) == 0U) - { - status = HAL_TIMEOUT; - break; - } - } - } - } - - /* Clear BSYENDF */ - WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); - - return status; -} - - -/** - * @brief Start the Instruction Cache performance monitoring. - * @param MonitorType Monitoring type - * This parameter can be one of the following values: - * @arg ICACHE_MONITOR_HIT_MISS Hit & Miss monitoring - * @arg ICACHE_MONITOR_HIT Hit monitoring - * @arg ICACHE_MONITOR_MISS Miss monitoring - * @retval HAL status (HAL_OK) - */ -HAL_StatusTypeDef HAL_ICACHE_Monitor_Start(uint32_t MonitorType) -{ - /* Check the parameters */ - assert_param(IS_ICACHE_MONITOR_TYPE(MonitorType)); - - SET_BIT(ICACHE->CR, MonitorType); - - return HAL_OK; -} - -/** - * @brief Stop the Instruction Cache performance monitoring. - * @note Stopping the monitoring does not reset the values. - * @param MonitorType Monitoring type - * This parameter can be one of the following values: - * @arg ICACHE_MONITOR_HIT_MISS Hit & Miss monitoring - * @arg ICACHE_MONITOR_HIT Hit monitoring - * @arg ICACHE_MONITOR_MISS Miss monitoring - * @retval HAL status (HAL_OK) - */ -HAL_StatusTypeDef HAL_ICACHE_Monitor_Stop(uint32_t MonitorType) -{ - /* Check the parameters */ - assert_param(IS_ICACHE_MONITOR_TYPE(MonitorType)); - - CLEAR_BIT(ICACHE->CR, MonitorType); - - return HAL_OK; -} - -/** - * @brief Reset the Instruction Cache performance monitoring values. - * @param MonitorType Monitoring type - * This parameter can be one of the following values: - * @arg ICACHE_MONITOR_HIT_MISS Hit & Miss monitoring - * @arg ICACHE_MONITOR_HIT Hit monitoring - * @arg ICACHE_MONITOR_MISS Miss monitoring - * @retval HAL status (HAL_OK) - */ -HAL_StatusTypeDef HAL_ICACHE_Monitor_Reset(uint32_t MonitorType) -{ - /* Check the parameters */ - assert_param(IS_ICACHE_MONITOR_TYPE(MonitorType)); - - /* Force/Release reset */ - SET_BIT(ICACHE->CR, (MonitorType << 2U)); - CLEAR_BIT(ICACHE->CR, (MonitorType << 2U)); - - return HAL_OK; -} - -/** - * @brief Get the Instruction Cache performance Hit monitoring value. - * @note Upon reaching the 32-bit maximum value, monitor does not wrap. - * @retval Hit monitoring value - */ -uint32_t HAL_ICACHE_Monitor_GetHitValue(void) -{ - return (ICACHE->HMONR); -} - -/** - * @brief Get the Instruction Cache performance Miss monitoring value. - * @note Upon reaching the 32-bit maximum value, monitor does not wrap. - * @retval Miss monitoring value - */ -uint32_t HAL_ICACHE_Monitor_GetMissValue(void) -{ - return (ICACHE->MMONR); -} - -/** - * @} - */ - -/** @defgroup ICACHE_Exported_Functions_Group2 IRQ and callback functions - * @brief IRQ and callback functions - * - @verbatim - ============================================================================== - ##### IRQ and callback functions ##### - ============================================================================== - [..] - This section provides functions allowing to handle ICACHE global interrupt - and the associated callback functions. - @endverbatim - * @{ - */ - -/** - * @brief Handle the Instruction Cache interrupt request. - * @note This function should be called under the ICACHE_IRQHandler(). - * @note This function respectively disables the interrupt and clears the - * flag of any pending flag before calling the associated user callback. - * @retval None - */ -void HAL_ICACHE_IRQHandler(void) -{ - /* Get current interrupt flags and interrupt sources value */ - uint32_t itflags = READ_REG(ICACHE->SR); - uint32_t itsources = READ_REG(ICACHE->IER); - - /* Check Instruction cache Error interrupt flag */ - if (((itflags & itsources) & ICACHE_FLAG_ERROR) != 0U) - { - /* Disable error interrupt */ - CLEAR_BIT(ICACHE->IER, ICACHE_IER_ERRIE); - - /* Clear ERR pending flag */ - WRITE_REG(ICACHE->FCR, ICACHE_FCR_CERRF); - - /* Instruction cache error interrupt user callback */ - HAL_ICACHE_ErrorCallback(); - } - - /* Check Instruction cache BusyEnd interrupt flag */ - if (((itflags & itsources) & ICACHE_FLAG_BUSYEND) != 0U) - { - /* Disable end of cache invalidation interrupt */ - CLEAR_BIT(ICACHE->IER, ICACHE_IER_BSYENDIE); - - /* Clear BSYENDF pending flag */ - WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); - - /* Instruction cache busyend interrupt user callback */ - HAL_ICACHE_InvalidateCompleteCallback(); - } -} - -/** - * @brief Cache invalidation complete callback. - */ -__weak void HAL_ICACHE_InvalidateCompleteCallback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_ICACHE_InvalidateCompleteCallback() should be implemented in the user file - */ -} - -/** - * @brief Error callback. - */ -__weak void HAL_ICACHE_ErrorCallback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_ICACHE_ErrorCallback() should be implemented in the user file - */ -} - -/** - * @} - */ - - -/** - * @} - */ - -#endif /* ICACHE && HAL_ICACHE_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_icache.c + * @author MCD Application Team + * @brief ICACHE HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Instruction Cache (ICACHE). + * + Initialization and Configuration + * + Invalidate functions + * + Monitoring management + * + Memory address remap management + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### ICACHE main features ##### + ============================================================================== + [..] + The Texture Cache (ICACHE) is introduced on AXI read-only texture port of + the GPU2D to improve performance when reading texture data from internal and + external memories. + + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The ICACHE HAL driver can be used as follows: + + (#) Optionally configure the Instruction Cache mode with + HAL_ICACHE_ConfigAssociativityMode() if the default configuration + does not suit the application requirements. + + (#) Enable and disable the Instruction Cache with respectively + HAL_ICACHE_Enable() and HAL_ICACHE_Disable(). + Use HAL_ICACHE_IsEnabled() to get the Instruction Cache status. + To ensure a deterministic cache behavior after power on, system reset or after + a call to @ref HAL_ICACHE_Disable(), the application must call + @ref HAL_ICACHE_WaitForInvalidateComplete(). Indeed on power on, system reset + or cache disable, an automatic cache invalidation procedure is launched and the + cache is bypassed until the operation completes. + + (#) Initiate the cache maintenance invalidation procedure with either + HAL_ICACHE_Invalidate() (blocking mode) or HAL_ICACHE_Invalidate_IT() + (interrupt mode). When interrupt mode is used, the callback function + HAL_ICACHE_InvalidateCompleteCallback() is called when the invalidate + procedure is complete. The function HAL_ICACHE_WaitForInvalidateComplete() + may be called to wait for the end of the invalidate procedure automatically + initiated when disabling the Instruction Cache with HAL_ICACHE_Disable(). + The cache operation is bypassed during the invalidation procedure. + + (#) Use the performance monitoring counters for Hit and Miss with the following + functions: HAL_ICACHE_Monitor_Start(), HAL_ICACHE_Monitor_Stop(), + HAL_ICACHE_Monitor_Reset(), HAL_ICACHE_Monitor_GetHitValue() and + HAL_ICACHE_Monitor_GetMissValue() + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup ICACHE ICACHE + * @brief HAL ICACHE module driver + * @{ + */ +#if defined(ICACHE) && defined (HAL_ICACHE_MODULE_ENABLED) + +/* Private typedef -----------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup ICACHE_Private_Constants ICACHE Private Constants + * @{ + */ +#define ICACHE_INVALIDATE_TIMEOUT_VALUE 1U /* 1ms */ +#define ICACHE_DISABLE_TIMEOUT_VALUE 1U /* 1ms */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup ICACHE_Private_Macros ICACHE Private Macros + * @{ + */ + +#define IS_ICACHE_ASSOCIATIVITY_MODE(__MODE__) (((__MODE__) == ICACHE_1WAY) || \ + ((__MODE__) == ICACHE_4WAYS)) + +#define IS_ICACHE_MONITOR_TYPE(__TYPE__) (((__TYPE__) == ICACHE_MONITOR_HIT_MISS) || \ + ((__TYPE__) == ICACHE_MONITOR_HIT) || \ + ((__TYPE__) == ICACHE_MONITOR_MISS)) + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup ICACHE_Exported_Functions ICACHE Exported Functions + * @{ + */ + +/** @defgroup ICACHE_Exported_Functions_Group1 Initialization and control functions + * @brief Initialization and control functions + * + @verbatim + ============================================================================== + ##### Initialization and control functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize and control the + Instruction Cache (mode, invalidate procedure, performance counters). + @endverbatim + * @{ + */ + +/** + * @brief Configure the Instruction Cache cache associativity mode selection. + * @param AssociativityMode Associativity mode selection + * This parameter can be one of the following values: + * @arg ICACHE_1WAY 1-way cache (direct mapped cache) + * @arg ICACHE_4WAYS 4-ways set associative cache (default) + * @retval HAL status (HAL_OK/HAL_ERROR) + */ +HAL_StatusTypeDef HAL_ICACHE_ConfigAssociativityMode(uint32_t AssociativityMode) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ICACHE_ASSOCIATIVITY_MODE(AssociativityMode)); + + /* Check cache is not enabled */ + if (READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) + { + status = HAL_ERROR; + } + else + { + MODIFY_REG(ICACHE->CR, ICACHE_CR_WAYSEL, AssociativityMode); + } + + return status; +} + +/** + * @brief DeInitialize the Instruction Cache. + * @retval HAL status (HAL_OK) + */ +HAL_StatusTypeDef HAL_ICACHE_DeInit(void) +{ + /* Reset interrupt enable value */ + WRITE_REG(ICACHE->IER, 0U); + + /* Clear any pending flags */ + WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF | ICACHE_FCR_CERRF); + + /* Disable cache then set default associative mode value */ + CLEAR_BIT(ICACHE->CR, ICACHE_CR_EN); + WRITE_REG(ICACHE->CR, ICACHE_CR_WAYSEL); + + /* Stop monitor and reset monitor values */ + CLEAR_BIT(ICACHE->CR, ICACHE_MONITOR_HIT_MISS); + SET_BIT(ICACHE->CR, (ICACHE_MONITOR_HIT_MISS << 2U)); + CLEAR_BIT(ICACHE->CR, (ICACHE_MONITOR_HIT_MISS << 2U)); + + + return HAL_OK; +} + +/** + * @brief Enable the Instruction Cache. + * @note This function always returns HAL_OK even if there is any ongoing + * cache operation. The Instruction Cache is bypassed until the + * cache operation completes. + * @retval HAL status (HAL_OK) + */ +HAL_StatusTypeDef HAL_ICACHE_Enable(void) +{ + SET_BIT(ICACHE->CR, ICACHE_CR_EN); + + return HAL_OK; +} + +/** + * @brief Disable the Instruction Cache. + * @note This function waits for the cache being disabled but + * not for the end of the automatic cache invalidation procedure. + * @retval HAL status (HAL_OK/HAL_TIMEOUT) + */ +HAL_StatusTypeDef HAL_ICACHE_Disable(void) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tickstart; + + /* Make sure BSYENDF is reset before to disable the instruction cache */ + /* as it automatically starts a cache invalidation procedure */ + WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); + + CLEAR_BIT(ICACHE->CR, ICACHE_CR_EN); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait for instruction cache being disabled */ + while (READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) + { + if ((HAL_GetTick() - tickstart) > ICACHE_DISABLE_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) + { + status = HAL_TIMEOUT; + break; + } + } + } + + return status; +} + +/** + * @brief Check whether the Instruction Cache is enabled or not. + * @retval Status (0: disabled, 1: enabled) + */ +uint32_t HAL_ICACHE_IsEnabled(void) +{ + return ((READ_BIT(ICACHE->CR, ICACHE_CR_EN) != 0U) ? 1UL : 0UL); +} + +/** + * @brief Invalidate the Instruction Cache. + * @note This function waits for the end of cache invalidation procedure + * and clears the associated BSYENDF flag. + * @retval HAL status (HAL_OK/HAL_ERROR/HAL_TIMEOUT) + */ +HAL_StatusTypeDef HAL_ICACHE_Invalidate(void) +{ + HAL_StatusTypeDef status; + + /* Check if no ongoing operation */ + if (READ_BIT(ICACHE->SR, ICACHE_SR_BUSYF) == 0U) + { + /* Launch cache invalidation */ + SET_BIT(ICACHE->CR, ICACHE_CR_CACHEINV); + } + + status = HAL_ICACHE_WaitForInvalidateComplete(); + + return status; +} + +/** + * @brief Invalidate the Instruction Cache with interrupt. + * @note This function launches cache invalidation and returns. + * User application shall resort to interrupt generation to check + * the end of the cache invalidation with the BSYENDF flag and the + * HAL_ICACHE_InvalidateCompleteCallback() callback. + * @retval HAL status (HAL_OK/HAL_ERROR) + */ +HAL_StatusTypeDef HAL_ICACHE_Invalidate_IT(void) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check no ongoing operation */ + if (READ_BIT(ICACHE->SR, ICACHE_SR_BUSYF) != 0U) + { + status = HAL_ERROR; + } + else + { + /* Make sure BSYENDF is reset before to start cache invalidation */ + WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); + + /* Enable end of cache invalidation interrupt */ + SET_BIT(ICACHE->IER, ICACHE_IER_BSYENDIE); + + /* Launch cache invalidation */ + SET_BIT(ICACHE->CR, ICACHE_CR_CACHEINV); + } + + return status; +} + +/** + * @brief Wait for the end of the Instruction Cache invalidate procedure. + * @note This function checks and clears the BSYENDF flag when set. + * @retval HAL status (HAL_OK/HAL_TIMEOUT) + */ +HAL_StatusTypeDef HAL_ICACHE_WaitForInvalidateComplete(void) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tickstart; + + /* Check if ongoing invalidation operation */ + if (READ_BIT(ICACHE->SR, ICACHE_SR_BUSYF) != 0U) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait for end of cache invalidation */ + while (READ_BIT(ICACHE->SR, ICACHE_SR_BSYENDF) == 0U) + { + if ((HAL_GetTick() - tickstart) > ICACHE_INVALIDATE_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(ICACHE->SR, ICACHE_SR_BSYENDF) == 0U) + { + status = HAL_TIMEOUT; + break; + } + } + } + } + + /* Clear BSYENDF */ + WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); + + return status; +} + + +/** + * @brief Start the Instruction Cache performance monitoring. + * @param MonitorType Monitoring type + * This parameter can be one of the following values: + * @arg ICACHE_MONITOR_HIT_MISS Hit & Miss monitoring + * @arg ICACHE_MONITOR_HIT Hit monitoring + * @arg ICACHE_MONITOR_MISS Miss monitoring + * @retval HAL status (HAL_OK) + */ +HAL_StatusTypeDef HAL_ICACHE_Monitor_Start(uint32_t MonitorType) +{ + /* Check the parameters */ + assert_param(IS_ICACHE_MONITOR_TYPE(MonitorType)); + + SET_BIT(ICACHE->CR, MonitorType); + + return HAL_OK; +} + +/** + * @brief Stop the Instruction Cache performance monitoring. + * @note Stopping the monitoring does not reset the values. + * @param MonitorType Monitoring type + * This parameter can be one of the following values: + * @arg ICACHE_MONITOR_HIT_MISS Hit & Miss monitoring + * @arg ICACHE_MONITOR_HIT Hit monitoring + * @arg ICACHE_MONITOR_MISS Miss monitoring + * @retval HAL status (HAL_OK) + */ +HAL_StatusTypeDef HAL_ICACHE_Monitor_Stop(uint32_t MonitorType) +{ + /* Check the parameters */ + assert_param(IS_ICACHE_MONITOR_TYPE(MonitorType)); + + CLEAR_BIT(ICACHE->CR, MonitorType); + + return HAL_OK; +} + +/** + * @brief Reset the Instruction Cache performance monitoring values. + * @param MonitorType Monitoring type + * This parameter can be one of the following values: + * @arg ICACHE_MONITOR_HIT_MISS Hit & Miss monitoring + * @arg ICACHE_MONITOR_HIT Hit monitoring + * @arg ICACHE_MONITOR_MISS Miss monitoring + * @retval HAL status (HAL_OK) + */ +HAL_StatusTypeDef HAL_ICACHE_Monitor_Reset(uint32_t MonitorType) +{ + /* Check the parameters */ + assert_param(IS_ICACHE_MONITOR_TYPE(MonitorType)); + + /* Force/Release reset */ + SET_BIT(ICACHE->CR, (MonitorType << 2U)); + CLEAR_BIT(ICACHE->CR, (MonitorType << 2U)); + + return HAL_OK; +} + +/** + * @brief Get the Instruction Cache performance Hit monitoring value. + * @note Upon reaching the 32-bit maximum value, monitor does not wrap. + * @retval Hit monitoring value + */ +uint32_t HAL_ICACHE_Monitor_GetHitValue(void) +{ + return (ICACHE->HMONR); +} + +/** + * @brief Get the Instruction Cache performance Miss monitoring value. + * @note Upon reaching the 32-bit maximum value, monitor does not wrap. + * @retval Miss monitoring value + */ +uint32_t HAL_ICACHE_Monitor_GetMissValue(void) +{ + return (ICACHE->MMONR); +} + +/** + * @} + */ + +/** @defgroup ICACHE_Exported_Functions_Group2 IRQ and callback functions + * @brief IRQ and callback functions + * + @verbatim + ============================================================================== + ##### IRQ and callback functions ##### + ============================================================================== + [..] + This section provides functions allowing to handle ICACHE global interrupt + and the associated callback functions. + @endverbatim + * @{ + */ + +/** + * @brief Handle the Instruction Cache interrupt request. + * @note This function should be called under the ICACHE_IRQHandler(). + * @note This function respectively disables the interrupt and clears the + * flag of any pending flag before calling the associated user callback. + * @retval None + */ +void HAL_ICACHE_IRQHandler(void) +{ + /* Get current interrupt flags and interrupt sources value */ + uint32_t itflags = READ_REG(ICACHE->SR); + uint32_t itsources = READ_REG(ICACHE->IER); + + /* Check Instruction cache Error interrupt flag */ + if (((itflags & itsources) & ICACHE_FLAG_ERROR) != 0U) + { + /* Disable error interrupt */ + CLEAR_BIT(ICACHE->IER, ICACHE_IER_ERRIE); + + /* Clear ERR pending flag */ + WRITE_REG(ICACHE->FCR, ICACHE_FCR_CERRF); + + /* Instruction cache error interrupt user callback */ + HAL_ICACHE_ErrorCallback(); + } + + /* Check Instruction cache BusyEnd interrupt flag */ + if (((itflags & itsources) & ICACHE_FLAG_BUSYEND) != 0U) + { + /* Disable end of cache invalidation interrupt */ + CLEAR_BIT(ICACHE->IER, ICACHE_IER_BSYENDIE); + + /* Clear BSYENDF pending flag */ + WRITE_REG(ICACHE->FCR, ICACHE_FCR_CBSYENDF); + + /* Instruction cache busyend interrupt user callback */ + HAL_ICACHE_InvalidateCompleteCallback(); + } +} + +/** + * @brief Cache invalidation complete callback. + */ +__weak void HAL_ICACHE_InvalidateCompleteCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_ICACHE_InvalidateCompleteCallback() should be implemented in the user file + */ +} + +/** + * @brief Error callback. + */ +__weak void HAL_ICACHE_ErrorCallback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_ICACHE_ErrorCallback() should be implemented in the user file + */ +} + +/** + * @} + */ + + +/** + * @} + */ + +#endif /* ICACHE && HAL_ICACHE_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_irda.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_irda.c index fd90c36d3..a843c8c32 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_irda.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_irda.c @@ -1,3015 +1,3013 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_irda.c - * @author MCD Application Team - * @brief IRDA HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the IrDA (Infrared Data Association) Peripheral - * (IRDA) - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State and Errors functions - * + Peripheral Control functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The IRDA HAL driver can be used as follows: - - (#) Declare a IRDA_HandleTypeDef handle structure (eg. IRDA_HandleTypeDef hirda). - (#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API - in setting the associated USART or UART in IRDA mode: - (++) Enable the USARTx/UARTx interface clock. - (++) USARTx/UARTx pins configuration: - (+++) Enable the clock for the USARTx/UARTx GPIOs. - (+++) Configure these USARTx/UARTx pins (TX as alternate function pull-up, RX as alternate function Input). - (++) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT() - and HAL_IRDA_Receive_IT() APIs): - (+++) Configure the USARTx/UARTx interrupt priority. - (+++) Enable the NVIC USARTx/UARTx IRQ handle. - (+++) 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. - - (++) 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 channel. - (+++) Enable the DMAx interface clock. - (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. - (+++) Configure the DMA Tx/Rx channel. - (+++) Associate the initialized 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 channel. - - (#) Program the Baud Rate, Word Length and Parity and Mode(Receiver/Transmitter), - the normal or low power mode and the clock prescaler in the hirda handle 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 customized 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 operation modes 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 half of transfer HAL_IRDA_TxHalfCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_IRDA_TxHalfCpltCallback() - (+) 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 half of transfer HAL_IRDA_RxHalfCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_IRDA_RxHalfCpltCallback() - (+) 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 : Check whether the specified IRDA flag is set or not - (+) __HAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag - (+) __HAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt - (+) __HAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt - (+) __HAL_IRDA_GET_IT_SOURCE: Check whether or not the specified IRDA interrupt is enabled - - [..] - (@) You can refer to the IRDA HAL driver header file for more useful macros - - ##### Callback registration ##### - ================================== - - [..] - The compilation define USE_HAL_IRDA_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - [..] - Use Function HAL_IRDA_RegisterCallback() to register a user callback. - Function HAL_IRDA_RegisterCallback() allows to register following callbacks: - (+) TxHalfCpltCallback : Tx Half Complete Callback. - (+) TxCpltCallback : Tx Complete Callback. - (+) RxHalfCpltCallback : Rx Half Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. - (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. - (+) MspInitCallback : IRDA MspInit. - (+) MspDeInitCallback : IRDA MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_IRDA_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_IRDA_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxHalfCpltCallback : Tx Half Complete Callback. - (+) TxCpltCallback : Tx Complete Callback. - (+) RxHalfCpltCallback : Rx Half Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. - (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. - (+) MspInitCallback : IRDA MspInit. - (+) MspDeInitCallback : IRDA MspDeInit. - - [..] - By default, after the HAL_IRDA_Init() and when the state is HAL_IRDA_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxHalfCpltCallback(). - Exception done for MspInit and MspDeInit functions that are respectively - reset to the legacy weak functions in the HAL_IRDA_Init() - and HAL_IRDA_DeInit() only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_IRDA_Init() and HAL_IRDA_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in HAL_IRDA_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_IRDA_STATE_READY or HAL_IRDA_STATE_RESET state, thus registered (user) - MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_IRDA_RegisterCallback() before calling HAL_IRDA_DeInit() - or HAL_IRDA_Init() function. - - [..] - When The compilation define USE_HAL_IRDA_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available - and weak callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup IRDA IRDA - * @brief HAL IRDA module driver - * @{ - */ - -#ifdef HAL_IRDA_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup IRDA_Private_Constants IRDA Private Constants - * @{ - */ -#define IRDA_TEACK_REACK_TIMEOUT 1000U /*!< IRDA TX or RX enable acknowledge time-out value */ - -#define IRDA_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE \ - | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) /*!< UART or USART CR1 fields of parameters set by IRDA_SetConfig API */ - -#define USART_BRR_MIN 0x10U /*!< USART BRR minimum authorized value */ - -#define USART_BRR_MAX 0x0000FFFFU /*!< USART BRR maximum authorized value */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup IRDA_Private_Macros IRDA Private Macros - * @{ - */ -/** @brief BRR division operation to set BRR register in 16-bit oversampling mode. - * @param __PCLK__ IRDA clock source. - * @param __BAUD__ Baud rate set by the user. - * @param __PRESCALER__ IRDA clock prescaler value. - * @retval Division result - */ -#define IRDA_DIV_SAMPLING16(__PCLK__, __BAUD__, __PRESCALER__) ((((__PCLK__)/IRDAPrescTable[(__PRESCALER__)])\ - + ((__BAUD__)/2U)) / (__BAUD__)) -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup IRDA_Private_Functions - * @{ - */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) -void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ -static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda); -static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda); -static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout); -#if defined(HAL_DMA_MODULE_ENABLED) -static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda); -#endif /* HAL_DMA_MODULE_ENABLED */ -static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda); -#if defined(HAL_DMA_MODULE_ENABLED) -static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma); -static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma); -static void IRDA_DMAError(DMA_HandleTypeDef *hdma); -static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -#endif /* HAL_DMA_MODULE_ENABLED */ -static void IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda); -static void IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda); -static void IRDA_Receive_IT(IRDA_HandleTypeDef *hirda); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup IRDA_Exported_Functions IRDA Exported Functions - * @{ - */ - -/** @defgroup IRDA_Exported_Functions_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 - in asynchronous IRDA mode. - (+) For the asynchronous mode only these parameters can be configured: - (++) Baud Rate - (++) Word Length - (++) 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. - (++) Power mode - (++) Prescaler setting - (++) Receiver/transmitter modes - - [..] - The HAL_IRDA_Init() API follows the USART asynchronous configuration procedures - (details for the procedures are available in reference manual). - -@endverbatim - - Depending on the frame length defined by the M1 and M0 bits (7-bit, - 8-bit or 9-bit), the possible IRDA frame formats are listed in the - following table. - - Table 1. IRDA frame format. - +-----------------------------------------------------------------------+ - | M1 bit | M0 bit | PCE bit | IRDA frame | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 0 | | SB | 8 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 0 | | SB | 9 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 0 | | SB | 7 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | - +-----------------------------------------------------------------------+ - - * @{ - */ - -/** - * @brief Initialize the IRDA mode according to the specified - * parameters in the IRDA_InitTypeDef and initialize the associated handle. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) -{ - /* Check the IRDA handle allocation */ - if (hirda == NULL) - { - return HAL_ERROR; - } - - /* Check the USART/UART associated to the IRDA handle */ - assert_param(IS_IRDA_INSTANCE(hirda->Instance)); - - if (hirda->gState == HAL_IRDA_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hirda->Lock = HAL_UNLOCKED; - -#if USE_HAL_IRDA_REGISTER_CALLBACKS == 1 - IRDA_InitCallbacksToDefault(hirda); - - if (hirda->MspInitCallback == NULL) - { - hirda->MspInitCallback = HAL_IRDA_MspInit; - } - - /* Init the low level hardware */ - hirda->MspInitCallback(hirda); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_IRDA_MspInit(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ - } - - hirda->gState = HAL_IRDA_STATE_BUSY; - - /* Disable the Peripheral to update the configuration registers */ - __HAL_IRDA_DISABLE(hirda); - - /* Set the IRDA Communication parameters */ - if (IRDA_SetConfig(hirda) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* 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.*/ - CLEAR_BIT(hirda->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP)); - CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL)); - - /* set the UART/USART in IRDA mode */ - hirda->Instance->CR3 |= USART_CR3_IREN; - - /* Enable the Peripheral */ - __HAL_IRDA_ENABLE(hirda); - - /* TEACK and/or REACK to check before moving hirda->gState and hirda->RxState to Ready */ - return (IRDA_CheckIdleState(hirda)); -} - -/** - * @brief DeInitialize the IRDA peripheral. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) -{ - /* Check the IRDA handle allocation */ - if (hirda == NULL) - { - return HAL_ERROR; - } - - /* Check the USART/UART associated to the IRDA handle */ - assert_param(IS_IRDA_INSTANCE(hirda->Instance)); - - hirda->gState = HAL_IRDA_STATE_BUSY; - - /* DeInit the low level hardware */ -#if USE_HAL_IRDA_REGISTER_CALLBACKS == 1 - if (hirda->MspDeInitCallback == NULL) - { - hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; - } - /* DeInit the low level hardware */ - hirda->MspDeInitCallback(hirda); -#else - HAL_IRDA_MspDeInit(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ - /* Disable the Peripheral */ - __HAL_IRDA_DISABLE(hirda); - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_RESET; - hirda->RxState = HAL_IRDA_STATE_RESET; - - /* Process Unlock */ - __HAL_UNLOCK(hirda); - - return HAL_OK; -} - -/** - * @brief Initialize the IRDA MSP. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_IRDA_MspInit can be implemented in the user file - */ -} - -/** - * @brief DeInitialize the IRDA MSP. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_IRDA_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User IRDA Callback - * To be used to override the weak predefined callback - * @note The HAL_IRDA_RegisterCallback() may be called before HAL_IRDA_Init() in HAL_IRDA_STATE_RESET - * to register callbacks for HAL_IRDA_MSPINIT_CB_ID and HAL_IRDA_MSPDEINIT_CB_ID - * @param hirda irda handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID - * @arg @ref HAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID - * @arg @ref HAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_IRDA_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID - * @arg @ref HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID - * @arg @ref HAL_IRDA_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_RegisterCallback(IRDA_HandleTypeDef *hirda, HAL_IRDA_CallbackIDTypeDef CallbackID, - pIRDA_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (hirda->gState == HAL_IRDA_STATE_READY) - { - switch (CallbackID) - { - case HAL_IRDA_TX_HALFCOMPLETE_CB_ID : - hirda->TxHalfCpltCallback = pCallback; - break; - - case HAL_IRDA_TX_COMPLETE_CB_ID : - hirda->TxCpltCallback = pCallback; - break; - - case HAL_IRDA_RX_HALFCOMPLETE_CB_ID : - hirda->RxHalfCpltCallback = pCallback; - break; - - case HAL_IRDA_RX_COMPLETE_CB_ID : - hirda->RxCpltCallback = pCallback; - break; - - case HAL_IRDA_ERROR_CB_ID : - hirda->ErrorCallback = pCallback; - break; - - case HAL_IRDA_ABORT_COMPLETE_CB_ID : - hirda->AbortCpltCallback = pCallback; - break; - - case HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID : - hirda->AbortTransmitCpltCallback = pCallback; - break; - - case HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID : - hirda->AbortReceiveCpltCallback = pCallback; - break; - - case HAL_IRDA_MSPINIT_CB_ID : - hirda->MspInitCallback = pCallback; - break; - - case HAL_IRDA_MSPDEINIT_CB_ID : - hirda->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hirda->gState == HAL_IRDA_STATE_RESET) - { - switch (CallbackID) - { - case HAL_IRDA_MSPINIT_CB_ID : - hirda->MspInitCallback = pCallback; - break; - - case HAL_IRDA_MSPDEINIT_CB_ID : - hirda->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an IRDA callback - * IRDA callback is redirected to the weak predefined callback - * @note The HAL_IRDA_UnRegisterCallback() may be called before HAL_IRDA_Init() in HAL_IRDA_STATE_RESET - * to un-register callbacks for HAL_IRDA_MSPINIT_CB_ID and HAL_IRDA_MSPDEINIT_CB_ID - * @param hirda irda handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID - * @arg @ref HAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID - * @arg @ref HAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_IRDA_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID - * @arg @ref HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID - * @arg @ref HAL_IRDA_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_UnRegisterCallback(IRDA_HandleTypeDef *hirda, HAL_IRDA_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_IRDA_STATE_READY == hirda->gState) - { - switch (CallbackID) - { - case HAL_IRDA_TX_HALFCOMPLETE_CB_ID : - hirda->TxHalfCpltCallback = HAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - break; - - case HAL_IRDA_TX_COMPLETE_CB_ID : - hirda->TxCpltCallback = HAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_IRDA_RX_HALFCOMPLETE_CB_ID : - hirda->RxHalfCpltCallback = HAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - break; - - case HAL_IRDA_RX_COMPLETE_CB_ID : - hirda->RxCpltCallback = HAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_IRDA_ERROR_CB_ID : - hirda->ErrorCallback = HAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_IRDA_ABORT_COMPLETE_CB_ID : - hirda->AbortCpltCallback = HAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID : - hirda->AbortTransmitCpltCallback = HAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak - AbortTransmitCpltCallback */ - break; - - case HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID : - hirda->AbortReceiveCpltCallback = HAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak - AbortReceiveCpltCallback */ - break; - - case HAL_IRDA_MSPINIT_CB_ID : - hirda->MspInitCallback = HAL_IRDA_MspInit; /* Legacy weak MspInitCallback */ - break; - - case HAL_IRDA_MSPDEINIT_CB_ID : - hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; /* Legacy weak MspDeInitCallback */ - break; - - default : - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_IRDA_STATE_RESET == hirda->gState) - { - switch (CallbackID) - { - case HAL_IRDA_MSPINIT_CB_ID : - hirda->MspInitCallback = HAL_IRDA_MspInit; - break; - - case HAL_IRDA_MSPDEINIT_CB_ID : - hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; - break; - - default : - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup IRDA_Exported_Functions_Group2 IO operation functions - * @brief IRDA Transmit and 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 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 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 respectively 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 APIs are : - (++) HAL_IRDA_Transmit() - (++) HAL_IRDA_Receive() - - (#) Non Blocking mode APIs with Interrupt are : - (++) HAL_IRDA_Transmit_IT() - (++) HAL_IRDA_Receive_IT() - (++) HAL_IRDA_IRQHandler() - - (#) Non Blocking mode functions with DMA are : - (++) HAL_IRDA_Transmit_DMA() - (++) HAL_IRDA_Receive_DMA() - (++) HAL_IRDA_DMAPause() - (++) HAL_IRDA_DMAResume() - (++) HAL_IRDA_DMAStop() - - (#) A set of Transfer Complete Callbacks are provided in Non Blocking mode: - (++) HAL_IRDA_TxHalfCpltCallback() - (++) HAL_IRDA_TxCpltCallback() - (++) HAL_IRDA_RxHalfCpltCallback() - (++) HAL_IRDA_RxCpltCallback() - (++) HAL_IRDA_ErrorCallback() - - (#) Non-Blocking mode transfers could be aborted using Abort API's : - (++) HAL_IRDA_Abort() - (++) HAL_IRDA_AbortTransmit() - (++) HAL_IRDA_AbortReceive() - (++) HAL_IRDA_Abort_IT() - (++) HAL_IRDA_AbortTransmit_IT() - (++) HAL_IRDA_AbortReceive_IT() - - (#) For Abort services based on interrupts (HAL_IRDA_Abortxxx_IT), a set of Abort Complete Callbacks are provided: - (++) HAL_IRDA_AbortCpltCallback() - (++) HAL_IRDA_AbortTransmitCpltCallback() - (++) HAL_IRDA_AbortReceiveCpltCallback() - - (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. - Errors are handled as follows : - (++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is - to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error - in Interrupt mode reception . - Received character is then retrieved and stored in Rx buffer, Error code is set to allow user - to identify error type, and HAL_IRDA_ErrorCallback() user callback is executed. - Transfer is kept ongoing on IRDA side. - If user wants to abort it, Abort services should be called by user. - (++) Error is considered as Blocking : Transfer could not be completed properly and is aborted. - This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. - Error code is set to allow user to identify error type, and - HAL_IRDA_ErrorCallback() user callback is executed. - -@endverbatim - * @{ - */ - -/** - * @brief Send an amount of data in blocking mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must reflect the number - * of u16 available through pData. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @param Timeout Specify timeout value. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size, uint32_t Timeout) -{ - const uint8_t *pdata8bits; - const uint16_t *pdata16bits; - uint32_t tickstart; - - /* Check that a Tx process is not already ongoing */ - if (hirda->gState == HAL_IRDA_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hirda); - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_BUSY_TX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - hirda->TxXferSize = Size; - hirda->TxXferCount = Size; - - /* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */ - if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) - { - pdata8bits = NULL; - pdata16bits = (const uint16_t *) pData; /* Derogation R.11.3 */ - } - else - { - pdata8bits = pData; - pdata16bits = NULL; - } - - while (hirda->TxXferCount > 0U) - { - hirda->TxXferCount--; - - if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - if (pdata8bits == NULL) - { - hirda->Instance->TDR = (uint16_t)(*pdata16bits & 0x01FFU); - pdata16bits++; - } - else - { - hirda->Instance->TDR = (uint8_t)(*pdata8bits & 0xFFU); - pdata8bits++; - } - } - - if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* At end of Tx process, restore hirda->gState to Ready */ - hirda->gState = 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. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must reflect the number - * of u16 available through pData. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) 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) -{ - uint8_t *pdata8bits; - uint16_t *pdata16bits; - uint16_t uhMask; - uint32_t tickstart; - - /* Check that a Rx process is not already ongoing */ - if (hirda->RxState == HAL_IRDA_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hirda); - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->RxState = HAL_IRDA_STATE_BUSY_RX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - hirda->RxXferSize = Size; - hirda->RxXferCount = Size; - - /* Computation of the mask to apply to RDR register - of the UART associated to the IRDA */ - IRDA_MASK_COMPUTATION(hirda); - uhMask = hirda->Mask; - - /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ - if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) - { - pdata8bits = NULL; - pdata16bits = (uint16_t *) pData; /* Derogation R.11.3 */ - } - else - { - pdata8bits = pData; - pdata16bits = NULL; - } - - /* Check data remaining to be received */ - while (hirda->RxXferCount > 0U) - { - hirda->RxXferCount--; - - if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - if (pdata8bits == NULL) - { - *pdata16bits = (uint16_t)(hirda->Instance->RDR & uhMask); - pdata16bits++; - } - else - { - *pdata8bits = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask); - pdata8bits++; - } - } - - /* At end of Rx process, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Send an amount of data in interrupt mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must reflect the number - * of u16 available through pData. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size) -{ - /* Check that a Tx process is not already ongoing */ - if (hirda->gState == HAL_IRDA_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hirda); - - hirda->pTxBuffPtr = pData; - hirda->TxXferSize = Size; - hirda->TxXferCount = Size; - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_BUSY_TX; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - /* Enable the IRDA Transmit Data Register Empty Interrupt */ - SET_BIT(hirda->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in interrupt mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must reflect the number - * of u16 available through pData. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) -{ - /* Check that a Rx process is not already ongoing */ - if (hirda->RxState == HAL_IRDA_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hirda); - - hirda->pRxBuffPtr = pData; - hirda->RxXferSize = Size; - hirda->RxXferCount = Size; - - /* Computation of the mask to apply to the RDR register - of the UART associated to the IRDA */ - IRDA_MASK_COMPUTATION(hirda); - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->RxState = HAL_IRDA_STATE_BUSY_RX; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - if (hirda->Init.Parity != IRDA_PARITY_NONE) - { - /* Enable the IRDA Parity Error and Data Register not empty Interrupts */ - SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); - } - else - { - /* Enable the IRDA Data Register not empty Interrupts */ - SET_BIT(hirda->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - - /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Send an amount of data in DMA mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must reflect the number - * of u16 available through pData. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param pData pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - uint16_t nbByte = Size; - - /* Check that a Tx process is not already ongoing */ - if (hirda->gState == HAL_IRDA_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hirda); - - hirda->pTxBuffPtr = pData; - hirda->TxXferSize = Size; - hirda->TxXferCount = Size; - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_BUSY_TX; - - /* Set the IRDA DMA transfer complete callback */ - hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt; - - /* Set the IRDA DMA half transfer complete callback */ - hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt; - - /* Set the DMA error callback */ - hirda->hdmatx->XferErrorCallback = IRDA_DMAError; - - /* Set the DMA abort callback */ - hirda->hdmatx->XferAbortCallback = NULL; - - /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ - if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - /* Check linked list mode */ - if ((hirda->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hirda->hdmatx->LinkedListQueue != NULL) && (hirda->hdmatx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - hirda->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - hirda->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)hirda->pTxBuffPtr; - - /* Set DMA destination address */ - hirda->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&hirda->Instance->TDR; - - /* Enable the IRDA transmit DMA channel */ - status = HAL_DMAEx_List_Start_IT(hirda->hdmatx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the IRDA transmit DMA channel */ - status = HAL_DMA_Start_IT(hirda->hdmatx, (uint32_t)hirda->pTxBuffPtr, (uint32_t)&hirda->Instance->TDR, nbByte); - } - - if (status == HAL_OK) - { - /* Clear the TC flag in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_TCF); - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the USART CR3 register */ - SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - return HAL_OK; - } - else - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - /* Restore hirda->gState to ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in DMA mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must reflect the number - * of u16 available through pData. - * @note When the IRDA parity is enabled (PCE = 1), the received data contains - * the parity bit (MSB position). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - uint16_t nbByte = Size; - - /* Check that a Rx process is not already ongoing */ - if (hirda->RxState == HAL_IRDA_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hirda); - - hirda->pRxBuffPtr = pData; - hirda->RxXferSize = Size; - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->RxState = HAL_IRDA_STATE_BUSY_RX; - - /* Set the IRDA DMA transfer complete callback */ - hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt; - - /* Set the IRDA DMA half transfer complete callback */ - hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt; - - /* Set the DMA error callback */ - hirda->hdmarx->XferErrorCallback = IRDA_DMAError; - - /* Set the DMA abort callback */ - hirda->hdmarx->XferAbortCallback = NULL; - - /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ - if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - /* Check linked list mode */ - if ((hirda->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hirda->hdmarx->LinkedListQueue != NULL) && (hirda->hdmarx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - hirda->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - hirda->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)&hirda->Instance->RDR; - - /* Set DMA destination address */ - hirda->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hirda->pRxBuffPtr; - - /* Enable the DMA channel */ - status = HAL_DMAEx_List_Start_IT(hirda->hdmarx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the DMA channel */ - status = HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->RDR, (uint32_t)hirda->pRxBuffPtr, nbByte); - } - - if (status == HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - if (hirda->Init.Parity != IRDA_PARITY_NONE) - { - /* Enable the UART Parity Error Interrupt */ - SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - } - - /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the USART CR3 register */ - SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - return HAL_OK; - } - else - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - /* Restore hirda->RxState to ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} - - -/** - * @brief Pause the DMA Transfer. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda) -{ - /* Process Locked */ - __HAL_LOCK(hirda); - - if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) - { - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable the IRDA DMA Tx request */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - } - } - if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) - { - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Disable the IRDA DMA Rx request */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - return HAL_OK; -} - -/** - * @brief Resume the DMA Transfer. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda) -{ - /* Process Locked */ - __HAL_LOCK(hirda); - - if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) - { - /* Enable the IRDA DMA Tx request */ - SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - } - if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) - { - /* Clear the Overrun flag before resuming the Rx transfer*/ - __HAL_IRDA_CLEAR_OREFLAG(hirda); - - /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ - if (hirda->Init.Parity != IRDA_PARITY_NONE) - { - SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - } - SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Enable the IRDA DMA Rx request */ - SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - return HAL_OK; -} - -/** - * @brief Stop the DMA Transfer. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda) -{ - /* The Lock is not implemented on this API to allow the user application - to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback() / - HAL_IRDA_TxHalfCpltCallback / HAL_IRDA_RxHalfCpltCallback: - indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete - interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of - the stream and the corresponding call back is executed. */ - - /* Stop IRDA DMA Tx request if ongoing */ - if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) - { - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel */ - if (hirda->hdmatx != NULL) - { - if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - - IRDA_EndTxTransfer(hirda); - } - } - - /* Stop IRDA DMA Rx request if ongoing */ - if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) - { - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel */ - if (hirda->hdmarx != NULL) - { - if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - - IRDA_EndRxTransfer(hirda); - } - } - - return HAL_OK; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Abort ongoing transfers (blocking mode). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable IRDA Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Abort(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | \ - USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the IRDA DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (hirda->hdmatx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - - /* Disable the IRDA DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx and Rx transfer counters */ - hirda->TxXferCount = 0U; - hirda->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Reset Handle ErrorCode to No Error */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (blocking mode). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable IRDA Interrupts (Tx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the IRDA DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (hirda->hdmatx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx transfer counter */ - hirda->TxXferCount = 0U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (blocking mode). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable IRDA Interrupts (Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the IRDA DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hirda->ErrorCode = HAL_IRDA_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Rx transfer counter */ - hirda->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (Interrupt mode). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable IRDA Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda) -{ - uint32_t abortcplt = 1U; - - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | \ - USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* If DMA Tx and/or DMA Rx Handles are associated to IRDA Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if (hirda->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if IRDA DMA Tx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - hirda->hdmatx->XferAbortCallback = IRDA_DMATxAbortCallback; - } - else - { - hirda->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if (hirda->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if IRDA DMA Rx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - hirda->hdmarx->XferAbortCallback = IRDA_DMARxAbortCallback; - } - else - { - hirda->hdmarx->XferAbortCallback = NULL; - } - } - - /* Disable the IRDA DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at UART level */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (hirda->hdmatx != NULL) - { - /* IRDA Tx DMA Abort callback has already been initialised : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK) - { - hirda->hdmatx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } - } - } - - /* Disable the IRDA DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (hirda->hdmarx != NULL) - { - /* IRDA Rx DMA Abort callback has already been initialised : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) - { - hirda->hdmarx->XferAbortCallback = NULL; - abortcplt = 1U; - } - else - { - abortcplt = 0U; - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if (abortcplt == 1U) - { - /* Reset Tx and Rx transfer counters */ - hirda->TxXferCount = 0U; - hirda->RxXferCount = 0U; - - /* Reset errorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - hirda->AbortCpltCallback(hirda); -#else - /* Call legacy weak Abort complete callback */ - HAL_IRDA_AbortCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (Interrupt mode). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable IRDA Interrupts (Tx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the IRDA DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (hirda->hdmatx != NULL) - { - /* Set the IRDA DMA Abort callback : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - hirda->hdmatx->XferAbortCallback = IRDA_DMATxOnlyAbortCallback; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK) - { - /* Call Directly hirda->hdmatx->XferAbortCallback function in case of error */ - hirda->hdmatx->XferAbortCallback(hirda->hdmatx); - } - } - else - { - /* Reset Tx transfer counter */ - hirda->TxXferCount = 0U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - hirda->AbortTransmitCpltCallback(hirda); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_IRDA_AbortTransmitCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Reset Tx transfer counter */ - hirda->TxXferCount = 0U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - hirda->AbortTransmitCpltCallback(hirda); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_IRDA_AbortTransmitCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (Interrupt mode). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable IRDA Interrupts (Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the IRDA DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = IRDA_DMARxOnlyAbortCallback; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) - { - /* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */ - hirda->hdmarx->XferAbortCallback(hirda->hdmarx); - } - } - else - { - /* Reset Rx transfer counter */ - hirda->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - hirda->AbortReceiveCpltCallback(hirda); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_IRDA_AbortReceiveCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Reset Rx transfer counter */ - hirda->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - hirda->AbortReceiveCpltCallback(hirda); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_IRDA_AbortReceiveCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - - return HAL_OK; -} - -/** - * @brief Handle IRDA interrupt request. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) -{ - uint32_t isrflags = READ_REG(hirda->Instance->ISR); - uint32_t cr1its = READ_REG(hirda->Instance->CR1); - uint32_t cr3its; - uint32_t errorflags; - uint32_t errorcode; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE)); - if (errorflags == 0U) - { - /* IRDA in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && ((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U)) - { - IRDA_Receive_IT(hirda); - return; - } - } - - /* If some errors occur */ - cr3its = READ_REG(hirda->Instance->CR3); - if ((errorflags != 0U) - && (((cr3its & USART_CR3_EIE) != 0U) - || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U))) - { - /* IRDA parity error interrupt occurred -------------------------------------*/ - if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) - { - __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_PEF); - - hirda->ErrorCode |= HAL_IRDA_ERROR_PE; - } - - /* IRDA frame error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_FEF); - - hirda->ErrorCode |= HAL_IRDA_ERROR_FE; - } - - /* IRDA noise error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_NEF); - - hirda->ErrorCode |= HAL_IRDA_ERROR_NE; - } - - /* IRDA Over-Run interrupt occurred -----------------------------------------*/ - if (((isrflags & USART_ISR_ORE) != 0U) && - (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_EIE) != 0U))) - { - __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_OREF); - - hirda->ErrorCode |= HAL_IRDA_ERROR_ORE; - } - - /* Call IRDA Error Call back function if need be --------------------------*/ - if (hirda->ErrorCode != HAL_IRDA_ERROR_NONE) - { - /* IRDA in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && ((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U)) - { - IRDA_Receive_IT(hirda); - } - - /* If Overrun error occurs, or if any error occurs in DMA mode reception, - consider error as blocking */ - errorcode = hirda->ErrorCode; - if ((HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) || - ((errorcode & HAL_IRDA_ERROR_ORE) != 0U)) - { - /* Blocking error : transfer is aborted - Set the IRDA state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - IRDA_EndRxTransfer(hirda); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the IRDA DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel */ - if (hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback : - will lead to call HAL_IRDA_ErrorCallback() at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = IRDA_DMAAbortOnError; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) - { - /* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */ - hirda->hdmarx->XferAbortCallback(hirda->hdmarx); - } - } - else - { -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hirda->ErrorCallback(hirda); -#else - /* Call legacy weak user error callback */ - HAL_IRDA_ErrorCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hirda->ErrorCallback(hirda); -#else - /* Call legacy weak user error callback */ - HAL_IRDA_ErrorCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hirda->ErrorCallback(hirda); -#else - /* Call legacy weak user error callback */ - HAL_IRDA_ErrorCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - } - } - return; - - } /* End if some error occurs */ - - /* IRDA in mode Transmitter ------------------------------------------------*/ - if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) && ((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U)) - { - IRDA_Transmit_IT(hirda); - return; - } - - /* IRDA in mode Transmitter (transmission end) -----------------------------*/ - if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) - { - IRDA_EndTransmit_IT(hirda); - return; - } - -} - -/** - * @brief Tx Transfer completed callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_TxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Tx Half Transfer completed callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified USART module. - * @retval None - */ -__weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_TxHalfCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_RxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Half Transfer complete callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_RxHalfCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief IRDA error callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_ErrorCallback can be implemented in the user file. - */ -} - -/** - * @brief IRDA Abort Complete callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief IRDA Abort Complete callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_AbortTransmitCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief IRDA Abort Receive Complete callback. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_AbortReceiveCpltCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup IRDA_Exported_Functions_Group4 Peripheral State and Error functions - * @brief IRDA State and Errors functions - * -@verbatim - ============================================================================== - ##### Peripheral State and Error functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to return the State of IrDA - communication process and also return Peripheral Errors occurred during communication process - (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state - of the IRDA peripheral handle. - (+) HAL_IRDA_GetError() checks in run-time errors that could occur during - communication. - -@endverbatim - * @{ - */ - -/** - * @brief Return the IRDA handle state. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval HAL state - */ -HAL_IRDA_StateTypeDef HAL_IRDA_GetState(const IRDA_HandleTypeDef *hirda) -{ - /* Return IRDA handle state */ - uint32_t temp1; - uint32_t temp2; - temp1 = (uint32_t)hirda->gState; - temp2 = (uint32_t)hirda->RxState; - - return (HAL_IRDA_StateTypeDef)(temp1 | temp2); -} - -/** - * @brief Return the IRDA handle error code. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval IRDA Error Code - */ -uint32_t HAL_IRDA_GetError(const IRDA_HandleTypeDef *hirda) -{ - return hirda->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup IRDA_Private_Functions IRDA Private Functions - * @{ - */ - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) -/** - * @brief Initialize the callbacks to their default values. - * @param hirda IRDA handle. - * @retval none - */ -void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda) -{ - /* Init the IRDA Callback settings */ - hirda->TxHalfCpltCallback = HAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - hirda->TxCpltCallback = HAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */ - hirda->RxHalfCpltCallback = HAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - hirda->RxCpltCallback = HAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */ - hirda->ErrorCallback = HAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */ - hirda->AbortCpltCallback = HAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - hirda->AbortTransmitCpltCallback = HAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ - hirda->AbortReceiveCpltCallback = HAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ - -} -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ - -/** - * @brief Configure the IRDA peripheral. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval HAL status - */ -static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda) -{ - uint32_t tmpreg; - IRDA_ClockSourceTypeDef clocksource; - HAL_StatusTypeDef ret = HAL_OK; - static const uint16_t IRDAPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; - uint32_t pclk; - - /* Check the communication parameters */ - 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_TX_RX_MODE(hirda->Init.Mode)); - assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler)); - assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode)); - assert_param(IS_IRDA_CLOCKPRESCALER(hirda->Init.ClockPrescaler)); - - /*-------------------------- USART CR1 Configuration -----------------------*/ - /* Configure the IRDA Word Length, Parity and transfer 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 ; - - MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg); - - /*-------------------------- USART CR3 Configuration -----------------------*/ - MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode); - - /*--------------------- USART clock PRESC Configuration ----------------*/ - /* Configure - * - IRDA Clock Prescaler: set PRESCALER according to hirda->Init.ClockPrescaler value */ - MODIFY_REG(hirda->Instance->PRESC, USART_PRESC_PRESCALER, hirda->Init.ClockPrescaler); - - /*-------------------------- USART GTPR Configuration ----------------------*/ - MODIFY_REG(hirda->Instance->GTPR, (uint16_t)USART_GTPR_PSC, (uint16_t)hirda->Init.Prescaler); - - /*-------------------------- USART BRR Configuration -----------------------*/ - IRDA_GETCLOCKSOURCE(hirda, clocksource); - tmpreg = 0U; - switch (clocksource) - { - case IRDA_CLOCKSOURCE_PLL2Q: - pclk = HAL_RCC_GetPLL2QFreq(); - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - case IRDA_CLOCKSOURCE_PLL3Q: - pclk = HAL_RCC_GetPLL3QFreq(); - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - case IRDA_CLOCKSOURCE_CSI: - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(CSI_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - case IRDA_CLOCKSOURCE_PCLK1: - pclk = HAL_RCC_GetPCLK1Freq(); - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - case IRDA_CLOCKSOURCE_PCLK2: - pclk = HAL_RCC_GetPCLK2Freq(); - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - case IRDA_CLOCKSOURCE_HSI: - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(HSI_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - case IRDA_CLOCKSOURCE_LSE: - tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16((uint32_t)LSE_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); - break; - default: - ret = HAL_ERROR; - break; - } - - /* USARTDIV must be greater than or equal to 0d16 */ - if ((tmpreg >= USART_BRR_MIN) && (tmpreg <= USART_BRR_MAX)) - { - hirda->Instance->BRR = (uint16_t)tmpreg; - } - else - { - ret = HAL_ERROR; - } - - return ret; -} - -/** - * @brief Check the IRDA Idle State. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval HAL status - */ -static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda) -{ - uint32_t tickstart; - - /* Initialize the IRDA ErrorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check if the Transmitter is enabled */ - if ((hirda->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) - { - /* Wait until TEACK flag is set */ - if (IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_TEACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK) - { - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - /* Check if the Receiver is enabled */ - if ((hirda->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) - { - /* Wait until REACK flag is set */ - if (IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_REACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK) - { - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - - /* Initialize the IRDA state*/ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - return HAL_OK; -} - -/** - * @brief Handle IRDA Communication Timeout. It waits - * until a flag is no longer in the specified status. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @param Flag Specifies the IRDA flag to check. - * @param Status The actual Flag status (SET or RESET) - * @param Tickstart Tick start value - * @param Timeout Timeout duration - * @retval HAL status - */ -static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is set */ - while ((__HAL_IRDA_GET_FLAG(hirda, Flag) ? SET : RESET) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) - interrupts for the interrupt process */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief End ongoing Tx transfer on IRDA peripheral (following error detection or Transmit completion). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - - /* At end of Tx process, restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* At end of Rx process, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; -} - - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief DMA IRDA transmit process complete callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - - /* DMA Normal mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - hirda->TxXferCount = 0U; - - /* Disable the DMA transfer for transmit request by resetting the DMAT bit - in the IRDA CR3 register */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Enable the IRDA Transmit Complete Interrupt */ - SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE); - } - /* DMA Circular mode */ - else - { -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Tx complete callback */ - hirda->TxCpltCallback(hirda); -#else - /* Call legacy weak Tx complete callback */ - HAL_IRDA_TxCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ - } - -} - -/** - * @brief DMA IRDA transmit process half complete callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Tx Half complete callback */ - hirda->TxHalfCpltCallback(hirda); -#else - /* Call legacy weak Tx complete callback */ - HAL_IRDA_TxHalfCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - -/** - * @brief DMA IRDA receive process complete callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - - /* DMA Normal mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - hirda->RxXferCount = 0U; - - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Disable the DMA transfer for the receiver request by resetting the DMAR bit - in the IRDA CR3 register */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* At end of Rx process, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - } - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Rx complete callback */ - hirda->RxCpltCallback(hirda); -#else - /* Call legacy weak Rx complete callback */ - HAL_IRDA_RxCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA IRDA receive process half complete callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /*Call registered Rx Half complete callback*/ - hirda->RxHalfCpltCallback(hirda); -#else - /* Call legacy weak Rx Half complete callback */ - HAL_IRDA_RxHalfCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - -/** - * @brief DMA IRDA communication error callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void IRDA_DMAError(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - - /* Stop IRDA DMA Tx request if ongoing */ - if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) - { - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - hirda->TxXferCount = 0U; - IRDA_EndTxTransfer(hirda); - } - } - - /* Stop IRDA DMA Rx request if ongoing */ - if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) - { - if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - hirda->RxXferCount = 0U; - IRDA_EndRxTransfer(hirda); - } - } - - hirda->ErrorCode |= HAL_IRDA_ERROR_DMA; -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hirda->ErrorCallback(hirda); -#else - /* Call legacy weak user error callback */ - HAL_IRDA_ErrorCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - -/** - * @brief DMA IRDA communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - hirda->RxXferCount = 0U; - hirda->TxXferCount = 0U; - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hirda->ErrorCallback(hirda); -#else - /* Call legacy weak user error callback */ - HAL_IRDA_ErrorCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - -/** - * @brief DMA IRDA Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - - hirda->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (hirda->hdmarx != NULL) - { - if (hirda->hdmarx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hirda->TxXferCount = 0U; - hirda->RxXferCount = 0U; - - /* Reset errorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - hirda->AbortCpltCallback(hirda); -#else - /* Call legacy weak Abort complete callback */ - HAL_IRDA_AbortCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - - -/** - * @brief DMA IRDA Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - - hirda->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (hirda->hdmatx != NULL) - { - if (hirda->hdmatx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hirda->TxXferCount = 0U; - hirda->RxXferCount = 0U; - - /* Reset errorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - hirda->AbortCpltCallback(hirda); -#else - /* Call legacy weak Abort complete callback */ - HAL_IRDA_AbortCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - - -/** - * @brief DMA IRDA Tx communication abort callback, when initiated by user by a call to - * HAL_IRDA_AbortTransmit_IT API (Abort only Tx transfer) - * (This callback is executed at end of DMA Tx Abort procedure following user abort request, - * and leads to user Tx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); - - hirda->TxXferCount = 0U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - hirda->AbortTransmitCpltCallback(hirda); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_IRDA_AbortTransmitCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - -/** - * @brief DMA IRDA Rx communication abort callback, when initiated by user by a call to - * HAL_IRDA_AbortReceive_IT API (Abort only Rx transfer) - * (This callback is executed at end of DMA Rx Abort procedure following user abort request, - * and leads to user Rx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hirda->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - hirda->AbortReceiveCpltCallback(hirda); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_IRDA_AbortReceiveCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Send an amount of data in interrupt mode. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_IRDA_Transmit_IT(). - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -static void IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) -{ - const uint16_t *tmp; - - /* Check that a Tx process is ongoing */ - if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) - { - if (hirda->TxXferCount == 0U) - { - /* Disable the IRDA Transmit Data Register Empty Interrupt */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - - /* Enable the IRDA Transmit Complete Interrupt */ - SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE); - } - else - { - if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) - { - tmp = (const uint16_t *) hirda->pTxBuffPtr; /* Derogation R.11.3 */ - hirda->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); - hirda->pTxBuffPtr += 2U; - } - else - { - hirda->Instance->TDR = (uint8_t)(*hirda->pTxBuffPtr & 0xFFU); - hirda->pTxBuffPtr++; - } - hirda->TxXferCount--; - } - } -} - -/** - * @brief Wrap up transmission in non-blocking mode. - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -static void IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda) -{ - /* Disable the IRDA Transmit Complete Interrupt */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TCIE); - - /* Tx process is ended, restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Tx complete callback */ - hirda->TxCpltCallback(hirda); -#else - /* Call legacy weak Tx complete callback */ - HAL_IRDA_TxCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ -} - -/** - * @brief Receive an amount of data in interrupt mode. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_IRDA_Receive_IT() - * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -static void IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) -{ - uint16_t *tmp; - uint16_t uhMask = hirda->Mask; - uint16_t uhdata; - - /* Check that a Rx process is ongoing */ - if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) - { - uhdata = (uint16_t) READ_REG(hirda->Instance->RDR); - if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) - { - tmp = (uint16_t *) hirda->pRxBuffPtr; /* Derogation R.11.3 */ - *tmp = (uint16_t)(uhdata & uhMask); - hirda->pRxBuffPtr += 2U; - } - else - { - *hirda->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); - hirda->pRxBuffPtr++; - } - - hirda->RxXferCount--; - if (hirda->RxXferCount == 0U) - { - /* Disable the IRDA Parity Error Interrupt and RXNE interrupt */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - - /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Rx process is completed, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - -#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) - /* Call registered Rx complete callback */ - hirda->RxCpltCallback(hirda); -#else - /* Call legacy weak Rx complete callback */ - HAL_IRDA_RxCpltCallback(hirda); -#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_IRDA_SEND_REQ(hirda, IRDA_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @} - */ - -#endif /* HAL_IRDA_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_irda.c + * @author MCD Application Team + * @brief IRDA HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the IrDA (Infrared Data Association) Peripheral + * (IRDA) + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + Peripheral Control functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The IRDA HAL driver can be used as follows: + + (#) Declare a IRDA_HandleTypeDef handle structure (eg. IRDA_HandleTypeDef hirda). + (#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API + in setting the associated USART or UART in IRDA mode: + (++) Enable the USARTx/UARTx interface clock. + (++) USARTx/UARTx pins configuration: + (+++) Enable the clock for the USARTx/UARTx GPIOs. + (+++) Configure these USARTx/UARTx pins (TX as alternate function pull-up, RX as alternate function Input). + (++) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT() + and HAL_IRDA_Receive_IT() APIs): + (+++) Configure the USARTx/UARTx interrupt priority. + (+++) Enable the NVIC USARTx/UARTx IRQ handle. + (+++) 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. + + (++) 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 channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx channel. + (+++) Associate the initialized 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 channel. + + (#) Program the Baud Rate, Word Length and Parity and Mode(Receiver/Transmitter), + the normal or low power mode and the clock prescaler in the hirda handle 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 customized 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 operation modes 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 half of transfer HAL_IRDA_TxHalfCpltCallback() is executed and user can + add his own code by customization of function pointer HAL_IRDA_TxHalfCpltCallback() + (+) 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 half of transfer HAL_IRDA_RxHalfCpltCallback() is executed and user can + add his own code by customization of function pointer HAL_IRDA_RxHalfCpltCallback() + (+) 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 : Check whether the specified IRDA flag is set or not + (+) __HAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag + (+) __HAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt + (+) __HAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt + (+) __HAL_IRDA_GET_IT_SOURCE: Check whether or not the specified IRDA interrupt is enabled + + [..] + (@) You can refer to the IRDA HAL driver header file for more useful macros + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_HAL_IRDA_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function HAL_IRDA_RegisterCallback() to register a user callback. + Function HAL_IRDA_RegisterCallback() allows to register following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : IRDA MspInit. + (+) MspDeInitCallback : IRDA MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_IRDA_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_IRDA_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) MspInitCallback : IRDA MspInit. + (+) MspDeInitCallback : IRDA MspDeInit. + + [..] + By default, after the HAL_IRDA_Init() and when the state is HAL_IRDA_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxHalfCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak functions in the HAL_IRDA_Init() + and HAL_IRDA_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_IRDA_Init() and HAL_IRDA_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in HAL_IRDA_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_IRDA_STATE_READY or HAL_IRDA_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_IRDA_RegisterCallback() before calling HAL_IRDA_DeInit() + or HAL_IRDA_Init() function. + + [..] + When The compilation define USE_HAL_IRDA_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup IRDA IRDA + * @brief HAL IRDA module driver + * @{ + */ + +#ifdef HAL_IRDA_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup IRDA_Private_Constants IRDA Private Constants + * @{ + */ +#define IRDA_TEACK_REACK_TIMEOUT 1000U /*!< IRDA TX or RX enable acknowledge time-out value */ + +#define IRDA_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE \ + | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) /*!< UART or USART CR1 fields of parameters set by IRDA_SetConfig API */ + +#define USART_BRR_MIN 0x10U /*!< USART BRR minimum authorized value */ + +#define USART_BRR_MAX 0x0000FFFFU /*!< USART BRR maximum authorized value */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup IRDA_Private_Macros IRDA Private Macros + * @{ + */ +/** @brief BRR division operation to set BRR register in 16-bit oversampling mode. + * @param __PCLK__ IRDA clock source. + * @param __BAUD__ Baud rate set by the user. + * @param __PRESCALER__ IRDA clock prescaler value. + * @retval Division result + */ +#define IRDA_DIV_SAMPLING16(__PCLK__, __BAUD__, __PRESCALER__) ((((__PCLK__)/IRDAPrescTable[(__PRESCALER__)])\ + + ((__BAUD__)/2U)) / (__BAUD__)) +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup IRDA_Private_Functions + * @{ + */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) +void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ +static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout); +#if defined(HAL_DMA_MODULE_ENABLED) +static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda); +#endif /* HAL_DMA_MODULE_ENABLED */ +static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda); +#if defined(HAL_DMA_MODULE_ENABLED) +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAError(DMA_HandleTypeDef *hdma); +static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +#endif /* HAL_DMA_MODULE_ENABLED */ +static void IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda); +static void IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda); +static void IRDA_Receive_IT(IRDA_HandleTypeDef *hirda); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup IRDA_Exported_Functions IRDA Exported Functions + * @{ + */ + +/** @defgroup IRDA_Exported_Functions_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 + in asynchronous IRDA mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) 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. + (++) Power mode + (++) Prescaler setting + (++) Receiver/transmitter modes + + [..] + The HAL_IRDA_Init() API follows the USART asynchronous configuration procedures + (details for the procedures are available in reference manual). + +@endverbatim + + Depending on the frame length defined by the M1 and M0 bits (7-bit, + 8-bit or 9-bit), the possible IRDA frame formats are listed in the + following table. + + Table 1. IRDA frame format. + +-----------------------------------------------------------------------+ + | M1 bit | M0 bit | PCE bit | IRDA frame | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 0 | | SB | 8 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 0 | | SB | 9 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 0 | | SB | 7 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | + +-----------------------------------------------------------------------+ + + * @{ + */ + +/** + * @brief Initialize the IRDA mode according to the specified + * parameters in the IRDA_InitTypeDef and initialize the associated handle. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if (hirda == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the IRDA handle */ + assert_param(IS_IRDA_INSTANCE(hirda->Instance)); + + if (hirda->gState == HAL_IRDA_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hirda->Lock = HAL_UNLOCKED; + +#if USE_HAL_IRDA_REGISTER_CALLBACKS == 1 + IRDA_InitCallbacksToDefault(hirda); + + if (hirda->MspInitCallback == NULL) + { + hirda->MspInitCallback = HAL_IRDA_MspInit; + } + + /* Init the low level hardware */ + hirda->MspInitCallback(hirda); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_IRDA_MspInit(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ + } + + hirda->gState = HAL_IRDA_STATE_BUSY; + + /* Disable the Peripheral to update the configuration registers */ + __HAL_IRDA_DISABLE(hirda); + + /* Set the IRDA Communication parameters */ + if (IRDA_SetConfig(hirda) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* 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.*/ + CLEAR_BIT(hirda->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP)); + CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL)); + + /* set the UART/USART in IRDA mode */ + hirda->Instance->CR3 |= USART_CR3_IREN; + + /* Enable the Peripheral */ + __HAL_IRDA_ENABLE(hirda); + + /* TEACK and/or REACK to check before moving hirda->gState and hirda->RxState to Ready */ + return (IRDA_CheckIdleState(hirda)); +} + +/** + * @brief DeInitialize the IRDA peripheral. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if (hirda == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the IRDA handle */ + assert_param(IS_IRDA_INSTANCE(hirda->Instance)); + + hirda->gState = HAL_IRDA_STATE_BUSY; + + /* DeInit the low level hardware */ +#if USE_HAL_IRDA_REGISTER_CALLBACKS == 1 + if (hirda->MspDeInitCallback == NULL) + { + hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; + } + /* DeInit the low level hardware */ + hirda->MspDeInitCallback(hirda); +#else + HAL_IRDA_MspDeInit(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ + /* Disable the Peripheral */ + __HAL_IRDA_DISABLE(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->gState = HAL_IRDA_STATE_RESET; + hirda->RxState = HAL_IRDA_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + +/** + * @brief Initialize the IRDA MSP. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_IRDA_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitialize the IRDA MSP. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_IRDA_MspDeInit can be implemented in the user file + */ +} + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User IRDA Callback + * To be used to override the weak predefined callback + * @note The HAL_IRDA_RegisterCallback() may be called before HAL_IRDA_Init() in HAL_IRDA_STATE_RESET + * to register callbacks for HAL_IRDA_MSPINIT_CB_ID and HAL_IRDA_MSPDEINIT_CB_ID + * @param hirda irda handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref HAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref HAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_IRDA_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref HAL_IRDA_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_RegisterCallback(IRDA_HandleTypeDef *hirda, HAL_IRDA_CallbackIDTypeDef CallbackID, + pIRDA_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (hirda->gState == HAL_IRDA_STATE_READY) + { + switch (CallbackID) + { + case HAL_IRDA_TX_HALFCOMPLETE_CB_ID : + hirda->TxHalfCpltCallback = pCallback; + break; + + case HAL_IRDA_TX_COMPLETE_CB_ID : + hirda->TxCpltCallback = pCallback; + break; + + case HAL_IRDA_RX_HALFCOMPLETE_CB_ID : + hirda->RxHalfCpltCallback = pCallback; + break; + + case HAL_IRDA_RX_COMPLETE_CB_ID : + hirda->RxCpltCallback = pCallback; + break; + + case HAL_IRDA_ERROR_CB_ID : + hirda->ErrorCallback = pCallback; + break; + + case HAL_IRDA_ABORT_COMPLETE_CB_ID : + hirda->AbortCpltCallback = pCallback; + break; + + case HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID : + hirda->AbortTransmitCpltCallback = pCallback; + break; + + case HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID : + hirda->AbortReceiveCpltCallback = pCallback; + break; + + case HAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = pCallback; + break; + + case HAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hirda->gState == HAL_IRDA_STATE_RESET) + { + switch (CallbackID) + { + case HAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = pCallback; + break; + + case HAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an IRDA callback + * IRDA callback is redirected to the weak predefined callback + * @note The HAL_IRDA_UnRegisterCallback() may be called before HAL_IRDA_Init() in HAL_IRDA_STATE_RESET + * to un-register callbacks for HAL_IRDA_MSPINIT_CB_ID and HAL_IRDA_MSPDEINIT_CB_ID + * @param hirda irda handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_IRDA_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref HAL_IRDA_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_IRDA_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref HAL_IRDA_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_IRDA_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_IRDA_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref HAL_IRDA_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_IRDA_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_UnRegisterCallback(IRDA_HandleTypeDef *hirda, HAL_IRDA_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_IRDA_STATE_READY == hirda->gState) + { + switch (CallbackID) + { + case HAL_IRDA_TX_HALFCOMPLETE_CB_ID : + hirda->TxHalfCpltCallback = HAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case HAL_IRDA_TX_COMPLETE_CB_ID : + hirda->TxCpltCallback = HAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_IRDA_RX_HALFCOMPLETE_CB_ID : + hirda->RxHalfCpltCallback = HAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case HAL_IRDA_RX_COMPLETE_CB_ID : + hirda->RxCpltCallback = HAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_IRDA_ERROR_CB_ID : + hirda->ErrorCallback = HAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_IRDA_ABORT_COMPLETE_CB_ID : + hirda->AbortCpltCallback = HAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_IRDA_ABORT_TRANSMIT_COMPLETE_CB_ID : + hirda->AbortTransmitCpltCallback = HAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak + AbortTransmitCpltCallback */ + break; + + case HAL_IRDA_ABORT_RECEIVE_COMPLETE_CB_ID : + hirda->AbortReceiveCpltCallback = HAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak + AbortReceiveCpltCallback */ + break; + + case HAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = HAL_IRDA_MspInit; /* Legacy weak MspInitCallback */ + break; + + case HAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_IRDA_STATE_RESET == hirda->gState) + { + switch (CallbackID) + { + case HAL_IRDA_MSPINIT_CB_ID : + hirda->MspInitCallback = HAL_IRDA_MspInit; + break; + + case HAL_IRDA_MSPDEINIT_CB_ID : + hirda->MspDeInitCallback = HAL_IRDA_MspDeInit; + break; + + default : + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hirda->ErrorCode |= HAL_IRDA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup IRDA_Exported_Functions_Group2 IO operation functions + * @brief IRDA Transmit and 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 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 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 respectively 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 APIs are : + (++) HAL_IRDA_Transmit() + (++) HAL_IRDA_Receive() + + (#) Non Blocking mode APIs with Interrupt are : + (++) HAL_IRDA_Transmit_IT() + (++) HAL_IRDA_Receive_IT() + (++) HAL_IRDA_IRQHandler() + + (#) Non Blocking mode functions with DMA are : + (++) HAL_IRDA_Transmit_DMA() + (++) HAL_IRDA_Receive_DMA() + (++) HAL_IRDA_DMAPause() + (++) HAL_IRDA_DMAResume() + (++) HAL_IRDA_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in Non Blocking mode: + (++) HAL_IRDA_TxHalfCpltCallback() + (++) HAL_IRDA_TxCpltCallback() + (++) HAL_IRDA_RxHalfCpltCallback() + (++) HAL_IRDA_RxCpltCallback() + (++) HAL_IRDA_ErrorCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (++) HAL_IRDA_Abort() + (++) HAL_IRDA_AbortTransmit() + (++) HAL_IRDA_AbortReceive() + (++) HAL_IRDA_Abort_IT() + (++) HAL_IRDA_AbortTransmit_IT() + (++) HAL_IRDA_AbortReceive_IT() + + (#) For Abort services based on interrupts (HAL_IRDA_Abortxxx_IT), a set of Abort Complete Callbacks are provided: + (++) HAL_IRDA_AbortCpltCallback() + (++) HAL_IRDA_AbortTransmitCpltCallback() + (++) HAL_IRDA_AbortReceiveCpltCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error + in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user + to identify error type, and HAL_IRDA_ErrorCallback() user callback is executed. + Transfer is kept ongoing on IRDA side. + If user wants to abort it, Abort services should be called by user. + (++) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, and + HAL_IRDA_ErrorCallback() user callback is executed. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @param Timeout Specify timeout value. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + const uint8_t *pdata8bits; + const uint16_t *pdata16bits; + uint32_t tickstart; + + /* Check that a Tx process is not already ongoing */ + if (hirda->gState == HAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->gState = HAL_IRDA_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */ + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (const uint16_t *) pData; /* Derogation R.11.3 */ + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + while (hirda->TxXferCount > 0U) + { + hirda->TxXferCount--; + + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if (pdata8bits == NULL) + { + hirda->Instance->TDR = (uint16_t)(*pdata16bits & 0x01FFU); + pdata16bits++; + } + else + { + hirda->Instance->TDR = (uint8_t)(*pdata8bits & 0xFFU); + pdata8bits++; + } + } + + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* At end of Tx process, restore hirda->gState to Ready */ + hirda->gState = 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. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) 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) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + uint16_t uhMask; + uint32_t tickstart; + + /* Check that a Rx process is not already ongoing */ + if (hirda->RxState == HAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->RxState = HAL_IRDA_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Computation of the mask to apply to RDR register + of the UART associated to the IRDA */ + IRDA_MASK_COMPUTATION(hirda); + uhMask = hirda->Mask; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) pData; /* Derogation R.11.3 */ + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + /* Check data remaining to be received */ + while (hirda->RxXferCount > 0U) + { + hirda->RxXferCount--; + + if (IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if (pdata8bits == NULL) + { + *pdata16bits = (uint16_t)(hirda->Instance->RDR & uhMask); + pdata16bits++; + } + else + { + *pdata8bits = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask); + pdata8bits++; + } + } + + /* At end of Rx process, restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size) +{ + /* Check that a Tx process is not already ongoing */ + if (hirda->gState == HAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->gState = HAL_IRDA_STATE_BUSY_TX; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Enable the IRDA Transmit Data Register Empty Interrupt */ + SET_BIT(hirda->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (hirda->RxState == HAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Computation of the mask to apply to the RDR register + of the UART associated to the IRDA */ + IRDA_MASK_COMPUTATION(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->RxState = HAL_IRDA_STATE_BUSY_RX; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + if (hirda->Init.Parity != IRDA_PARITY_NONE) + { + /* Enable the IRDA Parity Error and Data Register not empty Interrupts */ + SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); + } + else + { + /* Enable the IRDA Data Register not empty Interrupts */ + SET_BIT(hirda->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + + /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Send an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, const uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + uint16_t nbByte = Size; + + /* Check that a Tx process is not already ongoing */ + if (hirda->gState == HAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->gState = HAL_IRDA_STATE_BUSY_TX; + + /* Set the IRDA DMA transfer complete callback */ + hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt; + + /* Set the IRDA DMA half transfer complete callback */ + hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt; + + /* Set the DMA error callback */ + hirda->hdmatx->XferErrorCallback = IRDA_DMAError; + + /* Set the DMA abort callback */ + hirda->hdmatx->XferAbortCallback = NULL; + + /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + /* Check linked list mode */ + if ((hirda->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hirda->hdmatx->LinkedListQueue != NULL) && (hirda->hdmatx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + hirda->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + hirda->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)hirda->pTxBuffPtr; + + /* Set DMA destination address */ + hirda->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&hirda->Instance->TDR; + + /* Enable the IRDA transmit DMA channel */ + status = HAL_DMAEx_List_Start_IT(hirda->hdmatx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the IRDA transmit DMA channel */ + status = HAL_DMA_Start_IT(hirda->hdmatx, (uint32_t)hirda->pTxBuffPtr, (uint32_t)&hirda->Instance->TDR, nbByte); + } + + if (status == HAL_OK) + { + /* Clear the TC flag in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_TCF); + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + return HAL_OK; + } + else + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Restore hirda->gState to ready */ + hirda->gState = HAL_IRDA_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must reflect the number + * of u16 available through pData. + * @note When the IRDA parity is enabled (PCE = 1), the received data contains + * the parity bit (MSB position). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + uint16_t nbByte = Size; + + /* Check that a Rx process is not already ongoing */ + if (hirda->RxState == HAL_IRDA_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->RxState = HAL_IRDA_STATE_BUSY_RX; + + /* Set the IRDA DMA transfer complete callback */ + hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt; + + /* Set the IRDA DMA half transfer complete callback */ + hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt; + + /* Set the DMA error callback */ + hirda->hdmarx->XferErrorCallback = IRDA_DMAError; + + /* Set the DMA abort callback */ + hirda->hdmarx->XferAbortCallback = NULL; + + /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + /* Check linked list mode */ + if ((hirda->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hirda->hdmarx->LinkedListQueue != NULL) && (hirda->hdmarx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + hirda->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + hirda->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)&hirda->Instance->RDR; + + /* Set DMA destination address */ + hirda->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hirda->pRxBuffPtr; + + /* Enable the DMA channel */ + status = HAL_DMAEx_List_Start_IT(hirda->hdmarx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the DMA channel */ + status = HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->RDR, (uint32_t)hirda->pRxBuffPtr, nbByte); + } + + if (status == HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + if (hirda->Init.Parity != IRDA_PARITY_NONE) + { + /* Enable the UART Parity Error Interrupt */ + SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE); + } + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + return HAL_OK; + } + else + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Restore hirda->RxState to ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + + +/** + * @brief Pause the DMA Transfer. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda) +{ + /* Process Locked */ + __HAL_LOCK(hirda); + + if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) + { + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable the IRDA DMA Tx request */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + } + } + if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + { + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + /* Disable the IRDA DMA Rx request */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + +/** + * @brief Resume the DMA Transfer. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda) +{ + /* Process Locked */ + __HAL_LOCK(hirda); + + if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) + { + /* Enable the IRDA DMA Tx request */ + SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + } + if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + { + /* Clear the Overrun flag before resuming the Rx transfer*/ + __HAL_IRDA_CLEAR_OREFLAG(hirda); + + /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ + if (hirda->Init.Parity != IRDA_PARITY_NONE) + { + SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE); + } + SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + /* Enable the IRDA DMA Rx request */ + SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + +/** + * @brief Stop the DMA Transfer. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda) +{ + /* The Lock is not implemented on this API to allow the user application + to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback() / + HAL_IRDA_TxHalfCpltCallback / HAL_IRDA_RxHalfCpltCallback: + indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete + interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of + the stream and the corresponding call back is executed. */ + + /* Stop IRDA DMA Tx request if ongoing */ + if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) + { + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + /* Abort the IRDA DMA Tx channel */ + if (hirda->hdmatx != NULL) + { + if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + + IRDA_EndTxTransfer(hirda); + } + } + + /* Stop IRDA DMA Rx request if ongoing */ + if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + { + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA Rx channel */ + if (hirda->hdmarx != NULL) + { + if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + + IRDA_EndRxTransfer(hirda); + } + } + + return HAL_OK; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Abort(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | \ + USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the IRDA DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmatx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + + /* Disable the IRDA DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx and Rx transfer counters */ + hirda->TxXferCount = 0U; + hirda->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Reset Handle ErrorCode to No Error */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + return HAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (blocking mode). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the IRDA DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmatx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hirda->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hirda->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx transfer counter */ + hirda->TxXferCount = 0U; + + /* Restore hirda->gState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (blocking mode). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the IRDA DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hirda->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hirda->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hirda->ErrorCode = HAL_IRDA_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Rx transfer counter */ + hirda->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda) +{ + uint32_t abortcplt = 1U; + + /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | \ + USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* If DMA Tx and/or DMA Rx Handles are associated to IRDA Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (hirda->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if IRDA DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + hirda->hdmatx->XferAbortCallback = IRDA_DMATxAbortCallback; + } + else + { + hirda->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (hirda->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if IRDA DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + hirda->hdmarx->XferAbortCallback = IRDA_DMARxAbortCallback; + } + else + { + hirda->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the IRDA DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable DMA Tx at UART level */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmatx != NULL) + { + /* IRDA Tx DMA Abort callback has already been initialised : + will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK) + { + hirda->hdmatx->XferAbortCallback = NULL; + } + else + { + abortcplt = 0U; + } + } + } + + /* Disable the IRDA DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmarx != NULL) + { + /* IRDA Rx DMA Abort callback has already been initialised : + will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) + { + hirda->hdmarx->XferAbortCallback = NULL; + abortcplt = 1U; + } + else + { + abortcplt = 0U; + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (abortcplt == 1U) + { + /* Reset Tx and Rx transfer counters */ + hirda->TxXferCount = 0U; + hirda->RxXferCount = 0U; + + /* Reset errorCode */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + hirda->RxState = HAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hirda->AbortCpltCallback(hirda); +#else + /* Call legacy weak Abort complete callback */ + HAL_IRDA_AbortCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + + return HAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (Interrupt mode). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the IRDA DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmatx != NULL) + { + /* Set the IRDA DMA Abort callback : + will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + hirda->hdmatx->XferAbortCallback = IRDA_DMATxOnlyAbortCallback; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK) + { + /* Call Directly hirda->hdmatx->XferAbortCallback function in case of error */ + hirda->hdmatx->XferAbortCallback(hirda->hdmatx); + } + } + else + { + /* Reset Tx transfer counter */ + hirda->TxXferCount = 0U; + + /* Restore hirda->gState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hirda->AbortTransmitCpltCallback(hirda); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_IRDA_AbortTransmitCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Reset Tx transfer counter */ + hirda->TxXferCount = 0U; + + /* Restore hirda->gState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hirda->AbortTransmitCpltCallback(hirda); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_IRDA_AbortTransmitCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + + return HAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (Interrupt mode). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable IRDA Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the IRDA DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback : + will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = IRDA_DMARxOnlyAbortCallback; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) + { + /* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */ + hirda->hdmarx->XferAbortCallback(hirda->hdmarx); + } + } + else + { + /* Reset Rx transfer counter */ + hirda->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hirda->AbortReceiveCpltCallback(hirda); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_IRDA_AbortReceiveCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Reset Rx transfer counter */ + hirda->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hirda->AbortReceiveCpltCallback(hirda); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_IRDA_AbortReceiveCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + + return HAL_OK; +} + +/** + * @brief Handle IRDA interrupt request. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) +{ + uint32_t isrflags = READ_REG(hirda->Instance->ISR); + uint32_t cr1its = READ_REG(hirda->Instance->CR1); + uint32_t cr3its; + uint32_t errorflags; + uint32_t errorcode; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE)); + if (errorflags == 0U) + { + /* IRDA in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && ((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U)) + { + IRDA_Receive_IT(hirda); + return; + } + } + + /* If some errors occur */ + cr3its = READ_REG(hirda->Instance->CR3); + if ((errorflags != 0U) + && (((cr3its & USART_CR3_EIE) != 0U) + || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U))) + { + /* IRDA parity error interrupt occurred -------------------------------------*/ + if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_PEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_PE; + } + + /* IRDA frame error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_FEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_FE; + } + + /* IRDA noise error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_NEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_NE; + } + + /* IRDA Over-Run interrupt occurred -----------------------------------------*/ + if (((isrflags & USART_ISR_ORE) != 0U) && + (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_EIE) != 0U))) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_OREF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_ORE; + } + + /* Call IRDA Error Call back function if need be --------------------------*/ + if (hirda->ErrorCode != HAL_IRDA_ERROR_NONE) + { + /* IRDA in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && ((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U)) + { + IRDA_Receive_IT(hirda); + } + + /* If Overrun error occurs, or if any error occurs in DMA mode reception, + consider error as blocking */ + errorcode = hirda->ErrorCode; + if ((HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) || + ((errorcode & HAL_IRDA_ERROR_ORE) != 0U)) + { + /* Blocking error : transfer is aborted + Set the IRDA state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + IRDA_EndRxTransfer(hirda); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the IRDA DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA Rx channel */ + if (hirda->hdmarx != NULL) + { + /* Set the IRDA DMA Abort callback : + will lead to call HAL_IRDA_ErrorCallback() at end of DMA abort procedure */ + hirda->hdmarx->XferAbortCallback = IRDA_DMAAbortOnError; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) + { + /* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */ + hirda->hdmarx->XferAbortCallback(hirda->hdmarx); + } + } + else + { +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + HAL_IRDA_ErrorCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + HAL_IRDA_ErrorCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + HAL_IRDA_ErrorCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + } + } + return; + + } /* End if some error occurs */ + + /* IRDA in mode Transmitter ------------------------------------------------*/ + if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) && ((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U)) + { + IRDA_Transmit_IT(hirda); + return; + } + + /* IRDA in mode Transmitter (transmission end) -----------------------------*/ + if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) + { + IRDA_EndTransmit_IT(hirda); + return; + } + +} + +/** + * @brief Tx Transfer completed callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_TxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +__weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_TxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_RxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Half Transfer complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_RxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA error callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA Abort Complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA Abort Complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_AbortTransmitCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief IRDA Abort Receive Complete callback. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +__weak void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hirda); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_AbortReceiveCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup IRDA_Exported_Functions_Group4 Peripheral State and Error functions + * @brief IRDA State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Error functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to return the State of IrDA + communication process and also return Peripheral Errors occurred during communication process + (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state + of the IRDA peripheral handle. + (+) HAL_IRDA_GetError() checks in run-time errors that could occur during + communication. + +@endverbatim + * @{ + */ + +/** + * @brief Return the IRDA handle state. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval HAL state + */ +HAL_IRDA_StateTypeDef HAL_IRDA_GetState(const IRDA_HandleTypeDef *hirda) +{ + /* Return IRDA handle state */ + uint32_t temp1; + uint32_t temp2; + temp1 = (uint32_t)hirda->gState; + temp2 = (uint32_t)hirda->RxState; + + return (HAL_IRDA_StateTypeDef)(temp1 | temp2); +} + +/** + * @brief Return the IRDA handle error code. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval IRDA Error Code + */ +uint32_t HAL_IRDA_GetError(const IRDA_HandleTypeDef *hirda) +{ + return hirda->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup IRDA_Private_Functions IRDA Private Functions + * @{ + */ + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) +/** + * @brief Initialize the callbacks to their default values. + * @param hirda IRDA handle. + * @retval none + */ +void IRDA_InitCallbacksToDefault(IRDA_HandleTypeDef *hirda) +{ + /* Init the IRDA Callback settings */ + hirda->TxHalfCpltCallback = HAL_IRDA_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + hirda->TxCpltCallback = HAL_IRDA_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hirda->RxHalfCpltCallback = HAL_IRDA_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + hirda->RxCpltCallback = HAL_IRDA_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hirda->ErrorCallback = HAL_IRDA_ErrorCallback; /* Legacy weak ErrorCallback */ + hirda->AbortCpltCallback = HAL_IRDA_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hirda->AbortTransmitCpltCallback = HAL_IRDA_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + hirda->AbortReceiveCpltCallback = HAL_IRDA_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + +} +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ + +/** + * @brief Configure the IRDA peripheral. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda) +{ + uint32_t tmpreg; + IRDA_ClockSourceTypeDef clocksource; + HAL_StatusTypeDef ret = HAL_OK; + static const uint16_t IRDAPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; + uint32_t pclk; + + /* Check the communication parameters */ + 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_TX_RX_MODE(hirda->Init.Mode)); + assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler)); + assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode)); + assert_param(IS_IRDA_CLOCKPRESCALER(hirda->Init.ClockPrescaler)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Configure the IRDA Word Length, Parity and transfer 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 ; + + MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode); + + /*--------------------- USART clock PRESC Configuration ----------------*/ + /* Configure + * - IRDA Clock Prescaler: set PRESCALER according to hirda->Init.ClockPrescaler value */ + MODIFY_REG(hirda->Instance->PRESC, USART_PRESC_PRESCALER, hirda->Init.ClockPrescaler); + + /*-------------------------- USART GTPR Configuration ----------------------*/ + MODIFY_REG(hirda->Instance->GTPR, (uint16_t)USART_GTPR_PSC, (uint16_t)hirda->Init.Prescaler); + + /*-------------------------- USART BRR Configuration -----------------------*/ + IRDA_GETCLOCKSOURCE(hirda, clocksource); + tmpreg = 0U; + switch (clocksource) + { + case IRDA_CLOCKSOURCE_PLL2Q: + pclk = HAL_RCC_GetPLL2QFreq(); + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + case IRDA_CLOCKSOURCE_PLL3Q: + pclk = HAL_RCC_GetPLL3QFreq(); + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + case IRDA_CLOCKSOURCE_CSI: + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(CSI_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + case IRDA_CLOCKSOURCE_PCLK1: + pclk = HAL_RCC_GetPCLK1Freq(); + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + case IRDA_CLOCKSOURCE_PCLK2: + pclk = HAL_RCC_GetPCLK2Freq(); + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(pclk, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + case IRDA_CLOCKSOURCE_HSI: + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16(HSI_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + case IRDA_CLOCKSOURCE_LSE: + tmpreg = (uint32_t)(IRDA_DIV_SAMPLING16((uint32_t)LSE_VALUE, hirda->Init.BaudRate, hirda->Init.ClockPrescaler)); + break; + default: + ret = HAL_ERROR; + break; + } + + /* USARTDIV must be greater than or equal to 0d16 */ + if ((tmpreg >= USART_BRR_MIN) && (tmpreg <= USART_BRR_MAX)) + { + hirda->Instance->BRR = (uint16_t)tmpreg; + } + else + { + ret = HAL_ERROR; + } + + return ret; +} + +/** + * @brief Check the IRDA Idle State. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda) +{ + uint32_t tickstart; + + /* Initialize the IRDA ErrorCode */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check if the Transmitter is enabled */ + if ((hirda->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if (IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_TEACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if ((hirda->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if (IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_REACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + + /* Initialize the IRDA state*/ + hirda->gState = HAL_IRDA_STATE_READY; + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + +/** + * @brief Handle IRDA Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @param Flag Specifies the IRDA flag to check. + * @param Status The actual Flag status (SET or RESET) + * @param Tickstart Tick start value + * @param Timeout Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__HAL_IRDA_GET_FLAG(hirda, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) + interrupts for the interrupt process */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE)); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + hirda->gState = HAL_IRDA_STATE_READY; + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief End ongoing Tx transfer on IRDA peripheral (following error detection or Transmit completion). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda) +{ + /* Disable TXEIE and TCIE interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + + /* At end of Tx process, restore hirda->gState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + /* At end of Rx process, restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; +} + + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief DMA IRDA transmit process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + + /* DMA Normal mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + hirda->TxXferCount = 0U; + + /* Disable the DMA transfer for transmit request by resetting the DMAT bit + in the IRDA CR3 register */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + + /* Enable the IRDA Transmit Complete Interrupt */ + SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE); + } + /* DMA Circular mode */ + else + { +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Tx complete callback */ + hirda->TxCpltCallback(hirda); +#else + /* Call legacy weak Tx complete callback */ + HAL_IRDA_TxCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ + } + +} + +/** + * @brief DMA IRDA transmit process half complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Tx Half complete callback */ + hirda->TxHalfCpltCallback(hirda); +#else + /* Call legacy weak Tx complete callback */ + HAL_IRDA_TxHalfCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA receive process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + + /* DMA Normal mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + hirda->RxXferCount = 0U; + + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + /* Disable the DMA transfer for the receiver request by resetting the DMAR bit + in the IRDA CR3 register */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* At end of Rx process, restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + } + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hirda->RxCpltCallback(hirda); +#else + /* Call legacy weak Rx complete callback */ + HAL_IRDA_RxCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA IRDA receive process half complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /*Call registered Rx Half complete callback*/ + hirda->RxHalfCpltCallback(hirda); +#else + /* Call legacy weak Rx Half complete callback */ + HAL_IRDA_RxHalfCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA communication error callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void IRDA_DMAError(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + + /* Stop IRDA DMA Tx request if ongoing */ + if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) + { + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + { + hirda->TxXferCount = 0U; + IRDA_EndTxTransfer(hirda); + } + } + + /* Stop IRDA DMA Rx request if ongoing */ + if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + { + if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + { + hirda->RxXferCount = 0U; + IRDA_EndRxTransfer(hirda); + } + } + + hirda->ErrorCode |= HAL_IRDA_ERROR_DMA; +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + HAL_IRDA_ErrorCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA communication abort callback, when initiated by HAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + hirda->RxXferCount = 0U; + hirda->TxXferCount = 0U; + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hirda->ErrorCallback(hirda); +#else + /* Call legacy weak user error callback */ + HAL_IRDA_ErrorCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + + hirda->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hirda->hdmarx != NULL) + { + if (hirda->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hirda->TxXferCount = 0U; + hirda->RxXferCount = 0U; + + /* Reset errorCode */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hirda->AbortCpltCallback(hirda); +#else + /* Call legacy weak Abort complete callback */ + HAL_IRDA_AbortCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + + +/** + * @brief DMA IRDA Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + + hirda->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hirda->hdmatx != NULL) + { + if (hirda->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hirda->TxXferCount = 0U; + hirda->RxXferCount = 0U; + + /* Reset errorCode */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->gState and hirda->RxState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hirda->AbortCpltCallback(hirda); +#else + /* Call legacy weak Abort complete callback */ + HAL_IRDA_AbortCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + + +/** + * @brief DMA IRDA Tx communication abort callback, when initiated by user by a call to + * HAL_IRDA_AbortTransmit_IT API (Abort only Tx transfer) + * (This callback is executed at end of DMA Tx Abort procedure following user abort request, + * and leads to user Tx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)(hdma->Parent); + + hirda->TxXferCount = 0U; + + /* Restore hirda->gState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hirda->AbortTransmitCpltCallback(hirda); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_IRDA_AbortTransmitCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief DMA IRDA Rx communication abort callback, when initiated by user by a call to + * HAL_IRDA_AbortReceive_IT API (Abort only Rx transfer) + * (This callback is executed at end of DMA Rx Abort procedure following user abort request, + * and leads to user Rx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef *hirda = (IRDA_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hirda->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF); + + /* Restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hirda->AbortReceiveCpltCallback(hirda); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_IRDA_AbortReceiveCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Send an amount of data in interrupt mode. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Transmit_IT(). + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +static void IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) +{ + const uint16_t *tmp; + + /* Check that a Tx process is ongoing */ + if (hirda->gState == HAL_IRDA_STATE_BUSY_TX) + { + if (hirda->TxXferCount == 0U) + { + /* Disable the IRDA Transmit Data Register Empty Interrupt */ + CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + + /* Enable the IRDA Transmit Complete Interrupt */ + SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE); + } + else + { + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (const uint16_t *) hirda->pTxBuffPtr; /* Derogation R.11.3 */ + hirda->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); + hirda->pTxBuffPtr += 2U; + } + else + { + hirda->Instance->TDR = (uint8_t)(*hirda->pTxBuffPtr & 0xFFU); + hirda->pTxBuffPtr++; + } + hirda->TxXferCount--; + } + } +} + +/** + * @brief Wrap up transmission in non-blocking mode. + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +static void IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda) +{ + /* Disable the IRDA Transmit Complete Interrupt */ + CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TCIE); + + /* Tx process is ended, restore hirda->gState to Ready */ + hirda->gState = HAL_IRDA_STATE_READY; + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Tx complete callback */ + hirda->TxCpltCallback(hirda); +#else + /* Call legacy weak Tx complete callback */ + HAL_IRDA_TxCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACK */ +} + +/** + * @brief Receive an amount of data in interrupt mode. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Receive_IT() + * @param hirda Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +static void IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) +{ + uint16_t *tmp; + uint16_t uhMask = hirda->Mask; + uint16_t uhdata; + + /* Check that a Rx process is ongoing */ + if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + { + uhdata = (uint16_t) READ_REG(hirda->Instance->RDR); + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t *) hirda->pRxBuffPtr; /* Derogation R.11.3 */ + *tmp = (uint16_t)(uhdata & uhMask); + hirda->pRxBuffPtr += 2U; + } + else + { + *hirda->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); + hirda->pRxBuffPtr++; + } + + hirda->RxXferCount--; + if (hirda->RxXferCount == 0U) + { + /* Disable the IRDA Parity Error Interrupt and RXNE interrupt */ + CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + + /* Rx process is completed, restore hirda->RxState to Ready */ + hirda->RxState = HAL_IRDA_STATE_READY; + +#if (USE_HAL_IRDA_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hirda->RxCpltCallback(hirda); +#else + /* Call legacy weak Rx complete callback */ + HAL_IRDA_RxCpltCallback(hirda); +#endif /* USE_HAL_IRDA_REGISTER_CALLBACKS */ + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_IRDA_SEND_REQ(hirda, IRDA_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @} + */ + +#endif /* HAL_IRDA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_iwdg.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_iwdg.c index 2ae9f3208..8b677fee5 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_iwdg.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_iwdg.c @@ -1,510 +1,510 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_iwdg.c - * @author MCD Application Team - * @brief IWDG HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Independent Watchdog (IWDG) peripheral: - * + Initialization and Start functions - * + IO operation functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### IWDG Generic features ##### - ============================================================================== - [..] - (+) The IWDG can be started by either software or hardware (configurable - through option byte). - - (+) The IWDG is clocked by the Low-Speed Internal clock (LSI) and thus stays - active even if the main clock fails. - - (+) Once the IWDG is started, the LSI is forced ON and both cannot be - disabled. The counter starts counting down from the reset value (0xFFF). - When it reaches the end of count value (0x000) a reset signal is - generated (IWDG reset). - - (+) Whenever the key value 0x0000 AAAA is written in the IWDG_KR register, - the IWDG_RLR value is reloaded into the counter and the watchdog reset - is prevented. - - (+) The IWDG is implemented in the VDD voltage domain that is still functional - in STOP and STANDBY mode (IWDG reset can wake up the CPU from STANDBY). - IWDGRST flag in RCC_CSR register can be used to inform when an IWDG - reset occurs. - - (+) Debug mode: When the microcontroller enters debug mode (core halted), - the IWDG counter either continues to work normally or stops, depending - on DBG_IWDG_STOP configuration bit in DBG module, accessible through - __HAL_DBGMCU_FREEZE_IWDG() and __HAL_DBGMCU_UNFREEZE_IWDG() macros. - - [..] Min-max timeout value @32KHz (LSI): ~125us / ~32.7s - The IWDG timeout may vary due to LSI clock frequency dispersion. - STM32H7RSxx devices provide the capability to measure the LSI clock - frequency (LSI clock is internally connected to TIM16 CH1 input capture). - The measured value can be used to have an IWDG timeout with an - acceptable accuracy. - - [..] Default timeout value (necessary for IWDG_SR status register update): - Constant LSI_VALUE is defined based on the nominal LSI clock frequency. - This frequency being subject to variations as mentioned above, the - default timeout value (defined through constant HAL_IWDG_DEFAULT_TIMEOUT - below) may become too short or too long. - In such cases, this default timeout value can be tuned by redefining - the constant LSI_VALUE at user-application level (based, for instance, - on the measured LSI clock frequency as explained above). - - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Register callback to treat Iwdg interrupt and MspInit using HAL_IWDG_RegisterCallback(). - (++) Provide exiting handle as first parameter. - (++) Provide which callback will be registered using one value from - HAL_IWDG_CallbackIDTypeDef. - (++) Provide callback function pointer. - - (#) Use IWDG using HAL_IWDG_Init() function to : - (++) Enable instance by writing Start keyword in IWDG_KEY register. LSI - clock is forced ON and IWDG counter starts counting down. - (++) Enable write access to configuration registers: - IWDG_PR, IWDG_RLR, IWDG_WINR and EWCR. - (++) Configure the IWDG prescaler and counter reload value. This reload - value will be loaded in the IWDG counter each time the watchdog is - reloaded, then the IWDG will start counting down from this value. - (++) Depending on window parameter: - (+++) If Window Init parameter is same as Window register value, - nothing more is done but reload counter value in order to exit - function with exact time base. - (+++) Else modify Window register. This will automatically reload - watchdog counter. - (++) Depending on Early Wakeup Interrupt parameter: - (+++) If EWI is set to disable, comparator is set to 0, interrupt is - disable & flag is clear. - (+++) Else modify EWCR register, setting comparator value, enable - interrupt & clear flag. - (++) Wait for status flags to be reset. - - (#) 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 - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_IWDG_MODULE_ENABLED -/** @addtogroup IWDG - * @brief IWDG HAL module driver. - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup IWDG_Private_Defines IWDG Private Defines - * @{ - */ -/* Status register needs up to 5 LSI clock periods to be updated. However a - synchronisation is added on prescaled LSI clock rising edge, so we only - consider a highest prescaler cycle. - The timeout value is calculated using the highest prescaler (1024) and - the LSI_VALUE constant. The value of this constant can be changed by the user - to take into account possible LSI clock period variations. - The timeout value is multiplied by 1000 to be converted in milliseconds. - LSI startup time is also considered here by adding LSI_STARTUP_TIME - converted in milliseconds. */ -#define HAL_IWDG_DEFAULT_TIMEOUT (((1UL * 1024UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) -#define IWDG_KERNEL_UPDATE_FLAGS (IWDG_SR_EWU | IWDG_SR_WVU | IWDG_SR_RVU | IWDG_SR_PVU) -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup IWDG_Exported_Functions - * @{ - */ - -/** @addtogroup IWDG_Exported_Functions_Group1 - * @brief Initialization and Start functions. - * -@verbatim - =============================================================================== - ##### Initialization and Start functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Initialize the IWDG according to the specified parameters in the - IWDG_InitTypeDef of associated handle. - (+) Manage Window option. - (+) Once initialization is performed in HAL_IWDG_Init function, Watchdog - is reloaded in order to exit function with correct time base. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the IWDG according to the specified parameters in the - * IWDG_InitTypeDef and start watchdog. Before exiting function, - * watchdog is refreshed in order to have correct time base. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains - * the configuration information for the specified IWDG module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) -{ - uint32_t tickstart; - - /* Check the IWDG handle allocation */ - if (hiwdg == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance)); - assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler)); - assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); - assert_param(IS_IWDG_WINDOW(hiwdg->Init.Window)); - assert_param(IS_IWDG_EWI(hiwdg->Init.EWI)); - -#if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1) - /* Reset Callback pointers */ - if (hiwdg->EwiCallback == NULL) - { - hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback; - } - if (hiwdg->MspInitCallback == NULL) - { - hiwdg->MspInitCallback = HAL_IWDG_MspInit; - } - - /* Init the low level hardware */ - hiwdg->MspInitCallback(hiwdg); -#else - /* Init the low level hardware */ - HAL_IWDG_MspInit(hiwdg); -#endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */ - - /* Enable IWDG. LSI is turned on automatically */ - __HAL_IWDG_START(hiwdg); - - /* Enable write access to IWDG_PR, IWDG_RLR, IWDG_WINR and EWCR registers by writing - 0x5555 in KR */ - IWDG_ENABLE_WRITE_ACCESS(hiwdg); - - /* Write to IWDG registers the Prescaler & Reload values to work with */ - hiwdg->Instance->PR = hiwdg->Init.Prescaler; - hiwdg->Instance->RLR = hiwdg->Init.Reload; - - /* Check Reload update flag, before performing any reload of the counter, else previous value - will be taken. */ - tickstart = HAL_GetTick(); - - /* Wait for register to be updated */ - while ((hiwdg->Instance->SR & IWDG_SR_RVU) != 0x00u) - { - if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT) - { - if ((hiwdg->Instance->SR & IWDG_SR_RVU) != 0x00u) - { - return HAL_TIMEOUT; - } - } - } - - if (hiwdg->Init.EWI == IWDG_EWI_DISABLE) - { - /* EWI comparator value equal 0, disable the early wakeup interrupt - * acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register - * Set Watchdog Early Wakeup Comparator to 0x00 */ - hiwdg->Instance->EWCR = IWDG_EWCR_EWIC; - } - else - { - /* EWI comparator value different from 0, enable the early wakeup interrupt, - * acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register - * Set Watchdog Early Wakeup Comparator value */ - hiwdg->Instance->EWCR = IWDG_EWCR_EWIE | IWDG_EWCR_EWIC | hiwdg->Init.EWI; - } - - /* Check pending flag, if previous update not done, return timeout */ - tickstart = HAL_GetTick(); - - /* Wait for register to be updated */ - while ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u) - { - if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT) - { - if ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u) - { - return HAL_TIMEOUT; - } - } - } - - /* If window parameter is different than current value, modify window - register */ - if (hiwdg->Instance->WINR != hiwdg->Init.Window) - { - /* Write to IWDG WINR the IWDG_Window value to compare with. In any case, - even if window feature is disabled, Watchdog will be reloaded by writing - windows register */ - hiwdg->Instance->WINR = hiwdg->Init.Window; - } - else - { - /* Reload IWDG counter with value defined in the reload register */ - __HAL_IWDG_RELOAD_COUNTER(hiwdg); - } - - /* Return function status */ - return HAL_OK; -} - - -/** - * @brief Initialize the IWDG MSP. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains - * the configuration information for the specified IWDG module. - * @note When rewriting this function in user file, mechanism may be added - * to avoid multiple initialize when HAL_IWDG_Init function is called - * again to change parameters. - * @retval None - */ -__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hiwdg); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_IWDG_MspInit could be implemented in the user file - */ -} - - -#if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User IWDG Callback - * To be used instead of the weak (surcharged) predefined callback - * @param hiwdg IWDG handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID - * @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID - * @param pCallback pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_IWDG_RegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID, - pIWDG_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - status = HAL_ERROR; - } - else - { - switch (CallbackID) - { - case HAL_IWDG_EWI_CB_ID: - hiwdg->EwiCallback = pCallback; - break; - case HAL_IWDG_MSPINIT_CB_ID: - hiwdg->MspInitCallback = pCallback; - break; - - default: - status = HAL_ERROR; - break; - } - } - - return status; -} - - -/** - * @brief Unregister a IWDG Callback - * IWDG Callback is redirected to the weak (surcharged) predefined callback - * @param hiwdg IWDG handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID - * @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_IWDG_UnRegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - switch (CallbackID) - { - case HAL_IWDG_EWI_CB_ID: - hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback; - break; - case HAL_IWDG_MSPINIT_CB_ID: - hiwdg->MspInitCallback = HAL_IWDG_MspInit; - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} -#endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */ - - -/** - * @} - */ - - -/** @addtogroup IWDG_Exported_Functions_Group2 - * @brief IO operation functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Refresh the IWDG. - -@endverbatim - * @{ - */ - -/** - * @brief Refresh the IWDG. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains - * the configuration information for the specified IWDG module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) -{ - /* Reload IWDG counter with value defined in the reload register */ - __HAL_IWDG_RELOAD_COUNTER(hiwdg); - - /* Return function status */ - return HAL_OK; -} - - -/** - * @brief Get back IWDG running status - * @note This API allows to know if IWDG has been started by other master, thread - * or by hardware. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains - * the configuration information for the specified IWDG module. - * @retval can be one of following value : - * @arg @ref IWDG_STATUS_DISABLE - * @arg @ref IWDG_STATUS_ENABLE - */ -uint32_t HAL_IWDG_GetActiveStatus(const IWDG_HandleTypeDef *hiwdg) -{ - uint32_t status; - - /* Get back ONF flag */ - status = (hiwdg->Instance->SR & IWDG_SR_ONF); - - /* Return status */ - return status; -} - - -/** - * @brief Handle IWDG 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 by calling HAL_IWDG_Init function with - * EWIMode set to IWDG_EWI_ENABLE. - * 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 hiwdg pointer to a IWDG_HandleTypeDef structure that contains - * the configuration information for the specified IWDG module. - * @retval None - */ -void HAL_IWDG_IRQHandler(IWDG_HandleTypeDef *hiwdg) -{ - /* Check if IWDG Early Wakeup Interrupt occurred */ - if ((hiwdg->Instance->SR & IWDG_SR_EWIF) != 0x00u) - { - /* Clear the IWDG Early Wakeup flag */ - hiwdg->Instance->EWCR |= IWDG_EWCR_EWIC; - -#if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1) - /* Early Wakeup registered callback */ - hiwdg->EwiCallback(hiwdg); -#else - /* Early Wakeup callback */ - HAL_IWDG_EarlyWakeupCallback(hiwdg); -#endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */ - } -} - - -/** - * @brief IWDG Early Wakeup callback. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains - * the configuration information for the specified IWDG module. - * @retval None - */ -__weak void HAL_IWDG_EarlyWakeupCallback(IWDG_HandleTypeDef *hiwdg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hiwdg); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_IWDG_EarlyWakeupCallback could be implemented in the user file - */ -} - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_IWDG_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_iwdg.c + * @author MCD Application Team + * @brief IWDG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Independent Watchdog (IWDG) peripheral: + * + Initialization and Start functions + * + IO operation functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### IWDG Generic features ##### + ============================================================================== + [..] + (+) The IWDG can be started by either software or hardware (configurable + through option byte). + + (+) The IWDG is clocked by the Low-Speed Internal clock (LSI) and thus stays + active even if the main clock fails. + + (+) Once the IWDG is started, the LSI is forced ON and both cannot be + disabled. The counter starts counting down from the reset value (0xFFF). + When it reaches the end of count value (0x000) a reset signal is + generated (IWDG reset). + + (+) Whenever the key value 0x0000 AAAA is written in the IWDG_KR register, + the IWDG_RLR value is reloaded into the counter and the watchdog reset + is prevented. + + (+) The IWDG is implemented in the VDD voltage domain that is still functional + in STOP and STANDBY mode (IWDG reset can wake up the CPU from STANDBY). + IWDGRST flag in RCC_CSR register can be used to inform when an IWDG + reset occurs. + + (+) Debug mode: When the microcontroller enters debug mode (core halted), + the IWDG counter either continues to work normally or stops, depending + on DBG_IWDG_STOP configuration bit in DBG module, accessible through + __HAL_DBGMCU_FREEZE_IWDG() and __HAL_DBGMCU_UNFREEZE_IWDG() macros. + + [..] Min-max timeout value @32KHz (LSI): ~125us / ~32.7s + The IWDG timeout may vary due to LSI clock frequency dispersion. + STM32H7RSxx devices provide the capability to measure the LSI clock + frequency (LSI clock is internally connected to TIM16 CH1 input capture). + The measured value can be used to have an IWDG timeout with an + acceptable accuracy. + + [..] Default timeout value (necessary for IWDG_SR status register update): + Constant LSI_VALUE is defined based on the nominal LSI clock frequency. + This frequency being subject to variations as mentioned above, the + default timeout value (defined through constant HAL_IWDG_DEFAULT_TIMEOUT + below) may become too short or too long. + In such cases, this default timeout value can be tuned by redefining + the constant LSI_VALUE at user-application level (based, for instance, + on the measured LSI clock frequency as explained above). + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Register callback to treat Iwdg interrupt and MspInit using HAL_IWDG_RegisterCallback(). + (++) Provide exiting handle as first parameter. + (++) Provide which callback will be registered using one value from + HAL_IWDG_CallbackIDTypeDef. + (++) Provide callback function pointer. + + (#) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable instance by writing Start keyword in IWDG_KEY register. LSI + clock is forced ON and IWDG counter starts counting down. + (++) Enable write access to configuration registers: + IWDG_PR, IWDG_RLR, IWDG_WINR and EWCR. + (++) Configure the IWDG prescaler and counter reload value. This reload + value will be loaded in the IWDG counter each time the watchdog is + reloaded, then the IWDG will start counting down from this value. + (++) Depending on window parameter: + (+++) If Window Init parameter is same as Window register value, + nothing more is done but reload counter value in order to exit + function with exact time base. + (+++) Else modify Window register. This will automatically reload + watchdog counter. + (++) Depending on Early Wakeup Interrupt parameter: + (+++) If EWI is set to disable, comparator is set to 0, interrupt is + disable & flag is clear. + (+++) Else modify EWCR register, setting comparator value, enable + interrupt & clear flag. + (++) Wait for status flags to be reset. + + (#) 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 + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_IWDG_MODULE_ENABLED +/** @addtogroup IWDG + * @brief IWDG HAL module driver. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup IWDG_Private_Defines IWDG Private Defines + * @{ + */ +/* Status register needs up to 5 LSI clock periods to be updated. However a + synchronisation is added on prescaled LSI clock rising edge, so we only + consider a highest prescaler cycle. + The timeout value is calculated using the highest prescaler (1024) and + the LSI_VALUE constant. The value of this constant can be changed by the user + to take into account possible LSI clock period variations. + The timeout value is multiplied by 1000 to be converted in milliseconds. + LSI startup time is also considered here by adding LSI_STARTUP_TIME + converted in milliseconds. */ +#define HAL_IWDG_DEFAULT_TIMEOUT (((1UL * 1024UL * 1000UL) / LSI_VALUE) + ((LSI_STARTUP_TIME / 1000UL) + 1UL)) +#define IWDG_KERNEL_UPDATE_FLAGS (IWDG_SR_EWU | IWDG_SR_WVU | IWDG_SR_RVU | IWDG_SR_PVU) +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup IWDG_Exported_Functions + * @{ + */ + +/** @addtogroup IWDG_Exported_Functions_Group1 + * @brief Initialization and Start functions. + * +@verbatim + =============================================================================== + ##### Initialization and Start functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the IWDG according to the specified parameters in the + IWDG_InitTypeDef of associated handle. + (+) Manage Window option. + (+) Once initialization is performed in HAL_IWDG_Init function, Watchdog + is reloaded in order to exit function with correct time base. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the IWDG according to the specified parameters in the + * IWDG_InitTypeDef and start watchdog. Before exiting function, + * watchdog is refreshed in order to have correct time base. + * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart; + + /* Check the IWDG handle allocation */ + if (hiwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance)); + assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler)); + assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); + assert_param(IS_IWDG_WINDOW(hiwdg->Init.Window)); + assert_param(IS_IWDG_EWI(hiwdg->Init.EWI)); + +#if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1) + /* Reset Callback pointers */ + if (hiwdg->EwiCallback == NULL) + { + hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback; + } + if (hiwdg->MspInitCallback == NULL) + { + hiwdg->MspInitCallback = HAL_IWDG_MspInit; + } + + /* Init the low level hardware */ + hiwdg->MspInitCallback(hiwdg); +#else + /* Init the low level hardware */ + HAL_IWDG_MspInit(hiwdg); +#endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */ + + /* Enable IWDG. LSI is turned on automatically */ + __HAL_IWDG_START(hiwdg); + + /* Enable write access to IWDG_PR, IWDG_RLR, IWDG_WINR and EWCR registers by writing + 0x5555 in KR */ + IWDG_ENABLE_WRITE_ACCESS(hiwdg); + + /* Write to IWDG registers the Prescaler & Reload values to work with */ + hiwdg->Instance->PR = hiwdg->Init.Prescaler; + hiwdg->Instance->RLR = hiwdg->Init.Reload; + + /* Check Reload update flag, before performing any reload of the counter, else previous value + will be taken. */ + tickstart = HAL_GetTick(); + + /* Wait for register to be updated */ + while ((hiwdg->Instance->SR & IWDG_SR_RVU) != 0x00u) + { + if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT) + { + if ((hiwdg->Instance->SR & IWDG_SR_RVU) != 0x00u) + { + return HAL_TIMEOUT; + } + } + } + + if (hiwdg->Init.EWI == IWDG_EWI_DISABLE) + { + /* EWI comparator value equal 0, disable the early wakeup interrupt + * acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register + * Set Watchdog Early Wakeup Comparator to 0x00 */ + hiwdg->Instance->EWCR = IWDG_EWCR_EWIC; + } + else + { + /* EWI comparator value different from 0, enable the early wakeup interrupt, + * acknowledge the early wakeup interrupt in any cases. it clears the EWIF flag in SR register + * Set Watchdog Early Wakeup Comparator value */ + hiwdg->Instance->EWCR = IWDG_EWCR_EWIE | IWDG_EWCR_EWIC | hiwdg->Init.EWI; + } + + /* Check pending flag, if previous update not done, return timeout */ + tickstart = HAL_GetTick(); + + /* Wait for register to be updated */ + while ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u) + { + if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT) + { + if ((hiwdg->Instance->SR & IWDG_KERNEL_UPDATE_FLAGS) != 0x00u) + { + return HAL_TIMEOUT; + } + } + } + + /* If window parameter is different than current value, modify window + register */ + if (hiwdg->Instance->WINR != hiwdg->Init.Window) + { + /* Write to IWDG WINR the IWDG_Window value to compare with. In any case, + even if window feature is disabled, Watchdog will be reloaded by writing + windows register */ + hiwdg->Instance->WINR = hiwdg->Init.Window; + } + else + { + /* Reload IWDG counter with value defined in the reload register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + } + + /* Return function status */ + return HAL_OK; +} + + +/** + * @brief Initialize the IWDG MSP. + * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @note When rewriting this function in user file, mechanism may be added + * to avoid multiple initialize when HAL_IWDG_Init function is called + * again to change parameters. + * @retval None + */ +__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hiwdg); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_IWDG_MspInit could be implemented in the user file + */ +} + + +#if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User IWDG Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hiwdg IWDG handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID + * @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_IWDG_RegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID, + pIWDG_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + status = HAL_ERROR; + } + else + { + switch (CallbackID) + { + case HAL_IWDG_EWI_CB_ID: + hiwdg->EwiCallback = pCallback; + break; + case HAL_IWDG_MSPINIT_CB_ID: + hiwdg->MspInitCallback = pCallback; + break; + + default: + status = HAL_ERROR; + break; + } + } + + return status; +} + + +/** + * @brief Unregister a IWDG Callback + * IWDG Callback is redirected to the weak (surcharged) predefined callback + * @param hiwdg IWDG handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_IWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID + * @arg @ref HAL_IWDG_MSPINIT_CB_ID MspInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_IWDG_UnRegisterCallback(IWDG_HandleTypeDef *hiwdg, HAL_IWDG_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + switch (CallbackID) + { + case HAL_IWDG_EWI_CB_ID: + hiwdg->EwiCallback = HAL_IWDG_EarlyWakeupCallback; + break; + case HAL_IWDG_MSPINIT_CB_ID: + hiwdg->MspInitCallback = HAL_IWDG_MspInit; + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} +#endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */ + + +/** + * @} + */ + + +/** @addtogroup IWDG_Exported_Functions_Group2 + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Refresh the IWDG. + +@endverbatim + * @{ + */ + +/** + * @brief Refresh the IWDG. + * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) +{ + /* Reload IWDG counter with value defined in the reload register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + + /* Return function status */ + return HAL_OK; +} + + +/** + * @brief Get back IWDG running status + * @note This API allows to know if IWDG has been started by other master, thread + * or by hardware. + * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval can be one of following value : + * @arg @ref IWDG_STATUS_DISABLE + * @arg @ref IWDG_STATUS_ENABLE + */ +uint32_t HAL_IWDG_GetActiveStatus(const IWDG_HandleTypeDef *hiwdg) +{ + uint32_t status; + + /* Get back ONF flag */ + status = (hiwdg->Instance->SR & IWDG_SR_ONF); + + /* Return status */ + return status; +} + + +/** + * @brief Handle IWDG 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 by calling HAL_IWDG_Init function with + * EWIMode set to IWDG_EWI_ENABLE. + * 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 hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval None + */ +void HAL_IWDG_IRQHandler(IWDG_HandleTypeDef *hiwdg) +{ + /* Check if IWDG Early Wakeup Interrupt occurred */ + if ((hiwdg->Instance->SR & IWDG_SR_EWIF) != 0x00u) + { + /* Clear the IWDG Early Wakeup flag */ + hiwdg->Instance->EWCR |= IWDG_EWCR_EWIC; + +#if (USE_HAL_IWDG_REGISTER_CALLBACKS == 1) + /* Early Wakeup registered callback */ + hiwdg->EwiCallback(hiwdg); +#else + /* Early Wakeup callback */ + HAL_IWDG_EarlyWakeupCallback(hiwdg); +#endif /* USE_HAL_IWDG_REGISTER_CALLBACKS */ + } +} + + +/** + * @brief IWDG Early Wakeup callback. + * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval None + */ +__weak void HAL_IWDG_EarlyWakeupCallback(IWDG_HandleTypeDef *hiwdg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hiwdg); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_IWDG_EarlyWakeupCallback could be implemented in the user file + */ +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_IWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_jpeg.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_jpeg.c index df86ffc7e..781e54b7e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_jpeg.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_jpeg.c @@ -1,4280 +1,4280 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_jpeg.c - * @author MCD Application Team - * @brief JPEG HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the JPEG encoder/decoder peripheral: - * + Initialization and de-initialization functions - * + JPEG processing functions encoding and decoding - * + JPEG decoding Getting Info and encoding configuration setting - * + JPEG enable/disable header parsing functions (for decoding) - * + JPEG Input/Output Buffer configuration. - * + JPEG callback functions - * + JPEG Abort/Pause/Resume functions - * + JPEG custom quantization tables setting functions - * + IRQ handler management - * + Peripheral State and Error functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Initialize the JPEG peripheral using HAL_JPEG_Init : No initialization parameters are required. - Only the call to HAL_JPEG_Init is necessary to initialize the JPEG peripheral. - - (#) If operation is JPEG encoding use function HAL_JPEG_ConfigEncoding to set - the encoding parameters (mandatory before calling the encoding function). - the application can change the encoding parameter ImageQuality from - 1 to 100 to obtain a more or less quality (visual quality vs the original row image), - and inversely more or less jpg file size. - - (#) Note that for decoding operation the JPEG peripheral output data are organized in - YCbCr blocks called MCU (Minimum Coded Unit) as defioned in the JPEG specification - ISO/IEC 10918-1 standard. - It is up to the application to transform these YCbCr blocks to RGB data that can be display. - - Respectively, for Encoding operation the JPEG peripheral input should be organized - in YCbCr MCU blocks. It is up to the application to perform the necessary RGB to YCbCr - MCU blocks transformation before feeding the JPEG peripheral with data. - - (#) Use functions HAL_JPEG_Encode and HAL_JPEG_Decode to start respectively - a JPEG encoding/decoding operation in polling method (blocking). - - (#) Use functions HAL_JPEG_Encode_IT and HAL_JPEG_Decode_IT to start respectively - a JPEG encoding/decoding operation with Interrupt method (not blocking). - - (#) Use functions HAL_JPEG_Encode_DMA and HAL_JPEG_Decode_DMA to start respectively - a JPEG encoding/decoding operation with DMA method (not blocking). - - (#) Callback HAL_JPEG_InfoReadyCallback is asserted if the current operation - is a JPEG decoding to provide the application with JPEG image parameters. - This callback is asserted when the JPEG peripheral successfully parse the - JPEG header. - - (#) Callback HAL_JPEG_GetDataCallback is asserted for both encoding and decoding - operations to inform the application that the input buffer has been - consumed by the peripheral and to ask for a new data chunk if the operation - (encoding/decoding) has not been complete yet. - - (++) This CallBack should be implemented in the application side. It should - call the function HAL_JPEG_ConfigInputBuffer if new input data are available, - or call HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_INPUT - to inform the JPEG HAL driver that the ongoing operation shall pause waiting for the - application to provide a new input data chunk. - Once the application succeed getting new data and if the input has been paused, - the application can call the function HAL_JPEG_ConfigInputBuffer to set the new - input buffer and size, then resume the JPEG HAL input by calling new function HAL_JPEG_Resume. - If the application has ended feeding the HAL JPEG with input data (no more input data), the application - Should call the function HAL_JPEG_ConfigInputBuffer (within the callback HAL_JPEG_GetDataCallback) - with the parameter InDataLength set to zero. - - (++) The mechanism of HAL_JPEG_ConfigInputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows - to the application to provide the input data (for encoding or decoding) by chunks. - If the new input data chunk is not available (because data should be read from an input file - for example) the application can pause the JPEG input (using function HAL_JPEG_Pause) - Once the new input data chunk is available ( read from a file for example), the application - can call the function HAL_JPEG_ConfigInputBuffer to provide the HAL with the new chunk - then resume the JPEG HAL input by calling function HAL_JPEG_Resume. - - (++) The application can call functions HAL_JPEG_ConfigInputBuffer then HAL_JPEG_Resume. - any time (outside the HAL_JPEG_GetDataCallback) Once the new input chunk data available. - However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called - (if necessary) within the callback HAL_JPEG_GetDataCallback, i.e when the HAL JPEG has ended - Transferring the previous chunk buffer to the JPEG peripheral. - - (#) Callback HAL_JPEG_DataReadyCallback is asserted when the HAL JPEG driver - has filled the given output buffer with the given size. - - (++) This CallBack should be implemented in the application side. It should - call the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver - with the new output buffer location and size to be used to store next data chunk. - if the application is not ready to provide the output chunk location then it can - call the function HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_OUTPUT - to inform the JPEG HAL driver that it shall pause output data. Once the application - is ready to receive the new data chunk (output buffer location free or available) it should call - the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver - with the new output chunk buffer location and size, then call HAL_JPEG_Resume - to inform the HAL that it shall resume outputting data in the given output buffer. - - (++) The mechanism of HAL_JPEG_ConfigOutputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows - the application to receive data from the JPEG peripheral by chunks. when a chunk - is received, the application can pause the HAL JPEG output data to be able to process - these received data (YCbCr to RGB conversion in case of decoding or data storage in case - of encoding). - - (++) The application can call functions HAL_JPEG_ ConfigOutputBuffer then HAL_JPEG_Resume. - any time (outside the HAL_JPEG_DataReadyCallback) Once the output data buffer is free to use. - However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called - (if necessary) within the callback HAL_JPEG_ DataReadyCallback, i.e when the HAL JPEG has ended - Transferring the previous chunk buffer from the JPEG peripheral to the application. - - (#) Callback HAL_JPEG_EncodeCpltCallback is asserted when the HAL JPEG driver has - ended the current JPEG encoding operation, and all output data has been transmitted - to the application. - - (#) Callback HAL_JPEG_DecodeCpltCallback is asserted when the HAL JPEG driver has - ended the current JPEG decoding operation. and all output data has been transmitted - to the application. - - (#) Callback HAL_JPEG_ErrorCallback is asserted when an error occurred during - the current operation. the application can call the function HAL_JPEG_GetError() - to retrieve the error codes. - - (#) By default the HAL JPEG driver uses the default quantization tables - as provide in the JPEG specification (ISO/IEC 10918-1 standard) for encoding. - User can change these default tables if necessary using the function HAL_JPEG_SetUserQuantTables - Note that for decoding the quantization tables are automatically extracted from - the JPEG header. - - (#) To control JPEG state you can use the following function: HAL_JPEG_GetState() - - *** JPEG HAL driver macros list *** - ============================================= - [..] - Below the list of most used macros in JPEG HAL driver. - - (+) __HAL_JPEG_RESET_HANDLE_STATE : Reset JPEG handle state. - (+) __HAL_JPEG_ENABLE : Enable the JPEG peripheral. - (+) __HAL_JPEG_DISABLE : Disable the JPEG peripheral. - (+) __HAL_JPEG_GET_FLAG : Check the specified JPEG status flag. - (+) __HAL_JPEG_CLEAR_FLAG : Clear the specified JPEG status flag. - (+) __HAL_JPEG_ENABLE_IT : Enable the specified JPEG Interrupt. - (+) __HAL_JPEG_DISABLE_IT : Disable the specified JPEG Interrupt. - (+) __HAL_JPEG_GET_IT_SOURCE : returns the state of the specified JPEG Interrupt (Enabled or disabled). - - *** Callback registration *** - ============================================= - - The compilation define USE_HAL_JPEG_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_JPEG_RegisterCallback() or HAL_JPEG_RegisterXXXCallback() - to register an interrupt callback. - - Function HAL_JPEG_RegisterCallback() allows to register following callbacks: - (+) EncodeCpltCallback : callback for end of encoding operation. - (+) DecodeCpltCallback : callback for end of decoding operation. - (+) ErrorCallback : callback for error detection. - (+) MspInitCallback : JPEG MspInit. - (+) MspDeInitCallback : JPEG MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - For specific callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated - register callbacks : respectively HAL_JPEG_RegisterInfoReadyCallback(), - HAL_JPEG_RegisterGetDataCallback() and HAL_JPEG_RegisterDataReadyCallback(). - - Use function HAL_JPEG_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_JPEG_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) EncodeCpltCallback : callback for end of encoding operation. - (+) DecodeCpltCallback : callback for end of decoding operation. - (+) ErrorCallback : callback for error detection. - (+) MspInitCallback : JPEG MspInit. - (+) MspDeInitCallback : JPEG MspDeInit. - - For callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated - unregister callbacks : respectively HAL_JPEG_UnRegisterInfoReadyCallback(), - HAL_JPEG_UnRegisterGetDataCallback() and HAL_JPEG_UnRegisterDataReadyCallback(). - - By default, after the HAL_JPEG_Init() and when the state is HAL_JPEG_STATE_RESET - all callbacks are set to the corresponding weak functions : - examples HAL_JPEG_DecodeCpltCallback() , HAL_JPEG_GetDataCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak function in the HAL_JPEG_Init()/ HAL_JPEG_DeInit() only when - these callbacks are null (not registered beforehand). - if not, MspInit or MspDeInit are not null, the HAL_JPEG_Init() / HAL_JPEG_DeInit() - keep and use the user MspInit/MspDeInit functions (registered beforehand) - - Callbacks can be registered/unregistered in HAL_JPEG_STATE_READY state only. - Exception done MspInit/MspDeInit callbacks that can be registered/unregistered - in HAL_JPEG_STATE_READY or HAL_JPEG_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_JPEG_RegisterCallback() before calling HAL_JPEG_DeInit() - or HAL_JPEG_Init() function. - - When The compilation define USE_HAL_JPEG_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_JPEG_MODULE_ENABLED - -#if defined (JPEG) - -/** @defgroup JPEG JPEG - * @brief JPEG HAL module driver. - * @{ - */ - -/* Private define ------------------------------------------------------------*/ -/** @addtogroup JPEG_Private_Constants - * @{ - */ -#define JPEG_TIMEOUT_VALUE ((uint32_t)1000) /* 1s */ -#define JPEG_AC_HUFF_TABLE_SIZE ((uint32_t)162) /* Huffman AC table size : 162 codes*/ -#define JPEG_DC_HUFF_TABLE_SIZE ((uint32_t)12) /* Huffman DC table size : 12 codes*/ - -#define JPEG_QUANTVAL_MAX ((uint32_t)255) /* Quantization values are 8-bit numbers*/ -#define JPEG_LOW_QUALITY_REFERENCE ((uint32_t)5000) /*Reference value to generate scaling factor - for low quality factors (<50) */ -#define JPEG_HIGH_QUALITY_REFERENCE ((uint32_t)200) /*Reference value to generate scaling factor - for high quality factors (>=50)*/ - -#define JPEG_FIFO_SIZE ((uint32_t)16U) /* JPEG Input/Output HW FIFO size in words*/ - -#define JPEG_FIFO_TH_SIZE ((uint32_t)4U) /* JPEG Input/Output HW FIFO Threshold in words*/ - -#define JPEG_DMA_MASK ((uint32_t)0x00001800) /* JPEG DMA request Mask*/ -#define JPEG_DMA_IDMA ((uint32_t)JPEG_CR_IDMAEN) /* DMA request for the input FIFO */ -#define JPEG_DMA_ODMA ((uint32_t)JPEG_CR_ODMAEN) /* DMA request for the output FIFO */ - -#define JPEG_INTERRUPT_MASK ((uint32_t)0x0000007EU) /* JPEG Interrupt Mask*/ - -#define JPEG_CONTEXT_ENCODE ((uint32_t)0x00000001) /* JPEG context : operation is encoding*/ -#define JPEG_CONTEXT_DECODE ((uint32_t)0x00000002) /* JPEG context : operation is decoding*/ -#define JPEG_CONTEXT_OPERATION_MASK ((uint32_t)0x00000003) /* JPEG context : operation Mask */ - -#define JPEG_CONTEXT_POLLING ((uint32_t)0x00000004) /* JPEG context : Transfer use Polling */ -#define JPEG_CONTEXT_IT ((uint32_t)0x00000008) /* JPEG context : Transfer use Interrupt */ -#define JPEG_CONTEXT_DMA ((uint32_t)0x0000000C) /* JPEG context : Transfer use DMA */ -#define JPEG_CONTEXT_METHOD_MASK ((uint32_t)0x0000000C) /* JPEG context : Transfer Mask */ - - -#define JPEG_CONTEXT_CONF_ENCODING ((uint32_t)0x00000100) /* JPEG context : encoding config done */ - -#define JPEG_CONTEXT_PAUSE_INPUT ((uint32_t)0x00001000) /* JPEG context : Pause Input */ -#define JPEG_CONTEXT_PAUSE_OUTPUT ((uint32_t)0x00002000) /* JPEG context : Pause Output */ - -#define JPEG_CONTEXT_CUSTOM_TABLES ((uint32_t)0x00004000) /* JPEG context : Use custom quantization tables */ - -#define JPEG_CONTEXT_ENDING_DMA ((uint32_t)0x00008000) /* JPEG context : ending with DMA in progress */ - -#define JPEG_PROCESS_ONGOING ((uint32_t)0x00000000) /* Process is on going */ -#define JPEG_PROCESS_DONE ((uint32_t)0x00000001) /* Process is done (ends) */ -#define JPEG_GET_DMA_REMAIN_DATA(__HANDLE__) (__HAL_DMA_GET_COUNTER(__HANDLE__)\ - + HAL_DMAEx_GetFifoLevel(__HANDLE__)) -/** - * @} - */ - -/* Private typedef -----------------------------------------------------------*/ -/** @addtogroup JPEG_Private_Types - * @{ - */ - -/* - JPEG Huffman Table Structure definition : - This implementation of Huffman table structure is compliant with ISO/IEC 10918-1 standard, - Annex C Huffman Table specification - */ -typedef struct -{ - /* These two fields directly represent the contents of a JPEG DHT marker */ - uint8_t Bits[16]; /*!< bits[k] = # of symbols with codes of length k bits, - this parameter corresponds to BITS list in the Annex C */ - - uint8_t HuffVal[162]; /*!< The symbols, in order of incremented code length, - this parameter corresponds to HUFFVAL list in the Annex C */ - - -} JPEG_ACHuffTableTypeDef; - -typedef struct -{ - /* These two fields directly represent the contents of a JPEG DHT marker */ - uint8_t Bits[16]; /*!< bits[k] = # of symbols with codes of length k bits, - this parameter corresponds to BITS list in the Annex C */ - - uint8_t HuffVal[12]; /*!< The symbols, in order of incremented code length, - this parameter corresponds to HUFFVAL list in the Annex C */ - - -} JPEG_DCHuffTableTypeDef; - -typedef struct -{ - uint8_t CodeLength[JPEG_AC_HUFF_TABLE_SIZE]; /*!< Code length */ - - uint32_t HuffmanCode[JPEG_AC_HUFF_TABLE_SIZE]; /*!< HuffmanCode */ - -} JPEG_AC_HuffCodeTableTypeDef; - -typedef struct -{ - uint8_t CodeLength[JPEG_DC_HUFF_TABLE_SIZE]; /*!< Code length */ - - uint32_t HuffmanCode[JPEG_DC_HUFF_TABLE_SIZE]; /*!< HuffmanCode */ - -} JPEG_DC_HuffCodeTableTypeDef; -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/** @addtogroup JPEG_Private_Macros - * @{ - */ -#define JPEG_ENABLE_DMA(__HANDLE__,__DMA__) ((__HANDLE__)->Instance->CR |= ((__DMA__) & JPEG_DMA_MASK)) -/*note : To disable a DMA request we must use MODIFY_REG macro to avoid writing "1" to the FIFO flush bits - located in the same DMA request enable register (CR register). */ -#define JPEG_DISABLE_DMA(__HANDLE__,__DMA__) MODIFY_REG((__HANDLE__)->Instance->CR, ((__DMA__) & JPEG_DMA_MASK), 0UL) -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/** @addtogroup JPEG_Private_Variables - * @{ - */ - -static const JPEG_DCHuffTableTypeDef JPEG_DCLUM_HuffTable = -{ - { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, /*Bits*/ - - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb } /*HUFFVAL */ - -}; - -static const JPEG_DCHuffTableTypeDef JPEG_DCCHROM_HuffTable = -{ - { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }, /*Bits*/ - - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb } /*HUFFVAL */ -}; - -static const JPEG_ACHuffTableTypeDef JPEG_ACLUM_HuffTable = -{ - { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }, /*Bits*/ - - { - 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, /*HUFFVAL */ - 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, - 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, - 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, - 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, - 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, - 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, - 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, - 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, - 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, - 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, - 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, - 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, - 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, - 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, - 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, - 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, - 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, - 0xf9, 0xfa - } -}; - -static const JPEG_ACHuffTableTypeDef JPEG_ACCHROM_HuffTable = -{ - { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }, /*Bits*/ - - { - 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, /*HUFFVAL */ - 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, - 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, - 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, - 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, - 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, - 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, - 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, - 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, - 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, - 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, - 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, - 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, - 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, - 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, - 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, - 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, - 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, - 0xf9, 0xfa - } -}; - -static const uint8_t JPEG_ZIGZAG_ORDER[JPEG_QUANT_TABLE_SIZE] = -{ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63 -}; -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup JPEG_Private_Functions_Prototypes - * @{ - */ - -static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(const uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode, - uint32_t *LastK); -static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable, - JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable); -static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable, - JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable); -static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC, - const __IO uint32_t *DCTableAddress); -static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC, - const __IO uint32_t *ACTableAddress); -static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg); -static void JPEG_Set_Huff_DHTMem(const JPEG_HandleTypeDef *hjpeg); -static uint32_t JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef *hjpeg, const uint8_t *QTable, - __IO uint32_t *QTableAddress); -static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg); -static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg); -static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg); - -static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg); -static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg); -static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords); -static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords); -static uint32_t JPEG_GetQuality(const JPEG_HandleTypeDef *hjpeg); - -static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg); -static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg); -static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg); -static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg); -static void JPEG_DMAOutCpltCallback(DMA_HandleTypeDef *hdma); -static void JPEG_DMAInCpltCallback(DMA_HandleTypeDef *hdma); -static void JPEG_DMAErrorCallback(DMA_HandleTypeDef *hdma); -static void JPEG_DMAOutAbortCallback(DMA_HandleTypeDef *hdma) ; - -/** - * @} - */ - -/** @defgroup JPEG_Exported_Functions JPEG Exported Functions - * @{ - */ - -/** @defgroup JPEG_Exported_Functions_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 JPEG peripheral and creates the associated handle - (+) DeInitialize the JPEG peripheral - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the JPEG according to the specified - * parameters in the JPEG_InitTypeDef and creates the associated handle. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Init(JPEG_HandleTypeDef *hjpeg) -{ - /* These are the sample quantization tables given in JPEG spec ISO/IEC 10918-1 standard , section K.1. */ - static const uint8_t JPEG_LUM_QuantTable[JPEG_QUANT_TABLE_SIZE] = - { - 16, 11, 10, 16, 24, 40, 51, 61, - 12, 12, 14, 19, 26, 58, 60, 55, - 14, 13, 16, 24, 40, 57, 69, 56, - 14, 17, 22, 29, 51, 87, 80, 62, - 18, 22, 37, 56, 68, 109, 103, 77, - 24, 35, 55, 64, 81, 104, 113, 92, - 49, 64, 78, 87, 103, 121, 120, 101, - 72, 92, 95, 98, 112, 100, 103, 99 - }; - static const uint8_t JPEG_CHROM_QuantTable[JPEG_QUANT_TABLE_SIZE] = - { - 17, 18, 24, 47, 99, 99, 99, 99, - 18, 21, 26, 66, 99, 99, 99, 99, - 24, 26, 56, 99, 99, 99, 99, 99, - 47, 66, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99 - }; - - /* Check the JPEG handle allocation */ - if (hjpeg == NULL) - { - return HAL_ERROR; - } - -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - if (hjpeg->State == HAL_JPEG_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hjpeg->Lock = HAL_UNLOCKED; - - hjpeg->InfoReadyCallback = HAL_JPEG_InfoReadyCallback; /* Legacy weak InfoReadyCallback */ - hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback */ - hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback */ - hjpeg->ErrorCallback = HAL_JPEG_ErrorCallback; /* Legacy weak ErrorCallback */ - hjpeg->GetDataCallback = HAL_JPEG_GetDataCallback; /* Legacy weak GetDataCallback */ - hjpeg->DataReadyCallback = HAL_JPEG_DataReadyCallback; /* Legacy weak DataReadyCallback */ - - if (hjpeg->MspInitCallback == NULL) - { - hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware */ - hjpeg->MspInitCallback(hjpeg); - } -#else - if (hjpeg->State == HAL_JPEG_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hjpeg->Lock = HAL_UNLOCKED; - - /* Init the low level hardware : GPIO, CLOCK */ - HAL_JPEG_MspInit(hjpeg); - } -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_BUSY; - - /* Start the JPEG Core*/ - __HAL_JPEG_ENABLE(hjpeg); - - /* Stop the JPEG encoding/decoding process*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - /* Disable All Interrupts */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - /* Disable All DMA requests */ - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); - - /* Flush input and output FIFOs*/ - hjpeg->Instance->CR |= JPEG_CR_IFF; - hjpeg->Instance->CR |= JPEG_CR_OFF; - - /* Clear all flags */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); - - /* init default quantization tables*/ - hjpeg->QuantTable0 = (uint8_t *)((uint32_t)JPEG_LUM_QuantTable); - hjpeg->QuantTable1 = (uint8_t *)((uint32_t)JPEG_CHROM_QuantTable); - hjpeg->QuantTable2 = NULL; - hjpeg->QuantTable3 = NULL; - - /* init the default Huffman tables*/ - if (JPEG_Set_HuffEnc_Mem(hjpeg) != HAL_OK) - { - hjpeg->ErrorCode = HAL_JPEG_ERROR_HUFF_TABLE; - - return HAL_ERROR; - } - - /* Enable header processing*/ - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR; - - /* Reset JpegInCount and JpegOutCount */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /* Reset the JPEG ErrorCode */ - hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE; - - /* Clear the context fields */ - hjpeg->Context = 0; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief DeInitializes the JPEG peripheral. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_DeInit(JPEG_HandleTypeDef *hjpeg) -{ - /* Check the JPEG handle allocation */ - if (hjpeg == NULL) - { - return HAL_ERROR; - } - -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - if (hjpeg->MspDeInitCallback == NULL) - { - hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware */ - hjpeg->MspDeInitCallback(hjpeg); - -#else - /* DeInit the low level hardware: CLOCK, NVIC.*/ - HAL_JPEG_MspDeInit(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_BUSY; - - /* Reset the JPEG ErrorCode */ - hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE; - - /* Reset JpegInCount and JpegOutCount */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_RESET; - - /*Clear the context fields*/ - hjpeg->Context = 0; - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Initializes the JPEG MSP. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -__weak void HAL_JPEG_MspInit(JPEG_HandleTypeDef *hjpeg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitializes JPEG MSP. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -__weak void HAL_JPEG_MspDeInit(JPEG_HandleTypeDef *hjpeg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User JPEG Callback - * To be used to override the weak predefined callback - * @param hjpeg JPEG handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID - * @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID - * @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID - * @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_RegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID, - pJPEG_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - switch (CallbackID) - { - case HAL_JPEG_ENCODE_CPLT_CB_ID : - hjpeg->EncodeCpltCallback = pCallback; - break; - - case HAL_JPEG_DECODE_CPLT_CB_ID : - hjpeg->DecodeCpltCallback = pCallback; - break; - - case HAL_JPEG_ERROR_CB_ID : - hjpeg->ErrorCallback = pCallback; - break; - - case HAL_JPEG_MSPINIT_CB_ID : - hjpeg->MspInitCallback = pCallback; - break; - - case HAL_JPEG_MSPDEINIT_CB_ID : - hjpeg->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_JPEG_STATE_RESET == hjpeg->State) - { - switch (CallbackID) - { - case HAL_JPEG_MSPINIT_CB_ID : - hjpeg->MspInitCallback = pCallback; - break; - - case HAL_JPEG_MSPDEINIT_CB_ID : - hjpeg->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief Unregister a JPEG Callback - * JPEG callback is redirected to the weak predefined callback - * @param hjpeg JPEG handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID - * @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID - * @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID - * @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_UnRegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - switch (CallbackID) - { - case HAL_JPEG_ENCODE_CPLT_CB_ID : - hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback */ - break; - - case HAL_JPEG_DECODE_CPLT_CB_ID : - hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback */ - break; - - case HAL_JPEG_ERROR_CB_ID : - hjpeg->ErrorCallback = HAL_JPEG_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_JPEG_MSPINIT_CB_ID : - hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_JPEG_MSPDEINIT_CB_ID : - hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_JPEG_STATE_RESET == hjpeg->State) - { - switch (CallbackID) - { - case HAL_JPEG_MSPINIT_CB_ID : - hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_JPEG_MSPDEINIT_CB_ID : - hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspInit */ - break; - - default : - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief Register Info Ready JPEG Callback - * To be used instead of the weak HAL_JPEG_InfoReadyCallback() predefined callback - * @param hjpeg JPEG handle - * @param pCallback pointer to the Info Ready Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_RegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg, - pJPEG_InfoReadyCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - hjpeg->InfoReadyCallback = pCallback; - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief UnRegister the Info Ready JPEG Callback - * Info Ready JPEG Callback is redirected to the weak HAL_JPEG_InfoReadyCallback() predefined callback - * @param hjpeg JPEG handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_UnRegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - hjpeg->InfoReadyCallback = HAL_JPEG_InfoReadyCallback; /* Legacy weak InfoReadyCallback */ - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief Register Get Data JPEG Callback - * To be used instead of the weak HAL_JPEG_GetDataCallback() predefined callback - * @param hjpeg JPEG handle - * @param pCallback pointer to the Get Data Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_RegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg, pJPEG_GetDataCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - hjpeg->GetDataCallback = pCallback; - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief UnRegister the Get Data JPEG Callback - * Get Data JPEG Callback is redirected to the weak HAL_JPEG_GetDataCallback() predefined callback - * @param hjpeg JPEG handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_UnRegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - hjpeg->GetDataCallback = HAL_JPEG_GetDataCallback; /* Legacy weak GetDataCallback */ - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief Register Data Ready JPEG Callback - * To be used instead of the weak HAL_JPEG_DataReadyCallback() predefined callback - * @param hjpeg JPEG handle - * @param pCallback pointer to the Get Data Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_RegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg, - pJPEG_DataReadyCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - hjpeg->DataReadyCallback = pCallback; - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -/** - * @brief UnRegister the Data Ready JPEG Callback - * Get Data Ready Callback is redirected to the weak HAL_JPEG_DataReadyCallback() predefined callback - * @param hjpeg JPEG handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_UnRegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (HAL_JPEG_STATE_READY == hjpeg->State) - { - hjpeg->DataReadyCallback = HAL_JPEG_DataReadyCallback; /* Legacy weak DataReadyCallback */ - } - else - { - /* Update the error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hjpeg); - return status; -} - -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup JPEG_Exported_Functions_Group2 Configuration functions - * @brief JPEG Configuration functions. - * -@verbatim - ============================================================================== - ##### Configuration functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) HAL_JPEG_ConfigEncoding() : JPEG encoding configuration - (+) HAL_JPEG_GetInfo() : Extract the image configuration from the JPEG header during the decoding - (+) HAL_JPEG_EnableHeaderParsing() : Enable JPEG Header parsing for decoding - (+) HAL_JPEG_DisableHeaderParsing() : Disable JPEG Header parsing for decoding - (+) HAL_JPEG_SetUserQuantTables : Modify the default Quantization tables used for JPEG encoding. - -@endverbatim - * @{ - */ - -/** - * @brief Set the JPEG encoding configuration. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pConf pointer to a JPEG_ConfTypeDef structure that contains - * the encoding configuration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_ConfigEncoding(JPEG_HandleTypeDef *hjpeg, const JPEG_ConfTypeDef *pConf) -{ - uint32_t error; - uint32_t numberMCU; - uint32_t hfactor; - uint32_t vfactor; - uint32_t hMCU; - uint32_t vMCU; - - /* Check the JPEG handle allocation */ - if ((hjpeg == NULL) || (pConf == NULL)) - { - return HAL_ERROR; - } - else - { - /* Check the parameters */ - assert_param(IS_JPEG_COLORSPACE(pConf->ColorSpace)); - assert_param(IS_JPEG_CHROMASUBSAMPLING(pConf->ChromaSubsampling)); - assert_param(IS_JPEG_IMAGE_QUALITY(pConf->ImageQuality)); - - /* Process Locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - hjpeg->State = HAL_JPEG_STATE_BUSY; - - hjpeg->Conf.ColorSpace = pConf->ColorSpace; - hjpeg->Conf.ChromaSubsampling = pConf->ChromaSubsampling; - hjpeg->Conf.ImageHeight = pConf->ImageHeight; - hjpeg->Conf.ImageWidth = pConf->ImageWidth; - hjpeg->Conf.ImageQuality = pConf->ImageQuality; - - /* Reset the Color Space : by default only one quantization table is used*/ - hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_COLORSPACE; - - /* Set Number of color components*/ - if (hjpeg->Conf.ColorSpace == JPEG_GRAYSCALE_COLORSPACE) - { - /*Gray Scale is only one component 8x8 blocks i.e 4:4:4*/ - hjpeg->Conf.ChromaSubsampling = JPEG_444_SUBSAMPLING; - - JPEG_SetColorGrayScale(hjpeg); - /* Set quantization table 0*/ - error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0)); - } - else if (hjpeg->Conf.ColorSpace == JPEG_YCBCR_COLORSPACE) - { - /* - Set the Color Space for YCbCr : 2 quantization tables are used - one for Luminance(Y) and one for both Chrominances (Cb & Cr) - */ - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_0; - - JPEG_SetColorYCBCR(hjpeg); - - /* Set quantization table 0*/ - error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0)); - /*By default quantization table 0 for component 0 and quantization table 1 for both components 1 and 2*/ - (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1)); - - if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL) - { - /*Use user customized quantization tables , 1 table per component*/ - /* use 3 quantization tables , one for each component*/ - hjpeg->Instance->CONFR1 &= (~JPEG_CONFR1_COLORSPACE); - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_1; - - (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2)); - - /*Use Quantization 1 table for component 1*/ - hjpeg->Instance->CONFR5 &= (~JPEG_CONFR5_QT); - hjpeg->Instance->CONFR5 |= JPEG_CONFR5_QT_0; - - /*Use Quantization 2 table for component 2*/ - hjpeg->Instance->CONFR6 &= (~JPEG_CONFR6_QT); - hjpeg->Instance->CONFR6 |= JPEG_CONFR6_QT_1; - } - } - else /* ColorSpace == JPEG_CMYK_COLORSPACE */ - { - JPEG_SetColorCMYK(hjpeg); - - /* Set quantization table 0*/ - error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0)); - /*By default quantization table 0 for All components*/ - - if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL) - { - /*Use user customized quantization tables , 1 table per component*/ - /* use 4 quantization tables , one for each component*/ - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE; - - (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1)); - (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2)); - (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable3, (hjpeg->Instance->QMEM3)); - - /*Use Quantization 1 table for component 1*/ - hjpeg->Instance->CONFR5 |= JPEG_CONFR5_QT_0; - - /*Use Quantization 2 table for component 2*/ - hjpeg->Instance->CONFR6 |= JPEG_CONFR6_QT_1; - - /*Use Quantization 3 table for component 3*/ - hjpeg->Instance->CONFR7 |= JPEG_CONFR7_QT; - } - } - - if (error != 0UL) - { - hjpeg->ErrorCode = HAL_JPEG_ERROR_QUANT_TABLE; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Set the JPEG State to ready */ - hjpeg->State = HAL_JPEG_STATE_READY; - - return HAL_ERROR; - } - /* Set the image size*/ - /* set the number of lines*/ - MODIFY_REG(hjpeg->Instance->CONFR1, JPEG_CONFR1_YSIZE, ((hjpeg->Conf.ImageHeight & 0x0000FFFFUL) << 16)); - /* set the number of pixels per line*/ - MODIFY_REG(hjpeg->Instance->CONFR3, JPEG_CONFR3_XSIZE, ((hjpeg->Conf.ImageWidth & 0x0000FFFFUL) << 16)); - - - if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) /* 4:2:0*/ - { - hfactor = 16; - vfactor = 16; - } - else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) /* 4:2:2*/ - { - hfactor = 16; - vfactor = 8; - } - else /* Default is 8x8 MCU, 4:4:4*/ - { - hfactor = 8; - vfactor = 8; - } - - hMCU = (hjpeg->Conf.ImageWidth / hfactor); - if ((hjpeg->Conf.ImageWidth % hfactor) != 0UL) - { - hMCU++; /*+1 for horizontal incomplete MCU */ - } - - vMCU = (hjpeg->Conf.ImageHeight / vfactor); - if ((hjpeg->Conf.ImageHeight % vfactor) != 0UL) - { - vMCU++; /*+1 for vertical incomplete MCU */ - } - - numberMCU = (hMCU * vMCU) - 1UL; /* Bit Field JPEG_CONFR2_NMCU shall be set to NB_MCU - 1*/ - /* Set the number of MCU*/ - hjpeg->Instance->CONFR2 = (numberMCU & JPEG_CONFR2_NMCU); - - hjpeg->Context |= JPEG_CONTEXT_CONF_ENCODING; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Set the JPEG State to ready */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Return function status */ - return HAL_BUSY; - } - } -} - -/** - * @brief Extract the image configuration from the JPEG header during the decoding - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pInfo pointer to a JPEG_ConfTypeDef structure that contains - * The JPEG decoded header information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_GetInfo(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo) -{ - uint32_t yblockNb; - uint32_t cBblockNb; - uint32_t cRblockNb; - - /* Check the JPEG handle allocation */ - if ((hjpeg == NULL) || (pInfo == NULL)) - { - return HAL_ERROR; - } - - /*Read the conf parameters */ - if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF_1) - { - pInfo->ColorSpace = JPEG_YCBCR_COLORSPACE; - } - else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == 0UL) - { - pInfo->ColorSpace = JPEG_GRAYSCALE_COLORSPACE; - } - else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF) - { - pInfo->ColorSpace = JPEG_CMYK_COLORSPACE; - } - else - { - return HAL_ERROR; - } - - pInfo->ImageHeight = (hjpeg->Instance->CONFR1 & 0xFFFF0000UL) >> 16; - pInfo->ImageWidth = (hjpeg->Instance->CONFR3 & 0xFFFF0000UL) >> 16; - - if ((pInfo->ColorSpace == JPEG_YCBCR_COLORSPACE) || (pInfo->ColorSpace == JPEG_CMYK_COLORSPACE)) - { - yblockNb = (hjpeg->Instance->CONFR4 & JPEG_CONFR4_NB) >> 4; - cBblockNb = (hjpeg->Instance->CONFR5 & JPEG_CONFR5_NB) >> 4; - cRblockNb = (hjpeg->Instance->CONFR6 & JPEG_CONFR6_NB) >> 4; - - if ((yblockNb == 1UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL)) - { - pInfo->ChromaSubsampling = JPEG_422_SUBSAMPLING; /*16x8 block*/ - } - else if ((yblockNb == 0UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL)) - { - pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING; - } - else if ((yblockNb == 3UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL)) - { - pInfo->ChromaSubsampling = JPEG_420_SUBSAMPLING; - } - else /*Default is 4:4:4*/ - { - pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING; - } - } - else - { - pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING; - } - - pInfo->ImageQuality = JPEG_GetQuality(hjpeg); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Enable JPEG Header parsing for decoding - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for the JPEG. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_EnableHeaderParsing(JPEG_HandleTypeDef *hjpeg) -{ - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_BUSY; - - /* Enable header processing*/ - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR; - - /* Process unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - return HAL_OK; - } - else - { - /* Process unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } -} - -/** - * @brief Disable JPEG Header parsing for decoding - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for the JPEG. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_DisableHeaderParsing(JPEG_HandleTypeDef *hjpeg) -{ - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_BUSY; - - /* Disable header processing*/ - hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_HDR; - - /* Process unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - return HAL_OK; - } - else - { - /* Process unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } -} - -/** - * @brief Modify the default Quantization tables used for JPEG encoding. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param QTable0 pointer to uint8_t , define the user quantification table for color component 1. - * If NULL assume no need to update the table and no error return - * @param QTable1 pointer to uint8_t , define the user quantification table for color component 2. - * If NULL assume no need to update the table and no error return. - * @param QTable2 pointer to uint8_t , define the user quantification table for color component 3, - * If NULL assume no need to update the table and no error return. - * @param QTable3 pointer to uint8_t , define the user quantification table for color component 4. - * If NULL assume no need to update the table and no error return. - * - * @retval HAL status - */ - - -HAL_StatusTypeDef HAL_JPEG_SetUserQuantTables(JPEG_HandleTypeDef *hjpeg, uint8_t *QTable0, uint8_t *QTable1, - uint8_t *QTable2, uint8_t *QTable3) -{ - /* Process Locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - /* Change the DMA state */ - hjpeg->State = HAL_JPEG_STATE_BUSY; - - hjpeg->Context |= JPEG_CONTEXT_CUSTOM_TABLES; - - hjpeg->QuantTable0 = QTable0; - hjpeg->QuantTable1 = QTable1; - hjpeg->QuantTable2 = QTable2; - hjpeg->QuantTable3 = QTable3; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Change the DMA state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /* Return function status */ - return HAL_OK; - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } -} - -/** - * @} - */ - -/** @defgroup JPEG_Exported_Functions_Group3 encoding/decoding processing functions - * @brief processing functions. - * -@verbatim - ============================================================================== - ##### JPEG processing functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) HAL_JPEG_Encode() : JPEG encoding with polling process - (+) HAL_JPEG_Decode() : JPEG decoding with polling process - (+) HAL_JPEG_Encode_IT() : JPEG encoding with interrupt process - (+) HAL_JPEG_Decode_IT() : JPEG decoding with interrupt process - (+) HAL_JPEG_Encode_DMA() : JPEG encoding with DMA process - (+) HAL_JPEG_Decode_DMA() : JPEG decoding with DMA process - (+) HAL_JPEG_Pause() : Pause the Input/Output processing - (+) HAL_JPEG_Resume() : Resume the JPEG Input/Output processing - (+) HAL_JPEG_ConfigInputBuffer() : Config Encoding/Decoding Input Buffer - (+) HAL_JPEG_ConfigOutputBuffer() : Config Encoding/Decoding Output Buffer - (+) HAL_JPEG_Abort() : Aborts the JPEG Encoding/Decoding - -@endverbatim - * @{ - */ - -/** - * @brief Starts JPEG encoding with polling processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataInMCU Pointer to the Input buffer - * @param InDataLength size in bytes Input buffer - * @param pDataOut Pointer to the jpeg output data buffer - * @param OutDataLength size in bytes of the Output buffer - * @param Timeout Specify Timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Encode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength, - uint8_t *pDataOut, uint32_t OutDataLength, uint32_t Timeout) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param((InDataLength >= 4UL)); - assert_param((OutDataLength >= 4UL)); - - /* Check In/out buffer allocation and size */ - if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL)) - { - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State != HAL_JPEG_STATE_READY) - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING) - { - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING; - - /*Set the Context to Encode with Polling*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); - hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_POLLING); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /*Store In/out buffers pointers and size*/ - hjpeg->pJpegInBuffPtr = pDataInMCU; - hjpeg->pJpegOutBuffPtr = pDataOut; - hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /* In Data length must be multiple - of 4 Bytes (1 word)*/ - hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /* Out Data length must be multiple - of 4 Bytes (1 word)*/ - - /*Reset In/out data counter */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Init decoding process*/ - JPEG_Init_Process(hjpeg); - - /*JPEG data processing : In/Out FIFO transfer*/ - while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING)) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) - { - - /* Update error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_READY; - - return HAL_TIMEOUT; - } - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_READY; - - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts JPEG decoding with polling processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataIn Pointer to the input data buffer - * @param InDataLength size in bytes Input buffer - * @param pDataOutMCU Pointer to the Output data buffer - * @param OutDataLength size in bytes of the Output buffer - * @param Timeout Specify Timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Decode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength, - uint8_t *pDataOutMCU, uint32_t OutDataLength, uint32_t Timeout) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param((InDataLength >= 4UL)); - assert_param((OutDataLength >= 4UL)); - - /* Check In/out buffer allocation and size */ - if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hjpeg); - - /* Get tick */ - tickstart = HAL_GetTick(); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING; - - /*Set the Context to Decode with Polling*/ - /*Set the Context to Encode with Polling*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); - hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_POLLING); - - /*Store In/out buffers pointers and size*/ - hjpeg->pJpegInBuffPtr = pDataIn; - hjpeg->pJpegOutBuffPtr = pDataOutMCU; - hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /*In Data length must be multiple - of 4 Bytes (1 word)*/ - hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple - of 4 Bytes (1 word)*/ - - /*Reset In/out data counter */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Init decoding process*/ - JPEG_Init_Process(hjpeg); - - /*JPEG data processing : In/Out FIFO transfer*/ - while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING)) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) - { - - /* Update error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_READY; - - return HAL_TIMEOUT; - } - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_READY; - - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts JPEG encoding with interrupt processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataInMCU Pointer to the Input buffer - * @param InDataLength size in bytes Input buffer - * @param pDataOut Pointer to the jpeg output data buffer - * @param OutDataLength size in bytes of the Output buffer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Encode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength, - uint8_t *pDataOut, uint32_t OutDataLength) -{ - /* Check the parameters */ - assert_param((InDataLength >= 4UL)); - assert_param((OutDataLength >= 4UL)); - - /* Check In/out buffer allocation and size */ - if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State != HAL_JPEG_STATE_READY) - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } - else - { - if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING) - { - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING; - - /*Set the Context to Encode with IT*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); - hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_IT); - - /*Store In/out buffers pointers and size*/ - hjpeg->pJpegInBuffPtr = pDataInMCU; - hjpeg->pJpegOutBuffPtr = pDataOut; - hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /*In Data length must be multiple - of 4 Bytes (1 word)*/ - hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple - of 4 Bytes (1 word)*/ - - /*Reset In/out data counter */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Init decoding process*/ - JPEG_Init_Process(hjpeg); - - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts JPEG decoding with interrupt processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataIn Pointer to the input data buffer - * @param InDataLength size in bytes Input buffer - * @param pDataOutMCU Pointer to the Output data buffer - * @param OutDataLength size in bytes of the Output buffer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Decode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength, - uint8_t *pDataOutMCU, uint32_t OutDataLength) -{ - /* Check the parameters */ - assert_param((InDataLength >= 4UL)); - assert_param((OutDataLength >= 4UL)); - - /* Check In/out buffer allocation and size */ - if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING; - - /*Set the Context to Decode with IT*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); - hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_IT); - - /*Store In/out buffers pointers and size*/ - hjpeg->pJpegInBuffPtr = pDataIn; - hjpeg->pJpegOutBuffPtr = pDataOutMCU; - hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /*In Data length must be multiple - of 4 Bytes (1 word)*/ - hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple - of 4 Bytes (1 word)*/ - - /*Reset In/out data counter */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Init decoding process*/ - JPEG_Init_Process(hjpeg); - - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts JPEG encoding with DMA processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataInMCU Pointer to the Input buffer - * @param InDataLength size in bytes Input buffer - * @param pDataOut Pointer to the jpeg output data buffer - * @param OutDataLength size in bytes of the Output buffer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Encode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength, - uint8_t *pDataOut, uint32_t OutDataLength) -{ - /* Check the parameters */ - assert_param((InDataLength >= 4UL)); - assert_param((OutDataLength >= 4UL)); - - /* Check In/out buffer allocation and size */ - if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State != HAL_JPEG_STATE_READY) - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } - else - { - if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING) - { - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING; - - /*Set the Context to Encode with DMA*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); - hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_DMA); - - /*Store In/out buffers pointers and size*/ - hjpeg->pJpegInBuffPtr = pDataInMCU; - hjpeg->pJpegOutBuffPtr = pDataOut; - hjpeg->InDataLength = InDataLength; - hjpeg->OutDataLength = OutDataLength; - - /*Reset In/out data counter */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Init decoding process*/ - JPEG_Init_Process(hjpeg); - - /* JPEG encoding process using DMA */ - if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK) - { - /* Update State */ - hjpeg->State = HAL_JPEG_STATE_ERROR; - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts JPEG decoding with DMA processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataIn Pointer to the input data buffer - * @param InDataLength size in bytes Input buffer - * @param pDataOutMCU Pointer to the Output data buffer - * @param OutDataLength size in bytes of the Output buffer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Decode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength, - uint8_t *pDataOutMCU, uint32_t OutDataLength) -{ - /* Check the parameters */ - assert_param((InDataLength >= 4UL)); - assert_param((OutDataLength >= 4UL)); - - /* Check In/out buffer allocation and size */ - if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hjpeg); - - if (hjpeg->State == HAL_JPEG_STATE_READY) - { - /*Change JPEG state*/ - hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING; - - /*Set the Context to Decode with DMA*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); - hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_DMA); - - /*Store In/out buffers pointers and size*/ - hjpeg->pJpegInBuffPtr = pDataIn; - hjpeg->pJpegOutBuffPtr = pDataOutMCU; - hjpeg->InDataLength = InDataLength; - hjpeg->OutDataLength = OutDataLength; - - /*Reset In/out data counter */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Init decoding process*/ - JPEG_Init_Process(hjpeg); - - /* JPEG decoding process using DMA */ - if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK) - { - /* Update State */ - hjpeg->State = HAL_JPEG_STATE_ERROR; - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_BUSY; - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Pause the JPEG Input/Output processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param XferSelection This parameter can be one of the following values : - * JPEG_PAUSE_RESUME_INPUT : Pause Input processing - * JPEG_PAUSE_RESUME_OUTPUT: Pause Output processing - * JPEG_PAUSE_RESUME_INPUT_OUTPUT: Pause Input and Output processing - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Pause(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection) -{ - uint32_t mask = 0; - - assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection)); - - if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) - { - if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) - { - hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT; - mask |= JPEG_DMA_IDMA; - } - if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) - { - hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT; - mask |= JPEG_DMA_ODMA; - } - JPEG_DISABLE_DMA(hjpeg, mask); - - } - else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) - { - - if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) - { - hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT; - mask |= (JPEG_IT_IFT | JPEG_IT_IFNF); - } - if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) - { - hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT; - mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC); - } - __HAL_JPEG_DISABLE_IT(hjpeg, mask); - - } - else - { - /* Nothing to do */ - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Resume the JPEG Input/Output processing - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param XferSelection This parameter can be one of the following values : - * JPEG_PAUSE_RESUME_INPUT : Resume Input processing - * JPEG_PAUSE_RESUME_OUTPUT: Resume Output processing - * JPEG_PAUSE_RESUME_INPUT_OUTPUT: Resume Input and Output processing - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Resume(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection) -{ - uint32_t mask = 0; - - assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection)); - - if ((hjpeg->Context & (JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT)) == 0UL) - { - /* if nothing paused to resume return error*/ - return HAL_ERROR; - } - - if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) - { - - if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) - { - hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT); - mask |= JPEG_DMA_IDMA; - - /*JPEG Input DMA transfer data number must be multiple of DMA buffer size - as the destination is a 32 bits register */ - hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL); - - if (hjpeg->InDataLength > 0UL) - { - /* Start DMA FIFO In transfer */ - if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR, - hjpeg->InDataLength) != HAL_OK) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - hjpeg->State = HAL_JPEG_STATE_ERROR; - return HAL_ERROR; - } - } - } - if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) - { - hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT); - - if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL) - { - JPEG_DMA_PollResidualData(hjpeg); - } - else - { - mask |= JPEG_DMA_ODMA; - - /* Start DMA FIFO Out transfer */ - if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr, - hjpeg->OutDataLength) != HAL_OK) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - hjpeg->State = HAL_JPEG_STATE_ERROR; - return HAL_ERROR; - } - } - - } - JPEG_ENABLE_DMA(hjpeg, mask); - - } - else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) - { - if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) - { - hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT); - mask |= (JPEG_IT_IFT | JPEG_IT_IFNF); - } - if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) - { - hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT); - mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC); - } - __HAL_JPEG_ENABLE_IT(hjpeg, mask); - - } - else - { - /* Nothing to do */ - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Config Encoding/Decoding Input Buffer. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module. - * @param pNewInputBuffer Pointer to the new input data buffer - * @param InDataLength Size in bytes of the new Input data buffer - * @retval HAL status - */ -void HAL_JPEG_ConfigInputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewInputBuffer, uint32_t InDataLength) -{ - hjpeg->pJpegInBuffPtr = pNewInputBuffer; - hjpeg->InDataLength = InDataLength; -} - -/** - * @brief Config Encoding/Decoding Output Buffer. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module. - * @param pNewOutputBuffer Pointer to the new output data buffer - * @param OutDataLength Size in bytes of the new Output data buffer - * @retval HAL status - */ -void HAL_JPEG_ConfigOutputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewOutputBuffer, uint32_t OutDataLength) -{ - hjpeg->pJpegOutBuffPtr = pNewOutputBuffer; - hjpeg->OutDataLength = OutDataLength; -} - -/** - * @brief Aborts the JPEG Encoding/Decoding. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_JPEG_Abort(JPEG_HandleTypeDef *hjpeg) -{ - uint32_t tickstart; - uint32_t tmpContext; - tmpContext = hjpeg->Context; - - /*Reset the Context operation and method*/ - hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA); - - if ((tmpContext & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) - { - /* Stop the DMA In/out Xfer*/ - if (HAL_DMA_Abort(hjpeg->hdmaout) != HAL_OK) - { - if (hjpeg->hdmaout->ErrorCode == HAL_DMA_ERROR_TIMEOUT) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - } - } - if (HAL_DMA_Abort(hjpeg->hdmain) != HAL_OK) - { - if (hjpeg->hdmain->ErrorCode == HAL_DMA_ERROR_TIMEOUT) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - } - } - - } - - /* Stop the JPEG encoding/decoding process*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Check if the JPEG Codec is effectively disabled */ - while (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_COF) != 0UL) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > JPEG_TIMEOUT_VALUE) - { - /* Update error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT; - - /* Change the DMA state */ - hjpeg->State = HAL_JPEG_STATE_ERROR; - break; - } - } - - /* Disable All Interrupts */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - /* Disable All DMA requests */ - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); - - /* Flush input and output FIFOs*/ - hjpeg->Instance->CR |= JPEG_CR_IFF; - hjpeg->Instance->CR |= JPEG_CR_OFF; - - /* Clear all flags */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); - - /* Reset JpegInCount and JpegOutCount */ - hjpeg->JpegInCount = 0; - hjpeg->JpegOutCount = 0; - - /*Reset the Context Pause*/ - hjpeg->Context &= ~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT); - - /* Change the DMA state*/ - if (hjpeg->ErrorCode != HAL_JPEG_ERROR_NONE) - { - hjpeg->State = HAL_JPEG_STATE_ERROR; - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - /* Return function status */ - return HAL_ERROR; - } - else - { - hjpeg->State = HAL_JPEG_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - /* Return function status */ - return HAL_OK; - } - -} - - -/** - * @} - */ - -/** @defgroup JPEG_Exported_Functions_Group4 JPEG Decode/Encode callback functions - * @brief JPEG process callback functions. - * -@verbatim - ============================================================================== - ##### JPEG Decode and Encode callback functions ##### - ============================================================================== - [..] This section provides callback functions: - (+) HAL_JPEG_InfoReadyCallback() : Decoding JPEG Info ready callback - (+) HAL_JPEG_EncodeCpltCallback() : Encoding complete callback. - (+) HAL_JPEG_DecodeCpltCallback() : Decoding complete callback. - (+) HAL_JPEG_ErrorCallback() : JPEG error callback. - (+) HAL_JPEG_GetDataCallback() : Get New Data chunk callback. - (+) HAL_JPEG_DataReadyCallback() : Decoded/Encoded Data ready callback. - -@endverbatim - * @{ - */ - -/** - * @brief Decoding JPEG Info ready callback. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pInfo pointer to a JPEG_ConfTypeDef structure that contains - * The JPEG decoded header information - * @retval None - */ -__weak void HAL_JPEG_InfoReadyCallback(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - UNUSED(pInfo); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_HeaderParsingCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Encoding complete callback. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -__weak void HAL_JPEG_EncodeCpltCallback(JPEG_HandleTypeDef *hjpeg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_EncodeCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Decoding complete callback. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -__weak void HAL_JPEG_DecodeCpltCallback(JPEG_HandleTypeDef *hjpeg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_EncodeCpltCallback could be implemented in the user file - */ -} - -/** - * @brief JPEG error callback. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -__weak void HAL_JPEG_ErrorCallback(JPEG_HandleTypeDef *hjpeg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief Get New Data chunk callback. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param NbDecodedData Number of consumed data in the previous chunk in bytes - * @retval None - */ -__weak void HAL_JPEG_GetDataCallback(JPEG_HandleTypeDef *hjpeg, uint32_t NbDecodedData) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - UNUSED(NbDecodedData); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_GetDataCallback could be implemented in the user file - */ -} - -/** - * @brief Decoded/Encoded Data ready callback. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param pDataOut pointer to the output data buffer - * @param OutDataLength number in bytes of data available in the specified output buffer - * @retval None - */ -__weak void HAL_JPEG_DataReadyCallback(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataOut, uint32_t OutDataLength) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hjpeg); - UNUSED(pDataOut); - UNUSED(OutDataLength); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_JPEG_DataReadyCallback could be implemented in the user file - */ -} - -/** - * @} - */ - - -/** @defgroup JPEG_Exported_Functions_Group5 JPEG IRQ handler management - * @brief JPEG IRQ handler. - * -@verbatim - ============================================================================== - ##### JPEG IRQ handler management ##### - ============================================================================== - [..] This section provides JPEG IRQ handler function. - (+) HAL_JPEG_IRQHandler() : handles JPEG interrupt request - -@endverbatim - * @{ - */ - -/** - * @brief This function handles JPEG interrupt request. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -void HAL_JPEG_IRQHandler(JPEG_HandleTypeDef *hjpeg) -{ - switch (hjpeg->State) - { - case HAL_JPEG_STATE_BUSY_ENCODING: - case HAL_JPEG_STATE_BUSY_DECODING: - /* continue JPEG data encoding/Decoding*/ - /* JPEG data processing : In/Out FIFO transfer*/ - if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) - { - (void) JPEG_Process(hjpeg); - } - else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) - { - JPEG_DMA_ContinueProcess(hjpeg); - } - else - { - /* Nothing to do */ - } - break; - - default: - break; - } -} - -/** - * @} - */ - -/** @defgroup JPEG_Exported_Functions_Group6 Peripheral State functions - * @brief Peripheral State functions. - * -@verbatim - ============================================================================== - ##### Peripheral State and Error functions ##### - ============================================================================== - [..] This section provides JPEG State and Errors function. - (+) HAL_JPEG_GetState() : permits to get in run-time the JPEG state. - (+) HAL_JPEG_GetError() : Returns the JPEG error code if any. - -@endverbatim - * @{ - */ - -/** - * @brief Returns the JPEG state. - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval JPEG state - */ -HAL_JPEG_STATETypeDef HAL_JPEG_GetState(const JPEG_HandleTypeDef *hjpeg) -{ - return hjpeg->State; -} - -/** - * @brief Return the JPEG error code - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for the specified JPEG. - * @retval JPEG Error Code - */ -uint32_t HAL_JPEG_GetError(const JPEG_HandleTypeDef *hjpeg) -{ - return hjpeg->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - - -/** @addtogroup JPEG_Private_Functions - * @{ - */ - -/** - * @brief Generates Huffman sizes/Codes Table from Bits/vals Table - * @param Bits pointer to bits table - * @param Huffsize pointer to sizes table - * @param Huffcode pointer to codes table - * @param LastK pointer to last Coeff (table dimension) - * @retval HAL status - */ -static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(const uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode, - uint32_t *LastK) -{ - uint32_t i; - uint32_t j; - uint32_t k; - uint32_t code; - uint32_t si; - - /* Figure C.1: Generation of table of Huffman code sizes */ - j = 0; - for (k = 0; k < 16UL; k++) - { - i = (uint32_t)Bits[k]; - if ((j + i) > 256UL) - { - /* check for table overflow */ - return HAL_ERROR; - } - while (i != 0UL) - { - Huffsize[j] = (uint8_t) k + 1U; - j++; - i--; - } - } - Huffsize[j] = 0; - *LastK = j; - - /* Figure C.2: Generation of table of Huffman codes */ - code = 0; - si = Huffsize[0]; - j = 0; - while (Huffsize[j] != 0U) - { - while (((uint32_t) Huffsize[j]) == si) - { - Huffcode[j] = code; - j++; - code++; - } - /* code must fit in "size" bits (si), no code is allowed to be all ones*/ - if (si > 31UL) - { - return HAL_ERROR; - } - if (((uint32_t) code) >= (((uint32_t) 1) << si)) - { - return HAL_ERROR; - } - code <<= 1; - si++; - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Transform a Bits/Vals AC Huffman table to sizes/Codes huffman Table - * that can programmed to the JPEG encoder registers - * @param AC_BitsValsTable pointer to AC huffman bits/vals table - * @param AC_SizeCodesTable pointer to AC huffman Sizes/Codes table - * @retval HAL status - */ -static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable, - JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable) -{ - HAL_StatusTypeDef error; - uint8_t huffsize[257]; - uint32_t huffcode[257]; - uint32_t k; - uint32_t i; - uint32_t lsb; - uint32_t msb; - uint32_t lastK; - - error = JPEG_Bits_To_SizeCodes(AC_BitsValsTable->Bits, huffsize, huffcode, &lastK); - if (error != HAL_OK) - { - return error; - } - - /* Figure C.3: Ordering procedure for encoding procedure code tables */ - k = 0; - - while (k < lastK) - { - i = AC_BitsValsTable->HuffVal[k]; - if (i == 0UL) - { - i = JPEG_AC_HUFF_TABLE_SIZE - 2UL; /*i = 0x00 EOB code*/ - } - else if (i == 0xF0UL) /* i = 0xF0 ZRL code*/ - { - i = JPEG_AC_HUFF_TABLE_SIZE - 1UL; - } - else - { - msb = (i & 0xF0UL) >> 4; - lsb = (i & 0x0FUL); - i = (msb * 10UL) + lsb - 1UL; - } - if (i >= JPEG_AC_HUFF_TABLE_SIZE) - { - return HAL_ERROR; /* Huffman Table overflow error*/ - } - else - { - AC_SizeCodesTable->HuffmanCode[i] = huffcode[k]; - AC_SizeCodesTable->CodeLength[i] = huffsize[k] - 1U; - k++; - } - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Transform a Bits/Vals DC Huffman table to sizes/Codes huffman Table - * that can programmed to the JPEG encoder registers - * @param DC_BitsValsTable pointer to DC huffman bits/vals table - * @param DC_SizeCodesTable pointer to DC huffman Sizes/Codes table - * @retval HAL status - */ -static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable, - JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable) -{ - HAL_StatusTypeDef error; - - uint32_t k; - uint32_t i; - uint32_t lastK; - uint8_t huffsize[257]; - uint32_t huffcode[257]; - error = JPEG_Bits_To_SizeCodes(DC_BitsValsTable->Bits, huffsize, huffcode, &lastK); - if (error != HAL_OK) - { - return error; - } - /* Figure C.3: ordering procedure for encoding procedure code tables */ - k = 0; - - while (k < lastK) - { - i = DC_BitsValsTable->HuffVal[k]; - if (i >= JPEG_DC_HUFF_TABLE_SIZE) - { - return HAL_ERROR; /* Huffman Table overflow error*/ - } - else - { - DC_SizeCodesTable->HuffmanCode[i] = huffcode[k]; - DC_SizeCodesTable->CodeLength[i] = huffsize[k] - 1U; - k++; - } - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Set the JPEG register with an DC huffman table at the given DC table address - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param HuffTableDC pointer to DC huffman table - * @param DCTableAddress Encoder DC huffman table address it could be HUFFENC_DC0 or HUFFENC_DC1. - * @retval HAL status - */ -static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC, - const __IO uint32_t *DCTableAddress) -{ - HAL_StatusTypeDef error; - JPEG_DC_HuffCodeTableTypeDef dcSizeCodesTable; - uint32_t i; - uint32_t lsb; - uint32_t msb; - __IO uint32_t *address; - __IO uint32_t *addressDef; - - if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC0)) - { - address = (hjpeg->Instance->HUFFENC_DC0 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL)); - } - else if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC1)) - { - address = (hjpeg->Instance->HUFFENC_DC1 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL)); - } - else - { - return HAL_ERROR; - } - - if (HuffTableDC != NULL) - { - error = JPEG_DCHuff_BitsVals_To_SizeCodes(HuffTableDC, &dcSizeCodesTable); - if (error != HAL_OK) - { - return error; - } - addressDef = address; - *addressDef = 0x0FFF0FFF; - addressDef++; - *addressDef = 0x0FFF0FFF; - - i = JPEG_DC_HUFF_TABLE_SIZE; - while (i > 1UL) - { - i--; - address --; - msb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | - ((uint32_t)dcSizeCodesTable.HuffmanCode[i] & 0xFFUL); - i--; - lsb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | - ((uint32_t)dcSizeCodesTable.HuffmanCode[i] & 0xFFUL); - - *address = lsb | (msb << 16); - } - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Set the JPEG register with an AC huffman table at the given AC table address - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param HuffTableAC pointer to AC huffman table - * @param ACTableAddress Encoder AC huffman table address it could be HUFFENC_AC0 or HUFFENC_AC1. - * @retval HAL status - */ -static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC, - const __IO uint32_t *ACTableAddress) -{ - HAL_StatusTypeDef error; - JPEG_AC_HuffCodeTableTypeDef acSizeCodesTable; - uint32_t i; - uint32_t lsb; - uint32_t msb; - __IO uint32_t *address; - __IO uint32_t *addressDef; - - if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC0)) - { - address = (hjpeg->Instance->HUFFENC_AC0 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL)); - } - else if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC1)) - { - address = (hjpeg->Instance->HUFFENC_AC1 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL)); - } - else - { - return HAL_ERROR; - } - - if (HuffTableAC != NULL) - { - error = JPEG_ACHuff_BitsVals_To_SizeCodes(HuffTableAC, &acSizeCodesTable); - if (error != HAL_OK) - { - return error; - } - /* Default values settings: 162:167 FFFh , 168:175 FD0h_FD7h */ - /* Locations 162:175 of each AC table contain information used internally by the core */ - - addressDef = address; - for (i = 0; i < 3UL; i++) - { - *addressDef = 0x0FFF0FFF; - addressDef++; - } - *addressDef = 0x0FD10FD0; - addressDef++; - *addressDef = 0x0FD30FD2; - addressDef++; - *addressDef = 0x0FD50FD4; - addressDef++; - *addressDef = 0x0FD70FD6; - /* end of Locations 162:175 */ - - - i = JPEG_AC_HUFF_TABLE_SIZE; - while (i > 1UL) - { - i--; - address--; - msb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | - ((uint32_t)acSizeCodesTable.HuffmanCode[i] & 0xFFUL); - i--; - lsb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | - ((uint32_t)acSizeCodesTable.HuffmanCode[i] & 0xFFUL); - - *address = lsb | (msb << 16); - } - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Configure the JPEG encoder register huffman tables to used during - * the encdoing operation - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg) -{ - HAL_StatusTypeDef error; - - JPEG_Set_Huff_DHTMem(hjpeg); - error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable, - (hjpeg->Instance->HUFFENC_AC0)); - if (error != HAL_OK) - { - return error; - } - - error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable, - (hjpeg->Instance->HUFFENC_AC1)); - if (error != HAL_OK) - { - return error; - } - - error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable, - hjpeg->Instance->HUFFENC_DC0); - if (error != HAL_OK) - { - return error; - } - - error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable, - hjpeg->Instance->HUFFENC_DC1); - if (error != HAL_OK) - { - return error; - } - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Configure the JPEG register huffman tables to be included in the JPEG - * file header (used for encoding only) - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -static void JPEG_Set_Huff_DHTMem(const JPEG_HandleTypeDef *hjpeg) -{ - const JPEG_ACHuffTableTypeDef *HuffTableAC0 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable; - const JPEG_ACHuffTableTypeDef *HuffTableAC1 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable; - const JPEG_DCHuffTableTypeDef *HuffTableDC0 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable; - const JPEG_DCHuffTableTypeDef *HuffTableDC1 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable; - uint32_t value; - uint32_t index; - __IO uint32_t *address; - - /* DC0 Huffman Table : BITS*/ - /* DC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address to DHTMEM + 3*/ - address = (hjpeg->Instance->DHTMEM + 3); - index = 16; - while (index > 3UL) - { - - *address = (((uint32_t)HuffTableDC0->Bits[index - 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableDC0->Bits[index - 2UL] & 0xFFUL) << 16) | - (((uint32_t)HuffTableDC0->Bits[index - 3UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableDC0->Bits[index - 4UL] & 0xFFUL); - address--; - index -= 4UL; - - } - /* DC0 Huffman Table : Val*/ - /* DC0 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +4 to DHTMEM + 6 */ - address = (hjpeg->Instance->DHTMEM + 6); - index = 12; - while (index > 3UL) - { - *address = (((uint32_t)HuffTableDC0->HuffVal[index - 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableDC0->HuffVal[index - 2UL] & 0xFFUL) << 16) | - (((uint32_t)HuffTableDC0->HuffVal[index - 3UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableDC0->HuffVal[index - 4UL] & 0xFFUL); - address--; - index -= 4UL; - } - - /* AC0 Huffman Table : BITS*/ - /* AC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 7 to DHTMEM + 10*/ - address = (hjpeg->Instance->DHTMEM + 10UL); - index = 16; - while (index > 3UL) - { - - *address = (((uint32_t)HuffTableAC0->Bits[index - 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableAC0->Bits[index - 2UL] & 0xFFUL) << 16) | - (((uint32_t)HuffTableAC0->Bits[index - 3UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableAC0->Bits[index - 4UL] & 0xFFUL); - address--; - index -= 4UL; - - } - /* AC0 Huffman Table : Val*/ - /* AC0 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 11 to DHTMEM + 51 */ - /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 51) belong to AC0 VALS table */ - address = (hjpeg->Instance->DHTMEM + 51); - value = *address & 0xFFFF0000U; - value = value | (((uint32_t)HuffTableAC0->HuffVal[161] & 0xFFUL) << 8) | - ((uint32_t)HuffTableAC0->HuffVal[160] & 0xFFUL); - *address = value; - - /*continue setting 160 AC0 huffman values */ - address--; /* address = hjpeg->Instance->DHTMEM + 50*/ - index = JPEG_AC_HUFF_TABLE_SIZE - 2UL; - while (index > 3UL) - { - *address = (((uint32_t)HuffTableAC0->HuffVal[index - 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableAC0->HuffVal[index - 2UL] & 0xFFUL) << 16) | - (((uint32_t)HuffTableAC0->HuffVal[index - 3UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableAC0->HuffVal[index - 4UL] & 0xFFUL); - address--; - index -= 4UL; - } - - /* DC1 Huffman Table : BITS*/ - /* DC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM + 51 base address to DHTMEM + 55*/ - /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 51) belong to DC1 Bits table */ - address = (hjpeg->Instance->DHTMEM + 51); - value = *address & 0x0000FFFFU; - value = value | (((uint32_t)HuffTableDC1->Bits[1] & 0xFFUL) << 24) | - (((uint32_t)HuffTableDC1->Bits[0] & 0xFFUL) << 16); - *address = value; - - /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 55) belong to DC1 Bits table */ - address = (hjpeg->Instance->DHTMEM + 55); - value = *address & 0xFFFF0000U; - value = value | (((uint32_t)HuffTableDC1->Bits[15] & 0xFFUL) << 8) | - ((uint32_t)HuffTableDC1->Bits[14] & 0xFFUL); - *address = value; - - /*continue setting 12 DC1 huffman Bits from DHTMEM + 54 down to DHTMEM + 52*/ - address--; - index = 12; - while (index > 3UL) - { - - *address = (((uint32_t)HuffTableDC1->Bits[index + 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableDC1->Bits[index] & 0xFFUL) << 16) | - (((uint32_t)HuffTableDC1->Bits[index - 1UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableDC1->Bits[index - 2UL] & 0xFFUL); - address--; - index -= 4UL; - - } - /* DC1 Huffman Table : Val*/ - /* DC1 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +55 to DHTMEM + 58 */ - /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 55) belong to DC1 Val table */ - address = (hjpeg->Instance->DHTMEM + 55); - value = *address & 0x0000FFFFUL; - value = value | (((uint32_t)HuffTableDC1->HuffVal[1] & 0xFFUL) << 24) | - (((uint32_t)HuffTableDC1->HuffVal[0] & 0xFFUL) << 16); - *address = value; - - /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 58) belong to DC1 Val table */ - address = (hjpeg->Instance->DHTMEM + 58); - value = *address & 0xFFFF0000UL; - value = value | (((uint32_t)HuffTableDC1->HuffVal[11] & 0xFFUL) << 8) | - ((uint32_t)HuffTableDC1->HuffVal[10] & 0xFFUL); - *address = value; - - /*continue setting 8 DC1 huffman val from DHTMEM + 57 down to DHTMEM + 56*/ - address--; - index = 8; - while (index > 3UL) - { - *address = (((uint32_t)HuffTableDC1->HuffVal[index + 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableDC1->HuffVal[index] & 0xFFUL) << 16) | - (((uint32_t)HuffTableDC1->HuffVal[index - 1UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableDC1->HuffVal[index - 2UL] & 0xFFUL); - address--; - index -= 4UL; - } - - /* AC1 Huffman Table : BITS*/ - /* AC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 58 to DHTMEM + 62*/ - /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 58) belong to AC1 Bits table */ - address = (hjpeg->Instance->DHTMEM + 58); - value = *address & 0x0000FFFFU; - value = value | (((uint32_t)HuffTableAC1->Bits[1] & 0xFFUL) << 24) | - (((uint32_t)HuffTableAC1->Bits[0] & 0xFFUL) << 16); - *address = value; - - /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 62) belong to Bits Val table */ - address = (hjpeg->Instance->DHTMEM + 62); - value = *address & 0xFFFF0000U; - value = value | (((uint32_t)HuffTableAC1->Bits[15] & 0xFFUL) << 8) | ((uint32_t)HuffTableAC1->Bits[14] & 0xFFUL); - *address = value; - - /*continue setting 12 AC1 huffman Bits from DHTMEM + 61 down to DHTMEM + 59*/ - address--; - index = 12; - while (index > 3UL) - { - - *address = (((uint32_t)HuffTableAC1->Bits[index + 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableAC1->Bits[index] & 0xFFUL) << 16) | - (((uint32_t)HuffTableAC1->Bits[index - 1UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableAC1->Bits[index - 2UL] & 0xFFUL); - address--; - index -= 4UL; - - } - /* AC1 Huffman Table : Val*/ - /* AC1 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 62 to DHTMEM + 102 */ - /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 62) belong to AC1 VALS table */ - address = (hjpeg->Instance->DHTMEM + 62); - value = *address & 0x0000FFFFUL; - value = value | (((uint32_t)HuffTableAC1->HuffVal[1] & 0xFFUL) << 24) | - (((uint32_t)HuffTableAC1->HuffVal[0] & 0xFFUL) << 16); - *address = value; - - /*continue setting 160 AC1 huffman values from DHTMEM + 63 to DHTMEM+102 */ - address = (hjpeg->Instance->DHTMEM + 102); - index = JPEG_AC_HUFF_TABLE_SIZE - 2UL; - while (index > 3UL) - { - *address = (((uint32_t)HuffTableAC1->HuffVal[index + 1UL] & 0xFFUL) << 24) | - (((uint32_t)HuffTableAC1->HuffVal[index] & 0xFFUL) << 16) | - (((uint32_t)HuffTableAC1->HuffVal[index - 1UL] & 0xFFUL) << 8) | - ((uint32_t)HuffTableAC1->HuffVal[index - 2UL] & 0xFFUL); - address--; - index -= 4UL; - } - -} - -/** - * @brief Configure the JPEG registers with a given quantization table - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param QTable pointer to an array of 64 bytes giving the quantization table - * @param QTableAddress destination quantization address in the JPEG peripheral - * it could be QMEM0, QMEM1, QMEM2 or QMEM3 - * @retval 0 if no error, 1 if error - */ -static uint32_t JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef *hjpeg, const uint8_t *QTable, - __IO uint32_t *QTableAddress) -{ - uint32_t i; - uint32_t j; - uint32_t quantRow; - uint32_t quantVal; - uint32_t ScaleFactor; - __IO uint32_t *tableAddress; - - tableAddress = QTableAddress; - - if ((hjpeg->Conf.ImageQuality >= 50UL) && (hjpeg->Conf.ImageQuality <= 100UL)) - { - ScaleFactor = JPEG_HIGH_QUALITY_REFERENCE - (hjpeg->Conf.ImageQuality * 2UL); - } - else if (hjpeg->Conf.ImageQuality > 0UL) - { - ScaleFactor = JPEG_LOW_QUALITY_REFERENCE / ((uint32_t) hjpeg->Conf.ImageQuality); - } - else - { - return 1UL; - } - - /*Quantization_table = (Standard_quanization_table * ScaleFactor + 50) / 100*/ - i = 0; - while (i < (JPEG_QUANT_TABLE_SIZE - 3UL)) - { - quantRow = 0; - for (j = 0; j < 4UL; j++) - { - /* Note that the quantization coefficients must be specified in the table in zigzag order */ - quantVal = ((((uint32_t) QTable[JPEG_ZIGZAG_ORDER[i + j]]) * ScaleFactor) + 50UL) / 100UL; - - if (quantVal == 0UL) - { - quantVal = 1UL; - } - else if (quantVal > 255UL) - { - quantVal = JPEG_QUANTVAL_MAX; - } - else - { - /* Nothing to do, keep same value of quantVal */ - } - - quantRow |= ((quantVal & 0xFFUL) << (8UL * j)); - } - - i += 4UL; - *tableAddress = quantRow; - tableAddress ++; - } - - /* Return function status */ - return 0UL; -} - -/** - * @brief Configure the JPEG registers for YCbCr color space - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg) -{ - uint32_t ySamplingH; - uint32_t ySamplingV; - uint32_t yblockNb; - - /*Set Number of color components to 3*/ - hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_NF; - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_NF_1; - - /* compute MCU block size and Y, Cb ,Cr sampling factors*/ - if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) - { - ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ - ySamplingV = JPEG_CONFR4_VSF_1; /* Vs = 2*/ - - yblockNb = 0x30; /* 4 blocks of 8x8*/ - } - else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) - { - ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ - ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ - - yblockNb = 0x10; /* 2 blocks of 8x8*/ - } - else /*JPEG_444_SUBSAMPLING and default*/ - { - ySamplingH = JPEG_CONFR4_HSF_0; /* Hs = 1*/ - ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ - - yblockNb = 0; /* 1 block of 8x8*/ - } - - hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS); - hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF_1 | JPEG_CONFR1_NS_1); - - /*Reset CONFR4 register*/ - hjpeg->Instance->CONFR4 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 0*/ - hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB)); - - /*Reset CONFR5 register*/ - hjpeg->Instance->CONFR5 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 1*/ - hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0 | JPEG_CONFR5_QT_0 | JPEG_CONFR5_HA | - JPEG_CONFR5_HD); - - /*Reset CONFR6 register*/ - hjpeg->Instance->CONFR6 = 0; - /*Set Horizental and Vertical sampling factor and number of blocks for component 2*/ - /* In YCBCR , by default, both chrominance components (component 1 and component 2) - use the same Quantization table (table 1) */ - /* In YCBCR , both chrominance components (component 1 and component 2) use the same Huffman tables (table 1) */ - hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0 | JPEG_CONFR6_QT_0 | JPEG_CONFR6_HA | - JPEG_CONFR6_HD); - -} - -/** - * @brief Configure the JPEG registers for GrayScale color space - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg) -{ - /*Set Number of color components to 1*/ - hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS); - - /*in GrayScale use 1 single Quantization table (Table 0)*/ - /*in GrayScale use only one couple of AC/DC huffman table (table 0)*/ - - /*Reset CONFR4 register*/ - hjpeg->Instance->CONFR4 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 0*/ - hjpeg->Instance->CONFR4 |= JPEG_CONFR4_HSF_0 | JPEG_CONFR4_VSF_0 ; -} - -/** - * @brief Configure the JPEG registers for CMYK color space - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg) -{ - uint32_t ySamplingH; - uint32_t ySamplingV; - uint32_t yblockNb; - - /*Set Number of color components to 4*/ - hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF | JPEG_CONFR1_NS); - - /* compute MCU block size and Y, Cb ,Cr sampling factors*/ - if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) - { - ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ - ySamplingV = JPEG_CONFR4_VSF_1; /* Vs = 2*/ - - yblockNb = 0x30; /* 4 blocks of 8x8*/ - } - else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) - { - ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ - ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ - - yblockNb = 0x10; /* 2 blocks of 8x8*/ - } - else /*JPEG_444_SUBSAMPLING and default*/ - { - ySamplingH = JPEG_CONFR4_HSF_0; /* Hs = 1*/ - ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ - - yblockNb = 0; /* 1 block of 8x8*/ - } - - /*Reset CONFR4 register*/ - hjpeg->Instance->CONFR4 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 0*/ - hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB)); - - /*Reset CONFR5 register*/ - hjpeg->Instance->CONFR5 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 1*/ - hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0); - - /*Reset CONFR6 register*/ - hjpeg->Instance->CONFR6 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 2*/ - hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0); - - /*Reset CONFR7 register*/ - hjpeg->Instance->CONFR7 = 0; - /*Set Horizental and Vertical sampling factor , number of blocks, - Quantization table and Huffman AC/DC tables for component 3*/ - hjpeg->Instance->CONFR7 |= (JPEG_CONFR7_HSF_0 | JPEG_CONFR7_VSF_0); -} - -/** - * @brief Init the JPEG encoding/decoding process in case of Polling or Interrupt and DMA - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None - */ -static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg) -{ - /*Reset pause*/ - hjpeg->Context &= (~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT)); - - if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) - { - /*Set JPEG Codec to Decoding mode */ - hjpeg->Instance->CONFR1 |= JPEG_CONFR1_DE; - } - else /* JPEG_CONTEXT_ENCODE */ - { - /*Set JPEG Codec to Encoding mode */ - hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_DE; - } - - /*Stop JPEG processing */ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - /* Disable All Interrupts */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - /* Disable All DMA requests */ - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); - /* Flush input and output FIFOs*/ - hjpeg->Instance->CR |= JPEG_CR_IFF; - hjpeg->Instance->CR |= JPEG_CR_OFF; - - /* Clear all flags */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); - - /*Start Encoding/Decoding*/ - hjpeg->Instance->CONFR0 |= JPEG_CONFR0_START; - - if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) - { - /*Enable IN/OUT, end of Conversation, and end of header parsing interruptions*/ - __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_IFT | JPEG_IT_IFNF | JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC | JPEG_IT_HPD); - } - else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) - { - /*Enable End Of Conversation, and End Of Header parsing interruptions*/ - __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD); - - } - else - { - /* Nothing to do */ - } -} - -/** - * @brief JPEG encoding/decoding process in case of Polling or Interrupt - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval JPEG_PROCESS_DONE if the process has ends else JPEG_PROCESS_ONGOING - */ -static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg) -{ - uint32_t tmpContext; - - /*End of header processing flag */ - if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) - { - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL) - { - /*Call Header parsing complete callback */ - (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf); - /* Reset the ImageQuality */ - hjpeg->Conf.ImageQuality = 0; - /* Note : the image quality is only available at the end of the decoding operation */ - /* at the current stage the calculated image quality is not correct so reset it */ - - /*Call Info Ready callback */ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf); -#else - HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD); - - /* Clear header processing done flag */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF); - } - } - - /*Input FIFO status handling*/ - if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_INPUT) == 0UL) - { - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFTF) != 0UL) - { - /*Input FIFO threshold flag */ - /*JPEG_FIFO_TH_SIZE words can be written in */ - JPEG_ReadInputData(hjpeg, JPEG_FIFO_TH_SIZE); - } - else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFNFF) != 0UL) - { - /*Input FIFO Not Full flag */ - /*32-bit value can be written in */ - JPEG_ReadInputData(hjpeg, 1); - } - else - { - /* Nothing to do */ - } - } - - - /*Output FIFO flag handling*/ - if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) - { - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFTF) != 0UL) - { - /*Output FIFO threshold flag */ - /*JPEG_FIFO_TH_SIZE words can be read out */ - JPEG_StoreOutputData(hjpeg, JPEG_FIFO_TH_SIZE); - } - else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL) - { - /*Output FIFO Not Empty flag */ - /*32-bit value can be read out */ - JPEG_StoreOutputData(hjpeg, 1); - } - else - { - /* Nothing to do */ - } - } - - /*End of Conversion handling :i.e EOC flag is high and OFTF low and OFNEF low*/ - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF | JPEG_FLAG_OFTF | JPEG_FLAG_OFNEF) == JPEG_FLAG_EOCF) - { - /*Stop Encoding/Decoding*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) - { - /* Disable All Interrupts */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - } - - /* Clear all flags */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); - - /*Call End of conversion callback */ - if (hjpeg->JpegOutCount > 0UL) - { - /*Output Buffer is not empty, call DecodedDataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - hjpeg->JpegOutCount = 0; - } - - /*Reset Context Operation*/ - tmpContext = hjpeg->Context; - /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/ - hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES); - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /*Call End of Encoding/Decoding callback */ - if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DecodeCpltCallback(hjpeg); -#else - HAL_JPEG_DecodeCpltCallback(hjpeg); -#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ - } - else /* JPEG_CONTEXT_ENCODE */ - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->EncodeCpltCallback(hjpeg); -#else - HAL_JPEG_EncodeCpltCallback(hjpeg); -#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ - } - - return JPEG_PROCESS_DONE; - } - - - return JPEG_PROCESS_ONGOING; -} - -/** - * @brief Store some output data from the JPEG peripheral to the output buffer. - * This function is used when the JPEG peripheral has new data to output - * in case of Polling or Interrupt process - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param nbOutputWords Number of output words (of 32 bits) ready from the JPEG peripheral - * @retval None - */ -static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords) -{ - uint32_t index; - uint32_t nb_words; - uint32_t nb_bytes; - uint32_t dataword; - - if (hjpeg->OutDataLength >= (hjpeg->JpegOutCount + (nbOutputWords * 4UL))) - { - for (index = 0; index < nbOutputWords; index++) - { - /*Transfer 32 bits from the JPEG output FIFO*/ - dataword = hjpeg->Instance->DOR; - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24); - hjpeg->JpegOutCount += 4UL; - } - if (hjpeg->OutDataLength == hjpeg->JpegOutCount) - { - /*Output Buffer is full, call DecodedDataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ - hjpeg->JpegOutCount = 0; - } - } - else if (hjpeg->OutDataLength > hjpeg->JpegOutCount) - { - nb_words = (hjpeg->OutDataLength - hjpeg->JpegOutCount) / 4UL; - for (index = 0; index < nb_words; index++) - { - /*Transfer 32 bits from the JPEG output FIFO*/ - dataword = hjpeg->Instance->DOR; - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24); - hjpeg->JpegOutCount += 4UL; - } - if (hjpeg->OutDataLength == hjpeg->JpegOutCount) - { - /*Output Buffer is full, call DecodedDataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - hjpeg->JpegOutCount = 0; - } - else - { - nb_bytes = hjpeg->OutDataLength - hjpeg->JpegOutCount; - dataword = hjpeg->Instance->DOR; - for (index = 0; index < nb_bytes; index++) - { - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * (index & 0x3UL))) & 0xFFUL); - hjpeg->JpegOutCount++; - } - /*Output Buffer is full, call DecodedDataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - hjpeg->JpegOutCount = 0; - - nb_bytes = 4UL - nb_bytes; - for (index = nb_bytes; index < 4UL; index++) - { - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * index)) & 0xFFUL); - hjpeg->JpegOutCount++; - } - } - } - else - { - /* Nothing to do */ - } -} - -/** - * @brief Read some input Data from the input buffer. - * This function is used when the JPEG peripheral needs new data - * in case of Polling or Interrupt process - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @param nbRequestWords Number of input words (of 32 bits) that the JPE peripheral request - * @retval None - */ -static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords) -{ - uint32_t nb_bytes = 0; - uint32_t nb_words; - uint32_t index; - uint32_t dataword; - uint32_t input_count; - - if ((hjpeg->InDataLength == 0UL) || (nbRequestWords == 0UL)) - { - /* No more Input data : nothing to do*/ - (void) HAL_JPEG_Pause(hjpeg, JPEG_PAUSE_RESUME_INPUT); - } - else if (hjpeg->InDataLength > hjpeg->JpegInCount) - { - nb_bytes = hjpeg->InDataLength - hjpeg->JpegInCount; - } - else if (hjpeg->InDataLength == hjpeg->JpegInCount) - { - /*Call HAL_JPEG_GetDataCallback to get new data */ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount); -#else - HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount); -#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ - - if (hjpeg->InDataLength > 4UL) - { - hjpeg->InDataLength = ((hjpeg->InDataLength + 3UL) / 4UL) * 4UL; - } - hjpeg->JpegInCount = 0; - nb_bytes = hjpeg->InDataLength; - } - else - { - /* Nothing to do */ - } - if (((hjpeg->Context & JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (nb_bytes > 0UL)) - { - nb_words = nb_bytes / 4UL; - if (nb_words >= nbRequestWords) - { - for (index = 0; index < nbRequestWords; index++) - { - input_count = hjpeg->JpegInCount; - hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \ - (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \ - (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \ - (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24)); - - hjpeg->JpegInCount += 4UL; - } - } - else /*nb_words < nbRequestWords*/ - { - if (nb_words > 0UL) - { - for (index = 0; index < nb_words; index++) - { - input_count = hjpeg->JpegInCount; - hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \ - (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \ - (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \ - (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24)); - - hjpeg->JpegInCount += 4UL; - } - } - else - { - /* end of file*/ - dataword = 0; - for (index = 0; index < nb_bytes; index++) - { - dataword |= (uint32_t)hjpeg->pJpegInBuffPtr[hjpeg->JpegInCount] << (8UL * (index & 0x03UL)); - hjpeg->JpegInCount++; - } - hjpeg->Instance->DIR = dataword; - } - } - } -} - -/** - * @brief Start the JPEG DMA process (encoding/decoding) - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING - */ -static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg) -{ - if ((hjpeg->InDataLength < 4UL) || (hjpeg->OutDataLength < 4UL)) - { - return HAL_ERROR; - } - /* Reset Ending DMA internal context flag*/ - hjpeg->Context &= ~JPEG_CONTEXT_ENDING_DMA; - - /* Disable DMA In/Out Request*/ - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA | JPEG_DMA_IDMA); - - /* Set the JPEG DMA In transfer complete callback */ - hjpeg->hdmain->XferCpltCallback = JPEG_DMAInCpltCallback; - /* Set the DMA In error callback */ - hjpeg->hdmain->XferErrorCallback = JPEG_DMAErrorCallback; - - /* Set the JPEG DMA Out transfer complete callback */ - hjpeg->hdmaout->XferCpltCallback = JPEG_DMAOutCpltCallback; - /* Set the DMA Out error callback */ - hjpeg->hdmaout->XferErrorCallback = JPEG_DMAErrorCallback; - /* Set the DMA Out Abort callback */ - hjpeg->hdmaout->XferAbortCallback = JPEG_DMAOutAbortCallback; - - /*DMA transfer size must be a multiple of 4 bytes i.e multiple of 32bits words*/ - hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL); - - /*DMA transfer size must be a multiple of 4 bytes i.e multiple of 32bits words*/ - hjpeg->OutDataLength = hjpeg->OutDataLength - (hjpeg->OutDataLength % 4UL); - - if ((hjpeg->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hjpeg->hdmain->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hjpeg->InDataLength; - - /* Set DMA source address */ - hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hjpeg->pJpegInBuffPtr; - - /* Set DMA destination address */ - hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hjpeg->Instance->DIR; - - if (HAL_DMAEx_List_Start_IT(hjpeg->hdmain) != HAL_OK) - { - return HAL_ERROR; - } - } - else - { - /* Set the JPEG State to ready */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /* Update JPEG error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - } - else - { - /* Start DMA FIFO In transfer */ - if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR, - hjpeg->InDataLength) != HAL_OK) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - return HAL_ERROR; - } - } - - if ((hjpeg->hdmaout->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hjpeg->hdmaout->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hjpeg->OutDataLength; - - /* Set DMA source address */ - hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hjpeg->Instance->DOR; - - /* Set DMA destination address */ - hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hjpeg->pJpegOutBuffPtr; - - if (HAL_DMAEx_List_Start_IT(hjpeg->hdmaout) != HAL_OK) - { - return HAL_ERROR; - } - } - else - { - /* Set the JPEG State to ready */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /* Update JPEG error code */ - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - return HAL_ERROR; - } - } - else - { - /* Start DMA FIFO Out transfer */ - if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr, - hjpeg->OutDataLength) != HAL_OK) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - return HAL_ERROR; - } - } - - /* Enable JPEG In/Out DMA requests*/ - JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_IDMA | JPEG_DMA_ODMA); - - return HAL_OK; -} - -/** - * @brief Continue the current JPEG DMA process (encoding/decoding) - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING - */ -static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg) -{ - /*End of header processing flag rises*/ - if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) - { - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL) - { - /*Call Header parsing complete callback */ - (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf); - - /* Reset the ImageQuality */ - hjpeg->Conf.ImageQuality = 0; - /* Note : the image quality is only available at the end of the decoding operation */ - /* at the current stage the calculated image quality is not correct so reset it */ - - /*Call Info Ready callback */ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf); -#else - HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD); - - /* Clear header processing done flag */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF); - } - } - - /*End of Conversion handling*/ - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) != 0UL) - { - /*Disabkle JPEG In/Out DMA Requests*/ - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA | JPEG_DMA_IDMA); - - hjpeg->Context |= JPEG_CONTEXT_ENDING_DMA; - - /*Stop Encoding/Decoding*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - /* Clear all flags */ - __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); - - if (hjpeg->hdmain->State == HAL_DMA_STATE_BUSY) - { - /* Stop the DMA In Xfer*/ - (void) HAL_DMA_Abort(hjpeg->hdmain); - } - - if (hjpeg->hdmaout->State == HAL_DMA_STATE_BUSY) - { - /* Stop the DMA out Xfer*/ - (void) HAL_DMA_Abort(hjpeg->hdmaout); - } - - JPEG_DMA_EndProcess(hjpeg); - } - - -} - -/** - * @brief Finalize the current JPEG DMA process (encoding/decoding) - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval JPEG_PROCESS_DONE - */ -static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg) -{ - uint32_t tmpContext; - hjpeg->JpegOutCount = hjpeg->OutDataLength - JPEG_GET_DMA_REMAIN_DATA(hjpeg->hdmaout); - - /*if Output Buffer is full, call HAL_JPEG_DataReadyCallback*/ - if (hjpeg->JpegOutCount == hjpeg->OutDataLength) - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - hjpeg->JpegOutCount = 0; - } - - /*Check if remaining data in the output FIFO*/ - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL) - { - if (hjpeg->JpegOutCount > 0UL) - { - /*Output Buffer is not empty, call DecodedDataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - hjpeg->JpegOutCount = 0; - } - - /*Stop Encoding/Decoding*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - tmpContext = hjpeg->Context; - /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/ - hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES); - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /*Call End of Encoding/Decoding callback */ - if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DecodeCpltCallback(hjpeg); -#else - HAL_JPEG_DecodeCpltCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - } - else /* JPEG_CONTEXT_ENCODE */ - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->EncodeCpltCallback(hjpeg); -#else - HAL_JPEG_EncodeCpltCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - } - } - else if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) - { - JPEG_DMA_PollResidualData(hjpeg); - } - else - { - /* Nothing to do */ - } - -} - -/** - * @brief Poll residual output data when DMA process (encoding/decoding) - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval None. - */ -static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg) -{ - uint32_t tmpContext; - uint32_t count; - uint32_t dataOut; - - for (count = JPEG_FIFO_SIZE; count > 0UL; count--) - { - if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) - { - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL) - { - dataOut = hjpeg->Instance->DOR; - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataOut & 0x000000FFUL); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataOut & 0x0000FF00UL) >> 8); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataOut & 0x00FF0000UL) >> 16); - hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataOut & 0xFF000000UL) >> 24); - hjpeg->JpegOutCount += 4UL; - - if (hjpeg->JpegOutCount == hjpeg->OutDataLength) - { - /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - hjpeg->JpegOutCount = 0; - } - - } - } - } - - tmpContext = hjpeg->Context; - - if ((__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL) || ((tmpContext & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)) - { - /*Stop Encoding/Decoding*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - if (hjpeg->JpegOutCount > 0UL) - { - /*Output Buffer is not empty, call DecodedDataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - hjpeg->JpegOutCount = 0; - } - - tmpContext = hjpeg->Context; - /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/ - hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES); - - /* Process Unlocked */ - __HAL_UNLOCK(hjpeg); - - /* Change the JPEG state */ - hjpeg->State = HAL_JPEG_STATE_READY; - - /*Call End of Encoding/Decoding callback */ - if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DecodeCpltCallback(hjpeg); -#else - HAL_JPEG_DecodeCpltCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - } - else /* JPEG_CONTEXT_ENCODE */ - { -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->EncodeCpltCallback(hjpeg); -#else - HAL_JPEG_EncodeCpltCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief DMA input transfer complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure. - * @retval None - */ -static void JPEG_DMAInCpltCallback(DMA_HandleTypeDef *hdma) -{ - JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable The JPEG IT so the DMA Input Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) == - JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */ - { - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_IDMA); - - hjpeg->JpegInCount = hjpeg->InDataLength - JPEG_GET_DMA_REMAIN_DATA(hdma); - - /*Call HAL_JPEG_GetDataCallback to get new data */ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount); -#else - HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - if (hjpeg->InDataLength >= 4UL) - { - /*JPEG Input DMA transfer data number must be multiple of 32 bits word - as the destination is a 32 bits (4 bytes) register */ - hjpeg->InDataLength = ((hjpeg->InDataLength + 3UL) / 4UL) * 4UL; - } - else - { - /* Nothing to do */ - } - - if (((hjpeg->Context & JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (hjpeg->InDataLength > 0UL)) - { - /* Start DMA FIFO In transfer */ - if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR, - hjpeg->InDataLength) != HAL_OK) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - hjpeg->State = HAL_JPEG_STATE_ERROR; -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->ErrorCallback(hjpeg); -#else - HAL_JPEG_ErrorCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - return; - } - JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_IDMA); - } - - /* JPEG Conversion still on going : Enable the JPEG IT */ - __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD); - } -} - -/** - * @brief DMA output transfer complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure. - * @retval None - */ -static void JPEG_DMAOutCpltCallback(DMA_HandleTypeDef *hdma) -{ - JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable The JPEG IT so the DMA Output Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) == - JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */ - { - if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) == 0UL) - { - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA); - hjpeg->JpegOutCount = hjpeg->OutDataLength - JPEG_GET_DMA_REMAIN_DATA(hdma); - - /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/ -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#else - HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - - if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) - { - /* Start DMA FIFO Out transfer */ - if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr, - hjpeg->OutDataLength) != HAL_OK) - { - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; - hjpeg->State = HAL_JPEG_STATE_ERROR; -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->ErrorCallback(hjpeg); -#else - HAL_JPEG_ErrorCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - return; - } - JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_ODMA); - } - } - - /* JPEG Conversion still on going : Enable the JPEG IT */ - __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD); - } -} - - -/** - * @brief DMA Transfer error callback - * @param hdma pointer to a DMA_HandleTypeDef structure. - * @retval None - */ -static void JPEG_DMAErrorCallback(DMA_HandleTypeDef *hdma) -{ - JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (HAL_DMA_GetError(hdma) != HAL_DMA_ERROR_NONE) - { - /*Stop Encoding/Decoding*/ - hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; - - /* Disable All Interrupts */ - __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); - - /* Disable All DMA requests */ - JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); - - hjpeg->State = HAL_JPEG_STATE_READY; - hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; -#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) - hjpeg->ErrorCallback(hjpeg); -#else - HAL_JPEG_ErrorCallback(hjpeg); -#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DMA output Abort callback - * @param hdma pointer to a DMA_HandleTypeDef structure. - * @retval None - */ -static void JPEG_DMAOutAbortCallback(DMA_HandleTypeDef *hdma) -{ - JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL) - { - JPEG_DMA_EndProcess(hjpeg); - } -} - - -/** - * @brief Calculate the decoded image quality (from 1 to 100) - * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains - * the configuration information for JPEG module - * @retval JPEG image quality from 1 to 100. - */ -static uint32_t JPEG_GetQuality(const JPEG_HandleTypeDef *hjpeg) -{ - uint32_t quality = 0; - uint32_t quantRow; - uint32_t quantVal; - uint32_t scale; - uint32_t i; - uint32_t j; - const __IO uint32_t *tableAddress = hjpeg->Instance->QMEM0; - - i = 0; - while (i < (JPEG_QUANT_TABLE_SIZE - 3UL)) - { - quantRow = *tableAddress; - for (j = 0; j < 4UL; j++) - { - quantVal = (quantRow >> (8UL * j)) & 0xFFUL; - if (quantVal == 1UL) - { - /* if Quantization value = 1 then quality is 100%*/ - quality += 100UL; - } - else - { - /* Note that the quantization coefficients must be specified in the table in zigzag order */ - scale = (quantVal * 100UL) / ((uint32_t) hjpeg->QuantTable0[JPEG_ZIGZAG_ORDER[i + j]]); - - if (scale <= 100UL) - { - quality += (200UL - scale) / 2UL; - } - else - { - quality += 5000UL / scale; - } - } - } - - i += 4UL; - tableAddress ++; - } - - return (quality / 64UL); -} -/** - * @} - */ - -/** - * @} - */ -#endif /* JPEG */ -#endif /* HAL_JPEG_MODULE_ENABLED */ - - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_jpeg.c + * @author MCD Application Team + * @brief JPEG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the JPEG encoder/decoder peripheral: + * + Initialization and de-initialization functions + * + JPEG processing functions encoding and decoding + * + JPEG decoding Getting Info and encoding configuration setting + * + JPEG enable/disable header parsing functions (for decoding) + * + JPEG Input/Output Buffer configuration. + * + JPEG callback functions + * + JPEG Abort/Pause/Resume functions + * + JPEG custom quantization tables setting functions + * + IRQ handler management + * + Peripheral State and Error functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the JPEG peripheral using HAL_JPEG_Init : No initialization parameters are required. + Only the call to HAL_JPEG_Init is necessary to initialize the JPEG peripheral. + + (#) If operation is JPEG encoding use function HAL_JPEG_ConfigEncoding to set + the encoding parameters (mandatory before calling the encoding function). + the application can change the encoding parameter ImageQuality from + 1 to 100 to obtain a more or less quality (visual quality vs the original row image), + and inversely more or less jpg file size. + + (#) Note that for decoding operation the JPEG peripheral output data are organized in + YCbCr blocks called MCU (Minimum Coded Unit) as defioned in the JPEG specification + ISO/IEC 10918-1 standard. + It is up to the application to transform these YCbCr blocks to RGB data that can be display. + + Respectively, for Encoding operation the JPEG peripheral input should be organized + in YCbCr MCU blocks. It is up to the application to perform the necessary RGB to YCbCr + MCU blocks transformation before feeding the JPEG peripheral with data. + + (#) Use functions HAL_JPEG_Encode and HAL_JPEG_Decode to start respectively + a JPEG encoding/decoding operation in polling method (blocking). + + (#) Use functions HAL_JPEG_Encode_IT and HAL_JPEG_Decode_IT to start respectively + a JPEG encoding/decoding operation with Interrupt method (not blocking). + + (#) Use functions HAL_JPEG_Encode_DMA and HAL_JPEG_Decode_DMA to start respectively + a JPEG encoding/decoding operation with DMA method (not blocking). + + (#) Callback HAL_JPEG_InfoReadyCallback is asserted if the current operation + is a JPEG decoding to provide the application with JPEG image parameters. + This callback is asserted when the JPEG peripheral successfully parse the + JPEG header. + + (#) Callback HAL_JPEG_GetDataCallback is asserted for both encoding and decoding + operations to inform the application that the input buffer has been + consumed by the peripheral and to ask for a new data chunk if the operation + (encoding/decoding) has not been complete yet. + + (++) This CallBack should be implemented in the application side. It should + call the function HAL_JPEG_ConfigInputBuffer if new input data are available, + or call HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_INPUT + to inform the JPEG HAL driver that the ongoing operation shall pause waiting for the + application to provide a new input data chunk. + Once the application succeed getting new data and if the input has been paused, + the application can call the function HAL_JPEG_ConfigInputBuffer to set the new + input buffer and size, then resume the JPEG HAL input by calling new function HAL_JPEG_Resume. + If the application has ended feeding the HAL JPEG with input data (no more input data), the application + Should call the function HAL_JPEG_ConfigInputBuffer (within the callback HAL_JPEG_GetDataCallback) + with the parameter InDataLength set to zero. + + (++) The mechanism of HAL_JPEG_ConfigInputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows + to the application to provide the input data (for encoding or decoding) by chunks. + If the new input data chunk is not available (because data should be read from an input file + for example) the application can pause the JPEG input (using function HAL_JPEG_Pause) + Once the new input data chunk is available ( read from a file for example), the application + can call the function HAL_JPEG_ConfigInputBuffer to provide the HAL with the new chunk + then resume the JPEG HAL input by calling function HAL_JPEG_Resume. + + (++) The application can call functions HAL_JPEG_ConfigInputBuffer then HAL_JPEG_Resume. + any time (outside the HAL_JPEG_GetDataCallback) Once the new input chunk data available. + However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called + (if necessary) within the callback HAL_JPEG_GetDataCallback, i.e when the HAL JPEG has ended + Transferring the previous chunk buffer to the JPEG peripheral. + + (#) Callback HAL_JPEG_DataReadyCallback is asserted when the HAL JPEG driver + has filled the given output buffer with the given size. + + (++) This CallBack should be implemented in the application side. It should + call the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver + with the new output buffer location and size to be used to store next data chunk. + if the application is not ready to provide the output chunk location then it can + call the function HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_OUTPUT + to inform the JPEG HAL driver that it shall pause output data. Once the application + is ready to receive the new data chunk (output buffer location free or available) it should call + the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver + with the new output chunk buffer location and size, then call HAL_JPEG_Resume + to inform the HAL that it shall resume outputting data in the given output buffer. + + (++) The mechanism of HAL_JPEG_ConfigOutputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows + the application to receive data from the JPEG peripheral by chunks. when a chunk + is received, the application can pause the HAL JPEG output data to be able to process + these received data (YCbCr to RGB conversion in case of decoding or data storage in case + of encoding). + + (++) The application can call functions HAL_JPEG_ ConfigOutputBuffer then HAL_JPEG_Resume. + any time (outside the HAL_JPEG_DataReadyCallback) Once the output data buffer is free to use. + However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called + (if necessary) within the callback HAL_JPEG_ DataReadyCallback, i.e when the HAL JPEG has ended + Transferring the previous chunk buffer from the JPEG peripheral to the application. + + (#) Callback HAL_JPEG_EncodeCpltCallback is asserted when the HAL JPEG driver has + ended the current JPEG encoding operation, and all output data has been transmitted + to the application. + + (#) Callback HAL_JPEG_DecodeCpltCallback is asserted when the HAL JPEG driver has + ended the current JPEG decoding operation. and all output data has been transmitted + to the application. + + (#) Callback HAL_JPEG_ErrorCallback is asserted when an error occurred during + the current operation. the application can call the function HAL_JPEG_GetError() + to retrieve the error codes. + + (#) By default the HAL JPEG driver uses the default quantization tables + as provide in the JPEG specification (ISO/IEC 10918-1 standard) for encoding. + User can change these default tables if necessary using the function HAL_JPEG_SetUserQuantTables + Note that for decoding the quantization tables are automatically extracted from + the JPEG header. + + (#) To control JPEG state you can use the following function: HAL_JPEG_GetState() + + *** JPEG HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in JPEG HAL driver. + + (+) __HAL_JPEG_RESET_HANDLE_STATE : Reset JPEG handle state. + (+) __HAL_JPEG_ENABLE : Enable the JPEG peripheral. + (+) __HAL_JPEG_DISABLE : Disable the JPEG peripheral. + (+) __HAL_JPEG_GET_FLAG : Check the specified JPEG status flag. + (+) __HAL_JPEG_CLEAR_FLAG : Clear the specified JPEG status flag. + (+) __HAL_JPEG_ENABLE_IT : Enable the specified JPEG Interrupt. + (+) __HAL_JPEG_DISABLE_IT : Disable the specified JPEG Interrupt. + (+) __HAL_JPEG_GET_IT_SOURCE : returns the state of the specified JPEG Interrupt (Enabled or disabled). + + *** Callback registration *** + ============================================= + + The compilation define USE_HAL_JPEG_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_JPEG_RegisterCallback() or HAL_JPEG_RegisterXXXCallback() + to register an interrupt callback. + + Function HAL_JPEG_RegisterCallback() allows to register following callbacks: + (+) EncodeCpltCallback : callback for end of encoding operation. + (+) DecodeCpltCallback : callback for end of decoding operation. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : JPEG MspInit. + (+) MspDeInitCallback : JPEG MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + For specific callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated + register callbacks : respectively HAL_JPEG_RegisterInfoReadyCallback(), + HAL_JPEG_RegisterGetDataCallback() and HAL_JPEG_RegisterDataReadyCallback(). + + Use function HAL_JPEG_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_JPEG_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) EncodeCpltCallback : callback for end of encoding operation. + (+) DecodeCpltCallback : callback for end of decoding operation. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : JPEG MspInit. + (+) MspDeInitCallback : JPEG MspDeInit. + + For callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated + unregister callbacks : respectively HAL_JPEG_UnRegisterInfoReadyCallback(), + HAL_JPEG_UnRegisterGetDataCallback() and HAL_JPEG_UnRegisterDataReadyCallback(). + + By default, after the HAL_JPEG_Init() and when the state is HAL_JPEG_STATE_RESET + all callbacks are set to the corresponding weak functions : + examples HAL_JPEG_DecodeCpltCallback() , HAL_JPEG_GetDataCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the HAL_JPEG_Init()/ HAL_JPEG_DeInit() only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the HAL_JPEG_Init() / HAL_JPEG_DeInit() + keep and use the user MspInit/MspDeInit functions (registered beforehand) + + Callbacks can be registered/unregistered in HAL_JPEG_STATE_READY state only. + Exception done MspInit/MspDeInit callbacks that can be registered/unregistered + in HAL_JPEG_STATE_READY or HAL_JPEG_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_JPEG_RegisterCallback() before calling HAL_JPEG_DeInit() + or HAL_JPEG_Init() function. + + When The compilation define USE_HAL_JPEG_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_JPEG_MODULE_ENABLED + +#if defined (JPEG) + +/** @defgroup JPEG JPEG + * @brief JPEG HAL module driver. + * @{ + */ + +/* Private define ------------------------------------------------------------*/ +/** @addtogroup JPEG_Private_Constants + * @{ + */ +#define JPEG_TIMEOUT_VALUE ((uint32_t)1000) /* 1s */ +#define JPEG_AC_HUFF_TABLE_SIZE ((uint32_t)162) /* Huffman AC table size : 162 codes*/ +#define JPEG_DC_HUFF_TABLE_SIZE ((uint32_t)12) /* Huffman DC table size : 12 codes*/ + +#define JPEG_QUANTVAL_MAX ((uint32_t)255) /* Quantization values are 8-bit numbers*/ +#define JPEG_LOW_QUALITY_REFERENCE ((uint32_t)5000) /*Reference value to generate scaling factor + for low quality factors (<50) */ +#define JPEG_HIGH_QUALITY_REFERENCE ((uint32_t)200) /*Reference value to generate scaling factor + for high quality factors (>=50)*/ + +#define JPEG_FIFO_SIZE ((uint32_t)16U) /* JPEG Input/Output HW FIFO size in words*/ + +#define JPEG_FIFO_TH_SIZE ((uint32_t)4U) /* JPEG Input/Output HW FIFO Threshold in words*/ + +#define JPEG_DMA_MASK ((uint32_t)0x00001800) /* JPEG DMA request Mask*/ +#define JPEG_DMA_IDMA ((uint32_t)JPEG_CR_IDMAEN) /* DMA request for the input FIFO */ +#define JPEG_DMA_ODMA ((uint32_t)JPEG_CR_ODMAEN) /* DMA request for the output FIFO */ + +#define JPEG_INTERRUPT_MASK ((uint32_t)0x0000007EU) /* JPEG Interrupt Mask*/ + +#define JPEG_CONTEXT_ENCODE ((uint32_t)0x00000001) /* JPEG context : operation is encoding*/ +#define JPEG_CONTEXT_DECODE ((uint32_t)0x00000002) /* JPEG context : operation is decoding*/ +#define JPEG_CONTEXT_OPERATION_MASK ((uint32_t)0x00000003) /* JPEG context : operation Mask */ + +#define JPEG_CONTEXT_POLLING ((uint32_t)0x00000004) /* JPEG context : Transfer use Polling */ +#define JPEG_CONTEXT_IT ((uint32_t)0x00000008) /* JPEG context : Transfer use Interrupt */ +#define JPEG_CONTEXT_DMA ((uint32_t)0x0000000C) /* JPEG context : Transfer use DMA */ +#define JPEG_CONTEXT_METHOD_MASK ((uint32_t)0x0000000C) /* JPEG context : Transfer Mask */ + + +#define JPEG_CONTEXT_CONF_ENCODING ((uint32_t)0x00000100) /* JPEG context : encoding config done */ + +#define JPEG_CONTEXT_PAUSE_INPUT ((uint32_t)0x00001000) /* JPEG context : Pause Input */ +#define JPEG_CONTEXT_PAUSE_OUTPUT ((uint32_t)0x00002000) /* JPEG context : Pause Output */ + +#define JPEG_CONTEXT_CUSTOM_TABLES ((uint32_t)0x00004000) /* JPEG context : Use custom quantization tables */ + +#define JPEG_CONTEXT_ENDING_DMA ((uint32_t)0x00008000) /* JPEG context : ending with DMA in progress */ + +#define JPEG_PROCESS_ONGOING ((uint32_t)0x00000000) /* Process is on going */ +#define JPEG_PROCESS_DONE ((uint32_t)0x00000001) /* Process is done (ends) */ +#define JPEG_GET_DMA_REMAIN_DATA(__HANDLE__) (__HAL_DMA_GET_COUNTER(__HANDLE__)\ + + HAL_DMAEx_GetFifoLevel(__HANDLE__)) +/** + * @} + */ + +/* Private typedef -----------------------------------------------------------*/ +/** @addtogroup JPEG_Private_Types + * @{ + */ + +/* + JPEG Huffman Table Structure definition : + This implementation of Huffman table structure is compliant with ISO/IEC 10918-1 standard, + Annex C Huffman Table specification + */ +typedef struct +{ + /* These two fields directly represent the contents of a JPEG DHT marker */ + uint8_t Bits[16]; /*!< bits[k] = # of symbols with codes of length k bits, + this parameter corresponds to BITS list in the Annex C */ + + uint8_t HuffVal[162]; /*!< The symbols, in order of incremented code length, + this parameter corresponds to HUFFVAL list in the Annex C */ + + +} JPEG_ACHuffTableTypeDef; + +typedef struct +{ + /* These two fields directly represent the contents of a JPEG DHT marker */ + uint8_t Bits[16]; /*!< bits[k] = # of symbols with codes of length k bits, + this parameter corresponds to BITS list in the Annex C */ + + uint8_t HuffVal[12]; /*!< The symbols, in order of incremented code length, + this parameter corresponds to HUFFVAL list in the Annex C */ + + +} JPEG_DCHuffTableTypeDef; + +typedef struct +{ + uint8_t CodeLength[JPEG_AC_HUFF_TABLE_SIZE]; /*!< Code length */ + + uint32_t HuffmanCode[JPEG_AC_HUFF_TABLE_SIZE]; /*!< HuffmanCode */ + +} JPEG_AC_HuffCodeTableTypeDef; + +typedef struct +{ + uint8_t CodeLength[JPEG_DC_HUFF_TABLE_SIZE]; /*!< Code length */ + + uint32_t HuffmanCode[JPEG_DC_HUFF_TABLE_SIZE]; /*!< HuffmanCode */ + +} JPEG_DC_HuffCodeTableTypeDef; +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/** @addtogroup JPEG_Private_Macros + * @{ + */ +#define JPEG_ENABLE_DMA(__HANDLE__,__DMA__) ((__HANDLE__)->Instance->CR |= ((__DMA__) & JPEG_DMA_MASK)) +/*note : To disable a DMA request we must use MODIFY_REG macro to avoid writing "1" to the FIFO flush bits + located in the same DMA request enable register (CR register). */ +#define JPEG_DISABLE_DMA(__HANDLE__,__DMA__) MODIFY_REG((__HANDLE__)->Instance->CR, ((__DMA__) & JPEG_DMA_MASK), 0UL) +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup JPEG_Private_Variables + * @{ + */ + +/* The following Huffman tables, are based on the JPEG standard as defined by the ITU-T Recommendation T.81. */ +static const JPEG_DCHuffTableTypeDef JPEG_DCLUM_HuffTable = +{ + { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, /*Bits*/ + + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb } /*HUFFVAL */ + +}; + +static const JPEG_DCHuffTableTypeDef JPEG_DCCHROM_HuffTable = +{ + { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }, /*Bits*/ + + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb } /*HUFFVAL */ +}; + +static const JPEG_ACHuffTableTypeDef JPEG_ACLUM_HuffTable = +{ + { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }, /*Bits*/ + + { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, /*HUFFVAL */ + 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, + 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, + 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, + 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa + } +}; + +static const JPEG_ACHuffTableTypeDef JPEG_ACCHROM_HuffTable = +{ + { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }, /*Bits*/ + + { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, /*HUFFVAL */ + 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, + 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, + 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, + 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, + 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, + 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa + } +}; + +static const uint8_t JPEG_ZIGZAG_ORDER[JPEG_QUANT_TABLE_SIZE] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63 +}; +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup JPEG_Private_Functions_Prototypes + * @{ + */ + +static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(const uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode, + uint32_t *LastK); +static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable, + JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable); +static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable, + JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable); +static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC, + const __IO uint32_t *DCTableAddress); +static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC, + const __IO uint32_t *ACTableAddress); +static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg); +static void JPEG_Set_Huff_DHTMem(const JPEG_HandleTypeDef *hjpeg); +static uint32_t JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef *hjpeg, const uint8_t *QTable, + __IO uint32_t *QTableAddress); +static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg); +static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg); +static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg); + +static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg); +static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg); +static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords); +static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords); +static uint32_t JPEG_GetQuality(const JPEG_HandleTypeDef *hjpeg); + +static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg); +static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg); +static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg); +static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg); +static void JPEG_DMAOutCpltCallback(DMA_HandleTypeDef *hdma); +static void JPEG_DMAInCpltCallback(DMA_HandleTypeDef *hdma); +static void JPEG_DMAErrorCallback(DMA_HandleTypeDef *hdma); +static void JPEG_DMAOutAbortCallback(DMA_HandleTypeDef *hdma) ; + +/** + * @} + */ + +/** @defgroup JPEG_Exported_Functions JPEG Exported Functions + * @{ + */ + +/** @defgroup JPEG_Exported_Functions_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 JPEG peripheral and creates the associated handle + (+) DeInitialize the JPEG peripheral + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the JPEG according to the specified + * parameters in the JPEG_InitTypeDef and creates the associated handle. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Init(JPEG_HandleTypeDef *hjpeg) +{ + /* These are the sample quantization tables given in JPEG spec ISO/IEC 10918-1 standard , section K.1. */ + static const uint8_t JPEG_LUM_QuantTable[JPEG_QUANT_TABLE_SIZE] = + { + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, + 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, + 72, 92, 95, 98, 112, 100, 103, 99 + }; + static const uint8_t JPEG_CHROM_QuantTable[JPEG_QUANT_TABLE_SIZE] = + { + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99 + }; + + /* Check the JPEG handle allocation */ + if (hjpeg == NULL) + { + return HAL_ERROR; + } + +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + if (hjpeg->State == HAL_JPEG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hjpeg->Lock = HAL_UNLOCKED; + + hjpeg->InfoReadyCallback = HAL_JPEG_InfoReadyCallback; /* Legacy weak InfoReadyCallback */ + hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback */ + hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback */ + hjpeg->ErrorCallback = HAL_JPEG_ErrorCallback; /* Legacy weak ErrorCallback */ + hjpeg->GetDataCallback = HAL_JPEG_GetDataCallback; /* Legacy weak GetDataCallback */ + hjpeg->DataReadyCallback = HAL_JPEG_DataReadyCallback; /* Legacy weak DataReadyCallback */ + + if (hjpeg->MspInitCallback == NULL) + { + hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hjpeg->MspInitCallback(hjpeg); + } +#else + if (hjpeg->State == HAL_JPEG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hjpeg->Lock = HAL_UNLOCKED; + + /* Init the low level hardware : GPIO, CLOCK */ + HAL_JPEG_MspInit(hjpeg); + } +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_BUSY; + + /* Start the JPEG Core*/ + __HAL_JPEG_ENABLE(hjpeg); + + /* Stop the JPEG encoding/decoding process*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + /* Disable All Interrupts */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + /* Disable All DMA requests */ + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); + + /* Flush input and output FIFOs*/ + hjpeg->Instance->CR |= JPEG_CR_IFF; + hjpeg->Instance->CR |= JPEG_CR_OFF; + + /* Clear all flags */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); + + /* init default quantization tables*/ + hjpeg->QuantTable0 = (uint8_t *)((uint32_t)JPEG_LUM_QuantTable); + hjpeg->QuantTable1 = (uint8_t *)((uint32_t)JPEG_CHROM_QuantTable); + hjpeg->QuantTable2 = NULL; + hjpeg->QuantTable3 = NULL; + + /* init the default Huffman tables*/ + if (JPEG_Set_HuffEnc_Mem(hjpeg) != HAL_OK) + { + hjpeg->ErrorCode = HAL_JPEG_ERROR_HUFF_TABLE; + + return HAL_ERROR; + } + + /* Enable header processing*/ + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR; + + /* Reset JpegInCount and JpegOutCount */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /* Reset the JPEG ErrorCode */ + hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE; + + /* Clear the context fields */ + hjpeg->Context = 0; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the JPEG peripheral. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_DeInit(JPEG_HandleTypeDef *hjpeg) +{ + /* Check the JPEG handle allocation */ + if (hjpeg == NULL) + { + return HAL_ERROR; + } + +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + if (hjpeg->MspDeInitCallback == NULL) + { + hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hjpeg->MspDeInitCallback(hjpeg); + +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_JPEG_MspDeInit(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_BUSY; + + /* Reset the JPEG ErrorCode */ + hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE; + + /* Reset JpegInCount and JpegOutCount */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_RESET; + + /*Clear the context fields*/ + hjpeg->Context = 0; + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the JPEG MSP. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +__weak void HAL_JPEG_MspInit(JPEG_HandleTypeDef *hjpeg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes JPEG MSP. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +__weak void HAL_JPEG_MspDeInit(JPEG_HandleTypeDef *hjpeg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User JPEG Callback + * To be used to override the weak predefined callback + * @param hjpeg JPEG handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID + * @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID + * @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID + * @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_RegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID, + pJPEG_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + switch (CallbackID) + { + case HAL_JPEG_ENCODE_CPLT_CB_ID : + hjpeg->EncodeCpltCallback = pCallback; + break; + + case HAL_JPEG_DECODE_CPLT_CB_ID : + hjpeg->DecodeCpltCallback = pCallback; + break; + + case HAL_JPEG_ERROR_CB_ID : + hjpeg->ErrorCallback = pCallback; + break; + + case HAL_JPEG_MSPINIT_CB_ID : + hjpeg->MspInitCallback = pCallback; + break; + + case HAL_JPEG_MSPDEINIT_CB_ID : + hjpeg->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_JPEG_STATE_RESET == hjpeg->State) + { + switch (CallbackID) + { + case HAL_JPEG_MSPINIT_CB_ID : + hjpeg->MspInitCallback = pCallback; + break; + + case HAL_JPEG_MSPDEINIT_CB_ID : + hjpeg->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief Unregister a JPEG Callback + * JPEG callback is redirected to the weak predefined callback + * @param hjpeg JPEG handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID + * @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID + * @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID + * @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_UnRegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + switch (CallbackID) + { + case HAL_JPEG_ENCODE_CPLT_CB_ID : + hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback */ + break; + + case HAL_JPEG_DECODE_CPLT_CB_ID : + hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback */ + break; + + case HAL_JPEG_ERROR_CB_ID : + hjpeg->ErrorCallback = HAL_JPEG_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_JPEG_MSPINIT_CB_ID : + hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_JPEG_MSPDEINIT_CB_ID : + hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_JPEG_STATE_RESET == hjpeg->State) + { + switch (CallbackID) + { + case HAL_JPEG_MSPINIT_CB_ID : + hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_JPEG_MSPDEINIT_CB_ID : + hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspInit */ + break; + + default : + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief Register Info Ready JPEG Callback + * To be used instead of the weak HAL_JPEG_InfoReadyCallback() predefined callback + * @param hjpeg JPEG handle + * @param pCallback pointer to the Info Ready Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_RegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg, + pJPEG_InfoReadyCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + hjpeg->InfoReadyCallback = pCallback; + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief UnRegister the Info Ready JPEG Callback + * Info Ready JPEG Callback is redirected to the weak HAL_JPEG_InfoReadyCallback() predefined callback + * @param hjpeg JPEG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_UnRegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + hjpeg->InfoReadyCallback = HAL_JPEG_InfoReadyCallback; /* Legacy weak InfoReadyCallback */ + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief Register Get Data JPEG Callback + * To be used instead of the weak HAL_JPEG_GetDataCallback() predefined callback + * @param hjpeg JPEG handle + * @param pCallback pointer to the Get Data Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_RegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg, pJPEG_GetDataCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + hjpeg->GetDataCallback = pCallback; + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief UnRegister the Get Data JPEG Callback + * Get Data JPEG Callback is redirected to the weak HAL_JPEG_GetDataCallback() predefined callback + * @param hjpeg JPEG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_UnRegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + hjpeg->GetDataCallback = HAL_JPEG_GetDataCallback; /* Legacy weak GetDataCallback */ + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief Register Data Ready JPEG Callback + * To be used instead of the weak HAL_JPEG_DataReadyCallback() predefined callback + * @param hjpeg JPEG handle + * @param pCallback pointer to the Get Data Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_RegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg, + pJPEG_DataReadyCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + hjpeg->DataReadyCallback = pCallback; + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +/** + * @brief UnRegister the Data Ready JPEG Callback + * Get Data Ready Callback is redirected to the weak HAL_JPEG_DataReadyCallback() predefined callback + * @param hjpeg JPEG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_UnRegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (HAL_JPEG_STATE_READY == hjpeg->State) + { + hjpeg->DataReadyCallback = HAL_JPEG_DataReadyCallback; /* Legacy weak DataReadyCallback */ + } + else + { + /* Update the error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hjpeg); + return status; +} + +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup JPEG_Exported_Functions_Group2 Configuration functions + * @brief JPEG Configuration functions. + * +@verbatim + ============================================================================== + ##### Configuration functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) HAL_JPEG_ConfigEncoding() : JPEG encoding configuration + (+) HAL_JPEG_GetInfo() : Extract the image configuration from the JPEG header during the decoding + (+) HAL_JPEG_EnableHeaderParsing() : Enable JPEG Header parsing for decoding + (+) HAL_JPEG_DisableHeaderParsing() : Disable JPEG Header parsing for decoding + (+) HAL_JPEG_SetUserQuantTables : Modify the default Quantization tables used for JPEG encoding. + +@endverbatim + * @{ + */ + +/** + * @brief Set the JPEG encoding configuration. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pConf pointer to a JPEG_ConfTypeDef structure that contains + * the encoding configuration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_ConfigEncoding(JPEG_HandleTypeDef *hjpeg, const JPEG_ConfTypeDef *pConf) +{ + uint32_t error; + uint32_t numberMCU; + uint32_t hfactor; + uint32_t vfactor; + uint32_t hMCU; + uint32_t vMCU; + + /* Check the JPEG handle allocation */ + if ((hjpeg == NULL) || (pConf == NULL)) + { + return HAL_ERROR; + } + else + { + /* Check the parameters */ + assert_param(IS_JPEG_COLORSPACE(pConf->ColorSpace)); + assert_param(IS_JPEG_CHROMASUBSAMPLING(pConf->ChromaSubsampling)); + assert_param(IS_JPEG_IMAGE_QUALITY(pConf->ImageQuality)); + + /* Process Locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + hjpeg->State = HAL_JPEG_STATE_BUSY; + + hjpeg->Conf.ColorSpace = pConf->ColorSpace; + hjpeg->Conf.ChromaSubsampling = pConf->ChromaSubsampling; + hjpeg->Conf.ImageHeight = pConf->ImageHeight; + hjpeg->Conf.ImageWidth = pConf->ImageWidth; + hjpeg->Conf.ImageQuality = pConf->ImageQuality; + + /* Reset the Color Space : by default only one quantization table is used*/ + hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_COLORSPACE; + + /* Set Number of color components*/ + if (hjpeg->Conf.ColorSpace == JPEG_GRAYSCALE_COLORSPACE) + { + /*Gray Scale is only one component 8x8 blocks i.e 4:4:4*/ + hjpeg->Conf.ChromaSubsampling = JPEG_444_SUBSAMPLING; + + JPEG_SetColorGrayScale(hjpeg); + /* Set quantization table 0*/ + error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0)); + } + else if (hjpeg->Conf.ColorSpace == JPEG_YCBCR_COLORSPACE) + { + /* + Set the Color Space for YCbCr : 2 quantization tables are used + one for Luminance(Y) and one for both Chrominances (Cb & Cr) + */ + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_0; + + JPEG_SetColorYCBCR(hjpeg); + + /* Set quantization table 0*/ + error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0)); + /*By default quantization table 0 for component 0 and quantization table 1 for both components 1 and 2*/ + (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1)); + + if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL) + { + /*Use user customized quantization tables , 1 table per component*/ + /* use 3 quantization tables , one for each component*/ + hjpeg->Instance->CONFR1 &= (~JPEG_CONFR1_COLORSPACE); + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_1; + + (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2)); + + /*Use Quantization 1 table for component 1*/ + hjpeg->Instance->CONFR5 &= (~JPEG_CONFR5_QT); + hjpeg->Instance->CONFR5 |= JPEG_CONFR5_QT_0; + + /*Use Quantization 2 table for component 2*/ + hjpeg->Instance->CONFR6 &= (~JPEG_CONFR6_QT); + hjpeg->Instance->CONFR6 |= JPEG_CONFR6_QT_1; + } + } + else /* ColorSpace == JPEG_CMYK_COLORSPACE */ + { + JPEG_SetColorCMYK(hjpeg); + + /* Set quantization table 0*/ + error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0)); + /*By default quantization table 0 for All components*/ + + if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL) + { + /*Use user customized quantization tables , 1 table per component*/ + /* use 4 quantization tables , one for each component*/ + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE; + + (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1)); + (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2)); + (void) JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable3, (hjpeg->Instance->QMEM3)); + + /*Use Quantization 1 table for component 1*/ + hjpeg->Instance->CONFR5 |= JPEG_CONFR5_QT_0; + + /*Use Quantization 2 table for component 2*/ + hjpeg->Instance->CONFR6 |= JPEG_CONFR6_QT_1; + + /*Use Quantization 3 table for component 3*/ + hjpeg->Instance->CONFR7 |= JPEG_CONFR7_QT; + } + } + + if (error != 0UL) + { + hjpeg->ErrorCode = HAL_JPEG_ERROR_QUANT_TABLE; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Set the JPEG State to ready */ + hjpeg->State = HAL_JPEG_STATE_READY; + + return HAL_ERROR; + } + /* Set the image size*/ + /* set the number of lines*/ + MODIFY_REG(hjpeg->Instance->CONFR1, JPEG_CONFR1_YSIZE, ((hjpeg->Conf.ImageHeight & 0x0000FFFFUL) << 16)); + /* set the number of pixels per line*/ + MODIFY_REG(hjpeg->Instance->CONFR3, JPEG_CONFR3_XSIZE, ((hjpeg->Conf.ImageWidth & 0x0000FFFFUL) << 16)); + + + if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) /* 4:2:0*/ + { + hfactor = 16; + vfactor = 16; + } + else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) /* 4:2:2*/ + { + hfactor = 16; + vfactor = 8; + } + else /* Default is 8x8 MCU, 4:4:4*/ + { + hfactor = 8; + vfactor = 8; + } + + hMCU = (hjpeg->Conf.ImageWidth / hfactor); + if ((hjpeg->Conf.ImageWidth % hfactor) != 0UL) + { + hMCU++; /*+1 for horizontal incomplete MCU */ + } + + vMCU = (hjpeg->Conf.ImageHeight / vfactor); + if ((hjpeg->Conf.ImageHeight % vfactor) != 0UL) + { + vMCU++; /*+1 for vertical incomplete MCU */ + } + + numberMCU = (hMCU * vMCU) - 1UL; /* Bit Field JPEG_CONFR2_NMCU shall be set to NB_MCU - 1*/ + /* Set the number of MCU*/ + hjpeg->Instance->CONFR2 = (numberMCU & JPEG_CONFR2_NMCU); + + hjpeg->Context |= JPEG_CONTEXT_CONF_ENCODING; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Set the JPEG State to ready */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Return function status */ + return HAL_BUSY; + } + } +} + +/** + * @brief Extract the image configuration from the JPEG header during the decoding + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pInfo pointer to a JPEG_ConfTypeDef structure that contains + * The JPEG decoded header information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_GetInfo(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo) +{ + uint32_t yblockNb; + uint32_t cBblockNb; + uint32_t cRblockNb; + + /* Check the JPEG handle allocation */ + if ((hjpeg == NULL) || (pInfo == NULL)) + { + return HAL_ERROR; + } + + /*Read the conf parameters */ + if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF_1) + { + pInfo->ColorSpace = JPEG_YCBCR_COLORSPACE; + } + else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == 0UL) + { + pInfo->ColorSpace = JPEG_GRAYSCALE_COLORSPACE; + } + else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF) + { + pInfo->ColorSpace = JPEG_CMYK_COLORSPACE; + } + else + { + return HAL_ERROR; + } + + pInfo->ImageHeight = (hjpeg->Instance->CONFR1 & 0xFFFF0000UL) >> 16; + pInfo->ImageWidth = (hjpeg->Instance->CONFR3 & 0xFFFF0000UL) >> 16; + + if ((pInfo->ColorSpace == JPEG_YCBCR_COLORSPACE) || (pInfo->ColorSpace == JPEG_CMYK_COLORSPACE)) + { + yblockNb = (hjpeg->Instance->CONFR4 & JPEG_CONFR4_NB) >> 4; + cBblockNb = (hjpeg->Instance->CONFR5 & JPEG_CONFR5_NB) >> 4; + cRblockNb = (hjpeg->Instance->CONFR6 & JPEG_CONFR6_NB) >> 4; + + if ((yblockNb == 1UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL)) + { + pInfo->ChromaSubsampling = JPEG_422_SUBSAMPLING; /*16x8 block*/ + } + else if ((yblockNb == 0UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL)) + { + pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING; + } + else if ((yblockNb == 3UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL)) + { + pInfo->ChromaSubsampling = JPEG_420_SUBSAMPLING; + } + else /*Default is 4:4:4*/ + { + pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING; + } + } + else + { + pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING; + } + + pInfo->ImageQuality = JPEG_GetQuality(hjpeg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enable JPEG Header parsing for decoding + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for the JPEG. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_EnableHeaderParsing(JPEG_HandleTypeDef *hjpeg) +{ + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_BUSY; + + /* Enable header processing*/ + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR; + + /* Process unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + return HAL_OK; + } + else + { + /* Process unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } +} + +/** + * @brief Disable JPEG Header parsing for decoding + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for the JPEG. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_DisableHeaderParsing(JPEG_HandleTypeDef *hjpeg) +{ + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_BUSY; + + /* Disable header processing*/ + hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_HDR; + + /* Process unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + return HAL_OK; + } + else + { + /* Process unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } +} + +/** + * @brief Modify the default Quantization tables used for JPEG encoding. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param QTable0 pointer to uint8_t , define the user quantification table for color component 1. + * If NULL assume no need to update the table and no error return + * @param QTable1 pointer to uint8_t , define the user quantification table for color component 2. + * If NULL assume no need to update the table and no error return. + * @param QTable2 pointer to uint8_t , define the user quantification table for color component 3, + * If NULL assume no need to update the table and no error return. + * @param QTable3 pointer to uint8_t , define the user quantification table for color component 4. + * If NULL assume no need to update the table and no error return. + * + * @retval HAL status + */ + + +HAL_StatusTypeDef HAL_JPEG_SetUserQuantTables(JPEG_HandleTypeDef *hjpeg, uint8_t *QTable0, uint8_t *QTable1, + uint8_t *QTable2, uint8_t *QTable3) +{ + /* Process Locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + /* Change the DMA state */ + hjpeg->State = HAL_JPEG_STATE_BUSY; + + hjpeg->Context |= JPEG_CONTEXT_CUSTOM_TABLES; + + hjpeg->QuantTable0 = QTable0; + hjpeg->QuantTable1 = QTable1; + hjpeg->QuantTable2 = QTable2; + hjpeg->QuantTable3 = QTable3; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Change the DMA state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup JPEG_Exported_Functions_Group3 encoding/decoding processing functions + * @brief processing functions. + * +@verbatim + ============================================================================== + ##### JPEG processing functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) HAL_JPEG_Encode() : JPEG encoding with polling process + (+) HAL_JPEG_Decode() : JPEG decoding with polling process + (+) HAL_JPEG_Encode_IT() : JPEG encoding with interrupt process + (+) HAL_JPEG_Decode_IT() : JPEG decoding with interrupt process + (+) HAL_JPEG_Encode_DMA() : JPEG encoding with DMA process + (+) HAL_JPEG_Decode_DMA() : JPEG decoding with DMA process + (+) HAL_JPEG_Pause() : Pause the Input/Output processing + (+) HAL_JPEG_Resume() : Resume the JPEG Input/Output processing + (+) HAL_JPEG_ConfigInputBuffer() : Config Encoding/Decoding Input Buffer + (+) HAL_JPEG_ConfigOutputBuffer() : Config Encoding/Decoding Output Buffer + (+) HAL_JPEG_Abort() : Aborts the JPEG Encoding/Decoding + +@endverbatim + * @{ + */ + +/** + * @brief Starts JPEG encoding with polling processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataInMCU Pointer to the Input buffer + * @param InDataLength size in bytes Input buffer + * @param pDataOut Pointer to the jpeg output data buffer + * @param OutDataLength size in bytes of the Output buffer + * @param Timeout Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Encode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength, + uint8_t *pDataOut, uint32_t OutDataLength, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param((InDataLength >= 4UL)); + assert_param((OutDataLength >= 4UL)); + + /* Check In/out buffer allocation and size */ + if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL)) + { + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State != HAL_JPEG_STATE_READY) + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING) + { + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING; + + /*Set the Context to Encode with Polling*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); + hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_POLLING); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /*Store In/out buffers pointers and size*/ + hjpeg->pJpegInBuffPtr = pDataInMCU; + hjpeg->pJpegOutBuffPtr = pDataOut; + hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /* In Data length must be multiple + of 4 Bytes (1 word)*/ + hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /* Out Data length must be multiple + of 4 Bytes (1 word)*/ + + /*Reset In/out data counter */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Init decoding process*/ + JPEG_Init_Process(hjpeg); + + /*JPEG data processing : In/Out FIFO transfer*/ + while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING)) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) + { + + /* Update error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_READY; + + return HAL_TIMEOUT; + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_READY; + + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts JPEG decoding with polling processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataIn Pointer to the input data buffer + * @param InDataLength size in bytes Input buffer + * @param pDataOutMCU Pointer to the Output data buffer + * @param OutDataLength size in bytes of the Output buffer + * @param Timeout Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Decode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength, + uint8_t *pDataOutMCU, uint32_t OutDataLength, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param((InDataLength >= 4UL)); + assert_param((OutDataLength >= 4UL)); + + /* Check In/out buffer allocation and size */ + if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hjpeg); + + /* Get tick */ + tickstart = HAL_GetTick(); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING; + + /*Set the Context to Decode with Polling*/ + /*Set the Context to Encode with Polling*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); + hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_POLLING); + + /*Store In/out buffers pointers and size*/ + hjpeg->pJpegInBuffPtr = pDataIn; + hjpeg->pJpegOutBuffPtr = pDataOutMCU; + hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /*In Data length must be multiple + of 4 Bytes (1 word)*/ + hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple + of 4 Bytes (1 word)*/ + + /*Reset In/out data counter */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Init decoding process*/ + JPEG_Init_Process(hjpeg); + + /*JPEG data processing : In/Out FIFO transfer*/ + while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING)) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) + { + + /* Update error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_READY; + + return HAL_TIMEOUT; + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_READY; + + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts JPEG encoding with interrupt processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataInMCU Pointer to the Input buffer + * @param InDataLength size in bytes Input buffer + * @param pDataOut Pointer to the jpeg output data buffer + * @param OutDataLength size in bytes of the Output buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Encode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength, + uint8_t *pDataOut, uint32_t OutDataLength) +{ + /* Check the parameters */ + assert_param((InDataLength >= 4UL)); + assert_param((OutDataLength >= 4UL)); + + /* Check In/out buffer allocation and size */ + if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State != HAL_JPEG_STATE_READY) + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } + else + { + if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING) + { + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING; + + /*Set the Context to Encode with IT*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); + hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_IT); + + /*Store In/out buffers pointers and size*/ + hjpeg->pJpegInBuffPtr = pDataInMCU; + hjpeg->pJpegOutBuffPtr = pDataOut; + hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /*In Data length must be multiple + of 4 Bytes (1 word)*/ + hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple + of 4 Bytes (1 word)*/ + + /*Reset In/out data counter */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Init decoding process*/ + JPEG_Init_Process(hjpeg); + + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts JPEG decoding with interrupt processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataIn Pointer to the input data buffer + * @param InDataLength size in bytes Input buffer + * @param pDataOutMCU Pointer to the Output data buffer + * @param OutDataLength size in bytes of the Output buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Decode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength, + uint8_t *pDataOutMCU, uint32_t OutDataLength) +{ + /* Check the parameters */ + assert_param((InDataLength >= 4UL)); + assert_param((OutDataLength >= 4UL)); + + /* Check In/out buffer allocation and size */ + if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING; + + /*Set the Context to Decode with IT*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); + hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_IT); + + /*Store In/out buffers pointers and size*/ + hjpeg->pJpegInBuffPtr = pDataIn; + hjpeg->pJpegOutBuffPtr = pDataOutMCU; + hjpeg->InDataLength = InDataLength - (InDataLength % 4UL); /*In Data length must be multiple + of 4 Bytes (1 word)*/ + hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple + of 4 Bytes (1 word)*/ + + /*Reset In/out data counter */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Init decoding process*/ + JPEG_Init_Process(hjpeg); + + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts JPEG encoding with DMA processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataInMCU Pointer to the Input buffer + * @param InDataLength size in bytes Input buffer + * @param pDataOut Pointer to the jpeg output data buffer + * @param OutDataLength size in bytes of the Output buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Encode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength, + uint8_t *pDataOut, uint32_t OutDataLength) +{ + /* Check the parameters */ + assert_param((InDataLength >= 4UL)); + assert_param((OutDataLength >= 4UL)); + + /* Check In/out buffer allocation and size */ + if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State != HAL_JPEG_STATE_READY) + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } + else + { + if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING) + { + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING; + + /*Set the Context to Encode with DMA*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); + hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_DMA); + + /*Store In/out buffers pointers and size*/ + hjpeg->pJpegInBuffPtr = pDataInMCU; + hjpeg->pJpegOutBuffPtr = pDataOut; + hjpeg->InDataLength = InDataLength; + hjpeg->OutDataLength = OutDataLength; + + /*Reset In/out data counter */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Init decoding process*/ + JPEG_Init_Process(hjpeg); + + /* JPEG encoding process using DMA */ + if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK) + { + /* Update State */ + hjpeg->State = HAL_JPEG_STATE_ERROR; + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts JPEG decoding with DMA processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataIn Pointer to the input data buffer + * @param InDataLength size in bytes Input buffer + * @param pDataOutMCU Pointer to the Output data buffer + * @param OutDataLength size in bytes of the Output buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Decode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength, + uint8_t *pDataOutMCU, uint32_t OutDataLength) +{ + /* Check the parameters */ + assert_param((InDataLength >= 4UL)); + assert_param((OutDataLength >= 4UL)); + + /* Check In/out buffer allocation and size */ + if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hjpeg); + + if (hjpeg->State == HAL_JPEG_STATE_READY) + { + /*Change JPEG state*/ + hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING; + + /*Set the Context to Decode with DMA*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK); + hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_DMA); + + /*Store In/out buffers pointers and size*/ + hjpeg->pJpegInBuffPtr = pDataIn; + hjpeg->pJpegOutBuffPtr = pDataOutMCU; + hjpeg->InDataLength = InDataLength; + hjpeg->OutDataLength = OutDataLength; + + /*Reset In/out data counter */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Init decoding process*/ + JPEG_Init_Process(hjpeg); + + /* JPEG decoding process using DMA */ + if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK) + { + /* Update State */ + hjpeg->State = HAL_JPEG_STATE_ERROR; + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_BUSY; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Pause the JPEG Input/Output processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param XferSelection This parameter can be one of the following values : + * JPEG_PAUSE_RESUME_INPUT : Pause Input processing + * JPEG_PAUSE_RESUME_OUTPUT: Pause Output processing + * JPEG_PAUSE_RESUME_INPUT_OUTPUT: Pause Input and Output processing + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Pause(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection) +{ + uint32_t mask = 0; + + assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection)); + + if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) + { + if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) + { + hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT; + mask |= JPEG_DMA_IDMA; + } + if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) + { + hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT; + mask |= JPEG_DMA_ODMA; + } + JPEG_DISABLE_DMA(hjpeg, mask); + + } + else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) + { + + if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) + { + hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT; + mask |= (JPEG_IT_IFT | JPEG_IT_IFNF); + } + if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) + { + hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT; + mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC); + } + __HAL_JPEG_DISABLE_IT(hjpeg, mask); + + } + else + { + /* Nothing to do */ + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Resume the JPEG Input/Output processing + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param XferSelection This parameter can be one of the following values : + * JPEG_PAUSE_RESUME_INPUT : Resume Input processing + * JPEG_PAUSE_RESUME_OUTPUT: Resume Output processing + * JPEG_PAUSE_RESUME_INPUT_OUTPUT: Resume Input and Output processing + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Resume(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection) +{ + uint32_t mask = 0; + + assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection)); + + if ((hjpeg->Context & (JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT)) == 0UL) + { + /* if nothing paused to resume return error*/ + return HAL_ERROR; + } + + if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) + { + + if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) + { + hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT); + mask |= JPEG_DMA_IDMA; + + /*JPEG Input DMA transfer data number must be multiple of DMA buffer size + as the destination is a 32 bits register */ + hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL); + + if (hjpeg->InDataLength > 0UL) + { + /* Start DMA FIFO In transfer */ + if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR, + hjpeg->InDataLength) != HAL_OK) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + hjpeg->State = HAL_JPEG_STATE_ERROR; + return HAL_ERROR; + } + } + } + if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) + { + hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT); + + if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL) + { + JPEG_DMA_PollResidualData(hjpeg); + } + else + { + mask |= JPEG_DMA_ODMA; + + /* Start DMA FIFO Out transfer */ + if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr, + hjpeg->OutDataLength) != HAL_OK) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + hjpeg->State = HAL_JPEG_STATE_ERROR; + return HAL_ERROR; + } + } + + } + JPEG_ENABLE_DMA(hjpeg, mask); + + } + else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) + { + if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT) + { + hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT); + mask |= (JPEG_IT_IFT | JPEG_IT_IFNF); + } + if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT) + { + hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT); + mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC); + } + __HAL_JPEG_ENABLE_IT(hjpeg, mask); + + } + else + { + /* Nothing to do */ + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Config Encoding/Decoding Input Buffer. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module. + * @param pNewInputBuffer Pointer to the new input data buffer + * @param InDataLength Size in bytes of the new Input data buffer + * @retval HAL status + */ +void HAL_JPEG_ConfigInputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewInputBuffer, uint32_t InDataLength) +{ + hjpeg->pJpegInBuffPtr = pNewInputBuffer; + hjpeg->InDataLength = InDataLength; +} + +/** + * @brief Config Encoding/Decoding Output Buffer. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module. + * @param pNewOutputBuffer Pointer to the new output data buffer + * @param OutDataLength Size in bytes of the new Output data buffer + * @retval HAL status + */ +void HAL_JPEG_ConfigOutputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewOutputBuffer, uint32_t OutDataLength) +{ + hjpeg->pJpegOutBuffPtr = pNewOutputBuffer; + hjpeg->OutDataLength = OutDataLength; +} + +/** + * @brief Aborts the JPEG Encoding/Decoding. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_JPEG_Abort(JPEG_HandleTypeDef *hjpeg) +{ + uint32_t tickstart; + uint32_t tmpContext; + tmpContext = hjpeg->Context; + + /*Reset the Context operation and method*/ + hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA); + + if ((tmpContext & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) + { + /* Stop the DMA In/out Xfer*/ + if (HAL_DMA_Abort(hjpeg->hdmaout) != HAL_OK) + { + if (hjpeg->hdmaout->ErrorCode == HAL_DMA_ERROR_TIMEOUT) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + } + } + if (HAL_DMA_Abort(hjpeg->hdmain) != HAL_OK) + { + if (hjpeg->hdmain->ErrorCode == HAL_DMA_ERROR_TIMEOUT) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + } + } + + } + + /* Stop the JPEG encoding/decoding process*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Check if the JPEG Codec is effectively disabled */ + while (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_COF) != 0UL) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > JPEG_TIMEOUT_VALUE) + { + /* Update error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT; + + /* Change the DMA state */ + hjpeg->State = HAL_JPEG_STATE_ERROR; + break; + } + } + + /* Disable All Interrupts */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + /* Disable All DMA requests */ + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); + + /* Flush input and output FIFOs*/ + hjpeg->Instance->CR |= JPEG_CR_IFF; + hjpeg->Instance->CR |= JPEG_CR_OFF; + + /* Clear all flags */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); + + /* Reset JpegInCount and JpegOutCount */ + hjpeg->JpegInCount = 0; + hjpeg->JpegOutCount = 0; + + /*Reset the Context Pause*/ + hjpeg->Context &= ~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT); + + /* Change the DMA state*/ + if (hjpeg->ErrorCode != HAL_JPEG_ERROR_NONE) + { + hjpeg->State = HAL_JPEG_STATE_ERROR; + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + /* Return function status */ + return HAL_ERROR; + } + else + { + hjpeg->State = HAL_JPEG_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + /* Return function status */ + return HAL_OK; + } + +} + + +/** + * @} + */ + +/** @defgroup JPEG_Exported_Functions_Group4 JPEG Decode/Encode callback functions + * @brief JPEG process callback functions. + * +@verbatim + ============================================================================== + ##### JPEG Decode and Encode callback functions ##### + ============================================================================== + [..] This section provides callback functions: + (+) HAL_JPEG_InfoReadyCallback() : Decoding JPEG Info ready callback + (+) HAL_JPEG_EncodeCpltCallback() : Encoding complete callback. + (+) HAL_JPEG_DecodeCpltCallback() : Decoding complete callback. + (+) HAL_JPEG_ErrorCallback() : JPEG error callback. + (+) HAL_JPEG_GetDataCallback() : Get New Data chunk callback. + (+) HAL_JPEG_DataReadyCallback() : Decoded/Encoded Data ready callback. + +@endverbatim + * @{ + */ + +/** + * @brief Decoding JPEG Info ready callback. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pInfo pointer to a JPEG_ConfTypeDef structure that contains + * The JPEG decoded header information + * @retval None + */ +__weak void HAL_JPEG_InfoReadyCallback(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + UNUSED(pInfo); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_HeaderParsingCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Encoding complete callback. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +__weak void HAL_JPEG_EncodeCpltCallback(JPEG_HandleTypeDef *hjpeg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_EncodeCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Decoding complete callback. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +__weak void HAL_JPEG_DecodeCpltCallback(JPEG_HandleTypeDef *hjpeg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_EncodeCpltCallback could be implemented in the user file + */ +} + +/** + * @brief JPEG error callback. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +__weak void HAL_JPEG_ErrorCallback(JPEG_HandleTypeDef *hjpeg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Get New Data chunk callback. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param NbDecodedData Number of consumed data in the previous chunk in bytes + * @retval None + */ +__weak void HAL_JPEG_GetDataCallback(JPEG_HandleTypeDef *hjpeg, uint32_t NbDecodedData) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + UNUSED(NbDecodedData); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_GetDataCallback could be implemented in the user file + */ +} + +/** + * @brief Decoded/Encoded Data ready callback. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param pDataOut pointer to the output data buffer + * @param OutDataLength number in bytes of data available in the specified output buffer + * @retval None + */ +__weak void HAL_JPEG_DataReadyCallback(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataOut, uint32_t OutDataLength) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hjpeg); + UNUSED(pDataOut); + UNUSED(OutDataLength); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_JPEG_DataReadyCallback could be implemented in the user file + */ +} + +/** + * @} + */ + + +/** @defgroup JPEG_Exported_Functions_Group5 JPEG IRQ handler management + * @brief JPEG IRQ handler. + * +@verbatim + ============================================================================== + ##### JPEG IRQ handler management ##### + ============================================================================== + [..] This section provides JPEG IRQ handler function. + (+) HAL_JPEG_IRQHandler() : handles JPEG interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief This function handles JPEG interrupt request. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +void HAL_JPEG_IRQHandler(JPEG_HandleTypeDef *hjpeg) +{ + switch (hjpeg->State) + { + case HAL_JPEG_STATE_BUSY_ENCODING: + case HAL_JPEG_STATE_BUSY_DECODING: + /* continue JPEG data encoding/Decoding*/ + /* JPEG data processing : In/Out FIFO transfer*/ + if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) + { + (void) JPEG_Process(hjpeg); + } + else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) + { + JPEG_DMA_ContinueProcess(hjpeg); + } + else + { + /* Nothing to do */ + } + break; + + default: + break; + } +} + +/** + * @} + */ + +/** @defgroup JPEG_Exported_Functions_Group6 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + ============================================================================== + ##### Peripheral State and Error functions ##### + ============================================================================== + [..] This section provides JPEG State and Errors function. + (+) HAL_JPEG_GetState() : permits to get in run-time the JPEG state. + (+) HAL_JPEG_GetError() : Returns the JPEG error code if any. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the JPEG state. + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval JPEG state + */ +HAL_JPEG_STATETypeDef HAL_JPEG_GetState(const JPEG_HandleTypeDef *hjpeg) +{ + return hjpeg->State; +} + +/** + * @brief Return the JPEG error code + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for the specified JPEG. + * @retval JPEG Error Code + */ +uint32_t HAL_JPEG_GetError(const JPEG_HandleTypeDef *hjpeg) +{ + return hjpeg->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + + +/** @addtogroup JPEG_Private_Functions + * @{ + */ + +/** + * @brief Generates Huffman sizes/Codes Table from Bits/vals Table + * @param Bits pointer to bits table + * @param Huffsize pointer to sizes table + * @param Huffcode pointer to codes table + * @param LastK pointer to last Coeff (table dimension) + * @retval HAL status + */ +static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(const uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode, + uint32_t *LastK) +{ + uint32_t i; + uint32_t j; + uint32_t k; + uint32_t code; + uint32_t si; + + /* Figure C.1: Generation of table of Huffman code sizes */ + j = 0; + for (k = 0; k < 16UL; k++) + { + i = (uint32_t)Bits[k]; + if ((j + i) > 256UL) + { + /* check for table overflow */ + return HAL_ERROR; + } + while (i != 0UL) + { + Huffsize[j] = (uint8_t) k + 1U; + j++; + i--; + } + } + Huffsize[j] = 0; + *LastK = j; + + /* Figure C.2: Generation of table of Huffman codes */ + code = 0; + si = Huffsize[0]; + j = 0; + while (Huffsize[j] != 0U) + { + while (((uint32_t) Huffsize[j]) == si) + { + Huffcode[j] = code; + j++; + code++; + } + /* code must fit in "size" bits (si), no code is allowed to be all ones*/ + if (si > 31UL) + { + return HAL_ERROR; + } + if (((uint32_t) code) >= (((uint32_t) 1) << si)) + { + return HAL_ERROR; + } + code <<= 1; + si++; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Transform a Bits/Vals AC Huffman table to sizes/Codes huffman Table + * that can programmed to the JPEG encoder registers + * @param AC_BitsValsTable pointer to AC huffman bits/vals table + * @param AC_SizeCodesTable pointer to AC huffman Sizes/Codes table + * @retval HAL status + */ +static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable, + JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable) +{ + HAL_StatusTypeDef error; + uint8_t huffsize[257]; + uint32_t huffcode[257]; + uint32_t k; + uint32_t i; + uint32_t lsb; + uint32_t msb; + uint32_t lastK; + + error = JPEG_Bits_To_SizeCodes(AC_BitsValsTable->Bits, huffsize, huffcode, &lastK); + if (error != HAL_OK) + { + return error; + } + + /* Figure C.3: Ordering procedure for encoding procedure code tables */ + k = 0; + + while (k < lastK) + { + i = AC_BitsValsTable->HuffVal[k]; + if (i == 0UL) + { + i = JPEG_AC_HUFF_TABLE_SIZE - 2UL; /*i = 0x00 EOB code*/ + } + else if (i == 0xF0UL) /* i = 0xF0 ZRL code*/ + { + i = JPEG_AC_HUFF_TABLE_SIZE - 1UL; + } + else + { + msb = (i & 0xF0UL) >> 4; + lsb = (i & 0x0FUL); + i = (msb * 10UL) + lsb - 1UL; + } + if (i >= JPEG_AC_HUFF_TABLE_SIZE) + { + return HAL_ERROR; /* Huffman Table overflow error*/ + } + else + { + AC_SizeCodesTable->HuffmanCode[i] = huffcode[k]; + AC_SizeCodesTable->CodeLength[i] = huffsize[k] - 1U; + k++; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Transform a Bits/Vals DC Huffman table to sizes/Codes huffman Table + * that can programmed to the JPEG encoder registers + * @param DC_BitsValsTable pointer to DC huffman bits/vals table + * @param DC_SizeCodesTable pointer to DC huffman Sizes/Codes table + * @retval HAL status + */ +static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable, + JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable) +{ + HAL_StatusTypeDef error; + + uint32_t k; + uint32_t i; + uint32_t lastK; + uint8_t huffsize[257]; + uint32_t huffcode[257]; + error = JPEG_Bits_To_SizeCodes(DC_BitsValsTable->Bits, huffsize, huffcode, &lastK); + if (error != HAL_OK) + { + return error; + } + /* Figure C.3: ordering procedure for encoding procedure code tables */ + k = 0; + + while (k < lastK) + { + i = DC_BitsValsTable->HuffVal[k]; + if (i >= JPEG_DC_HUFF_TABLE_SIZE) + { + return HAL_ERROR; /* Huffman Table overflow error*/ + } + else + { + DC_SizeCodesTable->HuffmanCode[i] = huffcode[k]; + DC_SizeCodesTable->CodeLength[i] = huffsize[k] - 1U; + k++; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the JPEG register with an DC huffman table at the given DC table address + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param HuffTableDC pointer to DC huffman table + * @param DCTableAddress Encoder DC huffman table address it could be HUFFENC_DC0 or HUFFENC_DC1. + * @retval HAL status + */ +static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC, + const __IO uint32_t *DCTableAddress) +{ + HAL_StatusTypeDef error; + JPEG_DC_HuffCodeTableTypeDef dcSizeCodesTable; + uint32_t i; + uint32_t lsb; + uint32_t msb; + __IO uint32_t *address; + __IO uint32_t *addressDef; + + if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC0)) + { + address = (hjpeg->Instance->HUFFENC_DC0 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL)); + } + else if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC1)) + { + address = (hjpeg->Instance->HUFFENC_DC1 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL)); + } + else + { + return HAL_ERROR; + } + + if (HuffTableDC != NULL) + { + error = JPEG_DCHuff_BitsVals_To_SizeCodes(HuffTableDC, &dcSizeCodesTable); + if (error != HAL_OK) + { + return error; + } + addressDef = address; + *addressDef = 0x0FFF0FFF; + addressDef++; + *addressDef = 0x0FFF0FFF; + + i = JPEG_DC_HUFF_TABLE_SIZE; + while (i > 1UL) + { + i--; + address --; + msb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | + ((uint32_t)dcSizeCodesTable.HuffmanCode[i] & 0xFFUL); + i--; + lsb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | + ((uint32_t)dcSizeCodesTable.HuffmanCode[i] & 0xFFUL); + + *address = lsb | (msb << 16); + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the JPEG register with an AC huffman table at the given AC table address + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param HuffTableAC pointer to AC huffman table + * @param ACTableAddress Encoder AC huffman table address it could be HUFFENC_AC0 or HUFFENC_AC1. + * @retval HAL status + */ +static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(const JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC, + const __IO uint32_t *ACTableAddress) +{ + HAL_StatusTypeDef error; + JPEG_AC_HuffCodeTableTypeDef acSizeCodesTable; + uint32_t i; + uint32_t lsb; + uint32_t msb; + __IO uint32_t *address; + __IO uint32_t *addressDef; + + if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC0)) + { + address = (hjpeg->Instance->HUFFENC_AC0 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL)); + } + else if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC1)) + { + address = (hjpeg->Instance->HUFFENC_AC1 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL)); + } + else + { + return HAL_ERROR; + } + + if (HuffTableAC != NULL) + { + error = JPEG_ACHuff_BitsVals_To_SizeCodes(HuffTableAC, &acSizeCodesTable); + if (error != HAL_OK) + { + return error; + } + /* Default values settings: 162:167 FFFh , 168:175 FD0h_FD7h */ + /* Locations 162:175 of each AC table contain information used internally by the core */ + + addressDef = address; + for (i = 0; i < 3UL; i++) + { + *addressDef = 0x0FFF0FFF; + addressDef++; + } + *addressDef = 0x0FD10FD0; + addressDef++; + *addressDef = 0x0FD30FD2; + addressDef++; + *addressDef = 0x0FD50FD4; + addressDef++; + *addressDef = 0x0FD70FD6; + /* end of Locations 162:175 */ + + + i = JPEG_AC_HUFF_TABLE_SIZE; + while (i > 1UL) + { + i--; + address--; + msb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | + ((uint32_t)acSizeCodesTable.HuffmanCode[i] & 0xFFUL); + i--; + lsb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | + ((uint32_t)acSizeCodesTable.HuffmanCode[i] & 0xFFUL); + + *address = lsb | (msb << 16); + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configure the JPEG encoder register huffman tables to used during + * the encdoing operation + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg) +{ + HAL_StatusTypeDef error; + + JPEG_Set_Huff_DHTMem(hjpeg); + error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable, + (hjpeg->Instance->HUFFENC_AC0)); + if (error != HAL_OK) + { + return error; + } + + error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable, + (hjpeg->Instance->HUFFENC_AC1)); + if (error != HAL_OK) + { + return error; + } + + error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable, + hjpeg->Instance->HUFFENC_DC0); + if (error != HAL_OK) + { + return error; + } + + error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable, + hjpeg->Instance->HUFFENC_DC1); + if (error != HAL_OK) + { + return error; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configure the JPEG register huffman tables to be included in the JPEG + * file header (used for encoding only) + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +static void JPEG_Set_Huff_DHTMem(const JPEG_HandleTypeDef *hjpeg) +{ + const JPEG_ACHuffTableTypeDef *HuffTableAC0 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable; + const JPEG_ACHuffTableTypeDef *HuffTableAC1 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable; + const JPEG_DCHuffTableTypeDef *HuffTableDC0 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable; + const JPEG_DCHuffTableTypeDef *HuffTableDC1 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable; + uint32_t value; + uint32_t index; + __IO uint32_t *address; + + /* DC0 Huffman Table : BITS*/ + /* DC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address to DHTMEM + 3*/ + address = (hjpeg->Instance->DHTMEM + 3); + index = 16; + while (index > 3UL) + { + + *address = (((uint32_t)HuffTableDC0->Bits[index - 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableDC0->Bits[index - 2UL] & 0xFFUL) << 16) | + (((uint32_t)HuffTableDC0->Bits[index - 3UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableDC0->Bits[index - 4UL] & 0xFFUL); + address--; + index -= 4UL; + + } + /* DC0 Huffman Table : Val*/ + /* DC0 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +4 to DHTMEM + 6 */ + address = (hjpeg->Instance->DHTMEM + 6); + index = 12; + while (index > 3UL) + { + *address = (((uint32_t)HuffTableDC0->HuffVal[index - 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableDC0->HuffVal[index - 2UL] & 0xFFUL) << 16) | + (((uint32_t)HuffTableDC0->HuffVal[index - 3UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableDC0->HuffVal[index - 4UL] & 0xFFUL); + address--; + index -= 4UL; + } + + /* AC0 Huffman Table : BITS*/ + /* AC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 7 to DHTMEM + 10*/ + address = (hjpeg->Instance->DHTMEM + 10UL); + index = 16; + while (index > 3UL) + { + + *address = (((uint32_t)HuffTableAC0->Bits[index - 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableAC0->Bits[index - 2UL] & 0xFFUL) << 16) | + (((uint32_t)HuffTableAC0->Bits[index - 3UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableAC0->Bits[index - 4UL] & 0xFFUL); + address--; + index -= 4UL; + + } + /* AC0 Huffman Table : Val*/ + /* AC0 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 11 to DHTMEM + 51 */ + /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 51) belong to AC0 VALS table */ + address = (hjpeg->Instance->DHTMEM + 51); + value = *address & 0xFFFF0000U; + value = value | (((uint32_t)HuffTableAC0->HuffVal[161] & 0xFFUL) << 8) | + ((uint32_t)HuffTableAC0->HuffVal[160] & 0xFFUL); + *address = value; + + /*continue setting 160 AC0 huffman values */ + address--; /* address = hjpeg->Instance->DHTMEM + 50*/ + index = JPEG_AC_HUFF_TABLE_SIZE - 2UL; + while (index > 3UL) + { + *address = (((uint32_t)HuffTableAC0->HuffVal[index - 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableAC0->HuffVal[index - 2UL] & 0xFFUL) << 16) | + (((uint32_t)HuffTableAC0->HuffVal[index - 3UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableAC0->HuffVal[index - 4UL] & 0xFFUL); + address--; + index -= 4UL; + } + + /* DC1 Huffman Table : BITS*/ + /* DC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM + 51 base address to DHTMEM + 55*/ + /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 51) belong to DC1 Bits table */ + address = (hjpeg->Instance->DHTMEM + 51); + value = *address & 0x0000FFFFU; + value = value | (((uint32_t)HuffTableDC1->Bits[1] & 0xFFUL) << 24) | + (((uint32_t)HuffTableDC1->Bits[0] & 0xFFUL) << 16); + *address = value; + + /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 55) belong to DC1 Bits table */ + address = (hjpeg->Instance->DHTMEM + 55); + value = *address & 0xFFFF0000U; + value = value | (((uint32_t)HuffTableDC1->Bits[15] & 0xFFUL) << 8) | + ((uint32_t)HuffTableDC1->Bits[14] & 0xFFUL); + *address = value; + + /*continue setting 12 DC1 huffman Bits from DHTMEM + 54 down to DHTMEM + 52*/ + address--; + index = 12; + while (index > 3UL) + { + + *address = (((uint32_t)HuffTableDC1->Bits[index + 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableDC1->Bits[index] & 0xFFUL) << 16) | + (((uint32_t)HuffTableDC1->Bits[index - 1UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableDC1->Bits[index - 2UL] & 0xFFUL); + address--; + index -= 4UL; + + } + /* DC1 Huffman Table : Val*/ + /* DC1 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +55 to DHTMEM + 58 */ + /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 55) belong to DC1 Val table */ + address = (hjpeg->Instance->DHTMEM + 55); + value = *address & 0x0000FFFFUL; + value = value | (((uint32_t)HuffTableDC1->HuffVal[1] & 0xFFUL) << 24) | + (((uint32_t)HuffTableDC1->HuffVal[0] & 0xFFUL) << 16); + *address = value; + + /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 58) belong to DC1 Val table */ + address = (hjpeg->Instance->DHTMEM + 58); + value = *address & 0xFFFF0000UL; + value = value | (((uint32_t)HuffTableDC1->HuffVal[11] & 0xFFUL) << 8) | + ((uint32_t)HuffTableDC1->HuffVal[10] & 0xFFUL); + *address = value; + + /*continue setting 8 DC1 huffman val from DHTMEM + 57 down to DHTMEM + 56*/ + address--; + index = 8; + while (index > 3UL) + { + *address = (((uint32_t)HuffTableDC1->HuffVal[index + 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableDC1->HuffVal[index] & 0xFFUL) << 16) | + (((uint32_t)HuffTableDC1->HuffVal[index - 1UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableDC1->HuffVal[index - 2UL] & 0xFFUL); + address--; + index -= 4UL; + } + + /* AC1 Huffman Table : BITS*/ + /* AC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 58 to DHTMEM + 62*/ + /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 58) belong to AC1 Bits table */ + address = (hjpeg->Instance->DHTMEM + 58); + value = *address & 0x0000FFFFU; + value = value | (((uint32_t)HuffTableAC1->Bits[1] & 0xFFUL) << 24) | + (((uint32_t)HuffTableAC1->Bits[0] & 0xFFUL) << 16); + *address = value; + + /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 62) belong to Bits Val table */ + address = (hjpeg->Instance->DHTMEM + 62); + value = *address & 0xFFFF0000U; + value = value | (((uint32_t)HuffTableAC1->Bits[15] & 0xFFUL) << 8) | ((uint32_t)HuffTableAC1->Bits[14] & 0xFFUL); + *address = value; + + /*continue setting 12 AC1 huffman Bits from DHTMEM + 61 down to DHTMEM + 59*/ + address--; + index = 12; + while (index > 3UL) + { + + *address = (((uint32_t)HuffTableAC1->Bits[index + 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableAC1->Bits[index] & 0xFFUL) << 16) | + (((uint32_t)HuffTableAC1->Bits[index - 1UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableAC1->Bits[index - 2UL] & 0xFFUL); + address--; + index -= 4UL; + + } + /* AC1 Huffman Table : Val*/ + /* AC1 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 62 to DHTMEM + 102 */ + /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 62) belong to AC1 VALS table */ + address = (hjpeg->Instance->DHTMEM + 62); + value = *address & 0x0000FFFFUL; + value = value | (((uint32_t)HuffTableAC1->HuffVal[1] & 0xFFUL) << 24) | + (((uint32_t)HuffTableAC1->HuffVal[0] & 0xFFUL) << 16); + *address = value; + + /*continue setting 160 AC1 huffman values from DHTMEM + 63 to DHTMEM+102 */ + address = (hjpeg->Instance->DHTMEM + 102); + index = JPEG_AC_HUFF_TABLE_SIZE - 2UL; + while (index > 3UL) + { + *address = (((uint32_t)HuffTableAC1->HuffVal[index + 1UL] & 0xFFUL) << 24) | + (((uint32_t)HuffTableAC1->HuffVal[index] & 0xFFUL) << 16) | + (((uint32_t)HuffTableAC1->HuffVal[index - 1UL] & 0xFFUL) << 8) | + ((uint32_t)HuffTableAC1->HuffVal[index - 2UL] & 0xFFUL); + address--; + index -= 4UL; + } + +} + +/** + * @brief Configure the JPEG registers with a given quantization table + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param QTable pointer to an array of 64 bytes giving the quantization table + * @param QTableAddress destination quantization address in the JPEG peripheral + * it could be QMEM0, QMEM1, QMEM2 or QMEM3 + * @retval 0 if no error, 1 if error + */ +static uint32_t JPEG_Set_Quantization_Mem(const JPEG_HandleTypeDef *hjpeg, const uint8_t *QTable, + __IO uint32_t *QTableAddress) +{ + uint32_t i; + uint32_t j; + uint32_t quantRow; + uint32_t quantVal; + uint32_t ScaleFactor; + __IO uint32_t *tableAddress; + + tableAddress = QTableAddress; + + if ((hjpeg->Conf.ImageQuality >= 50UL) && (hjpeg->Conf.ImageQuality <= 100UL)) + { + ScaleFactor = JPEG_HIGH_QUALITY_REFERENCE - (hjpeg->Conf.ImageQuality * 2UL); + } + else if (hjpeg->Conf.ImageQuality > 0UL) + { + ScaleFactor = JPEG_LOW_QUALITY_REFERENCE / ((uint32_t) hjpeg->Conf.ImageQuality); + } + else + { + return 1UL; + } + + /*Quantization_table = (Standard_quanization_table * ScaleFactor + 50) / 100*/ + i = 0; + while (i < (JPEG_QUANT_TABLE_SIZE - 3UL)) + { + quantRow = 0; + for (j = 0; j < 4UL; j++) + { + /* Note that the quantization coefficients must be specified in the table in zigzag order */ + quantVal = ((((uint32_t) QTable[JPEG_ZIGZAG_ORDER[i + j]]) * ScaleFactor) + 50UL) / 100UL; + + if (quantVal == 0UL) + { + quantVal = 1UL; + } + else if (quantVal > 255UL) + { + quantVal = JPEG_QUANTVAL_MAX; + } + else + { + /* Nothing to do, keep same value of quantVal */ + } + + quantRow |= ((quantVal & 0xFFUL) << (8UL * j)); + } + + i += 4UL; + *tableAddress = quantRow; + tableAddress ++; + } + + /* Return function status */ + return 0UL; +} + +/** + * @brief Configure the JPEG registers for YCbCr color space + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg) +{ + uint32_t ySamplingH; + uint32_t ySamplingV; + uint32_t yblockNb; + + /*Set Number of color components to 3*/ + hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_NF; + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_NF_1; + + /* compute MCU block size and Y, Cb ,Cr sampling factors*/ + if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) + { + ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ + ySamplingV = JPEG_CONFR4_VSF_1; /* Vs = 2*/ + + yblockNb = 0x30; /* 4 blocks of 8x8*/ + } + else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) + { + ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ + ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ + + yblockNb = 0x10; /* 2 blocks of 8x8*/ + } + else /*JPEG_444_SUBSAMPLING and default*/ + { + ySamplingH = JPEG_CONFR4_HSF_0; /* Hs = 1*/ + ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ + + yblockNb = 0; /* 1 block of 8x8*/ + } + + hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS); + hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF_1 | JPEG_CONFR1_NS_1); + + /*Reset CONFR4 register*/ + hjpeg->Instance->CONFR4 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 0*/ + hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB)); + + /*Reset CONFR5 register*/ + hjpeg->Instance->CONFR5 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 1*/ + hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0 | JPEG_CONFR5_QT_0 | JPEG_CONFR5_HA | + JPEG_CONFR5_HD); + + /*Reset CONFR6 register*/ + hjpeg->Instance->CONFR6 = 0; + /*Set Horizental and Vertical sampling factor and number of blocks for component 2*/ + /* In YCBCR , by default, both chrominance components (component 1 and component 2) + use the same Quantization table (table 1) */ + /* In YCBCR , both chrominance components (component 1 and component 2) use the same Huffman tables (table 1) */ + hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0 | JPEG_CONFR6_QT_0 | JPEG_CONFR6_HA | + JPEG_CONFR6_HD); + +} + +/** + * @brief Configure the JPEG registers for GrayScale color space + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg) +{ + /*Set Number of color components to 1*/ + hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS); + + /*in GrayScale use 1 single Quantization table (Table 0)*/ + /*in GrayScale use only one couple of AC/DC huffman table (table 0)*/ + + /*Reset CONFR4 register*/ + hjpeg->Instance->CONFR4 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 0*/ + hjpeg->Instance->CONFR4 |= JPEG_CONFR4_HSF_0 | JPEG_CONFR4_VSF_0 ; +} + +/** + * @brief Configure the JPEG registers for CMYK color space + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg) +{ + uint32_t ySamplingH; + uint32_t ySamplingV; + uint32_t yblockNb; + + /*Set Number of color components to 4*/ + hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF | JPEG_CONFR1_NS); + + /* compute MCU block size and Y, Cb ,Cr sampling factors*/ + if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) + { + ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ + ySamplingV = JPEG_CONFR4_VSF_1; /* Vs = 2*/ + + yblockNb = 0x30; /* 4 blocks of 8x8*/ + } + else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) + { + ySamplingH = JPEG_CONFR4_HSF_1; /* Hs = 2*/ + ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ + + yblockNb = 0x10; /* 2 blocks of 8x8*/ + } + else /*JPEG_444_SUBSAMPLING and default*/ + { + ySamplingH = JPEG_CONFR4_HSF_0; /* Hs = 1*/ + ySamplingV = JPEG_CONFR4_VSF_0; /* Vs = 1*/ + + yblockNb = 0; /* 1 block of 8x8*/ + } + + /*Reset CONFR4 register*/ + hjpeg->Instance->CONFR4 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 0*/ + hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB)); + + /*Reset CONFR5 register*/ + hjpeg->Instance->CONFR5 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 1*/ + hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0); + + /*Reset CONFR6 register*/ + hjpeg->Instance->CONFR6 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 2*/ + hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0); + + /*Reset CONFR7 register*/ + hjpeg->Instance->CONFR7 = 0; + /*Set Horizental and Vertical sampling factor , number of blocks, + Quantization table and Huffman AC/DC tables for component 3*/ + hjpeg->Instance->CONFR7 |= (JPEG_CONFR7_HSF_0 | JPEG_CONFR7_VSF_0); +} + +/** + * @brief Init the JPEG encoding/decoding process in case of Polling or Interrupt and DMA + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None + */ +static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg) +{ + /*Reset pause*/ + hjpeg->Context &= (~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT)); + + if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) + { + /*Set JPEG Codec to Decoding mode */ + hjpeg->Instance->CONFR1 |= JPEG_CONFR1_DE; + } + else /* JPEG_CONTEXT_ENCODE */ + { + /*Set JPEG Codec to Encoding mode */ + hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_DE; + } + + /*Stop JPEG processing */ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + /* Disable All Interrupts */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + /* Disable All DMA requests */ + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); + /* Flush input and output FIFOs*/ + hjpeg->Instance->CR |= JPEG_CR_IFF; + hjpeg->Instance->CR |= JPEG_CR_OFF; + + /* Clear all flags */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); + + /*Start Encoding/Decoding*/ + hjpeg->Instance->CONFR0 |= JPEG_CONFR0_START; + + if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) + { + /*Enable IN/OUT, end of Conversation, and end of header parsing interruptions*/ + __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_IFT | JPEG_IT_IFNF | JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC | JPEG_IT_HPD); + } + else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA) + { + /*Enable End Of Conversation, and End Of Header parsing interruptions*/ + __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD); + + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief JPEG encoding/decoding process in case of Polling or Interrupt + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval JPEG_PROCESS_DONE if the process has ends else JPEG_PROCESS_ONGOING + */ +static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg) +{ + uint32_t tmpContext; + + /*End of header processing flag */ + if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) + { + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL) + { + /*Call Header parsing complete callback */ + (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf); + /* Reset the ImageQuality */ + hjpeg->Conf.ImageQuality = 0; + /* Note : the image quality is only available at the end of the decoding operation */ + /* at the current stage the calculated image quality is not correct so reset it */ + + /*Call Info Ready callback */ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf); +#else + HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD); + + /* Clear header processing done flag */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF); + } + } + + /*Input FIFO status handling*/ + if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_INPUT) == 0UL) + { + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFTF) != 0UL) + { + /*Input FIFO threshold flag */ + /*JPEG_FIFO_TH_SIZE words can be written in */ + JPEG_ReadInputData(hjpeg, JPEG_FIFO_TH_SIZE); + } + else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFNFF) != 0UL) + { + /*Input FIFO Not Full flag */ + /*32-bit value can be written in */ + JPEG_ReadInputData(hjpeg, 1); + } + else + { + /* Nothing to do */ + } + } + + + /*Output FIFO flag handling*/ + if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) + { + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFTF) != 0UL) + { + /*Output FIFO threshold flag */ + /*JPEG_FIFO_TH_SIZE words can be read out */ + JPEG_StoreOutputData(hjpeg, JPEG_FIFO_TH_SIZE); + } + else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL) + { + /*Output FIFO Not Empty flag */ + /*32-bit value can be read out */ + JPEG_StoreOutputData(hjpeg, 1); + } + else + { + /* Nothing to do */ + } + } + + /*End of Conversion handling :i.e EOC flag is high and OFTF low and OFNEF low*/ + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF | JPEG_FLAG_OFTF | JPEG_FLAG_OFNEF) == JPEG_FLAG_EOCF) + { + /*Stop Encoding/Decoding*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT) + { + /* Disable All Interrupts */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + } + + /* Clear all flags */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); + + /*Call End of conversion callback */ + if (hjpeg->JpegOutCount > 0UL) + { + /*Output Buffer is not empty, call DecodedDataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + hjpeg->JpegOutCount = 0; + } + + /*Reset Context Operation*/ + tmpContext = hjpeg->Context; + /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/ + hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES); + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /*Call End of Encoding/Decoding callback */ + if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DecodeCpltCallback(hjpeg); +#else + HAL_JPEG_DecodeCpltCallback(hjpeg); +#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ + } + else /* JPEG_CONTEXT_ENCODE */ + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->EncodeCpltCallback(hjpeg); +#else + HAL_JPEG_EncodeCpltCallback(hjpeg); +#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ + } + + return JPEG_PROCESS_DONE; + } + + + return JPEG_PROCESS_ONGOING; +} + +/** + * @brief Store some output data from the JPEG peripheral to the output buffer. + * This function is used when the JPEG peripheral has new data to output + * in case of Polling or Interrupt process + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param nbOutputWords Number of output words (of 32 bits) ready from the JPEG peripheral + * @retval None + */ +static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords) +{ + uint32_t index; + uint32_t nb_words; + uint32_t nb_bytes; + uint32_t dataword; + + if (hjpeg->OutDataLength >= (hjpeg->JpegOutCount + (nbOutputWords * 4UL))) + { + for (index = 0; index < nbOutputWords; index++) + { + /*Transfer 32 bits from the JPEG output FIFO*/ + dataword = hjpeg->Instance->DOR; + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24); + hjpeg->JpegOutCount += 4UL; + } + if (hjpeg->OutDataLength == hjpeg->JpegOutCount) + { + /*Output Buffer is full, call DecodedDataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ + hjpeg->JpegOutCount = 0; + } + } + else if (hjpeg->OutDataLength > hjpeg->JpegOutCount) + { + nb_words = (hjpeg->OutDataLength - hjpeg->JpegOutCount) / 4UL; + for (index = 0; index < nb_words; index++) + { + /*Transfer 32 bits from the JPEG output FIFO*/ + dataword = hjpeg->Instance->DOR; + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24); + hjpeg->JpegOutCount += 4UL; + } + if (hjpeg->OutDataLength == hjpeg->JpegOutCount) + { + /*Output Buffer is full, call DecodedDataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + hjpeg->JpegOutCount = 0; + } + else + { + nb_bytes = hjpeg->OutDataLength - hjpeg->JpegOutCount; + dataword = hjpeg->Instance->DOR; + for (index = 0; index < nb_bytes; index++) + { + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * (index & 0x3UL))) & 0xFFUL); + hjpeg->JpegOutCount++; + } + /*Output Buffer is full, call DecodedDataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + hjpeg->JpegOutCount = 0; + + nb_bytes = 4UL - nb_bytes; + for (index = nb_bytes; index < 4UL; index++) + { + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * index)) & 0xFFUL); + hjpeg->JpegOutCount++; + } + } + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief Read some input Data from the input buffer. + * This function is used when the JPEG peripheral needs new data + * in case of Polling or Interrupt process + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @param nbRequestWords Number of input words (of 32 bits) that the JPE peripheral request + * @retval None + */ +static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords) +{ + uint32_t nb_bytes = 0; + uint32_t nb_words; + uint32_t index; + uint32_t dataword; + uint32_t input_count; + + if ((hjpeg->InDataLength == 0UL) || (nbRequestWords == 0UL)) + { + /* No more Input data : nothing to do*/ + (void) HAL_JPEG_Pause(hjpeg, JPEG_PAUSE_RESUME_INPUT); + } + else if (hjpeg->InDataLength > hjpeg->JpegInCount) + { + nb_bytes = hjpeg->InDataLength - hjpeg->JpegInCount; + } + else if (hjpeg->InDataLength == hjpeg->JpegInCount) + { + /*Call HAL_JPEG_GetDataCallback to get new data */ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount); +#else + HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount); +#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/ + + if (hjpeg->InDataLength > 4UL) + { + hjpeg->InDataLength = ((hjpeg->InDataLength + 3UL) / 4UL) * 4UL; + } + hjpeg->JpegInCount = 0; + nb_bytes = hjpeg->InDataLength; + } + else + { + /* Nothing to do */ + } + if (((hjpeg->Context & JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (nb_bytes > 0UL)) + { + nb_words = nb_bytes / 4UL; + if (nb_words >= nbRequestWords) + { + for (index = 0; index < nbRequestWords; index++) + { + input_count = hjpeg->JpegInCount; + hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \ + (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \ + (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \ + (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24)); + + hjpeg->JpegInCount += 4UL; + } + } + else /*nb_words < nbRequestWords*/ + { + if (nb_words > 0UL) + { + for (index = 0; index < nb_words; index++) + { + input_count = hjpeg->JpegInCount; + hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \ + (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \ + (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \ + (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24)); + + hjpeg->JpegInCount += 4UL; + } + } + else + { + /* end of file*/ + dataword = 0; + for (index = 0; index < nb_bytes; index++) + { + dataword |= (uint32_t)hjpeg->pJpegInBuffPtr[hjpeg->JpegInCount] << (8UL * (index & 0x03UL)); + hjpeg->JpegInCount++; + } + hjpeg->Instance->DIR = dataword; + } + } + } +} + +/** + * @brief Start the JPEG DMA process (encoding/decoding) + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING + */ +static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg) +{ + if ((hjpeg->InDataLength < 4UL) || (hjpeg->OutDataLength < 4UL)) + { + return HAL_ERROR; + } + /* Reset Ending DMA internal context flag*/ + hjpeg->Context &= ~JPEG_CONTEXT_ENDING_DMA; + + /* Disable DMA In/Out Request*/ + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA | JPEG_DMA_IDMA); + + /* Set the JPEG DMA In transfer complete callback */ + hjpeg->hdmain->XferCpltCallback = JPEG_DMAInCpltCallback; + /* Set the DMA In error callback */ + hjpeg->hdmain->XferErrorCallback = JPEG_DMAErrorCallback; + + /* Set the JPEG DMA Out transfer complete callback */ + hjpeg->hdmaout->XferCpltCallback = JPEG_DMAOutCpltCallback; + /* Set the DMA Out error callback */ + hjpeg->hdmaout->XferErrorCallback = JPEG_DMAErrorCallback; + /* Set the DMA Out Abort callback */ + hjpeg->hdmaout->XferAbortCallback = JPEG_DMAOutAbortCallback; + + /*DMA transfer size must be a multiple of 4 bytes i.e multiple of 32bits words*/ + hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL); + + /*DMA transfer size must be a multiple of 4 bytes i.e multiple of 32bits words*/ + hjpeg->OutDataLength = hjpeg->OutDataLength - (hjpeg->OutDataLength % 4UL); + + if ((hjpeg->hdmain->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hjpeg->hdmain->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hjpeg->InDataLength; + + /* Set DMA source address */ + hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hjpeg->pJpegInBuffPtr; + + /* Set DMA destination address */ + hjpeg->hdmain->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hjpeg->Instance->DIR; + + if (HAL_DMAEx_List_Start_IT(hjpeg->hdmain) != HAL_OK) + { + return HAL_ERROR; + } + } + else + { + /* Set the JPEG State to ready */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /* Update JPEG error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + } + else + { + /* Start DMA FIFO In transfer */ + if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR, + hjpeg->InDataLength) != HAL_OK) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + return HAL_ERROR; + } + } + + if ((hjpeg->hdmaout->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hjpeg->hdmaout->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hjpeg->OutDataLength; + + /* Set DMA source address */ + hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hjpeg->Instance->DOR; + + /* Set DMA destination address */ + hjpeg->hdmaout->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hjpeg->pJpegOutBuffPtr; + + if (HAL_DMAEx_List_Start_IT(hjpeg->hdmaout) != HAL_OK) + { + return HAL_ERROR; + } + } + else + { + /* Set the JPEG State to ready */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /* Update JPEG error code */ + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + return HAL_ERROR; + } + } + else + { + /* Start DMA FIFO Out transfer */ + if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr, + hjpeg->OutDataLength) != HAL_OK) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + return HAL_ERROR; + } + } + + /* Enable JPEG In/Out DMA requests*/ + JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_IDMA | JPEG_DMA_ODMA); + + return HAL_OK; +} + +/** + * @brief Continue the current JPEG DMA process (encoding/decoding) + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING + */ +static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg) +{ + /*End of header processing flag rises*/ + if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) + { + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL) + { + /*Call Header parsing complete callback */ + (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf); + + /* Reset the ImageQuality */ + hjpeg->Conf.ImageQuality = 0; + /* Note : the image quality is only available at the end of the decoding operation */ + /* at the current stage the calculated image quality is not correct so reset it */ + + /*Call Info Ready callback */ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf); +#else + HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD); + + /* Clear header processing done flag */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF); + } + } + + /*End of Conversion handling*/ + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) != 0UL) + { + /*Disabkle JPEG In/Out DMA Requests*/ + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA | JPEG_DMA_IDMA); + + hjpeg->Context |= JPEG_CONTEXT_ENDING_DMA; + + /*Stop Encoding/Decoding*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + /* Clear all flags */ + __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL); + + if (hjpeg->hdmain->State == HAL_DMA_STATE_BUSY) + { + /* Stop the DMA In Xfer*/ + (void) HAL_DMA_Abort(hjpeg->hdmain); + } + + if (hjpeg->hdmaout->State == HAL_DMA_STATE_BUSY) + { + /* Stop the DMA out Xfer*/ + (void) HAL_DMA_Abort(hjpeg->hdmaout); + } + + JPEG_DMA_EndProcess(hjpeg); + } + + +} + +/** + * @brief Finalize the current JPEG DMA process (encoding/decoding) + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval JPEG_PROCESS_DONE + */ +static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg) +{ + uint32_t tmpContext; + hjpeg->JpegOutCount = hjpeg->OutDataLength - JPEG_GET_DMA_REMAIN_DATA(hjpeg->hdmaout); + + /*if Output Buffer is full, call HAL_JPEG_DataReadyCallback*/ + if (hjpeg->JpegOutCount == hjpeg->OutDataLength) + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + hjpeg->JpegOutCount = 0; + } + + /*Check if remaining data in the output FIFO*/ + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL) + { + if (hjpeg->JpegOutCount > 0UL) + { + /*Output Buffer is not empty, call DecodedDataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + hjpeg->JpegOutCount = 0; + } + + /*Stop Encoding/Decoding*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + tmpContext = hjpeg->Context; + /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/ + hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES); + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /*Call End of Encoding/Decoding callback */ + if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DecodeCpltCallback(hjpeg); +#else + HAL_JPEG_DecodeCpltCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + } + else /* JPEG_CONTEXT_ENCODE */ + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->EncodeCpltCallback(hjpeg); +#else + HAL_JPEG_EncodeCpltCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + } + } + else if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) + { + JPEG_DMA_PollResidualData(hjpeg); + } + else + { + /* Nothing to do */ + } + +} + +/** + * @brief Poll residual output data when DMA process (encoding/decoding) + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval None. + */ +static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg) +{ + uint32_t tmpContext; + uint32_t count; + uint32_t dataOut; + + for (count = JPEG_FIFO_SIZE; count > 0UL; count--) + { + if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) + { + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL) + { + dataOut = hjpeg->Instance->DOR; + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataOut & 0x000000FFUL); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataOut & 0x0000FF00UL) >> 8); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataOut & 0x00FF0000UL) >> 16); + hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataOut & 0xFF000000UL) >> 24); + hjpeg->JpegOutCount += 4UL; + + if (hjpeg->JpegOutCount == hjpeg->OutDataLength) + { + /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + hjpeg->JpegOutCount = 0; + } + + } + } + } + + tmpContext = hjpeg->Context; + + if ((__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL) || ((tmpContext & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)) + { + /*Stop Encoding/Decoding*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + if (hjpeg->JpegOutCount > 0UL) + { + /*Output Buffer is not empty, call DecodedDataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + hjpeg->JpegOutCount = 0; + } + + tmpContext = hjpeg->Context; + /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/ + hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES); + + /* Process Unlocked */ + __HAL_UNLOCK(hjpeg); + + /* Change the JPEG state */ + hjpeg->State = HAL_JPEG_STATE_READY; + + /*Call End of Encoding/Decoding callback */ + if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE) + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DecodeCpltCallback(hjpeg); +#else + HAL_JPEG_DecodeCpltCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + } + else /* JPEG_CONTEXT_ENCODE */ + { +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->EncodeCpltCallback(hjpeg); +#else + HAL_JPEG_EncodeCpltCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief DMA input transfer complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure. + * @retval None + */ +static void JPEG_DMAInCpltCallback(DMA_HandleTypeDef *hdma) +{ + JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable The JPEG IT so the DMA Input Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) == + JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */ + { + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_IDMA); + + hjpeg->JpegInCount = hjpeg->InDataLength - JPEG_GET_DMA_REMAIN_DATA(hdma); + + /*Call HAL_JPEG_GetDataCallback to get new data */ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount); +#else + HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + if (hjpeg->InDataLength >= 4UL) + { + /*JPEG Input DMA transfer data number must be multiple of 32 bits word + as the destination is a 32 bits (4 bytes) register */ + hjpeg->InDataLength = ((hjpeg->InDataLength + 3UL) / 4UL) * 4UL; + } + else + { + /* Nothing to do */ + } + + if (((hjpeg->Context & JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (hjpeg->InDataLength > 0UL)) + { + /* Start DMA FIFO In transfer */ + if (HAL_DMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR, + hjpeg->InDataLength) != HAL_OK) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + hjpeg->State = HAL_JPEG_STATE_ERROR; +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->ErrorCallback(hjpeg); +#else + HAL_JPEG_ErrorCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + return; + } + JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_IDMA); + } + + /* JPEG Conversion still on going : Enable the JPEG IT */ + __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD); + } +} + +/** + * @brief DMA output transfer complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure. + * @retval None + */ +static void JPEG_DMAOutCpltCallback(DMA_HandleTypeDef *hdma) +{ + JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable The JPEG IT so the DMA Output Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) == + JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */ + { + if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) == 0UL) + { + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_ODMA); + hjpeg->JpegOutCount = hjpeg->OutDataLength - JPEG_GET_DMA_REMAIN_DATA(hdma); + + /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/ +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#else + HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + + if ((hjpeg->Context & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL) + { + /* Start DMA FIFO Out transfer */ + if (HAL_DMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr, + hjpeg->OutDataLength) != HAL_OK) + { + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; + hjpeg->State = HAL_JPEG_STATE_ERROR; +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->ErrorCallback(hjpeg); +#else + HAL_JPEG_ErrorCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + return; + } + JPEG_ENABLE_DMA(hjpeg, JPEG_DMA_ODMA); + } + } + + /* JPEG Conversion still on going : Enable the JPEG IT */ + __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD); + } +} + + +/** + * @brief DMA Transfer error callback + * @param hdma pointer to a DMA_HandleTypeDef structure. + * @retval None + */ +static void JPEG_DMAErrorCallback(DMA_HandleTypeDef *hdma) +{ + JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (HAL_DMA_GetError(hdma) != HAL_DMA_ERROR_NONE) + { + /*Stop Encoding/Decoding*/ + hjpeg->Instance->CONFR0 &= ~JPEG_CONFR0_START; + + /* Disable All Interrupts */ + __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK); + + /* Disable All DMA requests */ + JPEG_DISABLE_DMA(hjpeg, JPEG_DMA_MASK); + + hjpeg->State = HAL_JPEG_STATE_READY; + hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA; +#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1) + hjpeg->ErrorCallback(hjpeg); +#else + HAL_JPEG_ErrorCallback(hjpeg); +#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA output Abort callback + * @param hdma pointer to a DMA_HandleTypeDef structure. + * @retval None + */ +static void JPEG_DMAOutAbortCallback(DMA_HandleTypeDef *hdma) +{ + JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL) + { + JPEG_DMA_EndProcess(hjpeg); + } +} + + +/** + * @brief Calculate the decoded image quality (from 1 to 100) + * @param hjpeg pointer to a JPEG_HandleTypeDef structure that contains + * the configuration information for JPEG module + * @retval JPEG image quality from 1 to 100. + */ +static uint32_t JPEG_GetQuality(const JPEG_HandleTypeDef *hjpeg) +{ + uint32_t quality = 0; + uint32_t quantRow; + uint32_t quantVal; + uint32_t scale; + uint32_t i; + uint32_t j; + const __IO uint32_t *tableAddress = hjpeg->Instance->QMEM0; + + i = 0; + while (i < (JPEG_QUANT_TABLE_SIZE - 3UL)) + { + quantRow = *tableAddress; + for (j = 0; j < 4UL; j++) + { + quantVal = (quantRow >> (8UL * j)) & 0xFFUL; + if (quantVal == 1UL) + { + /* if Quantization value = 1 then quality is 100%*/ + quality += 100UL; + } + else + { + /* Note that the quantization coefficients must be specified in the table in zigzag order */ + scale = (quantVal * 100UL) / ((uint32_t) hjpeg->QuantTable0[JPEG_ZIGZAG_ORDER[i + j]]); + + if (scale <= 100UL) + { + quality += (200UL - scale) / 2UL; + } + else + { + quality += 5000UL / scale; + } + } + } + + i += 4UL; + tableAddress ++; + } + + return (quality / 64UL); +} +/** + * @} + */ + +/** + * @} + */ +#endif /* JPEG */ +#endif /* HAL_JPEG_MODULE_ENABLED */ + + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_lptim.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_lptim.c index 4afa50b3f..7b219e2be 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_lptim.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_lptim.c @@ -1,3777 +1,3777 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_lptim.c - * @author MCD Application Team - * @brief LPTIM HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Low Power Timer (LPTIM) peripheral: - * + Initialization and de-initialization functions. - * + Start/Stop operation functions in polling mode. - * + Start/Stop operation functions in interrupt mode. - * + Reading operation functions. - * + Peripheral State functions. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The LPTIM HAL driver can be used as follows: - - (#)Initialize the LPTIM low level resources by implementing the - HAL_LPTIM_MspInit(): - (++) Enable the LPTIM interface clock using __HAL_RCC_LPTIMx_CLK_ENABLE(). - (++) In case of using interrupts (e.g. HAL_LPTIM_PWM_Start_IT()): - (+++) Configure the LPTIM interrupt priority using HAL_NVIC_SetPriority(). - (+++) Enable the LPTIM IRQ handler using HAL_NVIC_EnableIRQ(). - (+++) In LPTIM IRQ handler, call HAL_LPTIM_IRQHandler(). - - (#)Initialize the LPTIM HAL using HAL_LPTIM_Init(). This function - configures mainly: - (++) The instance: LPTIM1, LPTIM2, LPTIM3, LPTIM4 or LPTIM5. - (++) Clock: the counter clock. - (+++) Source : it can be either the ULPTIM input (IN1) or one of - the internal clock; (APB, LSE or LSI). - (+++) Prescaler: select the clock divider. - (++) UltraLowPowerClock : To be used only if the ULPTIM is selected - as counter clock source. - (+++) Polarity: polarity of the active edge for the counter unit - if the ULPTIM input is selected. - (+++) SampleTime: clock sampling time to configure the clock glitch - filter. - (++) Trigger: How the counter start. - (+++) Source: trigger can be software or one of the hardware triggers. - (+++) ActiveEdge : only for hardware trigger. - (+++) SampleTime : trigger sampling time to configure the trigger - glitch filter. - (++) OutputPolarity : 2 opposite polarities are possible. - (++) UpdateMode: specifies whether the update of the autoreload and - the compare values is done immediately or after the end of current - period. - (++) Input1Source: Source selected for input1 (GPIO or comparator output). - (++) Input2Source: Source selected for input2 (GPIO or comparator output). - Input2 is used only for encoder feature so is used only for LPTIM1 instance. - - (#)Six modes are available: - - (++) PWM Mode: To generate a PWM signal with specified period and pulse, - call HAL_LPTIM_PWM_Start() or HAL_LPTIM_PWM_Start_IT() for interruption - mode. - - (++) One Pulse Mode: To generate pulse with specified width in response - to a stimulus, call HAL_LPTIM_OnePulse_Start() or - HAL_LPTIM_OnePulse_Start_IT() for interruption mode. - - (++) Set once Mode: In this mode, the output changes the level (from - low level to high level if the output polarity is configured high, else - the opposite) when a compare match occurs. To start this mode, call - HAL_LPTIM_SetOnce_Start() or HAL_LPTIM_SetOnce_Start_IT() for - interruption mode. - - (++) Encoder Mode: To use the encoder interface call - HAL_LPTIM_Encoder_Start() or HAL_LPTIM_Encoder_Start_IT() for - interruption mode. Only available for LPTIM1 instance. - - (++) Time out Mode: an active edge on one selected trigger input rests - the counter. The first trigger event will start the timer, any - successive trigger event will reset the counter and the timer will - restart. To start this mode call HAL_LPTIM_TimeOut_Start_IT() or - HAL_LPTIM_TimeOut_Start_IT() for interruption mode. - - (++) Counter Mode: counter can be used to count external events on - the LPTIM Input1 or it can be used to count internal clock cycles. - To start this mode, call HAL_LPTIM_Counter_Start() or - HAL_LPTIM_Counter_Start_IT() for interruption mode. - - - (#) User can stop any process by calling the corresponding API: - HAL_LPTIM_Xxx_Stop() or HAL_LPTIM_Xxx_Stop_IT() if the process is - already started in interruption mode. - - (#) De-initialize the LPTIM peripheral using HAL_LPTIM_DeInit(). - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_LPTIM_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - [..] - Use Function HAL_LPTIM_RegisterCallback() to register a callback. - HAL_LPTIM_RegisterCallback() takes as parameters the HAL peripheral handle, - the Callback ID and a pointer to the user callback function. - [..] - Use function HAL_LPTIM_UnRegisterCallback() to reset a callback to the - default weak function. - HAL_LPTIM_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - [..] - These functions allow to register/unregister following callbacks: - - (+) MspInitCallback : LPTIM Base Msp Init Callback. - (+) MspDeInitCallback : LPTIM Base Msp DeInit Callback. - (+) CompareMatchCallback : Compare match Callback. - (+) AutoReloadMatchCallback : Auto-reload match Callback. - (+) TriggerCallback : External trigger event detection Callback. - (+) CompareWriteCallback : Compare register write complete Callback. - (+) AutoReloadWriteCallback : Auto-reload register write complete Callback. - (+) DirectionUpCallback : Up-counting direction change Callback. - (+) DirectionDownCallback : Down-counting direction change Callback. - (+) UpdateEventCallback : Update event detection Callback. - (+) RepCounterWriteCallback : Repetition counter register write complete Callback. - - [..] - By default, after the Init and when the state is HAL_LPTIM_STATE_RESET - all interrupt callbacks are set to the corresponding weak functions: - examples HAL_LPTIM_TriggerCallback(), HAL_LPTIM_CompareMatchCallback(). - - [..] - Exception done for MspInit and MspDeInit functions that are reset to the legacy weak - functionalities in the Init/DeInit only when these callbacks are null - (not registered beforehand). If not, MspInit or MspDeInit are not null, the Init/DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - [..] - Callbacks can be registered/unregistered in HAL_LPTIM_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_LPTIM_STATE_READY or HAL_LPTIM_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_LPTIM_RegisterCallback() before calling DeInit or Init function. - - [..] - When The compilation define USE_HAL_LPTIM_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup LPTIM LPTIM - * @brief LPTIM HAL module driver. - * @{ - */ - -#ifdef HAL_LPTIM_MODULE_ENABLED - -#if defined (LPTIM1) || defined (LPTIM2) || defined (LPTIM3) || defined (LPTIM4) || defined (LPTIM5) - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup LPTIM_Private_Constants - * @{ - */ -#define TIMEOUT 1000UL /* Timeout is 1s */ -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/** @addtogroup LPTIM_Private_Macros - * @{ - */ -#define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT(__INSTANCE__) \ - (((__INSTANCE__) == LPTIM1) ? __HAL_LPTIM_LPTIM1_EXTI_ENABLE_IT() :\ - ((__INSTANCE__) == LPTIM2) ? __HAL_LPTIM_LPTIM2_EXTI_ENABLE_IT() :\ - ((__INSTANCE__) == LPTIM3) ? __HAL_LPTIM_LPTIM3_EXTI_ENABLE_IT() :\ - ((__INSTANCE__) == LPTIM4) ? __HAL_LPTIM_LPTIM4_EXTI_ENABLE_IT() : __HAL_LPTIM_LPTIM5_EXTI_ENABLE_IT()) - -#define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT(__INSTANCE__) \ - (((__INSTANCE__) == LPTIM1) ? __HAL_LPTIM_LPTIM1_EXTI_DISABLE_IT() :\ - ((__INSTANCE__) == LPTIM2) ? __HAL_LPTIM_LPTIM2_EXTI_DISABLE_IT() :\ - ((__INSTANCE__) == LPTIM3) ? __HAL_LPTIM_LPTIM3_EXTI_DISABLE_IT() :\ - ((__INSTANCE__) == LPTIM4) ? __HAL_LPTIM_LPTIM4_EXTI_DISABLE_IT() : __HAL_LPTIM_LPTIM5_EXTI_DISABLE_IT()) -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -static HAL_StatusTypeDef LPTIM_OC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig); -static HAL_StatusTypeDef LPTIM_OC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig); -static void LPTIM_IC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig); -static void LPTIM_IC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig); -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) -static void LPTIM_ResetCallback(LPTIM_HandleTypeDef *lptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ -static HAL_StatusTypeDef LPTIM_WaitForFlag(const LPTIM_HandleTypeDef *hlptim, uint32_t flag); -void LPTIM_DMAError(DMA_HandleTypeDef *hdma); -void LPTIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); -void LPTIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma); -void LPTIM_DMAUpdateEventCplt(DMA_HandleTypeDef *hdma); -void LPTIM_DMAUpdateEventHalfCplt(DMA_HandleTypeDef *hdma); -HAL_StatusTypeDef LPTIM_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t src, uint32_t dst, - uint32_t length); - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup LPTIM_Exported_Functions LPTIM Exported Functions - * @{ - */ - -/** @defgroup LPTIM_Exported_Functions_Group1 Initialization/de-initialization functions - * @brief Initialization and Configuration functions. - * -@verbatim - ============================================================================== - ##### Initialization and de-initialization functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) Initialize the LPTIM according to the specified parameters in the - LPTIM_InitTypeDef and initialize the associated handle. - (+) DeInitialize the LPTIM peripheral. - (+) Initialize the LPTIM MSP. - (+) DeInitialize the LPTIM MSP. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the LPTIM according to the specified parameters in the - * LPTIM_InitTypeDef and initialize the associated handle. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim) -{ - uint32_t tmpcfgr; - - /* Check the LPTIM handle allocation */ - if (hlptim == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_PERIOD(hlptim->Init.Period)); - - assert_param(IS_LPTIM_CLOCK_SOURCE(hlptim->Init.Clock.Source)); - assert_param(IS_LPTIM_CLOCK_PRESCALER(hlptim->Init.Clock.Prescaler)); - if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM) - || (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) - { - assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); - assert_param(IS_LPTIM_CLOCK_SAMPLE_TIME(hlptim->Init.UltraLowPowerClock.SampleTime)); - } - assert_param(IS_LPTIM_TRG_SOURCE(hlptim->Init.Trigger.Source)); - if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE) - { - assert_param(IS_LPTIM_EXT_TRG_POLARITY(hlptim->Init.Trigger.ActiveEdge)); - assert_param(IS_LPTIM_TRIG_SAMPLE_TIME(hlptim->Init.Trigger.SampleTime)); - } - assert_param(IS_LPTIM_UPDATE_MODE(hlptim->Init.UpdateMode)); - assert_param(IS_LPTIM_COUNTER_SOURCE(hlptim->Init.CounterSource)); - assert_param(IS_LPTIM_REPETITION(hlptim->Init.RepetitionCounter)); - - if (hlptim->State == HAL_LPTIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hlptim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - LPTIM_ResetCallback(hlptim); - - if (hlptim->MspInitCallback == NULL) - { - hlptim->MspInitCallback = HAL_LPTIM_MspInit; - } - - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - hlptim->MspInitCallback(hlptim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - HAL_LPTIM_MspInit(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_REPOK); - - /* Set the repetition counter */ - __HAL_LPTIM_REPETITIONCOUNTER_SET(hlptim, hlptim->Init.RepetitionCounter); - - /* Wait for the completion of the write operation to the LPTIM_RCR register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_REPOK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); - - /* Set LPTIM Period */ - __HAL_LPTIM_AUTORELOAD_SET(hlptim, hlptim->Init.Period); - - /* Wait for the completion of the write operation to the LPTIM_ARR register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Get the LPTIMx CFGR value */ - tmpcfgr = hlptim->Instance->CFGR; - - if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM) - || (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) - { - tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKPOL | LPTIM_CFGR_CKFLT)); - } - if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE) - { - tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_TRGFLT | LPTIM_CFGR_TRIGSEL)); - } - - /* Clear CKSEL, PRESC, TRIGEN, TRGFLT, WAVPOL, PRELOAD & COUNTMODE bits */ - tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKSEL | LPTIM_CFGR_TRIGEN | LPTIM_CFGR_PRELOAD | - LPTIM_CFGR_PRESC | LPTIM_CFGR_COUNTMODE)); - - /* Set initialization parameters */ - tmpcfgr |= (hlptim->Init.Clock.Source | - hlptim->Init.Clock.Prescaler | - hlptim->Init.UpdateMode | - hlptim->Init.CounterSource); - - /* Glitch filters for internal triggers and external inputs are configured - * only if an internal clock source is provided to the LPTIM - */ - if (hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC) - { - tmpcfgr |= (hlptim->Init.Trigger.SampleTime | - hlptim->Init.UltraLowPowerClock.SampleTime); - } - - /* Configure LPTIM external clock polarity and digital filter */ - if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM) - || (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) - { - tmpcfgr |= (hlptim->Init.UltraLowPowerClock.Polarity | - hlptim->Init.UltraLowPowerClock.SampleTime); - } - - /* Configure LPTIM external trigger */ - if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Enable External trigger and set the trigger source */ - tmpcfgr |= (hlptim->Init.Trigger.Source | - hlptim->Init.Trigger.ActiveEdge | - hlptim->Init.Trigger.SampleTime); - } - - /* Write to LPTIMx CFGR */ - hlptim->Instance->CFGR = tmpcfgr; - - /* Configure LPTIM input sources */ - if ((hlptim->Instance == LPTIM1) || (hlptim->Instance == LPTIM2)) - { - /* Check LPTIM Input1 and Input2 sources */ - assert_param(IS_LPTIM_INPUT1_SOURCE(hlptim->Instance, hlptim->Init.Input1Source)); - assert_param(IS_LPTIM_INPUT2_SOURCE(hlptim->Instance, hlptim->Init.Input2Source)); - - /* Configure LPTIM Input1 and Input2 sources */ - hlptim->Instance->CFGR2 = (hlptim->Init.Input1Source | hlptim->Init.Input2Source); - } - else - { - if (hlptim->Instance == LPTIM3) - { - /* Check LPTIM3 Input1 source */ - assert_param(IS_LPTIM_INPUT1_SOURCE(hlptim->Instance, hlptim->Init.Input1Source)); - - /* Configure LPTIM3 Input1 source */ - hlptim->Instance->CFGR2 = hlptim->Init.Input1Source; - } - } - - /* Initialize the LPTIM channels state */ - LPTIM_CHANNEL_STATE_SET_ALL(hlptim, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief DeInitialize the LPTIM peripheral. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the LPTIM handle allocation */ - if (hlptim == NULL) - { - return HAL_ERROR; - } - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - __HAL_LPTIM_ENABLE(hlptim); - if (IS_LPTIM_CC2_INSTANCE(hlptim->Instance)) - { - hlptim->Instance->CCMR1 = 0; - } - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); - - __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, 0); - /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - if (IS_LPTIM_CC2_INSTANCE(hlptim->Instance)) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP2OK); - - __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_2, 0); - /* Wait for the completion of the write operation to the LPTIM_CCR2 register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP2OK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); - - __HAL_LPTIM_AUTORELOAD_SET(hlptim, 0); - - /* Wait for the completion of the write operation to the LPTIM_ARR register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Disable the LPTIM Peripheral Clock */ - __HAL_LPTIM_DISABLE(hlptim); - - hlptim->Instance->CFGR = 0; - hlptim->Instance->CFGR2 = 0; - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - if (hlptim->MspDeInitCallback == NULL) - { - hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit; - } - - /* DeInit the low level hardware: CLOCK, NVIC.*/ - hlptim->MspDeInitCallback(hlptim); -#else - /* DeInit the low level hardware: CLOCK, NVIC.*/ - HAL_LPTIM_MspDeInit(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - - /* Change the LPTIM channels state */ - LPTIM_CHANNEL_STATE_SET_ALL(hlptim, HAL_LPTIM_CHANNEL_STATE_RESET); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hlptim); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Initialize the LPTIM MSP. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitialize LPTIM MSP. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup LPTIM_Exported_Functions_Group2 LPTIM Start-Stop operation functions - * @brief Start-Stop operation functions. - * -@verbatim - ============================================================================== - ##### LPTIM Start Stop operation functions ##### - ============================================================================== - [..] This section provides functions allowing to: - (+) Start the PWM mode. - (+) Stop the PWM mode. - (+) Start the One pulse mode. - (+) Stop the One pulse mode. - (+) Start the Set once mode. - (+) Stop the Set once mode. - (+) Start the Encoder mode. - (+) Stop the Encoder mode. - (+) Start the Timeout mode. - (+) Stop the Timeout mode. - (+) Start the Counter mode. - (+) Stop the Counter mode. - - -@endverbatim - * @{ - */ - -/** - * @brief Start the LPTIM PWM generation. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Reset WAVE bit to set PWM mode */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Enable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM PWM generation. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable LPTIM signal from the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the LPTIM PWM generation in interrupt mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Reset WAVE bit to set PWM mode */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - case LPTIM_CHANNEL_2: - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* If external trigger source is used, then enable external trigger interrupt */ - if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Enable external trigger interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM PWM generation in interrupt mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable LPTIM signal from the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - case LPTIM_CHANNEL_2: - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* If external trigger source is used, then enable external trigger interrupt */ - if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Enable external trigger interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the LPTIM PWM generation in DMA mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @param pData The destination Buffer address - * @param Length The length of data to be transferred from LPTIM peripheral to memory - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_PWM_Start_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel, const uint32_t *pData, - uint32_t Length) -{ - DMA_HandleTypeDef *hdma; - - /* Check the parameters */ - assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Reset WAVE bit to set PWM mode */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Enable update event DMA request */ - __HAL_LPTIM_ENABLE_DMA(hlptim, LPTIM_DMA_UPDATE); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Set the DMA update event callbacks */ - hlptim->hdma[LPTIM_DMA_ID_CC1]->XferCpltCallback = LPTIM_DMAUpdateEventCplt; - hlptim->hdma[LPTIM_DMA_ID_CC1]->XferHalfCpltCallback = LPTIM_DMAUpdateEventHalfCplt; - - /* Set the DMA error callback */ - hlptim->hdma[LPTIM_DMA_ID_CC1]->XferErrorCallback = LPTIM_DMAError; - - /* Enable the DMA Channel */ - hdma = hlptim->hdma[LPTIM_DMA_ID_CC1]; - if (LPTIM_DMA_Start_IT(hdma, (uint32_t)pData, (uint32_t)&hlptim->Instance->CCR1, Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - break; - case LPTIM_CHANNEL_2: - /* Set the DMA update event callbacks */ - hlptim->hdma[LPTIM_DMA_ID_CC2]->XferCpltCallback = LPTIM_DMAUpdateEventCplt; - hlptim->hdma[LPTIM_DMA_ID_CC2]->XferHalfCpltCallback = LPTIM_DMAUpdateEventHalfCplt; - - /* Set the DMA error callback */ - hlptim->hdma[LPTIM_DMA_ID_CC2]->XferErrorCallback = LPTIM_DMAError; - - /* Enable the DMA Channel */ - hdma = hlptim->hdma[LPTIM_DMA_ID_CC2]; - if (LPTIM_DMA_Start_IT(hdma, (uint32_t)pData, (uint32_t)&hlptim->Instance->CCR2, Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - break; - default: - break; - } - - /* Enable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM PWM generation in DMA mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable update event DMA request */ - __HAL_LPTIM_DISABLE_DMA(hlptim, LPTIM_DMA_UPDATE); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Disable update event DMA request */ - (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC1]); - break; - case LPTIM_CHANNEL_2: - /* Disable update event DMA request */ - (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC2]); - break; - default: - break; - } - - /* Disable LPTIM signal from the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the LPTIM One pulse generation. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Reset WAVE bit to set one pulse mode */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Enable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in single (one shot) mode */ - __HAL_LPTIM_START_SINGLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM One pulse generation. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the LPTIM One pulse generation in interrupt mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Reset WAVE bit to set one pulse mode */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - case LPTIM_CHANNEL_2: - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* If external trigger source is used, then enable external trigger interrupt */ - if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - /* Enable external trigger interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG); - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Enable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in single (one shot) mode */ - __HAL_LPTIM_START_SINGLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM One pulse generation in interrupt mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - case LPTIM_CHANNEL_2: - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | - LPTIM_IT_UPDATE); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* If external trigger source is used, then enable external trigger interrupt */ - if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - /* Enable external trigger interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG); - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the LPTIM in Set once mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Set WAVE bit to enable the set once mode */ - hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Enable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in single (one shot) mode */ - __HAL_LPTIM_START_SINGLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM Set once mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the LPTIM Set once mode in interrupt mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Set WAVE bit to enable the set once mode */ - hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_UPDATE); - break; - case LPTIM_CHANNEL_2: - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_UPDATE); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* If external trigger source is used, then enable external trigger interrupt */ - if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - /* Enable external trigger interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG); - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Enable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Start timer in single (one shot) mode */ - __HAL_LPTIM_START_SINGLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the LPTIM Set once mode in interrupt mode. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable LPTIM signal on the corresponding output pin */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM); - break; - case LPTIM_CHANNEL_2: - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* If external trigger source is used, then enable external trigger interrupt */ - if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) - { - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - /* Enable external trigger interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the Encoder interface. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim) -{ - uint32_t tmpcfgr; - - /* Check the parameters */ - assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); - assert_param(hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC); - assert_param(hlptim->Init.Clock.Prescaler == LPTIM_PRESCALER_DIV1); - assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Get the LPTIMx CFGR value */ - tmpcfgr = hlptim->Instance->CFGR; - - /* Clear CKPOL bits */ - tmpcfgr &= (uint32_t)(~LPTIM_CFGR_CKPOL); - - /* Set Input polarity */ - tmpcfgr |= hlptim->Init.UltraLowPowerClock.Polarity; - - /* Write to LPTIMx CFGR */ - hlptim->Instance->CFGR = tmpcfgr; - - /* Set ENC bit to enable the encoder interface */ - hlptim->Instance->CFGR |= LPTIM_CFGR_ENC; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the Encoder interface. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Reset ENC bit to disable the encoder interface */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC; - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the Encoder interface in interrupt mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim) -{ - uint32_t tmpcfgr; - - /* Check the parameters */ - assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); - assert_param(hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC); - assert_param(hlptim->Init.Clock.Prescaler == LPTIM_PRESCALER_DIV1); - assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Configure edge sensitivity for encoder mode */ - /* Get the LPTIMx CFGR value */ - tmpcfgr = hlptim->Instance->CFGR; - - /* Clear CKPOL bits */ - tmpcfgr &= (uint32_t)(~LPTIM_CFGR_CKPOL); - - /* Set Input polarity */ - tmpcfgr |= hlptim->Init.UltraLowPowerClock.Polarity; - - /* Write to LPTIMx CFGR */ - hlptim->Instance->CFGR = tmpcfgr; - - /* Set ENC bit to enable the encoder interface */ - hlptim->Instance->CFGR |= LPTIM_CFGR_ENC; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Enable "switch to up/down direction" interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_UP | LPTIM_IT_DOWN); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the Encoder interface in interrupt mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Reset ENC bit to disable the encoder interface */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC; - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Disable "switch to down/up direction" interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_UP | LPTIM_IT_DOWN); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the Timeout function. - * @note The first trigger event will start the timer, any successive - * trigger event will reset the counter and the timer restarts. - * @param hlptim LPTIM handle - * @param Timeout Specifies the TimeOut value to reset the counter. - * This parameter must be a value between 0x0000 and 0xFFFF. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Timeout) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_PULSE(Timeout)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set TIMOUT bit to enable the timeout function */ - hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); - - /* Load the Timeout value in the compare register */ - __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, Timeout); - - /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the Timeout function. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Reset TIMOUT bit to enable the timeout function */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT; - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the Timeout function in interrupt mode. - * @note The first trigger event will start the timer, any successive - * trigger event will reset the counter and the timer restarts. - * @param hlptim LPTIM handle - * @param Timeout Specifies the TimeOut value to reset the counter. - * This parameter must be a value between 0x0000 and 0xFFFF. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Timeout) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_PULSE(Timeout)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Enable EXTI Line interrupt on the LPTIM Wake-up Timer */ - __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT(hlptim->Instance); - - /* Set TIMOUT bit to enable the timeout function */ - hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Enable Compare match CH1 interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CC1); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); - - /* Load the Timeout value in the compare register */ - __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, Timeout); - - /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the Timeout function in interrupt mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - - /* Disable EXTI Line interrupt on the LPTIM Wake-up Timer */ - __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT(hlptim->Instance); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Reset TIMOUT bit to enable the timeout function */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Disable Compare match CH1 interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CC1); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the Counter mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* If clock source is not ULPTIM clock and counter source is external, then it must not be prescaled */ - if ((hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM) - && (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) - { - /* Check if clock is prescaled */ - assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler)); - /* Set clock prescaler to 0 */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC; - } - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the Counter mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Start the Counter mode in interrupt mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Enable EXTI Line interrupt on the LPTIM Wake-up Timer */ - __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT(hlptim->Instance); - - /* If clock source is not ULPTIM clock and counter source is external, then it must not be prescaled */ - if ((hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM) - && (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) - { - /* Check if clock is prescaled */ - assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler)); - /* Set clock prescaler to 0 */ - hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC; - } - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Enable interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | LPTIM_IT_UPDATE); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stop the Counter mode in interrupt mode. - * @param hlptim LPTIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - - /* Disable EXTI Line interrupt on the LPTIM Wake-up Timer */ - __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT(hlptim->Instance); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); - - /* Disable interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | LPTIM_IT_UPDATE); - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the LPTIM Input Capture measurement. - * @param hlptim LPTIM Input Capture handle - * @param Channel LPTIM Channels to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Enable capture */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the LPTIM Input Capture measurement. - * @param hlptim LPTIM Input Capture handle - * @param Channel LPTIM Channels to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Disable capture */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the LPTIM Input Capture measurement in interrupt mode. - * @param hlptim LPTIM Input Capture handle - * @param Channel LPTIM Channels to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Enable Capture/Compare 1 interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CC1); - break; - case LPTIM_CHANNEL_2: - /* Disable Capture/Compare 2 interrupt */ - __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CC2); - break; - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Enable capture */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the LPTIM Input Capture measurement in interrupt mode. - * @param hlptim LPTIM Input Capture handle - * @param Channel LPTIM Channels to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Disable Capture/Compare 1 interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CC1); - break; - case LPTIM_CHANNEL_2: - /* Disable Capture/Compare 2 interrupt */ - __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CC2); - break; - default: - return HAL_ERROR; - break; - } - /* Disable capture */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the LPTIM Input Capture measurement in DMA mode. - * @param hlptim LPTIM Input Capture handle - * @param Channel LPTIM Channels to be enabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected - * @param pData The destination Buffer address - * @param Length The length of data to be transferred from LPTIM peripheral to memory - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_Start_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel, uint32_t *pData, - uint32_t Length) -{ - DMA_HandleTypeDef *hdma; - - /* Check the parameters */ - assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - - /* Check LPTIM channel state */ - if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Set the DMA capture callbacks */ - hlptim->hdma[LPTIM_DMA_ID_CC1]->XferCpltCallback = LPTIM_DMACaptureCplt; - hlptim->hdma[LPTIM_DMA_ID_CC1]->XferHalfCpltCallback = LPTIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - hlptim->hdma[LPTIM_DMA_ID_CC1]->XferErrorCallback = LPTIM_DMAError; - - /* Enable the DMA Channel */ - hdma = hlptim->hdma[LPTIM_DMA_ID_CC1]; - if (LPTIM_DMA_Start_IT(hdma, (uint32_t)&hlptim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Enable Capture/Compare 1 DMA request */ - __HAL_LPTIM_ENABLE_DMA(hlptim, LPTIM_DMA_CC1); - break; - - case LPTIM_CHANNEL_2: - /* Set the DMA capture callbacks */ - hlptim->hdma[LPTIM_DMA_ID_CC2]->XferCpltCallback = LPTIM_DMACaptureCplt; - hlptim->hdma[LPTIM_DMA_ID_CC2]->XferHalfCpltCallback = LPTIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - hlptim->hdma[LPTIM_DMA_ID_CC2]->XferErrorCallback = LPTIM_DMAError; - - /* Enable the DMA Channel */ - hdma = hlptim->hdma[LPTIM_DMA_ID_CC2]; - if (LPTIM_DMA_Start_IT(hdma, (uint32_t)&hlptim->Instance->CCR2, (uint32_t)pData, Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Enable Capture/Compare 2 DMA request */ - __HAL_LPTIM_ENABLE_DMA(hlptim, LPTIM_DMA_CC2); - break; - - default: - break; - } - - /* Wait for the completion of the write operation to the LPTIM_DIER register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Start timer in continuous mode */ - __HAL_LPTIM_START_CONTINUOUS(hlptim); - - /* Enable capture */ - __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the LPTIM Input Capture measurement in DMA mode. - * @param hlptim LPTIM Input Capture handle - * @param Channel LPTIM Channels to be disabled - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_Stop_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_BUSY; - - switch (Channel) - { - case LPTIM_CHANNEL_1: - /* Disable Capture/Compare 1 DMA request */ - __HAL_LPTIM_DISABLE_DMA(hlptim, LPTIM_DMA_CC1); - (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC1]); - break; - - case LPTIM_CHANNEL_2: - /* Disable Capture/Compare 2 DMA request */ - __HAL_LPTIM_DISABLE_DMA(hlptim, LPTIM_DMA_CC2); - (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC2]); - break; - default: - return HAL_ERROR; - break; - } - - /* Disable capture */ - __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Set the LPTIM channel state */ - LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); - - /* Set the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} -/** - * @} - */ - -/** @defgroup LPTIM_Exported_Functions_Group3 LPTIM Read operation functions - * @brief Read operation functions. - * -@verbatim - ============================================================================== - ##### LPTIM Read operation functions ##### - ============================================================================== -[..] This section provides LPTIM Reading functions. - (+) Read the counter value. - (+) Read the period (Auto-reload) value. - (+) Read the pulse (Compare)value. -@endverbatim - * @{ - */ - -/** - * @brief Return the current counter value. - * @param hlptim LPTIM handle - * @retval Counter value. - */ -uint32_t HAL_LPTIM_ReadCounter(const LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - return (hlptim->Instance->CNT); -} - -/** - * @brief Return the current Autoreload (Period) value. - * @param hlptim LPTIM handle - * @retval Autoreload value. - */ -uint32_t HAL_LPTIM_ReadAutoReload(const LPTIM_HandleTypeDef *hlptim) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); - - return (hlptim->Instance->ARR); -} - -/** - * @brief Return the current Compare (Pulse) value. - * @param hlptim LPTIM handle - * @param Channel LPTIM Channel to be selected - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval Compare value. - */ -uint32_t HAL_LPTIM_ReadCapturedValue(const LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - uint32_t tmpccr; - - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - - switch (Channel) - { - case LPTIM_CHANNEL_1: - tmpccr = hlptim->Instance->CCR1; - break; - case LPTIM_CHANNEL_2: - tmpccr = hlptim->Instance->CCR2; - break; - default: - tmpccr = 0; - break; - } - return tmpccr; -} - -/** - * @brief LPTimer Input Capture Get Offset(in counter step unit) - * @note The real capture value corresponding to the input capture trigger can be calculated using - * the formula hereafter : Real capture value = captured(LPTIM_CCRx) - offset - * The Offset value is depending on the glitch filter value for the channel - * and the value of the prescaler for the kernel clock. - * Please check Errata Sheet V1_8 for more details under "variable latency - * on input capture channel" section. - * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @param Channel This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @retval The offset value - */ -uint8_t HAL_LPTIM_IC_GetOffset(const LPTIM_HandleTypeDef *hlptim, uint32_t Channel) -{ - - uint8_t offset ; - uint32_t prescaler; - uint32_t filter ; - - /* Get prescaler value */ - prescaler = LL_LPTIM_GetPrescaler(hlptim->Instance); - - /* Get filter value */ - filter = LL_LPTIM_IC_GetFilter(hlptim->Instance, Channel); - - /* Get offset value */ - offset = LL_LPTIM_IC_GET_OFFSET(prescaler, filter); - - /* return offset value */ - return offset; -} - -/** - * @} - */ -/** @defgroup LPTIM_Exported_Functions_Group5 LPTIM Config function - * @brief Config channel - * -@verbatim - ============================================================================== - ##### LPTIM Config function ##### - ============================================================================== -[..] This section provides LPTIM Config function. - (+) Configure channel: Output Compare mode, Period, Polarity. -@endverbatim - * @{ - */ - -/** - * @brief - * @param hlptim LPTIM handle - * @param sConfig The output configuration structure - * @param Channel LPTIM Channel to be configured - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @note Successive calls to HAL_LPTIM_OC_ConfigChannel can only be performed - * after a delay that must be greater or equal than the value of - * (PRESC x 3) kernel clock cycles, PRESC[2:0] being the clock decimal - * division factor (1, 2, 4, ..., 128). Any successive call violating - * this delay, leads to unpredictable results. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_OC_ConfigChannel(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig, - uint32_t Channel) -{ - HAL_StatusTypeDef status; - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - assert_param(IS_LPTIM_OC_POLARITY(sConfig->OCPolarity)); - assert_param(IS_LPTIM_PULSE(sConfig->Pulse)); - - hlptim->State = HAL_LPTIM_STATE_BUSY; - - switch (Channel) - { - case LPTIM_CHANNEL_1: - { - /* Check the parameters */ - assert_param(IS_LPTIM_CC1_INSTANCE(hlptim->Instance)); - - /* Configure the LPTIM Channel 1 in Output Compare */ - status = LPTIM_OC1_SetConfig(hlptim, sConfig); - if (status != HAL_OK) - { - return status; - } - break; - } - case LPTIM_CHANNEL_2: - { - /* Check the parameters */ - assert_param(IS_LPTIM_CC2_INSTANCE(hlptim->Instance)); - - /* Configure the LPTIM Channel 2 in Output Compare */ - status = LPTIM_OC2_SetConfig(hlptim, sConfig); - if (status != HAL_OK) - { - return status; - } - break; - } - default: - break; - } - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief - * @param hlptim LPTIM handle - * @param sConfig The input configuration structure - * @param Channel LPTIM Channel to be configured - * This parameter can be one of the following values: - * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected - * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected - * @note Successive calls to HAL_LPTIM_IC_ConfigChannel can only be performed - * after a delay that must be greater or equal than the value of - * (PRESC x 3) kernel clock cycles, PRESC[2:0] being the clock decimal - * division factor (1, 2, 4, ..., 128). Any successive call violating - * this delay, leads to unpredictable results. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LPTIM_IC_ConfigChannel(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig, - uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); - assert_param(IS_LPTIM_IC_PRESCALER(sConfig->ICPrescaler)); - assert_param(IS_LPTIM_IC_POLARITY(sConfig->ICPolarity)); - assert_param(IS_LPTIM_IC_FILTER(sConfig->ICFilter)); - - hlptim->State = HAL_LPTIM_STATE_BUSY; - - switch (Channel) - { - case LPTIM_CHANNEL_1: - { - /* Check the parameters */ - assert_param(IS_LPTIM_CC1_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_IC1_SOURCE(hlptim->Instance, sConfig->ICInputSource)); - - /* Configure the LPTIM Channel 1 in Input Capture */ - LPTIM_IC1_SetConfig(hlptim, sConfig); - break; - } - case LPTIM_CHANNEL_2: - { - /* Check the parameters */ - assert_param(IS_LPTIM_CC2_INSTANCE(hlptim->Instance)); - assert_param(IS_LPTIM_IC2_SOURCE(hlptim->Instance, sConfig->ICInputSource)); - - /* Configure the LPTIM Channel 2 in Input Capture */ - LPTIM_IC2_SetConfig(hlptim, sConfig); - break; - } - default: - break; - } - - /* Change the LPTIM state */ - hlptim->State = HAL_LPTIM_STATE_READY; - /* Return function status */ - return HAL_OK; -} -/** - * @} - */ - -/** @defgroup LPTIM_Exported_Functions_Group4 LPTIM IRQ handler and callbacks - * @brief LPTIM IRQ handler. - * -@verbatim - ============================================================================== - ##### LPTIM IRQ handler and callbacks ##### - ============================================================================== -[..] This section provides LPTIM IRQ handler and callback functions called within - the IRQ handler: - (+) LPTIM interrupt request handler - (+) Compare match Callback - (+) Auto-reload match Callback - (+) External trigger event detection Callback - (+) Compare register write complete Callback - (+) Auto-reload register write complete Callback - (+) Up-counting direction change Callback - (+) Down-counting direction change Callback - -@endverbatim - * @{ - */ - -/** - * @brief Handle LPTIM interrupt request. - * @param hlptim LPTIM handle - * @retval None - */ -void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim) -{ - /* Capture Compare 1 interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC1) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC1) != RESET) - { - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC1); - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - - /* Input capture event */ - if ((hlptim->Instance->CCMR1 & LPTIM_CCMR1_CC1SEL) != 0x00U) - { -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->IC_CaptureCallback(hlptim); -#else - HAL_LPTIM_IC_CaptureCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - /* Output compare event */ - else - { -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->CompareMatchCallback(hlptim); -#else - HAL_LPTIM_CompareMatchCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; - } - } - - /* Capture Compare 2 interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC2) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC2) != RESET) - { - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC2); - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - - /* Input capture event */ - if ((hlptim->Instance->CCMR1 & LPTIM_CCMR1_CC2SEL) != 0x00U) - { -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->IC_CaptureCallback(hlptim); -#else - HAL_LPTIM_IC_CaptureCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - /* Output compare event */ - else - { -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->CompareMatchCallback(hlptim); -#else - HAL_LPTIM_CompareMatchCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; - } - } - - /* Over Capture 1 interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC1O) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC1O) != RESET) - { - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC1O); - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - - /* Over capture event */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->IC_OverCaptureCallback(hlptim); -#else - HAL_LPTIM_IC_OverCaptureCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; - } - } - - /* Over Capture 2 interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC2O) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC2O) != RESET) - { - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC2O); - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - - /* Over capture event */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->IC_OverCaptureCallback(hlptim); -#else - HAL_LPTIM_IC_OverCaptureCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; - } - } - - /* Autoreload match interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARRM) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_ARRM) != RESET) - { - /* Clear Autoreload match flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARRM); - - /* Autoreload match Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->AutoReloadMatchCallback(hlptim); -#else - HAL_LPTIM_AutoReloadMatchCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Trigger detected interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_EXTTRIG) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_EXTTRIG) != RESET) - { - /* Clear Trigger detected flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_EXTTRIG); - - /* Trigger detected callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->TriggerCallback(hlptim); -#else - HAL_LPTIM_TriggerCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Compare write interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMP1OK) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_CMP1OK) != RESET) - { - /* Clear Compare write flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - /* Compare write Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->CompareWriteCallback(hlptim); -#else - HAL_LPTIM_CompareWriteCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Compare write interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMP2OK) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_CMP2OK) != RESET) - { - /* Clear Compare write flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP2OK); - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - /* Compare write Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->CompareWriteCallback(hlptim); -#else - HAL_LPTIM_CompareWriteCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Autoreload write interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARROK) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_ARROK) != RESET) - { - /* Clear Autoreload write flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); - - /* Autoreload write Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->AutoReloadWriteCallback(hlptim); -#else - HAL_LPTIM_AutoReloadWriteCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Direction counter changed from Down to Up interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_UP) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_UP) != RESET) - { - /* Clear Direction counter changed from Down to Up flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_UP); - - /* Direction counter changed from Down to Up Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->DirectionUpCallback(hlptim); -#else - HAL_LPTIM_DirectionUpCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Direction counter changed from Up to Down interrupt */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_DOWN) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_DOWN) != RESET) - { - /* Clear Direction counter changed from Up to Down flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DOWN); - - /* Direction counter changed from Up to Down Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->DirectionDownCallback(hlptim); -#else - HAL_LPTIM_DirectionDownCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Repetition counter underflowed (or contains zero) and the LPTIM counter - overflowed */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_UPDATE) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_UPDATE) != RESET) - { - /* Clear update event flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_UPDATE); - - /* Update event Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->UpdateEventCallback(hlptim); -#else - HAL_LPTIM_UpdateEventCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } - - /* Successful APB bus write to repetition counter register */ - if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_REPOK) != RESET) - { - if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_REPOK) != RESET) - { - /* Clear successful APB bus write to repetition counter flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_REPOK); - - /* Successful APB bus write to repetition counter Callback */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->RepCounterWriteCallback(hlptim); -#else - HAL_LPTIM_RepCounterWriteCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Compare match callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_CompareMatchCallback could be implemented in the user file - */ -} - -/** - * @brief Autoreload match callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_AutoReloadMatchCallback could be implemented in the user file - */ -} - -/** - * @brief Trigger detected callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_TriggerCallback could be implemented in the user file - */ -} - -/** - * @brief Compare write callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_CompareWriteCallback could be implemented in the user file - */ -} - -/** - * @brief Autoreload write callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_AutoReloadWriteCallback could be implemented in the user file - */ -} - -/** - * @brief Direction counter changed from Down to Up callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_DirectionUpCallback could be implemented in the user file - */ -} - -/** - * @brief Direction counter changed from Up to Down callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_DirectionDownCallback could be implemented in the user file - */ -} - -/** - * @brief Repetition counter underflowed (or contains zero) and LPTIM counter overflowed callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_UpdateEventCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_UpdateEventCallback could be implemented in the user file - */ -} - -/** - * @brief Successful APB bus write to repetition counter register callback in non-blocking mode. - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_RepCounterWriteCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_RepCounterWriteCallback could be implemented in the user file - */ -} - -/** - * @brief Input Capture callback in non-blocking mode - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_IC_CaptureCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_IC_CaptureCallback could be implemented in the user file - */ -} - -/** - * @brief Over Capture callback in non-blocking mode - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_IC_OverCaptureCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_IC_OverCaptureCallback could be implemented in the user file - */ -} - -/** - * @brief Input Capture half complete callback in non-blocking mode - * @param hlptim LPTIM IC handle - * @retval None - */ -__weak void HAL_LPTIM_IC_CaptureHalfCpltCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_IC_CaptureHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Update event half complete callback in non-blocking mode - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_UpdateEventHalfCpltCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_UpdateEventHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Error callback in non-blocking mode - * @param hlptim LPTIM handle - * @retval None - */ -__weak void HAL_LPTIM_ErrorCallback(LPTIM_HandleTypeDef *hlptim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hlptim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LPTIM_ErrorCallback could be implemented in the user file - */ -} - - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User LPTIM callback to be used instead of the weak predefined callback - * @param hlptim LPTIM handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_LPTIM_MSPINIT_CB_ID LPTIM Base Msp Init Callback ID - * @arg @ref HAL_LPTIM_MSPDEINIT_CB_ID LPTIM Base Msp DeInit Callback ID - * @arg @ref HAL_LPTIM_COMPARE_MATCH_CB_ID Compare match Callback ID - * @arg @ref HAL_LPTIM_AUTORELOAD_MATCH_CB_ID Auto-reload match Callback ID - * @arg @ref HAL_LPTIM_TRIGGER_CB_ID External trigger event detection Callback ID - * @arg @ref HAL_LPTIM_COMPARE_WRITE_CB_ID Compare register write complete Callback ID - * @arg @ref HAL_LPTIM_AUTORELOAD_WRITE_CB_ID Auto-reload register write complete Callback ID - * @arg @ref HAL_LPTIM_DIRECTION_UP_CB_ID Up-counting direction change Callback ID - * @arg @ref HAL_LPTIM_DIRECTION_DOWN_CB_ID Down-counting direction change Callback ID - * @arg @ref HAL_LPTIM_UPDATE_EVENT_CB_ID Update event detection Callback ID - * @arg @ref HAL_LPTIM_REP_COUNTER_WRITE_CB_ID Repetition counter register write complete Callback ID - * @arg @ref HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID Update event Half detection Callback ID - * @arg @ref HAL_LPTIM_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_LPTIM_IC_CAPTURE_CB_ID Input Capture Callback ID - * @arg @ref HAL_LPTIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID - * @arg @ref HAL_LPTIM_OVER_CAPTURE_CB_ID Over Capture Callback ID - * @param pCallback pointer to the callback function - * @retval status - */ -HAL_StatusTypeDef HAL_LPTIM_RegisterCallback(LPTIM_HandleTypeDef *hlptim, - HAL_LPTIM_CallbackIDTypeDef CallbackID, - pLPTIM_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - if (hlptim->State == HAL_LPTIM_STATE_READY) - { - switch (CallbackID) - { - case HAL_LPTIM_MSPINIT_CB_ID : - hlptim->MspInitCallback = pCallback; - break; - - case HAL_LPTIM_MSPDEINIT_CB_ID : - hlptim->MspDeInitCallback = pCallback; - break; - - case HAL_LPTIM_COMPARE_MATCH_CB_ID : - hlptim->CompareMatchCallback = pCallback; - break; - - case HAL_LPTIM_AUTORELOAD_MATCH_CB_ID : - hlptim->AutoReloadMatchCallback = pCallback; - break; - - case HAL_LPTIM_TRIGGER_CB_ID : - hlptim->TriggerCallback = pCallback; - break; - - case HAL_LPTIM_COMPARE_WRITE_CB_ID : - hlptim->CompareWriteCallback = pCallback; - break; - - case HAL_LPTIM_AUTORELOAD_WRITE_CB_ID : - hlptim->AutoReloadWriteCallback = pCallback; - break; - - case HAL_LPTIM_DIRECTION_UP_CB_ID : - hlptim->DirectionUpCallback = pCallback; - break; - - case HAL_LPTIM_DIRECTION_DOWN_CB_ID : - hlptim->DirectionDownCallback = pCallback; - break; - - case HAL_LPTIM_UPDATE_EVENT_CB_ID : - hlptim->UpdateEventCallback = pCallback; - break; - - case HAL_LPTIM_REP_COUNTER_WRITE_CB_ID : - hlptim->RepCounterWriteCallback = pCallback; - break; - - case HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID : - hlptim->UpdateEventHalfCpltCallback = pCallback; - break; - - case HAL_LPTIM_ERROR_CB_ID : - hlptim->ErrorCallback = pCallback; - break; - - case HAL_LPTIM_IC_CAPTURE_CB_ID : - hlptim->IC_CaptureCallback = pCallback; - break; - - case HAL_LPTIM_IC_CAPTURE_HALF_CB_ID : - hlptim->IC_CaptureHalfCpltCallback = pCallback; - break; - - case HAL_LPTIM_OVER_CAPTURE_CB_ID : - hlptim->IC_OverCaptureCallback = pCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hlptim->State == HAL_LPTIM_STATE_RESET) - { - switch (CallbackID) - { - case HAL_LPTIM_MSPINIT_CB_ID : - hlptim->MspInitCallback = pCallback; - break; - - case HAL_LPTIM_MSPDEINIT_CB_ID : - hlptim->MspDeInitCallback = pCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a LPTIM callback - * LLPTIM callback is redirected to the weak predefined callback - * @param hlptim LPTIM handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_LPTIM_MSPINIT_CB_ID LPTIM Base Msp Init Callback ID - * @arg @ref HAL_LPTIM_MSPDEINIT_CB_ID LPTIM Base Msp DeInit Callback ID - * @arg @ref HAL_LPTIM_COMPARE_MATCH_CB_ID Compare match Callback ID - * @arg @ref HAL_LPTIM_AUTORELOAD_MATCH_CB_ID Auto-reload match Callback ID - * @arg @ref HAL_LPTIM_TRIGGER_CB_ID External trigger event detection Callback ID - * @arg @ref HAL_LPTIM_COMPARE_WRITE_CB_ID Compare register write complete Callback ID - * @arg @ref HAL_LPTIM_AUTORELOAD_WRITE_CB_ID Auto-reload register write complete Callback ID - * @arg @ref HAL_LPTIM_DIRECTION_UP_CB_ID Up-counting direction change Callback ID - * @arg @ref HAL_LPTIM_DIRECTION_DOWN_CB_ID Down-counting direction change Callback ID - * @arg @ref HAL_LPTIM_UPDATE_EVENT_CB_ID Update event detection Callback ID - * @arg @ref HAL_LPTIM_REP_COUNTER_WRITE_CB_ID Repetition counter register write complete Callback ID - * @arg @ref HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID Update event Half detection Callback ID - * @arg @ref HAL_LPTIM_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_LPTIM_IC_CAPTURE_CB_ID Input Capture Callback ID - * @arg @ref HAL_LPTIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID - * @arg @ref HAL_LPTIM_OVER_CAPTURE_CB_ID Over Capture Callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_LPTIM_UnRegisterCallback(LPTIM_HandleTypeDef *hlptim, - HAL_LPTIM_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hlptim->State == HAL_LPTIM_STATE_READY) - { - switch (CallbackID) - { - case HAL_LPTIM_MSPINIT_CB_ID : - /* Legacy weak MspInit Callback */ - hlptim->MspInitCallback = HAL_LPTIM_MspInit; - break; - - case HAL_LPTIM_MSPDEINIT_CB_ID : - /* Legacy weak Msp DeInit Callback */ - hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit; - break; - - case HAL_LPTIM_COMPARE_MATCH_CB_ID : - /* Legacy weak Compare match Callback */ - hlptim->CompareMatchCallback = HAL_LPTIM_CompareMatchCallback; - break; - - case HAL_LPTIM_AUTORELOAD_MATCH_CB_ID : - /* Legacy weak Auto-reload match Callback */ - hlptim->AutoReloadMatchCallback = HAL_LPTIM_AutoReloadMatchCallback; - break; - - case HAL_LPTIM_TRIGGER_CB_ID : - /* Legacy weak External trigger event detection Callback */ - hlptim->TriggerCallback = HAL_LPTIM_TriggerCallback; - break; - - case HAL_LPTIM_COMPARE_WRITE_CB_ID : - /* Legacy weak Compare register write complete Callback */ - hlptim->CompareWriteCallback = HAL_LPTIM_CompareWriteCallback; - break; - - case HAL_LPTIM_AUTORELOAD_WRITE_CB_ID : - /* Legacy weak Auto-reload register write complete Callback */ - hlptim->AutoReloadWriteCallback = HAL_LPTIM_AutoReloadWriteCallback; - break; - - case HAL_LPTIM_DIRECTION_UP_CB_ID : - /* Legacy weak Up-counting direction change Callback */ - hlptim->DirectionUpCallback = HAL_LPTIM_DirectionUpCallback; - break; - - case HAL_LPTIM_DIRECTION_DOWN_CB_ID : - /* Legacy weak Down-counting direction change Callback */ - hlptim->DirectionDownCallback = HAL_LPTIM_DirectionDownCallback; - break; - - case HAL_LPTIM_UPDATE_EVENT_CB_ID : - /* Legacy weak Update event detection Callback */ - hlptim->UpdateEventCallback = HAL_LPTIM_UpdateEventCallback; - break; - - case HAL_LPTIM_REP_COUNTER_WRITE_CB_ID : - /* Legacy weak Repetition counter register write complete Callback */ - hlptim->RepCounterWriteCallback = HAL_LPTIM_RepCounterWriteCallback; - break; - - case HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID : - /* Legacy weak Update event half complete detection Callback */ - hlptim->UpdateEventHalfCpltCallback = HAL_LPTIM_UpdateEventHalfCpltCallback; - break; - - case HAL_LPTIM_ERROR_CB_ID : - /* Legacy weak error Callback */ - hlptim->ErrorCallback = HAL_LPTIM_ErrorCallback; - break; - - case HAL_LPTIM_IC_CAPTURE_CB_ID : - /* Legacy weak IC Capture Callback */ - hlptim->IC_CaptureCallback = HAL_LPTIM_IC_CaptureCallback; - break; - - case HAL_LPTIM_IC_CAPTURE_HALF_CB_ID : - /* Legacy weak IC Capture half complete Callback */ - hlptim->IC_CaptureHalfCpltCallback = HAL_LPTIM_IC_CaptureHalfCpltCallback; - break; - - case HAL_LPTIM_OVER_CAPTURE_CB_ID : - /* Legacy weak IC over capture Callback */ - hlptim->IC_OverCaptureCallback = HAL_LPTIM_IC_OverCaptureCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hlptim->State == HAL_LPTIM_STATE_RESET) - { - switch (CallbackID) - { - case HAL_LPTIM_MSPINIT_CB_ID : - /* Legacy weak MspInit Callback */ - hlptim->MspInitCallback = HAL_LPTIM_MspInit; - break; - - case HAL_LPTIM_MSPDEINIT_CB_ID : - /* Legacy weak Msp DeInit Callback */ - hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup LPTIM_Group5 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 LPTIM handle state. - * @param hlptim LPTIM handle - * @retval HAL state - */ -HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(const LPTIM_HandleTypeDef *hlptim) -{ - /* Return LPTIM handle state */ - return hlptim->State; -} - -/** - * @} - */ - - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ - -/** @defgroup LPTIM_Private_Functions LPTIM Private Functions - * @{ - */ -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) -/** - * @brief Reset interrupt callbacks to the legacy weak callbacks. - * @param lptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @retval None - */ -static void LPTIM_ResetCallback(LPTIM_HandleTypeDef *lptim) -{ - /* Reset the LPTIM callback to the legacy weak callbacks */ - lptim->CompareMatchCallback = HAL_LPTIM_CompareMatchCallback; - lptim->AutoReloadMatchCallback = HAL_LPTIM_AutoReloadMatchCallback; - lptim->TriggerCallback = HAL_LPTIM_TriggerCallback; - lptim->CompareWriteCallback = HAL_LPTIM_CompareWriteCallback; - lptim->AutoReloadWriteCallback = HAL_LPTIM_AutoReloadWriteCallback; - lptim->DirectionUpCallback = HAL_LPTIM_DirectionUpCallback; - lptim->DirectionDownCallback = HAL_LPTIM_DirectionDownCallback; - lptim->UpdateEventCallback = HAL_LPTIM_UpdateEventCallback; - lptim->RepCounterWriteCallback = HAL_LPTIM_RepCounterWriteCallback; - lptim->UpdateEventHalfCpltCallback = HAL_LPTIM_UpdateEventHalfCpltCallback; - lptim->IC_CaptureCallback = HAL_LPTIM_IC_CaptureCallback; - lptim->IC_CaptureHalfCpltCallback = HAL_LPTIM_IC_CaptureHalfCpltCallback; - lptim->IC_OverCaptureCallback = HAL_LPTIM_IC_OverCaptureCallback; - lptim->ErrorCallback = HAL_LPTIM_ErrorCallback; -} -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - -/** - * @brief LPTimer Wait for flag set - * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @param flag The lptim flag - * @retval HAL status - */ -static HAL_StatusTypeDef LPTIM_WaitForFlag(const LPTIM_HandleTypeDef *hlptim, uint32_t flag) -{ - HAL_StatusTypeDef result = HAL_OK; - uint32_t count = TIMEOUT * (SystemCoreClock / 20UL / 1000UL); - do - { - count--; - if (count == 0UL) - { - result = HAL_TIMEOUT; - } - } while ((!(__HAL_LPTIM_GET_FLAG((hlptim), (flag)))) && (count != 0UL)); - - return result; -} - -/** - * @brief LPTIM DMA error callback - * @param hdma pointer to DMA handle. - * @retval None - */ -void LPTIM_DMAError(DMA_HandleTypeDef *hdma) -{ - LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hlptim->State = HAL_LPTIM_STATE_READY; - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->ErrorCallback(hlptim); -#else - HAL_LPTIM_ErrorCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ -} - -/** - * @brief LPTIM DMA Capture complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void LPTIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) -{ - LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hlptim->State = HAL_LPTIM_STATE_READY; - - if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - } - else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->IC_CaptureCallback(hlptim); -#else - HAL_LPTIM_IC_CaptureCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief LPTIM DMA Capture half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void LPTIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma) -{ - LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hlptim->State = HAL_LPTIM_STATE_READY; - - if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - } - else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->IC_CaptureHalfCpltCallback(hlptim); -#else - HAL_LPTIM_IC_CaptureHalfCpltCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief LPTIM DMA Update event complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void LPTIM_DMAUpdateEventCplt(DMA_HandleTypeDef *hdma) -{ - LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hlptim->State = HAL_LPTIM_STATE_READY; - - if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - } - else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->UpdateEventCallback(hlptim); -#else - HAL_LPTIM_UpdateEventCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief LPTIM DMA Capture half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void LPTIM_DMAUpdateEventHalfCplt(DMA_HandleTypeDef *hdma) -{ - LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hlptim->State = HAL_LPTIM_STATE_READY; - - if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; - } - else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) - { - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) - hlptim->UpdateEventHalfCpltCallback(hlptim); -#else - HAL_LPTIM_UpdateEventHalfCpltCallback(hlptim); -#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ - - hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; -} -/** - * @brief LPTimer Output Compare 1 configuration - * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @param sConfig The output configuration structure - * @retval None - */ -static HAL_StatusTypeDef LPTIM_OC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig) -{ - uint32_t tmpccmr1; - uint32_t tmpcfgr; - - tmpccmr1 = hlptim->Instance->CCMR1; - tmpccmr1 &= ~(LPTIM_CCMR1_CC1P_Msk | LPTIM_CCMR1_CC1SEL_Msk); - - if ((hlptim->Instance == LPTIM4) || (hlptim->Instance == LPTIM5)) - { - tmpcfgr = hlptim->Instance->CFGR; - tmpcfgr &= ~LPTIM_CFGR_WAVPOL_Msk; - tmpcfgr |= sConfig->OCPolarity << LPTIM_CFGR_WAVPOL_Pos; - - /* Write to CFGR register */ - hlptim->Instance->CFGR = tmpcfgr; - } - else - { - tmpccmr1 |= sConfig->OCPolarity << LPTIM_CCMR1_CC1P_Pos; - } - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); - - /* Write to CCR1 register */ - __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, sConfig->Pulse); - - /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Write to CCMR1 register */ - hlptim->Instance->CCMR1 = tmpccmr1; - - return HAL_OK; -} - -/** - * @brief LPTimer Output Compare 2 configuration - * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @param sConfig The output configuration structure - * @retval None - */ -static HAL_StatusTypeDef LPTIM_OC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig) -{ - uint32_t tmpccmr1; - - tmpccmr1 = hlptim->Instance->CCMR1; - tmpccmr1 &= ~(LPTIM_CCMR1_CC2P_Msk | LPTIM_CCMR1_CC2SEL_Msk); - tmpccmr1 |= sConfig->OCPolarity << LPTIM_CCMR1_CC2P_Pos; - - /* Enable the Peripheral */ - __HAL_LPTIM_ENABLE(hlptim); - - /* Clear flag */ - __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP2OK); - - /* Write to CCR2 register */ - __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_2, sConfig->Pulse); - - /* Wait for the completion of the write operation to the LPTIM_CCR2 register */ - if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP2OK) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral */ - __HAL_LPTIM_DISABLE(hlptim); - - /* Write to CCMR1 register */ - hlptim->Instance->CCMR1 = tmpccmr1; - - return HAL_OK; -} - -/** - * @brief LPTimer Input Capture 1 configuration - * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @param sConfig The input configuration structure - * @retval None - */ -static void LPTIM_IC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig) -{ - uint32_t tmpccmr1; - uint32_t tmpcfgr2; - - tmpccmr1 = hlptim->Instance->CCMR1; - tmpccmr1 &= ~(LPTIM_CCMR1_IC1PSC_Msk | LPTIM_CCMR1_CC1P_Msk | LPTIM_CCMR1_IC1F_Msk); - tmpccmr1 |= sConfig->ICPrescaler | - sConfig->ICPolarity | - sConfig->ICFilter | - LPTIM_CCMR1_CC1SEL; - - tmpcfgr2 = hlptim->Instance->CFGR2; - tmpcfgr2 &= ~(LPTIM_CFGR2_IC1SEL_Msk); - tmpcfgr2 |= sConfig->ICInputSource; - - /* Write to CCMR1 register */ - hlptim->Instance->CCMR1 = tmpccmr1; - - /* Write to CFGR2 register */ - hlptim->Instance->CFGR2 = tmpcfgr2; -} - -/** - * @brief LPTimer Input Capture 2 configuration - * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains - * the configuration information for LPTIM module. - * @param sConfig The input configuration structure - * @retval None - */ -static void LPTIM_IC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig) -{ - uint32_t tmpccmr1; - uint32_t tmpcfgr2; - - tmpccmr1 = hlptim->Instance->CCMR1; - tmpccmr1 &= ~(LPTIM_CCMR1_IC2PSC_Msk | LPTIM_CCMR1_CC2P_Msk | LPTIM_CCMR1_IC2F_Msk); - tmpccmr1 |= (sConfig->ICPrescaler << (LPTIM_CCMR1_IC2PSC_Pos - LPTIM_CCMR1_IC1PSC_Pos)) | - (sConfig->ICPolarity << (LPTIM_CCMR1_CC2P_Pos - LPTIM_CCMR1_CC1P_Pos)) | - (sConfig->ICFilter << (LPTIM_CCMR1_IC2F_Pos - LPTIM_CCMR1_IC1F_Pos)) | - LPTIM_CCMR1_CC2SEL; - - tmpcfgr2 = hlptim->Instance->CFGR2; - tmpcfgr2 &= ~(LPTIM_CFGR2_IC2SEL_Msk); - tmpcfgr2 |= sConfig->ICInputSource; - - /* Write to CCMR1 register */ - hlptim->Instance->CCMR1 = tmpccmr1; - - /* Write to CFGR2 register */ - hlptim->Instance->CFGR2 = tmpcfgr2; -} - -/** - * @brief Start the DMA data transfer. - * @param hdma DMA handle - * @param src The source memory Buffer address. - * @param dst The destination memory Buffer address. - * @param length The size of a source block transfer in byte. - * @retval HAL status - */ -HAL_StatusTypeDef LPTIM_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t src, uint32_t dst, - uint32_t length) -{ - HAL_StatusTypeDef status; - - /* Enable the DMA channel */ - if ((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hdma->LinkedListQueue != 0U) && (hdma->LinkedListQueue->Head != 0U)) - { - /* Enable the DMA channel */ - hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = length; - hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)src; - hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)dst; - - status = HAL_DMAEx_List_Start_IT(hdma); - } - else - { - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hdma, src, dst, length); - } - - return status; -} -/** - * @} - */ -#endif /* LPTIM1 || LPTIM2 || LPTIM3 || LPTIM4 || LPTIM5 */ - -#endif /* HAL_LPTIM_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_lptim.c + * @author MCD Application Team + * @brief LPTIM HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Low Power Timer (LPTIM) peripheral: + * + Initialization and de-initialization functions. + * + Start/Stop operation functions in polling mode. + * + Start/Stop operation functions in interrupt mode. + * + Reading operation functions. + * + Peripheral State functions. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The LPTIM HAL driver can be used as follows: + + (#)Initialize the LPTIM low level resources by implementing the + HAL_LPTIM_MspInit(): + (++) Enable the LPTIM interface clock using __HAL_RCC_LPTIMx_CLK_ENABLE(). + (++) In case of using interrupts (e.g. HAL_LPTIM_PWM_Start_IT()): + (+++) Configure the LPTIM interrupt priority using HAL_NVIC_SetPriority(). + (+++) Enable the LPTIM IRQ handler using HAL_NVIC_EnableIRQ(). + (+++) In LPTIM IRQ handler, call HAL_LPTIM_IRQHandler(). + + (#)Initialize the LPTIM HAL using HAL_LPTIM_Init(). This function + configures mainly: + (++) The instance: LPTIM1, LPTIM2, LPTIM3, LPTIM4 or LPTIM5. + (++) Clock: the counter clock. + (+++) Source : it can be either the ULPTIM input (IN1) or one of + the internal clock; (APB, LSE or LSI). + (+++) Prescaler: select the clock divider. + (++) UltraLowPowerClock : To be used only if the ULPTIM is selected + as counter clock source. + (+++) Polarity: polarity of the active edge for the counter unit + if the ULPTIM input is selected. + (+++) SampleTime: clock sampling time to configure the clock glitch + filter. + (++) Trigger: How the counter start. + (+++) Source: trigger can be software or one of the hardware triggers. + (+++) ActiveEdge : only for hardware trigger. + (+++) SampleTime : trigger sampling time to configure the trigger + glitch filter. + (++) OutputPolarity : 2 opposite polarities are possible. + (++) UpdateMode: specifies whether the update of the autoreload and + the compare values is done immediately or after the end of current + period. + (++) Input1Source: Source selected for input1 (GPIO or comparator output). + (++) Input2Source: Source selected for input2 (GPIO or comparator output). + Input2 is used only for encoder feature so is used only for LPTIM1 instance. + + (#)Six modes are available: + + (++) PWM Mode: To generate a PWM signal with specified period and pulse, + call HAL_LPTIM_PWM_Start() or HAL_LPTIM_PWM_Start_IT() for interruption + mode. + + (++) One Pulse Mode: To generate pulse with specified width in response + to a stimulus, call HAL_LPTIM_OnePulse_Start() or + HAL_LPTIM_OnePulse_Start_IT() for interruption mode. + + (++) Set once Mode: In this mode, the output changes the level (from + low level to high level if the output polarity is configured high, else + the opposite) when a compare match occurs. To start this mode, call + HAL_LPTIM_SetOnce_Start() or HAL_LPTIM_SetOnce_Start_IT() for + interruption mode. + + (++) Encoder Mode: To use the encoder interface call + HAL_LPTIM_Encoder_Start() or HAL_LPTIM_Encoder_Start_IT() for + interruption mode. Only available for LPTIM1 instance. + + (++) Time out Mode: an active edge on one selected trigger input rests + the counter. The first trigger event will start the timer, any + successive trigger event will reset the counter and the timer will + restart. To start this mode call HAL_LPTIM_TimeOut_Start_IT() or + HAL_LPTIM_TimeOut_Start_IT() for interruption mode. + + (++) Counter Mode: counter can be used to count external events on + the LPTIM Input1 or it can be used to count internal clock cycles. + To start this mode, call HAL_LPTIM_Counter_Start() or + HAL_LPTIM_Counter_Start_IT() for interruption mode. + + + (#) User can stop any process by calling the corresponding API: + HAL_LPTIM_Xxx_Stop() or HAL_LPTIM_Xxx_Stop_IT() if the process is + already started in interruption mode. + + (#) De-initialize the LPTIM peripheral using HAL_LPTIM_DeInit(). + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_LPTIM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + [..] + Use Function HAL_LPTIM_RegisterCallback() to register a callback. + HAL_LPTIM_RegisterCallback() takes as parameters the HAL peripheral handle, + the Callback ID and a pointer to the user callback function. + [..] + Use function HAL_LPTIM_UnRegisterCallback() to reset a callback to the + default weak function. + HAL_LPTIM_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + [..] + These functions allow to register/unregister following callbacks: + + (+) MspInitCallback : LPTIM Base Msp Init Callback. + (+) MspDeInitCallback : LPTIM Base Msp DeInit Callback. + (+) CompareMatchCallback : Compare match Callback. + (+) AutoReloadMatchCallback : Auto-reload match Callback. + (+) TriggerCallback : External trigger event detection Callback. + (+) CompareWriteCallback : Compare register write complete Callback. + (+) AutoReloadWriteCallback : Auto-reload register write complete Callback. + (+) DirectionUpCallback : Up-counting direction change Callback. + (+) DirectionDownCallback : Down-counting direction change Callback. + (+) UpdateEventCallback : Update event detection Callback. + (+) RepCounterWriteCallback : Repetition counter register write complete Callback. + + [..] + By default, after the Init and when the state is HAL_LPTIM_STATE_RESET + all interrupt callbacks are set to the corresponding weak functions: + examples HAL_LPTIM_TriggerCallback(), HAL_LPTIM_CompareMatchCallback(). + + [..] + Exception done for MspInit and MspDeInit functions that are reset to the legacy weak + functionalities in the Init/DeInit only when these callbacks are null + (not registered beforehand). If not, MspInit or MspDeInit are not null, the Init/DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + [..] + Callbacks can be registered/unregistered in HAL_LPTIM_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_LPTIM_STATE_READY or HAL_LPTIM_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_LPTIM_RegisterCallback() before calling DeInit or Init function. + + [..] + When The compilation define USE_HAL_LPTIM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup LPTIM LPTIM + * @brief LPTIM HAL module driver. + * @{ + */ + +#ifdef HAL_LPTIM_MODULE_ENABLED + +#if defined (LPTIM1) || defined (LPTIM2) || defined (LPTIM3) || defined (LPTIM4) || defined (LPTIM5) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup LPTIM_Private_Constants + * @{ + */ +#define TIMEOUT 1000UL /* Timeout is 1s */ +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/** @addtogroup LPTIM_Private_Macros + * @{ + */ +#define __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT(__INSTANCE__) \ + (((__INSTANCE__) == LPTIM1) ? __HAL_LPTIM_LPTIM1_EXTI_ENABLE_IT() :\ + ((__INSTANCE__) == LPTIM2) ? __HAL_LPTIM_LPTIM2_EXTI_ENABLE_IT() :\ + ((__INSTANCE__) == LPTIM3) ? __HAL_LPTIM_LPTIM3_EXTI_ENABLE_IT() :\ + ((__INSTANCE__) == LPTIM4) ? __HAL_LPTIM_LPTIM4_EXTI_ENABLE_IT() : __HAL_LPTIM_LPTIM5_EXTI_ENABLE_IT()) + +#define __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT(__INSTANCE__) \ + (((__INSTANCE__) == LPTIM1) ? __HAL_LPTIM_LPTIM1_EXTI_DISABLE_IT() :\ + ((__INSTANCE__) == LPTIM2) ? __HAL_LPTIM_LPTIM2_EXTI_DISABLE_IT() :\ + ((__INSTANCE__) == LPTIM3) ? __HAL_LPTIM_LPTIM3_EXTI_DISABLE_IT() :\ + ((__INSTANCE__) == LPTIM4) ? __HAL_LPTIM_LPTIM4_EXTI_DISABLE_IT() : __HAL_LPTIM_LPTIM5_EXTI_DISABLE_IT()) +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef LPTIM_OC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig); +static HAL_StatusTypeDef LPTIM_OC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig); +static void LPTIM_IC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig); +static void LPTIM_IC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig); +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) +static void LPTIM_ResetCallback(LPTIM_HandleTypeDef *lptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ +static HAL_StatusTypeDef LPTIM_WaitForFlag(const LPTIM_HandleTypeDef *hlptim, uint32_t flag); +void LPTIM_DMAError(DMA_HandleTypeDef *hdma); +void LPTIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); +void LPTIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma); +void LPTIM_DMAUpdateEventCplt(DMA_HandleTypeDef *hdma); +void LPTIM_DMAUpdateEventHalfCplt(DMA_HandleTypeDef *hdma); +HAL_StatusTypeDef LPTIM_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t src, uint32_t dst, + uint32_t length); + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup LPTIM_Exported_Functions LPTIM Exported Functions + * @{ + */ + +/** @defgroup LPTIM_Exported_Functions_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the LPTIM according to the specified parameters in the + LPTIM_InitTypeDef and initialize the associated handle. + (+) DeInitialize the LPTIM peripheral. + (+) Initialize the LPTIM MSP. + (+) DeInitialize the LPTIM MSP. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the LPTIM according to the specified parameters in the + * LPTIM_InitTypeDef and initialize the associated handle. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim) +{ + uint32_t tmpcfgr; + + /* Check the LPTIM handle allocation */ + if (hlptim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(hlptim->Init.Period)); + + assert_param(IS_LPTIM_CLOCK_SOURCE(hlptim->Init.Clock.Source)); + assert_param(IS_LPTIM_CLOCK_PRESCALER(hlptim->Init.Clock.Prescaler)); + if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM) + || (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) + { + assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); + assert_param(IS_LPTIM_CLOCK_SAMPLE_TIME(hlptim->Init.UltraLowPowerClock.SampleTime)); + } + assert_param(IS_LPTIM_TRG_SOURCE(hlptim->Init.Trigger.Source)); + if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE) + { + assert_param(IS_LPTIM_EXT_TRG_POLARITY(hlptim->Init.Trigger.ActiveEdge)); + assert_param(IS_LPTIM_TRIG_SAMPLE_TIME(hlptim->Init.Trigger.SampleTime)); + } + assert_param(IS_LPTIM_UPDATE_MODE(hlptim->Init.UpdateMode)); + assert_param(IS_LPTIM_COUNTER_SOURCE(hlptim->Init.CounterSource)); + assert_param(IS_LPTIM_REPETITION(hlptim->Init.RepetitionCounter)); + + if (hlptim->State == HAL_LPTIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hlptim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + LPTIM_ResetCallback(hlptim); + + if (hlptim->MspInitCallback == NULL) + { + hlptim->MspInitCallback = HAL_LPTIM_MspInit; + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + hlptim->MspInitCallback(hlptim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_LPTIM_MspInit(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_REPOK); + + /* Set the repetition counter */ + __HAL_LPTIM_REPETITIONCOUNTER_SET(hlptim, hlptim->Init.RepetitionCounter); + + /* Wait for the completion of the write operation to the LPTIM_RCR register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_REPOK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); + + /* Set LPTIM Period */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, hlptim->Init.Period); + + /* Wait for the completion of the write operation to the LPTIM_ARR register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Get the LPTIMx CFGR value */ + tmpcfgr = hlptim->Instance->CFGR; + + if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM) + || (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) + { + tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKPOL | LPTIM_CFGR_CKFLT)); + } + if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE) + { + tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_TRGFLT | LPTIM_CFGR_TRIGSEL)); + } + + /* Clear CKSEL, PRESC, TRIGEN, TRGFLT, WAVPOL, PRELOAD & COUNTMODE bits */ + tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKSEL | LPTIM_CFGR_TRIGEN | LPTIM_CFGR_PRELOAD | + LPTIM_CFGR_PRESC | LPTIM_CFGR_COUNTMODE)); + + /* Set initialization parameters */ + tmpcfgr |= (hlptim->Init.Clock.Source | + hlptim->Init.Clock.Prescaler | + hlptim->Init.UpdateMode | + hlptim->Init.CounterSource); + + /* Glitch filters for internal triggers and external inputs are configured + * only if an internal clock source is provided to the LPTIM + */ + if (hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC) + { + tmpcfgr |= (hlptim->Init.Trigger.SampleTime | + hlptim->Init.UltraLowPowerClock.SampleTime); + } + + /* Configure LPTIM external clock polarity and digital filter */ + if ((hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_ULPTIM) + || (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) + { + tmpcfgr |= (hlptim->Init.UltraLowPowerClock.Polarity | + hlptim->Init.UltraLowPowerClock.SampleTime); + } + + /* Configure LPTIM external trigger */ + if (hlptim->Init.Trigger.Source != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Enable External trigger and set the trigger source */ + tmpcfgr |= (hlptim->Init.Trigger.Source | + hlptim->Init.Trigger.ActiveEdge | + hlptim->Init.Trigger.SampleTime); + } + + /* Write to LPTIMx CFGR */ + hlptim->Instance->CFGR = tmpcfgr; + + /* Configure LPTIM input sources */ + if ((hlptim->Instance == LPTIM1) || (hlptim->Instance == LPTIM2)) + { + /* Check LPTIM Input1 and Input2 sources */ + assert_param(IS_LPTIM_INPUT1_SOURCE(hlptim->Instance, hlptim->Init.Input1Source)); + assert_param(IS_LPTIM_INPUT2_SOURCE(hlptim->Instance, hlptim->Init.Input2Source)); + + /* Configure LPTIM Input1 and Input2 sources */ + hlptim->Instance->CFGR2 = (hlptim->Init.Input1Source | hlptim->Init.Input2Source); + } + else + { + if (hlptim->Instance == LPTIM3) + { + /* Check LPTIM3 Input1 source */ + assert_param(IS_LPTIM_INPUT1_SOURCE(hlptim->Instance, hlptim->Init.Input1Source)); + + /* Configure LPTIM3 Input1 source */ + hlptim->Instance->CFGR2 = hlptim->Init.Input1Source; + } + } + + /* Initialize the LPTIM channels state */ + LPTIM_CHANNEL_STATE_SET_ALL(hlptim, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitialize the LPTIM peripheral. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the LPTIM handle allocation */ + if (hlptim == NULL) + { + return HAL_ERROR; + } + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + __HAL_LPTIM_ENABLE(hlptim); + if (IS_LPTIM_CC2_INSTANCE(hlptim->Instance)) + { + hlptim->Instance->CCMR1 = 0; + } + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); + + __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, 0); + /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + if (IS_LPTIM_CC2_INSTANCE(hlptim->Instance)) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP2OK); + + __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_2, 0); + /* Wait for the completion of the write operation to the LPTIM_CCR2 register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP2OK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); + + __HAL_LPTIM_AUTORELOAD_SET(hlptim, 0); + + /* Wait for the completion of the write operation to the LPTIM_ARR register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Disable the LPTIM Peripheral Clock */ + __HAL_LPTIM_DISABLE(hlptim); + + hlptim->Instance->CFGR = 0; + hlptim->Instance->CFGR2 = 0; + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + if (hlptim->MspDeInitCallback == NULL) + { + hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit; + } + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + hlptim->MspDeInitCallback(hlptim); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_LPTIM_MspDeInit(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + + /* Change the LPTIM channels state */ + LPTIM_CHANNEL_STATE_SET_ALL(hlptim, HAL_LPTIM_CHANNEL_STATE_RESET); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hlptim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initialize the LPTIM MSP. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize LPTIM MSP. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup LPTIM_Exported_Functions_Group2 LPTIM Start-Stop operation functions + * @brief Start-Stop operation functions. + * +@verbatim + ============================================================================== + ##### LPTIM Start Stop operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start the PWM mode. + (+) Stop the PWM mode. + (+) Start the One pulse mode. + (+) Stop the One pulse mode. + (+) Start the Set once mode. + (+) Stop the Set once mode. + (+) Start the Encoder mode. + (+) Stop the Encoder mode. + (+) Start the Timeout mode. + (+) Stop the Timeout mode. + (+) Start the Counter mode. + (+) Stop the Counter mode. + + +@endverbatim + * @{ + */ + +/** + * @brief Start the LPTIM PWM generation. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Enable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM PWM generation. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable LPTIM signal from the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the LPTIM PWM generation in interrupt mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + case LPTIM_CHANNEL_2: + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Enable external trigger interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM PWM generation in interrupt mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable LPTIM signal from the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + case LPTIM_CHANNEL_2: + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Enable external trigger interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the LPTIM PWM generation in DMA mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @param pData The destination Buffer address + * @param Length The length of data to be transferred from LPTIM peripheral to memory + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel, const uint32_t *pData, + uint32_t Length) +{ + DMA_HandleTypeDef *hdma; + + /* Check the parameters */ + assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Enable update event DMA request */ + __HAL_LPTIM_ENABLE_DMA(hlptim, LPTIM_DMA_UPDATE); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Set the DMA update event callbacks */ + hlptim->hdma[LPTIM_DMA_ID_CC1]->XferCpltCallback = LPTIM_DMAUpdateEventCplt; + hlptim->hdma[LPTIM_DMA_ID_CC1]->XferHalfCpltCallback = LPTIM_DMAUpdateEventHalfCplt; + + /* Set the DMA error callback */ + hlptim->hdma[LPTIM_DMA_ID_CC1]->XferErrorCallback = LPTIM_DMAError; + + /* Enable the DMA Channel */ + hdma = hlptim->hdma[LPTIM_DMA_ID_CC1]; + if (LPTIM_DMA_Start_IT(hdma, (uint32_t)pData, (uint32_t)&hlptim->Instance->CCR1, Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + break; + case LPTIM_CHANNEL_2: + /* Set the DMA update event callbacks */ + hlptim->hdma[LPTIM_DMA_ID_CC2]->XferCpltCallback = LPTIM_DMAUpdateEventCplt; + hlptim->hdma[LPTIM_DMA_ID_CC2]->XferHalfCpltCallback = LPTIM_DMAUpdateEventHalfCplt; + + /* Set the DMA error callback */ + hlptim->hdma[LPTIM_DMA_ID_CC2]->XferErrorCallback = LPTIM_DMAError; + + /* Enable the DMA Channel */ + hdma = hlptim->hdma[LPTIM_DMA_ID_CC2]; + if (LPTIM_DMA_Start_IT(hdma, (uint32_t)pData, (uint32_t)&hlptim->Instance->CCR2, Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + break; + default: + break; + } + + /* Enable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM PWM generation in DMA mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable update event DMA request */ + __HAL_LPTIM_DISABLE_DMA(hlptim, LPTIM_DMA_UPDATE); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Disable update event DMA request */ + (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC1]); + break; + case LPTIM_CHANNEL_2: + /* Disable update event DMA request */ + (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC2]); + break; + default: + break; + } + + /* Disable LPTIM signal from the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the LPTIM One pulse generation. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Reset WAVE bit to set one pulse mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Enable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in single (one shot) mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM One pulse generation. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the LPTIM One pulse generation in interrupt mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Reset WAVE bit to set one pulse mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + case LPTIM_CHANNEL_2: + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + /* Enable external trigger interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG); + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + /* Enable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in single (one shot) mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM One pulse generation in interrupt mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + case LPTIM_CHANNEL_2: + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | + LPTIM_IT_UPDATE); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + /* Enable external trigger interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG); + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the LPTIM in Set once mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Set WAVE bit to enable the set once mode */ + hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Enable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in single (one shot) mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM Set once mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the LPTIM Set once mode in interrupt mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Set WAVE bit to enable the set once mode */ + hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_UPDATE); + break; + case LPTIM_CHANNEL_2: + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_UPDATE); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + /* Enable external trigger interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_EXTTRIG); + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + /* Enable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Start timer in single (one shot) mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the LPTIM Set once mode in interrupt mode. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable LPTIM signal on the corresponding output pin */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP1OK | LPTIM_IT_CC1 | LPTIM_IT_ARROK | LPTIM_IT_ARRM); + break; + case LPTIM_CHANNEL_2: + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CMP2OK | LPTIM_IT_CC2 | LPTIM_IT_ARROK | LPTIM_IT_ARRM); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + /* Enable external trigger interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_EXTTRIG); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the Encoder interface. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim) +{ + uint32_t tmpcfgr; + + /* Check the parameters */ + assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); + assert_param(hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC); + assert_param(hlptim->Init.Clock.Prescaler == LPTIM_PRESCALER_DIV1); + assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Get the LPTIMx CFGR value */ + tmpcfgr = hlptim->Instance->CFGR; + + /* Clear CKPOL bits */ + tmpcfgr &= (uint32_t)(~LPTIM_CFGR_CKPOL); + + /* Set Input polarity */ + tmpcfgr |= hlptim->Init.UltraLowPowerClock.Polarity; + + /* Write to LPTIMx CFGR */ + hlptim->Instance->CFGR = tmpcfgr; + + /* Set ENC bit to enable the encoder interface */ + hlptim->Instance->CFGR |= LPTIM_CFGR_ENC; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the Encoder interface. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset ENC bit to disable the encoder interface */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC; + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the Encoder interface in interrupt mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim) +{ + uint32_t tmpcfgr; + + /* Check the parameters */ + assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); + assert_param(hlptim->Init.Clock.Source == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC); + assert_param(hlptim->Init.Clock.Prescaler == LPTIM_PRESCALER_DIV1); + assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Configure edge sensitivity for encoder mode */ + /* Get the LPTIMx CFGR value */ + tmpcfgr = hlptim->Instance->CFGR; + + /* Clear CKPOL bits */ + tmpcfgr &= (uint32_t)(~LPTIM_CFGR_CKPOL); + + /* Set Input polarity */ + tmpcfgr |= hlptim->Init.UltraLowPowerClock.Polarity; + + /* Write to LPTIMx CFGR */ + hlptim->Instance->CFGR = tmpcfgr; + + /* Set ENC bit to enable the encoder interface */ + hlptim->Instance->CFGR |= LPTIM_CFGR_ENC; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Enable "switch to up/down direction" interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_UP | LPTIM_IT_DOWN); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the Encoder interface in interrupt mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_ENCODER_INTERFACE_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset ENC bit to disable the encoder interface */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC; + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Disable "switch to down/up direction" interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_UP | LPTIM_IT_DOWN); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the Timeout function. + * @note The first trigger event will start the timer, any successive + * trigger event will reset the counter and the timer restarts. + * @param hlptim LPTIM handle + * @param Timeout Specifies the TimeOut value to reset the counter. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Timeout) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PULSE(Timeout)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); + + /* Load the Timeout value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, Timeout); + + /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the Timeout function. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT; + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the Timeout function in interrupt mode. + * @note The first trigger event will start the timer, any successive + * trigger event will reset the counter and the timer restarts. + * @param hlptim LPTIM handle + * @param Timeout Specifies the TimeOut value to reset the counter. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Timeout) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PULSE(Timeout)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Enable EXTI Line interrupt on the LPTIM Wake-up Timer */ + __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT(hlptim->Instance); + + /* Set TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Enable Compare match CH1 interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CC1); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); + + /* Load the Timeout value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, Timeout); + + /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the Timeout function in interrupt mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + + /* Disable EXTI Line interrupt on the LPTIM Wake-up Timer */ + __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT(hlptim->Instance); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Disable Compare match CH1 interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CC1); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the Counter mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* If clock source is not ULPTIM clock and counter source is external, then it must not be prescaled */ + if ((hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM) + && (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) + { + /* Check if clock is prescaled */ + assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler)); + /* Set clock prescaler to 0 */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC; + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the Counter mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Start the Counter mode in interrupt mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Enable EXTI Line interrupt on the LPTIM Wake-up Timer */ + __HAL_LPTIM_WAKEUPTIMER_EXTI_ENABLE_IT(hlptim->Instance); + + /* If clock source is not ULPTIM clock and counter source is external, then it must not be prescaled */ + if ((hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM) + && (hlptim->Init.CounterSource == LPTIM_COUNTERSOURCE_EXTERNAL)) + { + /* Check if clock is prescaled */ + assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler)); + /* Set clock prescaler to 0 */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC; + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Enable interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | LPTIM_IT_UPDATE); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the Counter mode in interrupt mode. + * @param hlptim LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + + /* Disable EXTI Line interrupt on the LPTIM Wake-up Timer */ + __HAL_LPTIM_WAKEUPTIMER_EXTI_DISABLE_IT(hlptim->Instance); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DIEROK); + + /* Disable interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_ARROK | LPTIM_IT_ARRM | LPTIM_IT_REPOK | LPTIM_IT_UPDATE); + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM Input Capture measurement. + * @param hlptim LPTIM Input Capture handle + * @param Channel LPTIM Channels to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Enable capture */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM Input Capture measurement. + * @param hlptim LPTIM Input Capture handle + * @param Channel LPTIM Channels to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_Stop(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable capture */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM Input Capture measurement in interrupt mode. + * @param hlptim LPTIM Input Capture handle + * @param Channel LPTIM Channels to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Enable Capture/Compare 1 interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CC1); + break; + case LPTIM_CHANNEL_2: + /* Disable Capture/Compare 2 interrupt */ + __HAL_LPTIM_ENABLE_IT(hlptim, LPTIM_IT_CC2); + break; + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Enable capture */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM Input Capture measurement in interrupt mode. + * @param hlptim LPTIM Input Capture handle + * @param Channel LPTIM Channels to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_Stop_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INPUT_CAPTURE_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Disable Capture/Compare 1 interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CC1); + break; + case LPTIM_CHANNEL_2: + /* Disable Capture/Compare 2 interrupt */ + __HAL_LPTIM_DISABLE_IT(hlptim, LPTIM_IT_CC2); + break; + default: + return HAL_ERROR; + break; + } + /* Disable capture */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM Input Capture measurement in DMA mode. + * @param hlptim LPTIM Input Capture handle + * @param Channel LPTIM Channels to be enabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected + * @param pData The destination Buffer address + * @param Length The length of data to be transferred from LPTIM peripheral to memory + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_Start_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel, uint32_t *pData, + uint32_t Length) +{ + DMA_HandleTypeDef *hdma; + + /* Check the parameters */ + assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + + /* Check LPTIM channel state */ + if (LPTIM_CHANNEL_STATE_GET(hlptim, Channel) != HAL_LPTIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_BUSY); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Set the DMA capture callbacks */ + hlptim->hdma[LPTIM_DMA_ID_CC1]->XferCpltCallback = LPTIM_DMACaptureCplt; + hlptim->hdma[LPTIM_DMA_ID_CC1]->XferHalfCpltCallback = LPTIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + hlptim->hdma[LPTIM_DMA_ID_CC1]->XferErrorCallback = LPTIM_DMAError; + + /* Enable the DMA Channel */ + hdma = hlptim->hdma[LPTIM_DMA_ID_CC1]; + if (LPTIM_DMA_Start_IT(hdma, (uint32_t)&hlptim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Enable Capture/Compare 1 DMA request */ + __HAL_LPTIM_ENABLE_DMA(hlptim, LPTIM_DMA_CC1); + break; + + case LPTIM_CHANNEL_2: + /* Set the DMA capture callbacks */ + hlptim->hdma[LPTIM_DMA_ID_CC2]->XferCpltCallback = LPTIM_DMACaptureCplt; + hlptim->hdma[LPTIM_DMA_ID_CC2]->XferHalfCpltCallback = LPTIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + hlptim->hdma[LPTIM_DMA_ID_CC2]->XferErrorCallback = LPTIM_DMAError; + + /* Enable the DMA Channel */ + hdma = hlptim->hdma[LPTIM_DMA_ID_CC2]; + if (LPTIM_DMA_Start_IT(hdma, (uint32_t)&hlptim->Instance->CCR2, (uint32_t)pData, Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Enable Capture/Compare 2 DMA request */ + __HAL_LPTIM_ENABLE_DMA(hlptim, LPTIM_DMA_CC2); + break; + + default: + break; + } + + /* Wait for the completion of the write operation to the LPTIM_DIER register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_DIEROK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Enable capture */ + __HAL_LPTIM_CAPTURE_COMPARE_ENABLE(hlptim, Channel); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM Input Capture measurement in DMA mode. + * @param hlptim LPTIM Input Capture handle + * @param Channel LPTIM Channels to be disabled + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: TIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_Stop_DMA(LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_DMA_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + switch (Channel) + { + case LPTIM_CHANNEL_1: + /* Disable Capture/Compare 1 DMA request */ + __HAL_LPTIM_DISABLE_DMA(hlptim, LPTIM_DMA_CC1); + (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC1]); + break; + + case LPTIM_CHANNEL_2: + /* Disable Capture/Compare 2 DMA request */ + __HAL_LPTIM_DISABLE_DMA(hlptim, LPTIM_DMA_CC2); + (void)HAL_DMA_Abort_IT(hlptim->hdma[LPTIM_DMA_ID_CC2]); + break; + default: + return HAL_ERROR; + break; + } + + /* Disable capture */ + __HAL_LPTIM_CAPTURE_COMPARE_DISABLE(hlptim, Channel); + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Set the LPTIM channel state */ + LPTIM_CHANNEL_STATE_SET(hlptim, Channel, HAL_LPTIM_CHANNEL_STATE_READY); + + /* Set the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} +/** + * @} + */ + +/** @defgroup LPTIM_Exported_Functions_Group3 LPTIM Read operation functions + * @brief Read operation functions. + * +@verbatim + ============================================================================== + ##### LPTIM Read operation functions ##### + ============================================================================== +[..] This section provides LPTIM Reading functions. + (+) Read the counter value. + (+) Read the period (Auto-reload) value. + (+) Read the pulse (Compare)value. +@endverbatim + * @{ + */ + +/** + * @brief Return the current counter value. + * @param hlptim LPTIM handle + * @retval Counter value. + */ +uint32_t HAL_LPTIM_ReadCounter(const LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + return (hlptim->Instance->CNT); +} + +/** + * @brief Return the current Autoreload (Period) value. + * @param hlptim LPTIM handle + * @retval Autoreload value. + */ +uint32_t HAL_LPTIM_ReadAutoReload(const LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + return (hlptim->Instance->ARR); +} + +/** + * @brief Return the current Compare (Pulse) value. + * @param hlptim LPTIM handle + * @param Channel LPTIM Channel to be selected + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval Compare value. + */ +uint32_t HAL_LPTIM_ReadCapturedValue(const LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + uint32_t tmpccr; + + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + + switch (Channel) + { + case LPTIM_CHANNEL_1: + tmpccr = hlptim->Instance->CCR1; + break; + case LPTIM_CHANNEL_2: + tmpccr = hlptim->Instance->CCR2; + break; + default: + tmpccr = 0; + break; + } + return tmpccr; +} + +/** + * @brief LPTimer Input Capture Get Offset(in counter step unit) + * @note The real capture value corresponding to the input capture trigger can be calculated using + * the formula hereafter : Real capture value = captured(LPTIM_CCRx) - offset + * The Offset value is depending on the glitch filter value for the channel + * and the value of the prescaler for the kernel clock. + * Please check Errata Sheet V1_8 for more details under "variable latency + * on input capture channel" section. + * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @param Channel This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @retval The offset value + */ +uint8_t HAL_LPTIM_IC_GetOffset(const LPTIM_HandleTypeDef *hlptim, uint32_t Channel) +{ + + uint8_t offset ; + uint32_t prescaler; + uint32_t filter ; + + /* Get prescaler value */ + prescaler = LL_LPTIM_GetPrescaler(hlptim->Instance); + + /* Get filter value */ + filter = LL_LPTIM_IC_GetFilter(hlptim->Instance, Channel); + + /* Get offset value */ + offset = LL_LPTIM_IC_GET_OFFSET(prescaler, filter); + + /* return offset value */ + return offset; +} + +/** + * @} + */ +/** @defgroup LPTIM_Exported_Functions_Group5 LPTIM Config function + * @brief Config channel + * +@verbatim + ============================================================================== + ##### LPTIM Config function ##### + ============================================================================== +[..] This section provides LPTIM Config function. + (+) Configure channel: Output Compare mode, Period, Polarity. +@endverbatim + * @{ + */ + +/** + * @brief + * @param hlptim LPTIM handle + * @param sConfig The output configuration structure + * @param Channel LPTIM Channel to be configured + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @note Successive calls to HAL_LPTIM_OC_ConfigChannel can only be performed + * after a delay that must be greater or equal than the value of + * (PRESC x 3) kernel clock cycles, PRESC[2:0] being the clock decimal + * division factor (1, 2, 4, ..., 128). Any successive call violating + * this delay, leads to unpredictable results. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OC_ConfigChannel(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig, + uint32_t Channel) +{ + HAL_StatusTypeDef status; + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + assert_param(IS_LPTIM_OC_POLARITY(sConfig->OCPolarity)); + assert_param(IS_LPTIM_PULSE(sConfig->Pulse)); + + hlptim->State = HAL_LPTIM_STATE_BUSY; + + switch (Channel) + { + case LPTIM_CHANNEL_1: + { + /* Check the parameters */ + assert_param(IS_LPTIM_CC1_INSTANCE(hlptim->Instance)); + + /* Configure the LPTIM Channel 1 in Output Compare */ + status = LPTIM_OC1_SetConfig(hlptim, sConfig); + if (status != HAL_OK) + { + return status; + } + break; + } + case LPTIM_CHANNEL_2: + { + /* Check the parameters */ + assert_param(IS_LPTIM_CC2_INSTANCE(hlptim->Instance)); + + /* Configure the LPTIM Channel 2 in Output Compare */ + status = LPTIM_OC2_SetConfig(hlptim, sConfig); + if (status != HAL_OK) + { + return status; + } + break; + } + default: + break; + } + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief + * @param hlptim LPTIM handle + * @param sConfig The input configuration structure + * @param Channel LPTIM Channel to be configured + * This parameter can be one of the following values: + * @arg LPTIM_CHANNEL_1: LPTIM Channel 1 selected + * @arg LPTIM_CHANNEL_2: LPTIM Channel 2 selected + * @note Successive calls to HAL_LPTIM_IC_ConfigChannel can only be performed + * after a delay that must be greater or equal than the value of + * (PRESC x 3) kernel clock cycles, PRESC[2:0] being the clock decimal + * division factor (1, 2, 4, ..., 128). Any successive call violating + * this delay, leads to unpredictable results. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_IC_ConfigChannel(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig, + uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_CCX_INSTANCE(hlptim->Instance, Channel)); + assert_param(IS_LPTIM_IC_PRESCALER(sConfig->ICPrescaler)); + assert_param(IS_LPTIM_IC_POLARITY(sConfig->ICPolarity)); + assert_param(IS_LPTIM_IC_FILTER(sConfig->ICFilter)); + + hlptim->State = HAL_LPTIM_STATE_BUSY; + + switch (Channel) + { + case LPTIM_CHANNEL_1: + { + /* Check the parameters */ + assert_param(IS_LPTIM_CC1_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_IC1_SOURCE(hlptim->Instance, sConfig->ICInputSource)); + + /* Configure the LPTIM Channel 1 in Input Capture */ + LPTIM_IC1_SetConfig(hlptim, sConfig); + break; + } + case LPTIM_CHANNEL_2: + { + /* Check the parameters */ + assert_param(IS_LPTIM_CC2_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_IC2_SOURCE(hlptim->Instance, sConfig->ICInputSource)); + + /* Configure the LPTIM Channel 2 in Input Capture */ + LPTIM_IC2_SetConfig(hlptim, sConfig); + break; + } + default: + break; + } + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + /* Return function status */ + return HAL_OK; +} +/** + * @} + */ + +/** @defgroup LPTIM_Exported_Functions_Group4 LPTIM IRQ handler and callbacks + * @brief LPTIM IRQ handler. + * +@verbatim + ============================================================================== + ##### LPTIM IRQ handler and callbacks ##### + ============================================================================== +[..] This section provides LPTIM IRQ handler and callback functions called within + the IRQ handler: + (+) LPTIM interrupt request handler + (+) Compare match Callback + (+) Auto-reload match Callback + (+) External trigger event detection Callback + (+) Compare register write complete Callback + (+) Auto-reload register write complete Callback + (+) Up-counting direction change Callback + (+) Down-counting direction change Callback + +@endverbatim + * @{ + */ + +/** + * @brief Handle LPTIM interrupt request. + * @param hlptim LPTIM handle + * @retval None + */ +void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim) +{ + /* Capture Compare 1 interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC1) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC1) != RESET) + { + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC1); + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + + /* Input capture event */ + if ((hlptim->Instance->CCMR1 & LPTIM_CCMR1_CC1SEL) != 0x00U) + { +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->IC_CaptureCallback(hlptim); +#else + HAL_LPTIM_IC_CaptureCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->CompareMatchCallback(hlptim); +#else + HAL_LPTIM_CompareMatchCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; + } + } + + /* Capture Compare 2 interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC2) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC2) != RESET) + { + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC2); + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + + /* Input capture event */ + if ((hlptim->Instance->CCMR1 & LPTIM_CCMR1_CC2SEL) != 0x00U) + { +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->IC_CaptureCallback(hlptim); +#else + HAL_LPTIM_IC_CaptureCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->CompareMatchCallback(hlptim); +#else + HAL_LPTIM_CompareMatchCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; + } + } + + /* Over Capture 1 interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC1O) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC1O) != RESET) + { + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC1O); + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + + /* Over capture event */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->IC_OverCaptureCallback(hlptim); +#else + HAL_LPTIM_IC_OverCaptureCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; + } + } + + /* Over Capture 2 interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CC2O) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_FLAG_CC2O) != RESET) + { + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CC2O); + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + + /* Over capture event */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->IC_OverCaptureCallback(hlptim); +#else + HAL_LPTIM_IC_OverCaptureCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; + } + } + + /* Autoreload match interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARRM) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_ARRM) != RESET) + { + /* Clear Autoreload match flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARRM); + + /* Autoreload match Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->AutoReloadMatchCallback(hlptim); +#else + HAL_LPTIM_AutoReloadMatchCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Trigger detected interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_EXTTRIG) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_EXTTRIG) != RESET) + { + /* Clear Trigger detected flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_EXTTRIG); + + /* Trigger detected callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->TriggerCallback(hlptim); +#else + HAL_LPTIM_TriggerCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Compare write interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMP1OK) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_CMP1OK) != RESET) + { + /* Clear Compare write flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + /* Compare write Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->CompareWriteCallback(hlptim); +#else + HAL_LPTIM_CompareWriteCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Compare write interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMP2OK) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_CMP2OK) != RESET) + { + /* Clear Compare write flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP2OK); + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + /* Compare write Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->CompareWriteCallback(hlptim); +#else + HAL_LPTIM_CompareWriteCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Autoreload write interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARROK) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_ARROK) != RESET) + { + /* Clear Autoreload write flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); + + /* Autoreload write Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->AutoReloadWriteCallback(hlptim); +#else + HAL_LPTIM_AutoReloadWriteCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Direction counter changed from Down to Up interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_UP) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_UP) != RESET) + { + /* Clear Direction counter changed from Down to Up flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_UP); + + /* Direction counter changed from Down to Up Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->DirectionUpCallback(hlptim); +#else + HAL_LPTIM_DirectionUpCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Direction counter changed from Up to Down interrupt */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_DOWN) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_DOWN) != RESET) + { + /* Clear Direction counter changed from Up to Down flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DOWN); + + /* Direction counter changed from Up to Down Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->DirectionDownCallback(hlptim); +#else + HAL_LPTIM_DirectionDownCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Repetition counter underflowed (or contains zero) and the LPTIM counter + overflowed */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_UPDATE) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_UPDATE) != RESET) + { + /* Clear update event flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_UPDATE); + + /* Update event Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->UpdateEventCallback(hlptim); +#else + HAL_LPTIM_UpdateEventCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } + + /* Successful APB bus write to repetition counter register */ + if (__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_REPOK) != RESET) + { + if (__HAL_LPTIM_GET_IT_SOURCE(hlptim, LPTIM_IT_REPOK) != RESET) + { + /* Clear successful APB bus write to repetition counter flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_REPOK); + + /* Successful APB bus write to repetition counter Callback */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->RepCounterWriteCallback(hlptim); +#else + HAL_LPTIM_RepCounterWriteCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Compare match callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_CompareMatchCallback could be implemented in the user file + */ +} + +/** + * @brief Autoreload match callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_AutoReloadMatchCallback could be implemented in the user file + */ +} + +/** + * @brief Trigger detected callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_TriggerCallback could be implemented in the user file + */ +} + +/** + * @brief Compare write callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_CompareWriteCallback could be implemented in the user file + */ +} + +/** + * @brief Autoreload write callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_AutoReloadWriteCallback could be implemented in the user file + */ +} + +/** + * @brief Direction counter changed from Down to Up callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_DirectionUpCallback could be implemented in the user file + */ +} + +/** + * @brief Direction counter changed from Up to Down callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_DirectionDownCallback could be implemented in the user file + */ +} + +/** + * @brief Repetition counter underflowed (or contains zero) and LPTIM counter overflowed callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_UpdateEventCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_UpdateEventCallback could be implemented in the user file + */ +} + +/** + * @brief Successful APB bus write to repetition counter register callback in non-blocking mode. + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_RepCounterWriteCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_RepCounterWriteCallback could be implemented in the user file + */ +} + +/** + * @brief Input Capture callback in non-blocking mode + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_IC_CaptureCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_IC_CaptureCallback could be implemented in the user file + */ +} + +/** + * @brief Over Capture callback in non-blocking mode + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_IC_OverCaptureCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_IC_OverCaptureCallback could be implemented in the user file + */ +} + +/** + * @brief Input Capture half complete callback in non-blocking mode + * @param hlptim LPTIM IC handle + * @retval None + */ +__weak void HAL_LPTIM_IC_CaptureHalfCpltCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_IC_CaptureHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Update event half complete callback in non-blocking mode + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_UpdateEventHalfCpltCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_UpdateEventHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Error callback in non-blocking mode + * @param hlptim LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_ErrorCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hlptim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LPTIM_ErrorCallback could be implemented in the user file + */ +} + + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User LPTIM callback to be used instead of the weak predefined callback + * @param hlptim LPTIM handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_LPTIM_MSPINIT_CB_ID LPTIM Base Msp Init Callback ID + * @arg @ref HAL_LPTIM_MSPDEINIT_CB_ID LPTIM Base Msp DeInit Callback ID + * @arg @ref HAL_LPTIM_COMPARE_MATCH_CB_ID Compare match Callback ID + * @arg @ref HAL_LPTIM_AUTORELOAD_MATCH_CB_ID Auto-reload match Callback ID + * @arg @ref HAL_LPTIM_TRIGGER_CB_ID External trigger event detection Callback ID + * @arg @ref HAL_LPTIM_COMPARE_WRITE_CB_ID Compare register write complete Callback ID + * @arg @ref HAL_LPTIM_AUTORELOAD_WRITE_CB_ID Auto-reload register write complete Callback ID + * @arg @ref HAL_LPTIM_DIRECTION_UP_CB_ID Up-counting direction change Callback ID + * @arg @ref HAL_LPTIM_DIRECTION_DOWN_CB_ID Down-counting direction change Callback ID + * @arg @ref HAL_LPTIM_UPDATE_EVENT_CB_ID Update event detection Callback ID + * @arg @ref HAL_LPTIM_REP_COUNTER_WRITE_CB_ID Repetition counter register write complete Callback ID + * @arg @ref HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID Update event Half detection Callback ID + * @arg @ref HAL_LPTIM_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_LPTIM_IC_CAPTURE_CB_ID Input Capture Callback ID + * @arg @ref HAL_LPTIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID + * @arg @ref HAL_LPTIM_OVER_CAPTURE_CB_ID Over Capture Callback ID + * @param pCallback pointer to the callback function + * @retval status + */ +HAL_StatusTypeDef HAL_LPTIM_RegisterCallback(LPTIM_HandleTypeDef *hlptim, + HAL_LPTIM_CallbackIDTypeDef CallbackID, + pLPTIM_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + if (hlptim->State == HAL_LPTIM_STATE_READY) + { + switch (CallbackID) + { + case HAL_LPTIM_MSPINIT_CB_ID : + hlptim->MspInitCallback = pCallback; + break; + + case HAL_LPTIM_MSPDEINIT_CB_ID : + hlptim->MspDeInitCallback = pCallback; + break; + + case HAL_LPTIM_COMPARE_MATCH_CB_ID : + hlptim->CompareMatchCallback = pCallback; + break; + + case HAL_LPTIM_AUTORELOAD_MATCH_CB_ID : + hlptim->AutoReloadMatchCallback = pCallback; + break; + + case HAL_LPTIM_TRIGGER_CB_ID : + hlptim->TriggerCallback = pCallback; + break; + + case HAL_LPTIM_COMPARE_WRITE_CB_ID : + hlptim->CompareWriteCallback = pCallback; + break; + + case HAL_LPTIM_AUTORELOAD_WRITE_CB_ID : + hlptim->AutoReloadWriteCallback = pCallback; + break; + + case HAL_LPTIM_DIRECTION_UP_CB_ID : + hlptim->DirectionUpCallback = pCallback; + break; + + case HAL_LPTIM_DIRECTION_DOWN_CB_ID : + hlptim->DirectionDownCallback = pCallback; + break; + + case HAL_LPTIM_UPDATE_EVENT_CB_ID : + hlptim->UpdateEventCallback = pCallback; + break; + + case HAL_LPTIM_REP_COUNTER_WRITE_CB_ID : + hlptim->RepCounterWriteCallback = pCallback; + break; + + case HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID : + hlptim->UpdateEventHalfCpltCallback = pCallback; + break; + + case HAL_LPTIM_ERROR_CB_ID : + hlptim->ErrorCallback = pCallback; + break; + + case HAL_LPTIM_IC_CAPTURE_CB_ID : + hlptim->IC_CaptureCallback = pCallback; + break; + + case HAL_LPTIM_IC_CAPTURE_HALF_CB_ID : + hlptim->IC_CaptureHalfCpltCallback = pCallback; + break; + + case HAL_LPTIM_OVER_CAPTURE_CB_ID : + hlptim->IC_OverCaptureCallback = pCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hlptim->State == HAL_LPTIM_STATE_RESET) + { + switch (CallbackID) + { + case HAL_LPTIM_MSPINIT_CB_ID : + hlptim->MspInitCallback = pCallback; + break; + + case HAL_LPTIM_MSPDEINIT_CB_ID : + hlptim->MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a LPTIM callback + * LLPTIM callback is redirected to the weak predefined callback + * @param hlptim LPTIM handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_LPTIM_MSPINIT_CB_ID LPTIM Base Msp Init Callback ID + * @arg @ref HAL_LPTIM_MSPDEINIT_CB_ID LPTIM Base Msp DeInit Callback ID + * @arg @ref HAL_LPTIM_COMPARE_MATCH_CB_ID Compare match Callback ID + * @arg @ref HAL_LPTIM_AUTORELOAD_MATCH_CB_ID Auto-reload match Callback ID + * @arg @ref HAL_LPTIM_TRIGGER_CB_ID External trigger event detection Callback ID + * @arg @ref HAL_LPTIM_COMPARE_WRITE_CB_ID Compare register write complete Callback ID + * @arg @ref HAL_LPTIM_AUTORELOAD_WRITE_CB_ID Auto-reload register write complete Callback ID + * @arg @ref HAL_LPTIM_DIRECTION_UP_CB_ID Up-counting direction change Callback ID + * @arg @ref HAL_LPTIM_DIRECTION_DOWN_CB_ID Down-counting direction change Callback ID + * @arg @ref HAL_LPTIM_UPDATE_EVENT_CB_ID Update event detection Callback ID + * @arg @ref HAL_LPTIM_REP_COUNTER_WRITE_CB_ID Repetition counter register write complete Callback ID + * @arg @ref HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID Update event Half detection Callback ID + * @arg @ref HAL_LPTIM_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_LPTIM_IC_CAPTURE_CB_ID Input Capture Callback ID + * @arg @ref HAL_LPTIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID + * @arg @ref HAL_LPTIM_OVER_CAPTURE_CB_ID Over Capture Callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_LPTIM_UnRegisterCallback(LPTIM_HandleTypeDef *hlptim, + HAL_LPTIM_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hlptim->State == HAL_LPTIM_STATE_READY) + { + switch (CallbackID) + { + case HAL_LPTIM_MSPINIT_CB_ID : + /* Legacy weak MspInit Callback */ + hlptim->MspInitCallback = HAL_LPTIM_MspInit; + break; + + case HAL_LPTIM_MSPDEINIT_CB_ID : + /* Legacy weak Msp DeInit Callback */ + hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit; + break; + + case HAL_LPTIM_COMPARE_MATCH_CB_ID : + /* Legacy weak Compare match Callback */ + hlptim->CompareMatchCallback = HAL_LPTIM_CompareMatchCallback; + break; + + case HAL_LPTIM_AUTORELOAD_MATCH_CB_ID : + /* Legacy weak Auto-reload match Callback */ + hlptim->AutoReloadMatchCallback = HAL_LPTIM_AutoReloadMatchCallback; + break; + + case HAL_LPTIM_TRIGGER_CB_ID : + /* Legacy weak External trigger event detection Callback */ + hlptim->TriggerCallback = HAL_LPTIM_TriggerCallback; + break; + + case HAL_LPTIM_COMPARE_WRITE_CB_ID : + /* Legacy weak Compare register write complete Callback */ + hlptim->CompareWriteCallback = HAL_LPTIM_CompareWriteCallback; + break; + + case HAL_LPTIM_AUTORELOAD_WRITE_CB_ID : + /* Legacy weak Auto-reload register write complete Callback */ + hlptim->AutoReloadWriteCallback = HAL_LPTIM_AutoReloadWriteCallback; + break; + + case HAL_LPTIM_DIRECTION_UP_CB_ID : + /* Legacy weak Up-counting direction change Callback */ + hlptim->DirectionUpCallback = HAL_LPTIM_DirectionUpCallback; + break; + + case HAL_LPTIM_DIRECTION_DOWN_CB_ID : + /* Legacy weak Down-counting direction change Callback */ + hlptim->DirectionDownCallback = HAL_LPTIM_DirectionDownCallback; + break; + + case HAL_LPTIM_UPDATE_EVENT_CB_ID : + /* Legacy weak Update event detection Callback */ + hlptim->UpdateEventCallback = HAL_LPTIM_UpdateEventCallback; + break; + + case HAL_LPTIM_REP_COUNTER_WRITE_CB_ID : + /* Legacy weak Repetition counter register write complete Callback */ + hlptim->RepCounterWriteCallback = HAL_LPTIM_RepCounterWriteCallback; + break; + + case HAL_LPTIM_UPDATE_EVENT_HALF_CB_ID : + /* Legacy weak Update event half complete detection Callback */ + hlptim->UpdateEventHalfCpltCallback = HAL_LPTIM_UpdateEventHalfCpltCallback; + break; + + case HAL_LPTIM_ERROR_CB_ID : + /* Legacy weak error Callback */ + hlptim->ErrorCallback = HAL_LPTIM_ErrorCallback; + break; + + case HAL_LPTIM_IC_CAPTURE_CB_ID : + /* Legacy weak IC Capture Callback */ + hlptim->IC_CaptureCallback = HAL_LPTIM_IC_CaptureCallback; + break; + + case HAL_LPTIM_IC_CAPTURE_HALF_CB_ID : + /* Legacy weak IC Capture half complete Callback */ + hlptim->IC_CaptureHalfCpltCallback = HAL_LPTIM_IC_CaptureHalfCpltCallback; + break; + + case HAL_LPTIM_OVER_CAPTURE_CB_ID : + /* Legacy weak IC over capture Callback */ + hlptim->IC_OverCaptureCallback = HAL_LPTIM_IC_OverCaptureCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hlptim->State == HAL_LPTIM_STATE_RESET) + { + switch (CallbackID) + { + case HAL_LPTIM_MSPINIT_CB_ID : + /* Legacy weak MspInit Callback */ + hlptim->MspInitCallback = HAL_LPTIM_MspInit; + break; + + case HAL_LPTIM_MSPDEINIT_CB_ID : + /* Legacy weak Msp DeInit Callback */ + hlptim->MspDeInitCallback = HAL_LPTIM_MspDeInit; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup LPTIM_Group5 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 LPTIM handle state. + * @param hlptim LPTIM handle + * @retval HAL state + */ +HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(const LPTIM_HandleTypeDef *hlptim) +{ + /* Return LPTIM handle state */ + return hlptim->State; +} + +/** + * @} + */ + + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup LPTIM_Private_Functions LPTIM Private Functions + * @{ + */ +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) +/** + * @brief Reset interrupt callbacks to the legacy weak callbacks. + * @param lptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @retval None + */ +static void LPTIM_ResetCallback(LPTIM_HandleTypeDef *lptim) +{ + /* Reset the LPTIM callback to the legacy weak callbacks */ + lptim->CompareMatchCallback = HAL_LPTIM_CompareMatchCallback; + lptim->AutoReloadMatchCallback = HAL_LPTIM_AutoReloadMatchCallback; + lptim->TriggerCallback = HAL_LPTIM_TriggerCallback; + lptim->CompareWriteCallback = HAL_LPTIM_CompareWriteCallback; + lptim->AutoReloadWriteCallback = HAL_LPTIM_AutoReloadWriteCallback; + lptim->DirectionUpCallback = HAL_LPTIM_DirectionUpCallback; + lptim->DirectionDownCallback = HAL_LPTIM_DirectionDownCallback; + lptim->UpdateEventCallback = HAL_LPTIM_UpdateEventCallback; + lptim->RepCounterWriteCallback = HAL_LPTIM_RepCounterWriteCallback; + lptim->UpdateEventHalfCpltCallback = HAL_LPTIM_UpdateEventHalfCpltCallback; + lptim->IC_CaptureCallback = HAL_LPTIM_IC_CaptureCallback; + lptim->IC_CaptureHalfCpltCallback = HAL_LPTIM_IC_CaptureHalfCpltCallback; + lptim->IC_OverCaptureCallback = HAL_LPTIM_IC_OverCaptureCallback; + lptim->ErrorCallback = HAL_LPTIM_ErrorCallback; +} +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + +/** + * @brief LPTimer Wait for flag set + * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @param flag The lptim flag + * @retval HAL status + */ +static HAL_StatusTypeDef LPTIM_WaitForFlag(const LPTIM_HandleTypeDef *hlptim, uint32_t flag) +{ + HAL_StatusTypeDef result = HAL_OK; + uint32_t count = TIMEOUT * (SystemCoreClock / 20UL / 1000UL); + do + { + count--; + if (count == 0UL) + { + result = HAL_TIMEOUT; + } + } while ((!(__HAL_LPTIM_GET_FLAG((hlptim), (flag)))) && (count != 0UL)); + + return result; +} + +/** + * @brief LPTIM DMA error callback + * @param hdma pointer to DMA handle. + * @retval None + */ +void LPTIM_DMAError(DMA_HandleTypeDef *hdma) +{ + LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hlptim->State = HAL_LPTIM_STATE_READY; + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->ErrorCallback(hlptim); +#else + HAL_LPTIM_ErrorCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ +} + +/** + * @brief LPTIM DMA Capture complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void LPTIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) +{ + LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hlptim->State = HAL_LPTIM_STATE_READY; + + if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + } + else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->IC_CaptureCallback(hlptim); +#else + HAL_LPTIM_IC_CaptureCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief LPTIM DMA Capture half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void LPTIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma) +{ + LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hlptim->State = HAL_LPTIM_STATE_READY; + + if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + } + else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->IC_CaptureHalfCpltCallback(hlptim); +#else + HAL_LPTIM_IC_CaptureHalfCpltCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief LPTIM DMA Update event complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void LPTIM_DMAUpdateEventCplt(DMA_HandleTypeDef *hdma) +{ + LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hlptim->State = HAL_LPTIM_STATE_READY; + + if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + } + else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->UpdateEventCallback(hlptim); +#else + HAL_LPTIM_UpdateEventCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief LPTIM DMA Capture half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void LPTIM_DMAUpdateEventHalfCplt(DMA_HandleTypeDef *hdma) +{ + LPTIM_HandleTypeDef *hlptim = (LPTIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hlptim->State = HAL_LPTIM_STATE_READY; + + if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC1]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_1; + } + else if (hdma == hlptim->hdma[LPTIM_DMA_ID_CC2]) + { + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_2; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_LPTIM_REGISTER_CALLBACKS == 1) + hlptim->UpdateEventHalfCpltCallback(hlptim); +#else + HAL_LPTIM_UpdateEventHalfCpltCallback(hlptim); +#endif /* USE_HAL_LPTIM_REGISTER_CALLBACKS */ + + hlptim->Channel = HAL_LPTIM_ACTIVE_CHANNEL_CLEARED; +} +/** + * @brief LPTimer Output Compare 1 configuration + * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @param sConfig The output configuration structure + * @retval None + */ +static HAL_StatusTypeDef LPTIM_OC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig) +{ + uint32_t tmpccmr1; + uint32_t tmpcfgr; + + tmpccmr1 = hlptim->Instance->CCMR1; + tmpccmr1 &= ~(LPTIM_CCMR1_CC1P_Msk | LPTIM_CCMR1_CC1SEL_Msk); + + if ((hlptim->Instance == LPTIM4) || (hlptim->Instance == LPTIM5)) + { + tmpcfgr = hlptim->Instance->CFGR; + tmpcfgr &= ~LPTIM_CFGR_WAVPOL_Msk; + tmpcfgr |= sConfig->OCPolarity << LPTIM_CFGR_WAVPOL_Pos; + + /* Write to CFGR register */ + hlptim->Instance->CFGR = tmpcfgr; + } + else + { + tmpccmr1 |= sConfig->OCPolarity << LPTIM_CCMR1_CC1P_Pos; + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP1OK); + + /* Write to CCR1 register */ + __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_1, sConfig->Pulse); + + /* Wait for the completion of the write operation to the LPTIM_CCR1 register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP1OK) == HAL_TIMEOUT) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Write to CCMR1 register */ + hlptim->Instance->CCMR1 = tmpccmr1; + + return HAL_OK; +} + +/** + * @brief LPTimer Output Compare 2 configuration + * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @param sConfig The output configuration structure + * @retval None + */ +static HAL_StatusTypeDef LPTIM_OC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_OC_ConfigTypeDef *sConfig) +{ + uint32_t tmpccmr1; + + tmpccmr1 = hlptim->Instance->CCMR1; + tmpccmr1 &= ~(LPTIM_CCMR1_CC2P_Msk | LPTIM_CCMR1_CC2SEL_Msk); + tmpccmr1 |= sConfig->OCPolarity << LPTIM_CCMR1_CC2P_Pos; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Clear flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMP2OK); + + /* Write to CCR2 register */ + __HAL_LPTIM_COMPARE_SET(hlptim, LPTIM_CHANNEL_2, sConfig->Pulse); + + /* Wait for the completion of the write operation to the LPTIM_CCR2 register */ + if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_CMP2OK) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Write to CCMR1 register */ + hlptim->Instance->CCMR1 = tmpccmr1; + + return HAL_OK; +} + +/** + * @brief LPTimer Input Capture 1 configuration + * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @param sConfig The input configuration structure + * @retval None + */ +static void LPTIM_IC1_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig) +{ + uint32_t tmpccmr1; + uint32_t tmpcfgr2; + + tmpccmr1 = hlptim->Instance->CCMR1; + tmpccmr1 &= ~(LPTIM_CCMR1_IC1PSC_Msk | LPTIM_CCMR1_CC1P_Msk | LPTIM_CCMR1_IC1F_Msk); + tmpccmr1 |= sConfig->ICPrescaler | + sConfig->ICPolarity | + sConfig->ICFilter | + LPTIM_CCMR1_CC1SEL; + + tmpcfgr2 = hlptim->Instance->CFGR2; + tmpcfgr2 &= ~(LPTIM_CFGR2_IC1SEL_Msk); + tmpcfgr2 |= sConfig->ICInputSource; + + /* Write to CCMR1 register */ + hlptim->Instance->CCMR1 = tmpccmr1; + + /* Write to CFGR2 register */ + hlptim->Instance->CFGR2 = tmpcfgr2; +} + +/** + * @brief LPTimer Input Capture 2 configuration + * @param hlptim pointer to a LPTIM_HandleTypeDef structure that contains + * the configuration information for LPTIM module. + * @param sConfig The input configuration structure + * @retval None + */ +static void LPTIM_IC2_SetConfig(LPTIM_HandleTypeDef *hlptim, const LPTIM_IC_ConfigTypeDef *sConfig) +{ + uint32_t tmpccmr1; + uint32_t tmpcfgr2; + + tmpccmr1 = hlptim->Instance->CCMR1; + tmpccmr1 &= ~(LPTIM_CCMR1_IC2PSC_Msk | LPTIM_CCMR1_CC2P_Msk | LPTIM_CCMR1_IC2F_Msk); + tmpccmr1 |= (sConfig->ICPrescaler << (LPTIM_CCMR1_IC2PSC_Pos - LPTIM_CCMR1_IC1PSC_Pos)) | + (sConfig->ICPolarity << (LPTIM_CCMR1_CC2P_Pos - LPTIM_CCMR1_CC1P_Pos)) | + (sConfig->ICFilter << (LPTIM_CCMR1_IC2F_Pos - LPTIM_CCMR1_IC1F_Pos)) | + LPTIM_CCMR1_CC2SEL; + + tmpcfgr2 = hlptim->Instance->CFGR2; + tmpcfgr2 &= ~(LPTIM_CFGR2_IC2SEL_Msk); + tmpcfgr2 |= sConfig->ICInputSource; + + /* Write to CCMR1 register */ + hlptim->Instance->CCMR1 = tmpccmr1; + + /* Write to CFGR2 register */ + hlptim->Instance->CFGR2 = tmpcfgr2; +} + +/** + * @brief Start the DMA data transfer. + * @param hdma DMA handle + * @param src The source memory Buffer address. + * @param dst The destination memory Buffer address. + * @param length The size of a source block transfer in byte. + * @retval HAL status + */ +HAL_StatusTypeDef LPTIM_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t src, uint32_t dst, + uint32_t length) +{ + HAL_StatusTypeDef status; + + /* Enable the DMA channel */ + if ((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hdma->LinkedListQueue != 0U) && (hdma->LinkedListQueue->Head != 0U)) + { + /* Enable the DMA channel */ + hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = length; + hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)src; + hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)dst; + + status = HAL_DMAEx_List_Start_IT(hdma); + } + else + { + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hdma, src, dst, length); + } + + return status; +} +/** + * @} + */ +#endif /* LPTIM1 || LPTIM2 || LPTIM3 || LPTIM4 || LPTIM5 */ + +#endif /* HAL_LPTIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc.c index e68cb979f..b8e7abe6a 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc.c @@ -1,2219 +1,2218 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_ltdc.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The LTDC HAL driver can be used as follows: - - (#) Declare a LTDC_HandleTypeDef handle structure, for example: LTDC_HandleTypeDef hltdc; - - (#) Initialize the LTDC low level resources by implementing the HAL_LTDC_MspInit() API: - (##) Enable the LTDC interface clock - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the LTDC interrupt priority - (+++) Enable the NVIC LTDC IRQ Channel - - (#) Initialize the required configuration through the 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 - - *** Configuration *** - ========================= - [..] - (#) Program the required configuration through the 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_ProgramLineEvent() - 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() and HAL_LTDC_SetAddress(). - - (#) Variant functions with _NoReload suffix allows to set the LTDC configuration/settings without immediate reload. - This is useful in case when the program requires to modify serval LTDC settings (on one or both layers) - then applying(reload) these settings in one shot by calling the function HAL_LTDC_Reload(). - - After calling the _NoReload functions to set different color/format/layer settings, - the program shall call the function HAL_LTDC_Reload() to apply(reload) these settings. - Function HAL_LTDC_Reload() can be called with the parameter ReloadType set to LTDC_RELOAD_IMMEDIATE if - an immediate reload is required. - Function HAL_LTDC_Reload() can be called with the parameter ReloadType set to LTDC_RELOAD_VERTICAL_BLANKING if - the reload should be done in the next vertical blanking period, - this option allows to avoid display flicker by applying the new settings during the vertical blanking period. - - - (#) 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 an LTDC Layer. - (+) __HAL_LTDC_LAYER_DISABLE: Disable an LTDC Layer. - (+) __HAL_LTDC_RELOAD_IMMEDIATE_CONFIG: Reload Layer Configuration. - (+) __HAL_LTDC_GET_FLAG: Get the LTDC pending flags. - (+) __HAL_LTDC_CLEAR_FLAG: Clear the LTDC pending flags. - (+) __HAL_LTDC_ENABLE_IT: Enable the specified LTDC interrupts. - (+) __HAL_LTDC_DISABLE_IT: Disable the specified LTDC interrupts. - (+) __HAL_LTDC_GET_IT_SOURCE: Check whether the specified LTDC interrupt has occurred or not. - - [..] - (@) You can refer to the LTDC HAL driver header file for more useful macros - - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_LTDC_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use function HAL_LTDC_RegisterCallback() to register a callback. - - [..] - Function HAL_LTDC_RegisterCallback() allows to register following callbacks: - (+) LineEventCallback : LTDC Line Event Callback. - (+) ReloadEventCallback : LTDC Reload Event Callback. - (+) ErrorCallback : LTDC Error Callback - (+) MspInitCallback : LTDC MspInit. - (+) MspDeInitCallback : LTDC MspDeInit. - [..] - This function takes as parameters the HAL peripheral handle, the callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_LTDC_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_LTDC_UnRegisterCallback() takes as parameters the HAL peripheral handle - and the callback ID. - [..] - This function allows to reset following callbacks: - (+) LineEventCallback : LTDC Line Event Callback - (+) ReloadEventCallback : LTDC Reload Event Callback - (+) ErrorCallback : LTDC Error Callback - (+) MspInitCallback : LTDC MspInit - (+) MspDeInitCallback : LTDC MspDeInit. - - [..] - By default, after the HAL_LTDC_Init and when the state is HAL_LTDC_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_LTDC_LineEventCallback(), HAL_LTDC_ErrorCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak (surcharged) functions in the HAL_LTDC_Init() and HAL_LTDC_DeInit() - only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_LTDC_Init() and HAL_LTDC_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in HAL_LTDC_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_LTDC_STATE_READY or HAL_LTDC_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_LTDC_RegisterCallback() before calling HAL_LTDC_DeInit() - or HAL_LTDC_Init() function. - - [..] - When the compilation define USE_HAL_LTDC_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_LTDC_MODULE_ENABLED - -#if defined (LTDC) - -/** @defgroup LTDC LTDC - * @brief LTDC HAL module driver - * @{ - */ - - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup LTDC_Private_Define LTDC Private Define - * @{ - */ -#define LTDC_TIMEOUT_VALUE ((uint32_t)100U) /* 100ms */ -/** - * @} - */ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -static void LTDC_SetConfig(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx); -/* Private functions ---------------------------------------------------------*/ - -/** @defgroup LTDC_Exported_Functions LTDC Exported Functions - * @{ - */ - -/** @defgroup LTDC_Exported_Functions_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 Initialize the LTDC according to the specified parameters in the LTDC_InitTypeDef. - * @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; - uint32_t tmp1; - - /* 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 (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) - if (hltdc->State == HAL_LTDC_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hltdc->Lock = HAL_UNLOCKED; - - /* Reset the LTDC callback to the legacy weak callbacks */ - hltdc->LineEventCallback = HAL_LTDC_LineEventCallback; /* Legacy weak LineEventCallback */ - hltdc->ReloadEventCallback = HAL_LTDC_ReloadEventCallback; /* Legacy weak ReloadEventCallback */ - hltdc->ErrorCallback = HAL_LTDC_ErrorCallback; /* Legacy weak ErrorCallback */ - - if (hltdc->MspInitCallback == NULL) - { - hltdc->MspInitCallback = HAL_LTDC_MspInit; - } - /* Init the low level hardware */ - hltdc->MspInitCallback(hltdc); - } -#else - if (hltdc->State == HAL_LTDC_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hltdc->Lock = HAL_UNLOCKED; - /* Init the low level hardware */ - HAL_LTDC_MspInit(hltdc); - } -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Configure 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); - - /* Set Synchronization size */ - hltdc->Instance->SSCR &= ~(LTDC_SSCR_VSH | LTDC_SSCR_HSW); - tmp = (hltdc->Init.HorizontalSync << 16U); - hltdc->Instance->SSCR |= (tmp | hltdc->Init.VerticalSync); - - /* Set Accumulated Back porch */ - hltdc->Instance->BPCR &= ~(LTDC_BPCR_AVBP | LTDC_BPCR_AHBP); - tmp = (hltdc->Init.AccumulatedHBP << 16U); - hltdc->Instance->BPCR |= (tmp | hltdc->Init.AccumulatedVBP); - - /* Set Accumulated Active Width */ - hltdc->Instance->AWCR &= ~(LTDC_AWCR_AAH | LTDC_AWCR_AAW); - tmp = (hltdc->Init.AccumulatedActiveW << 16U); - hltdc->Instance->AWCR |= (tmp | hltdc->Init.AccumulatedActiveH); - - /* Set Total Width */ - hltdc->Instance->TWCR &= ~(LTDC_TWCR_TOTALH | LTDC_TWCR_TOTALW); - tmp = (hltdc->Init.TotalWidth << 16U); - hltdc->Instance->TWCR |= (tmp | hltdc->Init.TotalHeigh); - - /* Set the background color value */ - tmp = ((uint32_t)(hltdc->Init.Backcolor.Green) << 8U); - tmp1 = ((uint32_t)(hltdc->Init.Backcolor.Red) << 16U); - 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 and FIFO underrun interrupts */ - __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_TE | LTDC_IT_FU); - - /* Enable LTDC by setting LTDCEN bit */ - __HAL_LTDC_ENABLE(hltdc); - - /* Initialize the error code */ - hltdc->ErrorCode = HAL_LTDC_ERROR_NONE; - - /* Initialize the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - return HAL_OK; -} - -/** - * @brief De-initialize the LTDC peripheral. - * @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) -{ - uint32_t tickstart; - - /* Check the LTDC peripheral state */ - if (hltdc == NULL) - { - return HAL_ERROR; - } - - /* Check function parameters */ - assert_param(IS_LTDC_ALL_INSTANCE(hltdc->Instance)); - - /* Disable LTDC Layer 1 */ - __HAL_LTDC_LAYER_DISABLE(hltdc, LTDC_LAYER_1); - -#if defined(LTDC_Layer2_BASE) - /* Disable LTDC Layer 2 */ - __HAL_LTDC_LAYER_DISABLE(hltdc, LTDC_LAYER_2); -#endif /* LTDC_Layer2_BASE */ - - /* Reload during vertical blanking period */ - __HAL_LTDC_VERTICAL_BLANKING_RELOAD_CONFIG(hltdc); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait for VSYNC Interrupt */ - while (READ_BIT(hltdc->Instance->CDSR, LTDC_CDSR_VSYNCS) == 0U) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > LTDC_TIMEOUT_VALUE) - { - break; - } - } - - /* Disable LTDC */ - __HAL_LTDC_DISABLE(hltdc); - -#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) - if (hltdc->MspDeInitCallback == NULL) - { - hltdc->MspDeInitCallback = HAL_LTDC_MspDeInit; - } - /* DeInit the low level hardware */ - hltdc->MspDeInitCallback(hltdc); -#else - /* DeInit the low level hardware */ - HAL_LTDC_MspDeInit(hltdc); -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - - /* Initialize 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 Initialize 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 De-initialize 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hltdc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LTDC_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User LTDC Callback - * To be used instead of the weak predefined callback - * @param hltdc ltdc handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_LTDC_LINE_EVENT_CB_ID Line Event Callback ID - * @arg @ref HAL_LTDC_RELOAD_EVENT_CB_ID Reload Event Callback ID - * @arg @ref HAL_LTDC_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_LTDC_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_LTDC_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_LTDC_RegisterCallback(LTDC_HandleTypeDef *hltdc, HAL_LTDC_CallbackIDTypeDef CallbackID, - pLTDC_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hltdc); - - if (hltdc->State == HAL_LTDC_STATE_READY) - { - switch (CallbackID) - { - case HAL_LTDC_LINE_EVENT_CB_ID : - hltdc->LineEventCallback = pCallback; - break; - - case HAL_LTDC_RELOAD_EVENT_CB_ID : - hltdc->ReloadEventCallback = pCallback; - break; - - case HAL_LTDC_ERROR_CB_ID : - hltdc->ErrorCallback = pCallback; - break; - - case HAL_LTDC_MSPINIT_CB_ID : - hltdc->MspInitCallback = pCallback; - break; - - case HAL_LTDC_MSPDEINIT_CB_ID : - hltdc->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hltdc->State == HAL_LTDC_STATE_RESET) - { - switch (CallbackID) - { - case HAL_LTDC_MSPINIT_CB_ID : - hltdc->MspInitCallback = pCallback; - break; - - case HAL_LTDC_MSPDEINIT_CB_ID : - hltdc->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hltdc); - - return status; -} - -/** - * @brief Unregister an LTDC Callback - * LTDC callback is redirected to the weak predefined callback - * @param hltdc ltdc handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_LTDC_LINE_EVENT_CB_ID Line Event Callback ID - * @arg @ref HAL_LTDC_RELOAD_EVENT_CB_ID Reload Event Callback ID - * @arg @ref HAL_LTDC_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_LTDC_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_LTDC_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_LTDC_UnRegisterCallback(LTDC_HandleTypeDef *hltdc, HAL_LTDC_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hltdc); - - if (hltdc->State == HAL_LTDC_STATE_READY) - { - switch (CallbackID) - { - case HAL_LTDC_LINE_EVENT_CB_ID : - hltdc->LineEventCallback = HAL_LTDC_LineEventCallback; /* Legacy weak LineEventCallback */ - break; - - case HAL_LTDC_RELOAD_EVENT_CB_ID : - hltdc->ReloadEventCallback = HAL_LTDC_ReloadEventCallback; /* Legacy weak ReloadEventCallback */ - break; - - case HAL_LTDC_ERROR_CB_ID : - hltdc->ErrorCallback = HAL_LTDC_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_LTDC_MSPINIT_CB_ID : - hltdc->MspInitCallback = HAL_LTDC_MspInit; /* Legcay weak MspInit Callback */ - break; - - case HAL_LTDC_MSPDEINIT_CB_ID : - hltdc->MspDeInitCallback = HAL_LTDC_MspDeInit; /* Legcay weak MspDeInit Callback */ - break; - - default : - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hltdc->State == HAL_LTDC_STATE_RESET) - { - switch (CallbackID) - { - case HAL_LTDC_MSPINIT_CB_ID : - hltdc->MspInitCallback = HAL_LTDC_MspInit; /* Legcay weak MspInit Callback */ - break; - - case HAL_LTDC_MSPDEINIT_CB_ID : - hltdc->MspDeInitCallback = HAL_LTDC_MspDeInit; /* Legcay weak MspDeInit Callback */ - break; - - default : - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hltdc); - - return status; -} -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup LTDC_Exported_Functions_Group2 IO operation functions - * @brief IO operation functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] This section provides function allowing to: - (+) Handle LTDC interrupt request - -@endverbatim - * @{ - */ -/** - * @brief Handle 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) -{ - uint32_t isrflags = READ_REG(hltdc->Instance->ISR); - uint32_t itsources = READ_REG(hltdc->Instance->IER); - - /* Transfer Error Interrupt management ***************************************/ - if (((isrflags & LTDC_ISR_TERRIF) != 0U) && ((itsources & LTDC_IER_TERRIE) != 0U)) - { - /* 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 */ -#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - hltdc->ErrorCallback(hltdc); -#else - /* Call legacy error callback*/ - HAL_LTDC_ErrorCallback(hltdc); -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - } - - /* FIFO underrun Interrupt management ***************************************/ - if (((isrflags & LTDC_ISR_FUIF) != 0U) && ((itsources & LTDC_IER_FUIE) != 0U)) - { - /* 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 */ -#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - hltdc->ErrorCallback(hltdc); -#else - /* Call legacy error callback*/ - HAL_LTDC_ErrorCallback(hltdc); -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - } - - /* Line Interrupt management ************************************************/ - if (((isrflags & LTDC_ISR_LIF) != 0U) && ((itsources & LTDC_IER_LIE) != 0U)) - { - /* 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 */ -#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) - /*Call registered Line Event callback */ - hltdc->LineEventCallback(hltdc); -#else - /*Call Legacy Line Event callback */ - HAL_LTDC_LineEventCallback(hltdc); -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - } - - /* Register reload Interrupt management ***************************************/ - if (((isrflags & LTDC_ISR_RRIF) != 0U) && ((itsources & LTDC_IER_RRIE) != 0U)) - { - /* Disable the register reload interrupt */ - __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_RR); - - /* Clear the register reload flag */ - __HAL_LTDC_CLEAR_FLAG(hltdc, LTDC_FLAG_RR); - - /* Change LTDC state */ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - /* Reload interrupt Callback */ -#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) - /*Call registered reload Event callback */ - hltdc->ReloadEventCallback(hltdc); -#else - /*Call Legacy Reload Event callback */ - HAL_LTDC_ReloadEventCallback(hltdc); -#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ - } -} - -/** - * @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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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_LineEventCallback(LTDC_HandleTypeDef *hltdc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hltdc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LTDC_LineEventCallback could be implemented in the user file - */ -} - -/** - * @brief Reload Event callback. - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @retval None - */ -__weak void HAL_LTDC_ReloadEventCallback(LTDC_HandleTypeDef *hltdc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hltdc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_LTDC_ReloadEvenCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup LTDC_Exported_Functions_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. - (+) Update transparency on the fly. - (+) 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_ConfigLayer(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t 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)); - assert_param(IS_LTDC_PIXEL_FORMAT(pLayerCfg->PixelFormat)); - assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha)); - assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha0)); - assert_param(IS_LTDC_BLENDING_FACTOR1(pLayerCfg->BlendingFactor1)); - assert_param(IS_LTDC_BLENDING_FACTOR2(pLayerCfg->BlendingFactor2)); - assert_param(IS_LTDC_CFBLL(pLayerCfg->ImageWidth)); - assert_param(IS_LTDC_CFBLNBR(pLayerCfg->ImageHeight)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Copy new layer configuration into handle structure */ - hltdc->LayerCfg[LayerIdx] = *pLayerCfg; - - /* Configure the LTDC Layer */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Configure the default color values */ - LTDC_LAYER(hltdc, LayerIdx)->CKCR &= ~(LTDC_LxCKCR_CKBLUE | LTDC_LxCKCR_CKGREEN | LTDC_LxCKCR_CKRED); - LTDC_LAYER(hltdc, LayerIdx)->CKCR = RGBValue; - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_ConfigCLUT(LTDC_HandleTypeDef *hltdc, const uint32_t *pCLUT, uint32_t CLUTSize, - uint32_t LayerIdx) -{ - uint32_t tmp; - uint32_t counter; - const uint32_t *pcolorlut = pCLUT; - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - for (counter = 0U; (counter < CLUTSize); counter++) - { - if (hltdc->LayerCfg[LayerIdx].PixelFormat == LTDC_PIXEL_FORMAT_AL44) - { - tmp = (((counter + (16U * counter)) << 24U) | ((uint32_t)(*pcolorlut) & 0xFFU) | \ - ((uint32_t)(*pcolorlut) & 0xFF00U) | ((uint32_t)(*pcolorlut) & 0xFF0000U)); - } - else - { - tmp = ((counter << 24U) | ((uint32_t)(*pcolorlut) & 0xFFU) | \ - ((uint32_t)(*pcolorlut) & 0xFF00U) | ((uint32_t)(*pcolorlut) & 0xFF0000U)); - } - - pcolorlut++; - - /* Specifies the C-LUT address and RGB value */ - 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_EnableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Enable LTDC color keying by setting COLKEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_COLKEN; - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_DisableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Disable LTDC color keying by setting COLKEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_COLKEN; - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_EnableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Enable LTDC color lookup table by setting CLUTEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_CLUTEN; - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_DisableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Disable LTDC color lookup table by setting CLUTEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_CLUTEN; - - /* Set the Immediate 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 Dither. - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @retval HAL status - */ - -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_DEN; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Disable Dither. - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @retval HAL status - */ - -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_DEN; - - /* 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetWindowSize(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters (Layers parameters)*/ - assert_param(IS_LTDC_LAYER(LayerIdx)); - assert_param(IS_LTDC_CFBLL(XSize)); - assert_param(IS_LTDC_CFBLNBR(YSize)); - - /* 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]; - - /* update horizontal stop */ - pLayerCfg->WindowX1 = XSize + pLayerCfg->WindowX0; - - /* update vertical stop */ - 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); - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetWindowPosition(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - assert_param(IS_LTDC_CFBLL(X0)); - assert_param(IS_LTDC_CFBLNBR(Y0)); - - /* 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]; - - /* 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); - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetPixelFormat(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_PIXEL_FORMAT(Pixelformat)); - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* 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]; - - /* Reconfigure the pixel format */ - pLayerCfg->PixelFormat = Pixelformat; - - /* Set LTDC parameters */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetAlpha(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_ALPHA(Alpha)); - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* 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]; - - /* Reconfigure the Alpha value */ - pLayerCfg->Alpha = Alpha; - - /* Set LTDC parameters */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Set the Immediate 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetAddress(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* 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]; - - /* Reconfigure the Address */ - pLayerCfg->FBStartAdress = Address; - - /* Set LTDC parameters */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Set the Immediate 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 Function used to reconfigure the pitch for specific cases where the attached LayerIdx buffer have a width - * that is larger than the one intended to be displayed on screen. Example of a buffer 800x480 attached to - * layer for which we want to read and display on screen only a portion 320x240 taken in the center - * of the buffer. - * The pitch in pixels will be in that case 800 pixels and not 320 pixels as initially configured by previous - * call to HAL_LTDC_ConfigLayer(). - * @note This function should be called only after a previous call to HAL_LTDC_ConfigLayer() to modify the default - * pitch configured by HAL_LTDC_ConfigLayer() when required (refer to example described just above). - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @param LinePitchInPixels New line pitch in pixels to configure for LTDC layer 'LayerIdx'. - * @param LayerIdx LTDC layer index concerned by the modification of line pitch. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetPitch(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx) -{ - uint32_t tmp; - uint32_t pitchUpdate; - uint32_t pixelFormat; - - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* get LayerIdx used pixel format */ - pixelFormat = hltdc->LayerCfg[LayerIdx].PixelFormat; - - if (pixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) - { - tmp = 4U; - } - else if (pixelFormat == LTDC_PIXEL_FORMAT_RGB888) - { - tmp = 3U; - } - else if ((pixelFormat == LTDC_PIXEL_FORMAT_ARGB4444) || \ - (pixelFormat == LTDC_PIXEL_FORMAT_RGB565) || \ - (pixelFormat == LTDC_PIXEL_FORMAT_ARGB1555) || \ - (pixelFormat == LTDC_PIXEL_FORMAT_AL88)) - { - tmp = 2U; - } - else - { - tmp = 1U; - } - - pitchUpdate = ((LinePitchInPixels * tmp) << 16U); - - /* Clear previously set standard pitch */ - LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~LTDC_LxCFBLR_CFBP; - - /* Set the Reload type as immediate update of LTDC pitch configured above */ - LTDC->SRCR |= LTDC_SRCR_IMR; - - /* Set new line pitch value */ - LTDC_LAYER(hltdc, LayerIdx)->CFBLR |= pitchUpdate; - - /* Set the Reload type as immediate update of LTDC pitch configured above */ - LTDC->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. - * @note User application may resort to HAL_LTDC_LineEventCallback() at line interrupt generation. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_ProgramLineEvent(LTDC_HandleTypeDef *hltdc, uint32_t Line) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LIPOS(Line)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Disable the Line interrupt */ - __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_LI); - - /* Set the Line Interrupt position */ - LTDC->LIPCR = (uint32_t)Line; - - /* Enable the Line interrupt */ - __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_LI); - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Reload LTDC Layers configuration. - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @param ReloadType This parameter can be one of the following values : - * LTDC_RELOAD_IMMEDIATE : Immediate Reload - * LTDC_RELOAD_VERTICAL_BLANKING : Reload in the next Vertical Blanking - * @note User application may resort to HAL_LTDC_ReloadEventCallback() at reload interrupt generation. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_Reload(LTDC_HandleTypeDef *hltdc, uint32_t ReloadType) -{ - /* Check the parameters */ - assert_param(IS_LTDC_RELOAD(ReloadType)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Enable the Reload interrupt */ - __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_RR); - - /* Apply Reload type */ - hltdc->Instance->SRCR = ReloadType; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Configure the LTDC Layer according to the specified without reloading - * parameters in the LTDC_InitTypeDef and create the associated handle. - * Variant of the function HAL_LTDC_ConfigLayer without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_ConfigLayer_NoReload(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, - uint32_t 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)); - assert_param(IS_LTDC_PIXEL_FORMAT(pLayerCfg->PixelFormat)); - assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha)); - assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha0)); - assert_param(IS_LTDC_BLENDING_FACTOR1(pLayerCfg->BlendingFactor1)); - assert_param(IS_LTDC_BLENDING_FACTOR2(pLayerCfg->BlendingFactor2)); - assert_param(IS_LTDC_CFBLL(pLayerCfg->ImageWidth)); - assert_param(IS_LTDC_CFBLNBR(pLayerCfg->ImageHeight)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Copy new layer configuration into handle structure */ - hltdc->LayerCfg[LayerIdx] = *pLayerCfg; - - /* Configure the LTDC Layer */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Initialize the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Set the LTDC window size without reloading. - * Variant of the function HAL_LTDC_SetWindowSize without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetWindowSize_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, - uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters (Layers parameters)*/ - assert_param(IS_LTDC_LAYER(LayerIdx)); - assert_param(IS_LTDC_CFBLL(XSize)); - assert_param(IS_LTDC_CFBLNBR(YSize)); - - /* 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]; - - /* update horizontal stop */ - pLayerCfg->WindowX1 = XSize + pLayerCfg->WindowX0; - - /* update vertical stop */ - 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); - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Set the LTDC window position without reloading. - * Variant of the function HAL_LTDC_SetWindowPosition without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetWindowPosition_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, - uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - assert_param(IS_LTDC_CFBLL(X0)); - assert_param(IS_LTDC_CFBLNBR(Y0)); - - /* 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]; - - /* 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); - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Reconfigure the pixel format without reloading. - * Variant of the function HAL_LTDC_SetPixelFormat without immediate reload. - * @param hltdc pointer to a LTDC_HandleTypeDfef 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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetPixelFormat_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_PIXEL_FORMAT(Pixelformat)); - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* 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]; - - /* Reconfigure the pixel format */ - pLayerCfg->PixelFormat = Pixelformat; - - /* Set LTDC parameters */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Reconfigure the layer alpha value without reloading. - * Variant of the function HAL_LTDC_SetAlpha without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetAlpha_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_ALPHA(Alpha)); - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* 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]; - - /* Reconfigure the Alpha value */ - pLayerCfg->Alpha = Alpha; - - /* Set LTDC parameters */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Reconfigure the frame buffer Address without reloading. - * Variant of the function HAL_LTDC_SetAddress without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetAddress_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx) -{ - LTDC_LayerCfgTypeDef *pLayerCfg; - - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* 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]; - - /* Reconfigure the Address */ - pLayerCfg->FBStartAdress = Address; - - /* Set LTDC parameters */ - LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Function used to reconfigure the pitch for specific cases where the attached LayerIdx buffer have a width - * that is larger than the one intended to be displayed on screen. Example of a buffer 800x480 attached to - * layer for which we want to read and display on screen only a portion 320x240 taken in the center - * of the buffer. - * The pitch in pixels will be in that case 800 pixels and not 320 pixels as initially configured by - * previous call to HAL_LTDC_ConfigLayer(). - * @note This function should be called only after a previous call to HAL_LTDC_ConfigLayer() to modify the default - * pitch configured by HAL_LTDC_ConfigLayer() when required (refer to example described just above). - * Variant of the function HAL_LTDC_SetPitch without immediate reload. - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @param LinePitchInPixels New line pitch in pixels to configure for LTDC layer 'LayerIdx'. - * @param LayerIdx LTDC layer index concerned by the modification of line pitch. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_SetPitch_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx) -{ - uint32_t tmp; - uint32_t pitchUpdate; - uint32_t pixelFormat; - - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* get LayerIdx used pixel format */ - pixelFormat = hltdc->LayerCfg[LayerIdx].PixelFormat; - - if (pixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) - { - tmp = 4U; - } - else if (pixelFormat == LTDC_PIXEL_FORMAT_RGB888) - { - tmp = 3U; - } - else if ((pixelFormat == LTDC_PIXEL_FORMAT_ARGB4444) || \ - (pixelFormat == LTDC_PIXEL_FORMAT_RGB565) || \ - (pixelFormat == LTDC_PIXEL_FORMAT_ARGB1555) || \ - (pixelFormat == LTDC_PIXEL_FORMAT_AL88)) - { - tmp = 2U; - } - else - { - tmp = 1U; - } - - pitchUpdate = ((LinePitchInPixels * tmp) << 16U); - - /* Clear previously set standard pitch */ - LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~LTDC_LxCFBLR_CFBP; - - /* Set new line pitch value */ - LTDC_LAYER(hltdc, LayerIdx)->CFBLR |= pitchUpdate; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - - -/** - * @brief Configure the color keying without reloading. - * Variant of the function HAL_LTDC_ConfigColorKeying without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Configure the default color values */ - LTDC_LAYER(hltdc, LayerIdx)->CKCR &= ~(LTDC_LxCKCR_CKBLUE | LTDC_LxCKCR_CKGREEN | LTDC_LxCKCR_CKRED); - LTDC_LAYER(hltdc, LayerIdx)->CKCR = RGBValue; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Enable the color keying without reloading. - * Variant of the function HAL_LTDC_EnableColorKeying without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_EnableColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Enable LTDC color keying by setting COLKEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_COLKEN; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Disable the color keying without reloading. - * Variant of the function HAL_LTDC_DisableColorKeying without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_DisableColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Disable LTDC color keying by setting COLKEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_COLKEN; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Enable the color lookup table without reloading. - * Variant of the function HAL_LTDC_EnableCLUT without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_EnableCLUT_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Disable LTDC color lookup table by setting CLUTEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_CLUTEN; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @brief Disable the color lookup table without reloading. - * Variant of the function HAL_LTDC_DisableCLUT without immediate reload. - * @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: - * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDC_DisableCLUT_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LTDC_LAYER(LayerIdx)); - - /* Process locked */ - __HAL_LOCK(hltdc); - - /* Change LTDC peripheral state */ - hltdc->State = HAL_LTDC_STATE_BUSY; - - /* Disable LTDC color lookup table by setting CLUTEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_CLUTEN; - - /* Change the LTDC state*/ - hltdc->State = HAL_LTDC_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hltdc); - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup LTDC_Exported_Functions_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 handle state. - (+) Get the LTDC handle error code. - -@endverbatim - * @{ - */ - -/** - * @brief Return the LTDC handle 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(const LTDC_HandleTypeDef *hltdc) -{ - return hltdc->State; -} - -/** - * @brief Return the LTDC handle 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(const LTDC_HandleTypeDef *hltdc) -{ - return hltdc->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup LTDC_Private_Functions LTDC Private Functions - * @{ - */ - -/** - * @brief Configure 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 structure - * @param LayerIdx LTDC Layer index. - * This parameter can be one of the following values: LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) - * @retval None - */ -static void LTDC_SetConfig(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx) -{ - uint32_t tmp; - uint32_t tmp1; - uint32_t tmp2; - - /* Configure the horizontal start and stop position */ - tmp = ((pLayerCfg->WindowX1 + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16U)) << 16U); - LTDC_LAYER(hltdc, LayerIdx)->WHPCR &= ~(LTDC_LxWHPCR_WHSTPOS | LTDC_LxWHPCR_WHSPPOS); - LTDC_LAYER(hltdc, LayerIdx)->WHPCR = ((pLayerCfg->WindowX0 + \ - ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16U) + 1U) | tmp); - - /* Configure the vertical start and stop position */ - tmp = ((pLayerCfg->WindowY1 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP)) << 16U); - LTDC_LAYER(hltdc, LayerIdx)->WVPCR &= ~(LTDC_LxWVPCR_WVSTPOS | LTDC_LxWVPCR_WVSPPOS); - LTDC_LAYER(hltdc, LayerIdx)->WVPCR = ((pLayerCfg->WindowY0 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP) + 1U) | tmp); - - /* Specifies the pixel format */ - LTDC_LAYER(hltdc, LayerIdx)->PFCR &= ~(LTDC_LxPFCR_PF); - LTDC_LAYER(hltdc, LayerIdx)->PFCR = (pLayerCfg->PixelFormat); - - /* Configure the default color values */ - tmp = ((uint32_t)(pLayerCfg->Backcolor.Green) << 8U); - tmp1 = ((uint32_t)(pLayerCfg->Backcolor.Red) << 16U); - tmp2 = (pLayerCfg->Alpha0 << 24U); - WRITE_REG(LTDC_LAYER(hltdc, LayerIdx)->DCCR, (pLayerCfg->Backcolor.Blue | tmp | tmp1 | tmp2)); - - /* Specifies the constant alpha value */ - LTDC_LAYER(hltdc, LayerIdx)->CACR &= ~(LTDC_LxCACR_CONSTA); - LTDC_LAYER(hltdc, LayerIdx)->CACR = (pLayerCfg->Alpha); - - /* Specifies the blending factors */ - LTDC_LAYER(hltdc, LayerIdx)->BFCR &= ~(LTDC_LxBFCR_BF2 | LTDC_LxBFCR_BF1); - LTDC_LAYER(hltdc, LayerIdx)->BFCR = (pLayerCfg->BlendingFactor1 | pLayerCfg->BlendingFactor2); - - /* Configure the color frame buffer start address */ - WRITE_REG(LTDC_LAYER(hltdc, LayerIdx)->CFBAR, pLayerCfg->FBStartAdress); - - if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) - { - tmp = 4U; - } - else if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_RGB888) - { - tmp = 3U; - } - 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 = 2U; - } - else - { - tmp = 1U; - } - - /* Configure the color frame buffer pitch in byte */ - LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~(LTDC_LxCFBLR_CFBLL | LTDC_LxCFBLR_CFBP); - LTDC_LAYER(hltdc, LayerIdx)->CFBLR = (((pLayerCfg->ImageWidth * tmp) << 16U) | - (((pLayerCfg->WindowX1 - pLayerCfg->WindowX0) * tmp) + 7U)); - /* Configure the frame buffer line number */ - LTDC_LAYER(hltdc, LayerIdx)->CFBLNR &= ~(LTDC_LxCFBLNR_CFBLNBR); - LTDC_LAYER(hltdc, LayerIdx)->CFBLNR = (pLayerCfg->ImageHeight); - - /* Enable LTDC_Layer by setting LEN bit */ - LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_LEN; -} - -/** - * @} - */ - - -/** - * @} - */ - -#endif /* LTDC */ - -#endif /* HAL_LTDC_MODULE_ENABLED */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_ltdc.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The LTDC HAL driver can be used as follows: + + (#) Declare a LTDC_HandleTypeDef handle structure, for example: LTDC_HandleTypeDef hltdc; + + (#) Initialize the LTDC low level resources by implementing the HAL_LTDC_MspInit() API: + (##) Enable the LTDC interface clock + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the LTDC interrupt priority + (+++) Enable the NVIC LTDC IRQ Channel + + (#) Initialize the required configuration through the 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 + + *** Configuration *** + ========================= + [..] + (#) Program the required configuration through the 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_ProgramLineEvent() + 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() and HAL_LTDC_SetAddress(). + + (#) Variant functions with _NoReload suffix allows to set the LTDC configuration/settings without immediate reload. + This is useful in case when the program requires to modify serval LTDC settings (on one or both layers) + then applying(reload) these settings in one shot by calling the function HAL_LTDC_Reload(). + + After calling the _NoReload functions to set different color/format/layer settings, + the program shall call the function HAL_LTDC_Reload() to apply(reload) these settings. + Function HAL_LTDC_Reload() can be called with the parameter ReloadType set to LTDC_RELOAD_IMMEDIATE if + an immediate reload is required. + Function HAL_LTDC_Reload() can be called with the parameter ReloadType set to LTDC_RELOAD_VERTICAL_BLANKING if + the reload should be done in the next vertical blanking period, + this option allows to avoid display flicker by applying the new settings during the vertical blanking period. + + + (#) 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 an LTDC Layer. + (+) __HAL_LTDC_LAYER_DISABLE: Disable an LTDC Layer. + (+) __HAL_LTDC_RELOAD_IMMEDIATE_CONFIG: Reload Layer Configuration. + (+) __HAL_LTDC_GET_FLAG: Get the LTDC pending flags. + (+) __HAL_LTDC_CLEAR_FLAG: Clear the LTDC pending flags. + (+) __HAL_LTDC_ENABLE_IT: Enable the specified LTDC interrupts. + (+) __HAL_LTDC_DISABLE_IT: Disable the specified LTDC interrupts. + (+) __HAL_LTDC_GET_IT_SOURCE: Check whether the specified LTDC interrupt has occurred or not. + + [..] + (@) You can refer to the LTDC HAL driver header file for more useful macros + + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_LTDC_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use function HAL_LTDC_RegisterCallback() to register a callback. + + [..] + Function HAL_LTDC_RegisterCallback() allows to register following callbacks: + (+) LineEventCallback : LTDC Line Event Callback. + (+) ReloadEventCallback : LTDC Reload Event Callback. + (+) ErrorCallback : LTDC Error Callback + (+) MspInitCallback : LTDC MspInit. + (+) MspDeInitCallback : LTDC MspDeInit. + [..] + This function takes as parameters the HAL peripheral handle, the callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_LTDC_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_LTDC_UnRegisterCallback() takes as parameters the HAL peripheral handle + and the callback ID. + [..] + This function allows to reset following callbacks: + (+) LineEventCallback : LTDC Line Event Callback + (+) ReloadEventCallback : LTDC Reload Event Callback + (+) ErrorCallback : LTDC Error Callback + (+) MspInitCallback : LTDC MspInit + (+) MspDeInitCallback : LTDC MspDeInit. + + [..] + By default, after the HAL_LTDC_Init and when the state is HAL_LTDC_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_LTDC_LineEventCallback(), HAL_LTDC_ErrorCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak (surcharged) functions in the HAL_LTDC_Init() and HAL_LTDC_DeInit() + only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_LTDC_Init() and HAL_LTDC_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in HAL_LTDC_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_LTDC_STATE_READY or HAL_LTDC_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_LTDC_RegisterCallback() before calling HAL_LTDC_DeInit() + or HAL_LTDC_Init() function. + + [..] + When the compilation define USE_HAL_LTDC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_LTDC_MODULE_ENABLED + +#if defined (LTDC) + +/** @defgroup LTDC LTDC + * @brief LTDC HAL module driver + * @{ + */ + + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup LTDC_Private_Define LTDC Private Define + * @{ + */ +#define LTDC_TIMEOUT_VALUE ((uint32_t)100U) /* 100ms */ +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void LTDC_SetConfig(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup LTDC_Exported_Functions LTDC Exported Functions + * @{ + */ + +/** @defgroup LTDC_Exported_Functions_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 Initialize the LTDC according to the specified parameters in the LTDC_InitTypeDef. + * @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; + uint32_t tmp1; + + /* 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 (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) + if (hltdc->State == HAL_LTDC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hltdc->Lock = HAL_UNLOCKED; + + /* Reset the LTDC callback to the legacy weak callbacks */ + hltdc->LineEventCallback = HAL_LTDC_LineEventCallback; /* Legacy weak LineEventCallback */ + hltdc->ReloadEventCallback = HAL_LTDC_ReloadEventCallback; /* Legacy weak ReloadEventCallback */ + hltdc->ErrorCallback = HAL_LTDC_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hltdc->MspInitCallback == NULL) + { + hltdc->MspInitCallback = HAL_LTDC_MspInit; + } + /* Init the low level hardware */ + hltdc->MspInitCallback(hltdc); + } +#else + if (hltdc->State == HAL_LTDC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hltdc->Lock = HAL_UNLOCKED; + /* Init the low level hardware */ + HAL_LTDC_MspInit(hltdc); + } +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Configure 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); + + /* Set Synchronization size */ + hltdc->Instance->SSCR &= ~(LTDC_SSCR_VSH | LTDC_SSCR_HSW); + tmp = (hltdc->Init.HorizontalSync << 16U); + hltdc->Instance->SSCR |= (tmp | hltdc->Init.VerticalSync); + + /* Set Accumulated Back porch */ + hltdc->Instance->BPCR &= ~(LTDC_BPCR_AVBP | LTDC_BPCR_AHBP); + tmp = (hltdc->Init.AccumulatedHBP << 16U); + hltdc->Instance->BPCR |= (tmp | hltdc->Init.AccumulatedVBP); + + /* Set Accumulated Active Width */ + hltdc->Instance->AWCR &= ~(LTDC_AWCR_AAH | LTDC_AWCR_AAW); + tmp = (hltdc->Init.AccumulatedActiveW << 16U); + hltdc->Instance->AWCR |= (tmp | hltdc->Init.AccumulatedActiveH); + + /* Set Total Width */ + hltdc->Instance->TWCR &= ~(LTDC_TWCR_TOTALH | LTDC_TWCR_TOTALW); + tmp = (hltdc->Init.TotalWidth << 16U); + hltdc->Instance->TWCR |= (tmp | hltdc->Init.TotalHeigh); + + /* Set the background color value */ + tmp = ((uint32_t)(hltdc->Init.Backcolor.Green) << 8U); + tmp1 = ((uint32_t)(hltdc->Init.Backcolor.Red) << 16U); + 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 and FIFO underrun interrupts */ + __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_TE | LTDC_IT_FU); + + /* Enable LTDC by setting LTDCEN bit */ + __HAL_LTDC_ENABLE(hltdc); + + /* Initialize the error code */ + hltdc->ErrorCode = HAL_LTDC_ERROR_NONE; + + /* Initialize the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief De-initialize the LTDC peripheral. + * @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) +{ + uint32_t tickstart; + + /* Check the LTDC peripheral state */ + if (hltdc == NULL) + { + return HAL_ERROR; + } + + /* Check function parameters */ + assert_param(IS_LTDC_ALL_INSTANCE(hltdc->Instance)); + + /* Disable LTDC Layer 1 */ + __HAL_LTDC_LAYER_DISABLE(hltdc, LTDC_LAYER_1); + +#if defined(LTDC_Layer2_BASE) + /* Disable LTDC Layer 2 */ + __HAL_LTDC_LAYER_DISABLE(hltdc, LTDC_LAYER_2); +#endif /* LTDC_Layer2_BASE */ + + /* Reload during vertical blanking period */ + __HAL_LTDC_VERTICAL_BLANKING_RELOAD_CONFIG(hltdc); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait for VSYNC Interrupt */ + while (READ_BIT(hltdc->Instance->CDSR, LTDC_CDSR_VSYNCS) == 0U) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > LTDC_TIMEOUT_VALUE) + { + break; + } + } + + /* Disable LTDC */ + __HAL_LTDC_DISABLE(hltdc); + +#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) + if (hltdc->MspDeInitCallback == NULL) + { + hltdc->MspDeInitCallback = HAL_LTDC_MspDeInit; + } + /* DeInit the low level hardware */ + hltdc->MspDeInitCallback(hltdc); +#else + /* DeInit the low level hardware */ + HAL_LTDC_MspDeInit(hltdc); +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + + /* Initialize 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 Initialize 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 De-initialize 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hltdc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LTDC_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User LTDC Callback + * To be used instead of the weak predefined callback + * @param hltdc ltdc handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_LTDC_LINE_EVENT_CB_ID Line Event Callback ID + * @arg @ref HAL_LTDC_RELOAD_EVENT_CB_ID Reload Event Callback ID + * @arg @ref HAL_LTDC_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_LTDC_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_LTDC_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_LTDC_RegisterCallback(LTDC_HandleTypeDef *hltdc, HAL_LTDC_CallbackIDTypeDef CallbackID, + pLTDC_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hltdc); + + if (hltdc->State == HAL_LTDC_STATE_READY) + { + switch (CallbackID) + { + case HAL_LTDC_LINE_EVENT_CB_ID : + hltdc->LineEventCallback = pCallback; + break; + + case HAL_LTDC_RELOAD_EVENT_CB_ID : + hltdc->ReloadEventCallback = pCallback; + break; + + case HAL_LTDC_ERROR_CB_ID : + hltdc->ErrorCallback = pCallback; + break; + + case HAL_LTDC_MSPINIT_CB_ID : + hltdc->MspInitCallback = pCallback; + break; + + case HAL_LTDC_MSPDEINIT_CB_ID : + hltdc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hltdc->State == HAL_LTDC_STATE_RESET) + { + switch (CallbackID) + { + case HAL_LTDC_MSPINIT_CB_ID : + hltdc->MspInitCallback = pCallback; + break; + + case HAL_LTDC_MSPDEINIT_CB_ID : + hltdc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hltdc); + + return status; +} + +/** + * @brief Unregister an LTDC Callback + * LTDC callback is redirected to the weak predefined callback + * @param hltdc ltdc handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_LTDC_LINE_EVENT_CB_ID Line Event Callback ID + * @arg @ref HAL_LTDC_RELOAD_EVENT_CB_ID Reload Event Callback ID + * @arg @ref HAL_LTDC_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_LTDC_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_LTDC_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_LTDC_UnRegisterCallback(LTDC_HandleTypeDef *hltdc, HAL_LTDC_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hltdc); + + if (hltdc->State == HAL_LTDC_STATE_READY) + { + switch (CallbackID) + { + case HAL_LTDC_LINE_EVENT_CB_ID : + hltdc->LineEventCallback = HAL_LTDC_LineEventCallback; /* Legacy weak LineEventCallback */ + break; + + case HAL_LTDC_RELOAD_EVENT_CB_ID : + hltdc->ReloadEventCallback = HAL_LTDC_ReloadEventCallback; /* Legacy weak ReloadEventCallback */ + break; + + case HAL_LTDC_ERROR_CB_ID : + hltdc->ErrorCallback = HAL_LTDC_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_LTDC_MSPINIT_CB_ID : + hltdc->MspInitCallback = HAL_LTDC_MspInit; /* Legcay weak MspInit Callback */ + break; + + case HAL_LTDC_MSPDEINIT_CB_ID : + hltdc->MspDeInitCallback = HAL_LTDC_MspDeInit; /* Legcay weak MspDeInit Callback */ + break; + + default : + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hltdc->State == HAL_LTDC_STATE_RESET) + { + switch (CallbackID) + { + case HAL_LTDC_MSPINIT_CB_ID : + hltdc->MspInitCallback = HAL_LTDC_MspInit; /* Legcay weak MspInit Callback */ + break; + + case HAL_LTDC_MSPDEINIT_CB_ID : + hltdc->MspDeInitCallback = HAL_LTDC_MspDeInit; /* Legcay weak MspDeInit Callback */ + break; + + default : + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hltdc->ErrorCode |= HAL_LTDC_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hltdc); + + return status; +} +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup LTDC_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides function allowing to: + (+) Handle LTDC interrupt request + +@endverbatim + * @{ + */ +/** + * @brief Handle 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) +{ + uint32_t isrflags = READ_REG(hltdc->Instance->ISR); + uint32_t itsources = READ_REG(hltdc->Instance->IER); + + /* Transfer Error Interrupt management ***************************************/ + if (((isrflags & LTDC_ISR_TERRIF) != 0U) && ((itsources & LTDC_IER_TERRIE) != 0U)) + { + /* 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 */ +#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hltdc->ErrorCallback(hltdc); +#else + /* Call legacy error callback*/ + HAL_LTDC_ErrorCallback(hltdc); +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + } + + /* FIFO underrun Interrupt management ***************************************/ + if (((isrflags & LTDC_ISR_FUIF) != 0U) && ((itsources & LTDC_IER_FUIE) != 0U)) + { + /* 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 */ +#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + hltdc->ErrorCallback(hltdc); +#else + /* Call legacy error callback*/ + HAL_LTDC_ErrorCallback(hltdc); +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + } + + /* Line Interrupt management ************************************************/ + if (((isrflags & LTDC_ISR_LIF) != 0U) && ((itsources & LTDC_IER_LIE) != 0U)) + { + /* 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 */ +#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) + /*Call registered Line Event callback */ + hltdc->LineEventCallback(hltdc); +#else + /*Call Legacy Line Event callback */ + HAL_LTDC_LineEventCallback(hltdc); +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + } + + /* Register reload Interrupt management ***************************************/ + if (((isrflags & LTDC_ISR_RRIF) != 0U) && ((itsources & LTDC_IER_RRIE) != 0U)) + { + /* Disable the register reload interrupt */ + __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_RR); + + /* Clear the register reload flag */ + __HAL_LTDC_CLEAR_FLAG(hltdc, LTDC_FLAG_RR); + + /* Change LTDC state */ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + /* Reload interrupt Callback */ +#if (USE_HAL_LTDC_REGISTER_CALLBACKS == 1) + /*Call registered reload Event callback */ + hltdc->ReloadEventCallback(hltdc); +#else + /*Call Legacy Reload Event callback */ + HAL_LTDC_ReloadEventCallback(hltdc); +#endif /* USE_HAL_LTDC_REGISTER_CALLBACKS */ + } +} + +/** + * @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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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_LineEventCallback(LTDC_HandleTypeDef *hltdc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hltdc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LTDC_LineEventCallback could be implemented in the user file + */ +} + +/** + * @brief Reload Event callback. + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @retval None + */ +__weak void HAL_LTDC_ReloadEventCallback(LTDC_HandleTypeDef *hltdc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hltdc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_LTDC_ReloadEvenCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup LTDC_Exported_Functions_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. + (+) Update transparency on the fly. + (+) 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_ConfigLayer(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t 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)); + assert_param(IS_LTDC_PIXEL_FORMAT(pLayerCfg->PixelFormat)); + assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha)); + assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha0)); + assert_param(IS_LTDC_BLENDING_FACTOR1(pLayerCfg->BlendingFactor1)); + assert_param(IS_LTDC_BLENDING_FACTOR2(pLayerCfg->BlendingFactor2)); + assert_param(IS_LTDC_CFBLL(pLayerCfg->ImageWidth)); + assert_param(IS_LTDC_CFBLNBR(pLayerCfg->ImageHeight)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Copy new layer configuration into handle structure */ + hltdc->LayerCfg[LayerIdx] = *pLayerCfg; + + /* Configure the LTDC Layer */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Configure the default color values */ + LTDC_LAYER(hltdc, LayerIdx)->CKCR &= ~(LTDC_LxCKCR_CKBLUE | LTDC_LxCKCR_CKGREEN | LTDC_LxCKCR_CKRED); + LTDC_LAYER(hltdc, LayerIdx)->CKCR = RGBValue; + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_ConfigCLUT(LTDC_HandleTypeDef *hltdc, const uint32_t *pCLUT, uint32_t CLUTSize, + uint32_t LayerIdx) +{ + uint32_t tmp; + uint32_t counter; + const uint32_t *pcolorlut = pCLUT; + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + for (counter = 0U; (counter < CLUTSize); counter++) + { + if (hltdc->LayerCfg[LayerIdx].PixelFormat == LTDC_PIXEL_FORMAT_AL44) + { + tmp = (((counter + (16U * counter)) << 24U) | ((uint32_t)(*pcolorlut) & 0xFFU) | \ + ((uint32_t)(*pcolorlut) & 0xFF00U) | ((uint32_t)(*pcolorlut) & 0xFF0000U)); + } + else + { + tmp = ((counter << 24U) | ((uint32_t)(*pcolorlut) & 0xFFU) | \ + ((uint32_t)(*pcolorlut) & 0xFF00U) | ((uint32_t)(*pcolorlut) & 0xFF0000U)); + } + + pcolorlut++; + + /* Specifies the C-LUT address and RGB value */ + 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_EnableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Enable LTDC color keying by setting COLKEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_COLKEN; + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_DisableColorKeying(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Disable LTDC color keying by setting COLKEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_COLKEN; + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_EnableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Enable LTDC color lookup table by setting CLUTEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_CLUTEN; + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_DisableCLUT(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Disable LTDC color lookup table by setting CLUTEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_CLUTEN; + + /* Set the Immediate 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 Dither. + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @retval HAL status + */ + +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_DEN; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Disable Dither. + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @retval HAL status + */ + +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_DEN; + + /* 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetWindowSize(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters (Layers parameters)*/ + assert_param(IS_LTDC_LAYER(LayerIdx)); + assert_param(IS_LTDC_CFBLL(XSize)); + assert_param(IS_LTDC_CFBLNBR(YSize)); + + /* 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]; + + /* update horizontal stop */ + pLayerCfg->WindowX1 = XSize + pLayerCfg->WindowX0; + + /* update vertical stop */ + 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); + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetWindowPosition(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + assert_param(IS_LTDC_CFBLL(X0)); + assert_param(IS_LTDC_CFBLNBR(Y0)); + + /* 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]; + + /* 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); + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetPixelFormat(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_PIXEL_FORMAT(Pixelformat)); + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* 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]; + + /* Reconfigure the pixel format */ + pLayerCfg->PixelFormat = Pixelformat; + + /* Set LTDC parameters */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetAlpha(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_ALPHA(Alpha)); + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* 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]; + + /* Reconfigure the Alpha value */ + pLayerCfg->Alpha = Alpha; + + /* Set LTDC parameters */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Set the Immediate 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetAddress(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* 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]; + + /* Reconfigure the Address */ + pLayerCfg->FBStartAdress = Address; + + /* Set LTDC parameters */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Set the Immediate 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 Function used to reconfigure the pitch for specific cases where the attached LayerIdx buffer have a width + * that is larger than the one intended to be displayed on screen. Example of a buffer 800x480 attached to + * layer for which we want to read and display on screen only a portion 320x240 taken in the center + * of the buffer. + * The pitch in pixels will be in that case 800 pixels and not 320 pixels as initially configured by previous + * call to HAL_LTDC_ConfigLayer(). + * @note This function should be called only after a previous call to HAL_LTDC_ConfigLayer() to modify the default + * pitch configured by HAL_LTDC_ConfigLayer() when required (refer to example described just above). + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @param LinePitchInPixels New line pitch in pixels to configure for LTDC layer 'LayerIdx'. + * @param LayerIdx LTDC layer index concerned by the modification of line pitch. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetPitch(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx) +{ + uint32_t tmp; + uint32_t pitchUpdate; + uint32_t pixelFormat; + + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* get LayerIdx used pixel format */ + pixelFormat = hltdc->LayerCfg[LayerIdx].PixelFormat; + + if (pixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) + { + tmp = 4U; + } + else if (pixelFormat == LTDC_PIXEL_FORMAT_RGB888) + { + tmp = 3U; + } + else if ((pixelFormat == LTDC_PIXEL_FORMAT_ARGB4444) || \ + (pixelFormat == LTDC_PIXEL_FORMAT_RGB565) || \ + (pixelFormat == LTDC_PIXEL_FORMAT_ARGB1555) || \ + (pixelFormat == LTDC_PIXEL_FORMAT_AL88)) + { + tmp = 2U; + } + else + { + tmp = 1U; + } + + pitchUpdate = ((LinePitchInPixels * tmp) << 16U); + + /* Clear previously set standard pitch */ + LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~LTDC_LxCFBLR_CFBP; + + /* Set the Reload type as immediate update of LTDC pitch configured above */ + LTDC->SRCR |= LTDC_SRCR_IMR; + + /* Set new line pitch value */ + LTDC_LAYER(hltdc, LayerIdx)->CFBLR |= pitchUpdate; + + /* Set the Reload type as immediate update of LTDC pitch configured above */ + LTDC->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. + * @note User application may resort to HAL_LTDC_LineEventCallback() at line interrupt generation. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_ProgramLineEvent(LTDC_HandleTypeDef *hltdc, uint32_t Line) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LIPOS(Line)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Disable the Line interrupt */ + __HAL_LTDC_DISABLE_IT(hltdc, LTDC_IT_LI); + + /* Set the Line Interrupt position */ + LTDC->LIPCR = (uint32_t)Line; + + /* Enable the Line interrupt */ + __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_LI); + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Reload LTDC Layers configuration. + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @param ReloadType This parameter can be one of the following values : + * LTDC_RELOAD_IMMEDIATE : Immediate Reload + * LTDC_RELOAD_VERTICAL_BLANKING : Reload in the next Vertical Blanking + * @note User application may resort to HAL_LTDC_ReloadEventCallback() at reload interrupt generation. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_Reload(LTDC_HandleTypeDef *hltdc, uint32_t ReloadType) +{ + /* Check the parameters */ + assert_param(IS_LTDC_RELOAD(ReloadType)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Enable the Reload interrupt */ + __HAL_LTDC_ENABLE_IT(hltdc, LTDC_IT_RR); + + /* Apply Reload type */ + hltdc->Instance->SRCR = ReloadType; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Configure the LTDC Layer according to the specified without reloading + * parameters in the LTDC_InitTypeDef and create the associated handle. + * Variant of the function HAL_LTDC_ConfigLayer without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_ConfigLayer_NoReload(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, + uint32_t 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)); + assert_param(IS_LTDC_PIXEL_FORMAT(pLayerCfg->PixelFormat)); + assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha)); + assert_param(IS_LTDC_ALPHA(pLayerCfg->Alpha0)); + assert_param(IS_LTDC_BLENDING_FACTOR1(pLayerCfg->BlendingFactor1)); + assert_param(IS_LTDC_BLENDING_FACTOR2(pLayerCfg->BlendingFactor2)); + assert_param(IS_LTDC_CFBLL(pLayerCfg->ImageWidth)); + assert_param(IS_LTDC_CFBLNBR(pLayerCfg->ImageHeight)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Copy new layer configuration into handle structure */ + hltdc->LayerCfg[LayerIdx] = *pLayerCfg; + + /* Configure the LTDC Layer */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Initialize the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Set the LTDC window size without reloading. + * Variant of the function HAL_LTDC_SetWindowSize without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetWindowSize_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t XSize, uint32_t YSize, + uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters (Layers parameters)*/ + assert_param(IS_LTDC_LAYER(LayerIdx)); + assert_param(IS_LTDC_CFBLL(XSize)); + assert_param(IS_LTDC_CFBLNBR(YSize)); + + /* 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]; + + /* update horizontal stop */ + pLayerCfg->WindowX1 = XSize + pLayerCfg->WindowX0; + + /* update vertical stop */ + 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); + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Set the LTDC window position without reloading. + * Variant of the function HAL_LTDC_SetWindowPosition without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetWindowPosition_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t X0, uint32_t Y0, + uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + assert_param(IS_LTDC_CFBLL(X0)); + assert_param(IS_LTDC_CFBLNBR(Y0)); + + /* 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]; + + /* 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); + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Reconfigure the pixel format without reloading. + * Variant of the function HAL_LTDC_SetPixelFormat without immediate reload. + * @param hltdc pointer to a LTDC_HandleTypeDfef 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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetPixelFormat_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Pixelformat, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_PIXEL_FORMAT(Pixelformat)); + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* 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]; + + /* Reconfigure the pixel format */ + pLayerCfg->PixelFormat = Pixelformat; + + /* Set LTDC parameters */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Reconfigure the layer alpha value without reloading. + * Variant of the function HAL_LTDC_SetAlpha without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetAlpha_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Alpha, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_ALPHA(Alpha)); + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* 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]; + + /* Reconfigure the Alpha value */ + pLayerCfg->Alpha = Alpha; + + /* Set LTDC parameters */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Reconfigure the frame buffer Address without reloading. + * Variant of the function HAL_LTDC_SetAddress without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetAddress_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t Address, uint32_t LayerIdx) +{ + LTDC_LayerCfgTypeDef *pLayerCfg; + + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* 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]; + + /* Reconfigure the Address */ + pLayerCfg->FBStartAdress = Address; + + /* Set LTDC parameters */ + LTDC_SetConfig(hltdc, pLayerCfg, LayerIdx); + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Function used to reconfigure the pitch for specific cases where the attached LayerIdx buffer have a width + * that is larger than the one intended to be displayed on screen. Example of a buffer 800x480 attached to + * layer for which we want to read and display on screen only a portion 320x240 taken in the center + * of the buffer. + * The pitch in pixels will be in that case 800 pixels and not 320 pixels as initially configured by + * previous call to HAL_LTDC_ConfigLayer(). + * @note This function should be called only after a previous call to HAL_LTDC_ConfigLayer() to modify the default + * pitch configured by HAL_LTDC_ConfigLayer() when required (refer to example described just above). + * Variant of the function HAL_LTDC_SetPitch without immediate reload. + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @param LinePitchInPixels New line pitch in pixels to configure for LTDC layer 'LayerIdx'. + * @param LayerIdx LTDC layer index concerned by the modification of line pitch. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_SetPitch_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LinePitchInPixels, uint32_t LayerIdx) +{ + uint32_t tmp; + uint32_t pitchUpdate; + uint32_t pixelFormat; + + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* get LayerIdx used pixel format */ + pixelFormat = hltdc->LayerCfg[LayerIdx].PixelFormat; + + if (pixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) + { + tmp = 4U; + } + else if (pixelFormat == LTDC_PIXEL_FORMAT_RGB888) + { + tmp = 3U; + } + else if ((pixelFormat == LTDC_PIXEL_FORMAT_ARGB4444) || \ + (pixelFormat == LTDC_PIXEL_FORMAT_RGB565) || \ + (pixelFormat == LTDC_PIXEL_FORMAT_ARGB1555) || \ + (pixelFormat == LTDC_PIXEL_FORMAT_AL88)) + { + tmp = 2U; + } + else + { + tmp = 1U; + } + + pitchUpdate = ((LinePitchInPixels * tmp) << 16U); + + /* Clear previously set standard pitch */ + LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~LTDC_LxCFBLR_CFBP; + + /* Set new line pitch value */ + LTDC_LAYER(hltdc, LayerIdx)->CFBLR |= pitchUpdate; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + + +/** + * @brief Configure the color keying without reloading. + * Variant of the function HAL_LTDC_ConfigColorKeying without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_ConfigColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t RGBValue, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Configure the default color values */ + LTDC_LAYER(hltdc, LayerIdx)->CKCR &= ~(LTDC_LxCKCR_CKBLUE | LTDC_LxCKCR_CKGREEN | LTDC_LxCKCR_CKRED); + LTDC_LAYER(hltdc, LayerIdx)->CKCR = RGBValue; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Enable the color keying without reloading. + * Variant of the function HAL_LTDC_EnableColorKeying without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_EnableColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Enable LTDC color keying by setting COLKEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_COLKEN; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Disable the color keying without reloading. + * Variant of the function HAL_LTDC_DisableColorKeying without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_DisableColorKeying_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Disable LTDC color keying by setting COLKEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_COLKEN; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Enable the color lookup table without reloading. + * Variant of the function HAL_LTDC_EnableCLUT without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_EnableCLUT_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Disable LTDC color lookup table by setting CLUTEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_CLUTEN; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @brief Disable the color lookup table without reloading. + * Variant of the function HAL_LTDC_DisableCLUT without immediate reload. + * @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: + * LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDC_DisableCLUT_NoReload(LTDC_HandleTypeDef *hltdc, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LTDC_LAYER(LayerIdx)); + + /* Process locked */ + __HAL_LOCK(hltdc); + + /* Change LTDC peripheral state */ + hltdc->State = HAL_LTDC_STATE_BUSY; + + /* Disable LTDC color lookup table by setting CLUTEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR &= ~(uint32_t)LTDC_LxCR_CLUTEN; + + /* Change the LTDC state*/ + hltdc->State = HAL_LTDC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hltdc); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup LTDC_Exported_Functions_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 handle state. + (+) Get the LTDC handle error code. + +@endverbatim + * @{ + */ + +/** + * @brief Return the LTDC handle 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(const LTDC_HandleTypeDef *hltdc) +{ + return hltdc->State; +} + +/** + * @brief Return the LTDC handle 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(const LTDC_HandleTypeDef *hltdc) +{ + return hltdc->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup LTDC_Private_Functions LTDC Private Functions + * @{ + */ + +/** + * @brief Configure 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 structure + * @param LayerIdx LTDC Layer index. + * This parameter can be one of the following values: LTDC_LAYER_1 (0) or LTDC_LAYER_2 (1) + * @retval None + */ +static void LTDC_SetConfig(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx) +{ + uint32_t tmp; + uint32_t tmp1; + uint32_t tmp2; + + /* Configure the horizontal start and stop position */ + tmp = ((pLayerCfg->WindowX1 + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16U)) << 16U); + LTDC_LAYER(hltdc, LayerIdx)->WHPCR &= ~(LTDC_LxWHPCR_WHSTPOS | LTDC_LxWHPCR_WHSPPOS); + LTDC_LAYER(hltdc, LayerIdx)->WHPCR = ((pLayerCfg->WindowX0 + \ + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16U) + 1U) | tmp); + + /* Configure the vertical start and stop position */ + tmp = ((pLayerCfg->WindowY1 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP)) << 16U); + LTDC_LAYER(hltdc, LayerIdx)->WVPCR &= ~(LTDC_LxWVPCR_WVSTPOS | LTDC_LxWVPCR_WVSPPOS); + LTDC_LAYER(hltdc, LayerIdx)->WVPCR = ((pLayerCfg->WindowY0 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP) + 1U) | tmp); + + /* Specifies the pixel format */ + LTDC_LAYER(hltdc, LayerIdx)->PFCR &= ~(LTDC_LxPFCR_PF); + LTDC_LAYER(hltdc, LayerIdx)->PFCR = (pLayerCfg->PixelFormat); + + /* Configure the default color values */ + tmp = ((uint32_t)(pLayerCfg->Backcolor.Green) << 8U); + tmp1 = ((uint32_t)(pLayerCfg->Backcolor.Red) << 16U); + tmp2 = (pLayerCfg->Alpha0 << 24U); + WRITE_REG(LTDC_LAYER(hltdc, LayerIdx)->DCCR, (pLayerCfg->Backcolor.Blue | tmp | tmp1 | tmp2)); + + /* Specifies the constant alpha value */ + LTDC_LAYER(hltdc, LayerIdx)->CACR &= ~(LTDC_LxCACR_CONSTA); + LTDC_LAYER(hltdc, LayerIdx)->CACR = (pLayerCfg->Alpha); + + /* Specifies the blending factors */ + LTDC_LAYER(hltdc, LayerIdx)->BFCR &= ~(LTDC_LxBFCR_BF2 | LTDC_LxBFCR_BF1); + LTDC_LAYER(hltdc, LayerIdx)->BFCR = (pLayerCfg->BlendingFactor1 | pLayerCfg->BlendingFactor2); + + /* Configure the color frame buffer start address */ + WRITE_REG(LTDC_LAYER(hltdc, LayerIdx)->CFBAR, pLayerCfg->FBStartAdress); + + if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) + { + tmp = 4U; + } + else if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_RGB888) + { + tmp = 3U; + } + 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 = 2U; + } + else + { + tmp = 1U; + } + + /* Configure the color frame buffer pitch in byte */ + LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~(LTDC_LxCFBLR_CFBLL | LTDC_LxCFBLR_CFBP); + LTDC_LAYER(hltdc, LayerIdx)->CFBLR = (((pLayerCfg->ImageWidth * tmp) << 16U) | + (((pLayerCfg->WindowX1 - pLayerCfg->WindowX0) * tmp) + 7U)); + /* Configure the frame buffer line number */ + LTDC_LAYER(hltdc, LayerIdx)->CFBLNR &= ~(LTDC_LxCFBLNR_CFBLNBR); + LTDC_LAYER(hltdc, LayerIdx)->CFBLNR = (pLayerCfg->ImageHeight); + + /* Enable LTDC_Layer by setting LEN bit */ + LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_LEN; +} + +/** + * @} + */ + + +/** + * @} + */ + +#endif /* LTDC */ + +#endif /* HAL_LTDC_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc_ex.c index d1a69d0e3..10514a3f2 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ltdc_ex.c @@ -1,154 +1,153 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_ltdc_ex.c - * @author MCD Application Team - * @brief LTDC Extension HAL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#if defined(HAL_LTDC_MODULE_ENABLED) && defined(HAL_DSI_MODULE_ENABLED) - -#if defined (LTDC) && defined (DSI) - -/** @defgroup LTDCEx LTDCEx - * @brief LTDC HAL module driver - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup LTDCEx_Exported_Functions LTDC Extended Exported Functions - * @{ - */ - -/** @defgroup LTDCEx_Exported_Functions_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 - -@endverbatim - * @{ - */ - -/** - * @brief Retrieve common parameters from DSI Video mode configuration structure - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @param VidCfg pointer to a DSI_VidCfgTypeDef structure that contains - * the DSI video mode configuration parameters - * @note The implementation of this function is taking into account the LTDC - * polarities inversion as described in the current LTDC specification - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDCEx_StructInitFromVideoConfig(LTDC_HandleTypeDef *hltdc, DSI_VidCfgTypeDef *VidCfg) -{ - /* Retrieve signal polarities from DSI */ - - /* The following polarity is inverted: - LTDC_DEPOLARITY_AL <-> LTDC_DEPOLARITY_AH */ - -#if !defined(POLARITIES_INVERSION_UPDATED) - /* Note 1 : Code in line w/ Current LTDC specification */ - hltdc->Init.DEPolarity = (VidCfg->DEPolarity == \ - DSI_DATA_ENABLE_ACTIVE_HIGH) ? LTDC_DEPOLARITY_AL : LTDC_DEPOLARITY_AH; - hltdc->Init.VSPolarity = (VidCfg->VSPolarity == DSI_VSYNC_ACTIVE_HIGH) ? LTDC_VSPOLARITY_AH : LTDC_VSPOLARITY_AL; - hltdc->Init.HSPolarity = (VidCfg->HSPolarity == DSI_HSYNC_ACTIVE_HIGH) ? LTDC_HSPOLARITY_AH : LTDC_HSPOLARITY_AL; -#else - /* Note 2: Code to be used in case LTDC polarities inversion updated in the specification */ - hltdc->Init.DEPolarity = VidCfg->DEPolarity << 29; - hltdc->Init.VSPolarity = VidCfg->VSPolarity << 29; - hltdc->Init.HSPolarity = VidCfg->HSPolarity << 29; -#endif /* POLARITIES_INVERSION_UPDATED */ - - /* Retrieve vertical timing parameters from DSI */ - hltdc->Init.VerticalSync = VidCfg->VerticalSyncActive - 1U; - hltdc->Init.AccumulatedVBP = VidCfg->VerticalSyncActive + VidCfg->VerticalBackPorch - 1U; - hltdc->Init.AccumulatedActiveH = VidCfg->VerticalSyncActive + VidCfg->VerticalBackPorch + \ - VidCfg->VerticalActive - 1U; - hltdc->Init.TotalHeigh = VidCfg->VerticalSyncActive + VidCfg->VerticalBackPorch + \ - VidCfg->VerticalActive + VidCfg->VerticalFrontPorch - 1U; - - return HAL_OK; -} - -/** - * @brief Retrieve common parameters from DSI Adapted command mode configuration structure - * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains - * the configuration information for the LTDC. - * @param CmdCfg pointer to a DSI_CmdCfgTypeDef structure that contains - * the DSI command mode configuration parameters - * @note The implementation of this function is taking into account the LTDC - * polarities inversion as described in the current LTDC specification - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LTDCEx_StructInitFromAdaptedCommandConfig(LTDC_HandleTypeDef *hltdc, DSI_CmdCfgTypeDef *CmdCfg) -{ - /* Retrieve signal polarities from DSI */ - - /* The following polarities are inverted: - LTDC_DEPOLARITY_AL <-> LTDC_DEPOLARITY_AH - LTDC_VSPOLARITY_AL <-> LTDC_VSPOLARITY_AH - LTDC_HSPOLARITY_AL <-> LTDC_HSPOLARITY_AH)*/ - -#if !defined(POLARITIES_INVERSION_UPDATED) - /* Note 1 : Code in line w/ Current LTDC specification */ - hltdc->Init.DEPolarity = (CmdCfg->DEPolarity == \ - DSI_DATA_ENABLE_ACTIVE_HIGH) ? LTDC_DEPOLARITY_AL : LTDC_DEPOLARITY_AH; - hltdc->Init.VSPolarity = (CmdCfg->VSPolarity == DSI_VSYNC_ACTIVE_HIGH) ? LTDC_VSPOLARITY_AL : LTDC_VSPOLARITY_AH; - hltdc->Init.HSPolarity = (CmdCfg->HSPolarity == DSI_HSYNC_ACTIVE_HIGH) ? LTDC_HSPOLARITY_AL : LTDC_HSPOLARITY_AH; -#else - /* Note 2: Code to be used in case LTDC polarities inversion updated in the specification */ - hltdc->Init.DEPolarity = CmdCfg->DEPolarity << 29; - hltdc->Init.VSPolarity = CmdCfg->VSPolarity << 29; - hltdc->Init.HSPolarity = CmdCfg->HSPolarity << 29; -#endif /* POLARITIES_INVERSION_UPDATED */ - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* LTDC && DSI */ - -#endif /* HAL_LTCD_MODULE_ENABLED && HAL_DSI_MODULE_ENABLED */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_ltdc_ex.c + * @author MCD Application Team + * @brief LTDC Extension HAL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#if defined(HAL_LTDC_MODULE_ENABLED) && defined(HAL_DSI_MODULE_ENABLED) + +#if defined (LTDC) && defined (DSI) + +/** @defgroup LTDCEx LTDCEx + * @brief LTDC HAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup LTDCEx_Exported_Functions LTDC Extended Exported Functions + * @{ + */ + +/** @defgroup LTDCEx_Exported_Functions_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 + +@endverbatim + * @{ + */ + +/** + * @brief Retrieve common parameters from DSI Video mode configuration structure + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @param VidCfg pointer to a DSI_VidCfgTypeDef structure that contains + * the DSI video mode configuration parameters + * @note The implementation of this function is taking into account the LTDC + * polarities inversion as described in the current LTDC specification + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDCEx_StructInitFromVideoConfig(LTDC_HandleTypeDef *hltdc, DSI_VidCfgTypeDef *VidCfg) +{ + /* Retrieve signal polarities from DSI */ + + /* The following polarity is inverted: + LTDC_DEPOLARITY_AL <-> LTDC_DEPOLARITY_AH */ + +#if !defined(POLARITIES_INVERSION_UPDATED) + /* Note 1 : Code in line w/ Current LTDC specification */ + hltdc->Init.DEPolarity = (VidCfg->DEPolarity == \ + DSI_DATA_ENABLE_ACTIVE_HIGH) ? LTDC_DEPOLARITY_AL : LTDC_DEPOLARITY_AH; + hltdc->Init.VSPolarity = (VidCfg->VSPolarity == DSI_VSYNC_ACTIVE_HIGH) ? LTDC_VSPOLARITY_AH : LTDC_VSPOLARITY_AL; + hltdc->Init.HSPolarity = (VidCfg->HSPolarity == DSI_HSYNC_ACTIVE_HIGH) ? LTDC_HSPOLARITY_AH : LTDC_HSPOLARITY_AL; +#else + /* Note 2: Code to be used in case LTDC polarities inversion updated in the specification */ + hltdc->Init.DEPolarity = VidCfg->DEPolarity << 29; + hltdc->Init.VSPolarity = VidCfg->VSPolarity << 29; + hltdc->Init.HSPolarity = VidCfg->HSPolarity << 29; +#endif /* POLARITIES_INVERSION_UPDATED */ + + /* Retrieve vertical timing parameters from DSI */ + hltdc->Init.VerticalSync = VidCfg->VerticalSyncActive - 1U; + hltdc->Init.AccumulatedVBP = VidCfg->VerticalSyncActive + VidCfg->VerticalBackPorch - 1U; + hltdc->Init.AccumulatedActiveH = VidCfg->VerticalSyncActive + VidCfg->VerticalBackPorch + \ + VidCfg->VerticalActive - 1U; + hltdc->Init.TotalHeigh = VidCfg->VerticalSyncActive + VidCfg->VerticalBackPorch + \ + VidCfg->VerticalActive + VidCfg->VerticalFrontPorch - 1U; + + return HAL_OK; +} + +/** + * @brief Retrieve common parameters from DSI Adapted command mode configuration structure + * @param hltdc pointer to a LTDC_HandleTypeDef structure that contains + * the configuration information for the LTDC. + * @param CmdCfg pointer to a DSI_CmdCfgTypeDef structure that contains + * the DSI command mode configuration parameters + * @note The implementation of this function is taking into account the LTDC + * polarities inversion as described in the current LTDC specification + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LTDCEx_StructInitFromAdaptedCommandConfig(LTDC_HandleTypeDef *hltdc, DSI_CmdCfgTypeDef *CmdCfg) +{ + /* Retrieve signal polarities from DSI */ + + /* The following polarities are inverted: + LTDC_DEPOLARITY_AL <-> LTDC_DEPOLARITY_AH + LTDC_VSPOLARITY_AL <-> LTDC_VSPOLARITY_AH + LTDC_HSPOLARITY_AL <-> LTDC_HSPOLARITY_AH)*/ + +#if !defined(POLARITIES_INVERSION_UPDATED) + /* Note 1 : Code in line w/ Current LTDC specification */ + hltdc->Init.DEPolarity = (CmdCfg->DEPolarity == \ + DSI_DATA_ENABLE_ACTIVE_HIGH) ? LTDC_DEPOLARITY_AL : LTDC_DEPOLARITY_AH; + hltdc->Init.VSPolarity = (CmdCfg->VSPolarity == DSI_VSYNC_ACTIVE_HIGH) ? LTDC_VSPOLARITY_AL : LTDC_VSPOLARITY_AH; + hltdc->Init.HSPolarity = (CmdCfg->HSPolarity == DSI_HSYNC_ACTIVE_HIGH) ? LTDC_HSPOLARITY_AL : LTDC_HSPOLARITY_AH; +#else + /* Note 2: Code to be used in case LTDC polarities inversion updated in the specification */ + hltdc->Init.DEPolarity = CmdCfg->DEPolarity << 29; + hltdc->Init.VSPolarity = CmdCfg->VSPolarity << 29; + hltdc->Init.HSPolarity = CmdCfg->HSPolarity << 29; +#endif /* POLARITIES_INVERSION_UPDATED */ + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* LTDC && DSI */ + +#endif /* HAL_LTCD_MODULE_ENABLED && HAL_DSI_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mce.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mce.c index 849daabb6..fbffbd75a 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mce.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mce.c @@ -1,1063 +1,1074 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_mce.c - * @author MCD Application Team - * @brief MCE HAL module driver. - * This file provides firmware functions to manage the following - * features of the Memory Cipher Engine (MCE) peripheral: - * + Initialization and de-initialization functions - * + Region setting/enable functions - * + Peripheral State functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The MCE HAL driver can be used as follows: - - (#) ToBC (refer to MCE comments) - - - [..] - - *** Callback registration *** - ============================================= - [..] - - The compilation flag USE_HAL_MCE_REGISTER_CALLBACKS, when set to 1, - allows the user to configure dynamically the driver callbacks. - Use Functions @ref HAL_MCE_RegisterCallback() - to register an interrupt callback. - [..] - - ToBC (refer to MCE comments) - - When the compilation flag USE_HAL_MCE_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup MCE MCE - * @brief MCE HAL module driver. - * @{ - */ - - -#ifdef HAL_MCE_MODULE_ENABLED - -#if defined(MCE1) - -/* Private typedef -----------------------------------------------------------*/ -/* Private defines -----------------------------------------------------------*/ -#define MCE_TIMEOUT_VALUE 255U /* Internal timeout for keys valid flag */ -#define MCE1_CONTEXT_NB 2U -/* Private macros ------------------------------------------------------------*/ - - -#define IS_MCE_AES_INSTANCE(INSTANCE) ((INSTANCE) == MCE1) -#define IS_MCE_NOEKEON_INSTANCE(INSTANCE) ((INSTANCE) == MCE2) || ((INSTANCE) == MCE3) - -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ - - - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup MCE_Exported_Functions - * @{ - */ - -/** @defgroup MCE_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions. - * -@verbatim - ============================================================================== - ##### Initialization and de-initialization functions ##### - ============================================================================== - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the MCE peripheral and create the associated handle. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_Init(MCE_HandleTypeDef *hmce) -{ - /* Check the MCE handle allocation */ - if (hmce == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - if (hmce->State == HAL_MCE_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - __HAL_UNLOCK(hmce); - -#if (USE_HAL_MCE_REGISTER_CALLBACKS == 1) - /* Init the MCE Callback settings */ - hmce->ErrorCallback = HAL_MCE_ErrorCallback; /* Legacy weak callback */ - - if (hmce->MspInitCallback == NULL) - { - hmce->MspInitCallback = HAL_MCE_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware */ - hmce->MspInitCallback(hmce); -#else - /* Init the low level hardware */ - HAL_MCE_MspInit(hmce); -#endif /* USE_HAL_MCE_REGISTER_CALLBACKS */ - } - - /* Change the MCE state */ - hmce->State = HAL_MCE_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief DeInitialize the MCE peripheral. - * @note Any lock set at peripheral, key or cipher context level requires a MCE peripheral reset - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_DeInit(MCE_HandleTypeDef *hmce) -{ - MCE_Region_TypeDef *p_region; - MCE_Context_TypeDef *p_context; - - /* Check the MCE handle allocation */ - if (hmce == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - /* Change the MCE state */ - hmce->State = HAL_MCE_STATE_BUSY; - - /* Disable interrupts */ - CLEAR_BIT(hmce->Instance->IAIER, MCE_IAIER_IAEIE | MCE_IAIER_CAEIE); - - /* Disable all regions */ - for (uint32_t i = MCE_REGION1; i <= MCE_REGION4; i++) - { - p_region = (MCE_Region_TypeDef *)((uint32_t)(hmce->Instance) + 0x40U + (0x10U * i)); - CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); - CLEAR_BIT(p_region->ATTR, MCE_ATTR_WREN); - } - - /* Disable all cipher contexts if any for the MCE instance */ - if (hmce->Instance == MCE1) - { - for (uint32_t i = 0; i < MCE1_CONTEXT_NB; i++) - { - p_context = (MCE_Context_TypeDef *)((uint32_t)(hmce->Instance) + 0x240U + (0x30U * i)); - CLEAR_BIT(p_context->CCCFGR, MCE_CCCFGR_CCEN); - } - } - - /* Clear privileged-only configuration access */ - CLEAR_BIT(hmce->Instance->PRIVCFGR, MCE_PRIVCFGR_PRIV); - - /* Clear flags */ - WRITE_REG(hmce->Instance->IACR, MCE_IACR_IAEF | MCE_IACR_CAEF); - -#if (USE_HAL_MCE_REGISTER_CALLBACKS == 1) - if (hmce->MspDeInitCallback == NULL) - { - hmce->MspDeInitCallback = HAL_MCE_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: CLOCK, NVIC */ - hmce->MspDeInitCallback(hmce); -#else - /* DeInit the low level hardware: CLOCK, NVIC */ - HAL_MCE_MspDeInit(hmce); -#endif /* USE_HAL_MCE_REGISTER_CALLBACKS */ - - /* Change the MCE state */ - hmce->State = HAL_MCE_STATE_RESET; - - /* Reset MCE error status */ - hmce->ErrorCode = HAL_MCE_ERROR_NONE; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - - /* Return function status */ - return HAL_OK; -} - - -/** ********* main sequence functions : set the configuration of regions, AES context and Noekeon config *********/ - -/** - * @brief Write instance master or fast master keys - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param pConfig pointer at an MCE_NoekeonConfig structure that contains - the configuration on the Noekeon encryption engine - * @note Writes are ignored if MKLOCK or GLOCK bit is set in MCE_CR register and HAL error - * is reported in that case - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_ConfigNoekeon(MCE_HandleTypeDef *hmce, const MCE_NoekeonConfigTypeDef *pConfig) -{ - HAL_StatusTypeDef ret = HAL_OK; - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - assert_param(IS_MCE_NOEKEON_INSTANCE(hmce->Instance)); - /* If Key is null, or - if the global lock is set or - if the master keys lock is set, - return an error */ - tickstart = HAL_GetTick(); - if (((hmce->Instance->CR & (MCE_CR_GLOCK | MCE_CR_MKLOCK)) == 0U) && (pConfig->pKey != NULL)) - { - /* Take Lock */ - __HAL_LOCK(hmce); - - /* master keys are used for encryption */ - if (pConfig->KeyType == MCE_USE_MASTERKEYS) - { - /* If Master Key valid flag is set, need to write dummy value in MKEYRx to reset it */ - if ((hmce->Instance->SR & MCE_SR_MKVALID) != 0U) - { - WRITE_REG(hmce->Instance->MKEYR0, 0U); - } - - /* Set Key */ - WRITE_REG(hmce->Instance->MKEYR0, pConfig->pKey[0]); - WRITE_REG(hmce->Instance->MKEYR1, pConfig->pKey[1]); - WRITE_REG(hmce->Instance->MKEYR2, pConfig->pKey[2]); - WRITE_REG(hmce->Instance->MKEYR3, pConfig->pKey[3]); - if (HAL_IS_BIT_CLR(hmce->Instance->SR, MCE_SR_MKVALID)) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > MCE_TIMEOUT_VALUE) - { - - hmce->ErrorCode |= HAL_MCE_MASTER_KEY_ERROR; - ret = HAL_ERROR; - } - } - - } - else if (pConfig->KeyType == MCE_USE_FASTMASTERKEYS) - { - /* If Fast Master Key valid flag is set, need to write dummy value in FMKEYRx to reset it */ - if ((hmce->Instance->SR & MCE_SR_FMKVALID) != 0U) - { - WRITE_REG(hmce->Instance->FMKEYR0, 0U); - } - /* Set Key */ - WRITE_REG(hmce->Instance->FMKEYR0, pConfig->pKey[0]); - WRITE_REG(hmce->Instance->FMKEYR1, pConfig->pKey[1]); - WRITE_REG(hmce->Instance->FMKEYR2, pConfig->pKey[2]); - WRITE_REG(hmce->Instance->FMKEYR3, pConfig->pKey[3]); - if (HAL_IS_BIT_CLR(hmce->Instance->SR, MCE_SR_FMKVALID)) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > MCE_TIMEOUT_VALUE) - { - hmce->ErrorCode |= HAL_MCE_FASTMASTER_KEY_ERROR; - ret = HAL_ERROR; - } - } - } - else - { - /* nothing to do, the keytype is not valid */ - } - __HAL_UNLOCK(hmce); - } - return ret; -} - - -/** - * @brief Set context configuration. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param AESConfig context configuration - * @param ContextIndex index of context that is configured - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_ConfigAESContext(MCE_HandleTypeDef *hmce, const MCE_AESConfigTypeDef *AESConfig, - uint32_t ContextIndex) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Context_TypeDef *p_context; - uint32_t *p_key; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_AES_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - - - /* If global lock is set or no configuration provided, context cannot be configured */ - if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && (AESConfig != NULL) && \ - ((ContextIndex == MCE_CONTEXT1) || (ContextIndex == MCE_CONTEXT2))) - { - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ - (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); - p_context = (MCE_Context_TypeDef *)address; - /* Check cipher context is not locked */ - if (((p_context->CCCFGR & MCE_CCCFGR_CCLOCK) != MCE_CCCFGR_CCLOCK)) - { - if ((p_context->CCCFGR & MCE_CCCFGR_KEYLOCK) != MCE_CCCFGR_KEYLOCK) - { - /* Take Lock */ - __HAL_LOCK(hmce); - - /* Write nonce */ - WRITE_REG(p_context->CCNR0, AESConfig->Nonce[0]); - WRITE_REG(p_context->CCNR1, AESConfig->Nonce[1]); - - if (AESConfig->pKey != NULL) - { - p_key = AESConfig->pKey; - WRITE_REG(p_context->CCKEYR0, *p_key); - p_key++; - WRITE_REG(p_context->CCKEYR1, *p_key); - p_key++; - WRITE_REG(p_context->CCKEYR2, *p_key); - p_key++; - WRITE_REG(p_context->CCKEYR3, *p_key); - } - /* Compute theoretically expected CRC and compare it with that reported by the peripheral */ - - /* Write version */ - MODIFY_REG(p_context->CCCFGR, MCE_CCCFGR_VERSION, ((uint32_t) AESConfig->Version) << MCE_CCCFGR_VERSION_Pos); - - ret = HAL_OK; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - } - } - return ret; -} - - -/** - * @brief Set region configuration. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param RegionIndex index of region that is configured - * @param pConfig region configuration - * @note The region is enabled by default once the configuration is complete - * @note An enabled region is temporary disabled to apply the new configuration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_ConfigRegion(MCE_HandleTypeDef *hmce, uint32_t RegionIndex, - const MCE_RegionConfigTypeDef *pConfig) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Region_TypeDef *p_region; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_REGIONINDEX(RegionIndex)); - assert_param(IS_MCE_ALGORITHM(hmce->Instance, pConfig->Mode)); - - assert_param(IS_MCE_WRITE(pConfig->AccessMode)); - assert_param(IS_MCE_REGIONPRIVILEGED(pConfig->PrivilegedAccess)); - - /* If global lock is set or no configuration provided, region cannot be configured */ - if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && (pConfig != NULL)) - { - /* Take Lock */ - __HAL_LOCK(hmce); - - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); - p_region = (MCE_Region_TypeDef *)address; - - /* If region is enabled, disable it during the configuration process */ - if ((p_region->REGCR & MCE_REGCR_BREN) == MCE_REGCR_BREN) - { - CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); - } - - /* Set privileged access, ciphering algorithm and context ID */ - MODIFY_REG(p_region->REGCR, MCE_REGCR_ENC | MCE_REGCR_PRIV, \ - pConfig->PrivilegedAccess | pConfig->Mode); - - /* Set start and end addresses */ - WRITE_REG(p_region->SADDR, pConfig->StartAddress); - WRITE_REG(p_region->EADDR, pConfig->EndAddress); - - /* Set write attribute for the region */ - MODIFY_REG(p_region->ATTR, MCE_ATTR_WREN, pConfig->AccessMode); - - /* Enable the region by default */ - SET_BIT(p_region->REGCR, MCE_REGCR_BREN); - - ret = HAL_OK; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - - return ret; - -} - -HAL_StatusTypeDef HAL_MCE_SetRegionAESContext(MCE_HandleTypeDef *hmce, uint32_t ContextIndex, uint32_t RegionIndex) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Region_TypeDef *p_region; - __IO uint32_t address; - - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - assert_param(IS_MCE_REGIONINDEX(RegionIndex)); - - /* If global lock is set, region cannot be configured */ - if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) - { - - /* Take Lock */ - __HAL_LOCK(hmce); - - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); - p_region = (MCE_Region_TypeDef *)address; - - /* If region is enabled, disable it during the configuration process */ - if ((p_region->REGCR & MCE_REGCR_BREN) == MCE_REGCR_BREN) - { - CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); - } - - /* Set context ID */ - MODIFY_REG(p_region->REGCR, MCE_REGCR_CTXID, ContextIndex); - - /* Enable the region by default */ - SET_BIT(p_region->REGCR, MCE_REGCR_BREN); - - ret = HAL_OK; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - - } - - return ret; -} - - -/** ********* Enabling and disabling functions : enable/disable AES and Noekeon configurations and regions *********/ - - -/** - * @brief Cipher context enable - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param ContextIndex index of context that is enabled - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_EnableAESContext(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) -{ - MCE_Context_TypeDef *p_context; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - - if ((ContextIndex != MCE_CONTEXT1) && (ContextIndex != MCE_CONTEXT2)) - { - return HAL_ERROR; - } - - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ - (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); - p_context = (MCE_Context_TypeDef *)address; - - /* If cipher context is locked or if global lock is set, - and if cipher context is not enabled already, return an error */ - - if ((p_context->CCCFGR & MCE_CCCFGR_CCEN) != MCE_CCCFGR_CCEN) - { - if ((p_context->CCCFGR & MCE_CCCFGR_CCLOCK) == MCE_CCCFGR_CCLOCK) - { - return HAL_ERROR; - } - if ((hmce->Instance->CR & MCE_CR_GLOCK) == MCE_CR_GLOCK) - { - return HAL_ERROR; - } - } - - __HAL_LOCK(hmce); - - /* Enable context */ - SET_BIT(p_context->CCCFGR, MCE_CCCFGR_CCEN); - - __HAL_UNLOCK(hmce); - - return HAL_OK; - -} - -/** - * @brief Cipher context disable - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param ContextIndex index of context that is disabled - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_DisableAESContext(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) -{ - MCE_Context_TypeDef *p_context; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - - if ((ContextIndex != MCE_CONTEXT1) && (ContextIndex != MCE_CONTEXT2)) - { - return HAL_ERROR; - } - - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ - (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); - p_context = (MCE_Context_TypeDef *)address; - - /* If cipher context is locked or if global lock is set, - and if cipher context is not disabled already, return an error */ - - if ((p_context->CCCFGR & MCE_CCCFGR_CCEN) == MCE_CCCFGR_CCEN) - { - if ((p_context->CCCFGR & MCE_CCCFGR_CCLOCK) == MCE_CCCFGR_CCLOCK) - { - return HAL_ERROR; - } - if ((hmce->Instance->CR & MCE_CR_GLOCK) == MCE_CR_GLOCK) - { - return HAL_ERROR; - } - } - - __HAL_LOCK(hmce); - - /* Disable context */ - CLEAR_BIT(p_context->CCCFGR, MCE_CCCFGR_CCEN); - - __HAL_UNLOCK(hmce); - - return HAL_OK; - -} - - -/** - * @brief Enable region. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param RegionIndex index of region that is enabled - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_EnableRegion(MCE_HandleTypeDef *hmce, uint32_t RegionIndex) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Region_TypeDef *p_region; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_REGIONINDEX(RegionIndex)); - - /* If global lock is set, region cannot be configured */ - if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) - { - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); - p_region = (MCE_Region_TypeDef *)address; - - /* Take Lock */ - __HAL_LOCK(hmce); - - /* Check region is not enabled, else error */ - if ((p_region->REGCR & MCE_REGCR_BREN) != MCE_REGCR_BREN) - { - /* Enable the region */ - SET_BIT(p_region->REGCR, MCE_REGCR_BREN); - - ret = HAL_OK; - } - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - - return ret; - -} - - -/** - * @brief Disable region. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param RegionIndex index of region that is disabled - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_DisableRegion(MCE_HandleTypeDef *hmce, uint32_t RegionIndex) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Region_TypeDef *p_region; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_REGIONINDEX(RegionIndex)); - - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); - p_region = (MCE_Region_TypeDef *)address; - - /* If global lock is set, region cannot be configured */ - if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) - { - /* Take Lock */ - __HAL_LOCK(hmce); - - /* Check region is enabled, else error */ - if ((p_region->REGCR & MCE_REGCR_BREN) == MCE_REGCR_BREN) - { - /* Disable the region */ - CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); - - ret = HAL_OK; - } - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - - return ret; - -} - - -/** ************* Lock functions : Lock AES and Noekeon configurations and keys *********/ - -/** - * @brief Lock MCE instance registers configuration - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @note Once MCE_CR_GLOCK is set, all writes to MCE registers are ignored, - * with the exception of MCE_IACR and MCE_IAIER registers. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_LockGlobalConfig(MCE_HandleTypeDef *hmce) -{ - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - /* Take Lock */ - __HAL_LOCK(hmce); - - SET_BIT(hmce->Instance->CR, MCE_CR_GLOCK); - - /* Release Lock */ - __HAL_UNLOCK(hmce); - - return HAL_OK; - -} - -/** - * @brief Lock cipher context - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param ContextIndex index of context that is locked - * @note Once MCE_CCCFGR_CCLOCK is set, writes to MCE_CCxCFGR and MCE_CCxNR registers - * are ignored until next MCE reset. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_LockAESContextConfig(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Context_TypeDef *p_context; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - - /* If global lock is set or no configuration provided, context cannot be configured */ - if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && \ - ((ContextIndex == MCE_CONTEXT1) || (ContextIndex == MCE_CONTEXT2))) - { - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ - (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); - p_context = (MCE_Context_TypeDef *)address; - - /* Take Lock */ - __HAL_LOCK(hmce); - - SET_BIT(p_context->CCCFGR, MCE_CCCFGR_CCLOCK); - - ret = HAL_OK; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - - return ret; - -} - -/** - * @brief Lock context cipher key - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param ContextIndex index of context the cipher key of which is locked - * @note Once MCE_CCCFGR_KEYLOCK is set, writes to MCE_CCxKEYR registers are ignored - * until next MCE reset. KEYCRC bitfield value does not change. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_LockAESContextKey(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - MCE_Context_TypeDef *p_context; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - - /* If global lock is set or no configuration provided, context cannot be configured */ - if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && \ - ((ContextIndex == MCE_CONTEXT1) || (ContextIndex == MCE_CONTEXT2))) - { - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ - (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); - p_context = (MCE_Context_TypeDef *)address; - - /* Take Lock */ - __HAL_LOCK(hmce); - - SET_BIT(p_context->CCCFGR, MCE_CCCFGR_KEYLOCK); - - ret = HAL_OK; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - - return ret; - -} - -/** - * @brief Lock Noekeon master keys - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @note Once MCE_CR_MKLOCK is set, writes to MCE_MKEYRx and MCE_FMKEYRx registers are ignored until next MCE reset. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MCE_LockNoekeonMasterKeys(MCE_HandleTypeDef *hmce) -{ - HAL_StatusTypeDef ret = HAL_ERROR; - - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - /* If global lock is set, master keys lock cannot be set */ - if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) - { - /* Take Lock */ - __HAL_LOCK(hmce); - - SET_BIT(hmce->Instance->CR, MCE_CR_MKLOCK); - - ret = HAL_OK; - - /* Release Lock */ - __HAL_UNLOCK(hmce); - } - - return ret; - -} - - -/** - * @brief Initialize the MCE MSP. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval None - */ -__weak void HAL_MCE_MspInit(MCE_HandleTypeDef *hmce) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmce); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_MCE_MspInit can be implemented in the user file. - */ -} - -/** - * @brief DeInitialize MCE MSP. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval None - */ -__weak void HAL_MCE_MspDeInit(MCE_HandleTypeDef *hmce) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmce); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_MCE_MspDeInit can be implemented in the user file. - */ -} - -/** - * @brief get the CRC key of the specified context. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @param pCRCKey pointer to the CRC key - * @param ContextIndex index of CONTEXT the CRC key - * @retval HAL status - */ - -HAL_StatusTypeDef HAL_MCE_GetAESContextCRCKey(const MCE_HandleTypeDef *hmce, uint32_t *pCRCKey, uint32_t ContextIndex) -{ - HAL_StatusTypeDef ret = HAL_OK; - MCE_Context_TypeDef *p_context; - __IO uint32_t address; - - /* Check the parameters */ - assert_param(IS_MCE_AES_INSTANCE(hmce->Instance)); - assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); - - address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ - (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); - p_context = (MCE_Context_TypeDef *)address; - - *pCRCKey = READ_REG((p_context->CCCFGR)) & MCE_CCCFGR_KEYCRC; - - *pCRCKey >>= MCE_CCCFGR_KEYCRC_Pos; - if (*pCRCKey == 0x00U) - { - ret = HAL_ERROR; - } - - return ret; -} - -/** - * @brief Compute Key CRC - * @param pKey pointer at set of keys - * @retval CRC value - */ -uint32_t HAL_MCE_KeyCRCComputation(const uint32_t *pKey) -{ - uint8_t crc7_poly = 0x7; - const uint32_t key_strobe[4] = {0xAA55AA55U, 0x3U, 0x18U, 0xC0U}; - uint8_t i; - uint8_t crc = 0; - uint32_t j; - uint32_t keyval; - uint32_t k; - const uint32_t *temp = pKey; - - for (j = 0U; j < 4U; j++) - { - keyval = *temp; - temp++; - if (j == 0U) - { - keyval ^= key_strobe[0]; - } - else - { - keyval ^= (key_strobe[j] << 24) | ((uint32_t)crc << 16) | (key_strobe[j] << 8) | crc; - } - - crc = 0; - for (i = 0; i < (uint8_t)32; i++) - { - k = ((((uint32_t)crc >> 7) ^ ((keyval >> ((uint8_t)31 - i)) & ((uint8_t)0xF)))) & 1U; - crc <<= 1; - if (k != 0U) - { - crc ^= crc7_poly; - } - } - - crc ^= (uint8_t)0x55; - } - - return (uint32_t) crc; -} - -/** - * @brief Handle MCE interrupt request. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval None - */ -void HAL_MCE_IRQHandler(MCE_HandleTypeDef *hmce) -{ - uint32_t isr_reg; - uint32_t iaesr_reg; - - isr_reg = READ_REG(hmce->Instance->IASR); - if ((isr_reg & MCE_IASR_CAEF) == MCE_IASR_CAEF) - { - /* Set configuration access error */ - hmce->ErrorCode |= HAL_MCE_CONFIGURATION_ACCESS_ERROR; - - /* Clear configuration access error flag */ - WRITE_REG(hmce->Instance->IACR, MCE_IACR_CAEF); - } - if ((isr_reg & MCE_IASR_IAEF) == MCE_IASR_IAEF) - { - iaesr_reg = (READ_REG(hmce->Instance->IAESR) & (MCE_IAESR_IAPRIV | MCE_IAESR_IANRW)); - - /* Clear illegal access error flag */ - WRITE_REG(hmce->Instance->IACR, MCE_IACR_IAEF); - - /* Set precise illegal access error */ - if (iaesr_reg == MCE_IAESR_IAPRIV) - { - /* Illegal privileged data read or instruction fetch access error */ - hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_READ_PRIV_ERROR; - } - else if (iaesr_reg == (MCE_IAESR_IAPRIV | MCE_IAESR_IANRW)) - { - /* Illegal privileged data write access error */ - hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_WRITE_PRIV_ERROR; - } - else if (iaesr_reg == MCE_IAESR_IANRW) - { - /* Illegal un privileged data write access error */ - hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_WRITE_NPRIV_ERROR; - } - else - { - /* Illegal unprivileged data read or instruction fetch access error */ - hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_READ_NPRIV_ERROR; - } - } - -#if (USE_HAL_MCE_REGISTER_CALLBACKS == 1) - hmce->ErrorCallback(hmce); -#else - HAL_MCE_ErrorCallback(hmce); -#endif /* USE_HAL_MCE_REGISTER_CALLBACKS */ -} - -/** - * @brief MCE error callback. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval None - */ -__weak void HAL_MCE_ErrorCallback(MCE_HandleTypeDef *hmce) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmce); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_MCE_ErrorCallback can be implemented in the user file. - */ -} - -/** - * @brief Return the MCE state. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval HAL status - */ -HAL_MCE_StateTypeDef HAL_MCE_GetState(MCE_HandleTypeDef const *hmce) -{ - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - return hmce->State; -} - -/** - * @brief Return the MCE error code. - * @param hmce pointer to an MCE_HandleTypeDef structure that contains - * the configuration information for MCE module - * @retval MCE error code (bitfield on 32 bits) - */ -uint32_t HAL_MCE_GetError(MCE_HandleTypeDef const *hmce) -{ - /* Check the parameters */ - assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); - - return hmce->ErrorCode; -} - - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* MCE1 */ - -#endif /* HAL_MCE_MODULE_ENABLED */ - - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_mce.c + * @author MCD Application Team + * @brief MCE HAL module driver. + * This file provides firmware functions to manage the following + * features of the Memory Cipher Engine (MCE) peripheral: + * + Initialization and de-initialization functions + * + Region setting/enable functions + * + Peripheral State functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The MCE HAL driver can be used as follows: + + (#) ToBC (refer to MCE comments) + + + [..] + + *** Callback registration *** + ============================================= + [..] + + The compilation flag USE_HAL_MCE_REGISTER_CALLBACKS, when set to 1, + allows the user to configure dynamically the driver callbacks. + Use Functions @ref HAL_MCE_RegisterCallback() + to register an interrupt callback. + [..] + + ToBC (refer to MCE comments) + + When the compilation flag USE_HAL_MCE_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup MCE MCE + * @brief MCE HAL module driver. + * @{ + */ + + +#ifdef HAL_MCE_MODULE_ENABLED + +#if defined(MCE1) + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +#define MCE_TIMEOUT_VALUE 255U /* Internal timeout for keys valid flag */ +#define MCE1_CONTEXT_NB 2U +/* Private macros ------------------------------------------------------------*/ + +#define IS_MCE_AES_INSTANCE(INSTANCE) ((INSTANCE) == MCE1) + + +#define IS_MCE_NOEKEON_INSTANCE(INSTANCE) ((INSTANCE) == MCE2) || ((INSTANCE) == MCE3) + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup MCE_Exported_Functions + * @{ + */ + +/** @defgroup MCE_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the MCE peripheral and create the associated handle. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_Init(MCE_HandleTypeDef *hmce) +{ + /* Check the MCE handle allocation */ + if (hmce == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + if (hmce->State == HAL_MCE_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + __HAL_UNLOCK(hmce); + +#if (USE_HAL_MCE_REGISTER_CALLBACKS == 1) + /* Init the MCE Callback settings */ + hmce->ErrorCallback = HAL_MCE_ErrorCallback; /* Legacy weak callback */ + + if (hmce->MspInitCallback == NULL) + { + hmce->MspInitCallback = HAL_MCE_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hmce->MspInitCallback(hmce); +#else + /* Init the low level hardware */ + HAL_MCE_MspInit(hmce); +#endif /* USE_HAL_MCE_REGISTER_CALLBACKS */ + } + + /* Change the MCE state */ + hmce->State = HAL_MCE_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitialize the MCE peripheral. + * @note Any lock set at peripheral, key or cipher context level requires a MCE peripheral reset + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_DeInit(MCE_HandleTypeDef *hmce) +{ + MCE_Region_TypeDef *p_region; + MCE_Context_TypeDef *p_context; + + /* Check the MCE handle allocation */ + if (hmce == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + /* Change the MCE state */ + hmce->State = HAL_MCE_STATE_BUSY; + + /* Disable interrupts */ + CLEAR_BIT(hmce->Instance->IAIER, MCE_IAIER_IAEIE | MCE_IAIER_CAEIE); + + /* Disable all regions */ + for (uint32_t i = MCE_REGION1; i <= MCE_REGION4; i++) + { + p_region = (MCE_Region_TypeDef *)((uint32_t)(hmce->Instance) + 0x40U + (0x10U * i)); + CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); + CLEAR_BIT(p_region->ATTR, MCE_ATTR_WREN); + } + + /* Disable all cipher contexts if any for the MCE instance */ + if (hmce->Instance == MCE1) + { + for (uint32_t i = 0; i < MCE1_CONTEXT_NB; i++) + { + p_context = (MCE_Context_TypeDef *)((uint32_t)(hmce->Instance) + 0x240U + (0x30U * i)); + CLEAR_BIT(p_context->CCCFGR, MCE_CCCFGR_CCEN); + } + } + + /* Clear privileged-only configuration access */ + CLEAR_BIT(hmce->Instance->PRIVCFGR, MCE_PRIVCFGR_PRIV); + + /* Clear flags */ + WRITE_REG(hmce->Instance->IACR, MCE_IACR_IAEF | MCE_IACR_CAEF); + +#if (USE_HAL_MCE_REGISTER_CALLBACKS == 1) + if (hmce->MspDeInitCallback == NULL) + { + hmce->MspDeInitCallback = HAL_MCE_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: CLOCK, NVIC */ + hmce->MspDeInitCallback(hmce); +#else + /* DeInit the low level hardware: CLOCK, NVIC */ + HAL_MCE_MspDeInit(hmce); +#endif /* USE_HAL_MCE_REGISTER_CALLBACKS */ + + /* Change the MCE state */ + hmce->State = HAL_MCE_STATE_RESET; + + /* Reset MCE error status */ + hmce->ErrorCode = HAL_MCE_ERROR_NONE; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + + /* Return function status */ + return HAL_OK; +} + + +/** ********* main sequence functions : set the configuration of regions, AES context and Noekeon config *********/ + +/** + * @brief Write instance master or fast master keys + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param pConfig pointer at an MCE_NoekeonConfig structure that contains + the configuration on the Noekeon encryption engine + * @note Writes are ignored if MKLOCK or GLOCK bit is set in MCE_CR register and HAL error + * is reported in that case + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_ConfigNoekeon(MCE_HandleTypeDef *hmce, const MCE_NoekeonConfigTypeDef *pConfig) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + assert_param(IS_MCE_NOEKEON_INSTANCE(hmce->Instance)); + /* If Key is null, or + if the global lock is set or + if the master keys lock is set, + return an error */ + tickstart = HAL_GetTick(); + if (((hmce->Instance->CR & (MCE_CR_GLOCK | MCE_CR_MKLOCK)) == 0U) && (pConfig->pKey != NULL)) + { + /* Take Lock */ + __HAL_LOCK(hmce); + + /* master keys are used for encryption */ + if (pConfig->KeyType == MCE_USE_MASTERKEYS) + { + /* If Master Key valid flag is set, need to write dummy value in MKEYRx to reset it */ + if ((hmce->Instance->SR & MCE_SR_MKVALID) != 0U) + { + WRITE_REG(hmce->Instance->MKEYR0, 0U); + } + + /* Set Key */ + WRITE_REG(hmce->Instance->MKEYR0, pConfig->pKey[0]); + WRITE_REG(hmce->Instance->MKEYR1, pConfig->pKey[1]); + WRITE_REG(hmce->Instance->MKEYR2, pConfig->pKey[2]); + WRITE_REG(hmce->Instance->MKEYR3, pConfig->pKey[3]); + while (HAL_IS_BIT_CLR(hmce->Instance->SR, MCE_SR_MKVALID)) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > MCE_TIMEOUT_VALUE) + { + + hmce->ErrorCode |= HAL_MCE_MASTER_KEY_ERROR; + ret = HAL_ERROR; + break; + } + } + + } + else if (pConfig->KeyType == MCE_USE_FASTMASTERKEYS) + { + /* If Fast Master Key valid flag is set, need to write dummy value in FMKEYRx to reset it */ + if ((hmce->Instance->SR & MCE_SR_FMKVALID) != 0U) + { + WRITE_REG(hmce->Instance->FMKEYR0, 0U); + } + /* Set Key */ + WRITE_REG(hmce->Instance->FMKEYR0, pConfig->pKey[0]); + WRITE_REG(hmce->Instance->FMKEYR1, pConfig->pKey[1]); + WRITE_REG(hmce->Instance->FMKEYR2, pConfig->pKey[2]); + WRITE_REG(hmce->Instance->FMKEYR3, pConfig->pKey[3]); + while (HAL_IS_BIT_CLR(hmce->Instance->SR, MCE_SR_FMKVALID)) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > MCE_TIMEOUT_VALUE) + { + hmce->ErrorCode |= HAL_MCE_FASTMASTER_KEY_ERROR; + ret = HAL_ERROR; + break; + } + } + } + else + { + /* nothing to do, the keytype is not valid */ + } + __HAL_UNLOCK(hmce); + } + return ret; +} + + +/** + * @brief Set context configuration. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param AESConfig context configuration + * @param ContextIndex index of context that is configured + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_ConfigAESContext(MCE_HandleTypeDef *hmce, const MCE_AESConfigTypeDef *AESConfig, + uint32_t ContextIndex) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Context_TypeDef *p_context; + uint32_t *p_key; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_AES_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + + + /* If global lock is set or no configuration provided, context cannot be configured */ + if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && (AESConfig != NULL) && \ + ((ContextIndex == MCE_CONTEXT1) || (ContextIndex == MCE_CONTEXT2))) + { + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ + (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); + p_context = (MCE_Context_TypeDef *)address; + /* Check cipher context is not locked */ + if (((p_context->CCCFGR & MCE_CCCFGR_CCLOCK) != MCE_CCCFGR_CCLOCK)) + { + if ((p_context->CCCFGR & MCE_CCCFGR_KEYLOCK) != MCE_CCCFGR_KEYLOCK) + { + /* Take Lock */ + __HAL_LOCK(hmce); + + /* Write nonce */ + WRITE_REG(p_context->CCNR0, AESConfig->Nonce[0]); + WRITE_REG(p_context->CCNR1, AESConfig->Nonce[1]); + + if (AESConfig->pKey != NULL) + { + p_key = AESConfig->pKey; + WRITE_REG(p_context->CCKEYR0, *p_key); + p_key++; + WRITE_REG(p_context->CCKEYR1, *p_key); + p_key++; + WRITE_REG(p_context->CCKEYR2, *p_key); + p_key++; + WRITE_REG(p_context->CCKEYR3, *p_key); + } + /* Compute theoretically expected CRC and compare it with that reported by the peripheral */ + + /* Write version */ + MODIFY_REG(p_context->CCCFGR, MCE_CCCFGR_VERSION, ((uint32_t) AESConfig->Version) << MCE_CCCFGR_VERSION_Pos); + + ret = HAL_OK; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + } + } + return ret; +} + + +/** + * @brief Set region configuration. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param RegionIndex index of region that is configured + * @param pConfig region configuration + * @note The region is enabled by default once the configuration is complete + * @note An enabled region is temporary disabled to apply the new configuration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_ConfigRegion(MCE_HandleTypeDef *hmce, uint32_t RegionIndex, + const MCE_RegionConfigTypeDef *pConfig) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Region_TypeDef *p_region; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_REGIONINDEX(RegionIndex)); + assert_param(IS_MCE_ALGORITHM(hmce->Instance, pConfig->Mode)); + + assert_param(IS_MCE_WRITE(pConfig->AccessMode)); + assert_param(IS_MCE_REGIONPRIVILEGED(pConfig->PrivilegedAccess)); + + /* If global lock is set or no configuration provided, region cannot be configured */ + if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && (pConfig != NULL)) + { + /* Take Lock */ + __HAL_LOCK(hmce); + + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); + p_region = (MCE_Region_TypeDef *)address; + + /* If region is enabled, disable it during the configuration process */ + if ((p_region->REGCR & MCE_REGCR_BREN) == MCE_REGCR_BREN) + { + CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); + } + + /* Set privileged access, ciphering algorithm and context ID */ + MODIFY_REG(p_region->REGCR, MCE_REGCR_ENC | MCE_REGCR_PRIV, \ + pConfig->PrivilegedAccess | pConfig->Mode); + + /* Set start and end addresses */ + WRITE_REG(p_region->SADDR, pConfig->StartAddress); + WRITE_REG(p_region->EADDR, pConfig->EndAddress); + + /* Set write attribute for the region */ + MODIFY_REG(p_region->ATTR, MCE_ATTR_WREN, pConfig->AccessMode); + + /* Enable the region by default */ + SET_BIT(p_region->REGCR, MCE_REGCR_BREN); + + ret = HAL_OK; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + + return ret; + +} + +/** + * @brief Set region AES Context. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param ContextIndex index of context that is configured + * @param RegionIndex index of region that is configured + * @note The Region is enabled by default once the configuration is complete + * @note An enabled region is temporary disabled to apply the new configuration + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_MCE_SetRegionAESContext(MCE_HandleTypeDef *hmce, uint32_t ContextIndex, uint32_t RegionIndex) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Region_TypeDef *p_region; + __IO uint32_t address; + + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + assert_param(IS_MCE_REGIONINDEX(RegionIndex)); + + /* If global lock is set, region cannot be configured */ + if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) + { + + /* Take Lock */ + __HAL_LOCK(hmce); + + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); + p_region = (MCE_Region_TypeDef *)address; + + /* If region is enabled, disable it during the configuration process */ + if ((p_region->REGCR & MCE_REGCR_BREN) == MCE_REGCR_BREN) + { + CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); + } + + /* Set context ID */ + MODIFY_REG(p_region->REGCR, MCE_REGCR_CTXID, ContextIndex); + + /* Enable the region by default */ + SET_BIT(p_region->REGCR, MCE_REGCR_BREN); + + ret = HAL_OK; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + + } + + return ret; +} + + +/** ********* Enabling and disabling functions : enable/disable AES and Noekeon configurations and regions *********/ + + +/** + * @brief Cipher context enable + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param ContextIndex index of context that is enabled + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_EnableAESContext(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) +{ + MCE_Context_TypeDef *p_context; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + + if ((ContextIndex != MCE_CONTEXT1) && (ContextIndex != MCE_CONTEXT2)) + { + return HAL_ERROR; + } + + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ + (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); + p_context = (MCE_Context_TypeDef *)address; + + /* If cipher context is locked or if global lock is set, + and if cipher context is not enabled already, return an error */ + + if ((p_context->CCCFGR & MCE_CCCFGR_CCEN) != MCE_CCCFGR_CCEN) + { + if ((p_context->CCCFGR & MCE_CCCFGR_CCLOCK) == MCE_CCCFGR_CCLOCK) + { + return HAL_ERROR; + } + if ((hmce->Instance->CR & MCE_CR_GLOCK) == MCE_CR_GLOCK) + { + return HAL_ERROR; + } + } + + __HAL_LOCK(hmce); + + /* Enable context */ + SET_BIT(p_context->CCCFGR, MCE_CCCFGR_CCEN); + + __HAL_UNLOCK(hmce); + + return HAL_OK; + +} + +/** + * @brief Cipher context disable + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param ContextIndex index of context that is disabled + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_DisableAESContext(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) +{ + MCE_Context_TypeDef *p_context; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + + if ((ContextIndex != MCE_CONTEXT1) && (ContextIndex != MCE_CONTEXT2)) + { + return HAL_ERROR; + } + + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ + (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); + p_context = (MCE_Context_TypeDef *)address; + + /* If cipher context is locked or if global lock is set, + and if cipher context is not disabled already, return an error */ + + if ((p_context->CCCFGR & MCE_CCCFGR_CCEN) == MCE_CCCFGR_CCEN) + { + if ((p_context->CCCFGR & MCE_CCCFGR_CCLOCK) == MCE_CCCFGR_CCLOCK) + { + return HAL_ERROR; + } + if ((hmce->Instance->CR & MCE_CR_GLOCK) == MCE_CR_GLOCK) + { + return HAL_ERROR; + } + } + + __HAL_LOCK(hmce); + + /* Disable context */ + CLEAR_BIT(p_context->CCCFGR, MCE_CCCFGR_CCEN); + + __HAL_UNLOCK(hmce); + + return HAL_OK; + +} + + +/** + * @brief Enable region. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param RegionIndex index of region that is enabled + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_EnableRegion(MCE_HandleTypeDef *hmce, uint32_t RegionIndex) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Region_TypeDef *p_region; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_REGIONINDEX(RegionIndex)); + + /* If global lock is set, region cannot be configured */ + if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) + { + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); + p_region = (MCE_Region_TypeDef *)address; + + /* Take Lock */ + __HAL_LOCK(hmce); + + /* Check region is not enabled, else error */ + if ((p_region->REGCR & MCE_REGCR_BREN) != MCE_REGCR_BREN) + { + /* Enable the region */ + SET_BIT(p_region->REGCR, MCE_REGCR_BREN); + + ret = HAL_OK; + } + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + + return ret; + +} + + +/** + * @brief Disable region. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param RegionIndex index of region that is disabled + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_DisableRegion(MCE_HandleTypeDef *hmce, uint32_t RegionIndex) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Region_TypeDef *p_region; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_REGIONINDEX(RegionIndex)); + + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x40U + (0x10U * RegionIndex)); + p_region = (MCE_Region_TypeDef *)address; + + /* If global lock is set, region cannot be configured */ + if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) + { + /* Take Lock */ + __HAL_LOCK(hmce); + + /* Check region is enabled, else error */ + if ((p_region->REGCR & MCE_REGCR_BREN) == MCE_REGCR_BREN) + { + /* Disable the region */ + CLEAR_BIT(p_region->REGCR, MCE_REGCR_BREN); + + ret = HAL_OK; + } + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + + return ret; + +} + + +/** ************* Lock functions : Lock AES and Noekeon configurations and keys *********/ + +/** + * @brief Lock MCE instance registers configuration + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @note Once MCE_CR_GLOCK is set, all writes to MCE registers are ignored, + * with the exception of MCE_IACR and MCE_IAIER registers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_LockGlobalConfig(MCE_HandleTypeDef *hmce) +{ + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + /* Take Lock */ + __HAL_LOCK(hmce); + + SET_BIT(hmce->Instance->CR, MCE_CR_GLOCK); + + /* Release Lock */ + __HAL_UNLOCK(hmce); + + return HAL_OK; + +} + +/** + * @brief Lock cipher context + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param ContextIndex index of context that is locked + * @note Once MCE_CCCFGR_CCLOCK is set, writes to MCE_CCxCFGR and MCE_CCxNR registers + * are ignored until next MCE reset. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_LockAESContextConfig(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Context_TypeDef *p_context; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + + /* If global lock is set or no configuration provided, context cannot be configured */ + if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && \ + ((ContextIndex == MCE_CONTEXT1) || (ContextIndex == MCE_CONTEXT2))) + { + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ + (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); + p_context = (MCE_Context_TypeDef *)address; + + /* Take Lock */ + __HAL_LOCK(hmce); + + SET_BIT(p_context->CCCFGR, MCE_CCCFGR_CCLOCK); + + ret = HAL_OK; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + + return ret; + +} + +/** + * @brief Lock context cipher key + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param ContextIndex index of context the cipher key of which is locked + * @note Once MCE_CCCFGR_KEYLOCK is set, writes to MCE_CCxKEYR registers are ignored + * until next MCE reset. KEYCRC bitfield value does not change. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_LockAESContextKey(MCE_HandleTypeDef *hmce, uint32_t ContextIndex) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + MCE_Context_TypeDef *p_context; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + + /* If global lock is set or no configuration provided, context cannot be configured */ + if (((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) && \ + ((ContextIndex == MCE_CONTEXT1) || (ContextIndex == MCE_CONTEXT2))) + { + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ + (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); + p_context = (MCE_Context_TypeDef *)address; + + /* Take Lock */ + __HAL_LOCK(hmce); + + SET_BIT(p_context->CCCFGR, MCE_CCCFGR_KEYLOCK); + + ret = HAL_OK; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + + return ret; + +} + +/** + * @brief Lock Noekeon master keys + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @note Once MCE_CR_MKLOCK is set, writes to MCE_MKEYRx and MCE_FMKEYRx registers are ignored until next MCE reset. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MCE_LockNoekeonMasterKeys(MCE_HandleTypeDef *hmce) +{ + HAL_StatusTypeDef ret = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + /* If global lock is set, master keys lock cannot be set */ + if ((hmce->Instance->CR & MCE_CR_GLOCK) != MCE_CR_GLOCK) + { + /* Take Lock */ + __HAL_LOCK(hmce); + + SET_BIT(hmce->Instance->CR, MCE_CR_MKLOCK); + + ret = HAL_OK; + + /* Release Lock */ + __HAL_UNLOCK(hmce); + } + + return ret; + +} + + +/** + * @brief Initialize the MCE MSP. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval None + */ +__weak void HAL_MCE_MspInit(MCE_HandleTypeDef *hmce) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmce); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_MCE_MspInit can be implemented in the user file. + */ +} + +/** + * @brief DeInitialize MCE MSP. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval None + */ +__weak void HAL_MCE_MspDeInit(MCE_HandleTypeDef *hmce) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmce); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_MCE_MspDeInit can be implemented in the user file. + */ +} + +/** + * @brief get the CRC key of the specified context. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @param pCRCKey pointer to the CRC key + * @param ContextIndex index of CONTEXT the CRC key + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_MCE_GetAESContextCRCKey(const MCE_HandleTypeDef *hmce, uint32_t *pCRCKey, uint32_t ContextIndex) +{ + HAL_StatusTypeDef ret = HAL_OK; + MCE_Context_TypeDef *p_context; + __IO uint32_t address; + + /* Check the parameters */ + assert_param(IS_MCE_AES_INSTANCE(hmce->Instance)); + assert_param(IS_MCE_CONTEXT(hmce->Instance, ContextIndex)); + + if (*pCRCKey == 0x00U) + { + ret = HAL_ERROR; + } + + address = (__IO uint32_t)((uint32_t)hmce->Instance + 0x240UL + \ + (0x30UL * ((ContextIndex - MCE_CONTEXT1) >> MCE_REGCR_CTXID_Pos))); + p_context = (MCE_Context_TypeDef *)address; + + *pCRCKey = READ_REG((p_context->CCCFGR)) & MCE_CCCFGR_KEYCRC; + + *pCRCKey >>= MCE_CCCFGR_KEYCRC_Pos; + return ret; +} + +/** + * @brief Compute Key CRC + * @param pKey pointer at set of keys + * @retval CRC value + */ +uint32_t HAL_MCE_KeyCRCComputation(const uint32_t *pKey) +{ + uint8_t crc7_poly = 0x7; + const uint32_t key_strobe[4] = {0xAA55AA55U, 0x3U, 0x18U, 0xC0U}; + uint8_t i; + uint8_t crc = 0; + uint32_t j; + uint32_t keyval; + uint32_t k; + const uint32_t *temp = pKey; + + for (j = 0U; j < 4U; j++) + { + keyval = *temp; + temp++; + if (j == 0U) + { + keyval ^= key_strobe[0]; + } + else + { + keyval ^= (key_strobe[j] << 24) | ((uint32_t)crc << 16) | (key_strobe[j] << 8) | crc; + } + + crc = 0; + for (i = 0; i < (uint8_t)32; i++) + { + k = ((((uint32_t)crc >> 7) ^ ((keyval >> ((uint8_t)31 - i)) & ((uint8_t)0xF)))) & 1U; + crc <<= 1; + if (k != 0U) + { + crc ^= crc7_poly; + } + } + + crc ^= (uint8_t)0x55; + } + + return (uint32_t) crc; +} + +/** + * @brief Handle MCE interrupt request. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval None + */ +void HAL_MCE_IRQHandler(MCE_HandleTypeDef *hmce) +{ + uint32_t isr_reg; + uint32_t iaesr_reg; + + isr_reg = READ_REG(hmce->Instance->IASR); + if ((isr_reg & MCE_IASR_CAEF) == MCE_IASR_CAEF) + { + /* Set configuration access error */ + hmce->ErrorCode |= HAL_MCE_CONFIGURATION_ACCESS_ERROR; + + /* Clear configuration access error flag */ + WRITE_REG(hmce->Instance->IACR, MCE_IACR_CAEF); + } + if ((isr_reg & MCE_IASR_IAEF) == MCE_IASR_IAEF) + { + iaesr_reg = (READ_REG(hmce->Instance->IAESR) & (MCE_IAESR_IAPRIV | MCE_IAESR_IANRW)); + + /* Clear illegal access error flag */ + WRITE_REG(hmce->Instance->IACR, MCE_IACR_IAEF); + + /* Set precise illegal access error */ + if (iaesr_reg == MCE_IAESR_IAPRIV) + { + /* Illegal privileged data read or instruction fetch access error */ + hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_READ_PRIV_ERROR; + } + else if (iaesr_reg == (MCE_IAESR_IAPRIV | MCE_IAESR_IANRW)) + { + /* Illegal privileged data write access error */ + hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_WRITE_PRIV_ERROR; + } + else if (iaesr_reg == MCE_IAESR_IANRW) + { + /* Illegal un privileged data write access error */ + hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_WRITE_NPRIV_ERROR; + } + else + { + /* Illegal unprivileged data read or instruction fetch access error */ + hmce->ErrorCode |= HAL_MCE_ILLEGAL_ACCESS_READ_NPRIV_ERROR; + } + } + +#if (USE_HAL_MCE_REGISTER_CALLBACKS == 1) + hmce->ErrorCallback(hmce); +#else + HAL_MCE_ErrorCallback(hmce); +#endif /* USE_HAL_MCE_REGISTER_CALLBACKS */ +} + +/** + * @brief MCE error callback. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval None + */ +__weak void HAL_MCE_ErrorCallback(MCE_HandleTypeDef *hmce) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmce); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_MCE_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief Return the MCE state. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval HAL status + */ +HAL_MCE_StateTypeDef HAL_MCE_GetState(MCE_HandleTypeDef const *hmce) +{ + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + return hmce->State; +} + +/** + * @brief Return the MCE error code. + * @param hmce pointer to an MCE_HandleTypeDef structure that contains + * the configuration information for MCE module + * @retval MCE error code (bitfield on 32 bits) + */ +uint32_t HAL_MCE_GetError(MCE_HandleTypeDef const *hmce) +{ + /* Check the parameters */ + assert_param(IS_MCE_ALL_INSTANCE(hmce->Instance)); + + return hmce->ErrorCode; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* MCE1 */ + +#endif /* HAL_MCE_MODULE_ENABLED */ + + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdf.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdf.c index fb9ddbce0..11d2f4bcf 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdf.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdf.c @@ -1,2236 +1,2236 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_mdf.c - * @author MCD Application Team - * @brief This file provides firmware functions to manage the following - * functionalities of the Multi-function Digital Filter (MDF) - * peripheral: - * + Initialization and de-initialization - * + Acquisition - * + Clock absence detection - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - *** Initialization and de-initialization *** - ============================================ - [..] - (#) User has first to initialize ADF instance. - (#) As prerequisite, fill in the HAL_MDF_MspInit() : - (++) Enable ADFz clock interface with __HAL_RCC_ADFz_CLK_ENABLE(). - (++) Enable the clocks for the used GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). - (++) Configure these pins in alternate mode using HAL_GPIO_Init(). - (++) If interrupt mode is used, enable and configure ADFz_FLTx - interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). - (++) If DMA mode is used, initialize and configure DMA. - (#) Configure the common parameters, serial interface parameters and - filter bitstream selection by calling HAL_MDF_Init() function. - - [..] - (#) User can de-initialize ADF instance with HAL_MDF_DeInit() function. - - *** Acquisition *** - =================== - [..] - (#) Configure filter parameters and start acquisition using HAL_MDF_AcqStart(), - HAL_MDF_AcqStart_IT() or HAL_MDF_AcqStart_DMA(). - (#) In polling mode : - (++) Use HAL_MDF_PollForAcq() to detect the end of acquisition. - Use HAL_MDF_GetAcqValue to get acquisition value. - (++) Use HAL_MDF_PollForSndLvl() to detect and get - new sound level value and ambient noise value. - (++) Use HAL_MDF_PollForSad() to detect sound activity. - (#) In interrupt mode : - (++) HAL_MDF_AcqCpltCallback() will be called at the end of acquisition. - Use HAL_MDF_GetAcqValue to get acquisition value. - (++) HAL_MDF_SndLvlCallback() will be called when new - sound level and ambient noise values are available. - (++) HAL_MDF_SadCallback() will be called when - sound activity detection occurs. - (++) HAL_MDF_ErrorCallback() will be called if overflow, filter overrun or - saturation occurs. - Use HAL_MDF_GetErrorCode() to get the corresponding error. - (#) In DMA mode : - (++) HAL_MDF_AcqHalfCpltCallback() and HAL_MDF_AcqCpltCallback() will be called - respectively at the half acquisition and at the acquisition complete. - (++) HAL_MDF_SndLvlCallback() will be called when new - sound level and ambient noise values are available. - (++) HAL_MDF_SadCallback() will be called when - sound activity detection occurs. - (++) HAL_MDF_ErrorCallback() will be called if overflow, filter overrun, - saturation or DMA error occurs. - Use HAL_MDF_GetErrorCode() to get the corresponding error. - (#) Use HAL_MDF_GenerateTrgo() to generate pulse on TRGO signal. - (#) During acquisition, use HAL_MDF_SetDelay() and HAL_MDF_GetDelay() to respectively - set and get the delay on data source. - (#) During acquisition, use HAL_MDF_SetGain() and HAL_MDF_GetGain() to respectively - set and get the filter gain. - (#) Stop acquisition using HAL_MDF_AcqStop(), HAL_MDF_AcqStop_IT() or HAL_MDF_AcqStop_DMA(). - - *** Clock absence detection *** - =============================== - [..] - (#) Clock absence detection is always enabled so no need to start clock absence detection - in polling mode. - Use HAL_MDF_CkabStart_IT() to start clock absence detection in interrupt mode. - (#) In polling mode, use HAL_MDF_PollForCkab() to detect the clock absence. - (#) In interrupt mode, HAL_MDF_ErrorCallback() will be called if clock absence detection - occurs. - Use HAL_MDF_GetErrorCode() to get the corresponding error. - (#) Stop clock absence detection in interrupt mode using HAL_MDF_CkabStop_IT(). - - *** generic functions *** - ========================= - [..] - (#) HAL_MDF_IRQHandler will be called when ADF interrupt occurs. - (#) HAL_MDF_ErrorCallback will be called when ADF error occurs. - (#) Use HAL_MDF_GetState() to get the current ADF instance state. - (#) Use HAL_MDF_GetErrorCode() to get the current ADF instance error code. - - *** Callback registration *** - ============================= - [..] - The compilation define USE_HAL_MDF_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use functions HAL_MDF_RegisterCallback(), HAL_MDF_RegisterOldCallback() - or HAL_MDF_RegisterSndLvlCallback() to register a user callback. - - [..] - Function HAL_MDF_RegisterCallback() allows to register following callbacks : - (+) AcqCpltCallback : Acquisition complete callback. - (+) AcqHalfCpltCallback : Acquisition half complete callback. - (+) SadCallback : Sound activity detection callback (only for ADF instance). - (+) ErrorCallback : Error callback. - (+) MspInitCallback : MSP init callback. - (+) MspDeInitCallback : MSP de-init callback. - [..] - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - [..] - For specific sound level callback use dedicated register callback : - HAL_MDF_RegisterSndLvlCallback(). - - [..] - Use function HAL_MDF_UnRegisterCallback() to reset a callback to the default weak function. - - [..] - HAL_MDF_UnRegisterCallback() takes as parameters the HAL peripheral handle and the Callback ID. - [..] - This function allows to reset following callbacks : - (+) AcqCpltCallback : Acquisition complete callback. - (+) AcqHalfCpltCallback : Acquisition half complete callback. - (+) SadCallback : Sound activity detection callback (only for ADF instance). - (+) ErrorCallback : Error callback. - (+) MspInitCallback : MSP init callback. - (+) MspDeInitCallback : MSP de-init callback. - - [..] - For specific sound level callback use dedicated unregister callback : - HAL_MDF_UnRegisterSndLvlCallback(). - - [..] - By default, after the call of init function and if the state is RESET - all callbacks are reset to the corresponding legacy weak functions : - examples HAL_MDF_AcqCpltCallback(), HAL_MDF_ErrorCallback(). - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak functions in the init and de-init only when these - callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the init and de-init keep and use - the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the init/de-init. - In that case first register the MspInit/MspDeInit user callbacks using - HAL_MDF_RegisterCallback() before calling init or de-init function. - - [..] - When the compilation define USE_HAL_MDF_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak callbacks are used. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup MDF MDF - * @brief MDF HAL module driver - * @{ - */ - -#ifdef HAL_MDF_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/** @defgroup MDF_Private_Typedefs MDF Private Typedefs - * @{ - */ -/** - * @} - */ - -/* Private define ------------------------------------------------------------*/ -/** @defgroup MDF_Private_Constants MDF Private Constants - * @{ - */ -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup MDF_Private_Variables MDF Private Variables - * @{ - */ -static MDF_HandleTypeDef *v_mdfHandle = NULL; -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup MDF_Private_Functions MDF Private Functions - * @{ - */ -static void MDF_AcqStart(MDF_HandleTypeDef *const hmdf, const MDF_FilterConfigTypeDef *const pFilterConfig); -static void MDF_DmaXferCpltCallback(DMA_HandleTypeDef *hdma); -static void MDF_DmaXferHalfCpltCallback(DMA_HandleTypeDef *hdma); -static void MDF_DmaErrorCallback(DMA_HandleTypeDef *hdma); -/** - * @} - */ - -/* Exported functions ---------------------------------------------------------*/ -/** @defgroup MDF_Exported_Functions MDF Exported Functions - * @{ - */ - -/** @defgroup MDF_Exported_Functions_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 ADF instance. - (+) De-initialize the ADF instance. - (+) Register and unregister callbacks. -@endverbatim - * @{ - */ - -/** - * @brief Initialize the MDF instance according to the specified parameters - * in the MDF_InitTypeDef structure and initialize the associated handle. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_Init(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check MDF handle */ - if (hmdf == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_MDF_ALL_INSTANCE(hmdf->Instance)); - assert_param(IS_MDF_FILTER_BITSTREAM(hmdf->Init.FilterBistream)); - assert_param(IS_FUNCTIONAL_STATE(hmdf->Init.SerialInterface.Activation)); - - /* Check that instance has not been already initialized */ - if (v_mdfHandle != NULL) - { - status = HAL_ERROR; - } - else - { -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - /* Reset callback pointers to the weak predefined callbacks */ - hmdf->SndLvCallback = HAL_MDF_SndLvlCallback; - hmdf->SadCallback = HAL_MDF_SadCallback; - hmdf->AcqCpltCallback = HAL_MDF_AcqCpltCallback; - hmdf->AcqHalfCpltCallback = HAL_MDF_AcqHalfCpltCallback; - hmdf->ErrorCallback = HAL_MDF_ErrorCallback; - - /* Call MDF MSP init function */ - if (hmdf->MspInitCallback == NULL) - { - hmdf->MspInitCallback = HAL_MDF_MspInit; - } - hmdf->MspInitCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - /* Call MDF MSP init function */ - HAL_MDF_MspInit(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - - /* Configure common parameters */ - /* Check clock generator status */ - if ((ADF1->CKGCR & MDF_CKGCR_CKGACTIVE) != 0U) - { - status = HAL_ERROR; - } - else - { - /* Configure processing clock divider, output clock divider, - output clock pins and output clock generation trigger */ - assert_param(IS_MDF_PROC_CLOCK_DIVIDER(hmdf->Init.CommonParam.ProcClockDivider)); - assert_param(IS_FUNCTIONAL_STATE(hmdf->Init.CommonParam.OutputClock.Activation)); - ADF1->CKGCR = 0U; - ADF1->CKGCR |= ((hmdf->Init.CommonParam.ProcClockDivider - 1U) << MDF_CKGCR_PROCDIV_Pos); - if (hmdf->Init.CommonParam.OutputClock.Activation == ENABLE) - { - assert_param(IS_MDF_OUTPUT_CLOCK_PINS(hmdf->Init.CommonParam.OutputClock.Pins)); - assert_param(IS_MDF_OUTPUT_CLOCK_DIVIDER(hmdf->Init.CommonParam.OutputClock.Divider)); - assert_param(IS_FUNCTIONAL_STATE(hmdf->Init.CommonParam.OutputClock.Trigger.Activation)); - ADF1->CKGCR |= (((hmdf->Init.CommonParam.OutputClock.Divider - 1U) << MDF_CKGCR_CCKDIV_Pos) | - hmdf->Init.CommonParam.OutputClock.Pins | - (hmdf->Init.CommonParam.OutputClock.Pins >> 4U)); - if (hmdf->Init.CommonParam.OutputClock.Trigger.Activation == ENABLE) - { - assert_param(IS_MDF_OUTPUT_CLOCK_TRIGGER_SOURCE(hmdf->Init.CommonParam.OutputClock.Trigger.Source)); - assert_param(IS_MDF_OUTPUT_CLOCK_TRIGGER_EDGE(hmdf->Init.CommonParam.OutputClock.Trigger.Edge)); - ADF1->CKGCR |= (hmdf->Init.CommonParam.OutputClock.Trigger.Source | - hmdf->Init.CommonParam.OutputClock.Trigger.Edge | - MDF_CKGCR_CKGMOD); - } - } - - /* Activate clock generator */ - ADF1->CKGCR |= MDF_CKGCR_CKGDEN; - } - - /* Configure serial interface */ - if ((status == HAL_OK) && (hmdf->Init.SerialInterface.Activation == ENABLE)) - { - /* Check serial interface status */ - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) != 0U) - { - status = HAL_ERROR; - } - else - { - /* Configure mode, clock source and threshold */ - assert_param(IS_MDF_SITF_MODE(hmdf->Init.SerialInterface.Mode)); - assert_param(IS_MDF_SITF_CLOCK_SOURCE(hmdf->Init.SerialInterface.ClockSource)); - assert_param(IS_MDF_SITF_THRESHOLD(hmdf->Init.SerialInterface.Threshold)); - hmdf->Instance->SITFCR = 0U; - hmdf->Instance->SITFCR |= ((hmdf->Init.SerialInterface.Threshold << MDF_SITFCR_STH_Pos) | - hmdf->Init.SerialInterface.Mode | hmdf->Init.SerialInterface.ClockSource); - - /* Activate serial interface */ - hmdf->Instance->SITFCR |= MDF_SITFCR_SITFEN; - } - } - - if (status == HAL_OK) - { - /* Configure filter bitstream */ - hmdf->Instance->BSMXCR &= ~(MDF_BSMXCR_BSSEL); - hmdf->Instance->BSMXCR |= hmdf->Init.FilterBistream; - - /* Update instance pointer */ - v_mdfHandle = hmdf; - - /* Update error code and state */ - hmdf->ErrorCode = MDF_ERROR_NONE; - hmdf->State = HAL_MDF_STATE_READY; - } - } - } - - /* Return function status */ - return status; -} - -/** - * @brief De-initialize the MDF instance. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_DeInit(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check MDF handle */ - if (hmdf == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check parameters */ - assert_param(IS_MDF_ALL_INSTANCE(hmdf->Instance)); - - /* Check that instance has not been already deinitialized */ - if (v_mdfHandle == NULL) - { - status = HAL_ERROR; - } - else - { - /* Disable sound activity detector if needed */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); - } - - /* Disable filter if needed */ - if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) - { - hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); - } - - /* Disable serial interface if needed */ - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) != 0U) - { - hmdf->Instance->SITFCR &= ~(MDF_SITFCR_SITFEN); - } - - /* Disable all interrupts and clear all pending flags */ - hmdf->Instance->DFLTIER = 0U; - hmdf->Instance->DFLTISR = 0xFFFFFFFFU; - - /* Disable clock generator */ - ADF1->CKGCR &= ~(MDF_CKGCR_CKGDEN); - - /* Call MDF MSP deinit function */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - if (hmdf->MspDeInitCallback == NULL) - { - hmdf->MspDeInitCallback = HAL_MDF_MspDeInit; - } - hmdf->MspDeInitCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_MspDeInit(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - - /* Update instance pointer */ - v_mdfHandle = (MDF_HandleTypeDef *) NULL; - - /* Update state */ - hmdf->State = HAL_MDF_STATE_RESET; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Initialize the MDF instance MSP. - * @param hmdf MDF handle. - * @retval None. - */ -__weak void HAL_MDF_MspInit(MDF_HandleTypeDef *hmdf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_MspInit could be implemented in the user file */ -} - -/** - * @brief De-initialize the MDF instance MSP. - * @param hmdf MDF handle. - * @retval None. - */ -__weak void HAL_MDF_MspDeInit(MDF_HandleTypeDef *hmdf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_MspDeInit could be implemented in the user file */ -} - -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) -/** - * @brief Register a user MDF callback to be used instead of the weak predefined callback. - * @param hmdf MDF handle. - * @param CallbackID ID of the callback to be registered. - * This parameter can be one of the following values: - * @arg @ref HAL_MDF_ACQ_COMPLETE_CB_ID acquisition complete callback ID. - * @arg @ref HAL_MDF_ACQ_HALFCOMPLETE_CB_ID acquisition half complete callback ID. - * @arg @ref HAL_MDF_SAD_CB_ID sound activity detector callback ID (only for ADF instance). - * @arg @ref HAL_MDF_ERROR_CB_ID error callback ID. - * @arg @ref HAL_MDF_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_MDF_MSPDEINIT_CB_ID MSP de-init callback ID. - * @param pCallback pointer to the callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_RegisterCallback(MDF_HandleTypeDef *hmdf, - HAL_MDF_CallbackIDTypeDef CallbackID, - pMDF_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pCallback == NULL) - { - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - else - { - if (hmdf->State == HAL_MDF_STATE_READY) - { - switch (CallbackID) - { - case HAL_MDF_ACQ_COMPLETE_CB_ID : - hmdf->AcqCpltCallback = pCallback; - break; - case HAL_MDF_ACQ_HALFCOMPLETE_CB_ID : - hmdf->AcqHalfCpltCallback = pCallback; - break; - case HAL_MDF_SAD_CB_ID : - hmdf->SadCallback = pCallback; - break; - case HAL_MDF_ERROR_CB_ID : - hmdf->ErrorCallback = pCallback; - break; - case HAL_MDF_MSPINIT_CB_ID : - hmdf->MspInitCallback = pCallback; - break; - case HAL_MDF_MSPDEINIT_CB_ID : - hmdf->MspDeInitCallback = pCallback; - break; - default : - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (hmdf->State == HAL_MDF_STATE_RESET) - { - switch (CallbackID) - { - case HAL_MDF_MSPINIT_CB_ID : - hmdf->MspInitCallback = pCallback; - break; - case HAL_MDF_MSPDEINIT_CB_ID : - hmdf->MspDeInitCallback = pCallback; - break; - default : - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Unregister a user MDF callback. - * MDF callback is redirected to the weak predefined callback. - * @param hmdf MDF handle. - * @param CallbackID ID of the callback to be unregistered. - * This parameter can be one of the following values: - * @arg @ref HAL_MDF_ACQ_COMPLETE_CB_ID acquisition complete callback ID. - * @arg @ref HAL_MDF_ACQ_HALFCOMPLETE_CB_ID acquisition half complete callback ID. - * @arg @ref HAL_MDF_SAD_CB_ID sound activity detector callback ID (only for ADF instance). - * @arg @ref HAL_MDF_ERROR_CB_ID error callback ID. - * @arg @ref HAL_MDF_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_MDF_MSPDEINIT_CB_ID MSP de-init callback ID. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_UnRegisterCallback(MDF_HandleTypeDef *hmdf, - HAL_MDF_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hmdf->State == HAL_MDF_STATE_READY) - { - switch (CallbackID) - { - case HAL_MDF_ACQ_COMPLETE_CB_ID : - hmdf->AcqCpltCallback = HAL_MDF_AcqCpltCallback; - break; - case HAL_MDF_ACQ_HALFCOMPLETE_CB_ID : - hmdf->AcqHalfCpltCallback = HAL_MDF_AcqHalfCpltCallback; - break; - case HAL_MDF_SAD_CB_ID : - hmdf->SadCallback = HAL_MDF_SadCallback; - break; - case HAL_MDF_ERROR_CB_ID : - hmdf->ErrorCallback = HAL_MDF_ErrorCallback; - break; - case HAL_MDF_MSPINIT_CB_ID : - hmdf->MspInitCallback = HAL_MDF_MspInit; - break; - case HAL_MDF_MSPDEINIT_CB_ID : - hmdf->MspDeInitCallback = HAL_MDF_MspDeInit; - break; - default : - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (hmdf->State == HAL_MDF_STATE_RESET) - { - switch (CallbackID) - { - case HAL_MDF_MSPINIT_CB_ID : - hmdf->MspInitCallback = HAL_MDF_MspInit; - break; - case HAL_MDF_MSPDEINIT_CB_ID : - hmdf->MspDeInitCallback = HAL_MDF_MspDeInit; - break; - default : - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - - /* Return function status */ - return status; -} - -/** - * @brief Register specific MDF sound level callback - * to be used instead of the weak predefined callback. - * @param hmdf MDF handle. - * @param pCallback pointer to the sound level callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_RegisterSndLvlCallback(MDF_HandleTypeDef *hmdf, - pMDF_SndLvlCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pCallback == NULL) - { - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - else - { - if (hmdf->State == HAL_MDF_STATE_READY) - { - hmdf->SndLvCallback = pCallback; - } - else - { - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Unregister the specific MDF sound level callback. - * MDF sound level callback is redirected to the weak predefined callback. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_UnRegisterSndLvlCallback(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hmdf->State == HAL_MDF_STATE_READY) - { - hmdf->SndLvCallback = HAL_MDF_SndLvlCallback; - } - else - { - /* Update error code and status */ - hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - - /* Return function status */ - return status; -} -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup MDF_Exported_Functions_Group2 Acquisition functions - * @brief Acquisition functions - * -@verbatim - ============================================================================== - ##### Acquisition functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Start and stop acquisition in polling, interrupt or DMA mode. - (+) Wait and get acquisition values. - (+) Generate pulse on TRGO signal. - (+) Modify and get some filter parameters during acquisition. - (+) Wait and get sound level values. - (+) Detect sound activity. -@endverbatim - * @{ - */ - -/** - * @brief This function allows to start acquisition in polling mode. - * @param hmdf MDF handle. - * @param pFilterConfig Filter configuration parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_AcqStart(MDF_HandleTypeDef *hmdf, const MDF_FilterConfigTypeDef *pFilterConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pFilterConfig == NULL) - { - status = HAL_ERROR; - } - else - { - assert_param(IS_MDF_ACQUISITION_MODE(pFilterConfig->AcquisitionMode)); - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); - if ((pFilterConfig->SoundActivity.Activation == ENABLE) && - ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE) || - (pFilterConfig->AcquisitionMode == MDF_MODE_SYNC_SINGLE) || - (pFilterConfig->AcquisitionMode == MDF_MODE_WINDOW_CONT))) - { - status = HAL_ERROR; - } - /* Check state */ - else if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - /* Check filter status */ - else if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) - { - status = HAL_ERROR; - } - else - { - /* Check SAD status */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Configure filter and start acquisition */ - hmdf->Instance->DFLTCR = 0U; - MDF_AcqStart(hmdf, pFilterConfig); - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to poll for available acquisition value. - * @param hmdf MDF handle. - * @param Timeout Timeout value in milliseconds. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_PollForAcq(MDF_HandleTypeDef *hmdf, uint32_t Timeout) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - else - { - uint32_t tickstart = HAL_GetTick(); - - /* Wait for available acquisition value */ - while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_RXNEF) != MDF_DFLTISR_RXNEF) && (status == HAL_OK)) - { - /* Check the timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - status = HAL_TIMEOUT; - } - } - } - - /* Check if data overflow, saturation or reshape filter occurs */ - uint32_t error_flags = (hmdf->Instance->DFLTISR & (MDF_DFLTISR_DOVRF | MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF)); - if (error_flags != 0U) - { - /* Update error code */ - if ((error_flags & MDF_DFLTISR_DOVRF) == MDF_DFLTISR_DOVRF) - { - hmdf->ErrorCode |= MDF_ERROR_ACQUISITION_OVERFLOW; - } - if ((error_flags & MDF_DFLTISR_SATF) == MDF_DFLTISR_SATF) - { - hmdf->ErrorCode |= MDF_ERROR_SATURATION; - } - if ((error_flags & MDF_DFLTISR_RFOVRF) == MDF_DFLTISR_RFOVRF) - { - hmdf->ErrorCode |= MDF_ERROR_RSF_OVERRUN; - } - - /* Clear corresponding flags */ - hmdf->Instance->DFLTISR |= error_flags; - - /* Call error callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->ErrorCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_ErrorCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - - if (status == HAL_OK) - { - /* Update state only in asynchronous single shot mode */ - if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_ACQMOD) == MDF_MODE_ASYNC_SINGLE) - { - hmdf->State = HAL_MDF_STATE_READY; - } - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to get acquisition value. - * @param hmdf MDF handle. - * @param pValue Acquisition value on 24 MSB. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_GetAcqValue(const MDF_HandleTypeDef *hmdf, int32_t *pValue) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pValue == NULL) - { - status = HAL_ERROR; - } - else - { - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - } - } - - if (status == HAL_OK) - { - /* Get acquisition value */ - *pValue = (int32_t) hmdf->Instance->DFLTDR; - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to stop acquisition in polling mode. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_AcqStop(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - /* Check if state is ready and filter active */ - if (hmdf->State == HAL_MDF_STATE_READY) - { - if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != MDF_DFLTCR_DFLTACTIVE) - { - status = HAL_ERROR; - } - } - else - { - status = HAL_ERROR; - } - } - else - { - /* Disable sound activity detector if needed */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); - } - } - - if (status == HAL_OK) - { - /* Disable filter */ - hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); - - /* Clear all potential pending flags */ - hmdf->Instance->DFLTISR |= (MDF_DFLTISR_DOVRF | MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF | - MDF_DFLTISR_SDDETF | MDF_DFLTISR_SDLVLF); - - /* Update state */ - hmdf->State = HAL_MDF_STATE_READY; - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to start acquisition in interrupt mode. - * @param hmdf MDF handle. - * @param pFilterConfig Filter configuration parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_AcqStart_IT(MDF_HandleTypeDef *hmdf, const MDF_FilterConfigTypeDef *pFilterConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pFilterConfig == NULL) - { - status = HAL_ERROR; - } - else - { - assert_param(IS_MDF_ACQUISITION_MODE(pFilterConfig->AcquisitionMode)); - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); - if ((pFilterConfig->SoundActivity.Activation == ENABLE) && - ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE) || - (pFilterConfig->AcquisitionMode == MDF_MODE_SYNC_SINGLE) || - (pFilterConfig->AcquisitionMode == MDF_MODE_WINDOW_CONT))) - { - status = HAL_ERROR; - } - /* Check state */ - else if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - /* Check filter status */ - else if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) - { - status = HAL_ERROR; - } - else - { - /* Check SAD status */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - if ((pFilterConfig->SoundActivity.Activation == DISABLE) || - (pFilterConfig->SoundActivity.DataMemoryTransfer != MDF_SAD_NO_MEMORY_TRANSFER)) - { - /* Enable data overflow and fifo threshold interrupts */ - hmdf->Instance->DFLTIER |= (MDF_DFLTIER_DOVRIE | MDF_DFLTIER_FTHIE); - } - - if (pFilterConfig->ReshapeFilter.Activation == ENABLE) - { - /* Enable reshape filter overrun interrupt */ - hmdf->Instance->DFLTIER |= MDF_DFLTIER_RFOVRIE; - } - - /* Enable saturation interrupt */ - hmdf->Instance->DFLTIER |= MDF_DFLTIER_SATIE; - - if (pFilterConfig->SoundActivity.Activation == ENABLE) - { - /* Enable sound level value ready and sound activity detection interrupts */ - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.SoundLevelInterrupt)); - hmdf->Instance->DFLTIER |= (pFilterConfig->SoundActivity.SoundLevelInterrupt == ENABLE) ? - (MDF_DFLTIER_SDLVLIE | MDF_DFLTIER_SDDETIE) : - MDF_DFLTIER_SDDETIE; - } - - /* Configure filter and start acquisition */ - hmdf->Instance->DFLTCR = 0U; - MDF_AcqStart(hmdf, pFilterConfig); - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to stop acquisition in interrupt mode. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_AcqStop_IT(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - /* Check if state is ready and filter active */ - if (hmdf->State == HAL_MDF_STATE_READY) - { - if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != MDF_DFLTCR_DFLTACTIVE) - { - status = HAL_ERROR; - } - } - else - { - status = HAL_ERROR; - } - } - else - { - /* Disable sound activity detector if needed */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); - } - } - - if (status == HAL_OK) - { - /* Disable filter */ - hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); - - /* Disable interrupts and clear all potential pending flags */ - hmdf->Instance->DFLTIER &= ~(MDF_DFLTIER_FTHIE | MDF_DFLTIER_DOVRIE | MDF_DFLTIER_SATIE | - MDF_DFLTIER_RFOVRIE | MDF_DFLTIER_SDDETIE | MDF_DFLTIER_SDLVLIE); - hmdf->Instance->DFLTISR |= (MDF_DFLTISR_DOVRF | MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF | - MDF_DFLTISR_SDDETF | MDF_DFLTISR_SDLVLF); - - /* Update state */ - hmdf->State = HAL_MDF_STATE_READY; - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to start acquisition in DMA mode. - * @param hmdf MDF handle. - * @param pFilterConfig Filter configuration parameters. - * @param pDmaConfig DMA configuration parameters. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_AcqStart_DMA(MDF_HandleTypeDef *hmdf, const MDF_FilterConfigTypeDef *pFilterConfig, - const MDF_DmaConfigTypeDef *pDmaConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if ((pFilterConfig == NULL) || (pDmaConfig == NULL)) - { - status = HAL_ERROR; - } - else - { - assert_param(IS_FUNCTIONAL_STATE(pDmaConfig->MsbOnly)); - assert_param(IS_MDF_ACQUISITION_MODE(pFilterConfig->AcquisitionMode)); - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); - if ((pFilterConfig->SoundActivity.Activation == ENABLE) && - ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE) || - (pFilterConfig->AcquisitionMode == MDF_MODE_SYNC_SINGLE) || - (pFilterConfig->AcquisitionMode == MDF_MODE_WINDOW_CONT))) - { - status = HAL_ERROR; - } - /* Check state */ - else if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - /* Check filter status */ - else if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) - { - status = HAL_ERROR; - } - else - { - /* Check SAD status */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - uint32_t SrcAddress; - - if (pFilterConfig->ReshapeFilter.Activation == ENABLE) - { - /* Enable reshape filter overrun interrupt */ - hmdf->Instance->DFLTIER |= MDF_DFLTIER_RFOVRIE; - } - - /* Enable saturation interrupt */ - hmdf->Instance->DFLTIER |= MDF_DFLTIER_SATIE; - - if (pFilterConfig->SoundActivity.Activation == ENABLE) - { - /* Enable sound level value ready and sound activity detection interrupts */ - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.SoundLevelInterrupt)); - hmdf->Instance->DFLTIER |= (pFilterConfig->SoundActivity.SoundLevelInterrupt == ENABLE) ? - (MDF_DFLTIER_SDLVLIE | MDF_DFLTIER_SDDETIE) : - MDF_DFLTIER_SDDETIE; - } - - /* Enable MDF DMA requests */ - hmdf->Instance->DFLTCR = MDF_DFLTCR_DMAEN; - - /* Start DMA transfer */ - hmdf->hdma->XferCpltCallback = MDF_DmaXferCpltCallback; - hmdf->hdma->XferHalfCpltCallback = MDF_DmaXferHalfCpltCallback; - hmdf->hdma->XferErrorCallback = MDF_DmaErrorCallback; - SrcAddress = (pDmaConfig->MsbOnly == ENABLE) ? (((uint32_t) &hmdf->Instance->DFLTDR) + 2U) : - (uint32_t) &hmdf->Instance->DFLTDR; - if ((hmdf->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hmdf->hdma->LinkedListQueue != NULL) - { - hmdf->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = pDmaConfig->DataLength; - hmdf->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = SrcAddress; - hmdf->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = pDmaConfig->Address; - - status = HAL_DMAEx_List_Start_IT(hmdf->hdma); - } - else - { - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hmdf->hdma, SrcAddress, pDmaConfig->Address, pDmaConfig->DataLength); - } - if (status != HAL_OK) - { - /* Update state */ - hmdf->State = HAL_MDF_STATE_ERROR; - status = HAL_ERROR; - } - else - { - /* Configure filter and start acquisition */ - MDF_AcqStart(hmdf, pFilterConfig); - } - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to stop acquisition in DMA mode. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_AcqStop_DMA(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check if state is ready and filter active */ - if (hmdf->State == HAL_MDF_STATE_READY) - { - if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != MDF_DFLTCR_DFLTACTIVE) - { - status = HAL_ERROR; - } - } - else - { - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - else - { - /* Stop the DMA transfer */ - if (HAL_DMA_Abort(hmdf->hdma) != HAL_OK) - { - /* Update state */ - hmdf->State = HAL_MDF_STATE_ERROR; - status = HAL_ERROR; - } - } - } - - if (status == HAL_OK) - { - /* Disable sound activity detector if needed */ - if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) - { - hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); - } - - /* Disable filter */ - hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); - - /* Disable interrupts and clear all potential pending flags */ - hmdf->Instance->DFLTIER &= ~(MDF_DFLTIER_SATIE | MDF_DFLTIER_RFOVRIE | MDF_DFLTIER_SDDETIE | - MDF_DFLTIER_SDLVLIE); - hmdf->Instance->DFLTISR |= (MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF | MDF_DFLTISR_SDDETF | - MDF_DFLTISR_SDLVLF); - - /* Disable MDF DMA requests */ - hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DMAEN); - - /* Update state */ - hmdf->State = HAL_MDF_STATE_READY; - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to generate pulse on TRGO signal. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_GenerateTrgo(const MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_READY) - { - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Check if trigger output control is already active */ - if ((ADF1->GCR & MDF_GCR_TRGO) == MDF_GCR_TRGO) - { - status = HAL_ERROR; - } - else - { - /* Generate pulse on trigger output control signal */ - ADF1->GCR |= MDF_GCR_TRGO; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to set delay to apply on data source in number of samples. - * @param hmdf MDF handle. - * @param Delay Delay to apply on data source in number of samples. - * This parameter must be a number between Min_Data = 0 and Max_Data = 127. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_SetDelay(MDF_HandleTypeDef *hmdf, uint32_t Delay) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_MDF_DELAY(Delay)); - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - else - { - /* Check if bitstream delay is already active */ - if ((hmdf->Instance->DLYCR & MDF_DLYCR_SKPBF) == MDF_DLYCR_SKPBF) - { - status = HAL_ERROR; - } - else - { - /* Configure bitstream delay */ - hmdf->Instance->DLYCR |= Delay; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to get current delay applied on data source in number of samples. - * @param hmdf MDF handle. - * @param pDelay Current delay applied on data source in number of samples. - * This value is between Min_Data = 0 and Max_Data = 127. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_GetDelay(const MDF_HandleTypeDef *hmdf, uint32_t *pDelay) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pDelay == NULL) - { - status = HAL_ERROR; - } - /* Check state */ - else if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - else - { - /* Get current bitstream delay */ - *pDelay = (hmdf->Instance->DLYCR & MDF_DLYCR_SKPDLY); - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to set filter gain. - * @param hmdf MDF handle. - * @param Gain Filter gain in step of around 3db (from -48db to 72dB). - * This parameter must be a number between Min_Data = -16 and Max_Data = 24. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_SetGain(MDF_HandleTypeDef *hmdf, int32_t Gain) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_MDF_GAIN(Gain)); - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - else - { - uint32_t register_gain_value; - uint32_t tmp_register; - - if (Gain < 0) - { - int32_t adjust_gain; - - /* adjust gain value to set on register for negative value (offset of -16) */ - adjust_gain = Gain - 16; - register_gain_value = ((uint32_t) adjust_gain & 0x3FU); - } - else - { - /* for positive value, no offset to apply */ - register_gain_value = (uint32_t) Gain; - } - /* Set gain */ - tmp_register = (hmdf->Instance->DFLTCICR & ~(MDF_DFLTCICR_SCALE)); - hmdf->Instance->DFLTCICR = (tmp_register | (register_gain_value << MDF_DFLTCICR_SCALE_Pos)); - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to get filter gain. - * @param hmdf MDF handle. - * @param pGain Filter gain in step of around 3db (from -48db to 72dB). - * This parameter is between Min_Data = -16 and Max_Data = 24. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_GetGain(const MDF_HandleTypeDef *hmdf, int32_t *pGain) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if (pGain == NULL) - { - status = HAL_ERROR; - } - /* Check state */ - else if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - else - { - uint32_t register_gain_value; - - /* Get current gain */ - register_gain_value = ((hmdf->Instance->DFLTCICR & MDF_DFLTCICR_SCALE) >> MDF_DFLTCICR_SCALE_Pos); - if (register_gain_value > 31U) - { - /* adjust gain value to set on register for negative value (offset of +16) */ - register_gain_value |= 0xFFFFFFC0U; - *pGain = (int32_t) register_gain_value + 16; - } - else - { - /* for positive value, no offset to apply */ - *pGain = (int32_t) register_gain_value; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to poll for sound level data. - * @param hmdf MDF handle. - * @param Timeout Timeout value in milliseconds. - * @param pSoundLevel Sound level. - This parameter can be a value between Min_Data = 0 and Max_Data = 32767. - * @param pAmbientNoise Ambient noise. - This parameter can be a value between Min_Data = 0 and Max_Data = 32767. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_PollForSndLvl(MDF_HandleTypeDef *hmdf, uint32_t Timeout, uint32_t *pSoundLevel, - uint32_t *pAmbientNoise) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - if ((pSoundLevel == NULL) || (pAmbientNoise == NULL)) - { - status = HAL_ERROR; - } - /* Check state */ - else if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - /* Check SAD status */ - else if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) == 0U) - { - status = HAL_ERROR; - } - else - { - uint32_t tickstart = HAL_GetTick(); - - /* Wait for available sound level data */ - while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_SDLVLF) != MDF_DFLTISR_SDLVLF) && (status == HAL_OK)) - { - /* Check the timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - status = HAL_TIMEOUT; - } - } - } - - if (status == HAL_OK) - { - /* Get sound level */ - *pSoundLevel = hmdf->Instance->SADSDLVR; - - /* Get ambient noise */ - *pAmbientNoise = hmdf->Instance->SADANLVR; - - /* Clear sound level ready flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDLVLF; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to poll for sound activity detection. - * @param hmdf MDF handle. - * @param Timeout Timeout value in milliseconds. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_PollForSad(MDF_HandleTypeDef *hmdf, uint32_t Timeout) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - status = HAL_ERROR; - } - /* Check SAD status */ - else if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) == 0U) - { - status = HAL_ERROR; - } - else - { - uint32_t tickstart = HAL_GetTick(); - - /* Wait for sound activity detection */ - while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_SDDETF) != MDF_DFLTISR_SDDETF) && (status == HAL_OK)) - { - /* Check the timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - status = HAL_TIMEOUT; - } - } - } - - if (status == HAL_OK) - { - /* Clear sound activity detection flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDDETF; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief MDF acquisition complete callback. - * @param hmdf MDF handle. - * @retval None. - */ -__weak void HAL_MDF_AcqCpltCallback(MDF_HandleTypeDef *hmdf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_AcqCpltCallback could be implemented in the user file */ -} - -/** - * @brief MDF acquisition half complete callback. - * @param hmdf MDF handle. - * @retval None. - */ -__weak void HAL_MDF_AcqHalfCpltCallback(MDF_HandleTypeDef *hmdf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_AcqHalfCpltCallback could be implemented in the user file */ -} - -/** - * @brief MDF sound level callback. - * @param hmdf MDF handle. - * @param SoundLevel Sound level value computed by sound activity detector. - * This parameter can be a value between Min_Data = 0 and Max_Data = 32767. - * @param AmbientNoise Ambient noise value computed by sound activity detector. - * This parameter can be a value between Min_Data = 0 and Max_Data = 32767. - * @retval None. - */ -__weak void HAL_MDF_SndLvlCallback(MDF_HandleTypeDef *hmdf, uint32_t SoundLevel, uint32_t AmbientNoise) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - UNUSED(SoundLevel); - UNUSED(AmbientNoise); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_SndLvlCallback could be implemented in the user file */ -} - -/** - * @brief MDF sound activity detector callback. - * @param hmdf MDF handle. - * @retval None. - */ -__weak void HAL_MDF_SadCallback(MDF_HandleTypeDef *hmdf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_SadCallback could be implemented in the user file */ -} - -/** - * @} - */ - -/** @defgroup MDF_Exported_Functions_Group3 Clock absence detection functions - * @brief Clock absence detection functions - * -@verbatim - ============================================================================== - ##### Clock absence detection functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Start and stop clock absence detection in interrupt mode. - (+) Detect clock absence. -@endverbatim - * @{ - */ - -/** - * @brief This function allows to poll for the clock absence detection. - * @param hmdf MDF handle. - * @param Timeout Timeout value in milliseconds. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_PollForCkab(MDF_HandleTypeDef *hmdf, uint32_t Timeout) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Check serial interface status and mode */ - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) == 0U) - { - status = HAL_ERROR; - } - else - { - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFMOD) != MDF_SITF_NORMAL_SPI_MODE) - { - status = HAL_ERROR; - } - } - } - - if (status == HAL_OK) - { - uint32_t tickstart = HAL_GetTick(); - - /* Wait for clock absence detection */ - while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_CKABF) != MDF_DFLTISR_CKABF) && (status == HAL_OK)) - { - /* Check the timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - status = HAL_TIMEOUT; - } - } - } - - if (status == HAL_OK) - { - /* Clear clock absence detection flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to start clock absence detection in interrupt mode. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_CkabStart_IT(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Check serial interface status and mode */ - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) == 0U) - { - status = HAL_ERROR; - } - else - { - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFMOD) != MDF_SITF_NORMAL_SPI_MODE) - { - status = HAL_ERROR; - } - } - } - - if (status == HAL_OK) - { - /* Clear clock absence detection flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; - - /* Check clock absence detection flag */ - if ((hmdf->Instance->DFLTISR & MDF_DFLTISR_CKABF) == MDF_DFLTISR_CKABF) - { - status = HAL_ERROR; - } - else - { - /* Enable clock absence detection interrupt */ - hmdf->Instance->DFLTIER |= MDF_DFLTIER_CKABIE; - } - } - - /* Return function status */ - return status; -} - -/** - * @brief This function allows to stop clock absence detection in interrupt mode. - * @param hmdf MDF handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_MDF_CkabStop_IT(MDF_HandleTypeDef *hmdf) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check state */ - if (hmdf->State != HAL_MDF_STATE_ACQUISITION) - { - if (hmdf->State != HAL_MDF_STATE_READY) - { - status = HAL_ERROR; - } - } - - if (status == HAL_OK) - { - /* Check serial interface status and mode */ - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) == 0U) - { - status = HAL_ERROR; - } - else - { - if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFMOD) != MDF_SITF_NORMAL_SPI_MODE) - { - status = HAL_ERROR; - } - } - } - - if (status == HAL_OK) - { - /* Disable clock absence detection interrupt */ - hmdf->Instance->DFLTIER &= ~(MDF_DFLTIER_CKABIE); - - /* Clear potential pending clock absence detection flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; - } - - /* Return function status */ - return status; -} - -/** - * @} - */ - -/** @defgroup MDF_Exported_Functions_Group4 Generic functions - * @brief Generic functions - * -@verbatim - ============================================================================== - ##### Generic functions ##### - ============================================================================== - [..] This section provides functions allowing to : - (+) Handle MDF interrupt. - (+) Inform user that error occurs. - (+) Get the current MDF instance state. - (+) Get the current MDF instance error code. -@endverbatim - * @{ - */ - -/** - * @brief This function handles the MDF interrupts. - * @param hmdf MDF handle. - * @retval None. - */ -void HAL_MDF_IRQHandler(MDF_HandleTypeDef *hmdf) -{ - uint32_t tmp_reg1; - uint32_t tmp_reg2; - uint32_t interrupts; - - /* Read current flags and interrupts and determine which ones occur */ - tmp_reg1 = hmdf->Instance->DFLTIER; - tmp_reg2 = hmdf->Instance->DFLTISR; - interrupts = (tmp_reg1 & tmp_reg2); - - /* Check if data overflow occurs */ - if ((interrupts & MDF_DFLTISR_DOVRF) == MDF_DFLTISR_DOVRF) - { - /* Clear data overflow flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_DOVRF; - - /* Update error code */ - hmdf->ErrorCode |= MDF_ERROR_ACQUISITION_OVERFLOW; - - /* Call error callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->ErrorCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_ErrorCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - /* Check if RXFIFO threshold occurs */ - else if ((interrupts & MDF_DFLTISR_FTHF) == MDF_DFLTISR_FTHF) - { - /* Call acquisition complete callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->AcqCpltCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_AcqCpltCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - - /* Update state only in asynchronous single shot mode */ - if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_ACQMOD) == MDF_MODE_ASYNC_SINGLE) - { - hmdf->State = HAL_MDF_STATE_READY; - } - } - /* Check if reshape filter overrun occurs */ - else if ((interrupts & MDF_DFLTISR_RFOVRF) == MDF_DFLTISR_RFOVRF) - { - /* Clear reshape filter overrun flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_RFOVRF; - - /* Update error code */ - hmdf->ErrorCode |= MDF_ERROR_RSF_OVERRUN; - - /* Call error callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->ErrorCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_ErrorCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - /* Check if clock absence detection occurs */ - else if ((interrupts & MDF_DFLTISR_CKABF) == MDF_DFLTISR_CKABF) - { - /* Clear clock absence detection flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; - - /* Update error code */ - hmdf->ErrorCode |= MDF_ERROR_CLOCK_ABSENCE; - - /* Call error callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->ErrorCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_ErrorCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - /* Check if saturation occurs */ - else if ((interrupts & MDF_DFLTISR_SATF) == MDF_DFLTISR_SATF) - { - /* Clear saturation flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_SATF; - - /* Update error code */ - hmdf->ErrorCode |= MDF_ERROR_SATURATION; - - /* Call error callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->ErrorCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_ErrorCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - /* Check if sound activity detection occurs */ - else if ((interrupts & MDF_DFLTISR_SDDETF) == MDF_DFLTISR_SDDETF) - { - /* Clear sound activity detection flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDDETF; - - /* Call sound activity detection callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->SadCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_SadCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - else - { - /* Check if sound level ready occurs */ - if ((interrupts & MDF_DFLTISR_SDLVLF) == MDF_DFLTISR_SDLVLF) - { - uint32_t sound_level; - uint32_t ambient_noise; - - /* Get sound level */ - sound_level = hmdf->Instance->SADSDLVR; - - /* Get ambient noise */ - ambient_noise = hmdf->Instance->SADANLVR; - - /* Clear sound level ready flag */ - hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDLVLF; - - /* Call sound level callback */ -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->SndLvCallback(hmdf, sound_level, ambient_noise); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_SndLvlCallback(hmdf, sound_level, ambient_noise); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief MDF error callback. - * @param hmdf MDF handle. - * @retval None. - */ -__weak void HAL_MDF_ErrorCallback(MDF_HandleTypeDef *hmdf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdf); - - /* NOTE : This function should not be modified, when the function is needed, - the HAL_MDF_ErrorCallback could be implemented in the user file */ -} - -/** - * @brief This function allows to get the current MDF state. - * @param hmdf MDF handle. - * @retval MDF state. - */ -HAL_MDF_StateTypeDef HAL_MDF_GetState(const MDF_HandleTypeDef *hmdf) -{ - /* Return MDF state */ - return hmdf->State; -} - -/** - * @brief This function allows to get the current MDF error. - * @param hmdf MDF handle. - * @retval MDF error code. - */ -uint32_t HAL_MDF_GetError(const MDF_HandleTypeDef *hmdf) -{ - /* Return MDF error code */ - return hmdf->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup MDF_Private_Functions - * @brief Private functions - * @{ - */ - -/** - * @brief This function allows to configure filter and start acquisition. - * @param hmdf MDF handle. - * @param pFilterConfig Filter configuration parameters. - * @retval None. - */ -static void MDF_AcqStart(MDF_HandleTypeDef *const hmdf, const MDF_FilterConfigTypeDef *const pFilterConfig) -{ - uint32_t register_gain_value; - - /* Configure acquisition mode, discard samples, trigger and fifo threshold */ - assert_param(IS_MDF_DISCARD_SAMPLES(pFilterConfig->DiscardSamples)); - assert_param(IS_MDF_FIFO_THRESHOLD(pFilterConfig->FifoThreshold)); - if ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_CONT) || - (pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE)) - { - /* Trigger parameters are not used */ - hmdf->Instance->DFLTCR |= (pFilterConfig->AcquisitionMode | pFilterConfig->FifoThreshold | - (pFilterConfig->DiscardSamples << MDF_DFLTCR_NBDIS_Pos)); - } - else - { - /* Trigger parameters are used */ - assert_param(IS_MDF_TRIGGER_SOURCE(pFilterConfig->Trigger.Source)); - assert_param(IS_MDF_TRIGGER_EDGE(pFilterConfig->Trigger.Edge)); - hmdf->Instance->DFLTCR |= (pFilterConfig->AcquisitionMode | pFilterConfig->FifoThreshold | - pFilterConfig->Trigger.Source | pFilterConfig->Trigger.Edge | - (pFilterConfig->DiscardSamples << MDF_DFLTCR_NBDIS_Pos)); - } - - /* Configure data source, CIC mode, decimation ratio and gain */ - assert_param(IS_MDF_DATA_SOURCE(pFilterConfig->DataSource)); - assert_param(IS_MDF_CIC_MODE(pFilterConfig->CicMode)); - assert_param(IS_MDF_DECIMATION_RATIO(pFilterConfig->DecimationRatio)); - assert_param(IS_MDF_GAIN(pFilterConfig->Gain)); - if (pFilterConfig->Gain < 0) - { - int32_t adjust_gain; - - /* adjust gain value to set on register for negative value (offset of -16) */ - adjust_gain = pFilterConfig->Gain - 16; - register_gain_value = ((uint32_t) adjust_gain & 0x3FU); - } - else - { - /* for positive value, no offset to apply */ - register_gain_value = (uint32_t) pFilterConfig->Gain; - } - hmdf->Instance->DFLTCICR = (pFilterConfig->DataSource | pFilterConfig->CicMode | - ((pFilterConfig->DecimationRatio - 1U) << MDF_DFLTCICR_MCICD_Pos) | - (register_gain_value << MDF_DFLTCICR_SCALE_Pos)); - - /* Configure bitstream delay */ - assert_param(IS_MDF_DELAY(pFilterConfig->Delay)); - hmdf->Instance->DLYCR = pFilterConfig->Delay; - - /* Configure reshape filter */ - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->ReshapeFilter.Activation)); - hmdf->Instance->DFLTRSFR = 0U; - if (pFilterConfig->ReshapeFilter.Activation == ENABLE) - { - /* Configure reshape filter decimation ratio */ - assert_param(IS_MDF_RSF_DECIMATION_RATIO(pFilterConfig->ReshapeFilter.DecimationRatio)); - hmdf->Instance->DFLTRSFR |= pFilterConfig->ReshapeFilter.DecimationRatio; - } - else - { - /* Bypass reshape filter */ - hmdf->Instance->DFLTRSFR |= MDF_DFLTRSFR_RSFLTBYP; - } - - /* Configure high-pass filter */ - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->HighPassFilter.Activation)); - if (pFilterConfig->HighPassFilter.Activation == ENABLE) - { - /* Configure high-pass filter cut-off frequency */ - assert_param(IS_MDF_HPF_CUTOFF_FREQ(pFilterConfig->HighPassFilter.CutOffFrequency)); - hmdf->Instance->DFLTRSFR |= pFilterConfig->HighPassFilter.CutOffFrequency; - } - else - { - /* Bypass high-pass filter */ - hmdf->Instance->DFLTRSFR |= MDF_DFLTRSFR_HPFBYP; - } - - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); - if (pFilterConfig->SoundActivity.Activation == ENABLE) - { - /* Configure SAD mode, frame size, hysteresis, sound trigger event - and data memory transfer only for ADF instance */ - assert_param(IS_MDF_SAD_MODE(pFilterConfig->SoundActivity.Mode)); - assert_param(IS_MDF_SAD_FRAME_SIZE(pFilterConfig->SoundActivity.FrameSize)); - if (pFilterConfig->SoundActivity.Mode != MDF_SAD_AMBIENT_NOISE_DETECTOR) - { - assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Hysteresis)); - } - assert_param(IS_MDF_SAD_SOUND_TRIGGER(pFilterConfig->SoundActivity.SoundTriggerEvent)); - assert_param(IS_MDF_SAD_DATA_MEMORY_TRANSFER(pFilterConfig->SoundActivity.DataMemoryTransfer)); - if ((pFilterConfig->SoundActivity.Mode != MDF_SAD_AMBIENT_NOISE_DETECTOR) && - (pFilterConfig->SoundActivity.Hysteresis == ENABLE)) - { - hmdf->Instance->SADCR = (pFilterConfig->SoundActivity.Mode | pFilterConfig->SoundActivity.FrameSize | - MDF_SADCR_HYSTEN | pFilterConfig->SoundActivity.SoundTriggerEvent | - pFilterConfig->SoundActivity.DataMemoryTransfer); - } - else - { - hmdf->Instance->SADCR = (pFilterConfig->SoundActivity.Mode | pFilterConfig->SoundActivity.FrameSize | - pFilterConfig->SoundActivity.SoundTriggerEvent | - pFilterConfig->SoundActivity.DataMemoryTransfer); - } - - /* Configure SAD minimum noise level, hangover window, learning frames, - ambient noise slope control and signal noise threshold only for ADF instance */ - assert_param(IS_MDF_SAD_MIN_NOISE_LEVEL(pFilterConfig->SoundActivity.MinNoiseLevel)); - assert_param(IS_MDF_SAD_HANGOVER_WINDOW(pFilterConfig->SoundActivity.HangoverWindow)); - assert_param(IS_MDF_SAD_LEARNING_FRAMES(pFilterConfig->SoundActivity.LearningFrames)); - assert_param(IS_MDF_SAD_SIGNAL_NOISE_THRESHOLD(pFilterConfig->SoundActivity.SignalNoiseThreshold)); - if (pFilterConfig->SoundActivity.Mode != MDF_SAD_SOUND_DETECTOR) - { - assert_param(IS_MDF_SAD_AMBIENT_NOISE_SLOPE(pFilterConfig->SoundActivity.AmbientNoiseSlope)); - hmdf->Instance->SADCFGR = ((pFilterConfig->SoundActivity.MinNoiseLevel << MDF_SADCFGR_ANMIN_Pos) | - pFilterConfig->SoundActivity.HangoverWindow | - pFilterConfig->SoundActivity.LearningFrames | - (pFilterConfig->SoundActivity.AmbientNoiseSlope << MDF_SADCFGR_ANSLP_Pos) | - pFilterConfig->SoundActivity.SignalNoiseThreshold); - } - else - { - hmdf->Instance->SADCFGR = ((pFilterConfig->SoundActivity.MinNoiseLevel << MDF_SADCFGR_ANMIN_Pos) | - pFilterConfig->SoundActivity.HangoverWindow | - pFilterConfig->SoundActivity.LearningFrames | - pFilterConfig->SoundActivity.SignalNoiseThreshold); - } - } - else - { - /* SAD is not used */ - hmdf->Instance->SADCR = 0U; - hmdf->Instance->SADCFGR = 0U; - } - - /* Update instance state */ - hmdf->State = HAL_MDF_STATE_ACQUISITION; - - /* Enable sound activity detector if needed */ - if (pFilterConfig->SoundActivity.Activation == ENABLE) - { - hmdf->Instance->SADCR |= MDF_SADCR_SADEN; - } - - /* Enable filter */ - hmdf->Instance->DFLTCR |= MDF_DFLTCR_DFLTEN; -} - -/** - * @brief This function handles DMA transfer complete callback. - * @param hdma DMA handle. - * @retval None. - */ -static void MDF_DmaXferCpltCallback(DMA_HandleTypeDef *hdma) -{ - MDF_HandleTypeDef *hmdf = (MDF_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Check if DMA in circular mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - hmdf->State = HAL_MDF_STATE_READY; - } - -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->AcqCpltCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_AcqCpltCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ -} - -/** - * @brief This function handles DMA half transfer complete callback. - * @param hdma DMA handle. - * @retval None. - */ -static void MDF_DmaXferHalfCpltCallback(DMA_HandleTypeDef *hdma) -{ - MDF_HandleTypeDef *hmdf = (MDF_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->AcqHalfCpltCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_AcqHalfCpltCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ -} - -/** - * @brief This function handles DMA error callback. - * @param hdma DMA handle. - * @retval None. - */ -static void MDF_DmaErrorCallback(DMA_HandleTypeDef *hdma) -{ - MDF_HandleTypeDef *hmdf = (MDF_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Update error code */ - hmdf->ErrorCode |= MDF_ERROR_DMA; - -#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) - hmdf->ErrorCallback(hmdf); -#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ - HAL_MDF_ErrorCallback(hmdf); -#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ -} - -/** - * @} - */ - -#endif /* HAL_MDF_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_mdf.c + * @author MCD Application Team + * @brief This file provides firmware functions to manage the following + * functionalities of the Multi-function Digital Filter (MDF) + * peripheral: + * + Initialization and de-initialization + * + Acquisition + * + Clock absence detection + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + *** Initialization and de-initialization *** + ============================================ + [..] + (#) User has first to initialize ADF instance. + (#) As prerequisite, fill in the HAL_MDF_MspInit() : + (++) Enable ADFz clock interface with __HAL_RCC_ADFz_CLK_ENABLE(). + (++) Enable the clocks for the used GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). + (++) Configure these pins in alternate mode using HAL_GPIO_Init(). + (++) If interrupt mode is used, enable and configure ADFz_FLTx + interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). + (++) If DMA mode is used, initialize and configure DMA. + (#) Configure the common parameters, serial interface parameters and + filter bitstream selection by calling HAL_MDF_Init() function. + + [..] + (#) User can de-initialize ADF instance with HAL_MDF_DeInit() function. + + *** Acquisition *** + =================== + [..] + (#) Configure filter parameters and start acquisition using HAL_MDF_AcqStart(), + HAL_MDF_AcqStart_IT() or HAL_MDF_AcqStart_DMA(). + (#) In polling mode : + (++) Use HAL_MDF_PollForAcq() to detect the end of acquisition. + Use HAL_MDF_GetAcqValue to get acquisition value. + (++) Use HAL_MDF_PollForSndLvl() to detect and get + new sound level value and ambient noise value. + (++) Use HAL_MDF_PollForSad() to detect sound activity. + (#) In interrupt mode : + (++) HAL_MDF_AcqCpltCallback() will be called at the end of acquisition. + Use HAL_MDF_GetAcqValue to get acquisition value. + (++) HAL_MDF_SndLvlCallback() will be called when new + sound level and ambient noise values are available. + (++) HAL_MDF_SadCallback() will be called when + sound activity detection occurs. + (++) HAL_MDF_ErrorCallback() will be called if overflow, filter overrun or + saturation occurs. + Use HAL_MDF_GetErrorCode() to get the corresponding error. + (#) In DMA mode : + (++) HAL_MDF_AcqHalfCpltCallback() and HAL_MDF_AcqCpltCallback() will be called + respectively at the half acquisition and at the acquisition complete. + (++) HAL_MDF_SndLvlCallback() will be called when new + sound level and ambient noise values are available. + (++) HAL_MDF_SadCallback() will be called when + sound activity detection occurs. + (++) HAL_MDF_ErrorCallback() will be called if overflow, filter overrun, + saturation or DMA error occurs. + Use HAL_MDF_GetErrorCode() to get the corresponding error. + (#) Use HAL_MDF_GenerateTrgo() to generate pulse on TRGO signal. + (#) During acquisition, use HAL_MDF_SetDelay() and HAL_MDF_GetDelay() to respectively + set and get the delay on data source. + (#) During acquisition, use HAL_MDF_SetGain() and HAL_MDF_GetGain() to respectively + set and get the filter gain. + (#) Stop acquisition using HAL_MDF_AcqStop(), HAL_MDF_AcqStop_IT() or HAL_MDF_AcqStop_DMA(). + + *** Clock absence detection *** + =============================== + [..] + (#) Clock absence detection is always enabled so no need to start clock absence detection + in polling mode. + Use HAL_MDF_CkabStart_IT() to start clock absence detection in interrupt mode. + (#) In polling mode, use HAL_MDF_PollForCkab() to detect the clock absence. + (#) In interrupt mode, HAL_MDF_ErrorCallback() will be called if clock absence detection + occurs. + Use HAL_MDF_GetErrorCode() to get the corresponding error. + (#) Stop clock absence detection in interrupt mode using HAL_MDF_CkabStop_IT(). + + *** generic functions *** + ========================= + [..] + (#) HAL_MDF_IRQHandler will be called when ADF interrupt occurs. + (#) HAL_MDF_ErrorCallback will be called when ADF error occurs. + (#) Use HAL_MDF_GetState() to get the current ADF instance state. + (#) Use HAL_MDF_GetErrorCode() to get the current ADF instance error code. + + *** Callback registration *** + ============================= + [..] + The compilation define USE_HAL_MDF_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use functions HAL_MDF_RegisterCallback(), HAL_MDF_RegisterOldCallback() + or HAL_MDF_RegisterSndLvlCallback() to register a user callback. + + [..] + Function HAL_MDF_RegisterCallback() allows to register following callbacks : + (+) AcqCpltCallback : Acquisition complete callback. + (+) AcqHalfCpltCallback : Acquisition half complete callback. + (+) SadCallback : Sound activity detection callback (only for ADF instance). + (+) ErrorCallback : Error callback. + (+) MspInitCallback : MSP init callback. + (+) MspDeInitCallback : MSP de-init callback. + [..] + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + For specific sound level callback use dedicated register callback : + HAL_MDF_RegisterSndLvlCallback(). + + [..] + Use function HAL_MDF_UnRegisterCallback() to reset a callback to the default weak function. + + [..] + HAL_MDF_UnRegisterCallback() takes as parameters the HAL peripheral handle and the Callback ID. + [..] + This function allows to reset following callbacks : + (+) AcqCpltCallback : Acquisition complete callback. + (+) AcqHalfCpltCallback : Acquisition half complete callback. + (+) SadCallback : Sound activity detection callback (only for ADF instance). + (+) ErrorCallback : Error callback. + (+) MspInitCallback : MSP init callback. + (+) MspDeInitCallback : MSP de-init callback. + + [..] + For specific sound level callback use dedicated unregister callback : + HAL_MDF_UnRegisterSndLvlCallback(). + + [..] + By default, after the call of init function and if the state is RESET + all callbacks are reset to the corresponding legacy weak functions : + examples HAL_MDF_AcqCpltCallback(), HAL_MDF_ErrorCallback(). + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak functions in the init and de-init only when these + callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the init and de-init keep and use + the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the init/de-init. + In that case first register the MspInit/MspDeInit user callbacks using + HAL_MDF_RegisterCallback() before calling init or de-init function. + + [..] + When the compilation define USE_HAL_MDF_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak callbacks are used. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup MDF MDF + * @brief MDF HAL module driver + * @{ + */ + +#ifdef HAL_MDF_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/** @defgroup MDF_Private_Typedefs MDF Private Typedefs + * @{ + */ +/** + * @} + */ + +/* Private define ------------------------------------------------------------*/ +/** @defgroup MDF_Private_Constants MDF Private Constants + * @{ + */ +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup MDF_Private_Variables MDF Private Variables + * @{ + */ +static MDF_HandleTypeDef *v_mdfHandle = NULL; +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup MDF_Private_Functions MDF Private Functions + * @{ + */ +static void MDF_AcqStart(MDF_HandleTypeDef *const hmdf, const MDF_FilterConfigTypeDef *const pFilterConfig); +static void MDF_DmaXferCpltCallback(DMA_HandleTypeDef *hdma); +static void MDF_DmaXferHalfCpltCallback(DMA_HandleTypeDef *hdma); +static void MDF_DmaErrorCallback(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ +/** @defgroup MDF_Exported_Functions MDF Exported Functions + * @{ + */ + +/** @defgroup MDF_Exported_Functions_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 ADF instance. + (+) De-initialize the ADF instance. + (+) Register and unregister callbacks. +@endverbatim + * @{ + */ + +/** + * @brief Initialize the MDF instance according to the specified parameters + * in the MDF_InitTypeDef structure and initialize the associated handle. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_Init(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check MDF handle */ + if (hmdf == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_MDF_ALL_INSTANCE(hmdf->Instance)); + assert_param(IS_MDF_FILTER_BITSTREAM(hmdf->Init.FilterBistream)); + assert_param(IS_FUNCTIONAL_STATE(hmdf->Init.SerialInterface.Activation)); + + /* Check that instance has not been already initialized */ + if (v_mdfHandle != NULL) + { + status = HAL_ERROR; + } + else + { +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + /* Reset callback pointers to the weak predefined callbacks */ + hmdf->SndLvCallback = HAL_MDF_SndLvlCallback; + hmdf->SadCallback = HAL_MDF_SadCallback; + hmdf->AcqCpltCallback = HAL_MDF_AcqCpltCallback; + hmdf->AcqHalfCpltCallback = HAL_MDF_AcqHalfCpltCallback; + hmdf->ErrorCallback = HAL_MDF_ErrorCallback; + + /* Call MDF MSP init function */ + if (hmdf->MspInitCallback == NULL) + { + hmdf->MspInitCallback = HAL_MDF_MspInit; + } + hmdf->MspInitCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + /* Call MDF MSP init function */ + HAL_MDF_MspInit(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + + /* Configure common parameters */ + /* Check clock generator status */ + if ((ADF1->CKGCR & MDF_CKGCR_CKGACTIVE) != 0U) + { + status = HAL_ERROR; + } + else + { + /* Configure processing clock divider, output clock divider, + output clock pins and output clock generation trigger */ + assert_param(IS_MDF_PROC_CLOCK_DIVIDER(hmdf->Init.CommonParam.ProcClockDivider)); + assert_param(IS_FUNCTIONAL_STATE(hmdf->Init.CommonParam.OutputClock.Activation)); + ADF1->CKGCR = 0U; + ADF1->CKGCR |= ((hmdf->Init.CommonParam.ProcClockDivider - 1U) << MDF_CKGCR_PROCDIV_Pos); + if (hmdf->Init.CommonParam.OutputClock.Activation == ENABLE) + { + assert_param(IS_MDF_OUTPUT_CLOCK_PINS(hmdf->Init.CommonParam.OutputClock.Pins)); + assert_param(IS_MDF_OUTPUT_CLOCK_DIVIDER(hmdf->Init.CommonParam.OutputClock.Divider)); + assert_param(IS_FUNCTIONAL_STATE(hmdf->Init.CommonParam.OutputClock.Trigger.Activation)); + ADF1->CKGCR |= (((hmdf->Init.CommonParam.OutputClock.Divider - 1U) << MDF_CKGCR_CCKDIV_Pos) | + hmdf->Init.CommonParam.OutputClock.Pins | + (hmdf->Init.CommonParam.OutputClock.Pins >> 4U)); + if (hmdf->Init.CommonParam.OutputClock.Trigger.Activation == ENABLE) + { + assert_param(IS_MDF_OUTPUT_CLOCK_TRIGGER_SOURCE(hmdf->Init.CommonParam.OutputClock.Trigger.Source)); + assert_param(IS_MDF_OUTPUT_CLOCK_TRIGGER_EDGE(hmdf->Init.CommonParam.OutputClock.Trigger.Edge)); + ADF1->CKGCR |= (hmdf->Init.CommonParam.OutputClock.Trigger.Source | + hmdf->Init.CommonParam.OutputClock.Trigger.Edge | + MDF_CKGCR_CKGMOD); + } + } + + /* Activate clock generator */ + ADF1->CKGCR |= MDF_CKGCR_CKGDEN; + } + + /* Configure serial interface */ + if ((status == HAL_OK) && (hmdf->Init.SerialInterface.Activation == ENABLE)) + { + /* Check serial interface status */ + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) != 0U) + { + status = HAL_ERROR; + } + else + { + /* Configure mode, clock source and threshold */ + assert_param(IS_MDF_SITF_MODE(hmdf->Init.SerialInterface.Mode)); + assert_param(IS_MDF_SITF_CLOCK_SOURCE(hmdf->Init.SerialInterface.ClockSource)); + assert_param(IS_MDF_SITF_THRESHOLD(hmdf->Init.SerialInterface.Threshold)); + hmdf->Instance->SITFCR = 0U; + hmdf->Instance->SITFCR |= ((hmdf->Init.SerialInterface.Threshold << MDF_SITFCR_STH_Pos) | + hmdf->Init.SerialInterface.Mode | hmdf->Init.SerialInterface.ClockSource); + + /* Activate serial interface */ + hmdf->Instance->SITFCR |= MDF_SITFCR_SITFEN; + } + } + + if (status == HAL_OK) + { + /* Configure filter bitstream */ + hmdf->Instance->BSMXCR &= ~(MDF_BSMXCR_BSSEL); + hmdf->Instance->BSMXCR |= hmdf->Init.FilterBistream; + + /* Update instance pointer */ + v_mdfHandle = hmdf; + + /* Update error code and state */ + hmdf->ErrorCode = MDF_ERROR_NONE; + hmdf->State = HAL_MDF_STATE_READY; + } + } + } + + /* Return function status */ + return status; +} + +/** + * @brief De-initialize the MDF instance. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_DeInit(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check MDF handle */ + if (hmdf == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check parameters */ + assert_param(IS_MDF_ALL_INSTANCE(hmdf->Instance)); + + /* Check that instance has not been already deinitialized */ + if (v_mdfHandle == NULL) + { + status = HAL_ERROR; + } + else + { + /* Disable sound activity detector if needed */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); + } + + /* Disable filter if needed */ + if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) + { + hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); + } + + /* Disable serial interface if needed */ + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) != 0U) + { + hmdf->Instance->SITFCR &= ~(MDF_SITFCR_SITFEN); + } + + /* Disable all interrupts and clear all pending flags */ + hmdf->Instance->DFLTIER = 0U; + hmdf->Instance->DFLTISR = 0xFFFFFFFFU; + + /* Disable clock generator */ + ADF1->CKGCR &= ~(MDF_CKGCR_CKGDEN); + + /* Call MDF MSP deinit function */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + if (hmdf->MspDeInitCallback == NULL) + { + hmdf->MspDeInitCallback = HAL_MDF_MspDeInit; + } + hmdf->MspDeInitCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_MspDeInit(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + + /* Update instance pointer */ + v_mdfHandle = (MDF_HandleTypeDef *) NULL; + + /* Update state */ + hmdf->State = HAL_MDF_STATE_RESET; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Initialize the MDF instance MSP. + * @param hmdf MDF handle. + * @retval None. + */ +__weak void HAL_MDF_MspInit(MDF_HandleTypeDef *hmdf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_MspInit could be implemented in the user file */ +} + +/** + * @brief De-initialize the MDF instance MSP. + * @param hmdf MDF handle. + * @retval None. + */ +__weak void HAL_MDF_MspDeInit(MDF_HandleTypeDef *hmdf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_MspDeInit could be implemented in the user file */ +} + +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) +/** + * @brief Register a user MDF callback to be used instead of the weak predefined callback. + * @param hmdf MDF handle. + * @param CallbackID ID of the callback to be registered. + * This parameter can be one of the following values: + * @arg @ref HAL_MDF_ACQ_COMPLETE_CB_ID acquisition complete callback ID. + * @arg @ref HAL_MDF_ACQ_HALFCOMPLETE_CB_ID acquisition half complete callback ID. + * @arg @ref HAL_MDF_SAD_CB_ID sound activity detector callback ID (only for ADF instance). + * @arg @ref HAL_MDF_ERROR_CB_ID error callback ID. + * @arg @ref HAL_MDF_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_MDF_MSPDEINIT_CB_ID MSP de-init callback ID. + * @param pCallback pointer to the callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_RegisterCallback(MDF_HandleTypeDef *hmdf, + HAL_MDF_CallbackIDTypeDef CallbackID, + pMDF_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pCallback == NULL) + { + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + else + { + if (hmdf->State == HAL_MDF_STATE_READY) + { + switch (CallbackID) + { + case HAL_MDF_ACQ_COMPLETE_CB_ID : + hmdf->AcqCpltCallback = pCallback; + break; + case HAL_MDF_ACQ_HALFCOMPLETE_CB_ID : + hmdf->AcqHalfCpltCallback = pCallback; + break; + case HAL_MDF_SAD_CB_ID : + hmdf->SadCallback = pCallback; + break; + case HAL_MDF_ERROR_CB_ID : + hmdf->ErrorCallback = pCallback; + break; + case HAL_MDF_MSPINIT_CB_ID : + hmdf->MspInitCallback = pCallback; + break; + case HAL_MDF_MSPDEINIT_CB_ID : + hmdf->MspDeInitCallback = pCallback; + break; + default : + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (hmdf->State == HAL_MDF_STATE_RESET) + { + switch (CallbackID) + { + case HAL_MDF_MSPINIT_CB_ID : + hmdf->MspInitCallback = pCallback; + break; + case HAL_MDF_MSPDEINIT_CB_ID : + hmdf->MspDeInitCallback = pCallback; + break; + default : + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Unregister a user MDF callback. + * MDF callback is redirected to the weak predefined callback. + * @param hmdf MDF handle. + * @param CallbackID ID of the callback to be unregistered. + * This parameter can be one of the following values: + * @arg @ref HAL_MDF_ACQ_COMPLETE_CB_ID acquisition complete callback ID. + * @arg @ref HAL_MDF_ACQ_HALFCOMPLETE_CB_ID acquisition half complete callback ID. + * @arg @ref HAL_MDF_SAD_CB_ID sound activity detector callback ID (only for ADF instance). + * @arg @ref HAL_MDF_ERROR_CB_ID error callback ID. + * @arg @ref HAL_MDF_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_MDF_MSPDEINIT_CB_ID MSP de-init callback ID. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_UnRegisterCallback(MDF_HandleTypeDef *hmdf, + HAL_MDF_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hmdf->State == HAL_MDF_STATE_READY) + { + switch (CallbackID) + { + case HAL_MDF_ACQ_COMPLETE_CB_ID : + hmdf->AcqCpltCallback = HAL_MDF_AcqCpltCallback; + break; + case HAL_MDF_ACQ_HALFCOMPLETE_CB_ID : + hmdf->AcqHalfCpltCallback = HAL_MDF_AcqHalfCpltCallback; + break; + case HAL_MDF_SAD_CB_ID : + hmdf->SadCallback = HAL_MDF_SadCallback; + break; + case HAL_MDF_ERROR_CB_ID : + hmdf->ErrorCallback = HAL_MDF_ErrorCallback; + break; + case HAL_MDF_MSPINIT_CB_ID : + hmdf->MspInitCallback = HAL_MDF_MspInit; + break; + case HAL_MDF_MSPDEINIT_CB_ID : + hmdf->MspDeInitCallback = HAL_MDF_MspDeInit; + break; + default : + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (hmdf->State == HAL_MDF_STATE_RESET) + { + switch (CallbackID) + { + case HAL_MDF_MSPINIT_CB_ID : + hmdf->MspInitCallback = HAL_MDF_MspInit; + break; + case HAL_MDF_MSPDEINIT_CB_ID : + hmdf->MspDeInitCallback = HAL_MDF_MspDeInit; + break; + default : + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + + /* Return function status */ + return status; +} + +/** + * @brief Register specific MDF sound level callback + * to be used instead of the weak predefined callback. + * @param hmdf MDF handle. + * @param pCallback pointer to the sound level callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_RegisterSndLvlCallback(MDF_HandleTypeDef *hmdf, + pMDF_SndLvlCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pCallback == NULL) + { + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + else + { + if (hmdf->State == HAL_MDF_STATE_READY) + { + hmdf->SndLvCallback = pCallback; + } + else + { + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Unregister the specific MDF sound level callback. + * MDF sound level callback is redirected to the weak predefined callback. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_UnRegisterSndLvlCallback(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hmdf->State == HAL_MDF_STATE_READY) + { + hmdf->SndLvCallback = HAL_MDF_SndLvlCallback; + } + else + { + /* Update error code and status */ + hmdf->ErrorCode |= MDF_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + + /* Return function status */ + return status; +} +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup MDF_Exported_Functions_Group2 Acquisition functions + * @brief Acquisition functions + * +@verbatim + ============================================================================== + ##### Acquisition functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Start and stop acquisition in polling, interrupt or DMA mode. + (+) Wait and get acquisition values. + (+) Generate pulse on TRGO signal. + (+) Modify and get some filter parameters during acquisition. + (+) Wait and get sound level values. + (+) Detect sound activity. +@endverbatim + * @{ + */ + +/** + * @brief This function allows to start acquisition in polling mode. + * @param hmdf MDF handle. + * @param pFilterConfig Filter configuration parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_AcqStart(MDF_HandleTypeDef *hmdf, const MDF_FilterConfigTypeDef *pFilterConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pFilterConfig == NULL) + { + status = HAL_ERROR; + } + else + { + assert_param(IS_MDF_ACQUISITION_MODE(pFilterConfig->AcquisitionMode)); + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); + if ((pFilterConfig->SoundActivity.Activation == ENABLE) && + ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE) || + (pFilterConfig->AcquisitionMode == MDF_MODE_SYNC_SINGLE) || + (pFilterConfig->AcquisitionMode == MDF_MODE_WINDOW_CONT))) + { + status = HAL_ERROR; + } + /* Check state */ + else if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + /* Check filter status */ + else if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) + { + status = HAL_ERROR; + } + else + { + /* Check SAD status */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Configure filter and start acquisition */ + hmdf->Instance->DFLTCR = 0U; + MDF_AcqStart(hmdf, pFilterConfig); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to poll for available acquisition value. + * @param hmdf MDF handle. + * @param Timeout Timeout value in milliseconds. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_PollForAcq(MDF_HandleTypeDef *hmdf, uint32_t Timeout) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + else + { + uint32_t tickstart = HAL_GetTick(); + + /* Wait for available acquisition value */ + while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_RXNEF) != MDF_DFLTISR_RXNEF) && (status == HAL_OK)) + { + /* Check the timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + status = HAL_TIMEOUT; + } + } + } + + /* Check if data overflow, saturation or reshape filter occurs */ + uint32_t error_flags = (hmdf->Instance->DFLTISR & (MDF_DFLTISR_DOVRF | MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF)); + if (error_flags != 0U) + { + /* Update error code */ + if ((error_flags & MDF_DFLTISR_DOVRF) == MDF_DFLTISR_DOVRF) + { + hmdf->ErrorCode |= MDF_ERROR_ACQUISITION_OVERFLOW; + } + if ((error_flags & MDF_DFLTISR_SATF) == MDF_DFLTISR_SATF) + { + hmdf->ErrorCode |= MDF_ERROR_SATURATION; + } + if ((error_flags & MDF_DFLTISR_RFOVRF) == MDF_DFLTISR_RFOVRF) + { + hmdf->ErrorCode |= MDF_ERROR_RSF_OVERRUN; + } + + /* Clear corresponding flags */ + hmdf->Instance->DFLTISR |= error_flags; + + /* Call error callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->ErrorCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_ErrorCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + + if (status == HAL_OK) + { + /* Update state only in asynchronous single shot mode */ + if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_ACQMOD) == MDF_MODE_ASYNC_SINGLE) + { + hmdf->State = HAL_MDF_STATE_READY; + } + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to get acquisition value. + * @param hmdf MDF handle. + * @param pValue Acquisition value on 24 MSB. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_GetAcqValue(const MDF_HandleTypeDef *hmdf, int32_t *pValue) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pValue == NULL) + { + status = HAL_ERROR; + } + else + { + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + } + } + + if (status == HAL_OK) + { + /* Get acquisition value */ + *pValue = (int32_t) hmdf->Instance->DFLTDR; + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to stop acquisition in polling mode. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_AcqStop(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + /* Check if state is ready and filter active */ + if (hmdf->State == HAL_MDF_STATE_READY) + { + if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != MDF_DFLTCR_DFLTACTIVE) + { + status = HAL_ERROR; + } + } + else + { + status = HAL_ERROR; + } + } + else + { + /* Disable sound activity detector if needed */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); + } + } + + if (status == HAL_OK) + { + /* Disable filter */ + hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); + + /* Clear all potential pending flags */ + hmdf->Instance->DFLTISR |= (MDF_DFLTISR_DOVRF | MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF | + MDF_DFLTISR_SDDETF | MDF_DFLTISR_SDLVLF); + + /* Update state */ + hmdf->State = HAL_MDF_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to start acquisition in interrupt mode. + * @param hmdf MDF handle. + * @param pFilterConfig Filter configuration parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_AcqStart_IT(MDF_HandleTypeDef *hmdf, const MDF_FilterConfigTypeDef *pFilterConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pFilterConfig == NULL) + { + status = HAL_ERROR; + } + else + { + assert_param(IS_MDF_ACQUISITION_MODE(pFilterConfig->AcquisitionMode)); + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); + if ((pFilterConfig->SoundActivity.Activation == ENABLE) && + ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE) || + (pFilterConfig->AcquisitionMode == MDF_MODE_SYNC_SINGLE) || + (pFilterConfig->AcquisitionMode == MDF_MODE_WINDOW_CONT))) + { + status = HAL_ERROR; + } + /* Check state */ + else if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + /* Check filter status */ + else if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) + { + status = HAL_ERROR; + } + else + { + /* Check SAD status */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + if ((pFilterConfig->SoundActivity.Activation == DISABLE) || + (pFilterConfig->SoundActivity.DataMemoryTransfer != MDF_SAD_NO_MEMORY_TRANSFER)) + { + /* Enable data overflow and fifo threshold interrupts */ + hmdf->Instance->DFLTIER |= (MDF_DFLTIER_DOVRIE | MDF_DFLTIER_FTHIE); + } + + if (pFilterConfig->ReshapeFilter.Activation == ENABLE) + { + /* Enable reshape filter overrun interrupt */ + hmdf->Instance->DFLTIER |= MDF_DFLTIER_RFOVRIE; + } + + /* Enable saturation interrupt */ + hmdf->Instance->DFLTIER |= MDF_DFLTIER_SATIE; + + if (pFilterConfig->SoundActivity.Activation == ENABLE) + { + /* Enable sound level value ready and sound activity detection interrupts */ + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.SoundLevelInterrupt)); + hmdf->Instance->DFLTIER |= (pFilterConfig->SoundActivity.SoundLevelInterrupt == ENABLE) ? + (MDF_DFLTIER_SDLVLIE | MDF_DFLTIER_SDDETIE) : + MDF_DFLTIER_SDDETIE; + } + + /* Configure filter and start acquisition */ + hmdf->Instance->DFLTCR = 0U; + MDF_AcqStart(hmdf, pFilterConfig); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to stop acquisition in interrupt mode. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_AcqStop_IT(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + /* Check if state is ready and filter active */ + if (hmdf->State == HAL_MDF_STATE_READY) + { + if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != MDF_DFLTCR_DFLTACTIVE) + { + status = HAL_ERROR; + } + } + else + { + status = HAL_ERROR; + } + } + else + { + /* Disable sound activity detector if needed */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); + } + } + + if (status == HAL_OK) + { + /* Disable filter */ + hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); + + /* Disable interrupts and clear all potential pending flags */ + hmdf->Instance->DFLTIER &= ~(MDF_DFLTIER_FTHIE | MDF_DFLTIER_DOVRIE | MDF_DFLTIER_SATIE | + MDF_DFLTIER_RFOVRIE | MDF_DFLTIER_SDDETIE | MDF_DFLTIER_SDLVLIE); + hmdf->Instance->DFLTISR |= (MDF_DFLTISR_DOVRF | MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF | + MDF_DFLTISR_SDDETF | MDF_DFLTISR_SDLVLF); + + /* Update state */ + hmdf->State = HAL_MDF_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to start acquisition in DMA mode. + * @param hmdf MDF handle. + * @param pFilterConfig Filter configuration parameters. + * @param pDmaConfig DMA configuration parameters. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_AcqStart_DMA(MDF_HandleTypeDef *hmdf, const MDF_FilterConfigTypeDef *pFilterConfig, + const MDF_DmaConfigTypeDef *pDmaConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if ((pFilterConfig == NULL) || (pDmaConfig == NULL)) + { + status = HAL_ERROR; + } + else + { + assert_param(IS_FUNCTIONAL_STATE(pDmaConfig->MsbOnly)); + assert_param(IS_MDF_ACQUISITION_MODE(pFilterConfig->AcquisitionMode)); + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); + if ((pFilterConfig->SoundActivity.Activation == ENABLE) && + ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE) || + (pFilterConfig->AcquisitionMode == MDF_MODE_SYNC_SINGLE) || + (pFilterConfig->AcquisitionMode == MDF_MODE_WINDOW_CONT))) + { + status = HAL_ERROR; + } + /* Check state */ + else if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + /* Check filter status */ + else if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != 0U) + { + status = HAL_ERROR; + } + else + { + /* Check SAD status */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + uint32_t SrcAddress; + + if (pFilterConfig->ReshapeFilter.Activation == ENABLE) + { + /* Enable reshape filter overrun interrupt */ + hmdf->Instance->DFLTIER |= MDF_DFLTIER_RFOVRIE; + } + + /* Enable saturation interrupt */ + hmdf->Instance->DFLTIER |= MDF_DFLTIER_SATIE; + + if (pFilterConfig->SoundActivity.Activation == ENABLE) + { + /* Enable sound level value ready and sound activity detection interrupts */ + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.SoundLevelInterrupt)); + hmdf->Instance->DFLTIER |= (pFilterConfig->SoundActivity.SoundLevelInterrupt == ENABLE) ? + (MDF_DFLTIER_SDLVLIE | MDF_DFLTIER_SDDETIE) : + MDF_DFLTIER_SDDETIE; + } + + /* Enable MDF DMA requests */ + hmdf->Instance->DFLTCR = MDF_DFLTCR_DMAEN; + + /* Start DMA transfer */ + hmdf->hdma->XferCpltCallback = MDF_DmaXferCpltCallback; + hmdf->hdma->XferHalfCpltCallback = MDF_DmaXferHalfCpltCallback; + hmdf->hdma->XferErrorCallback = MDF_DmaErrorCallback; + SrcAddress = (pDmaConfig->MsbOnly == ENABLE) ? (((uint32_t) &hmdf->Instance->DFLTDR) + 2U) : + (uint32_t) &hmdf->Instance->DFLTDR; + if ((hmdf->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hmdf->hdma->LinkedListQueue != NULL) + { + hmdf->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = pDmaConfig->DataLength; + hmdf->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = SrcAddress; + hmdf->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = pDmaConfig->Address; + + status = HAL_DMAEx_List_Start_IT(hmdf->hdma); + } + else + { + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hmdf->hdma, SrcAddress, pDmaConfig->Address, pDmaConfig->DataLength); + } + if (status != HAL_OK) + { + /* Update state */ + hmdf->State = HAL_MDF_STATE_ERROR; + status = HAL_ERROR; + } + else + { + /* Configure filter and start acquisition */ + MDF_AcqStart(hmdf, pFilterConfig); + } + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to stop acquisition in DMA mode. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_AcqStop_DMA(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check if state is ready and filter active */ + if (hmdf->State == HAL_MDF_STATE_READY) + { + if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_DFLTACTIVE) != MDF_DFLTCR_DFLTACTIVE) + { + status = HAL_ERROR; + } + } + else + { + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + else + { + /* Stop the DMA transfer */ + if (HAL_DMA_Abort(hmdf->hdma) != HAL_OK) + { + /* Update state */ + hmdf->State = HAL_MDF_STATE_ERROR; + status = HAL_ERROR; + } + } + } + + if (status == HAL_OK) + { + /* Disable sound activity detector if needed */ + if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) != 0U) + { + hmdf->Instance->SADCR &= ~(MDF_SADCR_SADEN); + } + + /* Disable filter */ + hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DFLTEN); + + /* Disable interrupts and clear all potential pending flags */ + hmdf->Instance->DFLTIER &= ~(MDF_DFLTIER_SATIE | MDF_DFLTIER_RFOVRIE | MDF_DFLTIER_SDDETIE | + MDF_DFLTIER_SDLVLIE); + hmdf->Instance->DFLTISR |= (MDF_DFLTISR_SATF | MDF_DFLTISR_RFOVRF | MDF_DFLTISR_SDDETF | + MDF_DFLTISR_SDLVLF); + + /* Disable MDF DMA requests */ + hmdf->Instance->DFLTCR &= ~(MDF_DFLTCR_DMAEN); + + /* Update state */ + hmdf->State = HAL_MDF_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to generate pulse on TRGO signal. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_GenerateTrgo(const MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_READY) + { + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Check if trigger output control is already active */ + if ((ADF1->GCR & MDF_GCR_TRGO) == MDF_GCR_TRGO) + { + status = HAL_ERROR; + } + else + { + /* Generate pulse on trigger output control signal */ + ADF1->GCR |= MDF_GCR_TRGO; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to set delay to apply on data source in number of samples. + * @param hmdf MDF handle. + * @param Delay Delay to apply on data source in number of samples. + * This parameter must be a number between Min_Data = 0 and Max_Data = 127. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_SetDelay(MDF_HandleTypeDef *hmdf, uint32_t Delay) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_MDF_DELAY(Delay)); + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + else + { + /* Check if bitstream delay is already active */ + if ((hmdf->Instance->DLYCR & MDF_DLYCR_SKPBF) == MDF_DLYCR_SKPBF) + { + status = HAL_ERROR; + } + else + { + /* Configure bitstream delay */ + hmdf->Instance->DLYCR |= Delay; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to get current delay applied on data source in number of samples. + * @param hmdf MDF handle. + * @param pDelay Current delay applied on data source in number of samples. + * This value is between Min_Data = 0 and Max_Data = 127. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_GetDelay(const MDF_HandleTypeDef *hmdf, uint32_t *pDelay) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pDelay == NULL) + { + status = HAL_ERROR; + } + /* Check state */ + else if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + else + { + /* Get current bitstream delay */ + *pDelay = (hmdf->Instance->DLYCR & MDF_DLYCR_SKPDLY); + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to set filter gain. + * @param hmdf MDF handle. + * @param Gain Filter gain in step of around 3db (from -48db to 72dB). + * This parameter must be a number between Min_Data = -16 and Max_Data = 24. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_SetGain(MDF_HandleTypeDef *hmdf, int32_t Gain) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_MDF_GAIN(Gain)); + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + else + { + uint32_t register_gain_value; + uint32_t tmp_register; + + if (Gain < 0) + { + int32_t adjust_gain; + + /* adjust gain value to set on register for negative value (offset of -16) */ + adjust_gain = Gain - 16; + register_gain_value = ((uint32_t) adjust_gain & 0x3FU); + } + else + { + /* for positive value, no offset to apply */ + register_gain_value = (uint32_t) Gain; + } + /* Set gain */ + tmp_register = (hmdf->Instance->DFLTCICR & ~(MDF_DFLTCICR_SCALE)); + hmdf->Instance->DFLTCICR = (tmp_register | (register_gain_value << MDF_DFLTCICR_SCALE_Pos)); + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to get filter gain. + * @param hmdf MDF handle. + * @param pGain Filter gain in step of around 3db (from -48db to 72dB). + * This parameter is between Min_Data = -16 and Max_Data = 24. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_GetGain(const MDF_HandleTypeDef *hmdf, int32_t *pGain) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if (pGain == NULL) + { + status = HAL_ERROR; + } + /* Check state */ + else if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + else + { + uint32_t register_gain_value; + + /* Get current gain */ + register_gain_value = ((hmdf->Instance->DFLTCICR & MDF_DFLTCICR_SCALE) >> MDF_DFLTCICR_SCALE_Pos); + if (register_gain_value > 31U) + { + /* adjust gain value to set on register for negative value (offset of +16) */ + register_gain_value |= 0xFFFFFFC0U; + *pGain = (int32_t) register_gain_value + 16; + } + else + { + /* for positive value, no offset to apply */ + *pGain = (int32_t) register_gain_value; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to poll for sound level data. + * @param hmdf MDF handle. + * @param Timeout Timeout value in milliseconds. + * @param pSoundLevel Sound level. + This parameter can be a value between Min_Data = 0 and Max_Data = 32767. + * @param pAmbientNoise Ambient noise. + This parameter can be a value between Min_Data = 0 and Max_Data = 32767. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_PollForSndLvl(MDF_HandleTypeDef *hmdf, uint32_t Timeout, uint32_t *pSoundLevel, + uint32_t *pAmbientNoise) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + if ((pSoundLevel == NULL) || (pAmbientNoise == NULL)) + { + status = HAL_ERROR; + } + /* Check state */ + else if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + /* Check SAD status */ + else if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) == 0U) + { + status = HAL_ERROR; + } + else + { + uint32_t tickstart = HAL_GetTick(); + + /* Wait for available sound level data */ + while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_SDLVLF) != MDF_DFLTISR_SDLVLF) && (status == HAL_OK)) + { + /* Check the timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + status = HAL_TIMEOUT; + } + } + } + + if (status == HAL_OK) + { + /* Get sound level */ + *pSoundLevel = hmdf->Instance->SADSDLVR; + + /* Get ambient noise */ + *pAmbientNoise = hmdf->Instance->SADANLVR; + + /* Clear sound level ready flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDLVLF; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to poll for sound activity detection. + * @param hmdf MDF handle. + * @param Timeout Timeout value in milliseconds. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_PollForSad(MDF_HandleTypeDef *hmdf, uint32_t Timeout) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + status = HAL_ERROR; + } + /* Check SAD status */ + else if ((hmdf->Instance->SADCR & MDF_SADCR_SADACTIVE) == 0U) + { + status = HAL_ERROR; + } + else + { + uint32_t tickstart = HAL_GetTick(); + + /* Wait for sound activity detection */ + while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_SDDETF) != MDF_DFLTISR_SDDETF) && (status == HAL_OK)) + { + /* Check the timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + status = HAL_TIMEOUT; + } + } + } + + if (status == HAL_OK) + { + /* Clear sound activity detection flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDDETF; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief MDF acquisition complete callback. + * @param hmdf MDF handle. + * @retval None. + */ +__weak void HAL_MDF_AcqCpltCallback(MDF_HandleTypeDef *hmdf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_AcqCpltCallback could be implemented in the user file */ +} + +/** + * @brief MDF acquisition half complete callback. + * @param hmdf MDF handle. + * @retval None. + */ +__weak void HAL_MDF_AcqHalfCpltCallback(MDF_HandleTypeDef *hmdf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_AcqHalfCpltCallback could be implemented in the user file */ +} + +/** + * @brief MDF sound level callback. + * @param hmdf MDF handle. + * @param SoundLevel Sound level value computed by sound activity detector. + * This parameter can be a value between Min_Data = 0 and Max_Data = 32767. + * @param AmbientNoise Ambient noise value computed by sound activity detector. + * This parameter can be a value between Min_Data = 0 and Max_Data = 32767. + * @retval None. + */ +__weak void HAL_MDF_SndLvlCallback(MDF_HandleTypeDef *hmdf, uint32_t SoundLevel, uint32_t AmbientNoise) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + UNUSED(SoundLevel); + UNUSED(AmbientNoise); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_SndLvlCallback could be implemented in the user file */ +} + +/** + * @brief MDF sound activity detector callback. + * @param hmdf MDF handle. + * @retval None. + */ +__weak void HAL_MDF_SadCallback(MDF_HandleTypeDef *hmdf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_SadCallback could be implemented in the user file */ +} + +/** + * @} + */ + +/** @defgroup MDF_Exported_Functions_Group3 Clock absence detection functions + * @brief Clock absence detection functions + * +@verbatim + ============================================================================== + ##### Clock absence detection functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Start and stop clock absence detection in interrupt mode. + (+) Detect clock absence. +@endverbatim + * @{ + */ + +/** + * @brief This function allows to poll for the clock absence detection. + * @param hmdf MDF handle. + * @param Timeout Timeout value in milliseconds. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_PollForCkab(MDF_HandleTypeDef *hmdf, uint32_t Timeout) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Check serial interface status and mode */ + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) == 0U) + { + status = HAL_ERROR; + } + else + { + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFMOD) != MDF_SITF_NORMAL_SPI_MODE) + { + status = HAL_ERROR; + } + } + } + + if (status == HAL_OK) + { + uint32_t tickstart = HAL_GetTick(); + + /* Wait for clock absence detection */ + while (((hmdf->Instance->DFLTISR & MDF_DFLTISR_CKABF) != MDF_DFLTISR_CKABF) && (status == HAL_OK)) + { + /* Check the timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + status = HAL_TIMEOUT; + } + } + } + + if (status == HAL_OK) + { + /* Clear clock absence detection flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to start clock absence detection in interrupt mode. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_CkabStart_IT(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Check serial interface status and mode */ + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) == 0U) + { + status = HAL_ERROR; + } + else + { + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFMOD) != MDF_SITF_NORMAL_SPI_MODE) + { + status = HAL_ERROR; + } + } + } + + if (status == HAL_OK) + { + /* Clear clock absence detection flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; + + /* Check clock absence detection flag */ + if ((hmdf->Instance->DFLTISR & MDF_DFLTISR_CKABF) == MDF_DFLTISR_CKABF) + { + status = HAL_ERROR; + } + else + { + /* Enable clock absence detection interrupt */ + hmdf->Instance->DFLTIER |= MDF_DFLTIER_CKABIE; + } + } + + /* Return function status */ + return status; +} + +/** + * @brief This function allows to stop clock absence detection in interrupt mode. + * @param hmdf MDF handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_MDF_CkabStop_IT(MDF_HandleTypeDef *hmdf) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check state */ + if (hmdf->State != HAL_MDF_STATE_ACQUISITION) + { + if (hmdf->State != HAL_MDF_STATE_READY) + { + status = HAL_ERROR; + } + } + + if (status == HAL_OK) + { + /* Check serial interface status and mode */ + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFACTIVE) == 0U) + { + status = HAL_ERROR; + } + else + { + if ((hmdf->Instance->SITFCR & MDF_SITFCR_SITFMOD) != MDF_SITF_NORMAL_SPI_MODE) + { + status = HAL_ERROR; + } + } + } + + if (status == HAL_OK) + { + /* Disable clock absence detection interrupt */ + hmdf->Instance->DFLTIER &= ~(MDF_DFLTIER_CKABIE); + + /* Clear potential pending clock absence detection flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup MDF_Exported_Functions_Group4 Generic functions + * @brief Generic functions + * +@verbatim + ============================================================================== + ##### Generic functions ##### + ============================================================================== + [..] This section provides functions allowing to : + (+) Handle MDF interrupt. + (+) Inform user that error occurs. + (+) Get the current MDF instance state. + (+) Get the current MDF instance error code. +@endverbatim + * @{ + */ + +/** + * @brief This function handles the MDF interrupts. + * @param hmdf MDF handle. + * @retval None. + */ +void HAL_MDF_IRQHandler(MDF_HandleTypeDef *hmdf) +{ + uint32_t tmp_reg1; + uint32_t tmp_reg2; + uint32_t interrupts; + + /* Read current flags and interrupts and determine which ones occur */ + tmp_reg1 = hmdf->Instance->DFLTIER; + tmp_reg2 = hmdf->Instance->DFLTISR; + interrupts = (tmp_reg1 & tmp_reg2); + + /* Check if data overflow occurs */ + if ((interrupts & MDF_DFLTISR_DOVRF) == MDF_DFLTISR_DOVRF) + { + /* Clear data overflow flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_DOVRF; + + /* Update error code */ + hmdf->ErrorCode |= MDF_ERROR_ACQUISITION_OVERFLOW; + + /* Call error callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->ErrorCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_ErrorCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + /* Check if RXFIFO threshold occurs */ + else if ((interrupts & MDF_DFLTISR_FTHF) == MDF_DFLTISR_FTHF) + { + /* Call acquisition complete callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->AcqCpltCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_AcqCpltCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + + /* Update state only in asynchronous single shot mode */ + if ((hmdf->Instance->DFLTCR & MDF_DFLTCR_ACQMOD) == MDF_MODE_ASYNC_SINGLE) + { + hmdf->State = HAL_MDF_STATE_READY; + } + } + /* Check if reshape filter overrun occurs */ + else if ((interrupts & MDF_DFLTISR_RFOVRF) == MDF_DFLTISR_RFOVRF) + { + /* Clear reshape filter overrun flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_RFOVRF; + + /* Update error code */ + hmdf->ErrorCode |= MDF_ERROR_RSF_OVERRUN; + + /* Call error callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->ErrorCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_ErrorCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + /* Check if clock absence detection occurs */ + else if ((interrupts & MDF_DFLTISR_CKABF) == MDF_DFLTISR_CKABF) + { + /* Clear clock absence detection flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_CKABF; + + /* Update error code */ + hmdf->ErrorCode |= MDF_ERROR_CLOCK_ABSENCE; + + /* Call error callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->ErrorCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_ErrorCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + /* Check if saturation occurs */ + else if ((interrupts & MDF_DFLTISR_SATF) == MDF_DFLTISR_SATF) + { + /* Clear saturation flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_SATF; + + /* Update error code */ + hmdf->ErrorCode |= MDF_ERROR_SATURATION; + + /* Call error callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->ErrorCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_ErrorCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + /* Check if sound activity detection occurs */ + else if ((interrupts & MDF_DFLTISR_SDDETF) == MDF_DFLTISR_SDDETF) + { + /* Clear sound activity detection flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDDETF; + + /* Call sound activity detection callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->SadCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_SadCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + else + { + /* Check if sound level ready occurs */ + if ((interrupts & MDF_DFLTISR_SDLVLF) == MDF_DFLTISR_SDLVLF) + { + uint32_t sound_level; + uint32_t ambient_noise; + + /* Get sound level */ + sound_level = hmdf->Instance->SADSDLVR; + + /* Get ambient noise */ + ambient_noise = hmdf->Instance->SADANLVR; + + /* Clear sound level ready flag */ + hmdf->Instance->DFLTISR |= MDF_DFLTISR_SDLVLF; + + /* Call sound level callback */ +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->SndLvCallback(hmdf, sound_level, ambient_noise); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_SndLvlCallback(hmdf, sound_level, ambient_noise); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief MDF error callback. + * @param hmdf MDF handle. + * @retval None. + */ +__weak void HAL_MDF_ErrorCallback(MDF_HandleTypeDef *hmdf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdf); + + /* NOTE : This function should not be modified, when the function is needed, + the HAL_MDF_ErrorCallback could be implemented in the user file */ +} + +/** + * @brief This function allows to get the current MDF state. + * @param hmdf MDF handle. + * @retval MDF state. + */ +HAL_MDF_StateTypeDef HAL_MDF_GetState(const MDF_HandleTypeDef *hmdf) +{ + /* Return MDF state */ + return hmdf->State; +} + +/** + * @brief This function allows to get the current MDF error. + * @param hmdf MDF handle. + * @retval MDF error code. + */ +uint32_t HAL_MDF_GetError(const MDF_HandleTypeDef *hmdf) +{ + /* Return MDF error code */ + return hmdf->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup MDF_Private_Functions + * @brief Private functions + * @{ + */ + +/** + * @brief This function allows to configure filter and start acquisition. + * @param hmdf MDF handle. + * @param pFilterConfig Filter configuration parameters. + * @retval None. + */ +static void MDF_AcqStart(MDF_HandleTypeDef *const hmdf, const MDF_FilterConfigTypeDef *const pFilterConfig) +{ + uint32_t register_gain_value; + + /* Configure acquisition mode, discard samples, trigger and fifo threshold */ + assert_param(IS_MDF_DISCARD_SAMPLES(pFilterConfig->DiscardSamples)); + assert_param(IS_MDF_FIFO_THRESHOLD(pFilterConfig->FifoThreshold)); + if ((pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_CONT) || + (pFilterConfig->AcquisitionMode == MDF_MODE_ASYNC_SINGLE)) + { + /* Trigger parameters are not used */ + hmdf->Instance->DFLTCR |= (pFilterConfig->AcquisitionMode | pFilterConfig->FifoThreshold | + (pFilterConfig->DiscardSamples << MDF_DFLTCR_NBDIS_Pos)); + } + else + { + /* Trigger parameters are used */ + assert_param(IS_MDF_TRIGGER_SOURCE(pFilterConfig->Trigger.Source)); + assert_param(IS_MDF_TRIGGER_EDGE(pFilterConfig->Trigger.Edge)); + hmdf->Instance->DFLTCR |= (pFilterConfig->AcquisitionMode | pFilterConfig->FifoThreshold | + pFilterConfig->Trigger.Source | pFilterConfig->Trigger.Edge | + (pFilterConfig->DiscardSamples << MDF_DFLTCR_NBDIS_Pos)); + } + + /* Configure data source, CIC mode, decimation ratio and gain */ + assert_param(IS_MDF_DATA_SOURCE(pFilterConfig->DataSource)); + assert_param(IS_MDF_CIC_MODE(pFilterConfig->CicMode)); + assert_param(IS_MDF_DECIMATION_RATIO(pFilterConfig->DecimationRatio)); + assert_param(IS_MDF_GAIN(pFilterConfig->Gain)); + if (pFilterConfig->Gain < 0) + { + int32_t adjust_gain; + + /* adjust gain value to set on register for negative value (offset of -16) */ + adjust_gain = pFilterConfig->Gain - 16; + register_gain_value = ((uint32_t) adjust_gain & 0x3FU); + } + else + { + /* for positive value, no offset to apply */ + register_gain_value = (uint32_t) pFilterConfig->Gain; + } + hmdf->Instance->DFLTCICR = (pFilterConfig->DataSource | pFilterConfig->CicMode | + ((pFilterConfig->DecimationRatio - 1U) << MDF_DFLTCICR_MCICD_Pos) | + (register_gain_value << MDF_DFLTCICR_SCALE_Pos)); + + /* Configure bitstream delay */ + assert_param(IS_MDF_DELAY(pFilterConfig->Delay)); + hmdf->Instance->DLYCR = pFilterConfig->Delay; + + /* Configure reshape filter */ + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->ReshapeFilter.Activation)); + hmdf->Instance->DFLTRSFR = 0U; + if (pFilterConfig->ReshapeFilter.Activation == ENABLE) + { + /* Configure reshape filter decimation ratio */ + assert_param(IS_MDF_RSF_DECIMATION_RATIO(pFilterConfig->ReshapeFilter.DecimationRatio)); + hmdf->Instance->DFLTRSFR |= pFilterConfig->ReshapeFilter.DecimationRatio; + } + else + { + /* Bypass reshape filter */ + hmdf->Instance->DFLTRSFR |= MDF_DFLTRSFR_RSFLTBYP; + } + + /* Configure high-pass filter */ + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->HighPassFilter.Activation)); + if (pFilterConfig->HighPassFilter.Activation == ENABLE) + { + /* Configure high-pass filter cut-off frequency */ + assert_param(IS_MDF_HPF_CUTOFF_FREQ(pFilterConfig->HighPassFilter.CutOffFrequency)); + hmdf->Instance->DFLTRSFR |= pFilterConfig->HighPassFilter.CutOffFrequency; + } + else + { + /* Bypass high-pass filter */ + hmdf->Instance->DFLTRSFR |= MDF_DFLTRSFR_HPFBYP; + } + + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Activation)); + if (pFilterConfig->SoundActivity.Activation == ENABLE) + { + /* Configure SAD mode, frame size, hysteresis, sound trigger event + and data memory transfer only for ADF instance */ + assert_param(IS_MDF_SAD_MODE(pFilterConfig->SoundActivity.Mode)); + assert_param(IS_MDF_SAD_FRAME_SIZE(pFilterConfig->SoundActivity.FrameSize)); + if (pFilterConfig->SoundActivity.Mode != MDF_SAD_AMBIENT_NOISE_DETECTOR) + { + assert_param(IS_FUNCTIONAL_STATE(pFilterConfig->SoundActivity.Hysteresis)); + } + assert_param(IS_MDF_SAD_SOUND_TRIGGER(pFilterConfig->SoundActivity.SoundTriggerEvent)); + assert_param(IS_MDF_SAD_DATA_MEMORY_TRANSFER(pFilterConfig->SoundActivity.DataMemoryTransfer)); + if ((pFilterConfig->SoundActivity.Mode != MDF_SAD_AMBIENT_NOISE_DETECTOR) && + (pFilterConfig->SoundActivity.Hysteresis == ENABLE)) + { + hmdf->Instance->SADCR = (pFilterConfig->SoundActivity.Mode | pFilterConfig->SoundActivity.FrameSize | + MDF_SADCR_HYSTEN | pFilterConfig->SoundActivity.SoundTriggerEvent | + pFilterConfig->SoundActivity.DataMemoryTransfer); + } + else + { + hmdf->Instance->SADCR = (pFilterConfig->SoundActivity.Mode | pFilterConfig->SoundActivity.FrameSize | + pFilterConfig->SoundActivity.SoundTriggerEvent | + pFilterConfig->SoundActivity.DataMemoryTransfer); + } + + /* Configure SAD minimum noise level, hangover window, learning frames, + ambient noise slope control and signal noise threshold only for ADF instance */ + assert_param(IS_MDF_SAD_MIN_NOISE_LEVEL(pFilterConfig->SoundActivity.MinNoiseLevel)); + assert_param(IS_MDF_SAD_HANGOVER_WINDOW(pFilterConfig->SoundActivity.HangoverWindow)); + assert_param(IS_MDF_SAD_LEARNING_FRAMES(pFilterConfig->SoundActivity.LearningFrames)); + assert_param(IS_MDF_SAD_SIGNAL_NOISE_THRESHOLD(pFilterConfig->SoundActivity.SignalNoiseThreshold)); + if (pFilterConfig->SoundActivity.Mode != MDF_SAD_SOUND_DETECTOR) + { + assert_param(IS_MDF_SAD_AMBIENT_NOISE_SLOPE(pFilterConfig->SoundActivity.AmbientNoiseSlope)); + hmdf->Instance->SADCFGR = ((pFilterConfig->SoundActivity.MinNoiseLevel << MDF_SADCFGR_ANMIN_Pos) | + pFilterConfig->SoundActivity.HangoverWindow | + pFilterConfig->SoundActivity.LearningFrames | + (pFilterConfig->SoundActivity.AmbientNoiseSlope << MDF_SADCFGR_ANSLP_Pos) | + pFilterConfig->SoundActivity.SignalNoiseThreshold); + } + else + { + hmdf->Instance->SADCFGR = ((pFilterConfig->SoundActivity.MinNoiseLevel << MDF_SADCFGR_ANMIN_Pos) | + pFilterConfig->SoundActivity.HangoverWindow | + pFilterConfig->SoundActivity.LearningFrames | + pFilterConfig->SoundActivity.SignalNoiseThreshold); + } + } + else + { + /* SAD is not used */ + hmdf->Instance->SADCR = 0U; + hmdf->Instance->SADCFGR = 0U; + } + + /* Update instance state */ + hmdf->State = HAL_MDF_STATE_ACQUISITION; + + /* Enable sound activity detector if needed */ + if (pFilterConfig->SoundActivity.Activation == ENABLE) + { + hmdf->Instance->SADCR |= MDF_SADCR_SADEN; + } + + /* Enable filter */ + hmdf->Instance->DFLTCR |= MDF_DFLTCR_DFLTEN; +} + +/** + * @brief This function handles DMA transfer complete callback. + * @param hdma DMA handle. + * @retval None. + */ +static void MDF_DmaXferCpltCallback(DMA_HandleTypeDef *hdma) +{ + MDF_HandleTypeDef *hmdf = (MDF_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Check if DMA in circular mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + hmdf->State = HAL_MDF_STATE_READY; + } + +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->AcqCpltCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_AcqCpltCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ +} + +/** + * @brief This function handles DMA half transfer complete callback. + * @param hdma DMA handle. + * @retval None. + */ +static void MDF_DmaXferHalfCpltCallback(DMA_HandleTypeDef *hdma) +{ + MDF_HandleTypeDef *hmdf = (MDF_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->AcqHalfCpltCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_AcqHalfCpltCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ +} + +/** + * @brief This function handles DMA error callback. + * @param hdma DMA handle. + * @retval None. + */ +static void MDF_DmaErrorCallback(DMA_HandleTypeDef *hdma) +{ + MDF_HandleTypeDef *hmdf = (MDF_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Update error code */ + hmdf->ErrorCode |= MDF_ERROR_DMA; + +#if (USE_HAL_MDF_REGISTER_CALLBACKS == 1) + hmdf->ErrorCallback(hmdf); +#else /* USE_HAL_MDF_REGISTER_CALLBACKS */ + HAL_MDF_ErrorCallback(hmdf); +#endif /* USE_HAL_MDF_REGISTER_CALLBACKS */ +} + +/** + * @} + */ + +#endif /* HAL_MDF_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdios.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdios.c index 9e34bde20..dc2038a99 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdios.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mdios.c @@ -1,921 +1,921 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_mdios.c - * @author MCD Application Team - * @brief MDIOS HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the MDIOS Peripheral. - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral Control functions - * - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2017 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - =============================================================================== - ##### How to use this driver ##### - =============================================================================== - [..] - The MDIOS HAL driver can be used as follow: - - (#) Declare a MDIOS_HandleTypeDef handle structure. - - (#) Initialize the MDIOS low level resources by implementing the HAL_MDIOS_MspInit() API: - (##) Enable the MDIOS interface clock. - (##) MDIOS pins configuration: - (+++) Enable clocks for the MDIOS GPIOs. - (+++) Configure the MDIOS pins as alternate function. - (##) NVIC configuration if you need to use interrupt process: - (+++) Configure the MDIOS interrupt priority. - (+++) Enable the NVIC MDIOS IRQ handle. - - (#) Program the Port Address and the Preamble Check in the Init structure. - - (#) Initialize the MDIOS registers by calling the HAL_MDIOS_Init() API. - - (#) Perform direct slave read/write operations using the following APIs: - (##) Read the value of a DINn register: HAL_MDIOS_ReadReg() - (##) Write a value to a DOUTn register: HAL_MDIOS_WriteReg() - - (#) Get the Master read/write operations flags using the following APIs: - (##) Bit map of DOUTn registers read by Master: HAL_MDIOS_GetReadRegAddress() - (##) Bit map of DINn registers written by Master : HAL_MDIOS_GetWrittenRegAddress() - - (#) Clear the read/write flags using the following APIs: - (##) Clear read flags of a set of registers: HAL_MDIOS_ClearReadRegAddress() - (##) Clear write flags of a set of registers: HAL_MDIOS_ClearWriteRegAddress() - - (#) Enable interrupts on events using HAL_MDIOS_EnableEvents(), when called - the MDIOS will generate an interrupt in the following cases: - (##) a DINn register written by the Master - (##) a DOUTn register read by the Master - (##) an error occur - - (@) A callback is executed for each generated interrupt, so the driver provide the following - HAL_MDIOS_WriteCpltCallback(), HAL_MDIOS_ReadCpltCallback() and HAL_MDIOS_ErrorCallback() - (@) HAL_MDIOS_IRQHandler() must be called from the MDIOS IRQ Handler, to handle the interrupt - and execute the previous callbacks - - (#) Reset the MDIOS peripheral and all related resources by calling the HAL_MDIOS_DeInit() API. - (##) HAL_MDIOS_MspDeInit() must be implemented to reset low level resources - (GPIO, Clocks, NVIC configuration ...) - - *** Callback registration *** - ============================================= - - The compilation define USE_HAL_MDIOS_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Function @ref HAL_MDIOS_RegisterCallback() to register an interrupt callback. - - Function @ref HAL_MDIOS_RegisterCallback() allows to register following callbacks: - (+) WriteCpltCallback : Write Complete Callback. - (+) ReadCpltCallback : Read Complete Callback. - (+) ErrorCallback : Error Callback. - (+) WakeUpCallback : Wake UP Callback - (+) MspInitCallback : MspInit Callback. - (+) MspDeInitCallback : MspDeInit Callback. - - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function @ref HAL_MDIOS_UnRegisterCallback() to reset a callback to the default - weak function. - @ref HAL_MDIOS_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) WriteCpltCallback : Write Complete Callback. - (+) ReadCpltCallback : Read Complete Callback. - (+) ErrorCallback : Error Callback. - (+) WakeUpCallback : Wake UP Callback - (+) MspInitCallback : MspInit Callback. - (+) MspDeInitCallback : MspDeInit Callback. - - By default, after the HAL_MDIOS_Init and when the state is HAL_MDIOS_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples @ref HAL_MDIOS_WriteCpltCallback(), @ref HAL_MDIOS_ReadCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak function in the HAL_MDIOS_Init/ @ref HAL_MDIOS_DeInit only when - these callbacks are null (not registered beforehand). - if not, MspInit or MspDeInit are not null, the HAL_MDIOS_Init/ @ref HAL_MDIOS_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in HAL_MDIOS_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_MDIOS_STATE_READY or HAL_MDIOS_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using @ref HAL_MDIOS_RegisterCallback() before calling @ref HAL_MDIOS_DeInit - or HAL_MDIOS_Init function. - - When The compilation define USE_HAL_MDIOS_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ -#if defined (MDIOS) -/** @defgroup MDIOS MDIOS - * @brief HAL MDIOS module driver - * @{ - */ -#ifdef HAL_MDIOS_MODULE_ENABLED - - - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -#define MDIOS_PORT_ADDRESS_SHIFT ((uint32_t)8) -#define MDIOS_ALL_REG_FLAG ((uint32_t)0xFFFFFFFFU) -#define MDIOS_ALL_ERRORS_FLAG ((uint32_t)(MDIOS_SR_PERF | MDIOS_SR_SERF | MDIOS_SR_TERF)) - -#define MDIOS_DIN_BASE_ADDR (MDIOS_BASE + 0x100U) -#define MDIOS_DOUT_BASE_ADDR (MDIOS_BASE + 0x180U) - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) -static void MDIOS_InitCallbacksToDefault(MDIOS_HandleTypeDef *hmdios); -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @defgroup MDIOS_Exported_Functions MDIOS Exported Functions - * @{ - */ - -/** @defgroup MDIOS_Exported_Functions_Group1 Initialization/de-initialization functions - * @brief Initialization and Configuration functions - * -@verbatim -=============================================================================== - ##### Initialization and Configuration functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to initialize the MDIOS - (+) The following parameters can be configured: - (++) Port Address - (++) Preamble Check - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the MDIOS according to the specified parameters in - * the MDIOS_InitTypeDef and creates the associated handle . - * @param hmdios: pointer to a MDIOS_HandleTypeDef structure that contains - * the configuration information for MDIOS module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_Init(MDIOS_HandleTypeDef *hmdios) -{ - uint32_t tmpcr; - - /* Check the MDIOS handle allocation */ - if (hmdios == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_MDIOS_ALL_INSTANCE(hmdios->Instance)); - assert_param(IS_MDIOS_PORTADDRESS(hmdios->Init.PortAddress)); - assert_param(IS_MDIOS_PREAMBLECHECK(hmdios->Init.PreambleCheck)); - -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) - - if (hmdios->State == HAL_MDIOS_STATE_RESET) - { - MDIOS_InitCallbacksToDefault(hmdios); - - if (hmdios->MspInitCallback == NULL) - { - hmdios->MspInitCallback = HAL_MDIOS_MspInit; - } - - /* Init the low level hardware */ - hmdios->MspInitCallback(hmdios); - } - -#else - - if (hmdios->State == HAL_MDIOS_STATE_RESET) - { - /* Init the low level hardware */ - HAL_MDIOS_MspInit(hmdios); - } - -#endif /* (USE_HAL_MDIOS_REGISTER_CALLBACKS) */ - - /* Change the MDIOS state */ - hmdios->State = HAL_MDIOS_STATE_BUSY; - - /* Get the MDIOS CR value */ - tmpcr = hmdios->Instance->CR; - - /* Clear PORT_ADDRESS, DPC and EN bits */ - tmpcr &= ((uint32_t)~(MDIOS_CR_EN | MDIOS_CR_DPC | MDIOS_CR_PORT_ADDRESS)); - - /* Set MDIOS control parameters and enable the peripheral */ - tmpcr |= (uint32_t)(((hmdios->Init.PortAddress) << MDIOS_PORT_ADDRESS_SHIFT) | \ - (hmdios->Init.PreambleCheck) | \ - (MDIOS_CR_EN)); - - /* Write the MDIOS CR */ - hmdios->Instance->CR = tmpcr; - - hmdios->ErrorCode = HAL_MDIOS_ERROR_NONE; - - /* Change the MDIOS state */ - hmdios->State = HAL_MDIOS_STATE_READY; - - /* Release Lock */ - __HAL_UNLOCK(hmdios); - - /* Return function status */ - return HAL_OK; - -} - -/** - * @brief DeInitializes the MDIOS peripheral. - * @param hmdios: MDIOS handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_DeInit(MDIOS_HandleTypeDef *hmdios) -{ - /* Check the MDIOS handle allocation */ - if (hmdios == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_MDIOS_ALL_INSTANCE(hmdios->Instance)); - - /* Change the MDIOS state */ - hmdios->State = HAL_MDIOS_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_MDIOS_DISABLE(hmdios); - -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) - - if (hmdios->MspDeInitCallback == NULL) - { - hmdios->MspDeInitCallback = HAL_MDIOS_MspDeInit; - } - /* DeInit the low level hardware */ - hmdios->MspDeInitCallback(hmdios); -#else - - /* DeInit the low level hardware */ - HAL_MDIOS_MspDeInit(hmdios); - -#endif /* (USE_HAL_MDIOS_REGISTER_CALLBACKS) */ - - /* Change the MDIOS state */ - hmdios->State = HAL_MDIOS_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hmdios); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief MDIOS MSP Init - * @param hmdios: mdios handle - * @retval None - */ -__weak void HAL_MDIOS_MspInit(MDIOS_HandleTypeDef *hmdios) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdios); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MDIOS_MspInit can be implemented in the user file - */ -} - -/** - * @brief MDIOS MSP DeInit - * @param hmdios: mdios handle - * @retval None - */ -__weak void HAL_MDIOS_MspDeInit(MDIOS_HandleTypeDef *hmdios) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdios); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MDIOS_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User MDIOS Callback - * To be used instead of the weak predefined callback - * @param hmdios mdios handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_MDIOS_WRITE_COMPLETE_CB_ID Write Complete Callback ID - * @arg @ref HAL_MDIOS_READ_COMPLETE_CB_ID Read Complete Callback ID - * @arg @ref HAL_MDIOS_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_MDIOS_WAKEUP_CB_ID Wake Up Callback ID - * @arg @ref HAL_MDIOS_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_MDIOS_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_MDIOS_RegisterCallback(MDIOS_HandleTypeDef *hmdios, HAL_MDIOS_CallbackIDTypeDef CallbackID, - pMDIOS_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hmdios); - - if (hmdios->State == HAL_MDIOS_STATE_READY) - { - switch (CallbackID) - { - case HAL_MDIOS_WRITE_COMPLETE_CB_ID : - hmdios->WriteCpltCallback = pCallback; - break; - - case HAL_MDIOS_READ_COMPLETE_CB_ID : - hmdios->ReadCpltCallback = pCallback; - break; - - case HAL_MDIOS_ERROR_CB_ID : - hmdios->ErrorCallback = pCallback; - break; - - case HAL_MDIOS_WAKEUP_CB_ID : - hmdios->WakeUpCallback = pCallback; - break; - - case HAL_MDIOS_MSPINIT_CB_ID : - hmdios->MspInitCallback = pCallback; - break; - - case HAL_MDIOS_MSPDEINIT_CB_ID : - hmdios->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hmdios->State == HAL_MDIOS_STATE_RESET) - { - switch (CallbackID) - { - case HAL_MDIOS_MSPINIT_CB_ID : - hmdios->MspInitCallback = pCallback; - break; - - case HAL_MDIOS_MSPDEINIT_CB_ID : - hmdios->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hmdios); - - return status; -} - -/** - * @brief Unregister an MDIOS Callback - * MDIOS callback is redirected to the weak predefined callback - * @param hmdios mdios handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_MDIOS_WRITE_COMPLETE_CB_ID Write Complete Callback ID - * @arg @ref HAL_MDIOS_READ_COMPLETE_CB_ID Read Complete Callback ID - * @arg @ref HAL_MDIOS_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_MDIOS_WAKEUP_CB_ID Wake Up Callback ID - * @arg @ref HAL_MDIOS_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_MDIOS_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_MDIOS_UnRegisterCallback(MDIOS_HandleTypeDef *hmdios, HAL_MDIOS_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hmdios); - - if (hmdios->State == HAL_MDIOS_STATE_READY) - { - switch (CallbackID) - { - case HAL_MDIOS_WRITE_COMPLETE_CB_ID : - hmdios->WriteCpltCallback = HAL_MDIOS_WriteCpltCallback; - break; - - case HAL_MDIOS_READ_COMPLETE_CB_ID : - hmdios->ReadCpltCallback = HAL_MDIOS_ReadCpltCallback; - break; - - case HAL_MDIOS_ERROR_CB_ID : - hmdios->ErrorCallback = HAL_MDIOS_ErrorCallback; - break; - - case HAL_MDIOS_WAKEUP_CB_ID : - hmdios->WakeUpCallback = HAL_MDIOS_WakeUpCallback; - break; - - case HAL_MDIOS_MSPINIT_CB_ID : - hmdios->MspInitCallback = HAL_MDIOS_MspInit; - break; - - case HAL_MDIOS_MSPDEINIT_CB_ID : - hmdios->MspDeInitCallback = HAL_MDIOS_MspDeInit; - break; - - default : - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hmdios->State == HAL_MDIOS_STATE_RESET) - { - switch (CallbackID) - { - case HAL_MDIOS_MSPINIT_CB_ID : - hmdios->MspInitCallback = HAL_MDIOS_MspInit; - break; - - case HAL_MDIOS_MSPDEINIT_CB_ID : - hmdios->MspDeInitCallback = HAL_MDIOS_MspDeInit; - break; - - default : - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hmdios); - - return status; -} -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup MDIOS_Exported_Functions_Group2 IO operation functions - * @brief MDIOS Read/Write functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - This subsection provides a set of functions allowing to manage the MDIOS - read and write operations. - - (#) APIs that allow to the MDIOS to read/write from/to the - values of one of the DINn/DOUTn registers: - (+) Read the value of a DINn register: HAL_MDIOS_ReadReg() - (+) Write a value to a DOUTn register: HAL_MDIOS_WriteReg() - - (#) APIs that provide if there are some Slave registres have been - read or written by the Master: - (+) DOUTn registers read by Master: HAL_MDIOS_GetReadRegAddress() - (+) DINn registers written by Master : HAL_MDIOS_GetWrittenRegAddress() - - (#) APIs that Clear the read/write flags: - (+) Clear read registers flags: HAL_MDIOS_ClearReadRegAddress() - (+) Clear write registers flags: HAL_MDIOS_ClearWriteRegAddress() - - (#) A set of Callbacks are provided: - (+) HAL_MDIOS_WriteCpltCallback() - (+) HAL_MDIOS_ReadCpltCallback() - (+) HAL_MDIOS_ErrorCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Writes to an MDIOS output register - * @param hmdios: mdios handle - * @param RegNum: MDIOS output register address - * @param Data: Data to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_WriteReg(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum, uint16_t Data) -{ - uint32_t tmpreg; - - /* Check the parameters */ - assert_param(IS_MDIOS_REGISTER(RegNum)); - - /* Process Locked */ - __HAL_LOCK(hmdios); - - /* Get the addr of output register to be written by the MDIOS */ - tmpreg = MDIOS_DOUT_BASE_ADDR + (4U * RegNum); - - /* Write to DOUTn register */ - *((uint32_t *)tmpreg) = Data; - - /* Process Unlocked */ - __HAL_UNLOCK(hmdios); - - return HAL_OK; -} - -/** - * @brief Reads an MDIOS input register - * @param hmdios: mdios handle - * @param RegNum: MDIOS input register address - * @param pData: pointer to Data - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_ReadReg(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum, uint16_t *pData) -{ - uint32_t tmpreg; - - /* Check the parameters */ - assert_param(IS_MDIOS_REGISTER(RegNum)); - - /* Process Locked */ - __HAL_LOCK(hmdios); - - /* Get the addr of input register to be read by the MDIOS */ - tmpreg = MDIOS_DIN_BASE_ADDR + (4U * RegNum); - - /* Read DINn register */ - *pData = (uint16_t)(*((uint32_t *)tmpreg)); - - /* Process Unlocked */ - __HAL_UNLOCK(hmdios); - - return HAL_OK; -} - -/** - * @brief Gets Written registers by MDIO master - * @param hmdios: mdios handle - * @retval bit map of written registers addresses - */ -uint32_t HAL_MDIOS_GetWrittenRegAddress(MDIOS_HandleTypeDef *hmdios) -{ - return hmdios->Instance->WRFR; -} - -/** - * @brief Gets Read registers by MDIO master - * @param hmdios: mdios handle - * @retval bit map of read registers addresses - */ -uint32_t HAL_MDIOS_GetReadRegAddress(MDIOS_HandleTypeDef *hmdios) -{ - return hmdios->Instance->RDFR; -} - -/** - * @brief Clears Write registers flag - * @param hmdios: mdios handle - * @param RegNum: registers addresses to be cleared - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_ClearWriteRegAddress(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum) -{ - /* Check the parameters */ - assert_param(IS_MDIOS_REGISTER(RegNum)); - - /* Process Locked */ - __HAL_LOCK(hmdios); - - /* Clear write registers flags */ - hmdios->Instance->CWRFR |= (RegNum); - - /* Release Lock */ - __HAL_UNLOCK(hmdios); - - return HAL_OK; -} - -/** - * @brief Clears Read register flag - * @param hmdios: mdios handle - * @param RegNum: registers addresses to be cleared - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_ClearReadRegAddress(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum) -{ - /* Check the parameters */ - assert_param(IS_MDIOS_REGISTER(RegNum)); - - /* Process Locked */ - __HAL_LOCK(hmdios); - - /* Clear read registers flags */ - hmdios->Instance->CRDFR |= (RegNum); - - /* Release Lock */ - __HAL_UNLOCK(hmdios); - - return HAL_OK; -} - -/** - * @brief Enables Events for MDIOS peripheral - * @param hmdios: mdios handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MDIOS_EnableEvents(MDIOS_HandleTypeDef *hmdios) -{ - /* Process Locked */ - __HAL_LOCK(hmdios); - - /* Enable MDIOS interrupts: Register Write, Register Read and Error ITs */ - __HAL_MDIOS_ENABLE_IT(hmdios, (MDIOS_IT_WRITE | MDIOS_IT_READ | MDIOS_IT_ERROR)); - - /* Process Unlocked */ - __HAL_UNLOCK(hmdios); - - return HAL_OK; -} - -/** - * @brief This function handles MDIOS interrupt request. - * @param hmdios: MDIOS handle - * @retval None - */ -void HAL_MDIOS_IRQHandler(MDIOS_HandleTypeDef *hmdios) -{ - /* Write Register Interrupt enabled ? */ - if (__HAL_MDIOS_GET_IT_SOURCE(hmdios, MDIOS_IT_WRITE) != (uint32_t)RESET) - { - /* Write register flag */ - if (HAL_MDIOS_GetWrittenRegAddress(hmdios) != (uint32_t)RESET) - { -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) - /*Call registered Write complete callback*/ - hmdios->WriteCpltCallback(hmdios); -#else - /* Write callback function */ - HAL_MDIOS_WriteCpltCallback(hmdios); -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ - - /* Clear write register flag */ - hmdios->Instance->CWRFR |= MDIOS_ALL_REG_FLAG; - } - } - - /* Read Register Interrupt enabled ? */ - if (__HAL_MDIOS_GET_IT_SOURCE(hmdios, MDIOS_IT_READ) != (uint32_t)RESET) - { - /* Read register flag */ - if (HAL_MDIOS_GetReadRegAddress(hmdios) != (uint32_t)RESET) - { -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) - /*Call registered Read complete callback*/ - hmdios->ReadCpltCallback(hmdios); -#else - /* Read callback function */ - HAL_MDIOS_ReadCpltCallback(hmdios); -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ - - /* Clear read register flag */ - hmdios->Instance->CRDFR |= MDIOS_ALL_REG_FLAG; - } - } - - /* Error Interrupt enabled ? */ - if (__HAL_MDIOS_GET_IT_SOURCE(hmdios, MDIOS_IT_ERROR) != (uint32_t)RESET) - { - /* All Errors Flag */ - if (__HAL_MDIOS_GET_ERROR_FLAG(hmdios, MDIOS_ALL_ERRORS_FLAG) != (uint32_t)RESET) - { - hmdios->ErrorCode |= HAL_MDIOS_ERROR_DATA; - -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) - /*Call registered Error callback*/ - hmdios->ErrorCallback(hmdios); -#else - /* Error Callback */ - HAL_MDIOS_ErrorCallback(hmdios); -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ - - /* Clear errors flag */ - __HAL_MDIOS_CLEAR_ERROR_FLAG(hmdios, MDIOS_ALL_ERRORS_FLAG); - } - hmdios->ErrorCode = HAL_MDIOS_ERROR_NONE; - } - /* check MDIOS WAKEUP exti flag */ - if (__HAL_MDIOS_WAKEUP_EXTI_GET_FLAG(MDIOS_WAKEUP_EXTI_LINE) != (uint32_t)RESET) - { - /* Clear MDIOS WAKEUP Exti pending bit */ - __HAL_MDIOS_WAKEUP_EXTI_CLEAR_FLAG(MDIOS_WAKEUP_EXTI_LINE); -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) - /*Call registered WakeUp callback*/ - hmdios->WakeUpCallback(hmdios); -#else - /* MDIOS WAKEUP callback */ - HAL_MDIOS_WakeUpCallback(hmdios); -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ - } - -} - -/** - * @brief Write Complete Callback - * @param hmdios: mdios handle - * @retval None - */ -__weak void HAL_MDIOS_WriteCpltCallback(MDIOS_HandleTypeDef *hmdios) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdios); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MDIOS_WriteCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Read Complete Callback - * @param hmdios: mdios handle - * @retval None - */ -__weak void HAL_MDIOS_ReadCpltCallback(MDIOS_HandleTypeDef *hmdios) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdios); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MDIOS_ReadCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Error Callback - * @param hmdios: mdios handle - * @retval None - */ -__weak void HAL_MDIOS_ErrorCallback(MDIOS_HandleTypeDef *hmdios) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdios); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MDIOS_ErrorCallback can be implemented in the user file - */ -} - -/** - * @brief MDIOS WAKEUP interrupt callback - * @param hmdios: mdios handle - * @retval None - */ -__weak void HAL_MDIOS_WakeUpCallback(MDIOS_HandleTypeDef *hmdios) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmdios); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_MDIOS_WakeUpCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup MDIOS_Exported_Functions_Group3 Peripheral Control functions - * @brief MDIOS control functions - * -@verbatim - =============================================================================== - ##### Peripheral Control functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to control the MDIOS. - (+) HAL_MDIOS_GetState() API, helpful to check in run-time the state. - (+) HAL_MDIOS_GetError() API, returns the errors code of the HAL state machine. - -@endverbatim - * @{ - */ - -/** - * @brief Gets MDIOS error code - * @param hmdios: mdios handle - * @retval mdios error code - */ -uint32_t HAL_MDIOS_GetError(MDIOS_HandleTypeDef *hmdios) -{ - /* return the error code */ - return hmdios->ErrorCode; -} - -/** - * @brief Return the MDIOS HAL state - * @param hmdios: mdios handle - * @retval HAL state - */ -HAL_MDIOS_StateTypeDef HAL_MDIOS_GetState(MDIOS_HandleTypeDef *hmdios) -{ - /* Return MDIOS state */ - return hmdios->State; -} - -/** - * @} - */ - -/** - * @} - */ - -#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) -static void MDIOS_InitCallbacksToDefault(MDIOS_HandleTypeDef *hmdios) -{ - /* Init the MDIOS Callback settings */ - hmdios->WriteCpltCallback = HAL_MDIOS_WriteCpltCallback; /* Legacy weak WriteCpltCallback */ - hmdios->ReadCpltCallback = HAL_MDIOS_ReadCpltCallback; /* Legacy weak ReadCpltCallback */ - hmdios->ErrorCallback = HAL_MDIOS_ErrorCallback; /* Legacy weak ErrorCallback */ - hmdios->WakeUpCallback = HAL_MDIOS_WakeUpCallback; /* Legacy weak WakeUpCallback */ -} -#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ - -/** - * @} - */ -#endif /* HAL_MDIOS_MODULE_ENABLED */ -/** - * @} - */ -#endif /* MDIOS */ -/** - * @} - */ \ No newline at end of file +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_mdios.c + * @author MCD Application Team + * @brief MDIOS HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the MDIOS Peripheral. + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2017 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The MDIOS HAL driver can be used as follow: + + (#) Declare a MDIOS_HandleTypeDef handle structure. + + (#) Initialize the MDIOS low level resources by implementing the HAL_MDIOS_MspInit() API: + (##) Enable the MDIOS interface clock. + (##) MDIOS pins configuration: + (+++) Enable clocks for the MDIOS GPIOs. + (+++) Configure the MDIOS pins as alternate function. + (##) NVIC configuration if you need to use interrupt process: + (+++) Configure the MDIOS interrupt priority. + (+++) Enable the NVIC MDIOS IRQ handle. + + (#) Program the Port Address and the Preamble Check in the Init structure. + + (#) Initialize the MDIOS registers by calling the HAL_MDIOS_Init() API. + + (#) Perform direct slave read/write operations using the following APIs: + (##) Read the value of a DINn register: HAL_MDIOS_ReadReg() + (##) Write a value to a DOUTn register: HAL_MDIOS_WriteReg() + + (#) Get the Master read/write operations flags using the following APIs: + (##) Bit map of DOUTn registers read by Master: HAL_MDIOS_GetReadRegAddress() + (##) Bit map of DINn registers written by Master : HAL_MDIOS_GetWrittenRegAddress() + + (#) Clear the read/write flags using the following APIs: + (##) Clear read flags of a set of registers: HAL_MDIOS_ClearReadRegAddress() + (##) Clear write flags of a set of registers: HAL_MDIOS_ClearWriteRegAddress() + + (#) Enable interrupts on events using HAL_MDIOS_EnableEvents(), when called + the MDIOS will generate an interrupt in the following cases: + (##) a DINn register written by the Master + (##) a DOUTn register read by the Master + (##) an error occur + + (@) A callback is executed for each generated interrupt, so the driver provide the following + HAL_MDIOS_WriteCpltCallback(), HAL_MDIOS_ReadCpltCallback() and HAL_MDIOS_ErrorCallback() + (@) HAL_MDIOS_IRQHandler() must be called from the MDIOS IRQ Handler, to handle the interrupt + and execute the previous callbacks + + (#) Reset the MDIOS peripheral and all related resources by calling the HAL_MDIOS_DeInit() API. + (##) HAL_MDIOS_MspDeInit() must be implemented to reset low level resources + (GPIO, Clocks, NVIC configuration ...) + + *** Callback registration *** + ============================================= + + The compilation define USE_HAL_MDIOS_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function @ref HAL_MDIOS_RegisterCallback() to register an interrupt callback. + + Function @ref HAL_MDIOS_RegisterCallback() allows to register following callbacks: + (+) WriteCpltCallback : Write Complete Callback. + (+) ReadCpltCallback : Read Complete Callback. + (+) ErrorCallback : Error Callback. + (+) WakeUpCallback : Wake UP Callback + (+) MspInitCallback : MspInit Callback. + (+) MspDeInitCallback : MspDeInit Callback. + + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function @ref HAL_MDIOS_UnRegisterCallback() to reset a callback to the default + weak function. + @ref HAL_MDIOS_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) WriteCpltCallback : Write Complete Callback. + (+) ReadCpltCallback : Read Complete Callback. + (+) ErrorCallback : Error Callback. + (+) WakeUpCallback : Wake UP Callback + (+) MspInitCallback : MspInit Callback. + (+) MspDeInitCallback : MspDeInit Callback. + + By default, after the HAL_MDIOS_Init and when the state is HAL_MDIOS_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples @ref HAL_MDIOS_WriteCpltCallback(), @ref HAL_MDIOS_ReadCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the HAL_MDIOS_Init/ @ref HAL_MDIOS_DeInit only when + these callbacks are null (not registered beforehand). + if not, MspInit or MspDeInit are not null, the HAL_MDIOS_Init/ @ref HAL_MDIOS_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in HAL_MDIOS_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_MDIOS_STATE_READY or HAL_MDIOS_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using @ref HAL_MDIOS_RegisterCallback() before calling @ref HAL_MDIOS_DeInit + or HAL_MDIOS_Init function. + + When The compilation define USE_HAL_MDIOS_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ +#if defined (MDIOS) +/** @defgroup MDIOS MDIOS + * @brief HAL MDIOS module driver + * @{ + */ +#ifdef HAL_MDIOS_MODULE_ENABLED + + + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define MDIOS_PORT_ADDRESS_SHIFT ((uint32_t)8) +#define MDIOS_ALL_REG_FLAG ((uint32_t)0xFFFFFFFFU) +#define MDIOS_ALL_ERRORS_FLAG ((uint32_t)(MDIOS_SR_PERF | MDIOS_SR_SERF | MDIOS_SR_TERF)) + +#define MDIOS_DIN_BASE_ADDR (MDIOS_BASE + 0x100U) +#define MDIOS_DOUT_BASE_ADDR (MDIOS_BASE + 0x180U) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) +static void MDIOS_InitCallbacksToDefault(MDIOS_HandleTypeDef *hmdios); +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup MDIOS_Exported_Functions MDIOS Exported Functions + * @{ + */ + +/** @defgroup MDIOS_Exported_Functions_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the MDIOS + (+) The following parameters can be configured: + (++) Port Address + (++) Preamble Check + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the MDIOS according to the specified parameters in + * the MDIOS_InitTypeDef and creates the associated handle . + * @param hmdios: pointer to a MDIOS_HandleTypeDef structure that contains + * the configuration information for MDIOS module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_Init(MDIOS_HandleTypeDef *hmdios) +{ + uint32_t tmpcr; + + /* Check the MDIOS handle allocation */ + if (hmdios == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_MDIOS_ALL_INSTANCE(hmdios->Instance)); + assert_param(IS_MDIOS_PORTADDRESS(hmdios->Init.PortAddress)); + assert_param(IS_MDIOS_PREAMBLECHECK(hmdios->Init.PreambleCheck)); + +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) + + if (hmdios->State == HAL_MDIOS_STATE_RESET) + { + MDIOS_InitCallbacksToDefault(hmdios); + + if (hmdios->MspInitCallback == NULL) + { + hmdios->MspInitCallback = HAL_MDIOS_MspInit; + } + + /* Init the low level hardware */ + hmdios->MspInitCallback(hmdios); + } + +#else + + if (hmdios->State == HAL_MDIOS_STATE_RESET) + { + /* Init the low level hardware */ + HAL_MDIOS_MspInit(hmdios); + } + +#endif /* (USE_HAL_MDIOS_REGISTER_CALLBACKS) */ + + /* Change the MDIOS state */ + hmdios->State = HAL_MDIOS_STATE_BUSY; + + /* Get the MDIOS CR value */ + tmpcr = hmdios->Instance->CR; + + /* Clear PORT_ADDRESS, DPC and EN bits */ + tmpcr &= ((uint32_t)~(MDIOS_CR_EN | MDIOS_CR_DPC | MDIOS_CR_PORT_ADDRESS)); + + /* Set MDIOS control parameters and enable the peripheral */ + tmpcr |= (uint32_t)(((hmdios->Init.PortAddress) << MDIOS_PORT_ADDRESS_SHIFT) | \ + (hmdios->Init.PreambleCheck) | \ + (MDIOS_CR_EN)); + + /* Write the MDIOS CR */ + hmdios->Instance->CR = tmpcr; + + hmdios->ErrorCode = HAL_MDIOS_ERROR_NONE; + + /* Change the MDIOS state */ + hmdios->State = HAL_MDIOS_STATE_READY; + + /* Release Lock */ + __HAL_UNLOCK(hmdios); + + /* Return function status */ + return HAL_OK; + +} + +/** + * @brief DeInitializes the MDIOS peripheral. + * @param hmdios: MDIOS handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_DeInit(MDIOS_HandleTypeDef *hmdios) +{ + /* Check the MDIOS handle allocation */ + if (hmdios == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_MDIOS_ALL_INSTANCE(hmdios->Instance)); + + /* Change the MDIOS state */ + hmdios->State = HAL_MDIOS_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_MDIOS_DISABLE(hmdios); + +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) + + if (hmdios->MspDeInitCallback == NULL) + { + hmdios->MspDeInitCallback = HAL_MDIOS_MspDeInit; + } + /* DeInit the low level hardware */ + hmdios->MspDeInitCallback(hmdios); +#else + + /* DeInit the low level hardware */ + HAL_MDIOS_MspDeInit(hmdios); + +#endif /* (USE_HAL_MDIOS_REGISTER_CALLBACKS) */ + + /* Change the MDIOS state */ + hmdios->State = HAL_MDIOS_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hmdios); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief MDIOS MSP Init + * @param hmdios: mdios handle + * @retval None + */ +__weak void HAL_MDIOS_MspInit(MDIOS_HandleTypeDef *hmdios) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdios); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MDIOS_MspInit can be implemented in the user file + */ +} + +/** + * @brief MDIOS MSP DeInit + * @param hmdios: mdios handle + * @retval None + */ +__weak void HAL_MDIOS_MspDeInit(MDIOS_HandleTypeDef *hmdios) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdios); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MDIOS_MspDeInit can be implemented in the user file + */ +} + +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User MDIOS Callback + * To be used instead of the weak predefined callback + * @param hmdios mdios handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_MDIOS_WRITE_COMPLETE_CB_ID Write Complete Callback ID + * @arg @ref HAL_MDIOS_READ_COMPLETE_CB_ID Read Complete Callback ID + * @arg @ref HAL_MDIOS_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_MDIOS_WAKEUP_CB_ID Wake Up Callback ID + * @arg @ref HAL_MDIOS_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_MDIOS_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_MDIOS_RegisterCallback(MDIOS_HandleTypeDef *hmdios, HAL_MDIOS_CallbackIDTypeDef CallbackID, + pMDIOS_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hmdios); + + if (hmdios->State == HAL_MDIOS_STATE_READY) + { + switch (CallbackID) + { + case HAL_MDIOS_WRITE_COMPLETE_CB_ID : + hmdios->WriteCpltCallback = pCallback; + break; + + case HAL_MDIOS_READ_COMPLETE_CB_ID : + hmdios->ReadCpltCallback = pCallback; + break; + + case HAL_MDIOS_ERROR_CB_ID : + hmdios->ErrorCallback = pCallback; + break; + + case HAL_MDIOS_WAKEUP_CB_ID : + hmdios->WakeUpCallback = pCallback; + break; + + case HAL_MDIOS_MSPINIT_CB_ID : + hmdios->MspInitCallback = pCallback; + break; + + case HAL_MDIOS_MSPDEINIT_CB_ID : + hmdios->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hmdios->State == HAL_MDIOS_STATE_RESET) + { + switch (CallbackID) + { + case HAL_MDIOS_MSPINIT_CB_ID : + hmdios->MspInitCallback = pCallback; + break; + + case HAL_MDIOS_MSPDEINIT_CB_ID : + hmdios->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hmdios); + + return status; +} + +/** + * @brief Unregister an MDIOS Callback + * MDIOS callback is redirected to the weak predefined callback + * @param hmdios mdios handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_MDIOS_WRITE_COMPLETE_CB_ID Write Complete Callback ID + * @arg @ref HAL_MDIOS_READ_COMPLETE_CB_ID Read Complete Callback ID + * @arg @ref HAL_MDIOS_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_MDIOS_WAKEUP_CB_ID Wake Up Callback ID + * @arg @ref HAL_MDIOS_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_MDIOS_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_MDIOS_UnRegisterCallback(MDIOS_HandleTypeDef *hmdios, HAL_MDIOS_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hmdios); + + if (hmdios->State == HAL_MDIOS_STATE_READY) + { + switch (CallbackID) + { + case HAL_MDIOS_WRITE_COMPLETE_CB_ID : + hmdios->WriteCpltCallback = HAL_MDIOS_WriteCpltCallback; + break; + + case HAL_MDIOS_READ_COMPLETE_CB_ID : + hmdios->ReadCpltCallback = HAL_MDIOS_ReadCpltCallback; + break; + + case HAL_MDIOS_ERROR_CB_ID : + hmdios->ErrorCallback = HAL_MDIOS_ErrorCallback; + break; + + case HAL_MDIOS_WAKEUP_CB_ID : + hmdios->WakeUpCallback = HAL_MDIOS_WakeUpCallback; + break; + + case HAL_MDIOS_MSPINIT_CB_ID : + hmdios->MspInitCallback = HAL_MDIOS_MspInit; + break; + + case HAL_MDIOS_MSPDEINIT_CB_ID : + hmdios->MspDeInitCallback = HAL_MDIOS_MspDeInit; + break; + + default : + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hmdios->State == HAL_MDIOS_STATE_RESET) + { + switch (CallbackID) + { + case HAL_MDIOS_MSPINIT_CB_ID : + hmdios->MspInitCallback = HAL_MDIOS_MspInit; + break; + + case HAL_MDIOS_MSPDEINIT_CB_ID : + hmdios->MspDeInitCallback = HAL_MDIOS_MspDeInit; + break; + + default : + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hmdios->ErrorCode |= HAL_MDIOS_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hmdios); + + return status; +} +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup MDIOS_Exported_Functions_Group2 IO operation functions + * @brief MDIOS Read/Write functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the MDIOS + read and write operations. + + (#) APIs that allow to the MDIOS to read/write from/to the + values of one of the DINn/DOUTn registers: + (+) Read the value of a DINn register: HAL_MDIOS_ReadReg() + (+) Write a value to a DOUTn register: HAL_MDIOS_WriteReg() + + (#) APIs that provide if there are some Slave registres have been + read or written by the Master: + (+) DOUTn registers read by Master: HAL_MDIOS_GetReadRegAddress() + (+) DINn registers written by Master : HAL_MDIOS_GetWrittenRegAddress() + + (#) APIs that Clear the read/write flags: + (+) Clear read registers flags: HAL_MDIOS_ClearReadRegAddress() + (+) Clear write registers flags: HAL_MDIOS_ClearWriteRegAddress() + + (#) A set of Callbacks are provided: + (+) HAL_MDIOS_WriteCpltCallback() + (+) HAL_MDIOS_ReadCpltCallback() + (+) HAL_MDIOS_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Writes to an MDIOS output register + * @param hmdios: mdios handle + * @param RegNum: MDIOS output register address + * @param Data: Data to write + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_WriteReg(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum, uint16_t Data) +{ + uint32_t tmpreg; + + /* Check the parameters */ + assert_param(IS_MDIOS_REGISTER(RegNum)); + + /* Process Locked */ + __HAL_LOCK(hmdios); + + /* Get the addr of output register to be written by the MDIOS */ + tmpreg = MDIOS_DOUT_BASE_ADDR + (4U * RegNum); + + /* Write to DOUTn register */ + *((uint32_t *)tmpreg) = Data; + + /* Process Unlocked */ + __HAL_UNLOCK(hmdios); + + return HAL_OK; +} + +/** + * @brief Reads an MDIOS input register + * @param hmdios: mdios handle + * @param RegNum: MDIOS input register address + * @param pData: pointer to Data + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_ReadReg(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum, uint16_t *pData) +{ + uint32_t tmpreg; + + /* Check the parameters */ + assert_param(IS_MDIOS_REGISTER(RegNum)); + + /* Process Locked */ + __HAL_LOCK(hmdios); + + /* Get the addr of input register to be read by the MDIOS */ + tmpreg = MDIOS_DIN_BASE_ADDR + (4U * RegNum); + + /* Read DINn register */ + *pData = (uint16_t)(*((uint32_t *)tmpreg)); + + /* Process Unlocked */ + __HAL_UNLOCK(hmdios); + + return HAL_OK; +} + +/** + * @brief Gets Written registers by MDIO master + * @param hmdios: mdios handle + * @retval bit map of written registers addresses + */ +uint32_t HAL_MDIOS_GetWrittenRegAddress(MDIOS_HandleTypeDef *hmdios) +{ + return hmdios->Instance->WRFR; +} + +/** + * @brief Gets Read registers by MDIO master + * @param hmdios: mdios handle + * @retval bit map of read registers addresses + */ +uint32_t HAL_MDIOS_GetReadRegAddress(MDIOS_HandleTypeDef *hmdios) +{ + return hmdios->Instance->RDFR; +} + +/** + * @brief Clears Write registers flag + * @param hmdios: mdios handle + * @param RegNum: registers addresses to be cleared + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_ClearWriteRegAddress(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum) +{ + /* Check the parameters */ + assert_param(IS_MDIOS_REGISTER(RegNum)); + + /* Process Locked */ + __HAL_LOCK(hmdios); + + /* Clear write registers flags */ + hmdios->Instance->CWRFR |= (RegNum); + + /* Release Lock */ + __HAL_UNLOCK(hmdios); + + return HAL_OK; +} + +/** + * @brief Clears Read register flag + * @param hmdios: mdios handle + * @param RegNum: registers addresses to be cleared + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_ClearReadRegAddress(MDIOS_HandleTypeDef *hmdios, uint32_t RegNum) +{ + /* Check the parameters */ + assert_param(IS_MDIOS_REGISTER(RegNum)); + + /* Process Locked */ + __HAL_LOCK(hmdios); + + /* Clear read registers flags */ + hmdios->Instance->CRDFR |= (RegNum); + + /* Release Lock */ + __HAL_UNLOCK(hmdios); + + return HAL_OK; +} + +/** + * @brief Enables Events for MDIOS peripheral + * @param hmdios: mdios handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MDIOS_EnableEvents(MDIOS_HandleTypeDef *hmdios) +{ + /* Process Locked */ + __HAL_LOCK(hmdios); + + /* Enable MDIOS interrupts: Register Write, Register Read and Error ITs */ + __HAL_MDIOS_ENABLE_IT(hmdios, (MDIOS_IT_WRITE | MDIOS_IT_READ | MDIOS_IT_ERROR)); + + /* Process Unlocked */ + __HAL_UNLOCK(hmdios); + + return HAL_OK; +} + +/** + * @brief This function handles MDIOS interrupt request. + * @param hmdios: MDIOS handle + * @retval None + */ +void HAL_MDIOS_IRQHandler(MDIOS_HandleTypeDef *hmdios) +{ + /* Write Register Interrupt enabled ? */ + if (__HAL_MDIOS_GET_IT_SOURCE(hmdios, MDIOS_IT_WRITE) != (uint32_t)RESET) + { + /* Write register flag */ + if (HAL_MDIOS_GetWrittenRegAddress(hmdios) != (uint32_t)RESET) + { +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) + /*Call registered Write complete callback*/ + hmdios->WriteCpltCallback(hmdios); +#else + /* Write callback function */ + HAL_MDIOS_WriteCpltCallback(hmdios); +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ + + /* Clear write register flag */ + hmdios->Instance->CWRFR |= MDIOS_ALL_REG_FLAG; + } + } + + /* Read Register Interrupt enabled ? */ + if (__HAL_MDIOS_GET_IT_SOURCE(hmdios, MDIOS_IT_READ) != (uint32_t)RESET) + { + /* Read register flag */ + if (HAL_MDIOS_GetReadRegAddress(hmdios) != (uint32_t)RESET) + { +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) + /*Call registered Read complete callback*/ + hmdios->ReadCpltCallback(hmdios); +#else + /* Read callback function */ + HAL_MDIOS_ReadCpltCallback(hmdios); +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ + + /* Clear read register flag */ + hmdios->Instance->CRDFR |= MDIOS_ALL_REG_FLAG; + } + } + + /* Error Interrupt enabled ? */ + if (__HAL_MDIOS_GET_IT_SOURCE(hmdios, MDIOS_IT_ERROR) != (uint32_t)RESET) + { + /* All Errors Flag */ + if (__HAL_MDIOS_GET_ERROR_FLAG(hmdios, MDIOS_ALL_ERRORS_FLAG) != (uint32_t)RESET) + { + hmdios->ErrorCode |= HAL_MDIOS_ERROR_DATA; + +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) + /*Call registered Error callback*/ + hmdios->ErrorCallback(hmdios); +#else + /* Error Callback */ + HAL_MDIOS_ErrorCallback(hmdios); +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ + + /* Clear errors flag */ + __HAL_MDIOS_CLEAR_ERROR_FLAG(hmdios, MDIOS_ALL_ERRORS_FLAG); + } + hmdios->ErrorCode = HAL_MDIOS_ERROR_NONE; + } + /* check MDIOS WAKEUP exti flag */ + if (__HAL_MDIOS_WAKEUP_EXTI_GET_FLAG(MDIOS_WAKEUP_EXTI_LINE) != (uint32_t)RESET) + { + /* Clear MDIOS WAKEUP Exti pending bit */ + __HAL_MDIOS_WAKEUP_EXTI_CLEAR_FLAG(MDIOS_WAKEUP_EXTI_LINE); +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) + /*Call registered WakeUp callback*/ + hmdios->WakeUpCallback(hmdios); +#else + /* MDIOS WAKEUP callback */ + HAL_MDIOS_WakeUpCallback(hmdios); +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ + } + +} + +/** + * @brief Write Complete Callback + * @param hmdios: mdios handle + * @retval None + */ +__weak void HAL_MDIOS_WriteCpltCallback(MDIOS_HandleTypeDef *hmdios) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdios); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MDIOS_WriteCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Read Complete Callback + * @param hmdios: mdios handle + * @retval None + */ +__weak void HAL_MDIOS_ReadCpltCallback(MDIOS_HandleTypeDef *hmdios) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdios); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MDIOS_ReadCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Error Callback + * @param hmdios: mdios handle + * @retval None + */ +__weak void HAL_MDIOS_ErrorCallback(MDIOS_HandleTypeDef *hmdios) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdios); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MDIOS_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief MDIOS WAKEUP interrupt callback + * @param hmdios: mdios handle + * @retval None + */ +__weak void HAL_MDIOS_WakeUpCallback(MDIOS_HandleTypeDef *hmdios) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmdios); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MDIOS_WakeUpCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup MDIOS_Exported_Functions_Group3 Peripheral Control functions + * @brief MDIOS control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the MDIOS. + (+) HAL_MDIOS_GetState() API, helpful to check in run-time the state. + (+) HAL_MDIOS_GetError() API, returns the errors code of the HAL state machine. + +@endverbatim + * @{ + */ + +/** + * @brief Gets MDIOS error code + * @param hmdios: mdios handle + * @retval mdios error code + */ +uint32_t HAL_MDIOS_GetError(MDIOS_HandleTypeDef *hmdios) +{ + /* return the error code */ + return hmdios->ErrorCode; +} + +/** + * @brief Return the MDIOS HAL state + * @param hmdios: mdios handle + * @retval HAL state + */ +HAL_MDIOS_StateTypeDef HAL_MDIOS_GetState(MDIOS_HandleTypeDef *hmdios) +{ + /* Return MDIOS state */ + return hmdios->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#if (USE_HAL_MDIOS_REGISTER_CALLBACKS == 1) +static void MDIOS_InitCallbacksToDefault(MDIOS_HandleTypeDef *hmdios) +{ + /* Init the MDIOS Callback settings */ + hmdios->WriteCpltCallback = HAL_MDIOS_WriteCpltCallback; /* Legacy weak WriteCpltCallback */ + hmdios->ReadCpltCallback = HAL_MDIOS_ReadCpltCallback; /* Legacy weak ReadCpltCallback */ + hmdios->ErrorCallback = HAL_MDIOS_ErrorCallback; /* Legacy weak ErrorCallback */ + hmdios->WakeUpCallback = HAL_MDIOS_WakeUpCallback; /* Legacy weak WakeUpCallback */ +} +#endif /* USE_HAL_MDIOS_REGISTER_CALLBACKS */ + +/** + * @} + */ +#endif /* HAL_MDIOS_MODULE_ENABLED */ +/** + * @} + */ +#endif /* MDIOS */ +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc.c index 874060e3d..1fb9a27f0 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc.c @@ -1,5890 +1,5890 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_mmc.c - * @author MCD Application Team - * @brief MMC card HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Secure Digital (MMC) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral Control functions - * + MMC card Control functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 (SDMMC and GPIO) are performed by - the user in HAL_MMC_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 SDMMC memories which uses the HAL - SDMMC driver functions to interface with MMC and eMMC cards devices. - It is used as follows: - - (#)Initialize the SDMMC low level resources by implement the HAL_MMC_MspInit() API: - (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE(); - (##) SDMMC pins configuration for MMC card - (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE(); - (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init() - and according to your pin assignment; - (##) NVIC configuration if you need to use interrupt process (HAL_MMC_ReadBlocks_IT() - and HAL_MMC_WriteBlocks_IT() APIs). - (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority(); - (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ() - (+++) SDMMC interrupts are managed using the macros __HAL_MMC_ENABLE_IT() - and __HAL_MMC_DISABLE_IT() inside the communication process. - (+++) SDMMC interrupts pending bits are managed using the macros __HAL_MMC_GET_IT() - and __HAL_MMC_CLEAR_IT() - (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used. - - (#) At this stage, you can perform MMC read/write/erase operations after MMC card initialization - - *** MMC Card Initialization and configuration *** - ================================================ - [..] - To initialize the MMC Card, use the HAL_MMC_Init() function. It Initializes - SDMMC Peripheral (STM32 side) and the MMC Card, and put it into StandBy State (Ready for data transfer). - This function provide the following operations: - - (#) Initialize the SDMMC peripheral interface with default configuration. - The initialization process is done at 400KHz. You can change or adapt - this frequency by adjusting the "ClockDiv" field. - The MMC Card frequency (SDMMC_CK) is computed as follows: - - SDMMC_CK = SDMMCCLK / (2 * ClockDiv) - - In initialization mode and according to the MMC Card standard, - make sure that the SDMMC_CK frequency doesn't exceed 400KHz. - - This phase of initialization is done through SDMMC_Init() and - SDMMC_PowerState_ON() SDMMC low level APIs. - - (#) Initialize the MMC card. The API used is HAL_MMC_InitCard(). - This phase allows the card initialization and identification - and check the MMC Card type (Standard Capacity or High Capacity) - The initialization flow is compatible with MMC standard. - - This API (HAL_MMC_InitCard()) could be used also to reinitialize the card in case - of plug-off plug-in. - - (#) Configure the MMC Card Data transfer frequency. By Default, the card transfer - frequency by adjusting the "ClockDiv" field. - In transfer mode and according to the MMC Card standard, make sure that the - SDMMC_CK frequency doesn't exceed 25MHz and 100MHz in High-speed mode switch. - - (#) Select the corresponding MMC Card according to the address read with the step 2. - - (#) Configure the MMC Card in wide bus mode: 4-bits data. - (#) Select the MMC Card partition using HAL_MMC_SwitchPartition() - - *** MMC Card Read operation *** - ============================== - [..] - (+) You can read from MMC card in polling mode by using function HAL_MMC_ReadBlocks(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - - (+) You can read from MMC card in DMA mode by using function HAL_MMC_ReadBlocks_DMA(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the DMA transfer process through the MMC Rx interrupt event. - - (+) You can read from MMC card in Interrupt mode by using function HAL_MMC_ReadBlocks_IT(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the IT transfer process through the MMC Rx interrupt event. - - *** MMC Card Write operation *** - =============================== - [..] - (+) You can write to MMC card in polling mode by using function HAL_MMC_WriteBlocks(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - - (+) You can write to MMC card in DMA mode by using function HAL_MMC_WriteBlocks_DMA(). - This function support only 512-bytes 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 ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the DMA transfer process through the MMC Tx interrupt event. - - (+) You can write to MMC card in Interrupt mode by using function HAL_MMC_WriteBlocks_IT(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the IT transfer process through the MMC Tx interrupt event. - - *** MMC card information *** - =========================== - [..] - (+) To get MMC card information, you can use the function HAL_MMC_GetCardInfo(). - It returns useful information about the MMC card such as block size, card type, - block number ... - - *** MMC card CSD register *** - ============================ - [..] - (+) The HAL_MMC_GetCardCSD() API allows to get the parameters of the CSD register. - Some of the CSD parameters are useful for card initialization and identification. - - *** MMC card CID register *** - ============================ - [..] - (+) The HAL_MMC_GetCardCID() API allows to get the parameters of the CID register. - Some of the CID parameters are useful for card initialization and identification. - - *** MMC Card Reply Protected Memory Block (RPMB) Key Programming operation *** - ============================== - [..] - (+) You can program the authentication key of RPMB area in polling mode by using function - HAL_MMC_RPMB_ProgramAuthenticationKey(). - This function is only used once during the life of an MMC card. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetRPMBError() function for operation state. - (+) You can program the authentication key of RPMB area in Interrupt mode by using function - HAL_MMC_RPMB_ProgramAuthenticationKey_IT(). - This function is only used once during the life of an MMC card. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetRPMBError() function for operation state. - - *** MMC Card Reply Protected Memory Block (RPMB) write counter operation *** - ============================== - [..] - (+) You can get the write counter value of RPMB area in polling mode by using function - HAL_MMC_RPMB_GetWriteCounter(). - (+) You can get the write counter value of RPMB area in Interrupt mode by using function - HAL_MMC_RPMB_GetWriteCounter_IT(). - - *** MMC Card Reply Protected Memory Block (RPMB) write operation *** - ============================== - [..] - (+) You can write to the RPMB area of MMC card in polling mode by using function - HAL_MMC_WriteBlocks(). - This function supports the one, two, or thirty two blocks write operation - (with 512-bytes block length). - You can choose the number of blocks at the multiple block read operation by adjusting - the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetRPMBError() function for operation state. - (+) You can write to the RPMB area of MMC card in Interrupt mode by using function - HAL_MMC_WriteBlocks_IT(). - This function supports the one, two, or thirty two blocks write operation - (with 512-bytes block length). - You can choose the number of blocks at the multiple block read operation by adjusting - the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetRPMBError() function for operation state. - - *** MMC Card Reply Protected Memory Block (RPMB) read operation *** - ============================== - [..] - (+) You can read from the RPMB area of MMC card in polling mode by using function - HAL_MMC_RPMB_ReadBlocks(). - The block size should be chosen as multiple of 512 bytes. - You can choose the number of blocks by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetRPMBError() function for MMC card state. - (+) You can read from the RPMB area of MMC card in Interrupt mode by using function - HAL_MMC_RPMB_ReadBlocks_IT(). - The block size should be chosen as multiple of 512 bytes. - You can choose the number of blocks by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetRPMBError() function for MMC card state. - - *** MMC HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in MMC HAL driver. - - (+) __HAL_MMC_ENABLE_IT: Enable the MMC device interrupt - (+) __HAL_MMC_DISABLE_IT: Disable the MMC device interrupt - (+) __HAL_MMC_GET_FLAG:Check whether the specified MMC flag is set or not - (+) __HAL_MMC_CLEAR_FLAG: Clear the MMC's pending flags - - [..] - (@) You can refer to the MMC HAL driver header file for more useful macros - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_MMC_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - Use Functions HAL_MMC_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) TxCpltCallback : callback when a transmission transfer is completed. - (+) RxCpltCallback : callback when a reception transfer is completed. - (+) ErrorCallback : callback when error occurs. - (+) AbortCpltCallback : callback when abort is completed. - (+) Read_DMALnkLstBufCpltCallback : callback when the DMA reception of linked list node buffer is completed. - (+) Write_DMALnkLstBufCpltCallback : callback when the DMA transmission of linked list node buffer is completed. - (+) MspInitCallback : MMC MspInit. - (+) MspDeInitCallback : MMC MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function HAL_MMC_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) TxCpltCallback : callback when a transmission transfer is completed. - (+) RxCpltCallback : callback when a reception transfer is completed. - (+) ErrorCallback : callback when error occurs. - (+) AbortCpltCallback : callback when abort is completed. - (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed. - (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed. - (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed. - (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed. - (+) MspInitCallback : MMC MspInit. - (+) MspDeInitCallback : MMC MspDeInit. - This function) takes as parameters the HAL peripheral handle and the Callback ID. - - By default, after the HAL_MMC_Init and if the state is HAL_MMC_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_MMC_Init - and HAL_MMC_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_MMC_Init and HAL_MMC_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_MMC_RegisterCallback before calling HAL_MMC_DeInit - or HAL_MMC_Init function. - - When The compilation define USE_HAL_MMC_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup MMC MMC - * @brief MMC HAL module driver - * @{ - */ - -#if defined (SDMMC1) || defined (SDMMC2) -#ifdef HAL_MMC_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup MMC_Private_Defines - * @{ - */ -#if defined (VDD_VALUE) && (VDD_VALUE <= 1950U) -#define MMC_VOLTAGE_RANGE EMMC_LOW_VOLTAGE_RANGE - -#define MMC_EXT_CSD_PWR_CL_26_INDEX 201 -#define MMC_EXT_CSD_PWR_CL_52_INDEX 200 -#define MMC_EXT_CSD_PWR_CL_DDR_52_INDEX 238 - -#define MMC_EXT_CSD_PWR_CL_26_POS 8 -#define MMC_EXT_CSD_PWR_CL_52_POS 0 -#define MMC_EXT_CSD_PWR_CL_DDR_52_POS 16 -#else -#define MMC_VOLTAGE_RANGE EMMC_HIGH_VOLTAGE_RANGE - -#define MMC_EXT_CSD_PWR_CL_26_INDEX 203 -#define MMC_EXT_CSD_PWR_CL_52_INDEX 202 -#define MMC_EXT_CSD_PWR_CL_DDR_52_INDEX 239 - -#define MMC_EXT_CSD_PWR_CL_26_POS 24 -#define MMC_EXT_CSD_PWR_CL_52_POS 16 -#define MMC_EXT_CSD_PWR_CL_DDR_52_POS 24 -#endif /* (VDD_VALUE) && (VDD_VALUE <= 1950U)*/ - -#define MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_INDEX 216 -#define MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_POS 0 -#define MMC_EXT_CSD_S_A_TIMEOUT_INDEX 217 -#define MMC_EXT_CSD_S_A_TIMEOUT_POS 8 - -/* Frequencies used in the driver for clock divider calculation */ -#define MMC_INIT_FREQ 400000U /* Initialization phase : 400 kHz max */ -#define MMC_HIGH_SPEED_FREQ 52000000U /* High speed phase : 52 MHz max */ - -/* The Data elements' postitions in the frame Frame for RPMB area */ -#define MMC_RPMB_KEYMAC_POSITION 196U -#define MMC_RPMB_DATA_POSITION 228U -#define MMC_RPMB_NONCE_POSITION 484U -#define MMC_RPMB_WRITE_COUNTER_POSITION 500U -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup MMC_Private_Functions MMC Private Functions - * @{ - */ -static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc); -static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc); -static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus); -static void MMC_PowerOFF(MMC_HandleTypeDef *hmmc); -static void MMC_Write_IT(MMC_HandleTypeDef *hmmc); -static void MMC_Read_IT(MMC_HandleTypeDef *hmmc); -static uint32_t MMC_HighSpeed(MMC_HandleTypeDef *hmmc, FunctionalState state); -static uint32_t MMC_DDR_Mode(MMC_HandleTypeDef *hmmc, FunctionalState state); -static HAL_StatusTypeDef MMC_ReadExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pFieldData, uint16_t FieldIndex, - uint32_t Timeout); -static uint32_t MMC_PwrClassUpdate(MMC_HandleTypeDef *hmmc, uint32_t Wide, uint32_t Speed); - -/** - * @} - */ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup MMC_Exported_Functions - * @{ - */ - -/** @addtogroup MMC_Exported_Functions_Group1 - * @brief Initialization and de-initialization functions - * -@verbatim - ============================================================================== - ##### Initialization and de-initialization functions ##### - ============================================================================== - [..] - This section provides functions allowing to initialize/de-initialize the MMC - card device to be ready for use. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the MMC according to the specified parameters in the - MMC_HandleTypeDef and create the associated handle. - * @param hmmc Pointer to the MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Init(MMC_HandleTypeDef *hmmc) -{ - /* Check the MMC handle allocation */ - if (hmmc == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDMMC_ALL_INSTANCE(hmmc->Instance)); - assert_param(IS_SDMMC_CLOCK_EDGE(hmmc->Init.ClockEdge)); - assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hmmc->Init.ClockPowerSave)); - assert_param(IS_SDMMC_BUS_WIDE(hmmc->Init.BusWide)); - assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hmmc->Init.HardwareFlowControl)); - assert_param(IS_SDMMC_CLKDIV(hmmc->Init.ClockDiv)); - - if (hmmc->State == HAL_MMC_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hmmc->Lock = HAL_UNLOCKED; -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - /* Reset Callback pointers in HAL_MMC_STATE_RESET only */ - hmmc->TxCpltCallback = HAL_MMC_TxCpltCallback; - hmmc->RxCpltCallback = HAL_MMC_RxCpltCallback; - hmmc->ErrorCallback = HAL_MMC_ErrorCallback; - hmmc->AbortCpltCallback = HAL_MMC_AbortCallback; - hmmc->Read_DMALnkLstBufCpltCallback = HAL_MMCEx_Read_DMALnkLstBufCpltCallback; - hmmc->Write_DMALnkLstBufCpltCallback = HAL_MMCEx_Write_DMALnkLstBufCpltCallback; - - if (hmmc->MspInitCallback == NULL) - { - hmmc->MspInitCallback = HAL_MMC_MspInit; - } - - /* Init the low level hardware */ - hmmc->MspInitCallback(hmmc); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_MMC_MspInit(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize the Card parameters */ - if (HAL_MMC_InitCard(hmmc) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* Initialize the error code */ - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - /* Initialize the MMC operation */ - hmmc->Context = MMC_CONTEXT_NONE; - - /* Initialize the MMC state */ - hmmc->State = HAL_MMC_STATE_READY; - - /* Configure bus width */ - if (hmmc->Init.BusWide != SDMMC_BUS_WIDE_1B) - { - if (HAL_MMC_ConfigWideBusOperation(hmmc, hmmc->Init.BusWide) != HAL_OK) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Initializes the MMC Card. - * @param hmmc Pointer to MMC handle - * @note This function initializes the MMC card. It could be used when a card - re-initialization is needed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_InitCard(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate; - MMC_InitTypeDef Init; - uint32_t sdmmc_clk; - - /* Default SDMMC peripheral configuration for MMC card initialization */ - Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; - Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; - Init.BusWide = SDMMC_BUS_WIDE_1B; - Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE; - - /* Init Clock should be less or equal to 400Khz*/ - sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); - if (sdmmc_clk == 0U) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER; - return HAL_ERROR; - } - Init.ClockDiv = sdmmc_clk / (2U * MMC_INIT_FREQ); - -#if (USE_SD_TRANSCEIVER != 0U) - Init.TranceiverPresent = SDMMC_TRANSCEIVER_NOT_PRESENT; -#endif /* USE_SD_TRANSCEIVER */ - - /* Initialize SDMMC peripheral interface with default configuration */ - (void)SDMMC_Init(hmmc->Instance, Init); - - /* Set Power State to ON */ - (void)SDMMC_PowerState_ON(hmmc->Instance); - - /* wait 74 Cycles: required power up waiting time before starting - the MMC initialization sequence */ - if (Init.ClockDiv != 0U) - { - sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv); - } - - if (sdmmc_clk != 0U) - { - HAL_Delay(1U + (74U * 1000U / (sdmmc_clk))); - } - - /* Identify card operating voltage */ - errorstate = MMC_PowerON(hmmc); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - /* Card initialization */ - errorstate = MMC_InitCard(hmmc); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, MMC_BLOCKSIZE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief De-Initializes the MMC card. - * @param hmmc Pointer to MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_DeInit(MMC_HandleTypeDef *hmmc) -{ - /* Check the MMC handle allocation */ - if (hmmc == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDMMC_ALL_INSTANCE(hmmc->Instance)); - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Set MMC power state to off */ - MMC_PowerOFF(hmmc); - -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - if (hmmc->MspDeInitCallback == NULL) - { - hmmc->MspDeInitCallback = HAL_MMC_MspDeInit; - } - - /* DeInit the low level hardware */ - hmmc->MspDeInitCallback(hmmc); -#else - /* De-Initialize the MSP layer */ - HAL_MMC_MspDeInit(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_RESET; - - return HAL_OK; -} - -/** - * @brief Initializes the MMC MSP. - * @param hmmc Pointer to MMC handle - * @retval None - */ -__weak void HAL_MMC_MspInit(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_MMC_MspInit could be implemented in the user file - */ -} - -/** - * @brief De-Initialize MMC MSP. - * @param hmmc Pointer to MMC handle - * @retval None - */ -__weak void HAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_MMC_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @addtogroup MMC_Exported_Functions_Group2 - * @brief Data transfer functions - * -@verbatim - ============================================================================== - ##### IO operation functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to manage the data - transfer from/to MMC card. - -@endverbatim - * @{ - */ - -/** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc Pointer to MMC handle - * @param pData pointer to the buffer that will contain the received data - * @param BlockAdd Block Address from where data is to be read - * @param NumberOfBlocks Number of MMC blocks to read - * @param Timeout Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks, - uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t data; - uint32_t dataremaining; - uint32_t add = BlockAdd; - uint8_t *tempbuff = pData; - - if (NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) - & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= MMC_BLOCKSIZE; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Read block(s) in polling mode */ - if (NumberOfBlocks > 1U) - { - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); - } - else - { - hmmc->Context = MMC_CONTEXT_READ_SINGLE_BLOCK; - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); - } - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Poll on SDMMC flags */ - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Send stop transmission command in case of multiblock read */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - } - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Allows to write block(s) to a specified address in a card. The Data - * transfer is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc Pointer to MMC handle - * @param pData pointer to the buffer that will contain the data to transmit - * @param BlockAdd Block Address where data will be written - * @param NumberOfBlocks Number of MMC blocks to write - * @param Timeout Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, const uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks, uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t data; - uint32_t dataremaining; - uint32_t add = BlockAdd; - const uint8_t *tempbuff = pData; - - if (NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= MMC_BLOCKSIZE; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - if (NumberOfBlocks > 1U) - { - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); - } - else - { - hmmc->Context = MMC_CONTEXT_WRITE_SINGLE_BLOCK; - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); - } - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write block(s) in polling mode */ - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*tempbuff); - tempbuff++; - data |= ((uint32_t)(*tempbuff) << 8U); - tempbuff++; - data |= ((uint32_t)(*tempbuff) << 16U); - tempbuff++; - data |= ((uint32_t)(*tempbuff) << 24U); - tempbuff++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Send stop transmission command in case of multiblock write */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - } - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the IT transfer process through the MMC Rx - * interrupt event. - * @param hmmc Pointer to MMC handle - * @param pData Pointer to the buffer that will contain the received data - * @param BlockAdd Block Address from where data is to be read - * @param NumberOfBlocks Number of blocks to read. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - hmmc->pRxBuffPtr = pData; - hmmc->RxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= MMC_BLOCKSIZE; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Read Blocks in IT mode */ - if (NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_IT); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); - } - else - { - hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_IT); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); - } - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | - SDMMC_FLAG_RXFIFOHF)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Writes block(s) to a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the IT transfer process through the MMC Tx - * interrupt event. - * @param hmmc Pointer to MMC handle - * @param pData Pointer to the buffer that will contain the data to transmit - * @param BlockAdd Block Address where data will be written - * @param NumberOfBlocks Number of blocks to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, const uint8_t *pData, - uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - hmmc->pTxBuffPtr = pData; - hmmc->TxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= MMC_BLOCKSIZE; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - if (NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_IT); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); - } - else - { - hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_IT); - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); - } - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Enable transfer interrupts */ - __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | - SDMMC_FLAG_TXFIFOHE)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @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 a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the DMA transfer process through the MMC Rx - * interrupt event. - * @param hmmc Pointer MMC handle - * @param pData Pointer to the buffer that will contain the received data - * @param BlockAdd Block Address from where data is to be read - * @param NumberOfBlocks Number of blocks to read. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - hmmc->pRxBuffPtr = pData; - hmmc->RxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= MMC_BLOCKSIZE; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - hmmc->Instance->IDMABASER = (uint32_t) pData ; - hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; - - /* Read Blocks in DMA mode */ - if (NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); - } - else - { - hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_DMA); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); - } - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode = errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Enable transfer interrupts */ - __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @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 a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the DMA transfer process through the MMC Tx - * interrupt event. - * @param hmmc Pointer to MMC handle - * @param pData Pointer to the buffer that will contain the data to transmit - * @param BlockAdd Block Address where data will be written - * @param NumberOfBlocks Number of blocks to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, const uint8_t *pData, - uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - hmmc->pTxBuffPtr = pData; - hmmc->TxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= MMC_BLOCKSIZE; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - hmmc->Instance->IDMABASER = (uint32_t) pData ; - hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; - - /* Write Blocks in Polling mode */ - if (NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); - } - else - { - hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_DMA); - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); - } - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Enable transfer interrupts */ - __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Erases the specified memory area of the given MMC card. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc Pointer to MMC handle - * @param BlockStartAdd: Start Block address - * @param BlockEndAdd: End Block address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd) -{ - uint32_t errorstate; - uint32_t start_add = BlockStartAdd; - uint32_t end_add = BlockEndAdd; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - if (end_add < start_add) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (end_add > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) - & 0x000000FFU) != 0x0U) - { - if (((start_add % 8U) != 0U) || ((end_add % 8U) != 0U)) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Check if the card command class supports erase command */ - if (((hmmc->MmcCard.Class) & SDMMC_CCCC_ERASE) == 0U) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - if ((SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_LOCK_UNLOCK_FAILED; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - start_add *= MMC_BLOCKSIZE; - end_add *= MMC_BLOCKSIZE; - } - - /* Send CMD35 MMC_ERASE_GRP_START with argument as addr */ - errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, start_add); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send CMD36 MMC_ERASE_GRP_END with argument as addr */ - errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, end_add); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send CMD38 ERASE */ - errorstate = SDMMC_CmdErase(hmmc->Instance, 0UL); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief This function handles MMC card interrupt request. - * @param hmmc Pointer to MMC handle - * @retval None - */ -void HAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate; - uint32_t context = hmmc->Context; - - /* Check for SDMMC interrupt flags */ - if ((__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) != RESET) && ((context & MMC_CONTEXT_IT) != 0U)) - { - MMC_Read_IT(hmmc); - } - - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) != RESET) - { - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_DATAEND); - - __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR | SDMMC_IT_TXFIFOHE | \ - SDMMC_IT_RXFIFOHF); - - __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_IDMABTC); - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - if ((context & MMC_CONTEXT_DMA) != 0U) - { - hmmc->Instance->DLEN = 0; - hmmc->Instance->DCTRL = 0; - hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA ; - - /* Stop Transfer for Write Multi blocks or Read Multi blocks */ - if (((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) - { - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->ErrorCallback(hmmc); -#else - HAL_MMC_ErrorCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - if (((context & MMC_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->TxCpltCallback(hmmc); -#else - HAL_MMC_TxCpltCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - if (((context & MMC_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->RxCpltCallback(hmmc); -#else - HAL_MMC_RxCpltCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - } - else if ((context & MMC_CONTEXT_IT) != 0U) - { - /* Stop Transfer for Write Multi blocks or Read Multi blocks */ - if (((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) - { - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->ErrorCallback(hmmc); -#else - HAL_MMC_ErrorCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - if (((context & MMC_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->RxCpltCallback(hmmc); -#else - HAL_MMC_RxCpltCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - else - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->TxCpltCallback(hmmc); -#else - HAL_MMC_TxCpltCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } - } - - else if ((__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) != RESET) && ((context & MMC_CONTEXT_IT) != 0U)) - { - MMC_Write_IT(hmmc); - } - - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL | - SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR | SDMMC_FLAG_TXUNDERR) != RESET) - { - /* Set Error code */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DCRCFAIL) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - } - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DTIMEOUT) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - } - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_RXOVERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - } - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_TXUNDERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - } - - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - /* Disable all interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); - - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - hmmc->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; - hmmc->Instance->CMD |= SDMMC_CMD_CMDSTOP; - hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); - hmmc->Instance->CMD &= ~(SDMMC_CMD_CMDSTOP); - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_DABORT); - - if ((context & MMC_CONTEXT_IT) != 0U) - { - /* Set the MMC state to ready to be able to start again the process */ - hmmc->State = HAL_MMC_STATE_READY; -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->ErrorCallback(hmmc); -#else - HAL_MMC_ErrorCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - else if ((context & MMC_CONTEXT_DMA) != 0U) - { - if (hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - /* Disable Internal DMA */ - __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_IDMABTC); - hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - /* Set the MMC state to ready to be able to start again the process */ - hmmc->State = HAL_MMC_STATE_READY; -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->ErrorCallback(hmmc); -#else - HAL_MMC_ErrorCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } - } - - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_IDMABTC) != RESET) - { - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_IT_IDMABTC); - - if ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U) - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->Write_DMALnkLstBufCpltCallback(hmmc); -#else - HAL_MMCEx_Write_DMALnkLstBufCpltCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - else /* MMC_CONTEXT_READ_MULTIPLE_BLOCK */ - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->Read_DMALnkLstBufCpltCallback(hmmc); -#else - HAL_MMCEx_Read_DMALnkLstBufCpltCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - } - - else - { - /* Nothing to do */ - } -} - -/** - * @brief return the MMC state - * @param hmmc Pointer to mmc handle - * @retval HAL state - */ -HAL_MMC_StateTypeDef HAL_MMC_GetState(const MMC_HandleTypeDef *hmmc) -{ - return hmmc->State; -} - -/** - * @brief Return the MMC error code - * @param hmmc : Pointer to a MMC_HandleTypeDef structure that contains - * the configuration information. - * @retval MMC Error Code - */ -uint32_t HAL_MMC_GetError(const MMC_HandleTypeDef *hmmc) -{ - return hmmc->ErrorCode; -} - -/** - * @brief Tx Transfer completed callbacks - * @param hmmc Pointer to MMC handle - * @retval None - */ -__weak void HAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_TxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hmmc Pointer MMC handle - * @retval None - */ -__weak void HAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_RxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief MMC error callbacks - * @param hmmc Pointer MMC handle - * @retval None - */ -__weak void HAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_ErrorCallback can be implemented in the user file - */ -} - -/** - * @brief MMC Abort callbacks - * @param hmmc Pointer MMC handle - * @retval None - */ -__weak void HAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_AbortCallback can be implemented in the user file - */ -} - -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a User MMC Callback - * To be used instead of the weak (overridden) predefined callback - * @note The HAL_MMC_RegisterCallback() may be called before HAL_MMC_Init() in - * HAL_MMC_STATE_RESET to register callbacks for HAL_MMC_MSP_INIT_CB_ID - * and HAL_MMC_MSP_DEINIT_CB_ID. - * @param hmmc : MMC handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_MMC_TX_CPLT_CB_ID MMC Tx Complete Callback ID - * @arg @ref HAL_MMC_RX_CPLT_CB_ID MMC Rx Complete Callback ID - * @arg @ref HAL_MMC_ERROR_CB_ID MMC Error Callback ID - * @arg @ref HAL_MMC_ABORT_CB_ID MMC Abort Callback ID - * @arg @ref HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Rx Linked List Node buffer Callback ID - * @arg @ref HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Tx Linked List Node buffer Callback ID - * @arg @ref HAL_MMC_MSP_INIT_CB_ID MMC MspInit Callback ID - * @arg @ref HAL_MMC_MSP_DEINIT_CB_ID MMC MspDeInit Callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_MMC_RegisterCallback(MMC_HandleTypeDef *hmmc, HAL_MMC_CallbackIDTypeDef CallbackId, - pMMC_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - switch (CallbackId) - { - case HAL_MMC_TX_CPLT_CB_ID : - hmmc->TxCpltCallback = pCallback; - break; - case HAL_MMC_RX_CPLT_CB_ID : - hmmc->RxCpltCallback = pCallback; - break; - case HAL_MMC_ERROR_CB_ID : - hmmc->ErrorCallback = pCallback; - break; - case HAL_MMC_ABORT_CB_ID : - hmmc->AbortCpltCallback = pCallback; - break; - case HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID : - hmmc->Read_DMALnkLstBufCpltCallback = pCallback; - break; - case HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : - hmmc->Write_DMALnkLstBufCpltCallback = pCallback; - break; - case HAL_MMC_MSP_INIT_CB_ID : - hmmc->MspInitCallback = pCallback; - break; - case HAL_MMC_MSP_DEINIT_CB_ID : - hmmc->MspDeInitCallback = pCallback; - break; - default : - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hmmc->State == HAL_MMC_STATE_RESET) - { - switch (CallbackId) - { - case HAL_MMC_MSP_INIT_CB_ID : - hmmc->MspInitCallback = pCallback; - break; - case HAL_MMC_MSP_DEINIT_CB_ID : - hmmc->MspDeInitCallback = pCallback; - break; - default : - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User MMC Callback - * MMC Callback is redirected to the weak (overridden) predefined callback - * @note The HAL_MMC_UnRegisterCallback() may be called before HAL_MMC_Init() in - * HAL_MMC_STATE_RESET to register callbacks for HAL_MMC_MSP_INIT_CB_ID - * and HAL_MMC_MSP_DEINIT_CB_ID. - * @param hmmc : MMC handle - * @param CallbackId : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_MMC_TX_CPLT_CB_ID MMC Tx Complete Callback ID - * @arg @ref HAL_MMC_RX_CPLT_CB_ID MMC Rx Complete Callback ID - * @arg @ref HAL_MMC_ERROR_CB_ID MMC Error Callback ID - * @arg @ref HAL_MMC_ABORT_CB_ID MMC Abort Callback ID - * @arg @ref HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Rx Linked List Node buffer Callback ID - * @arg @ref HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Tx Linked List Node buffer Callback ID - * @arg @ref HAL_MMC_MSP_INIT_CB_ID MMC MspInit Callback ID - * @arg @ref HAL_MMC_MSP_DEINIT_CB_ID MMC MspDeInit Callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_MMC_UnRegisterCallback(MMC_HandleTypeDef *hmmc, HAL_MMC_CallbackIDTypeDef CallbackId) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - switch (CallbackId) - { - case HAL_MMC_TX_CPLT_CB_ID : - hmmc->TxCpltCallback = HAL_MMC_TxCpltCallback; - break; - case HAL_MMC_RX_CPLT_CB_ID : - hmmc->RxCpltCallback = HAL_MMC_RxCpltCallback; - break; - case HAL_MMC_ERROR_CB_ID : - hmmc->ErrorCallback = HAL_MMC_ErrorCallback; - break; - case HAL_MMC_ABORT_CB_ID : - hmmc->AbortCpltCallback = HAL_MMC_AbortCallback; - break; - case HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID : - hmmc->Read_DMALnkLstBufCpltCallback = HAL_MMCEx_Read_DMALnkLstBufCpltCallback; - break; - case HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : - hmmc->Write_DMALnkLstBufCpltCallback = HAL_MMCEx_Write_DMALnkLstBufCpltCallback; - break; - case HAL_MMC_MSP_INIT_CB_ID : - hmmc->MspInitCallback = HAL_MMC_MspInit; - break; - case HAL_MMC_MSP_DEINIT_CB_ID : - hmmc->MspDeInitCallback = HAL_MMC_MspDeInit; - break; - default : - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hmmc->State == HAL_MMC_STATE_RESET) - { - switch (CallbackId) - { - case HAL_MMC_MSP_INIT_CB_ID : - hmmc->MspInitCallback = HAL_MMC_MspInit; - break; - case HAL_MMC_MSP_DEINIT_CB_ID : - hmmc->MspDeInitCallback = HAL_MMC_MspDeInit; - break; - default : - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @addtogroup MMC_Exported_Functions_Group3 - * @brief management functions - * -@verbatim - ============================================================================== - ##### Peripheral Control functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to control the MMC card - operations and get the related information - -@endverbatim - * @{ - */ - -/** - * @brief Returns information the information of the card which are stored on - * the CID register. - * @param hmmc Pointer to MMC handle - * @param pCID: Pointer to a HAL_MMC_CIDTypedef structure that - * contains all CID register parameters - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCIDTypeDef *pCID) -{ - pCID->ManufacturerID = (uint8_t)((hmmc->CID[0] & 0xFF000000U) >> 24U); - - pCID->OEM_AppliID = (uint16_t)((hmmc->CID[0] & 0x00FFFF00U) >> 8U); - - pCID->ProdName1 = (((hmmc->CID[0] & 0x000000FFU) << 24U) | ((hmmc->CID[1] & 0xFFFFFF00U) >> 8U)); - - pCID->ProdName2 = (uint8_t)(hmmc->CID[1] & 0x000000FFU); - - pCID->ProdRev = (uint8_t)((hmmc->CID[2] & 0xFF000000U) >> 24U); - - pCID->ProdSN = (((hmmc->CID[2] & 0x00FFFFFFU) << 8U) | ((hmmc->CID[3] & 0xFF000000U) >> 24U)); - - pCID->Reserved1 = (uint8_t)((hmmc->CID[3] & 0x00F00000U) >> 20U); - - pCID->ManufactDate = (uint16_t)((hmmc->CID[3] & 0x000FFF00U) >> 8U); - - pCID->CID_CRC = (uint8_t)((hmmc->CID[3] & 0x000000FEU) >> 1U); - - pCID->Reserved2 = 1U; - - return HAL_OK; -} - -/** - * @brief Returns information the information of the card which are stored on - * the CSD register. - * @param hmmc Pointer to MMC handle - * @param pCSD: Pointer to a HAL_MMC_CardCSDTypeDef structure that - * contains all CSD register parameters - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCSDTypeDef *pCSD) -{ - uint32_t block_nbr = 0; - - pCSD->CSDStruct = (uint8_t)((hmmc->CSD[0] & 0xC0000000U) >> 30U); - - pCSD->SysSpecVersion = (uint8_t)((hmmc->CSD[0] & 0x3C000000U) >> 26U); - - pCSD->Reserved1 = (uint8_t)((hmmc->CSD[0] & 0x03000000U) >> 24U); - - pCSD->TAAC = (uint8_t)((hmmc->CSD[0] & 0x00FF0000U) >> 16U); - - pCSD->NSAC = (uint8_t)((hmmc->CSD[0] & 0x0000FF00U) >> 8U); - - pCSD->MaxBusClkFrec = (uint8_t)(hmmc->CSD[0] & 0x000000FFU); - - pCSD->CardComdClasses = (uint16_t)((hmmc->CSD[1] & 0xFFF00000U) >> 20U); - - pCSD->RdBlockLen = (uint8_t)((hmmc->CSD[1] & 0x000F0000U) >> 16U); - - pCSD->PartBlockRead = (uint8_t)((hmmc->CSD[1] & 0x00008000U) >> 15U); - - pCSD->WrBlockMisalign = (uint8_t)((hmmc->CSD[1] & 0x00004000U) >> 14U); - - pCSD->RdBlockMisalign = (uint8_t)((hmmc->CSD[1] & 0x00002000U) >> 13U); - - pCSD->DSRImpl = (uint8_t)((hmmc->CSD[1] & 0x00001000U) >> 12U); - - pCSD->Reserved2 = 0U; /*!< Reserved */ - - if (MMC_ReadExtCSD(hmmc, &block_nbr, 212, 0x0FFFFFFFU) != HAL_OK) /* Field SEC_COUNT [215:212] */ - { - return HAL_ERROR; - } - - if (hmmc->MmcCard.CardType == MMC_LOW_CAPACITY_CARD) - { - pCSD->DeviceSize = (((hmmc->CSD[1] & 0x000003FFU) << 2U) | ((hmmc->CSD[2] & 0xC0000000U) >> 30U)); - - pCSD->MaxRdCurrentVDDMin = (uint8_t)((hmmc->CSD[2] & 0x38000000U) >> 27U); - - pCSD->MaxRdCurrentVDDMax = (uint8_t)((hmmc->CSD[2] & 0x07000000U) >> 24U); - - pCSD->MaxWrCurrentVDDMin = (uint8_t)((hmmc->CSD[2] & 0x00E00000U) >> 21U); - - pCSD->MaxWrCurrentVDDMax = (uint8_t)((hmmc->CSD[2] & 0x001C0000U) >> 18U); - - pCSD->DeviceSizeMul = (uint8_t)((hmmc->CSD[2] & 0x00038000U) >> 15U); - - hmmc->MmcCard.BlockNbr = (pCSD->DeviceSize + 1U) ; - hmmc->MmcCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U)); - hmmc->MmcCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU)); - - hmmc->MmcCard.LogBlockNbr = (hmmc->MmcCard.BlockNbr) * ((hmmc->MmcCard.BlockSize) / MMC_BLOCKSIZE); - hmmc->MmcCard.LogBlockSize = MMC_BLOCKSIZE; - } - else if (hmmc->MmcCard.CardType == MMC_HIGH_CAPACITY_CARD) - { - hmmc->MmcCard.BlockNbr = block_nbr; - hmmc->MmcCard.LogBlockNbr = hmmc->MmcCard.BlockNbr; - hmmc->MmcCard.BlockSize = MMC_BLOCKSIZE; - hmmc->MmcCard.LogBlockSize = hmmc->MmcCard.BlockSize; - } - else - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_UNSUPPORTED_FEATURE; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - pCSD->EraseGrSize = (uint8_t)((hmmc->CSD[2] & 0x00004000U) >> 14U); - - pCSD->EraseGrMul = (uint8_t)((hmmc->CSD[2] & 0x00003F80U) >> 7U); - - pCSD->WrProtectGrSize = (uint8_t)(hmmc->CSD[2] & 0x0000007FU); - - pCSD->WrProtectGrEnable = (uint8_t)((hmmc->CSD[3] & 0x80000000U) >> 31U); - - pCSD->ManDeflECC = (uint8_t)((hmmc->CSD[3] & 0x60000000U) >> 29U); - - pCSD->WrSpeedFact = (uint8_t)((hmmc->CSD[3] & 0x1C000000U) >> 26U); - - pCSD->MaxWrBlockLen = (uint8_t)((hmmc->CSD[3] & 0x03C00000U) >> 22U); - - pCSD->WriteBlockPaPartial = (uint8_t)((hmmc->CSD[3] & 0x00200000U) >> 21U); - - pCSD->Reserved3 = 0; - - pCSD->ContentProtectAppli = (uint8_t)((hmmc->CSD[3] & 0x00010000U) >> 16U); - - pCSD->FileFormatGroup = (uint8_t)((hmmc->CSD[3] & 0x00008000U) >> 15U); - - pCSD->CopyFlag = (uint8_t)((hmmc->CSD[3] & 0x00004000U) >> 14U); - - pCSD->PermWrProtect = (uint8_t)((hmmc->CSD[3] & 0x00002000U) >> 13U); - - pCSD->TempWrProtect = (uint8_t)((hmmc->CSD[3] & 0x00001000U) >> 12U); - - pCSD->FileFormat = (uint8_t)((hmmc->CSD[3] & 0x00000C00U) >> 10U); - - pCSD->ECC = (uint8_t)((hmmc->CSD[3] & 0x00000300U) >> 8U); - - pCSD->CSD_CRC = (uint8_t)((hmmc->CSD[3] & 0x000000FEU) >> 1U); - - pCSD->Reserved4 = 1; - - return HAL_OK; -} - -/** - * @brief Gets the MMC card info. - * @param hmmc Pointer to MMC handle - * @param pCardInfo: Pointer to the HAL_MMC_CardInfoTypeDef structure that - * will contain the MMC card status information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, HAL_MMC_CardInfoTypeDef *pCardInfo) -{ - pCardInfo->CardType = (uint32_t)(hmmc->MmcCard.CardType); - pCardInfo->Class = (uint32_t)(hmmc->MmcCard.Class); - pCardInfo->RelCardAdd = (uint32_t)(hmmc->MmcCard.RelCardAdd); - pCardInfo->BlockNbr = (uint32_t)(hmmc->MmcCard.BlockNbr); - pCardInfo->BlockSize = (uint32_t)(hmmc->MmcCard.BlockSize); - pCardInfo->LogBlockNbr = (uint32_t)(hmmc->MmcCard.LogBlockNbr); - pCardInfo->LogBlockSize = (uint32_t)(hmmc->MmcCard.LogBlockSize); - - return HAL_OK; -} - -/** - * @brief Returns information the information of the card which are stored on - * the Extended CSD register. - * @param hmmc Pointer to MMC handle - * @param pExtCSD Pointer to a memory area (512 bytes) that contains all - * Extended CSD register parameters - * @param Timeout Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pExtCSD, uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t *tmp_buf; - - if (NULL == pExtCSD) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0; - - /* Initiaize the destination pointer */ - tmp_buf = pExtCSD; - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Send ExtCSD Read command to Card */ - errorstate = SDMMC_CmdSendEXTCSD(hmmc->Instance, 0); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Poll on SDMMC flags */ - while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR | - SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - *tmp_buf = SDMMC_ReadFIFO(hmmc->Instance); - tmp_buf++; - } - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - hmmc->State = HAL_MMC_STATE_READY; - } - - return HAL_OK; -} - -/** - * @brief Enables wide bus operation for the requested card if supported by - * card. - * @param hmmc Pointer to MMC handle - * @param WideMode: Specifies the MMC card wide bus mode - * This parameter can be one of the following values: - * @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer - * @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer - * @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode) -{ - uint32_t count; - SDMMC_InitTypeDef Init; - uint32_t errorstate; - uint32_t response = 0U; - - /* Check the parameters */ - assert_param(IS_SDMMC_BUS_WIDE(WideMode)); - - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Check and update the power class if needed */ - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) != 0U) - { - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) != 0U) - { - errorstate = MMC_PwrClassUpdate(hmmc, WideMode, SDMMC_SPEED_MODE_DDR); - } - else - { - errorstate = MMC_PwrClassUpdate(hmmc, WideMode, SDMMC_SPEED_MODE_HIGH); - } - } - else - { - errorstate = MMC_PwrClassUpdate(hmmc, WideMode, SDMMC_SPEED_MODE_DEFAULT); - } - - if (errorstate == HAL_MMC_ERROR_NONE) - { - if (WideMode == SDMMC_BUS_WIDE_8B) - { - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200U); - } - else if (WideMode == SDMMC_BUS_WIDE_4B) - { - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100U); - } - else if (WideMode == SDMMC_BUS_WIDE_1B) - { - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70000U); - } - else - { - /* WideMode is not a valid argument*/ - errorstate = HAL_MMC_ERROR_PARAM; - } - - /* Check for switch error and violation of the trial number of sending CMD 13 */ - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } - else - { - /* Configure the SDMMC peripheral */ - Init = hmmc->Init; - Init.BusWide = WideMode; - (void)SDMMC_Init(hmmc->Instance, Init); - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Configure the speed bus mode - * @param hmmc Pointer to the MMC handle - * @param SpeedMode: Specifies the MMC card speed bus mode - * This parameter can be one of the following values: - * @arg SDMMC_SPEED_MODE_AUTO: Max speed mode supported by the card - * @arg SDMMC_SPEED_MODE_DEFAULT: Default Speed (MMC @ 26MHz) - * @arg SDMMC_SPEED_MODE_HIGH: High Speed (MMC @ 52 MHz) - * @arg SDMMC_SPEED_MODE_DDR: High Speed DDR (MMC DDR @ 52 MHz) - * @retval HAL status - */ - -HAL_StatusTypeDef HAL_MMC_ConfigSpeedBusOperation(MMC_HandleTypeDef *hmmc, uint32_t SpeedMode) -{ - uint32_t tickstart; - HAL_StatusTypeDef status = HAL_OK; - uint32_t device_type; - uint32_t errorstate; - - /* Check the parameters */ - assert_param(IS_SDMMC_SPEED_MODE(SpeedMode)); - - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Field DEVICE_TYPE [196 = 49*4] of Extended CSD register */ - device_type = (hmmc->Ext_CSD[49] & 0x000000FFU); - - switch (SpeedMode) - { - case SDMMC_SPEED_MODE_AUTO: - { - if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS) != 0U) && ((device_type & 0x04U) != 0U)) - { - /* High Speed DDR mode allowed */ - errorstate = MMC_HighSpeed(hmmc, ENABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - else - { - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_CLKDIV) != 0U) - { - /* DDR mode not supported with CLKDIV = 0 */ - errorstate = MMC_DDR_Mode(hmmc, ENABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - } - } - else if ((device_type & 0x02U) != 0U) - { - /* High Speed mode allowed */ - errorstate = MMC_HighSpeed(hmmc, ENABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - else - { - /* Nothing to do : keep current speed */ - } - break; - } - case SDMMC_SPEED_MODE_DDR: - { - if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS) != 0U) && ((device_type & 0x04U) != 0U)) - { - /* High Speed DDR mode allowed */ - errorstate = MMC_HighSpeed(hmmc, ENABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - else - { - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_CLKDIV) != 0U) - { - /* DDR mode not supported with CLKDIV = 0 */ - errorstate = MMC_DDR_Mode(hmmc, ENABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - } - } - else - { - /* High Speed DDR mode not allowed */ - hmmc->ErrorCode |= HAL_MMC_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_HIGH: - { - if ((device_type & 0x02U) != 0U) - { - /* High Speed mode allowed */ - errorstate = MMC_HighSpeed(hmmc, ENABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - else - { - /* High Speed mode not allowed */ - hmmc->ErrorCode |= HAL_MMC_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_DEFAULT: - { - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) != 0U) - { - /* High Speed DDR mode activated */ - errorstate = MMC_DDR_Mode(hmmc, DISABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) != 0U) - { - /* High Speed mode activated */ - errorstate = MMC_HighSpeed(hmmc, DISABLE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - break; - } - default: - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - status = HAL_ERROR; - break; - } - - /* Verify that MMC card is ready to use after Speed mode switch*/ - tickstart = HAL_GetTick(); - while ((HAL_MMC_GetCardState(hmmc) != HAL_MMC_CARD_TRANSFER)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - return status; -} - -/** - * @brief Gets the current mmc card data state. - * @param hmmc pointer to MMC handle - * @retval Card state - */ -HAL_MMC_CardStateTypeDef HAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc) -{ - uint32_t cardstate; - uint32_t errorstate; - uint32_t resp1 = 0U; - - errorstate = MMC_SendStatus(hmmc, &resp1); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - - cardstate = ((resp1 >> 9U) & 0x0FU); - - return (HAL_MMC_CardStateTypeDef)cardstate; -} - -/** - * @brief Abort the current transfer and disable the MMC. - * @param hmmc pointer to a MMC_HandleTypeDef structure that contains - * the configuration information for MMC module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Abort(MMC_HandleTypeDef *hmmc) -{ - uint32_t error_code; - uint32_t tickstart; - - if (hmmc->State == HAL_MMC_STATE_BUSY) - { - /* DIsable All interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /*we will send the CMD12 in all cases in order to stop the data transfers*/ - /*In case the data transfer just finished, the external memory will not respond - and will return HAL_MMC_ERROR_CMD_RSP_TIMEOUT*/ - /*In case the data transfer aborted , the external memory will respond and will return HAL_MMC_ERROR_NONE*/ - /*Other scenario will return HAL_ERROR*/ - - hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); - error_code = hmmc->ErrorCode; - if ((error_code != HAL_MMC_ERROR_NONE) && (error_code != HAL_MMC_ERROR_CMD_RSP_TIMEOUT)) - { - return HAL_ERROR; - } - - tickstart = HAL_GetTick(); - if ((hmmc->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_CARD) - { - if (hmmc->ErrorCode == HAL_MMC_ERROR_NONE) - { - while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DABORT | SDMMC_FLAG_BUSYD0END)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - } - - if (hmmc->ErrorCode == HAL_MMC_ERROR_CMD_RSP_TIMEOUT) - { - while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - else if ((hmmc->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_SDMMC) - { - while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DABORT | SDMMC_FLAG_DATAEND)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - } - else - { - /* Nothing to do*/ - } - - /*The reason of all these while conditions previously is that we need to wait the SDMMC and clear - the appropriate flags that will be set depending of the abort/non abort of the memory */ - /*Not waiting the SDMMC flags will cause the next SDMMC_DISABLE_IDMA to not get cleared and will result - in next SDMMC read/write operation to fail */ - - /*SDMMC ready for clear data flags*/ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - /* If IDMA Context, disable Internal DMA */ - hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - hmmc->State = HAL_MMC_STATE_READY; - - /* Initialize the MMC operation */ - hmmc->Context = MMC_CONTEXT_NONE; - } - return HAL_OK; -} -/** - * @brief Abort the current transfer and disable the MMC (IT mode). - * @param hmmc pointer to a MMC_HandleTypeDef structure that contains - * the configuration information for MMC module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc) -{ - HAL_MMC_CardStateTypeDef CardState; - - /* DIsable All interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); - - /* If IDMA Context, disable Internal DMA */ - hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - CardState = HAL_MMC_GetCardState(hmmc); - hmmc->State = HAL_MMC_STATE_READY; - - if ((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) - { - hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); - } - if (hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { -#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) - hmmc->AbortCpltCallback(hmmc); -#else - HAL_MMC_AbortCallback(hmmc); -#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @brief Perform specific commands sequence for the different type of erase. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc Pointer to MMC handle - * @param EraseType Specifies the type of erase to be performed - * This parameter can be one of the following values: - * @arg HAL_MMC_TRIM Erase the write blocks identified by CMD35 & 36 - * @arg HAL_MMC_ERASE Erase the erase groups identified by CMD35 & 36 - * @arg HAL_MMC_DISCARD Discard the write blocks identified by CMD35 & 36 - * @arg HAL_MMC_SECURE_ERASE Perform a secure purge according SRT on the erase groups identified - * by CMD35 & 36 - * @arg HAL_MMC_SECURE_TRIM_STEP1 Mark the write blocks identified by CMD35 & 36 for secure erase - * @arg HAL_MMC_SECURE_TRIM_STEP2 Perform a secure purge according SRT on the write blocks - * previously identified - * @param BlockStartAdd Start Block address - * @param BlockEndAdd End Block address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_EraseSequence(MMC_HandleTypeDef *hmmc, uint32_t EraseType, - uint32_t BlockStartAdd, uint32_t BlockEndAdd) -{ - uint32_t errorstate; - uint32_t start_add = BlockStartAdd; - uint32_t end_add = BlockEndAdd; - uint32_t tickstart = HAL_GetTick(); - - /* Check the erase type value is correct */ - assert_param(IS_MMC_ERASE_TYPE(EraseType)); - - /* Check the coherence between start and end address */ - if (end_add < start_add) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - /* Check that the end address is not out of range of device memory */ - if (end_add > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if (((start_add % 8U) != 0U) || ((end_add % 8U) != 0U)) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - /* Check if the card command class supports erase command */ - if (((hmmc->MmcCard.Class) & SDMMC_CCCC_ERASE) == 0U) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - return HAL_ERROR; - } - - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Check that the card is not locked */ - if ((SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_LOCK_UNLOCK_FAILED; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* In case of low capacity card, the address is not block number but bytes */ - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - start_add *= MMC_BLOCKSIZE; - end_add *= MMC_BLOCKSIZE; - } - - /* Send CMD35 MMC_ERASE_GRP_START with start address as argument */ - errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, start_add); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Send CMD36 MMC_ERASE_GRP_END with end address as argument */ - errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, end_add); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Send CMD38 ERASE with erase type as argument */ - errorstate = SDMMC_CmdErase(hmmc->Instance, EraseType); - if (errorstate == HAL_MMC_ERROR_NONE) - { - if ((EraseType == HAL_MMC_SECURE_ERASE) || (EraseType == HAL_MMC_SECURE_TRIM_STEP2)) - { - /* Wait that the device is ready by checking the D0 line */ - while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_MAXERASETIMEOUT) - { - errorstate = HAL_MMC_ERROR_TIMEOUT; - } - } - - /* Clear the flag corresponding to end D0 bus line */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - } - } - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - /* Manage errors */ - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - - if (errorstate != HAL_MMC_ERROR_TIMEOUT) - { - return HAL_ERROR; - } - else - { - return HAL_TIMEOUT; - } - } - else - { - return HAL_OK; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Perform sanitize operation on the device. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc Pointer to MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Sanitize(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate; - uint32_t response = 0U; - uint32_t count; - uint32_t tickstart = HAL_GetTick(); - - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Index : 165 - Value : 0x01 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03A50100U); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Wait that the device is ready by checking the D0 line */ - while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_MAXERASETIMEOUT) - { - errorstate = HAL_MMC_ERROR_TIMEOUT; - } - } - - /* Clear the flag corresponding to end D0 bus line */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - /* Manage errors */ - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - - if (errorstate != HAL_MMC_ERROR_TIMEOUT) - { - return HAL_ERROR; - } - else - { - return HAL_TIMEOUT; - } - } - else - { - return HAL_OK; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Configure the Secure Removal Type (SRT) in the Extended CSD register. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc Pointer to MMC handle - * @param SRTMode Specifies the type of erase to be performed - * This parameter can be one of the following values: - * @arg HAL_MMC_SRT_ERASE Information removed by an erase - * @arg HAL_MMC_SRT_WRITE_CHAR_ERASE Information removed by an overwriting with a character - * followed by an erase - * @arg HAL_MMC_SRT_WRITE_CHAR_COMPL_RANDOM Information removed by an overwriting with a character, - * its complement then a random character - * @arg HAL_MMC_SRT_VENDOR_DEFINED Information removed using a vendor defined - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ConfigSecRemovalType(MMC_HandleTypeDef *hmmc, uint32_t SRTMode) -{ - uint32_t srt; - uint32_t errorstate; - uint32_t response = 0U; - uint32_t count; - - /* Check the erase type value is correct */ - assert_param(IS_MMC_SRT_TYPE(SRTMode)); - - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Get the supported values by the device */ - if (HAL_MMC_GetSupportedSecRemovalType(hmmc, &srt) == HAL_OK) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Check the value passed as parameter is supported by the device */ - if ((SRTMode & srt) != 0U) - { - /* Index : 16 - Value : SRTMode */ - srt |= ((POSITION_VAL(SRTMode)) << 4U); - errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03100000U | (srt << 8U))); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - } - else - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - } - else - { - errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } - - /* Manage errors */ - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - else - { - return HAL_OK; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Gets the supported values of the the Secure Removal Type (SRT). - * @param hmmc pointer to MMC handle - * @param SupportedSRT pointer for supported SRT value - * This parameter is a bit field of the following values: - * @arg HAL_MMC_SRT_ERASE Information removed by an erase - * @arg HAL_MMC_SRT_WRITE_CHAR_ERASE Information removed by an overwriting with a character followed - * by an erase - * @arg HAL_MMC_SRT_WRITE_CHAR_COMPL_RANDOM Information removed by an overwriting with a character, - * its complement then a random character - * @arg HAL_MMC_SRT_VENDOR_DEFINED Information removed using a vendor defined - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetSupportedSecRemovalType(MMC_HandleTypeDef *hmmc, uint32_t *SupportedSRT) -{ - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Read field SECURE_REMOVAL_TYPE [16 = 4*4] of the Extended CSD register */ - *SupportedSRT = (hmmc->Ext_CSD[4] & 0x0000000FU); /* Bits [3:0] of field 16 */ - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Switch the device from Standby State to Sleep State. - * @param hmmc pointer to MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_SleepDevice(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate, - sleep_timeout, - timeout, - count, - response = 0U ; - uint32_t tickstart = HAL_GetTick(); - - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Set the power-off notification to powered-on : Ext_CSD[34] = 1 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03220100U)); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { - /* Set the power-off notification to sleep notification : Ext_CSD[34] = 4 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03220400U)); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Field SLEEP_NOTIFICATION_TIME [216] */ - sleep_timeout = ((hmmc->Ext_CSD[(MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_INDEX / 4)] >> - MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_POS) & 0x000000FFU); - - /* Sleep/Awake Timeout = 10us * 2^SLEEP_NOTIFICATION_TIME */ - /* In HAL, the tick interrupt occurs each ms */ - if ((sleep_timeout == 0U) || (sleep_timeout > 0x17U)) - { - sleep_timeout = 0x17U; /* Max register value defined is 0x17 */ - } - timeout = (((1UL << sleep_timeout) / 100U) + 1U); - - /* Wait that the device is ready by checking the D0 line */ - while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) - { - if ((HAL_GetTick() - tickstart) >= timeout) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - } - - /* Clear the flag corresponding to end D0 bus line */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, - (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { - /* Switch the device in stand-by mode */ - (void)SDMMC_CmdSelDesel(hmmc->Instance, 0U); - - /* Field S_A_TIEMOUT [217] */ - sleep_timeout = ((hmmc->Ext_CSD[(MMC_EXT_CSD_S_A_TIMEOUT_INDEX / 4)] >> - MMC_EXT_CSD_S_A_TIMEOUT_POS) & 0x000000FFU); - - /* Sleep/Awake Timeout = 100ns * 2^S_A_TIMEOUT */ - /* In HAL, the tick interrupt occurs each ms */ - if ((sleep_timeout == 0U) || (sleep_timeout > 0x17U)) - { - sleep_timeout = 0x17U; /* Max register value defined is 0x17 */ - } - timeout = (((1UL << sleep_timeout) / 10000U) + 1U); - - if (HAL_MMC_GetCardState(hmmc) == HAL_MMC_CARD_STANDBY) - { - /* Send CMD5 CMD_MMC_SLEEP_AWAKE with RCA and SLEEP as argument */ - errorstate = SDMMC_CmdSleepMmc(hmmc->Instance, - ((hmmc->MmcCard.RelCardAdd << 16U) | (0x1U << 15U))); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Wait that the device is ready by checking the D0 line */ - while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) - { - if ((HAL_GetTick() - tickstart) >= timeout) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - } - - /* Clear the flag corresponding to end D0 bus line */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - } - } - else - { - errorstate = SDMMC_ERROR_REQUEST_NOT_APPLICABLE; - } - } - } - else - { - /* Nothing to do */ - } - } - } - } - } - else - { - /* Nothing to do */ - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - /* Manage errors */ - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - - if (errorstate != HAL_MMC_ERROR_TIMEOUT) - { - return HAL_ERROR; - } - else - { - return HAL_TIMEOUT; - } - } - else - { - return HAL_OK; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Switch the device from Sleep State to Standby State. - * @param hmmc pointer to MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_AwakeDevice(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate; - uint32_t sleep_timeout; - uint32_t timeout; - uint32_t count; - uint32_t response = 0U; - uint32_t tickstart = HAL_GetTick(); - - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Field S_A_TIEMOUT [217] */ - sleep_timeout = ((hmmc->Ext_CSD[(MMC_EXT_CSD_S_A_TIMEOUT_INDEX / 4)] >> MMC_EXT_CSD_S_A_TIMEOUT_POS) & - 0x000000FFU); - - /* Sleep/Awake Timeout = 100ns * 2^S_A_TIMEOUT */ - /* In HAL, the tick interrupt occurs each ms */ - if ((sleep_timeout == 0U) || (sleep_timeout > 0x17U)) - { - sleep_timeout = 0x17U; /* Max register value defined is 0x17 */ - } - timeout = (((1UL << sleep_timeout) / 10000U) + 1U); - - /* Send CMD5 CMD_MMC_SLEEP_AWAKE with RCA and AWAKE as argument */ - errorstate = SDMMC_CmdSleepMmc(hmmc->Instance, (hmmc->MmcCard.RelCardAdd << 16U)); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Wait that the device is ready by checking the D0 line */ - while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) - { - if ((HAL_GetTick() - tickstart) >= timeout) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - } - - /* Clear the flag corresponding to end D0 bus line */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - - if (errorstate == HAL_MMC_ERROR_NONE) - { - if (HAL_MMC_GetCardState(hmmc) == HAL_MMC_CARD_STANDBY) - { - /* Switch the device in transfer mode */ - errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (hmmc->MmcCard.RelCardAdd << 16U)); - if (errorstate == HAL_MMC_ERROR_NONE) - { - if (HAL_MMC_GetCardState(hmmc) == HAL_MMC_CARD_TRANSFER) - { - /* Set the power-off notification to powered-on : Ext_CSD[34] = 1 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03220100U)); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, - (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - } - else - { - /* NOthing to do */ - } - } - } - else - { - errorstate = SDMMC_ERROR_REQUEST_NOT_APPLICABLE; - } - } - } - else - { - errorstate = SDMMC_ERROR_REQUEST_NOT_APPLICABLE; - } - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - /* Manage errors */ - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - - if (errorstate != HAL_MMC_ERROR_TIMEOUT) - { - return HAL_ERROR; - } - else - { - return HAL_TIMEOUT; - } - } - else - { - return HAL_OK; - } - } - else - { - return HAL_BUSY; - } -} -/** - * @} - */ - -/** - * @} - */ - -/* Private function ----------------------------------------------------------*/ -/** @addtogroup MMC_Private_Functions - * @{ - */ - -/** - * @brief Initializes the mmc card. - * @param hmmc Pointer to MMC handle - * @retval MMC Card error state - */ -static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc) -{ - HAL_MMC_CardCSDTypeDef CSD; - uint32_t errorstate; - uint16_t mmc_rca = 2U; - MMC_InitTypeDef Init; - - /* Check the power State */ - if (SDMMC_GetPowerState(hmmc->Instance) == 0U) - { - /* Power off */ - return HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - } - - /* Send CMD2 ALL_SEND_CID */ - errorstate = SDMMC_CmdSendCID(hmmc->Instance); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card identification number data */ - hmmc->CID[0U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - hmmc->CID[1U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2); - hmmc->CID[2U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP3); - hmmc->CID[3U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP4); - } - - /* Send CMD3 SET_REL_ADDR with RCA = 2 (should be greater than 1) */ - /* MMC Card publishes its RCA. */ - errorstate = SDMMC_CmdSetRelAddMmc(hmmc->Instance, mmc_rca); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - /* Get the MMC card RCA */ - hmmc->MmcCard.RelCardAdd = mmc_rca; - - /* Send CMD9 SEND_CSD with argument as card's RCA */ - errorstate = SDMMC_CmdSendCSD(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card Specific Data */ - hmmc->CSD[0U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - hmmc->CSD[1U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2); - hmmc->CSD[2U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP3); - hmmc->CSD[3U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP4); - } - - /* Get the Card Class */ - hmmc->MmcCard.Class = (SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2) >> 20U); - - /* Select the Card */ - errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - /* Get CSD parameters */ - if (HAL_MMC_GetCardCSD(hmmc, &CSD) != HAL_OK) - { - return hmmc->ErrorCode; - } - - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - - /* Get Extended CSD parameters */ - if (HAL_MMC_GetCardExtCSD(hmmc, hmmc->Ext_CSD, SDMMC_DATATIMEOUT) != HAL_OK) - { - return hmmc->ErrorCode; - } - - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - - /* Configure the SDMMC peripheral */ - Init = hmmc->Init; - Init.BusWide = SDMMC_BUS_WIDE_1B; - (void)SDMMC_Init(hmmc->Instance, Init); - - /* All cards are initialized */ - return HAL_MMC_ERROR_NONE; -} - -/** - * @brief Enquires cards about their operating voltage and configures clock - * controls and stores MMC information that will be needed in future - * in the MMC handle. - * @param hmmc Pointer to MMC handle - * @retval error state - */ -static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc) -{ - __IO uint32_t count = 0U; - uint32_t response = 0U; - uint32_t validvoltage = 0U; - uint32_t errorstate; - - /* CMD0: GO_IDLE_STATE */ - errorstate = SDMMC_CmdGoIdleState(hmmc->Instance); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - while (validvoltage == 0U) - { - if (count++ == SDMMC_MAX_VOLT_TRIAL) - { - return HAL_MMC_ERROR_INVALID_VOLTRANGE; - } - - /* SEND CMD1 APP_CMD with voltage range as argument */ - errorstate = SDMMC_CmdOpCondition(hmmc->Instance, MMC_VOLTAGE_RANGE); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return HAL_MMC_ERROR_UNSUPPORTED_FEATURE; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - - /* Get operating voltage*/ - validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); - } - - /* When power routine is finished and command returns valid voltage */ - if (((response & (0xFF000000U)) >> 24) == 0xC0U) - { - hmmc->MmcCard.CardType = MMC_HIGH_CAPACITY_CARD; - } - else - { - hmmc->MmcCard.CardType = MMC_LOW_CAPACITY_CARD; - } - - return HAL_MMC_ERROR_NONE; -} - -/** - * @brief Turns the SDMMC output signals off. - * @param hmmc Pointer to MMC handle - * @retval None - */ -static void MMC_PowerOFF(MMC_HandleTypeDef *hmmc) -{ - /* Set Power State to OFF */ - (void)SDMMC_PowerState_OFF(hmmc->Instance); -} - -/** - * @brief Returns the current card's status. - * @param hmmc Pointer to MMC handle - * @param pCardStatus: pointer to the buffer that will contain the MMC card - * status (Card Status register) - * @retval error state - */ -static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus) -{ - uint32_t errorstate; - - if (pCardStatus == NULL) - { - return HAL_MMC_ERROR_PARAM; - } - - /* Send Status command */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - /* Get MMC card status */ - *pCardStatus = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - - return HAL_MMC_ERROR_NONE; -} - -/** - * @brief Reads extended CSD register to get the sectors number of the device - * @param hmmc Pointer to MMC handle - * @param pFieldData: Pointer to the read buffer - * @param FieldIndex: Index of the field to be read - * @param Timeout Specify timeout value - * @retval HAL status - */ -static HAL_StatusTypeDef MMC_ReadExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pFieldData, - uint16_t FieldIndex, uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t i = 0; - uint32_t tmp_data; - - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0; - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_ENABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdSendEXTCSD(hmmc->Instance, 0); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Poll on SDMMC flags */ - while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | - SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - tmp_data = SDMMC_ReadFIFO(hmmc->Instance); - /* eg : SEC_COUNT : FieldIndex = 212 => i+count = 53 */ - /* DEVICE_TYPE : FieldIndex = 196 => i+count = 49 */ - if ((i + count) == ((uint32_t)FieldIndex / 4U)) - { - *pFieldData = tmp_data; - } - } - i += 8U; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Wrap up reading in non-blocking mode. - * @param hmmc pointer to a MMC_HandleTypeDef structure that contains - * the configuration information. - * @retval None - */ -static void MMC_Read_IT(MMC_HandleTypeDef *hmmc) -{ - uint32_t count; - uint32_t data; - uint8_t *tmp; - - tmp = hmmc->pRxBuffPtr; - - if (hmmc->RxXferSize >= SDMMC_FIFO_SIZE) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tmp = (uint8_t)(data & 0xFFU); - tmp++; - *tmp = (uint8_t)((data >> 8U) & 0xFFU); - tmp++; - *tmp = (uint8_t)((data >> 16U) & 0xFFU); - tmp++; - *tmp = (uint8_t)((data >> 24U) & 0xFFU); - tmp++; - } - - hmmc->pRxBuffPtr = tmp; - hmmc->RxXferSize -= SDMMC_FIFO_SIZE; - } -} - -/** - * @brief Wrap up writing in non-blocking mode. - * @param hmmc pointer to a MMC_HandleTypeDef structure that contains - * the configuration information. - * @retval None - */ -static void MMC_Write_IT(MMC_HandleTypeDef *hmmc) -{ - uint32_t count; - uint32_t data; - const uint8_t *tmp; - - tmp = hmmc->pTxBuffPtr; - - if (hmmc->TxXferSize >= SDMMC_FIFO_SIZE) - { - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*tmp); - tmp++; - data |= ((uint32_t)(*tmp) << 8U); - tmp++; - data |= ((uint32_t)(*tmp) << 16U); - tmp++; - data |= ((uint32_t)(*tmp) << 24U); - tmp++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - } - - hmmc->pTxBuffPtr = tmp; - hmmc->TxXferSize -= SDMMC_FIFO_SIZE; - } -} - -/** - * @brief Switches the MMC card to high speed mode. - * @param hmmc MMC handle - * @param state: State of high speed mode - * @retval MMC Card error state - */ -static uint32_t MMC_HighSpeed(MMC_HandleTypeDef *hmmc, FunctionalState state) -{ - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t response = 0U; - uint32_t count; - uint32_t sdmmc_clk; - SDMMC_InitTypeDef Init; - - if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) != 0U) && (state == DISABLE)) - { - errorstate = MMC_PwrClassUpdate(hmmc, (hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS), SDMMC_SPEED_MODE_DEFAULT); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Index : 185 - Value : 0 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B90000U); - } - } - - if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) == 0U) && (state != DISABLE)) - { - errorstate = MMC_PwrClassUpdate(hmmc, (hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS), SDMMC_SPEED_MODE_HIGH); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Index : 185 - Value : 1 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B90100U); - } - } - - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { - /* Configure high speed */ - Init.ClockEdge = hmmc->Init.ClockEdge; - Init.ClockPowerSave = hmmc->Init.ClockPowerSave; - Init.BusWide = (hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS); - Init.HardwareFlowControl = hmmc->Init.HardwareFlowControl; - - if (state == DISABLE) - { - Init.ClockDiv = hmmc->Init.ClockDiv; - (void)SDMMC_Init(hmmc->Instance, Init); - - CLEAR_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_BUSSPEED); - } - else - { - /* High Speed Clock should be less or equal to 52MHz*/ - sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); - - if (sdmmc_clk == 0U) - { - errorstate = SDMMC_ERROR_INVALID_PARAMETER; - } - else - { - if (sdmmc_clk <= MMC_HIGH_SPEED_FREQ) - { - Init.ClockDiv = 0; - } - else - { - Init.ClockDiv = (sdmmc_clk / (2U * MMC_HIGH_SPEED_FREQ)) + 1U; - } - (void)SDMMC_Init(hmmc->Instance, Init); - - SET_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_BUSSPEED); - } - } - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - - return errorstate; -} - -/** - * @brief Switches the MMC card to Double Data Rate (DDR) mode. - * @param hmmc MMC handle - * @param state: State of DDR mode - * @retval MMC Card error state - */ -static uint32_t MMC_DDR_Mode(MMC_HandleTypeDef *hmmc, FunctionalState state) -{ - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t response = 0U; - uint32_t count; - - if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) != 0U) && (state == DISABLE)) - { - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS_0) != 0U) - { - errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_4B, SDMMC_SPEED_MODE_HIGH); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Index : 183 - Value : 1 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100U); - } - } - else - { - errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_8B, SDMMC_SPEED_MODE_HIGH); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Index : 183 - Value : 2 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200U); - } - } - } - - if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) == 0U) && (state != DISABLE)) - { - if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS_0) != 0U) - { - errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_4B, SDMMC_SPEED_MODE_DDR); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Index : 183 - Value : 5 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70500U); - } - } - else - { - errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_8B, SDMMC_SPEED_MODE_DDR); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Index : 183 - Value : 6 */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70600U); - } - } - } - - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { - /* Configure DDR mode */ - if (state == DISABLE) - { - CLEAR_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_DDR); - } - else - { - SET_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_DDR); - } - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - - return errorstate; -} - -/** - * @brief Update the power class of the device. - * @param hmmc MMC handle - * @param Wide Wide of MMC bus - * @param Speed Speed of the MMC bus - * @retval MMC Card error state - */ -static uint32_t MMC_PwrClassUpdate(MMC_HandleTypeDef *hmmc, uint32_t Wide, uint32_t Speed) -{ - uint32_t count; - uint32_t response = 0U; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t power_class; - uint32_t supported_pwr_class; - - if ((Wide == SDMMC_BUS_WIDE_8B) || (Wide == SDMMC_BUS_WIDE_4B)) - { - power_class = 0U; /* Default value after power-on or software reset */ - - /* Read the PowerClass field of the Extended CSD register */ - if (MMC_ReadExtCSD(hmmc, &power_class, 187, SDMMC_DATATIMEOUT) != HAL_OK) /* Field POWER_CLASS [187] */ - { - errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } - else - { - power_class = ((power_class >> 24U) & 0x000000FFU); - } - - /* Get the supported PowerClass field of the Extended CSD register */ - if (Speed == SDMMC_SPEED_MODE_DDR) - { - /* Field PWR_CL_DDR_52_xxx [238 or 239] */ - supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_DDR_52_INDEX / 4)] >> MMC_EXT_CSD_PWR_CL_DDR_52_POS) & - 0x000000FFU); - } - else if (Speed == SDMMC_SPEED_MODE_HIGH) - { - /* Field PWR_CL_52_xxx [200 or 202] */ - supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_52_INDEX / 4)] >> MMC_EXT_CSD_PWR_CL_52_POS) & - 0x000000FFU); - } - else - { - /* Field PWR_CL_26_xxx [201 or 203] */ - supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_26_INDEX / 4)] >> MMC_EXT_CSD_PWR_CL_26_POS) & - 0x000000FFU); - } - - if (errorstate == HAL_MMC_ERROR_NONE) - { - if (Wide == SDMMC_BUS_WIDE_8B) - { - /* Bit [7:4]: power class for 8-bits bus configuration - Bit [3:0]: power class for 4-bits bus configuration */ - supported_pwr_class = (supported_pwr_class >> 4U); - } - - if ((power_class & 0x0FU) != (supported_pwr_class & 0x0FU)) - { - /* Need to change current power class */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03BB0000U | ((supported_pwr_class & 0x0FU) << 8U))); - - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - } - } - } - - return errorstate; -} - -/** - * @brief Used to select the partition. - * @param hmmc Pointer to MMC handle - * @param Partition Partition type - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_SwitchPartition(MMC_HandleTypeDef *hmmc, HAL_MMC_PartitionTypeDef Partition) -{ - uint32_t errorstate; - uint32_t response = 0U; - uint32_t count; - uint32_t tickstart = HAL_GetTick(); - uint32_t arg = Partition | 0x03B30000U; - - /* Check the state of the driver */ - if (hmmc->State == HAL_MMC_STATE_READY) - { - /* Change State */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Index : 179 - Value : partition */ - errorstate = SDMMC_CmdSwitch(hmmc->Instance, arg); - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* Wait that the device is ready by checking the D0 line */ - while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_MAXERASETIMEOUT) - { - errorstate = HAL_MMC_ERROR_TIMEOUT; - } - } - - /* Clear the flag corresponding to end D0 bus line */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); - - if (errorstate == HAL_MMC_ERROR_NONE) - { - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_MAX_TRIAL; - do - { - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if (errorstate != HAL_MMC_ERROR_NONE) - { - break; - } - - /* Get command response */ - response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); - count--; - } while (((response & 0x100U) == 0U) && (count != 0U)); - - /* Check the status after the switch command execution */ - if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) - { - /* Check the bit SWITCH_ERROR of the device status */ - if ((response & 0x80U) != 0U) - { - errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } - } - else if (count == 0U) - { - errorstate = SDMMC_ERROR_TIMEOUT; - } - else - { - /* Nothing to do */ - } - } - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - /* Manage errors */ - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - - if (errorstate != HAL_MMC_ERROR_TIMEOUT) - { - return HAL_ERROR; - } - else - { - return HAL_TIMEOUT; - } - } - else - { - return HAL_OK; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Allows to program the authentication key within the RPMB partition - * @param hmmc Pointer to MMC handle - * @param pKey pointer to the authentication key (32 bytes) - * @param Timeout Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_RPMB_ProgramAuthenticationKey(MMC_HandleTypeDef *hmmc, const uint8_t *pKey, uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t byte_count = 0; - uint32_t data; - uint32_t dataremaining; - uint8_t tail_pack[12] = {0}; - uint8_t zero_pack[4] = {0}; - const uint8_t *rtempbuff; - uint8_t *tempbuff; - - tail_pack[11] = 0x01; - - if (NULL == pKey) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x80000001U); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - { - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); - } - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write block(s) in polling mode */ - rtempbuff = zero_pack; - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*rtempbuff); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 8U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 16U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 24U); - rtempbuff++; - byte_count++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - if (byte_count < MMC_RPMB_KEYMAC_POSITION) - { - rtempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_KEYMAC_POSITION) - { - rtempbuff = pKey; - } - else if ((byte_count < MMC_RPMB_WRITE_COUNTER_POSITION) && \ - (byte_count >= MMC_RPMB_DATA_POSITION)) - { - rtempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - rtempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Read Response Packet */ - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - /* Poll on SDMMC flags */ - tempbuff = zero_pack; - byte_count = 0; - - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - byte_count++; - if (byte_count < MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - /* Check result of operation */ - if ((tail_pack[9] != 0x00U) || (tail_pack[10] != 0x01U)) - { - hmmc->RPMBErrorCode |= tail_pack[9]; - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Allows to get the value of write counter within the RPMB partition. - * @param hmmc Pointer to MMC handle - * @param pNonce pointer to the value of nonce (16 bytes) - * @param Timeout Specify timeout value - * @retval write counter value. - */ -uint32_t HAL_MMC_RPMB_GetWriteCounter(MMC_HandleTypeDef *hmmc, uint8_t *pNonce, uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t byte_count = 0; - uint32_t data; - uint32_t dataremaining; - uint8_t tail_pack[12] = {0}; - uint8_t zero_pack[4] = {0}; - uint8_t echo_nonce[16] = {0}; - uint8_t *tempbuff = zero_pack; - - tail_pack[11] = 0x02; - - if (NULL == pNonce) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001U); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - - /* Send Request Packet */ - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - - /* Write block(s) in polling mode */ - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*tempbuff); - tempbuff++; - byte_count++; - data |= ((uint32_t)(*tempbuff) << 8U); - tempbuff++; - byte_count++; - data |= ((uint32_t)(*tempbuff) << 16U); - tempbuff++; - byte_count++; - data |= ((uint32_t)(*tempbuff) << 24U); - tempbuff++; - byte_count++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - if (byte_count < MMC_RPMB_NONCE_POSITION) - { - tempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_NONCE_POSITION) - { - tempbuff = (uint8_t *)pNonce; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Read Response Packt */ - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001U); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - /* Poll on SDMMC flags */ - tempbuff = zero_pack; - - byte_count = 0; - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - byte_count++; - if (byte_count < MMC_RPMB_NONCE_POSITION) - { - tempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_NONCE_POSITION) - { - tempbuff = echo_nonce; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - for (uint8_t i = 0; i < 16U; i++) - { - if (pNonce[i] != echo_nonce[i]) - { - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } - } - - return ((uint32_t)tail_pack[3] | ((uint32_t)tail_pack[2] << 8) | ((uint32_t)tail_pack[1] << 16) | \ - ((uint32_t)tail_pack[0] << 24)); - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; - return 0; - } -} - -/** - * @brief Allows to write block(s) to a specified address in the RPMB partition. The Data - * transfer is managed by polling mode. - * @param hmmc Pointer to MMC handle - * @param pData Pointer to the buffer that will contain the data to transmit - * @param BlockAdd Block Address where data will be written - * @param NumberOfBlocks Number of blocks to write - * @param pMAC Pointer to the authentication MAC buffer - * @param Timeout Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_RPMB_WriteBlocks(MMC_HandleTypeDef *hmmc, const uint8_t *pData, uint16_t BlockAdd, - uint16_t NumberOfBlocks, const uint8_t *pMAC, uint32_t Timeout) -{ - - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t byte_count = 0; - uint32_t data; - uint32_t dataremaining; - uint8_t tail_pack[12] = {0}; - uint8_t zero_pack[4] = {0}; - uint8_t echo_nonce[16] = {0}; - const uint8_t local_nonce[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x00, 0x01, 0x02, - 0x03, 0x04, 0x00, 0x01, 0x02, 0x03, 0x04, 0x08 - }; - const uint8_t *rtempbuff; - uint8_t *tempbuff; - uint32_t arg = 0x80000000U; - uint32_t offset = 0; - - if ((NumberOfBlocks != 0x1U) && (NumberOfBlocks != 0x2U) && (NumberOfBlocks != 0x20U)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if ((NULL == pData) || (NULL == pMAC)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - tail_pack[11] = 0x02; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001U); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send Request Packet */ - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write block(s) in polling mode */ - rtempbuff = zero_pack; - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*rtempbuff); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 8U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 16U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 24U); - rtempbuff++; - byte_count++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - if (byte_count < MMC_RPMB_NONCE_POSITION) - { - rtempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_NONCE_POSITION) - { - rtempbuff = local_nonce; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - rtempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Read Response Packt */ - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - /* Poll on SDMMC flags */ - tempbuff = zero_pack; - - byte_count = 0; - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - byte_count++; - if (byte_count < MMC_RPMB_NONCE_POSITION) - { - tempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_NONCE_POSITION) - { - tempbuff = echo_nonce; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - for (uint8_t i = 0; i < 16U; i++) - { - if (local_nonce[i] != echo_nonce[i]) - { - return HAL_ERROR; - } - } - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } - tail_pack[11] = 0x03; - tail_pack[10] = 0x00; - tail_pack[7] = (uint8_t)(NumberOfBlocks) & 0xFFU; - tail_pack[6] = (uint8_t)(NumberOfBlocks >> 8) & 0xFFU; - tail_pack[5] = (uint8_t)(BlockAdd) & 0xFFU; - tail_pack[4] = (uint8_t)(BlockAdd >> 8) & 0xFFU; - - rtempbuff = zero_pack; - byte_count = 0; - arg |= NumberOfBlocks; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, arg); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send Request Packet */ - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - - { - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); - } - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - - /* Write block(s) in polling mode */ - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*rtempbuff); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 8U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 16U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 24U); - rtempbuff++; - byte_count++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - if (byte_count == MMC_RPMB_KEYMAC_POSITION) - { - rtempbuff = pMAC; - } - if (byte_count == MMC_RPMB_DATA_POSITION) - { - rtempbuff = &pData[offset]; - } - if ((byte_count >= MMC_RPMB_NONCE_POSITION) && \ - (byte_count < MMC_RPMB_WRITE_COUNTER_POSITION)) - { - rtempbuff = zero_pack; - } - if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - rtempbuff = tail_pack; - } - else if (byte_count == MMC_BLOCKSIZE) - { - offset += (uint32_t)256U; - byte_count = 0; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Response Packet */ - - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, arg); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - - { - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); - } - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - /* Poll on SDMMC flags */ - tempbuff = zero_pack; - byte_count = 0; - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - byte_count++; - if (byte_count < MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - /* Check result of operation */ - if (((tail_pack[9] & (uint8_t)0xFEU) != 0x00U) || (tail_pack[10] != 0x03U)) - { - hmmc->RPMBErrorCode |= tail_pack[9]; - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Allows to read block(s) to a specified address in the RPMB partition. The Data - * transfer is managed by polling mode. - * @param hmmc Pointer to MMC handle - * @param pData Pointer to the buffer that will contain the data to transmit - * @param BlockAdd Block Address where data will be written - * @param NumberOfBlocks Number of blocks to write - * @param pNonce Pointer to the buffer that will contain the nonce to transmit - * @param pMAC Pointer to the authentication MAC buffer - * @param Timeout Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_RPMB_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint16_t BlockAdd, - uint16_t NumberOfBlocks, const uint8_t *pNonce, uint8_t *pMAC, - uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t byte_count = 0; - uint32_t data; - uint8_t tail_pack[12] = {0}; - uint8_t zero_pack[4] = {0}; - uint8_t echo_nonce[16] = {0}; - uint32_t dataremaining; - const uint8_t *rtempbuff; - uint8_t *tempbuff; - uint32_t arg = 0; - uint32_t offset = 0; - - arg |= NumberOfBlocks; - - tail_pack[11] = 0x04; - tail_pack[10] = 0x00; - tail_pack[7] = 0x00; - tail_pack[6] = 0x00; - tail_pack[5] = (uint8_t)(BlockAdd) & 0xFFU; - tail_pack[4] = (uint8_t)(BlockAdd >> 8) & 0xFFU; - tail_pack[3] = 0x00; - tail_pack[2] = 0x00; - tail_pack[1] = 0x00; - tail_pack[0] = 0x00; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 1); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send Request Packet */ - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write block(s) in polling mode */ - rtempbuff = zero_pack; - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*rtempbuff); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 8U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 16U); - rtempbuff++; - byte_count++; - data |= ((uint32_t)(*rtempbuff) << 24U); - rtempbuff++; - byte_count++; - (void)SDMMC_WriteFIFO(hmmc->Instance, &data); - if (byte_count < MMC_RPMB_NONCE_POSITION) - { - rtempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_NONCE_POSITION) - { - rtempbuff = pNonce; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - rtempbuff = tail_pack; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Read Response Packet */ - errorstate = SDMMC_CmdBlockCount(hmmc->Instance, arg); - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - /* Write Blocks in Polling mode */ - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); - - if (errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - /* Poll on SDMMC flags */ - tempbuff = zero_pack; - byte_count = 0; - - dataremaining = config.DataLength; - while (!__HAL_MMC_GET_FLAG(hmmc, - SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hmmc->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - byte_count++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - byte_count++; - if (byte_count < MMC_RPMB_KEYMAC_POSITION) - { - tempbuff = zero_pack; - } - else if (byte_count == MMC_RPMB_KEYMAC_POSITION) - { - tempbuff = (uint8_t *)pMAC; - } - else if (byte_count == MMC_RPMB_DATA_POSITION) - { - tempbuff = &pData[offset]; - } - else if (byte_count == MMC_RPMB_NONCE_POSITION) - { - tempbuff = echo_nonce; - } - else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) - { - tempbuff = tail_pack; - } - else if (byte_count == MMC_BLOCKSIZE) - { - byte_count = 0; - offset += (uint32_t)256U; - } - else - { - /* Nothing to do */ - } - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); - - /* Get error state */ - if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - for (uint8_t i = 0; i < 16U; i++) - { - if (pNonce[i] != echo_nonce[i]) - { - return HAL_ERROR; - } - } - - /* Check result of operation */ - if ((tail_pack[9] != 0x00U) || (tail_pack[10] != 0x04U)) - { - hmmc->RPMBErrorCode |= tail_pack[9]; - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - - -/** - * @brief Read DMA Linked list node Transfer completed callbacks - * @param hmmc MMC handle - * @retval None - */ -__weak void HAL_MMCEx_Read_DMALnkLstBufCpltCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMCEx_Read_DMALnkLstBufCpltCallback can be implemented in the user file - */ -} -/** - * @brief Read DMA Linked list node Transfer completed callbacks - * @param hmmc MMC handle - * @retval None - */ -__weak void HAL_MMCEx_Write_DMALnkLstBufCpltCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMCEx_Write_DMALnkLstBufCpltCallback can be implemented in the user file - */ -} - -/** - * @} - */ - -#endif /* HAL_MMC_MODULE_ENABLED */ -#endif /* SDMMC1 || SDMMC2 */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_mmc.c + * @author MCD Application Team + * @brief MMC card HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Secure Digital (MMC) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + MMC card Control functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 (SDMMC and GPIO) are performed by + the user in HAL_MMC_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 SDMMC memories which uses the HAL + SDMMC driver functions to interface with MMC and eMMC cards devices. + It is used as follows: + + (#)Initialize the SDMMC low level resources by implement the HAL_MMC_MspInit() API: + (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE(); + (##) SDMMC pins configuration for MMC card + (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE(); + (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init() + and according to your pin assignment; + (##) NVIC configuration if you need to use interrupt process (HAL_MMC_ReadBlocks_IT() + and HAL_MMC_WriteBlocks_IT() APIs). + (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority(); + (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ() + (+++) SDMMC interrupts are managed using the macros __HAL_MMC_ENABLE_IT() + and __HAL_MMC_DISABLE_IT() inside the communication process. + (+++) SDMMC interrupts pending bits are managed using the macros __HAL_MMC_GET_IT() + and __HAL_MMC_CLEAR_IT() + (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used. + + (#) At this stage, you can perform MMC read/write/erase operations after MMC card initialization + + *** MMC Card Initialization and configuration *** + ================================================ + [..] + To initialize the MMC Card, use the HAL_MMC_Init() function. It Initializes + SDMMC Peripheral (STM32 side) and the MMC Card, and put it into StandBy State (Ready for data transfer). + This function provide the following operations: + + (#) Initialize the SDMMC peripheral interface with default configuration. + The initialization process is done at 400KHz. You can change or adapt + this frequency by adjusting the "ClockDiv" field. + The MMC Card frequency (SDMMC_CK) is computed as follows: + + SDMMC_CK = SDMMCCLK / (2 * ClockDiv) + + In initialization mode and according to the MMC Card standard, + make sure that the SDMMC_CK frequency doesn't exceed 400KHz. + + This phase of initialization is done through SDMMC_Init() and + SDMMC_PowerState_ON() SDMMC low level APIs. + + (#) Initialize the MMC card. The API used is HAL_MMC_InitCard(). + This phase allows the card initialization and identification + and check the MMC Card type (Standard Capacity or High Capacity) + The initialization flow is compatible with MMC standard. + + This API (HAL_MMC_InitCard()) could be used also to reinitialize the card in case + of plug-off plug-in. + + (#) Configure the MMC Card Data transfer frequency. By Default, the card transfer + frequency by adjusting the "ClockDiv" field. + In transfer mode and according to the MMC Card standard, make sure that the + SDMMC_CK frequency doesn't exceed 25MHz and 100MHz in High-speed mode switch. + + (#) Select the corresponding MMC Card according to the address read with the step 2. + + (#) Configure the MMC Card in wide bus mode: 4-bits data. + (#) Select the MMC Card partition using HAL_MMC_SwitchPartition() + + *** MMC Card Read operation *** + ============================== + [..] + (+) You can read from MMC card in polling mode by using function HAL_MMC_ReadBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetCardState() function for MMC card state. + + (+) You can read from MMC card in DMA mode by using function HAL_MMC_ReadBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetCardState() function for MMC card state. + You could also check the DMA transfer process through the MMC Rx interrupt event. + + (+) You can read from MMC card in Interrupt mode by using function HAL_MMC_ReadBlocks_IT(). + This function allows the read of 512 bytes blocks. + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetCardState() function for MMC card state. + You could also check the IT transfer process through the MMC Rx interrupt event. + + *** MMC Card Write operation *** + =============================== + [..] + (+) You can write to MMC card in polling mode by using function HAL_MMC_WriteBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetCardState() function for MMC card state. + + (+) You can write to MMC card in DMA mode by using function HAL_MMC_WriteBlocks_DMA(). + This function support only 512-bytes 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 ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetCardState() function for MMC card state. + You could also check the DMA transfer process through the MMC Tx interrupt event. + + (+) You can write to MMC card in Interrupt mode by using function HAL_MMC_WriteBlocks_IT(). + This function allows the read of 512 bytes blocks. + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetCardState() function for MMC card state. + You could also check the IT transfer process through the MMC Tx interrupt event. + + *** MMC card information *** + =========================== + [..] + (+) To get MMC card information, you can use the function HAL_MMC_GetCardInfo(). + It returns useful information about the MMC card such as block size, card type, + block number ... + + *** MMC card CSD register *** + ============================ + [..] + (+) The HAL_MMC_GetCardCSD() API allows to get the parameters of the CSD register. + Some of the CSD parameters are useful for card initialization and identification. + + *** MMC card CID register *** + ============================ + [..] + (+) The HAL_MMC_GetCardCID() API allows to get the parameters of the CID register. + Some of the CID parameters are useful for card initialization and identification. + + *** MMC Card Reply Protected Memory Block (RPMB) Key Programming operation *** + ============================== + [..] + (+) You can program the authentication key of RPMB area in polling mode by using function + HAL_MMC_RPMB_ProgramAuthenticationKey(). + This function is only used once during the life of an MMC card. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetRPMBError() function for operation state. + (+) You can program the authentication key of RPMB area in Interrupt mode by using function + HAL_MMC_RPMB_ProgramAuthenticationKey_IT(). + This function is only used once during the life of an MMC card. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetRPMBError() function for operation state. + + *** MMC Card Reply Protected Memory Block (RPMB) write counter operation *** + ============================== + [..] + (+) You can get the write counter value of RPMB area in polling mode by using function + HAL_MMC_RPMB_GetWriteCounter(). + (+) You can get the write counter value of RPMB area in Interrupt mode by using function + HAL_MMC_RPMB_GetWriteCounter_IT(). + + *** MMC Card Reply Protected Memory Block (RPMB) write operation *** + ============================== + [..] + (+) You can write to the RPMB area of MMC card in polling mode by using function + HAL_MMC_WriteBlocks(). + This function supports the one, two, or thirty two blocks write operation + (with 512-bytes block length). + You can choose the number of blocks at the multiple block read operation by adjusting + the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetRPMBError() function for operation state. + (+) You can write to the RPMB area of MMC card in Interrupt mode by using function + HAL_MMC_WriteBlocks_IT(). + This function supports the one, two, or thirty two blocks write operation + (with 512-bytes block length). + You can choose the number of blocks at the multiple block read operation by adjusting + the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetRPMBError() function for operation state. + + *** MMC Card Reply Protected Memory Block (RPMB) read operation *** + ============================== + [..] + (+) You can read from the RPMB area of MMC card in polling mode by using function + HAL_MMC_RPMB_ReadBlocks(). + The block size should be chosen as multiple of 512 bytes. + You can choose the number of blocks by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetRPMBError() function for MMC card state. + (+) You can read from the RPMB area of MMC card in Interrupt mode by using function + HAL_MMC_RPMB_ReadBlocks_IT(). + The block size should be chosen as multiple of 512 bytes. + You can choose the number of blocks by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_MMC_GetRPMBError() function for MMC card state. + + *** MMC HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in MMC HAL driver. + + (+) __HAL_MMC_ENABLE_IT: Enable the MMC device interrupt + (+) __HAL_MMC_DISABLE_IT: Disable the MMC device interrupt + (+) __HAL_MMC_GET_FLAG:Check whether the specified MMC flag is set or not + (+) __HAL_MMC_CLEAR_FLAG: Clear the MMC's pending flags + + [..] + (@) You can refer to the MMC HAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_MMC_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_MMC_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) Read_DMALnkLstBufCpltCallback : callback when the DMA reception of linked list node buffer is completed. + (+) Write_DMALnkLstBufCpltCallback : callback when the DMA transmission of linked list node buffer is completed. + (+) MspInitCallback : MMC MspInit. + (+) MspDeInitCallback : MMC MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function HAL_MMC_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed. + (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed. + (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed. + (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed. + (+) MspInitCallback : MMC MspInit. + (+) MspDeInitCallback : MMC MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + + By default, after the HAL_MMC_Init and if the state is HAL_MMC_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_MMC_Init + and HAL_MMC_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_MMC_Init and HAL_MMC_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_MMC_RegisterCallback before calling HAL_MMC_DeInit + or HAL_MMC_Init function. + + When The compilation define USE_HAL_MMC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup MMC MMC + * @brief MMC HAL module driver + * @{ + */ + +#if defined (SDMMC1) || defined (SDMMC2) +#ifdef HAL_MMC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup MMC_Private_Defines + * @{ + */ +#if defined (VDD_VALUE) && (VDD_VALUE <= 1950U) +#define MMC_VOLTAGE_RANGE EMMC_LOW_VOLTAGE_RANGE + +#define MMC_EXT_CSD_PWR_CL_26_INDEX 201 +#define MMC_EXT_CSD_PWR_CL_52_INDEX 200 +#define MMC_EXT_CSD_PWR_CL_DDR_52_INDEX 238 + +#define MMC_EXT_CSD_PWR_CL_26_POS 8 +#define MMC_EXT_CSD_PWR_CL_52_POS 0 +#define MMC_EXT_CSD_PWR_CL_DDR_52_POS 16 +#else +#define MMC_VOLTAGE_RANGE EMMC_HIGH_VOLTAGE_RANGE + +#define MMC_EXT_CSD_PWR_CL_26_INDEX 203 +#define MMC_EXT_CSD_PWR_CL_52_INDEX 202 +#define MMC_EXT_CSD_PWR_CL_DDR_52_INDEX 239 + +#define MMC_EXT_CSD_PWR_CL_26_POS 24 +#define MMC_EXT_CSD_PWR_CL_52_POS 16 +#define MMC_EXT_CSD_PWR_CL_DDR_52_POS 24 +#endif /* (VDD_VALUE) && (VDD_VALUE <= 1950U)*/ + +#define MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_INDEX 216 +#define MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_POS 0 +#define MMC_EXT_CSD_S_A_TIMEOUT_INDEX 217 +#define MMC_EXT_CSD_S_A_TIMEOUT_POS 8 + +/* Frequencies used in the driver for clock divider calculation */ +#define MMC_INIT_FREQ 400000U /* Initialization phase : 400 kHz max */ +#define MMC_HIGH_SPEED_FREQ 52000000U /* High speed phase : 52 MHz max */ + +/* The Data elements' postitions in the frame Frame for RPMB area */ +#define MMC_RPMB_KEYMAC_POSITION 196U +#define MMC_RPMB_DATA_POSITION 228U +#define MMC_RPMB_NONCE_POSITION 484U +#define MMC_RPMB_WRITE_COUNTER_POSITION 500U +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup MMC_Private_Functions MMC Private Functions + * @{ + */ +static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc); +static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc); +static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus); +static void MMC_PowerOFF(MMC_HandleTypeDef *hmmc); +static void MMC_Write_IT(MMC_HandleTypeDef *hmmc); +static void MMC_Read_IT(MMC_HandleTypeDef *hmmc); +static uint32_t MMC_HighSpeed(MMC_HandleTypeDef *hmmc, FunctionalState state); +static uint32_t MMC_DDR_Mode(MMC_HandleTypeDef *hmmc, FunctionalState state); +static HAL_StatusTypeDef MMC_ReadExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pFieldData, uint16_t FieldIndex, + uint32_t Timeout); +static uint32_t MMC_PwrClassUpdate(MMC_HandleTypeDef *hmmc, uint32_t Wide, uint32_t Speed); + +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup MMC_Exported_Functions + * @{ + */ + +/** @addtogroup MMC_Exported_Functions_Group1 + * @brief Initialization and de-initialization functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize the MMC + card device to be ready for use. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the MMC according to the specified parameters in the + MMC_HandleTypeDef and create the associated handle. + * @param hmmc Pointer to the MMC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_Init(MMC_HandleTypeDef *hmmc) +{ + /* Check the MMC handle allocation */ + if (hmmc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(hmmc->Instance)); + assert_param(IS_SDMMC_CLOCK_EDGE(hmmc->Init.ClockEdge)); + assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hmmc->Init.ClockPowerSave)); + assert_param(IS_SDMMC_BUS_WIDE(hmmc->Init.BusWide)); + assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hmmc->Init.HardwareFlowControl)); + assert_param(IS_SDMMC_CLKDIV(hmmc->Init.ClockDiv)); + + if (hmmc->State == HAL_MMC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hmmc->Lock = HAL_UNLOCKED; +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + /* Reset Callback pointers in HAL_MMC_STATE_RESET only */ + hmmc->TxCpltCallback = HAL_MMC_TxCpltCallback; + hmmc->RxCpltCallback = HAL_MMC_RxCpltCallback; + hmmc->ErrorCallback = HAL_MMC_ErrorCallback; + hmmc->AbortCpltCallback = HAL_MMC_AbortCallback; + hmmc->Read_DMALnkLstBufCpltCallback = HAL_MMCEx_Read_DMALnkLstBufCpltCallback; + hmmc->Write_DMALnkLstBufCpltCallback = HAL_MMCEx_Write_DMALnkLstBufCpltCallback; + + if (hmmc->MspInitCallback == NULL) + { + hmmc->MspInitCallback = HAL_MMC_MspInit; + } + + /* Init the low level hardware */ + hmmc->MspInitCallback(hmmc); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_MMC_MspInit(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize the Card parameters */ + if (HAL_MMC_InitCard(hmmc) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* Initialize the error code */ + hmmc->ErrorCode = HAL_DMA_ERROR_NONE; + + /* Initialize the MMC operation */ + hmmc->Context = MMC_CONTEXT_NONE; + + /* Initialize the MMC state */ + hmmc->State = HAL_MMC_STATE_READY; + + /* Configure bus width */ + if (hmmc->Init.BusWide != SDMMC_BUS_WIDE_1B) + { + if (HAL_MMC_ConfigWideBusOperation(hmmc, hmmc->Init.BusWide) != HAL_OK) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Initializes the MMC Card. + * @param hmmc Pointer to MMC handle + * @note This function initializes the MMC card. It could be used when a card + re-initialization is needed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_InitCard(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate; + MMC_InitTypeDef Init; + uint32_t sdmmc_clk; + + /* Default SDMMC peripheral configuration for MMC card initialization */ + Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; + Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; + Init.BusWide = SDMMC_BUS_WIDE_1B; + Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE; + + /* Init Clock should be less or equal to 400Khz*/ + sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); + if (sdmmc_clk == 0U) + { + hmmc->State = HAL_MMC_STATE_READY; + hmmc->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER; + return HAL_ERROR; + } + Init.ClockDiv = sdmmc_clk / (2U * MMC_INIT_FREQ); + +#if (USE_SD_TRANSCEIVER != 0U) + Init.TranceiverPresent = SDMMC_TRANSCEIVER_NOT_PRESENT; +#endif /* USE_SD_TRANSCEIVER */ + + /* Initialize SDMMC peripheral interface with default configuration */ + (void)SDMMC_Init(hmmc->Instance, Init); + + /* Set Power State to ON */ + (void)SDMMC_PowerState_ON(hmmc->Instance); + + /* wait 74 Cycles: required power up waiting time before starting + the MMC initialization sequence */ + if (Init.ClockDiv != 0U) + { + sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv); + } + + if (sdmmc_clk != 0U) + { + HAL_Delay(1U + (74U * 1000U / (sdmmc_clk))); + } + + /* Identify card operating voltage */ + errorstate = MMC_PowerON(hmmc); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->State = HAL_MMC_STATE_READY; + hmmc->ErrorCode |= errorstate; + return HAL_ERROR; + } + + /* Card initialization */ + errorstate = MMC_InitCard(hmmc); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->State = HAL_MMC_STATE_READY; + hmmc->ErrorCode |= errorstate; + return HAL_ERROR; + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hmmc->Instance, MMC_BLOCKSIZE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief De-Initializes the MMC card. + * @param hmmc Pointer to MMC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_DeInit(MMC_HandleTypeDef *hmmc) +{ + /* Check the MMC handle allocation */ + if (hmmc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(hmmc->Instance)); + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Set MMC power state to off */ + MMC_PowerOFF(hmmc); + +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + if (hmmc->MspDeInitCallback == NULL) + { + hmmc->MspDeInitCallback = HAL_MMC_MspDeInit; + } + + /* DeInit the low level hardware */ + hmmc->MspDeInitCallback(hmmc); +#else + /* De-Initialize the MSP layer */ + HAL_MMC_MspDeInit(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + hmmc->State = HAL_MMC_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initializes the MMC MSP. + * @param hmmc Pointer to MMC handle + * @retval None + */ +__weak void HAL_MMC_MspInit(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MMC_MspInit could be implemented in the user file + */ +} + +/** + * @brief De-Initialize MMC MSP. + * @param hmmc Pointer to MMC handle + * @retval None + */ +__weak void HAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MMC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @addtogroup MMC_Exported_Functions_Group2 + * @brief Data transfer functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the data + transfer from/to MMC card. + +@endverbatim + * @{ + */ + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed by polling mode. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @param hmmc Pointer to MMC handle + * @param pData pointer to the buffer that will contain the received data + * @param BlockAdd Block Address from where data is to be read + * @param NumberOfBlocks Number of MMC blocks to read + * @param Timeout Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks, + uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t data; + uint32_t dataremaining; + uint32_t add = BlockAdd; + uint8_t *tempbuff = pData; + + if (NULL == pData) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) + & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= MMC_BLOCKSIZE; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Read block(s) in polling mode */ + if (NumberOfBlocks > 1U) + { + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = MMC_CONTEXT_READ_SINGLE_BLOCK; + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); + } + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Poll on SDMMC flags */ + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Send stop transmission command in case of multiblock read */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + } + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + return HAL_OK; + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Allows to write block(s) to a specified address in a card. The Data + * transfer is managed by polling mode. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @param hmmc Pointer to MMC handle + * @param pData pointer to the buffer that will contain the data to transmit + * @param BlockAdd Block Address where data will be written + * @param NumberOfBlocks Number of MMC blocks to write + * @param Timeout Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, const uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks, uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t data; + uint32_t dataremaining; + uint32_t add = BlockAdd; + const uint8_t *tempbuff = pData; + + if (NULL == pData) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= MMC_BLOCKSIZE; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + if (NumberOfBlocks > 1U) + { + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = MMC_CONTEXT_WRITE_SINGLE_BLOCK; + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); + } + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*tempbuff); + tempbuff++; + data |= ((uint32_t)(*tempbuff) << 8U); + tempbuff++; + data |= ((uint32_t)(*tempbuff) << 16U); + tempbuff++; + data |= ((uint32_t)(*tempbuff) << 24U); + tempbuff++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Send stop transmission command in case of multiblock write */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + } + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + return HAL_OK; + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @note You could also check the IT transfer process through the MMC Rx + * interrupt event. + * @param hmmc Pointer to MMC handle + * @param pData Pointer to the buffer that will contain the received data + * @param BlockAdd Block Address from where data is to be read + * @param NumberOfBlocks Number of blocks to read. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + hmmc->pRxBuffPtr = pData; + hmmc->RxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= MMC_BLOCKSIZE; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Read Blocks in IT mode */ + if (NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_IT); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_IT); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); + } + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | + SDMMC_FLAG_RXFIFOHF)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Writes block(s) to a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @note You could also check the IT transfer process through the MMC Tx + * interrupt event. + * @param hmmc Pointer to MMC handle + * @param pData Pointer to the buffer that will contain the data to transmit + * @param BlockAdd Block Address where data will be written + * @param NumberOfBlocks Number of blocks to write + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, const uint8_t *pData, + uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + hmmc->pTxBuffPtr = pData; + hmmc->TxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= MMC_BLOCKSIZE; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + if (NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_IT); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_IT); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); + } + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Enable transfer interrupts */ + __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | + SDMMC_FLAG_TXFIFOHE)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @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 a check on the card state through + * HAL_MMC_GetCardState(). + * @note You could also check the DMA transfer process through the MMC Rx + * interrupt event. + * @param hmmc Pointer MMC handle + * @param pData Pointer to the buffer that will contain the received data + * @param BlockAdd Block Address from where data is to be read + * @param NumberOfBlocks Number of blocks to read. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_DMA_ERROR_NONE; + + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + hmmc->pRxBuffPtr = pData; + hmmc->RxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= MMC_BLOCKSIZE; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + hmmc->Instance->IDMABASER = (uint32_t) pData ; + hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; + + /* Read Blocks in DMA mode */ + if (NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_DMA); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, add); + } + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode = errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Enable transfer interrupts */ + __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @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 a check on the card state through + * HAL_MMC_GetCardState(). + * @note You could also check the DMA transfer process through the MMC Tx + * interrupt event. + * @param hmmc Pointer to MMC handle + * @param pData Pointer to the buffer that will contain the data to transmit + * @param BlockAdd Block Address where data will be written + * @param NumberOfBlocks Number of blocks to write + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, const uint8_t *pData, + uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + hmmc->pTxBuffPtr = pData; + hmmc->TxXferSize = MMC_BLOCKSIZE * NumberOfBlocks; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= MMC_BLOCKSIZE; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + hmmc->Instance->IDMABASER = (uint32_t) pData ; + hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; + + /* Write Blocks in Polling mode */ + if (NumberOfBlocks > 1U) + { + hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + } + else + { + hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_DMA); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, add); + } + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Enable transfer interrupts */ + __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Erases the specified memory area of the given MMC card. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @param hmmc Pointer to MMC handle + * @param BlockStartAdd: Start Block address + * @param BlockEndAdd: End Block address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd) +{ + uint32_t errorstate; + uint32_t start_add = BlockStartAdd; + uint32_t end_add = BlockEndAdd; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + if (end_add < start_add) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (end_add > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) + & 0x000000FFU) != 0x0U) + { + if (((start_add % 8U) != 0U) || ((end_add % 8U) != 0U)) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Check if the card command class supports erase command */ + if (((hmmc->MmcCard.Class) & SDMMC_CCCC_ERASE) == 0U) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + if ((SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_LOCK_UNLOCK_FAILED; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + start_add *= MMC_BLOCKSIZE; + end_add *= MMC_BLOCKSIZE; + } + + /* Send CMD35 MMC_ERASE_GRP_START with argument as addr */ + errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, start_add); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Send CMD36 MMC_ERASE_GRP_END with argument as addr */ + errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, end_add); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Send CMD38 ERASE */ + errorstate = SDMMC_CmdErase(hmmc->Instance, 0UL); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + hmmc->State = HAL_MMC_STATE_READY; + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles MMC card interrupt request. + * @param hmmc Pointer to MMC handle + * @retval None + */ +void HAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate; + uint32_t context = hmmc->Context; + + /* Check for SDMMC interrupt flags */ + if ((__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) != RESET) && ((context & MMC_CONTEXT_IT) != 0U)) + { + MMC_Read_IT(hmmc); + } + + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND) != RESET) + { + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_DATAEND); + + __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR | SDMMC_IT_TXFIFOHE | \ + SDMMC_IT_RXFIFOHF); + + __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_IDMABTC); + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + if ((context & MMC_CONTEXT_DMA) != 0U) + { + hmmc->Instance->DLEN = 0; + hmmc->Instance->DCTRL = 0; + hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA ; + + /* Stop Transfer for Write Multi blocks or Read Multi blocks */ + if (((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + HAL_MMC_ErrorCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + if (((context & MMC_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->TxCpltCallback(hmmc); +#else + HAL_MMC_TxCpltCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + if (((context & MMC_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->RxCpltCallback(hmmc); +#else + HAL_MMC_RxCpltCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + } + else if ((context & MMC_CONTEXT_IT) != 0U) + { + /* Stop Transfer for Write Multi blocks or Read Multi blocks */ + if (((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + HAL_MMC_ErrorCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + if (((context & MMC_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->RxCpltCallback(hmmc); +#else + HAL_MMC_RxCpltCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + else + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->TxCpltCallback(hmmc); +#else + HAL_MMC_TxCpltCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + } + + else if ((__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) != RESET) && ((context & MMC_CONTEXT_IT) != 0U)) + { + MMC_Write_IT(hmmc); + } + + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL | + SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR | SDMMC_FLAG_TXUNDERR) != RESET) + { + /* Set Error code */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DCRCFAIL) != RESET) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + } + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_DTIMEOUT) != RESET) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + } + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_RXOVERR) != RESET) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; + } + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_IT_TXUNDERR) != RESET) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + } + + /* Clear All flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + /* Disable all interrupts */ + __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); + + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + hmmc->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; + hmmc->Instance->CMD |= SDMMC_CMD_CMDSTOP; + hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); + hmmc->Instance->CMD &= ~(SDMMC_CMD_CMDSTOP); + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_DABORT); + + if ((context & MMC_CONTEXT_IT) != 0U) + { + /* Set the MMC state to ready to be able to start again the process */ + hmmc->State = HAL_MMC_STATE_READY; +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + HAL_MMC_ErrorCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + else if ((context & MMC_CONTEXT_DMA) != 0U) + { + if (hmmc->ErrorCode != HAL_MMC_ERROR_NONE) + { + /* Disable Internal DMA */ + __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_IDMABTC); + hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + /* Set the MMC state to ready to be able to start again the process */ + hmmc->State = HAL_MMC_STATE_READY; +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->ErrorCallback(hmmc); +#else + HAL_MMC_ErrorCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + } + + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_IDMABTC) != RESET) + { + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_IT_IDMABTC); + + if ((context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U) + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->Write_DMALnkLstBufCpltCallback(hmmc); +#else + HAL_MMCEx_Write_DMALnkLstBufCpltCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + else /* MMC_CONTEXT_READ_MULTIPLE_BLOCK */ + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->Read_DMALnkLstBufCpltCallback(hmmc); +#else + HAL_MMCEx_Read_DMALnkLstBufCpltCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + } + + else + { + /* Nothing to do */ + } +} + +/** + * @brief return the MMC state + * @param hmmc Pointer to mmc handle + * @retval HAL state + */ +HAL_MMC_StateTypeDef HAL_MMC_GetState(const MMC_HandleTypeDef *hmmc) +{ + return hmmc->State; +} + +/** + * @brief Return the MMC error code + * @param hmmc : Pointer to a MMC_HandleTypeDef structure that contains + * the configuration information. + * @retval MMC Error Code + */ +uint32_t HAL_MMC_GetError(const MMC_HandleTypeDef *hmmc) +{ + return hmmc->ErrorCode; +} + +/** + * @brief Tx Transfer completed callbacks + * @param hmmc Pointer to MMC handle + * @retval None + */ +__weak void HAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MMC_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hmmc Pointer MMC handle + * @retval None + */ +__weak void HAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MMC_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief MMC error callbacks + * @param hmmc Pointer MMC handle + * @retval None + */ +__weak void HAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MMC_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief MMC Abort callbacks + * @param hmmc Pointer MMC handle + * @retval None + */ +__weak void HAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MMC_AbortCallback can be implemented in the user file + */ +} + +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User MMC Callback + * To be used instead of the weak (overridden) predefined callback + * @note The HAL_MMC_RegisterCallback() may be called before HAL_MMC_Init() in + * HAL_MMC_STATE_RESET to register callbacks for HAL_MMC_MSP_INIT_CB_ID + * and HAL_MMC_MSP_DEINIT_CB_ID. + * @param hmmc : MMC handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_MMC_TX_CPLT_CB_ID MMC Tx Complete Callback ID + * @arg @ref HAL_MMC_RX_CPLT_CB_ID MMC Rx Complete Callback ID + * @arg @ref HAL_MMC_ERROR_CB_ID MMC Error Callback ID + * @arg @ref HAL_MMC_ABORT_CB_ID MMC Abort Callback ID + * @arg @ref HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Rx Linked List Node buffer Callback ID + * @arg @ref HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Tx Linked List Node buffer Callback ID + * @arg @ref HAL_MMC_MSP_INIT_CB_ID MMC MspInit Callback ID + * @arg @ref HAL_MMC_MSP_DEINIT_CB_ID MMC MspDeInit Callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_MMC_RegisterCallback(MMC_HandleTypeDef *hmmc, HAL_MMC_CallbackIDTypeDef CallbackId, + pMMC_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + switch (CallbackId) + { + case HAL_MMC_TX_CPLT_CB_ID : + hmmc->TxCpltCallback = pCallback; + break; + case HAL_MMC_RX_CPLT_CB_ID : + hmmc->RxCpltCallback = pCallback; + break; + case HAL_MMC_ERROR_CB_ID : + hmmc->ErrorCallback = pCallback; + break; + case HAL_MMC_ABORT_CB_ID : + hmmc->AbortCpltCallback = pCallback; + break; + case HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID : + hmmc->Read_DMALnkLstBufCpltCallback = pCallback; + break; + case HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : + hmmc->Write_DMALnkLstBufCpltCallback = pCallback; + break; + case HAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = pCallback; + break; + case HAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hmmc->State == HAL_MMC_STATE_RESET) + { + switch (CallbackId) + { + case HAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = pCallback; + break; + case HAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User MMC Callback + * MMC Callback is redirected to the weak (overridden) predefined callback + * @note The HAL_MMC_UnRegisterCallback() may be called before HAL_MMC_Init() in + * HAL_MMC_STATE_RESET to register callbacks for HAL_MMC_MSP_INIT_CB_ID + * and HAL_MMC_MSP_DEINIT_CB_ID. + * @param hmmc : MMC handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_MMC_TX_CPLT_CB_ID MMC Tx Complete Callback ID + * @arg @ref HAL_MMC_RX_CPLT_CB_ID MMC Rx Complete Callback ID + * @arg @ref HAL_MMC_ERROR_CB_ID MMC Error Callback ID + * @arg @ref HAL_MMC_ABORT_CB_ID MMC Abort Callback ID + * @arg @ref HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Rx Linked List Node buffer Callback ID + * @arg @ref HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID MMC DMA Tx Linked List Node buffer Callback ID + * @arg @ref HAL_MMC_MSP_INIT_CB_ID MMC MspInit Callback ID + * @arg @ref HAL_MMC_MSP_DEINIT_CB_ID MMC MspDeInit Callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_MMC_UnRegisterCallback(MMC_HandleTypeDef *hmmc, HAL_MMC_CallbackIDTypeDef CallbackId) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + switch (CallbackId) + { + case HAL_MMC_TX_CPLT_CB_ID : + hmmc->TxCpltCallback = HAL_MMC_TxCpltCallback; + break; + case HAL_MMC_RX_CPLT_CB_ID : + hmmc->RxCpltCallback = HAL_MMC_RxCpltCallback; + break; + case HAL_MMC_ERROR_CB_ID : + hmmc->ErrorCallback = HAL_MMC_ErrorCallback; + break; + case HAL_MMC_ABORT_CB_ID : + hmmc->AbortCpltCallback = HAL_MMC_AbortCallback; + break; + case HAL_MMC_READ_DMA_LNKLST_BUF_CPLT_CB_ID : + hmmc->Read_DMALnkLstBufCpltCallback = HAL_MMCEx_Read_DMALnkLstBufCpltCallback; + break; + case HAL_MMC_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : + hmmc->Write_DMALnkLstBufCpltCallback = HAL_MMCEx_Write_DMALnkLstBufCpltCallback; + break; + case HAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = HAL_MMC_MspInit; + break; + case HAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = HAL_MMC_MspDeInit; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hmmc->State == HAL_MMC_STATE_RESET) + { + switch (CallbackId) + { + case HAL_MMC_MSP_INIT_CB_ID : + hmmc->MspInitCallback = HAL_MMC_MspInit; + break; + case HAL_MMC_MSP_DEINIT_CB_ID : + hmmc->MspDeInitCallback = HAL_MMC_MspDeInit; + break; + default : + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hmmc->ErrorCode |= HAL_MMC_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup MMC_Exported_Functions_Group3 + * @brief management functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the MMC card + operations and get the related information + +@endverbatim + * @{ + */ + +/** + * @brief Returns information the information of the card which are stored on + * the CID register. + * @param hmmc Pointer to MMC handle + * @param pCID: Pointer to a HAL_MMC_CIDTypedef structure that + * contains all CID register parameters + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCIDTypeDef *pCID) +{ + pCID->ManufacturerID = (uint8_t)((hmmc->CID[0] & 0xFF000000U) >> 24U); + + pCID->OEM_AppliID = (uint16_t)((hmmc->CID[0] & 0x00FFFF00U) >> 8U); + + pCID->ProdName1 = (((hmmc->CID[0] & 0x000000FFU) << 24U) | ((hmmc->CID[1] & 0xFFFFFF00U) >> 8U)); + + pCID->ProdName2 = (uint8_t)(hmmc->CID[1] & 0x000000FFU); + + pCID->ProdRev = (uint8_t)((hmmc->CID[2] & 0xFF000000U) >> 24U); + + pCID->ProdSN = (((hmmc->CID[2] & 0x00FFFFFFU) << 8U) | ((hmmc->CID[3] & 0xFF000000U) >> 24U)); + + pCID->Reserved1 = (uint8_t)((hmmc->CID[3] & 0x00F00000U) >> 20U); + + pCID->ManufactDate = (uint16_t)((hmmc->CID[3] & 0x000FFF00U) >> 8U); + + pCID->CID_CRC = (uint8_t)((hmmc->CID[3] & 0x000000FEU) >> 1U); + + pCID->Reserved2 = 1U; + + return HAL_OK; +} + +/** + * @brief Returns information the information of the card which are stored on + * the CSD register. + * @param hmmc Pointer to MMC handle + * @param pCSD: Pointer to a HAL_MMC_CardCSDTypeDef structure that + * contains all CSD register parameters + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCSDTypeDef *pCSD) +{ + uint32_t block_nbr = 0; + + pCSD->CSDStruct = (uint8_t)((hmmc->CSD[0] & 0xC0000000U) >> 30U); + + pCSD->SysSpecVersion = (uint8_t)((hmmc->CSD[0] & 0x3C000000U) >> 26U); + + pCSD->Reserved1 = (uint8_t)((hmmc->CSD[0] & 0x03000000U) >> 24U); + + pCSD->TAAC = (uint8_t)((hmmc->CSD[0] & 0x00FF0000U) >> 16U); + + pCSD->NSAC = (uint8_t)((hmmc->CSD[0] & 0x0000FF00U) >> 8U); + + pCSD->MaxBusClkFrec = (uint8_t)(hmmc->CSD[0] & 0x000000FFU); + + pCSD->CardComdClasses = (uint16_t)((hmmc->CSD[1] & 0xFFF00000U) >> 20U); + + pCSD->RdBlockLen = (uint8_t)((hmmc->CSD[1] & 0x000F0000U) >> 16U); + + pCSD->PartBlockRead = (uint8_t)((hmmc->CSD[1] & 0x00008000U) >> 15U); + + pCSD->WrBlockMisalign = (uint8_t)((hmmc->CSD[1] & 0x00004000U) >> 14U); + + pCSD->RdBlockMisalign = (uint8_t)((hmmc->CSD[1] & 0x00002000U) >> 13U); + + pCSD->DSRImpl = (uint8_t)((hmmc->CSD[1] & 0x00001000U) >> 12U); + + pCSD->Reserved2 = 0U; /*!< Reserved */ + + if (MMC_ReadExtCSD(hmmc, &block_nbr, 212, 0x0FFFFFFFU) != HAL_OK) /* Field SEC_COUNT [215:212] */ + { + return HAL_ERROR; + } + + if (hmmc->MmcCard.CardType == MMC_LOW_CAPACITY_CARD) + { + pCSD->DeviceSize = (((hmmc->CSD[1] & 0x000003FFU) << 2U) | ((hmmc->CSD[2] & 0xC0000000U) >> 30U)); + + pCSD->MaxRdCurrentVDDMin = (uint8_t)((hmmc->CSD[2] & 0x38000000U) >> 27U); + + pCSD->MaxRdCurrentVDDMax = (uint8_t)((hmmc->CSD[2] & 0x07000000U) >> 24U); + + pCSD->MaxWrCurrentVDDMin = (uint8_t)((hmmc->CSD[2] & 0x00E00000U) >> 21U); + + pCSD->MaxWrCurrentVDDMax = (uint8_t)((hmmc->CSD[2] & 0x001C0000U) >> 18U); + + pCSD->DeviceSizeMul = (uint8_t)((hmmc->CSD[2] & 0x00038000U) >> 15U); + + hmmc->MmcCard.BlockNbr = (pCSD->DeviceSize + 1U) ; + hmmc->MmcCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U)); + hmmc->MmcCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU)); + + hmmc->MmcCard.LogBlockNbr = (hmmc->MmcCard.BlockNbr) * ((hmmc->MmcCard.BlockSize) / MMC_BLOCKSIZE); + hmmc->MmcCard.LogBlockSize = MMC_BLOCKSIZE; + } + else if (hmmc->MmcCard.CardType == MMC_HIGH_CAPACITY_CARD) + { + hmmc->MmcCard.BlockNbr = block_nbr; + hmmc->MmcCard.LogBlockNbr = hmmc->MmcCard.BlockNbr; + hmmc->MmcCard.BlockSize = MMC_BLOCKSIZE; + hmmc->MmcCard.LogBlockSize = hmmc->MmcCard.BlockSize; + } + else + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_UNSUPPORTED_FEATURE; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + pCSD->EraseGrSize = (uint8_t)((hmmc->CSD[2] & 0x00004000U) >> 14U); + + pCSD->EraseGrMul = (uint8_t)((hmmc->CSD[2] & 0x00003F80U) >> 7U); + + pCSD->WrProtectGrSize = (uint8_t)(hmmc->CSD[2] & 0x0000007FU); + + pCSD->WrProtectGrEnable = (uint8_t)((hmmc->CSD[3] & 0x80000000U) >> 31U); + + pCSD->ManDeflECC = (uint8_t)((hmmc->CSD[3] & 0x60000000U) >> 29U); + + pCSD->WrSpeedFact = (uint8_t)((hmmc->CSD[3] & 0x1C000000U) >> 26U); + + pCSD->MaxWrBlockLen = (uint8_t)((hmmc->CSD[3] & 0x03C00000U) >> 22U); + + pCSD->WriteBlockPaPartial = (uint8_t)((hmmc->CSD[3] & 0x00200000U) >> 21U); + + pCSD->Reserved3 = 0; + + pCSD->ContentProtectAppli = (uint8_t)((hmmc->CSD[3] & 0x00010000U) >> 16U); + + pCSD->FileFormatGroup = (uint8_t)((hmmc->CSD[3] & 0x00008000U) >> 15U); + + pCSD->CopyFlag = (uint8_t)((hmmc->CSD[3] & 0x00004000U) >> 14U); + + pCSD->PermWrProtect = (uint8_t)((hmmc->CSD[3] & 0x00002000U) >> 13U); + + pCSD->TempWrProtect = (uint8_t)((hmmc->CSD[3] & 0x00001000U) >> 12U); + + pCSD->FileFormat = (uint8_t)((hmmc->CSD[3] & 0x00000C00U) >> 10U); + + pCSD->ECC = (uint8_t)((hmmc->CSD[3] & 0x00000300U) >> 8U); + + pCSD->CSD_CRC = (uint8_t)((hmmc->CSD[3] & 0x000000FEU) >> 1U); + + pCSD->Reserved4 = 1; + + return HAL_OK; +} + +/** + * @brief Gets the MMC card info. + * @param hmmc Pointer to MMC handle + * @param pCardInfo: Pointer to the HAL_MMC_CardInfoTypeDef structure that + * will contain the MMC card status information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, HAL_MMC_CardInfoTypeDef *pCardInfo) +{ + pCardInfo->CardType = (uint32_t)(hmmc->MmcCard.CardType); + pCardInfo->Class = (uint32_t)(hmmc->MmcCard.Class); + pCardInfo->RelCardAdd = (uint32_t)(hmmc->MmcCard.RelCardAdd); + pCardInfo->BlockNbr = (uint32_t)(hmmc->MmcCard.BlockNbr); + pCardInfo->BlockSize = (uint32_t)(hmmc->MmcCard.BlockSize); + pCardInfo->LogBlockNbr = (uint32_t)(hmmc->MmcCard.LogBlockNbr); + pCardInfo->LogBlockSize = (uint32_t)(hmmc->MmcCard.LogBlockSize); + + return HAL_OK; +} + +/** + * @brief Returns information the information of the card which are stored on + * the Extended CSD register. + * @param hmmc Pointer to MMC handle + * @param pExtCSD Pointer to a memory area (512 bytes) that contains all + * Extended CSD register parameters + * @param Timeout Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_GetCardExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pExtCSD, uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t *tmp_buf; + + if (NULL == pExtCSD) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0; + + /* Initiaize the destination pointer */ + tmp_buf = pExtCSD; + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Send ExtCSD Read command to Card */ + errorstate = SDMMC_CmdSendEXTCSD(hmmc->Instance, 0); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Poll on SDMMC flags */ + while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR | + SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + *tmp_buf = SDMMC_ReadFIFO(hmmc->Instance); + tmp_buf++; + } + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + hmmc->State = HAL_MMC_STATE_READY; + } + + return HAL_OK; +} + +/** + * @brief Enables wide bus operation for the requested card if supported by + * card. + * @param hmmc Pointer to MMC handle + * @param WideMode: Specifies the MMC card wide bus mode + * This parameter can be one of the following values: + * @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer + * @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer + * @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode) +{ + uint32_t count; + SDMMC_InitTypeDef Init; + uint32_t errorstate; + uint32_t response = 0U; + + /* Check the parameters */ + assert_param(IS_SDMMC_BUS_WIDE(WideMode)); + + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Check and update the power class if needed */ + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) != 0U) + { + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) != 0U) + { + errorstate = MMC_PwrClassUpdate(hmmc, WideMode, SDMMC_SPEED_MODE_DDR); + } + else + { + errorstate = MMC_PwrClassUpdate(hmmc, WideMode, SDMMC_SPEED_MODE_HIGH); + } + } + else + { + errorstate = MMC_PwrClassUpdate(hmmc, WideMode, SDMMC_SPEED_MODE_DEFAULT); + } + + if (errorstate == HAL_MMC_ERROR_NONE) + { + if (WideMode == SDMMC_BUS_WIDE_8B) + { + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200U); + } + else if (WideMode == SDMMC_BUS_WIDE_4B) + { + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100U); + } + else if (WideMode == SDMMC_BUS_WIDE_1B) + { + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70000U); + } + else + { + /* WideMode is not a valid argument*/ + errorstate = HAL_MMC_ERROR_PARAM; + } + + /* Check for switch error and violation of the trial number of sending CMD 13 */ + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + else + { + /* Configure the SDMMC peripheral */ + Init = hmmc->Init; + Init.BusWide = WideMode; + (void)SDMMC_Init(hmmc->Instance, Init); + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Configure the speed bus mode + * @param hmmc Pointer to the MMC handle + * @param SpeedMode: Specifies the MMC card speed bus mode + * This parameter can be one of the following values: + * @arg SDMMC_SPEED_MODE_AUTO: Max speed mode supported by the card + * @arg SDMMC_SPEED_MODE_DEFAULT: Default Speed (MMC @ 26MHz) + * @arg SDMMC_SPEED_MODE_HIGH: High Speed (MMC @ 52 MHz) + * @arg SDMMC_SPEED_MODE_DDR: High Speed DDR (MMC DDR @ 52 MHz) + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_MMC_ConfigSpeedBusOperation(MMC_HandleTypeDef *hmmc, uint32_t SpeedMode) +{ + uint32_t tickstart; + HAL_StatusTypeDef status = HAL_OK; + uint32_t device_type; + uint32_t errorstate; + + /* Check the parameters */ + assert_param(IS_SDMMC_SPEED_MODE(SpeedMode)); + + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Field DEVICE_TYPE [196 = 49*4] of Extended CSD register */ + device_type = (hmmc->Ext_CSD[49] & 0x000000FFU); + + switch (SpeedMode) + { + case SDMMC_SPEED_MODE_AUTO: + { + if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS) != 0U) && ((device_type & 0x04U) != 0U)) + { + /* High Speed DDR mode allowed */ + errorstate = MMC_HighSpeed(hmmc, ENABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + else + { + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_CLKDIV) != 0U) + { + /* DDR mode not supported with CLKDIV = 0 */ + errorstate = MMC_DDR_Mode(hmmc, ENABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + } + } + } + else if ((device_type & 0x02U) != 0U) + { + /* High Speed mode allowed */ + errorstate = MMC_HighSpeed(hmmc, ENABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + } + else + { + /* Nothing to do : keep current speed */ + } + break; + } + case SDMMC_SPEED_MODE_DDR: + { + if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS) != 0U) && ((device_type & 0x04U) != 0U)) + { + /* High Speed DDR mode allowed */ + errorstate = MMC_HighSpeed(hmmc, ENABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + else + { + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_CLKDIV) != 0U) + { + /* DDR mode not supported with CLKDIV = 0 */ + errorstate = MMC_DDR_Mode(hmmc, ENABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + } + } + } + else + { + /* High Speed DDR mode not allowed */ + hmmc->ErrorCode |= HAL_MMC_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_HIGH: + { + if ((device_type & 0x02U) != 0U) + { + /* High Speed mode allowed */ + errorstate = MMC_HighSpeed(hmmc, ENABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + } + else + { + /* High Speed mode not allowed */ + hmmc->ErrorCode |= HAL_MMC_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_DEFAULT: + { + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) != 0U) + { + /* High Speed DDR mode activated */ + errorstate = MMC_DDR_Mode(hmmc, DISABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + } + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) != 0U) + { + /* High Speed mode activated */ + errorstate = MMC_HighSpeed(hmmc, DISABLE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + } + break; + } + default: + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + status = HAL_ERROR; + break; + } + + /* Verify that MMC card is ready to use after Speed mode switch*/ + tickstart = HAL_GetTick(); + while ((HAL_MMC_GetCardState(hmmc) != HAL_MMC_CARD_TRANSFER)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + return status; +} + +/** + * @brief Gets the current mmc card data state. + * @param hmmc pointer to MMC handle + * @retval Card state + */ +HAL_MMC_CardStateTypeDef HAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc) +{ + uint32_t cardstate; + uint32_t errorstate; + uint32_t resp1 = 0U; + + errorstate = MMC_SendStatus(hmmc, &resp1); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + cardstate = ((resp1 >> 9U) & 0x0FU); + + return (HAL_MMC_CardStateTypeDef)cardstate; +} + +/** + * @brief Abort the current transfer and disable the MMC. + * @param hmmc pointer to a MMC_HandleTypeDef structure that contains + * the configuration information for MMC module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_Abort(MMC_HandleTypeDef *hmmc) +{ + uint32_t error_code; + uint32_t tickstart; + + if (hmmc->State == HAL_MMC_STATE_BUSY) + { + /* DIsable All interrupts */ + __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /*we will send the CMD12 in all cases in order to stop the data transfers*/ + /*In case the data transfer just finished, the external memory will not respond + and will return HAL_MMC_ERROR_CMD_RSP_TIMEOUT*/ + /*In case the data transfer aborted , the external memory will respond and will return HAL_MMC_ERROR_NONE*/ + /*Other scenario will return HAL_ERROR*/ + + hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); + error_code = hmmc->ErrorCode; + if ((error_code != HAL_MMC_ERROR_NONE) && (error_code != HAL_MMC_ERROR_CMD_RSP_TIMEOUT)) + { + return HAL_ERROR; + } + + tickstart = HAL_GetTick(); + if ((hmmc->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_CARD) + { + if (hmmc->ErrorCode == HAL_MMC_ERROR_NONE) + { + while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DABORT | SDMMC_FLAG_BUSYD0END)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + } + + if (hmmc->ErrorCode == HAL_MMC_ERROR_CMD_RSP_TIMEOUT) + { + while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DATAEND)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + else if ((hmmc->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_SDMMC) + { + while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DABORT | SDMMC_FLAG_DATAEND)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + hmmc->ErrorCode = HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + } + else + { + /* Nothing to do*/ + } + + /*The reason of all these while conditions previously is that we need to wait the SDMMC and clear + the appropriate flags that will be set depending of the abort/non abort of the memory */ + /*Not waiting the SDMMC flags will cause the next SDMMC_DISABLE_IDMA to not get cleared and will result + in next SDMMC read/write operation to fail */ + + /*SDMMC ready for clear data flags*/ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + /* If IDMA Context, disable Internal DMA */ + hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + hmmc->State = HAL_MMC_STATE_READY; + + /* Initialize the MMC operation */ + hmmc->Context = MMC_CONTEXT_NONE; + } + return HAL_OK; +} +/** + * @brief Abort the current transfer and disable the MMC (IT mode). + * @param hmmc pointer to a MMC_HandleTypeDef structure that contains + * the configuration information for MMC module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc) +{ + HAL_MMC_CardStateTypeDef CardState; + + /* DIsable All interrupts */ + __HAL_MMC_DISABLE_IT(hmmc, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); + + /* If IDMA Context, disable Internal DMA */ + hmmc->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + /* Clear All flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + CardState = HAL_MMC_GetCardState(hmmc); + hmmc->State = HAL_MMC_STATE_READY; + + if ((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) + { + hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); + } + if (hmmc->ErrorCode != HAL_MMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { +#if defined (USE_HAL_MMC_REGISTER_CALLBACKS) && (USE_HAL_MMC_REGISTER_CALLBACKS == 1U) + hmmc->AbortCpltCallback(hmmc); +#else + HAL_MMC_AbortCallback(hmmc); +#endif /* USE_HAL_MMC_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @brief Perform specific commands sequence for the different type of erase. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @param hmmc Pointer to MMC handle + * @param EraseType Specifies the type of erase to be performed + * This parameter can be one of the following values: + * @arg HAL_MMC_TRIM Erase the write blocks identified by CMD35 & 36 + * @arg HAL_MMC_ERASE Erase the erase groups identified by CMD35 & 36 + * @arg HAL_MMC_DISCARD Discard the write blocks identified by CMD35 & 36 + * @arg HAL_MMC_SECURE_ERASE Perform a secure purge according SRT on the erase groups identified + * by CMD35 & 36 + * @arg HAL_MMC_SECURE_TRIM_STEP1 Mark the write blocks identified by CMD35 & 36 for secure erase + * @arg HAL_MMC_SECURE_TRIM_STEP2 Perform a secure purge according SRT on the write blocks + * previously identified + * @param BlockStartAdd Start Block address + * @param BlockEndAdd End Block address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_EraseSequence(MMC_HandleTypeDef *hmmc, uint32_t EraseType, + uint32_t BlockStartAdd, uint32_t BlockEndAdd) +{ + uint32_t errorstate; + uint32_t start_add = BlockStartAdd; + uint32_t end_add = BlockEndAdd; + uint32_t tickstart = HAL_GetTick(); + + /* Check the erase type value is correct */ + assert_param(IS_MMC_ERASE_TYPE(EraseType)); + + /* Check the coherence between start and end address */ + if (end_add < start_add) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + /* Check that the end address is not out of range of device memory */ + if (end_add > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if (((start_add % 8U) != 0U) || ((end_add % 8U) != 0U)) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + /* Check if the card command class supports erase command */ + if (((hmmc->MmcCard.Class) & SDMMC_CCCC_ERASE) == 0U) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; + return HAL_ERROR; + } + + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Check that the card is not locked */ + if ((SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_LOCK_UNLOCK_FAILED; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* In case of low capacity card, the address is not block number but bytes */ + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + start_add *= MMC_BLOCKSIZE; + end_add *= MMC_BLOCKSIZE; + } + + /* Send CMD35 MMC_ERASE_GRP_START with start address as argument */ + errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, start_add); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Send CMD36 MMC_ERASE_GRP_END with end address as argument */ + errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, end_add); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Send CMD38 ERASE with erase type as argument */ + errorstate = SDMMC_CmdErase(hmmc->Instance, EraseType); + if (errorstate == HAL_MMC_ERROR_NONE) + { + if ((EraseType == HAL_MMC_SECURE_ERASE) || (EraseType == HAL_MMC_SECURE_TRIM_STEP2)) + { + /* Wait that the device is ready by checking the D0 line */ + while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_MAXERASETIMEOUT) + { + errorstate = HAL_MMC_ERROR_TIMEOUT; + } + } + + /* Clear the flag corresponding to end D0 bus line */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + } + } + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + /* Manage errors */ + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + + if (errorstate != HAL_MMC_ERROR_TIMEOUT) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + else + { + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Perform sanitize operation on the device. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @param hmmc Pointer to MMC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_Sanitize(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate; + uint32_t response = 0U; + uint32_t count; + uint32_t tickstart = HAL_GetTick(); + + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Index : 165 - Value : 0x01 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03A50100U); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Wait that the device is ready by checking the D0 line */ + while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_MAXERASETIMEOUT) + { + errorstate = HAL_MMC_ERROR_TIMEOUT; + } + } + + /* Clear the flag corresponding to end D0 bus line */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + /* Manage errors */ + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + + if (errorstate != HAL_MMC_ERROR_TIMEOUT) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + else + { + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Configure the Secure Removal Type (SRT) in the Extended CSD register. + * @note This API should be followed by a check on the card state through + * HAL_MMC_GetCardState(). + * @param hmmc Pointer to MMC handle + * @param SRTMode Specifies the type of erase to be performed + * This parameter can be one of the following values: + * @arg HAL_MMC_SRT_ERASE Information removed by an erase + * @arg HAL_MMC_SRT_WRITE_CHAR_ERASE Information removed by an overwriting with a character + * followed by an erase + * @arg HAL_MMC_SRT_WRITE_CHAR_COMPL_RANDOM Information removed by an overwriting with a character, + * its complement then a random character + * @arg HAL_MMC_SRT_VENDOR_DEFINED Information removed using a vendor defined + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_ConfigSecRemovalType(MMC_HandleTypeDef *hmmc, uint32_t SRTMode) +{ + uint32_t srt; + uint32_t errorstate; + uint32_t response = 0U; + uint32_t count; + + /* Check the erase type value is correct */ + assert_param(IS_MMC_SRT_TYPE(SRTMode)); + + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Get the supported values by the device */ + if (HAL_MMC_GetSupportedSecRemovalType(hmmc, &srt) == HAL_OK) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Check the value passed as parameter is supported by the device */ + if ((SRTMode & srt) != 0U) + { + /* Index : 16 - Value : SRTMode */ + srt |= ((POSITION_VAL(SRTMode)) << 4U); + errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03100000U | (srt << 8U))); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + else + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + } + else + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + + /* Manage errors */ + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + return HAL_ERROR; + } + else + { + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Gets the supported values of the the Secure Removal Type (SRT). + * @param hmmc pointer to MMC handle + * @param SupportedSRT pointer for supported SRT value + * This parameter is a bit field of the following values: + * @arg HAL_MMC_SRT_ERASE Information removed by an erase + * @arg HAL_MMC_SRT_WRITE_CHAR_ERASE Information removed by an overwriting with a character followed + * by an erase + * @arg HAL_MMC_SRT_WRITE_CHAR_COMPL_RANDOM Information removed by an overwriting with a character, + * its complement then a random character + * @arg HAL_MMC_SRT_VENDOR_DEFINED Information removed using a vendor defined + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_GetSupportedSecRemovalType(MMC_HandleTypeDef *hmmc, uint32_t *SupportedSRT) +{ + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Read field SECURE_REMOVAL_TYPE [16 = 4*4] of the Extended CSD register */ + *SupportedSRT = (hmmc->Ext_CSD[4] & 0x0000000FU); /* Bits [3:0] of field 16 */ + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Switch the device from Standby State to Sleep State. + * @param hmmc pointer to MMC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_SleepDevice(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate, + sleep_timeout, + timeout, + count, + response = 0U ; + uint32_t tickstart = HAL_GetTick(); + + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Set the power-off notification to powered-on : Ext_CSD[34] = 1 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03220100U)); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { + /* Set the power-off notification to sleep notification : Ext_CSD[34] = 4 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03220400U)); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Field SLEEP_NOTIFICATION_TIME [216] */ + sleep_timeout = ((hmmc->Ext_CSD[(MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_INDEX / 4)] >> + MMC_EXT_CSD_SLEEP_NOTIFICATION_TIME_POS) & 0x000000FFU); + + /* Sleep/Awake Timeout = 10us * 2^SLEEP_NOTIFICATION_TIME */ + /* In HAL, the tick interrupt occurs each ms */ + if ((sleep_timeout == 0U) || (sleep_timeout > 0x17U)) + { + sleep_timeout = 0x17U; /* Max register value defined is 0x17 */ + } + timeout = (((1UL << sleep_timeout) / 100U) + 1U); + + /* Wait that the device is ready by checking the D0 line */ + while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) + { + if ((HAL_GetTick() - tickstart) >= timeout) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + } + + /* Clear the flag corresponding to end D0 bus line */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, + (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { + /* Switch the device in stand-by mode */ + (void)SDMMC_CmdSelDesel(hmmc->Instance, 0U); + + /* Field S_A_TIEMOUT [217] */ + sleep_timeout = ((hmmc->Ext_CSD[(MMC_EXT_CSD_S_A_TIMEOUT_INDEX / 4)] >> + MMC_EXT_CSD_S_A_TIMEOUT_POS) & 0x000000FFU); + + /* Sleep/Awake Timeout = 100ns * 2^S_A_TIMEOUT */ + /* In HAL, the tick interrupt occurs each ms */ + if ((sleep_timeout == 0U) || (sleep_timeout > 0x17U)) + { + sleep_timeout = 0x17U; /* Max register value defined is 0x17 */ + } + timeout = (((1UL << sleep_timeout) / 10000U) + 1U); + + if (HAL_MMC_GetCardState(hmmc) == HAL_MMC_CARD_STANDBY) + { + /* Send CMD5 CMD_MMC_SLEEP_AWAKE with RCA and SLEEP as argument */ + errorstate = SDMMC_CmdSleepMmc(hmmc->Instance, + ((hmmc->MmcCard.RelCardAdd << 16U) | (0x1U << 15U))); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Wait that the device is ready by checking the D0 line */ + while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) + { + if ((HAL_GetTick() - tickstart) >= timeout) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + } + + /* Clear the flag corresponding to end D0 bus line */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + } + } + else + { + errorstate = SDMMC_ERROR_REQUEST_NOT_APPLICABLE; + } + } + } + else + { + /* Nothing to do */ + } + } + } + } + } + else + { + /* Nothing to do */ + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + /* Manage errors */ + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + + if (errorstate != HAL_MMC_ERROR_TIMEOUT) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + else + { + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Switch the device from Sleep State to Standby State. + * @param hmmc pointer to MMC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_AwakeDevice(MMC_HandleTypeDef *hmmc) +{ + uint32_t errorstate; + uint32_t sleep_timeout; + uint32_t timeout; + uint32_t count; + uint32_t response = 0U; + uint32_t tickstart = HAL_GetTick(); + + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Field S_A_TIEMOUT [217] */ + sleep_timeout = ((hmmc->Ext_CSD[(MMC_EXT_CSD_S_A_TIMEOUT_INDEX / 4)] >> MMC_EXT_CSD_S_A_TIMEOUT_POS) & + 0x000000FFU); + + /* Sleep/Awake Timeout = 100ns * 2^S_A_TIMEOUT */ + /* In HAL, the tick interrupt occurs each ms */ + if ((sleep_timeout == 0U) || (sleep_timeout > 0x17U)) + { + sleep_timeout = 0x17U; /* Max register value defined is 0x17 */ + } + timeout = (((1UL << sleep_timeout) / 10000U) + 1U); + + /* Send CMD5 CMD_MMC_SLEEP_AWAKE with RCA and AWAKE as argument */ + errorstate = SDMMC_CmdSleepMmc(hmmc->Instance, (hmmc->MmcCard.RelCardAdd << 16U)); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Wait that the device is ready by checking the D0 line */ + while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) + { + if ((HAL_GetTick() - tickstart) >= timeout) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + } + + /* Clear the flag corresponding to end D0 bus line */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + + if (errorstate == HAL_MMC_ERROR_NONE) + { + if (HAL_MMC_GetCardState(hmmc) == HAL_MMC_CARD_STANDBY) + { + /* Switch the device in transfer mode */ + errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (hmmc->MmcCard.RelCardAdd << 16U)); + if (errorstate == HAL_MMC_ERROR_NONE) + { + if (HAL_MMC_GetCardState(hmmc) == HAL_MMC_CARD_TRANSFER) + { + /* Set the power-off notification to powered-on : Ext_CSD[34] = 1 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03220100U)); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, + (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + } + else + { + /* NOthing to do */ + } + } + } + else + { + errorstate = SDMMC_ERROR_REQUEST_NOT_APPLICABLE; + } + } + } + else + { + errorstate = SDMMC_ERROR_REQUEST_NOT_APPLICABLE; + } + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + /* Manage errors */ + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + + if (errorstate != HAL_MMC_ERROR_TIMEOUT) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + else + { + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} +/** + * @} + */ + +/** + * @} + */ + +/* Private function ----------------------------------------------------------*/ +/** @addtogroup MMC_Private_Functions + * @{ + */ + +/** + * @brief Initializes the mmc card. + * @param hmmc Pointer to MMC handle + * @retval MMC Card error state + */ +static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc) +{ + HAL_MMC_CardCSDTypeDef CSD; + uint32_t errorstate; + uint16_t mmc_rca = 2U; + MMC_InitTypeDef Init; + + /* Check the power State */ + if (SDMMC_GetPowerState(hmmc->Instance) == 0U) + { + /* Power off */ + return HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; + } + + /* Send CMD2 ALL_SEND_CID */ + errorstate = SDMMC_CmdSendCID(hmmc->Instance); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card identification number data */ + hmmc->CID[0U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + hmmc->CID[1U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2); + hmmc->CID[2U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP3); + hmmc->CID[3U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP4); + } + + /* Send CMD3 SET_REL_ADDR with RCA = 2 (should be greater than 1) */ + /* MMC Card publishes its RCA. */ + errorstate = SDMMC_CmdSetRelAddMmc(hmmc->Instance, mmc_rca); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return errorstate; + } + + /* Get the MMC card RCA */ + hmmc->MmcCard.RelCardAdd = mmc_rca; + + /* Send CMD9 SEND_CSD with argument as card's RCA */ + errorstate = SDMMC_CmdSendCSD(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card Specific Data */ + hmmc->CSD[0U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + hmmc->CSD[1U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2); + hmmc->CSD[2U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP3); + hmmc->CSD[3U] = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP4); + } + + /* Get the Card Class */ + hmmc->MmcCard.Class = (SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP2) >> 20U); + + /* Select the Card */ + errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return errorstate; + } + + /* Get CSD parameters */ + if (HAL_MMC_GetCardCSD(hmmc, &CSD) != HAL_OK) + { + return hmmc->ErrorCode; + } + + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + /* Get Extended CSD parameters */ + if (HAL_MMC_GetCardExtCSD(hmmc, hmmc->Ext_CSD, SDMMC_DATATIMEOUT) != HAL_OK) + { + return hmmc->ErrorCode; + } + + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + /* Configure the SDMMC peripheral */ + Init = hmmc->Init; + Init.BusWide = SDMMC_BUS_WIDE_1B; + (void)SDMMC_Init(hmmc->Instance, Init); + + /* All cards are initialized */ + return HAL_MMC_ERROR_NONE; +} + +/** + * @brief Enquires cards about their operating voltage and configures clock + * controls and stores MMC information that will be needed in future + * in the MMC handle. + * @param hmmc Pointer to MMC handle + * @retval error state + */ +static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc) +{ + __IO uint32_t count = 0U; + uint32_t response = 0U; + uint32_t validvoltage = 0U; + uint32_t errorstate; + + /* CMD0: GO_IDLE_STATE */ + errorstate = SDMMC_CmdGoIdleState(hmmc->Instance); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return errorstate; + } + + while (validvoltage == 0U) + { + if (count++ == SDMMC_MAX_VOLT_TRIAL) + { + return HAL_MMC_ERROR_INVALID_VOLTRANGE; + } + + /* SEND CMD1 APP_CMD with voltage range as argument */ + errorstate = SDMMC_CmdOpCondition(hmmc->Instance, MMC_VOLTAGE_RANGE); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return HAL_MMC_ERROR_UNSUPPORTED_FEATURE; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + + /* Get operating voltage*/ + validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); + } + + /* When power routine is finished and command returns valid voltage */ + if (((response & (0xFF000000U)) >> 24) == 0xC0U) + { + hmmc->MmcCard.CardType = MMC_HIGH_CAPACITY_CARD; + } + else + { + hmmc->MmcCard.CardType = MMC_LOW_CAPACITY_CARD; + } + + return HAL_MMC_ERROR_NONE; +} + +/** + * @brief Turns the SDMMC output signals off. + * @param hmmc Pointer to MMC handle + * @retval None + */ +static void MMC_PowerOFF(MMC_HandleTypeDef *hmmc) +{ + /* Set Power State to OFF */ + (void)SDMMC_PowerState_OFF(hmmc->Instance); +} + +/** + * @brief Returns the current card's status. + * @param hmmc Pointer to MMC handle + * @param pCardStatus: pointer to the buffer that will contain the MMC card + * status (Card Status register) + * @retval error state + */ +static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus) +{ + uint32_t errorstate; + + if (pCardStatus == NULL) + { + return HAL_MMC_ERROR_PARAM; + } + + /* Send Status command */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + return errorstate; + } + + /* Get MMC card status */ + *pCardStatus = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + + return HAL_MMC_ERROR_NONE; +} + +/** + * @brief Reads extended CSD register to get the sectors number of the device + * @param hmmc Pointer to MMC handle + * @param pFieldData: Pointer to the read buffer + * @param FieldIndex: Index of the field to be read + * @param Timeout Specify timeout value + * @retval HAL status + */ +static HAL_StatusTypeDef MMC_ReadExtCSD(MMC_HandleTypeDef *hmmc, uint32_t *pFieldData, + uint16_t FieldIndex, uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t i = 0; + uint32_t tmp_data; + + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0; + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_ENABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdSendEXTCSD(hmmc->Instance, 0); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Poll on SDMMC flags */ + while (!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | + SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + tmp_data = SDMMC_ReadFIFO(hmmc->Instance); + /* eg : SEC_COUNT : FieldIndex = 212 => i+count = 53 */ + /* DEVICE_TYPE : FieldIndex = 196 => i+count = 49 */ + if ((i + count) == ((uint32_t)FieldIndex / 4U)) + { + *pFieldData = tmp_data; + } + } + i += 8U; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->ErrorCode |= errorstate; + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Wrap up reading in non-blocking mode. + * @param hmmc pointer to a MMC_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void MMC_Read_IT(MMC_HandleTypeDef *hmmc) +{ + uint32_t count; + uint32_t data; + uint8_t *tmp; + + tmp = hmmc->pRxBuffPtr; + + if (hmmc->RxXferSize >= SDMMC_FIFO_SIZE) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tmp = (uint8_t)(data & 0xFFU); + tmp++; + *tmp = (uint8_t)((data >> 8U) & 0xFFU); + tmp++; + *tmp = (uint8_t)((data >> 16U) & 0xFFU); + tmp++; + *tmp = (uint8_t)((data >> 24U) & 0xFFU); + tmp++; + } + + hmmc->pRxBuffPtr = tmp; + hmmc->RxXferSize -= SDMMC_FIFO_SIZE; + } +} + +/** + * @brief Wrap up writing in non-blocking mode. + * @param hmmc pointer to a MMC_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void MMC_Write_IT(MMC_HandleTypeDef *hmmc) +{ + uint32_t count; + uint32_t data; + const uint8_t *tmp; + + tmp = hmmc->pTxBuffPtr; + + if (hmmc->TxXferSize >= SDMMC_FIFO_SIZE) + { + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*tmp); + tmp++; + data |= ((uint32_t)(*tmp) << 8U); + tmp++; + data |= ((uint32_t)(*tmp) << 16U); + tmp++; + data |= ((uint32_t)(*tmp) << 24U); + tmp++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + } + + hmmc->pTxBuffPtr = tmp; + hmmc->TxXferSize -= SDMMC_FIFO_SIZE; + } +} + +/** + * @brief Switches the MMC card to high speed mode. + * @param hmmc MMC handle + * @param state: State of high speed mode + * @retval MMC Card error state + */ +static uint32_t MMC_HighSpeed(MMC_HandleTypeDef *hmmc, FunctionalState state) +{ + uint32_t errorstate = HAL_MMC_ERROR_NONE; + uint32_t response = 0U; + uint32_t count; + uint32_t sdmmc_clk; + SDMMC_InitTypeDef Init; + + if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) != 0U) && (state == DISABLE)) + { + errorstate = MMC_PwrClassUpdate(hmmc, (hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS), SDMMC_SPEED_MODE_DEFAULT); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Index : 185 - Value : 0 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B90000U); + } + } + + if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_BUSSPEED) == 0U) && (state != DISABLE)) + { + errorstate = MMC_PwrClassUpdate(hmmc, (hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS), SDMMC_SPEED_MODE_HIGH); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Index : 185 - Value : 1 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B90100U); + } + } + + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { + /* Configure high speed */ + Init.ClockEdge = hmmc->Init.ClockEdge; + Init.ClockPowerSave = hmmc->Init.ClockPowerSave; + Init.BusWide = (hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS); + Init.HardwareFlowControl = hmmc->Init.HardwareFlowControl; + + if (state == DISABLE) + { + Init.ClockDiv = hmmc->Init.ClockDiv; + (void)SDMMC_Init(hmmc->Instance, Init); + + CLEAR_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_BUSSPEED); + } + else + { + /* High Speed Clock should be less or equal to 52MHz*/ + sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); + + if (sdmmc_clk == 0U) + { + errorstate = SDMMC_ERROR_INVALID_PARAMETER; + } + else + { + if (sdmmc_clk <= MMC_HIGH_SPEED_FREQ) + { + Init.ClockDiv = 0; + } + else + { + Init.ClockDiv = (sdmmc_clk / (2U * MMC_HIGH_SPEED_FREQ)) + 1U; + } + (void)SDMMC_Init(hmmc->Instance, Init); + + SET_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_BUSSPEED); + } + } + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + + return errorstate; +} + +/** + * @brief Switches the MMC card to Double Data Rate (DDR) mode. + * @param hmmc MMC handle + * @param state: State of DDR mode + * @retval MMC Card error state + */ +static uint32_t MMC_DDR_Mode(MMC_HandleTypeDef *hmmc, FunctionalState state) +{ + uint32_t errorstate = HAL_MMC_ERROR_NONE; + uint32_t response = 0U; + uint32_t count; + + if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) != 0U) && (state == DISABLE)) + { + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS_0) != 0U) + { + errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_4B, SDMMC_SPEED_MODE_HIGH); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Index : 183 - Value : 1 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100U); + } + } + else + { + errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_8B, SDMMC_SPEED_MODE_HIGH); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Index : 183 - Value : 2 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200U); + } + } + } + + if (((hmmc->Instance->CLKCR & SDMMC_CLKCR_DDR) == 0U) && (state != DISABLE)) + { + if ((hmmc->Instance->CLKCR & SDMMC_CLKCR_WIDBUS_0) != 0U) + { + errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_4B, SDMMC_SPEED_MODE_DDR); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Index : 183 - Value : 5 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70500U); + } + } + else + { + errorstate = MMC_PwrClassUpdate(hmmc, SDMMC_BUS_WIDE_8B, SDMMC_SPEED_MODE_DDR); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Index : 183 - Value : 6 */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70600U); + } + } + } + + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { + /* Configure DDR mode */ + if (state == DISABLE) + { + CLEAR_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_DDR); + } + else + { + SET_BIT(hmmc->Instance->CLKCR, SDMMC_CLKCR_DDR); + } + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + + return errorstate; +} + +/** + * @brief Update the power class of the device. + * @param hmmc MMC handle + * @param Wide Wide of MMC bus + * @param Speed Speed of the MMC bus + * @retval MMC Card error state + */ +static uint32_t MMC_PwrClassUpdate(MMC_HandleTypeDef *hmmc, uint32_t Wide, uint32_t Speed) +{ + uint32_t count; + uint32_t response = 0U; + uint32_t errorstate = HAL_MMC_ERROR_NONE; + uint32_t power_class; + uint32_t supported_pwr_class; + + if ((Wide == SDMMC_BUS_WIDE_8B) || (Wide == SDMMC_BUS_WIDE_4B)) + { + power_class = 0U; /* Default value after power-on or software reset */ + + /* Read the PowerClass field of the Extended CSD register */ + if (MMC_ReadExtCSD(hmmc, &power_class, 187, SDMMC_DATATIMEOUT) != HAL_OK) /* Field POWER_CLASS [187] */ + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + else + { + power_class = ((power_class >> 24U) & 0x000000FFU); + } + + /* Get the supported PowerClass field of the Extended CSD register */ + if (Speed == SDMMC_SPEED_MODE_DDR) + { + /* Field PWR_CL_DDR_52_xxx [238 or 239] */ + supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_DDR_52_INDEX / 4)] >> MMC_EXT_CSD_PWR_CL_DDR_52_POS) & + 0x000000FFU); + } + else if (Speed == SDMMC_SPEED_MODE_HIGH) + { + /* Field PWR_CL_52_xxx [200 or 202] */ + supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_52_INDEX / 4)] >> MMC_EXT_CSD_PWR_CL_52_POS) & + 0x000000FFU); + } + else + { + /* Field PWR_CL_26_xxx [201 or 203] */ + supported_pwr_class = ((hmmc->Ext_CSD[(MMC_EXT_CSD_PWR_CL_26_INDEX / 4)] >> MMC_EXT_CSD_PWR_CL_26_POS) & + 0x000000FFU); + } + + if (errorstate == HAL_MMC_ERROR_NONE) + { + if (Wide == SDMMC_BUS_WIDE_8B) + { + /* Bit [7:4]: power class for 8-bits bus configuration - Bit [3:0]: power class for 4-bits bus configuration */ + supported_pwr_class = (supported_pwr_class >> 4U); + } + + if ((power_class & 0x0FU) != (supported_pwr_class & 0x0FU)) + { + /* Need to change current power class */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, (0x03BB0000U | ((supported_pwr_class & 0x0FU) << 8U))); + + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + } + } + + return errorstate; +} + +/** + * @brief Used to select the partition. + * @param hmmc Pointer to MMC handle + * @param Partition Partition type + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_SwitchPartition(MMC_HandleTypeDef *hmmc, HAL_MMC_PartitionTypeDef Partition) +{ + uint32_t errorstate; + uint32_t response = 0U; + uint32_t count; + uint32_t tickstart = HAL_GetTick(); + uint32_t arg = Partition | 0x03B30000U; + + /* Check the state of the driver */ + if (hmmc->State == HAL_MMC_STATE_READY) + { + /* Change State */ + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Index : 179 - Value : partition */ + errorstate = SDMMC_CmdSwitch(hmmc->Instance, arg); + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* Wait that the device is ready by checking the D0 line */ + while ((!__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_BUSYD0END)) && (errorstate == HAL_MMC_ERROR_NONE)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_MAXERASETIMEOUT) + { + errorstate = HAL_MMC_ERROR_TIMEOUT; + } + } + + /* Clear the flag corresponding to end D0 bus line */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_FLAG_BUSYD0END); + + if (errorstate == HAL_MMC_ERROR_NONE) + { + /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ + count = SDMMC_MAX_TRIAL; + do + { + errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); + if (errorstate != HAL_MMC_ERROR_NONE) + { + break; + } + + /* Get command response */ + response = SDMMC_GetResponse(hmmc->Instance, SDMMC_RESP1); + count--; + } while (((response & 0x100U) == 0U) && (count != 0U)); + + /* Check the status after the switch command execution */ + if ((count != 0U) && (errorstate == HAL_MMC_ERROR_NONE)) + { + /* Check the bit SWITCH_ERROR of the device status */ + if ((response & 0x80U) != 0U) + { + errorstate = SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } + } + else if (count == 0U) + { + errorstate = SDMMC_ERROR_TIMEOUT; + } + else + { + /* Nothing to do */ + } + } + } + + /* Change State */ + hmmc->State = HAL_MMC_STATE_READY; + + /* Manage errors */ + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + + if (errorstate != HAL_MMC_ERROR_TIMEOUT) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + else + { + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Allows to program the authentication key within the RPMB partition + * @param hmmc Pointer to MMC handle + * @param pKey pointer to the authentication key (32 bytes) + * @param Timeout Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_RPMB_ProgramAuthenticationKey(MMC_HandleTypeDef *hmmc, const uint8_t *pKey, uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t byte_count = 0; + uint32_t data; + uint32_t dataremaining; + uint8_t tail_pack[12] = {0}; + uint8_t zero_pack[4] = {0}; + const uint8_t *rtempbuff; + uint8_t *tempbuff; + + tail_pack[11] = 0x01; + + if (NULL == pKey) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x80000001U); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + { + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); + } + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Write block(s) in polling mode */ + rtempbuff = zero_pack; + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*rtempbuff); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 8U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 16U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 24U); + rtempbuff++; + byte_count++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + if (byte_count < MMC_RPMB_KEYMAC_POSITION) + { + rtempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_KEYMAC_POSITION) + { + rtempbuff = pKey; + } + else if ((byte_count < MMC_RPMB_WRITE_COUNTER_POSITION) && \ + (byte_count >= MMC_RPMB_DATA_POSITION)) + { + rtempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + rtempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Read Response Packet */ + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + /* Poll on SDMMC flags */ + tempbuff = zero_pack; + byte_count = 0; + + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + byte_count++; + if (byte_count < MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + /* Check result of operation */ + if ((tail_pack[9] != 0x00U) || (tail_pack[10] != 0x01U)) + { + hmmc->RPMBErrorCode |= tail_pack[9]; + return HAL_ERROR; + } + + return HAL_OK; + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Allows to get the value of write counter within the RPMB partition. + * @param hmmc Pointer to MMC handle + * @param pNonce pointer to the value of nonce (16 bytes) + * @param Timeout Specify timeout value + * @retval write counter value. + */ +uint32_t HAL_MMC_RPMB_GetWriteCounter(MMC_HandleTypeDef *hmmc, uint8_t *pNonce, uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t byte_count = 0; + uint32_t data; + uint32_t dataremaining; + uint8_t tail_pack[12] = {0}; + uint8_t zero_pack[4] = {0}; + uint8_t echo_nonce[16] = {0}; + uint8_t *tempbuff = zero_pack; + + tail_pack[11] = 0x02; + + if (NULL == pNonce) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001U); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + + /* Send Request Packet */ + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*tempbuff); + tempbuff++; + byte_count++; + data |= ((uint32_t)(*tempbuff) << 8U); + tempbuff++; + byte_count++; + data |= ((uint32_t)(*tempbuff) << 16U); + tempbuff++; + byte_count++; + data |= ((uint32_t)(*tempbuff) << 24U); + tempbuff++; + byte_count++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + if (byte_count < MMC_RPMB_NONCE_POSITION) + { + tempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_NONCE_POSITION) + { + tempbuff = (uint8_t *)pNonce; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Read Response Packt */ + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001U); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + /* Poll on SDMMC flags */ + tempbuff = zero_pack; + + byte_count = 0; + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + byte_count++; + if (byte_count < MMC_RPMB_NONCE_POSITION) + { + tempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_NONCE_POSITION) + { + tempbuff = echo_nonce; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = HAL_MMC_STATE_READY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + for (uint8_t i = 0; i < 16U; i++) + { + if (pNonce[i] != echo_nonce[i]) + { + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } + } + + return ((uint32_t)tail_pack[3] | ((uint32_t)tail_pack[2] << 8) | ((uint32_t)tail_pack[1] << 16) | \ + ((uint32_t)tail_pack[0] << 24)); + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + hmmc->RPMBErrorCode |= HAL_MMC_ERROR_RPMB_COUNTER_FAILURE; + return 0; + } +} + +/** + * @brief Allows to write block(s) to a specified address in the RPMB partition. The Data + * transfer is managed by polling mode. + * @param hmmc Pointer to MMC handle + * @param pData Pointer to the buffer that will contain the data to transmit + * @param BlockAdd Block Address where data will be written + * @param NumberOfBlocks Number of blocks to write + * @param pMAC Pointer to the authentication MAC buffer + * @param Timeout Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_RPMB_WriteBlocks(MMC_HandleTypeDef *hmmc, const uint8_t *pData, uint16_t BlockAdd, + uint16_t NumberOfBlocks, const uint8_t *pMAC, uint32_t Timeout) +{ + + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t byte_count = 0; + uint32_t data; + uint32_t dataremaining; + uint8_t tail_pack[12] = {0}; + uint8_t zero_pack[4] = {0}; + uint8_t echo_nonce[16] = {0}; + const uint8_t local_nonce[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x00, 0x01, 0x02, 0x03, 0x04, 0x08 + }; + const uint8_t *rtempbuff; + uint8_t *tempbuff; + uint32_t arg = 0x80000000U; + uint32_t offset = 0; + + if ((NumberOfBlocks != 0x1U) && (NumberOfBlocks != 0x2U) && (NumberOfBlocks != 0x20U)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + if ((NULL == pData) || (NULL == pMAC)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; + return HAL_ERROR; + } + + tail_pack[11] = 0x02; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001U); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Send Request Packet */ + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Write block(s) in polling mode */ + rtempbuff = zero_pack; + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*rtempbuff); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 8U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 16U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 24U); + rtempbuff++; + byte_count++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + if (byte_count < MMC_RPMB_NONCE_POSITION) + { + rtempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_NONCE_POSITION) + { + rtempbuff = local_nonce; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + rtempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Read Response Packt */ + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 0x00000001); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + /* Poll on SDMMC flags */ + tempbuff = zero_pack; + + byte_count = 0; + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + byte_count++; + if (byte_count < MMC_RPMB_NONCE_POSITION) + { + tempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_NONCE_POSITION) + { + tempbuff = echo_nonce; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + for (uint8_t i = 0; i < 16U; i++) + { + if (local_nonce[i] != echo_nonce[i]) + { + return HAL_ERROR; + } + } + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + return HAL_ERROR; + } + tail_pack[11] = 0x03; + tail_pack[10] = 0x00; + tail_pack[7] = (uint8_t)(NumberOfBlocks) & 0xFFU; + tail_pack[6] = (uint8_t)(NumberOfBlocks >> 8) & 0xFFU; + tail_pack[5] = (uint8_t)(BlockAdd) & 0xFFU; + tail_pack[4] = (uint8_t)(BlockAdd >> 8) & 0xFFU; + + rtempbuff = zero_pack; + byte_count = 0; + arg |= NumberOfBlocks; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, arg); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Send Request Packet */ + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + + { + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); + } + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*rtempbuff); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 8U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 16U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 24U); + rtempbuff++; + byte_count++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + if (byte_count == MMC_RPMB_KEYMAC_POSITION) + { + rtempbuff = pMAC; + } + if (byte_count == MMC_RPMB_DATA_POSITION) + { + rtempbuff = &pData[offset]; + } + if ((byte_count >= MMC_RPMB_NONCE_POSITION) && \ + (byte_count < MMC_RPMB_WRITE_COUNTER_POSITION)) + { + rtempbuff = zero_pack; + } + if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + rtempbuff = tail_pack; + } + else if (byte_count == MMC_BLOCKSIZE) + { + offset += (uint32_t)256U; + byte_count = 0; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Response Packet */ + + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, arg); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + + { + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); + } + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + /* Poll on SDMMC flags */ + tempbuff = zero_pack; + byte_count = 0; + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + byte_count++; + if (byte_count < MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + /* Check result of operation */ + if (((tail_pack[9] & (uint8_t)0xFEU) != 0x00U) || (tail_pack[10] != 0x03U)) + { + hmmc->RPMBErrorCode |= tail_pack[9]; + return HAL_ERROR; + } + + return HAL_OK; + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Allows to read block(s) to a specified address in the RPMB partition. The Data + * transfer is managed by polling mode. + * @param hmmc Pointer to MMC handle + * @param pData Pointer to the buffer that will contain the data to transmit + * @param BlockAdd Block Address where data will be written + * @param NumberOfBlocks Number of blocks to write + * @param pNonce Pointer to the buffer that will contain the nonce to transmit + * @param pMAC Pointer to the authentication MAC buffer + * @param Timeout Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMC_RPMB_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint16_t BlockAdd, + uint16_t NumberOfBlocks, const uint8_t *pNonce, uint8_t *pMAC, + uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t byte_count = 0; + uint32_t data; + uint8_t tail_pack[12] = {0}; + uint8_t zero_pack[4] = {0}; + uint8_t echo_nonce[16] = {0}; + uint32_t dataremaining; + const uint8_t *rtempbuff; + uint8_t *tempbuff; + uint32_t arg = 0; + uint32_t offset = 0; + + arg |= NumberOfBlocks; + + tail_pack[11] = 0x04; + tail_pack[10] = 0x00; + tail_pack[7] = 0x00; + tail_pack[6] = 0x00; + tail_pack[5] = (uint8_t)(BlockAdd) & 0xFFU; + tail_pack[4] = (uint8_t)(BlockAdd >> 8) & 0xFFU; + tail_pack[3] = 0x00; + tail_pack[2] = 0x00; + tail_pack[1] = 0x00; + tail_pack[0] = 0x00; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + hmmc->State = HAL_MMC_STATE_BUSY; + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0U; + + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, 1); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Send Request Packet */ + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Write block(s) in polling mode */ + rtempbuff = zero_pack; + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*rtempbuff); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 8U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 16U); + rtempbuff++; + byte_count++; + data |= ((uint32_t)(*rtempbuff) << 24U); + rtempbuff++; + byte_count++; + (void)SDMMC_WriteFIFO(hmmc->Instance, &data); + if (byte_count < MMC_RPMB_NONCE_POSITION) + { + rtempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_NONCE_POSITION) + { + rtempbuff = pNonce; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + rtempbuff = tail_pack; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Read Response Packet */ + errorstate = SDMMC_CmdBlockCount(hmmc->Instance, arg); + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * MMC_BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + /* Write Blocks in Polling mode */ + hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, 0); + + if (errorstate != HAL_MMC_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= errorstate; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + /* Poll on SDMMC flags */ + tempbuff = zero_pack; + byte_count = 0; + + dataremaining = config.DataLength; + while (!__HAL_MMC_GET_FLAG(hmmc, + SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hmmc->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + byte_count++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + byte_count++; + if (byte_count < MMC_RPMB_KEYMAC_POSITION) + { + tempbuff = zero_pack; + } + else if (byte_count == MMC_RPMB_KEYMAC_POSITION) + { + tempbuff = (uint8_t *)pMAC; + } + else if (byte_count == MMC_RPMB_DATA_POSITION) + { + tempbuff = &pData[offset]; + } + else if (byte_count == MMC_RPMB_NONCE_POSITION) + { + tempbuff = echo_nonce; + } + else if (byte_count == MMC_RPMB_WRITE_COUNTER_POSITION) + { + tempbuff = tail_pack; + } + else if (byte_count == MMC_BLOCKSIZE) + { + byte_count = 0; + offset += (uint32_t)256U; + } + else + { + /* Nothing to do */ + } + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hmmc->Instance); + + /* Get error state */ + if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else if (__HAL_MMC_GET_FLAG(hmmc, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_FLAGS); + hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; + hmmc->State = HAL_MMC_STATE_READY; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_MMC_CLEAR_FLAG(hmmc, SDMMC_STATIC_DATA_FLAGS); + + hmmc->State = HAL_MMC_STATE_READY; + + for (uint8_t i = 0; i < 16U; i++) + { + if (pNonce[i] != echo_nonce[i]) + { + return HAL_ERROR; + } + } + + /* Check result of operation */ + if ((tail_pack[9] != 0x00U) || (tail_pack[10] != 0x04U)) + { + hmmc->RPMBErrorCode |= tail_pack[9]; + return HAL_ERROR; + } + + return HAL_OK; + } + else + { + hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; + return HAL_ERROR; + } +} + + +/** + * @brief Read DMA Linked list node Transfer completed callbacks + * @param hmmc MMC handle + * @retval None + */ +__weak void HAL_MMCEx_Read_DMALnkLstBufCpltCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MMCEx_Read_DMALnkLstBufCpltCallback can be implemented in the user file + */ +} +/** + * @brief Read DMA Linked list node Transfer completed callbacks + * @param hmmc MMC handle + * @retval None + */ +__weak void HAL_MMCEx_Write_DMALnkLstBufCpltCallback(MMC_HandleTypeDef *hmmc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hmmc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_MMCEx_Write_DMALnkLstBufCpltCallback can be implemented in the user file + */ +} + +/** + * @} + */ + +#endif /* HAL_MMC_MODULE_ENABLED */ +#endif /* SDMMC1 || SDMMC2 */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc_ex.c index 3616aa833..a067070ed 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_mmc_ex.c @@ -1,448 +1,448 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_mmc_ex.c - * @author MCD Application Team - * @brief MMC card Extended HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Secure Digital (MMC) peripheral: - * + Extended features functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The MMC Extension HAL driver can be used as follows: - (+) Configure Buffer0 and Buffer1 start address and Buffer size using HAL_MMCEx_ConfigDMAMultiBuffer() function. - - (+) Start Read and Write for multibuffer mode using HAL_MMCEx_ReadBlocksDMAMultiBuffer() and - HAL_MMCEx_WriteBlocksDMAMultiBuffer() functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup MMCEx MMCEx - * @brief MMC Extended HAL module driver - * @{ - */ - -#if defined (SDMMC1) || defined (SDMMC2) -#ifdef HAL_MMC_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup MMCEx_Exported_Functions - * @{ - */ - - - -/** @addtogroup MMCEx_Exported_Functions_Group1 - * @brief Linked List management functions - * -@verbatim - =============================================================================== - ##### Linked List management functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the needed functions. - -@endverbatim - * @{ - */ - -/** - * @brief Build Linked List node. - * @param pNode: Pointer to new node to add. - * @param pNodeConf: Pointer to configuration parameters for new node to add. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_BuildNode(MMC_DMALinkNodeTypeDef *pNode, - MMC_DMALinkNodeConfTypeDef *pNodeConf) -{ - - if (SDMMC_DMALinkedList_BuildNode(pNode, pNodeConf) != SDMMC_ERROR_NONE) - { - return (HAL_ERROR); - } - else - { - return (HAL_OK); - } - -} -/** - * @brief Insert Linked List node. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @param pPrevNode: Pointer to previous node. - * @param pNewNode: Pointer to new node to insert. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_InsertNode(MMC_DMALinkedListTypeDef *pLinkedList, - MMC_DMALinkNodeTypeDef *pPrevNode, - MMC_DMALinkNodeTypeDef *pNewNode) -{ - - if (SDMMC_DMALinkedList_InsertNode(pLinkedList, pPrevNode, pNewNode) != SDMMC_ERROR_NONE) - { - return (HAL_ERROR); - } - else - { - return (HAL_OK); - } - -} -/** - * @brief Remove Linked List node. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @param pNode: Pointer to node to remove. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_RemoveNode(MMC_DMALinkedListTypeDef *pLinkedList, - MMC_DMALinkNodeTypeDef *pNode) -{ - - if (SDMMC_DMALinkedList_RemoveNode(pLinkedList, pNode) != SDMMC_ERROR_NONE) - { - return (HAL_ERROR); - } - else - { - return (HAL_OK); - } -} - -/** - * @brief Lock Linked List node. - * @param pNode: Pointer to node to remove. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_LockNode(MMC_DMALinkNodeTypeDef *pNode) -{ - - if (SDMMC_DMALinkedList_LockNode(pNode) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} - -/** - * @brief Unlock Linked List node. - * @param pNode: Pointer to node to remove. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_UnlockNode(MMC_DMALinkNodeTypeDef *pNode) -{ - - if (SDMMC_DMALinkedList_UnlockNode(pNode) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} - -/** - * @brief Enable Circular mode for DMA Linked List mode. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_EnableCircularMode(MMC_DMALinkedListTypeDef *pLinkedList) -{ - - if (SDMMC_DMALinkedList_EnableCircularMode(pLinkedList) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} -/** - * @brief Disable Circular mode for DMA Linked List mode. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_DisableCircularMode(MMC_DMALinkedListTypeDef *pLinkedList) -{ - - if (SDMMC_DMALinkedList_DisableCircularMode(pLinkedList) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} - - -/** - * @brief Reads block(s) from a specified address in a card. The received Data will be stored in linked list buffers. - * linked list should be prepared before call this function . - * @param hmmc: MMC handle - * @param pLinkedList: pointer to first linked list node - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Total number of blocks to read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_ReadBlocks(MMC_HandleTypeDef *hmmc, MMC_DMALinkedListTypeDef *pLinkedList, - uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t DmaBase0_reg; - uint32_t DmaBase1_reg; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; - hmmc->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; - hmmc->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; - hmmc->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | - sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ - - DmaBase0_reg = hmmc->Instance->IDMABASER; - DmaBase1_reg = hmmc->Instance->IDMABAR; - - if ((hmmc->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) - { - hmmc->ErrorCode = HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0; - - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_BUSY; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= 512U; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - - hmmc->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; - - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; - - /* Read Blocks in DMA mode */ - hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | - SDMMC_FLAG_IDMATE | SDMMC_FLAG_IDMABTC)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } - -} - -/** - * @brief Write block(s) to a specified address in a card. The transferred Data are stored linked list nodes buffers . - * linked list should be prepared before call this function . - * @param hmmc: MMC handle - * @param pLinkedList: pointer to first linked list node - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Total number of blocks to read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_WriteBlocks(MMC_HandleTypeDef *hmmc, MMC_DMALinkedListTypeDef *pLinkedList, - uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t DmaBase0_reg; - uint32_t DmaBase1_reg; - uint32_t add = BlockAdd; - - if (hmmc->State == HAL_MMC_STATE_READY) - { - if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ - if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) - { - if ((NumberOfBlocks % 8U) != 0U) - { - /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ - hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; - return HAL_ERROR; - } - - if ((BlockAdd % 8U) != 0U) - { - /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; - return HAL_ERROR; - } - } - - hmmc->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; - hmmc->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; - - hmmc->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; - hmmc->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | - sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ - - DmaBase0_reg = hmmc->Instance->IDMABASER; - DmaBase1_reg = hmmc->Instance->IDMABAR; - - if ((hmmc->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) - { - hmmc->ErrorCode = HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0; - - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - - hmmc->State = HAL_MMC_STATE_BUSY; - - if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) - { - add *= 512U; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hmmc->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); - - hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; - - /* Write Blocks in DMA mode */ - hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); - if (errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | - SDMMC_FLAG_IDMATE | SDMMC_FLAG_IDMABTC)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_MMC_MODULE_ENABLED */ -#endif /* SDMMC1 || SDMMC2 */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_mmc_ex.c + * @author MCD Application Team + * @brief MMC card Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Secure Digital (MMC) peripheral: + * + Extended features functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The MMC Extension HAL driver can be used as follows: + (+) Configure Buffer0 and Buffer1 start address and Buffer size using HAL_MMCEx_ConfigDMAMultiBuffer() function. + + (+) Start Read and Write for multibuffer mode using HAL_MMCEx_ReadBlocksDMAMultiBuffer() and + HAL_MMCEx_WriteBlocksDMAMultiBuffer() functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup MMCEx MMCEx + * @brief MMC Extended HAL module driver + * @{ + */ + +#if defined (SDMMC1) || defined (SDMMC2) +#ifdef HAL_MMC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup MMCEx_Exported_Functions + * @{ + */ + + + +/** @addtogroup MMCEx_Exported_Functions_Group1 + * @brief Linked List management functions + * +@verbatim + =============================================================================== + ##### Linked List management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed functions. + +@endverbatim + * @{ + */ + +/** + * @brief Build Linked List node. + * @param pNode: Pointer to new node to add. + * @param pNodeConf: Pointer to configuration parameters for new node to add. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_BuildNode(MMC_DMALinkNodeTypeDef *pNode, + MMC_DMALinkNodeConfTypeDef *pNodeConf) +{ + + if (SDMMC_DMALinkedList_BuildNode(pNode, pNodeConf) != SDMMC_ERROR_NONE) + { + return (HAL_ERROR); + } + else + { + return (HAL_OK); + } + +} +/** + * @brief Insert Linked List node. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @param pPrevNode: Pointer to previous node. + * @param pNewNode: Pointer to new node to insert. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_InsertNode(MMC_DMALinkedListTypeDef *pLinkedList, + MMC_DMALinkNodeTypeDef *pPrevNode, + MMC_DMALinkNodeTypeDef *pNewNode) +{ + + if (SDMMC_DMALinkedList_InsertNode(pLinkedList, pPrevNode, pNewNode) != SDMMC_ERROR_NONE) + { + return (HAL_ERROR); + } + else + { + return (HAL_OK); + } + +} +/** + * @brief Remove Linked List node. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @param pNode: Pointer to node to remove. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_RemoveNode(MMC_DMALinkedListTypeDef *pLinkedList, + MMC_DMALinkNodeTypeDef *pNode) +{ + + if (SDMMC_DMALinkedList_RemoveNode(pLinkedList, pNode) != SDMMC_ERROR_NONE) + { + return (HAL_ERROR); + } + else + { + return (HAL_OK); + } +} + +/** + * @brief Lock Linked List node. + * @param pNode: Pointer to node to remove. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_LockNode(MMC_DMALinkNodeTypeDef *pNode) +{ + + if (SDMMC_DMALinkedList_LockNode(pNode) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Unlock Linked List node. + * @param pNode: Pointer to node to remove. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_UnlockNode(MMC_DMALinkNodeTypeDef *pNode) +{ + + if (SDMMC_DMALinkedList_UnlockNode(pNode) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Enable Circular mode for DMA Linked List mode. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_EnableCircularMode(MMC_DMALinkedListTypeDef *pLinkedList) +{ + + if (SDMMC_DMALinkedList_EnableCircularMode(pLinkedList) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} +/** + * @brief Disable Circular mode for DMA Linked List mode. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_DisableCircularMode(MMC_DMALinkedListTypeDef *pLinkedList) +{ + + if (SDMMC_DMALinkedList_DisableCircularMode(pLinkedList) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + + +/** + * @brief Reads block(s) from a specified address in a card. The received Data will be stored in linked list buffers. + * linked list should be prepared before call this function . + * @param hmmc: MMC handle + * @param pLinkedList: pointer to first linked list node + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Total number of blocks to read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_ReadBlocks(MMC_HandleTypeDef *hmmc, MMC_DMALinkedListTypeDef *pLinkedList, + uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t DmaBase0_reg; + uint32_t DmaBase1_reg; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; + hmmc->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; + hmmc->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; + hmmc->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | + sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ + + DmaBase0_reg = hmmc->Instance->IDMABASER; + DmaBase1_reg = hmmc->Instance->IDMABAR; + + if ((hmmc->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) + { + hmmc->ErrorCode = HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0; + + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + hmmc->State = HAL_MMC_STATE_BUSY; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + + hmmc->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; + + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; + + /* Read Blocks in DMA mode */ + hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, add); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->State = HAL_MMC_STATE_READY; + hmmc->ErrorCode |= errorstate; + return HAL_ERROR; + } + + __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | + SDMMC_FLAG_IDMATE | SDMMC_FLAG_IDMABTC)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } + +} + +/** + * @brief Write block(s) to a specified address in a card. The transferred Data are stored linked list nodes buffers . + * linked list should be prepared before call this function . + * @param hmmc: MMC handle + * @param pLinkedList: pointer to first linked list node + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Total number of blocks to read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_WriteBlocks(MMC_HandleTypeDef *hmmc, MMC_DMALinkedListTypeDef *pLinkedList, + uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t DmaBase0_reg; + uint32_t DmaBase1_reg; + uint32_t add = BlockAdd; + + if (hmmc->State == HAL_MMC_STATE_READY) + { + if ((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) + { + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Check the case of 4kB blocks (field DATA SECTOR SIZE of extended CSD register) */ + if (((hmmc->Ext_CSD[(MMC_EXT_CSD_DATA_SEC_SIZE_INDEX / 4)] >> MMC_EXT_CSD_DATA_SEC_SIZE_POS) & 0x000000FFU) != 0x0U) + { + if ((NumberOfBlocks % 8U) != 0U) + { + /* The number of blocks should be a multiple of 8 sectors of 512 bytes = 4 KBytes */ + hmmc->ErrorCode |= HAL_MMC_ERROR_BLOCK_LEN_ERR; + return HAL_ERROR; + } + + if ((BlockAdd % 8U) != 0U) + { + /* The address should be aligned to 8 (corresponding to 4 KBytes blocks) */ + hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_MISALIGNED; + return HAL_ERROR; + } + } + + hmmc->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; + hmmc->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; + + hmmc->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; + hmmc->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | + sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ + + DmaBase0_reg = hmmc->Instance->IDMABASER; + DmaBase1_reg = hmmc->Instance->IDMABAR; + + if ((hmmc->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) + { + hmmc->ErrorCode = HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Initialize data control register */ + hmmc->Instance->DCTRL = 0; + + hmmc->ErrorCode = HAL_MMC_ERROR_NONE; + + hmmc->State = HAL_MMC_STATE_BUSY; + + if ((hmmc->MmcCard.CardType) != MMC_HIGH_CAPACITY_CARD) + { + add *= 512U; + } + + /* Configure the MMC DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = MMC_BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hmmc->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hmmc->Instance); + + hmmc->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; + + /* Write Blocks in DMA mode */ + hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, add); + if (errorstate != HAL_MMC_ERROR_NONE) + { + hmmc->State = HAL_MMC_STATE_READY; + hmmc->ErrorCode |= errorstate; + return HAL_ERROR; + } + + __HAL_MMC_ENABLE_IT(hmmc, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | + SDMMC_FLAG_IDMATE | SDMMC_FLAG_IDMABTC)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_MMC_MODULE_ENABLED */ +#endif /* SDMMC1 || SDMMC2 */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_msp_template.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_msp_template.c index 0c4009107..39f93844d 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_msp_template.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_msp_template.c @@ -1,97 +1,97 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_msp.c - * @author MCD Application Team - * @brief HAL MSP module. - * This file should be copied to the application folder and renamed - * to stm32h7rsxx_hal_msp.c - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup HAL_MSP HAL MSP module driver - * @brief HAL MSP module. - * @{ - */ - -/* Private typedefs ----------------------------------------------------------*/ -/* Private defines -----------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ - -/** @defgroup HAL_MSP_Private_Functions - * @{ - */ - -/** - * @brief Initialize the Global MSP. - * @retval None - */ -void HAL_MspInit(void) -{ - /* NOTE : This function is generated automatically by STM32CubeMX and eventually - modified by the user - */ -} - -/** - * @brief DeInitialize the Global MSP. - * @retval None - */ -void HAL_MspDeInit(void) -{ - /* NOTE : This function is generated automatically by STM32CubeMX and eventually - modified by the user - */ -} - -/** - * @brief Initialize the PPP MSP. - * @retval None - */ -/* -void HAL_PPP_MspInit(void) -{ -} -*/ - -/** - * @brief DeInitialize the PPP MSP. - * @retval None - */ -/* -void HAL_PPP_MspDeInit(void) -{ -} -*/ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_msp.c + * @author MCD Application Team + * @brief HAL MSP module. + * This file should be copied to the application folder and renamed + * to stm32h7rsxx_hal_msp.c + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup HAL_MSP HAL MSP module driver + * @brief HAL MSP module. + * @{ + */ + +/* Private typedefs ----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_MSP_Private_Functions + * @{ + */ + +/** + * @brief Initialize the Global MSP. + * @retval None + */ +void HAL_MspInit(void) +{ + /* NOTE : This function is generated automatically by STM32CubeMX and eventually + modified by the user + */ +} + +/** + * @brief DeInitialize the Global MSP. + * @retval None + */ +void HAL_MspDeInit(void) +{ + /* NOTE : This function is generated automatically by STM32CubeMX and eventually + modified by the user + */ +} + +/** + * @brief Initialize the PPP MSP. + * @retval None + */ +/* +void HAL_PPP_MspInit(void) +{ +} +*/ + +/** + * @brief DeInitialize the PPP MSP. + * @retval None + */ +/* +void HAL_PPP_MspDeInit(void) +{ +} +*/ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nand.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nand.c index 09c550893..abc73cbc8 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nand.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nand.c @@ -1,2231 +1,2230 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_nand.c - * @author MCD Application Team - * @brief NAND HAL module driver. - * This file provides a generic firmware to drive NAND memories mounted - * as external device. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 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_8b()/HAL_NAND_Read_SpareArea_8b(), - HAL_NAND_Write_Page_8b()/HAL_NAND_Write_SpareArea_8b(), - HAL_NAND_Read_Page_16b()/HAL_NAND_Read_SpareArea_16b(), - HAL_NAND_Write_Page_16b()/HAL_NAND_Write_SpareArea_16b() - to read/write page(s)/spare area(s). These functions use specific device - information (Block, page size..) predefined by the user in the NAND_DeviceConfigTypeDef - 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. - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_NAND_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - Use Functions HAL_NAND_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) MspInitCallback : NAND MspInit. - (+) MspDeInitCallback : NAND MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function HAL_NAND_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) MspInitCallback : NAND MspInit. - (+) MspDeInitCallback : NAND MspDeInit. - This function) takes as parameters the HAL peripheral handle and the Callback ID. - - By default, after the HAL_NAND_Init and if the state is HAL_NAND_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_NAND_Init - and HAL_NAND_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_NAND_Init and HAL_NAND_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_NAND_RegisterCallback before calling HAL_NAND_DeInit - or HAL_NAND_Init function. - - When The compilation define USE_HAL_NAND_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_NAND_MODULE_ENABLED - -/** @defgroup NAND NAND - * @brief NAND HAL module driver - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private Constants ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions ---------------------------------------------------------*/ - -/** @defgroup NAND_Exported_Functions NAND Exported Functions - * @{ - */ - -/** @defgroup NAND_Exported_Functions_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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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) - { - /* Allocate lock resource and initialize it */ - hnand->Lock = HAL_UNLOCKED; - -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) - if (hnand->MspInitCallback == NULL) - { - hnand->MspInitCallback = HAL_NAND_MspInit; - } - hnand->ItCallback = HAL_NAND_ITCallback; - - /* Init the low level hardware */ - hnand->MspInitCallback(hnand); -#else - /* Initialize the low level hardware (MSP) */ - HAL_NAND_MspInit(hnand); -#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ - } - - /* Initialize NAND control Interface */ - (void)FMC_NAND_Init(hnand->Instance, &(hnand->Init)); - - /* Initialize NAND common space timing Interface */ - (void)FMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank); - - /* Initialize NAND attribute space timing Interface */ - (void)FMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank); - - /* Enable the NAND device */ - __FMC_NAND_ENABLE(hnand->Instance); - - /* Enable FMC Peripheral */ - __FMC_ENABLE(); - /* 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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand) -{ -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) - if (hnand->MspDeInitCallback == NULL) - { - hnand->MspDeInitCallback = HAL_NAND_MspDeInit; - } - - /* DeInit the low level hardware */ - hnand->MspDeInitCallback(hnand); -#else - /* Initialize the low level hardware (MSP) */ - HAL_NAND_MspDeInit(hnand); -#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ - - /* Configure the NAND registers with their reset values */ - (void)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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval None - */ -__weak void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval None - */ -__weak void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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*/ -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) - hnand->ItCallback(hnand); -#else - HAL_NAND_ITCallback(hnand); -#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ - - /* Clear NAND interrupt Rising edge pending bit */ - __FMC_NAND_CLEAR_FLAG(hnand->Instance, 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*/ -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) - hnand->ItCallback(hnand); -#else - HAL_NAND_ITCallback(hnand); -#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ - - /* Clear NAND interrupt Level pending bit */ - __FMC_NAND_CLEAR_FLAG(hnand->Instance, 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*/ -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) - hnand->ItCallback(hnand); -#else - HAL_NAND_ITCallback(hnand); -#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ - - /* Clear NAND interrupt Falling edge pending bit */ - __FMC_NAND_CLEAR_FLAG(hnand->Instance, 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*/ -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) - hnand->ItCallback(hnand); -#else - HAL_NAND_ITCallback(hnand); -#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ - - /* Clear NAND interrupt FIFO empty pending bit */ - __FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_FEMPT); - } - -} - -/** - * @brief NAND interrupt feature callback - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval None - */ -__weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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_Exported_Functions_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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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; - __IO uint32_t data1 = 0; - uint32_t deviceaddress; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* Send Read ID command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_READID; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - __DSB(); - - /* Read the electronic signature from NAND flash */ - if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8) - { - 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); - } - else - { - data = *(__IO uint32_t *)deviceaddress; - data1 = *((__IO uint32_t *)deviceaddress + 4); - - /* Return the data read */ - pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data); - pNAND_ID->Device_Id = ADDR_3RD_CYCLE(data); - pNAND_ID->Third_Id = ADDR_1ST_CYCLE(data1); - pNAND_ID->Fourth_Id = ADDR_3RD_CYCLE(data1); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief NAND memory reset - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand) -{ - uint32_t deviceaddress; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* 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); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; - -} - -/** - * @brief Configure the device: Enter the physical parameters of the device - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pDeviceConfig pointer to NAND_DeviceConfigTypeDef structure - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig) -{ - hnand->Config.PageSize = pDeviceConfig->PageSize; - hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize; - hnand->Config.BlockSize = pDeviceConfig->BlockSize; - hnand->Config.BlockNbr = pDeviceConfig->BlockNbr; - hnand->Config.PlaneSize = pDeviceConfig->PlaneSize; - hnand->Config.PlaneNbr = pDeviceConfig->PlaneNbr; - hnand->Config.ExtraCommandEnable = pDeviceConfig->ExtraCommandEnable; - - return HAL_OK; -} - -/** - * @brief Read Page(s) from NAND memory block (8-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - uint8_t *pBuffer, uint32_t NumPageToRead) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numpagesread = 0U; - uint32_t nandaddress; - uint32_t nbpages = NumPageToRead; - uint8_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Page(s) read loop */ - while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Send read page command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - __DSB(); - - - if (hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - __DSB(); - } - - /* Get Data into Buffer */ - for (index = 0U; index < hnand->Config.PageSize; index++) - { - *buff = *(uint8_t *)deviceaddress; - buff++; - } - - /* Increment read pages number */ - numpagesread++; - - /* Decrement pages to read */ - nbpages--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Read Page(s) from NAND memory block (16-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress pointer to NAND address structure - * @param pBuffer pointer to destination read buffer. pBuffer should be 16bits aligned - * @param NumPageToRead number of pages to read from block - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - uint16_t *pBuffer, uint32_t NumPageToRead) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numpagesread = 0U; - uint32_t nandaddress; - uint32_t nbpages = NumPageToRead; - uint16_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Page(s) read loop */ - while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Send read page command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - __DSB(); - - if (hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - __DSB(); - } - - /* Calculate PageSize */ - if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8) - { - hnand->Config.PageSize = hnand->Config.PageSize / 2U; - } - else - { - /* Do nothing */ - /* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/ - } - - /* Get Data into Buffer */ - for (index = 0U; index < hnand->Config.PageSize; index++) - { - *buff = *(uint16_t *)deviceaddress; - buff++; - } - - /* Increment read pages number */ - numpagesread++; - - /* Decrement pages to read */ - nbpages--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Write Page(s) to NAND memory block (8-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - const uint8_t *pBuffer, uint32_t NumPageToWrite) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numpageswritten = 0U; - uint32_t nandaddress; - uint32_t nbpages = NumPageToWrite; - const uint8_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Page(s) write loop */ - while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Send write page command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - __DSB(); - - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - /* Write data to memory */ - for (index = 0U; index < hnand->Config.PageSize; index++) - { - *(__IO uint8_t *)deviceaddress = *buff; - buff++; - __DSB(); - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; - __DSB(); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Increment written pages number */ - numpageswritten++; - - /* Decrement pages to write */ - nbpages--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Write Page(s) to NAND memory block (16-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress pointer to NAND address structure - * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned - * @param NumPageToWrite number of pages to write to block - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - const uint16_t *pBuffer, uint32_t NumPageToWrite) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numpageswritten = 0U; - uint32_t nandaddress; - uint32_t nbpages = NumPageToWrite; - const uint16_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Page(s) write loop */ - while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Send write page command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - __DSB(); - - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - /* Calculate PageSize */ - if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8) - { - hnand->Config.PageSize = hnand->Config.PageSize / 2U; - } - else - { - /* Do nothing */ - /* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/ - } - - /* Write data to memory */ - for (index = 0U; index < hnand->Config.PageSize; index++) - { - *(__IO uint16_t *)deviceaddress = *buff; - buff++; - __DSB(); - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; - __DSB(); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Increment written pages number */ - numpageswritten++; - - /* Decrement pages to write */ - nbpages--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Read Spare area(s) from NAND memory (8-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - uint8_t *pBuffer, uint32_t NumSpareAreaToRead) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numsparearearead = 0U; - uint32_t nandaddress; - uint32_t columnaddress; - uint32_t nbspare = NumSpareAreaToRead; - uint8_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = COLUMN_ADDRESS(hnand); - - /* Spare area(s) read loop */ - while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - __DSB(); - - if (hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - __DSB(); - } - - /* Get Data into Buffer */ - for (index = 0U; index < hnand->Config.SpareAreaSize; index++) - { - *buff = *(uint8_t *)deviceaddress; - buff++; - } - - /* Increment read spare areas number */ - numsparearearead++; - - /* Decrement spare areas to read */ - nbspare--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Read Spare area(s) from NAND memory (16-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress pointer to NAND address structure - * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned. - * @param NumSpareAreaToRead Number of spare area to read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - uint16_t *pBuffer, uint32_t NumSpareAreaToRead) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numsparearearead = 0U; - uint32_t nandaddress; - uint32_t columnaddress; - uint32_t nbspare = NumSpareAreaToRead; - uint16_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand)); - - /* Spare area(s) read loop */ - while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - __DSB(); - - if (hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - __DSB(); - } - - /* Get Data into Buffer */ - for (index = 0U; index < hnand->Config.SpareAreaSize; index++) - { - *buff = *(uint16_t *)deviceaddress; - buff++; - } - - /* Increment read spare areas number */ - numsparearearead++; - - /* Decrement spare areas to read */ - nbspare--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Write Spare area(s) to NAND memory (8-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - const uint8_t *pBuffer, uint32_t NumSpareAreaTowrite) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numspareareawritten = 0U; - uint32_t nandaddress; - uint32_t columnaddress; - uint32_t nbspare = NumSpareAreaTowrite; - const uint8_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* Page address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = COLUMN_ADDRESS(hnand); - - /* Spare area(s) write loop */ - while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - /* Write data to memory */ - for (index = 0U; index < hnand->Config.SpareAreaSize; index++) - { - *(__IO uint8_t *)deviceaddress = *buff; - buff++; - __DSB(); - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; - __DSB(); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Increment written spare areas number */ - numspareareawritten++; - - /* Decrement spare areas to write */ - nbspare--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Write Spare area(s) to NAND memory (16-bits addressing) - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress pointer to NAND address structure - * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned. - * @param NumSpareAreaTowrite number of spare areas to write to block - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, - const uint16_t *pBuffer, uint32_t NumSpareAreaTowrite) -{ - uint32_t index; - uint32_t tickstart; - uint32_t deviceaddress; - uint32_t numspareareawritten = 0U; - uint32_t nandaddress; - uint32_t columnaddress; - uint32_t nbspare = NumSpareAreaTowrite; - const uint16_t *buff = pBuffer; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand)); - - /* Spare area(s) write loop */ - while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* Cards with page size <= 512 bytes */ - if ((hnand->Config.PageSize) <= 512U) - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - __DSB(); - - if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - __DSB(); - } - } - - /* Write data to memory */ - for (index = 0U; index < hnand->Config.SpareAreaSize; index++) - { - *(__IO uint16_t *)deviceaddress = *buff; - buff++; - __DSB(); - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; - __DSB(); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while (HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) - { - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_ERROR; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_TIMEOUT; - } - } - - /* Increment written spare areas number */ - numspareareawritten++; - - /* Decrement spare areas to write */ - nbspare--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief NAND memory Block erase - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress pointer to NAND address structure - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress) -{ - uint32_t deviceaddress; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* Send Erase block command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE0; - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); - __DSB(); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); - __DSB(); - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE1; - __DSB(); - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Increment the NAND memory address - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress pointer to NAND address 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(const 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->Config.BlockSize) - { - pAddress->Page = 0; - pAddress->Block++; - - if (pAddress->Block == hnand->Config.PlaneSize) - { - pAddress->Block = 0; - pAddress->Plane++; - - if (pAddress->Plane == (hnand->Config.PlaneNbr)) - { - status = NAND_INVALID_ADDRESS; - } - } - } - - return (status); -} - -#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User NAND Callback - * To be used to override the weak predefined callback - * @param hnand : NAND handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID - * @arg @ref HAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID - * @arg @ref HAL_NAND_IT_CB_ID NAND IT callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_CallbackIDTypeDef CallbackId, - pNAND_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - if (hnand->State == HAL_NAND_STATE_READY) - { - switch (CallbackId) - { - case HAL_NAND_MSP_INIT_CB_ID : - hnand->MspInitCallback = pCallback; - break; - case HAL_NAND_MSP_DEINIT_CB_ID : - hnand->MspDeInitCallback = pCallback; - break; - case HAL_NAND_IT_CB_ID : - hnand->ItCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hnand->State == HAL_NAND_STATE_RESET) - { - switch (CallbackId) - { - case HAL_NAND_MSP_INIT_CB_ID : - hnand->MspInitCallback = pCallback; - break; - case HAL_NAND_MSP_DEINIT_CB_ID : - hnand->MspDeInitCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User NAND Callback - * NAND Callback is redirected to the weak predefined callback - * @param hnand : NAND handle - * @param CallbackId : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID - * @arg @ref HAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID - * @arg @ref HAL_NAND_IT_CB_ID NAND IT callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_CallbackIDTypeDef CallbackId) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hnand->State == HAL_NAND_STATE_READY) - { - switch (CallbackId) - { - case HAL_NAND_MSP_INIT_CB_ID : - hnand->MspInitCallback = HAL_NAND_MspInit; - break; - case HAL_NAND_MSP_DEINIT_CB_ID : - hnand->MspDeInitCallback = HAL_NAND_MspDeInit; - break; - case HAL_NAND_IT_CB_ID : - hnand->ItCallback = HAL_NAND_ITCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hnand->State == HAL_NAND_STATE_RESET) - { - switch (CallbackId) - { - case HAL_NAND_MSP_INIT_CB_ID : - hnand->MspInitCallback = HAL_NAND_MspInit; - break; - case HAL_NAND_MSP_DEINIT_CB_ID : - hnand->MspDeInitCallback = HAL_NAND_MspDeInit; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_NAND_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup NAND_Exported_Functions_Group3 Peripheral 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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Update the NAND state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Enable ECC feature */ - (void)FMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank); - - /* Update the NAND state */ - hnand->State = HAL_NAND_STATE_READY; - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Disables dynamically FMC_NAND ECC feature. - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* Update the NAND state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* Disable ECC feature */ - (void)FMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank); - - /* Update the NAND state */ - hnand->State = HAL_NAND_STATE_READY; - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Disables dynamically NAND ECC feature. - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @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; - - /* Check the NAND controller state */ - if (hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnand->State == HAL_NAND_STATE_READY) - { - /* 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; - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @} - */ - - -/** @defgroup NAND_Exported_Functions_Group4 Peripheral State functions - * @brief Peripheral State functions - * -@verbatim - ============================================================================== - ##### NAND State functions ##### - ============================================================================== - [..] - This subsection permits 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 a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval HAL state - */ -HAL_NAND_StateTypeDef HAL_NAND_GetState(const NAND_HandleTypeDef *hnand) -{ - return hnand->State; -} - -/** - * @brief NAND memory read status - * @param hnand pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @retval NAND status - */ -uint32_t HAL_NAND_Read_Status(const NAND_HandleTypeDef *hnand) -{ - uint32_t data; - uint32_t deviceaddress; - UNUSED(hnand); - - /* Identify the device address */ - deviceaddress = NAND_DEVICE; - - /* Send Read status operation command */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_STATUS; - - /* 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; - } - else - { - return NAND_BUSY; - } -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_NAND_MODULE_ENABLED */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_nand.c + * @author MCD Application Team + * @brief NAND HAL module driver. + * This file provides a generic firmware to drive NAND memories mounted + * as external device. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 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_8b()/HAL_NAND_Read_SpareArea_8b(), + HAL_NAND_Write_Page_8b()/HAL_NAND_Write_SpareArea_8b(), + HAL_NAND_Read_Page_16b()/HAL_NAND_Read_SpareArea_16b(), + HAL_NAND_Write_Page_16b()/HAL_NAND_Write_SpareArea_16b() + to read/write page(s)/spare area(s). These functions use specific device + information (Block, page size..) predefined by the user in the NAND_DeviceConfigTypeDef + 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. + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_NAND_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_NAND_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : NAND MspInit. + (+) MspDeInitCallback : NAND MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function HAL_NAND_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) MspInitCallback : NAND MspInit. + (+) MspDeInitCallback : NAND MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + + By default, after the HAL_NAND_Init and if the state is HAL_NAND_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_NAND_Init + and HAL_NAND_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_NAND_Init and HAL_NAND_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_NAND_RegisterCallback before calling HAL_NAND_DeInit + or HAL_NAND_Init function. + + When The compilation define USE_HAL_NAND_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_NAND_MODULE_ENABLED + +/** @defgroup NAND NAND + * @brief NAND HAL module driver + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private Constants ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup NAND_Exported_Functions NAND Exported Functions + * @{ + */ + +/** @defgroup NAND_Exported_Functions_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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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) + { + /* Allocate lock resource and initialize it */ + hnand->Lock = HAL_UNLOCKED; + +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) + if (hnand->MspInitCallback == NULL) + { + hnand->MspInitCallback = HAL_NAND_MspInit; + } + hnand->ItCallback = HAL_NAND_ITCallback; + + /* Init the low level hardware */ + hnand->MspInitCallback(hnand); +#else + /* Initialize the low level hardware (MSP) */ + HAL_NAND_MspInit(hnand); +#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ + } + + /* Initialize NAND control Interface */ + (void)FMC_NAND_Init(hnand->Instance, &(hnand->Init)); + + /* Initialize NAND common space timing Interface */ + (void)FMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank); + + /* Initialize NAND attribute space timing Interface */ + (void)FMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank); + + /* Enable the NAND device */ + __FMC_NAND_ENABLE(hnand->Instance); + + /* Enable FMC Peripheral */ + __FMC_ENABLE(); + /* 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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand) +{ +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) + if (hnand->MspDeInitCallback == NULL) + { + hnand->MspDeInitCallback = HAL_NAND_MspDeInit; + } + + /* DeInit the low level hardware */ + hnand->MspDeInitCallback(hnand); +#else + /* Initialize the low level hardware (MSP) */ + HAL_NAND_MspDeInit(hnand); +#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ + + /* Configure the NAND registers with their reset values */ + (void)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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval None + */ +__weak void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval None + */ +__weak void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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*/ +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + HAL_NAND_ITCallback(hnand); +#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt Rising edge pending bit */ + __FMC_NAND_CLEAR_FLAG(hnand->Instance, 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*/ +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + HAL_NAND_ITCallback(hnand); +#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt Level pending bit */ + __FMC_NAND_CLEAR_FLAG(hnand->Instance, 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*/ +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + HAL_NAND_ITCallback(hnand); +#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt Falling edge pending bit */ + __FMC_NAND_CLEAR_FLAG(hnand->Instance, 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*/ +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) + hnand->ItCallback(hnand); +#else + HAL_NAND_ITCallback(hnand); +#endif /* (USE_HAL_NAND_REGISTER_CALLBACKS) */ + + /* Clear NAND interrupt FIFO empty pending bit */ + __FMC_NAND_CLEAR_FLAG(hnand->Instance, FMC_FLAG_FEMPT); + } + +} + +/** + * @brief NAND interrupt feature callback + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval None + */ +__weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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_Exported_Functions_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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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; + __IO uint32_t data1 = 0; + uint32_t deviceaddress; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Send Read ID command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_READID; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; + __DSB(); + + /* Read the electronic signature from NAND flash */ + if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8) + { + 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); + } + else + { + data = *(__IO uint32_t *)deviceaddress; + data1 = *((__IO uint32_t *)deviceaddress + 4); + + /* Return the data read */ + pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data); + pNAND_ID->Device_Id = ADDR_3RD_CYCLE(data); + pNAND_ID->Third_Id = ADDR_1ST_CYCLE(data1); + pNAND_ID->Fourth_Id = ADDR_3RD_CYCLE(data1); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief NAND memory reset + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand) +{ + uint32_t deviceaddress; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* 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); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; + +} + +/** + * @brief Configure the device: Enter the physical parameters of the device + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pDeviceConfig pointer to NAND_DeviceConfigTypeDef structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, const NAND_DeviceConfigTypeDef *pDeviceConfig) +{ + hnand->Config.PageSize = pDeviceConfig->PageSize; + hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize; + hnand->Config.BlockSize = pDeviceConfig->BlockSize; + hnand->Config.BlockNbr = pDeviceConfig->BlockNbr; + hnand->Config.PlaneSize = pDeviceConfig->PlaneSize; + hnand->Config.PlaneNbr = pDeviceConfig->PlaneNbr; + hnand->Config.ExtraCommandEnable = pDeviceConfig->ExtraCommandEnable; + + return HAL_OK; +} + +/** + * @brief Read Page(s) from NAND memory block (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + uint8_t *pBuffer, uint32_t NumPageToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpagesread = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToRead; + uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) read loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send read page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *buff = *(uint8_t *)deviceaddress; + buff++; + } + + /* Increment read pages number */ + numpagesread++; + + /* Decrement pages to read */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Read Page(s) from NAND memory block (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to destination read buffer. pBuffer should be 16bits aligned + * @param NumPageToRead number of pages to read from block + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + uint16_t *pBuffer, uint32_t NumPageToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpagesread = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToRead; + uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) read loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send read page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Calculate PageSize */ + if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8) + { + hnand->Config.PageSize = hnand->Config.PageSize / 2U; + } + else + { + /* Do nothing */ + /* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/ + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *buff = *(uint16_t *)deviceaddress; + buff++; + } + + /* Increment read pages number */ + numpagesread++; + + /* Decrement pages to read */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Write Page(s) to NAND memory block (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + const uint8_t *pBuffer, uint32_t NumPageToWrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpageswritten = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToWrite; + const uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) write loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send write page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *(__IO uint8_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Increment written pages number */ + numpageswritten++; + + /* Decrement pages to write */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Write Page(s) to NAND memory block (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned + * @param NumPageToWrite number of pages to write to block + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + const uint16_t *pBuffer, uint32_t NumPageToWrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numpageswritten = 0U; + uint32_t nandaddress; + uint32_t nbpages = NumPageToWrite; + const uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Page(s) write loop */ + while ((nbpages != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Send write page command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Calculate PageSize */ + if (hnand->Init.MemoryDataWidth == FMC_NAND_MEM_BUS_WIDTH_8) + { + hnand->Config.PageSize = hnand->Config.PageSize / 2U; + } + else + { + /* Do nothing */ + /* Keep the same PageSize for FMC_NAND_MEM_BUS_WIDTH_16*/ + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.PageSize; index++) + { + *(__IO uint16_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Increment written pages number */ + numpageswritten++; + + /* Decrement pages to write */ + nbpages--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Read Spare area(s) from NAND memory (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + uint8_t *pBuffer, uint32_t NumSpareAreaToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numsparearearead = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaToRead; + uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = COLUMN_ADDRESS(hnand); + + /* Spare area(s) read loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *buff = *(uint8_t *)deviceaddress; + buff++; + } + + /* Increment read spare areas number */ + numsparearearead++; + + /* Decrement spare areas to read */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Read Spare area(s) from NAND memory (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned. + * @param NumSpareAreaToRead Number of spare area to read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + uint16_t *pBuffer, uint32_t NumSpareAreaToRead) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numsparearearead = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaToRead; + uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand)); + + /* Spare area(s) read loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + __DSB(); + + if (hnand->Config.ExtraCommandEnable == ENABLE) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Go back to read mode */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); + __DSB(); + } + + /* Get Data into Buffer */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *buff = *(uint16_t *)deviceaddress; + buff++; + } + + /* Increment read spare areas number */ + numsparearearead++; + + /* Decrement spare areas to read */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Write Spare area(s) to NAND memory (8-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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_8b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + const uint8_t *pBuffer, uint32_t NumSpareAreaTowrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numspareareawritten = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaTowrite; + const uint8_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Page address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = COLUMN_ADDRESS(hnand); + + /* Spare area(s) write loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *(__IO uint8_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Increment written spare areas number */ + numspareareawritten++; + + /* Decrement spare areas to write */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Write Spare area(s) to NAND memory (16-bits addressing) + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @param pBuffer pointer to source buffer to write. pBuffer should be 16bits aligned. + * @param NumSpareAreaTowrite number of spare areas to write to block + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress, + const uint16_t *pBuffer, uint32_t NumSpareAreaTowrite) +{ + uint32_t index; + uint32_t tickstart; + uint32_t deviceaddress; + uint32_t numspareareawritten = 0U; + uint32_t nandaddress; + uint32_t columnaddress; + uint32_t nbspare = NumSpareAreaTowrite; + const uint16_t *buff = pBuffer; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* NAND raw address calculation */ + nandaddress = ARRAY_ADDRESS(pAddress, hnand); + + /* Column in page address */ + columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand)); + + /* Spare area(s) write loop */ + while ((nbspare != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + { + /* Cards with page size <= 512 bytes */ + if ((hnand->Config.PageSize) <= 512U) + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00U; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + else /* (hnand->Config.PageSize) > 512 */ + { + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + __DSB(); + + if (((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)) <= 65535U) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + } + else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); + __DSB(); + } + } + + /* Write data to memory */ + for (index = 0U; index < hnand->Config.SpareAreaSize; index++) + { + *(__IO uint16_t *)deviceaddress = *buff; + buff++; + __DSB(); + } + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + __DSB(); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Read status until NAND is ready */ + while (HAL_NAND_Read_Status(hnand) != NAND_READY) + { + if ((HAL_GetTick() - tickstart) > NAND_WRITE_TIMEOUT) + { + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + + return HAL_TIMEOUT; + } + } + + /* Increment written spare areas number */ + numspareareawritten++; + + /* Decrement spare areas to write */ + nbspare--; + + /* Increment the NAND address */ + nandaddress = (uint32_t)(nandaddress + 1U); + } + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief NAND memory Block erase + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, const NAND_AddressTypeDef *pAddress) +{ + uint32_t deviceaddress; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnand); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Send Erase block command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE0; + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + __DSB(); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + __DSB(); + + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE1; + __DSB(); + + /* Update the NAND controller state */ + hnand->State = HAL_NAND_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnand); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Increment the NAND memory address + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param pAddress pointer to NAND address 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(const 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->Config.BlockSize) + { + pAddress->Page = 0; + pAddress->Block++; + + if (pAddress->Block == hnand->Config.PlaneSize) + { + pAddress->Block = 0; + pAddress->Plane++; + + if (pAddress->Plane == (hnand->Config.PlaneNbr)) + { + status = NAND_INVALID_ADDRESS; + } + } + } + + return (status); +} + +#if (USE_HAL_NAND_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User NAND Callback + * To be used to override the weak predefined callback + * @param hnand : NAND handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID + * @arg @ref HAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID + * @arg @ref HAL_NAND_IT_CB_ID NAND IT callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_NAND_RegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_CallbackIDTypeDef CallbackId, + pNAND_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + if (hnand->State == HAL_NAND_STATE_READY) + { + switch (CallbackId) + { + case HAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = pCallback; + break; + case HAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = pCallback; + break; + case HAL_NAND_IT_CB_ID : + hnand->ItCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hnand->State == HAL_NAND_STATE_RESET) + { + switch (CallbackId) + { + case HAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = pCallback; + break; + case HAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User NAND Callback + * NAND Callback is redirected to the weak predefined callback + * @param hnand : NAND handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_NAND_MSP_INIT_CB_ID NAND MspInit callback ID + * @arg @ref HAL_NAND_MSP_DEINIT_CB_ID NAND MspDeInit callback ID + * @arg @ref HAL_NAND_IT_CB_ID NAND IT callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_NAND_UnRegisterCallback(NAND_HandleTypeDef *hnand, HAL_NAND_CallbackIDTypeDef CallbackId) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hnand->State == HAL_NAND_STATE_READY) + { + switch (CallbackId) + { + case HAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = HAL_NAND_MspInit; + break; + case HAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = HAL_NAND_MspDeInit; + break; + case HAL_NAND_IT_CB_ID : + hnand->ItCallback = HAL_NAND_ITCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hnand->State == HAL_NAND_STATE_RESET) + { + switch (CallbackId) + { + case HAL_NAND_MSP_INIT_CB_ID : + hnand->MspInitCallback = HAL_NAND_MspInit; + break; + case HAL_NAND_MSP_DEINIT_CB_ID : + hnand->MspDeInitCallback = HAL_NAND_MspDeInit; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_NAND_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup NAND_Exported_Functions_Group3 Peripheral 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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Update the NAND state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Enable ECC feature */ + (void)FMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank); + + /* Update the NAND state */ + hnand->State = HAL_NAND_STATE_READY; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Disables dynamically FMC_NAND ECC feature. + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* Update the NAND state */ + hnand->State = HAL_NAND_STATE_BUSY; + + /* Disable ECC feature */ + (void)FMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank); + + /* Update the NAND state */ + hnand->State = HAL_NAND_STATE_READY; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Disables dynamically NAND ECC feature. + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @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; + + /* Check the NAND controller state */ + if (hnand->State == HAL_NAND_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnand->State == HAL_NAND_STATE_READY) + { + /* 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; + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @} + */ + + +/** @defgroup NAND_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### NAND State functions ##### + ============================================================================== + [..] + This subsection permits 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 a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval HAL state + */ +HAL_NAND_StateTypeDef HAL_NAND_GetState(const NAND_HandleTypeDef *hnand) +{ + return hnand->State; +} + +/** + * @brief NAND memory read status + * @param hnand pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @retval NAND status + */ +uint32_t HAL_NAND_Read_Status(const NAND_HandleTypeDef *hnand) +{ + uint32_t data; + uint32_t deviceaddress; + UNUSED(hnand); + + /* Identify the device address */ + deviceaddress = NAND_DEVICE; + + /* Send Read status operation command */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_STATUS; + + /* 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; + } + else + { + return NAND_BUSY; + } +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_NAND_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nor.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nor.c index e69cf19f2..34947831a 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nor.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_nor.c @@ -1,1642 +1,1641 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_nor.c - * @author MCD Application Team - * @brief NOR HAL module driver. - * This file provides a generic firmware to drive NOR memories mounted - * as external device. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 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 - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_NOR_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - Use Functions HAL_NOR_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) MspInitCallback : NOR MspInit. - (+) MspDeInitCallback : NOR MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function HAL_NOR_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) MspInitCallback : NOR MspInit. - (+) MspDeInitCallback : NOR MspDeInit. - This function) takes as parameters the HAL peripheral handle and the Callback ID. - - By default, after the HAL_NOR_Init and if the state is HAL_NOR_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_NOR_Init - and HAL_NOR_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_NOR_Init and HAL_NOR_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_NOR_RegisterCallback before calling HAL_NOR_DeInit - or HAL_NOR_Init function. - - When The compilation define USE_HAL_NOR_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_NOR_MODULE_ENABLED - -/** @defgroup NOR NOR - * @brief NOR driver modules - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ - -/** @defgroup NOR_Private_Defines NOR Private Defines - * @{ - */ - -/* Constants to define address to set to write a command */ -#define NOR_CMD_ADDRESS_FIRST_BYTE (uint16_t)0x0AAA -#define NOR_CMD_ADDRESS_FIRST_CFI_BYTE (uint16_t)0x00AA -#define NOR_CMD_ADDRESS_SECOND_BYTE (uint16_t)0x0555 -#define NOR_CMD_ADDRESS_THIRD_BYTE (uint16_t)0x0AAA - -#define NOR_CMD_ADDRESS_FIRST (uint16_t)0x0555 -#define NOR_CMD_ADDRESS_FIRST_CFI (uint16_t)0x0055 -#define NOR_CMD_ADDRESS_SECOND (uint16_t)0x02AA -#define NOR_CMD_ADDRESS_THIRD (uint16_t)0x0555 -#define NOR_CMD_ADDRESS_FOURTH (uint16_t)0x0555 -#define NOR_CMD_ADDRESS_FIFTH (uint16_t)0x02AA -#define NOR_CMD_ADDRESS_SIXTH (uint16_t)0x0555 - -/* Constants to define data to program a command */ -#define NOR_CMD_DATA_READ_RESET (uint16_t)0x00F0 -#define NOR_CMD_DATA_FIRST (uint16_t)0x00AA -#define NOR_CMD_DATA_SECOND (uint16_t)0x0055 -#define NOR_CMD_DATA_AUTO_SELECT (uint16_t)0x0090 -#define NOR_CMD_DATA_PROGRAM (uint16_t)0x00A0 -#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD (uint16_t)0x0080 -#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH (uint16_t)0x00AA -#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH (uint16_t)0x0055 -#define NOR_CMD_DATA_CHIP_ERASE (uint16_t)0x0010 -#define NOR_CMD_DATA_CFI (uint16_t)0x0098 - -#define NOR_CMD_DATA_BUFFER_AND_PROG (uint8_t)0x25 -#define NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM (uint8_t)0x29 -#define NOR_CMD_DATA_BLOCK_ERASE (uint8_t)0x30 - -#define NOR_CMD_READ_ARRAY (uint16_t)0x00FF -#define NOR_CMD_WORD_PROGRAM (uint16_t)0x0040 -#define NOR_CMD_BUFFERED_PROGRAM (uint16_t)0x00E8 -#define NOR_CMD_CONFIRM (uint16_t)0x00D0 -#define NOR_CMD_BLOCK_ERASE (uint16_t)0x0020 -#define NOR_CMD_BLOCK_UNLOCK (uint16_t)0x0060 -#define NOR_CMD_READ_STATUS_REG (uint16_t)0x0070 -#define NOR_CMD_CLEAR_STATUS_REG (uint16_t)0x0050 - -/* Mask on NOR STATUS REGISTER */ -#define NOR_MASK_STATUS_DQ4 (uint16_t)0x0010 -#define NOR_MASK_STATUS_DQ5 (uint16_t)0x0020 -#define NOR_MASK_STATUS_DQ6 (uint16_t)0x0040 -#define NOR_MASK_STATUS_DQ7 (uint16_t)0x0080 - -/* Address of the primary command set */ -#define NOR_ADDRESS_COMMAND_SET (uint16_t)0x0013 - -/* Command set code assignment (defined in JEDEC JEP137B version may 2004) */ -#define NOR_INTEL_SHARP_EXT_COMMAND_SET (uint16_t)0x0001 /* Supported in this driver */ -#define NOR_AMD_FUJITSU_COMMAND_SET (uint16_t)0x0002 /* Supported in this driver */ -#define NOR_INTEL_STANDARD_COMMAND_SET (uint16_t)0x0003 /* Not Supported in this driver */ -#define NOR_AMD_FUJITSU_EXT_COMMAND_SET (uint16_t)0x0004 /* Not Supported in this driver */ -#define NOR_WINDBOND_STANDARD_COMMAND_SET (uint16_t)0x0006 /* Not Supported in this driver */ -#define NOR_MITSUBISHI_STANDARD_COMMAND_SET (uint16_t)0x0100 /* Not Supported in this driver */ -#define NOR_MITSUBISHI_EXT_COMMAND_SET (uint16_t)0x0101 /* Not Supported in this driver */ -#define NOR_PAGE_WRITE_COMMAND_SET (uint16_t)0x0102 /* Not Supported in this driver */ -#define NOR_INTEL_PERFORMANCE_COMMAND_SET (uint16_t)0x0200 /* Not Supported in this driver */ -#define NOR_INTEL_DATA_COMMAND_SET (uint16_t)0x0210 /* Not Supported in this driver */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup NOR_Private_Variables NOR Private Variables - * @{ - */ - -static uint32_t uwNORMemoryDataWidth = NOR_MEMORY_8B; - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @defgroup NOR_Exported_Functions NOR Exported Functions - * @{ - */ - -/** @defgroup NOR_Exported_Functions_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 a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @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) -{ - uint32_t deviceaddress; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR handle parameter */ - if (hnor == NULL) - { - return HAL_ERROR; - } - - if (hnor->State == HAL_NOR_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hnor->Lock = HAL_UNLOCKED; - -#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) - if (hnor->MspInitCallback == NULL) - { - hnor->MspInitCallback = HAL_NOR_MspInit; - } - - /* Init the low level hardware */ - hnor->MspInitCallback(hnor); -#else - /* Initialize the low level hardware (MSP) */ - HAL_NOR_MspInit(hnor); -#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */ - } - - /* Initialize NOR control Interface */ - (void)FMC_NORSRAM_Init(hnor->Instance, &(hnor->Init)); - - /* Initialize NOR timing Interface */ - (void)FMC_NORSRAM_Timing_Init(hnor->Instance, Timing, hnor->Init.NSBank); - - /* Initialize NOR extended mode timing Interface */ - (void)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); - - /* Initialize NOR Memory Data Width*/ - if (hnor->Init.MemoryDataWidth == FMC_NORSRAM_MEM_BUS_WIDTH_8) - { - uwNORMemoryDataWidth = NOR_MEMORY_8B; - } - else - { - uwNORMemoryDataWidth = NOR_MEMORY_16B; - } - - /* Enable FMC Peripheral */ - __FMC_ENABLE(); - - /* Initialize the NOR controller state */ - hnor->State = HAL_NOR_STATE_READY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - if (hnor->Init.WriteOperation == FMC_WRITE_OPERATION_DISABLE) - { - (void)FMC_NORSRAM_WriteOperation_Disable(hnor->Instance, hnor->Init.NSBank); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_PROTECTED; - } - else - { - /* Get the value of the command set */ - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI_BYTE), - NOR_CMD_DATA_CFI); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI); - } - - hnor->CommandSet = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_ADDRESS_COMMAND_SET); - - status = HAL_NOR_ReturnToReadMode(hnor); - } - - return status; -} - -/** - * @brief Perform NOR memory De-Initialization sequence - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor) -{ -#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) - if (hnor->MspDeInitCallback == NULL) - { - hnor->MspDeInitCallback = HAL_NOR_MspDeInit; - } - - /* DeInit the low level hardware */ - hnor->MspDeInitCallback(hnor); -#else - /* De-Initialize the low level hardware (MSP) */ - HAL_NOR_MspDeInit(hnor); -#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */ - - /* Configure the NOR registers with their reset values */ - (void)FMC_NORSRAM_DeInit(hnor->Instance, hnor->Extended, hnor->Init.NSBank); - - /* Reset 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 a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval None - */ -__weak void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval None - */ -__weak void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 MSP Wait for Ready/Busy signal - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @param Timeout Maximum timeout value - * @retval None - */ -__weak void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hnor); - UNUSED(Timeout); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_NOR_MspWait could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup NOR_Exported_Functions_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 a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @param pNOR_ID pointer to NOR ID structure - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID) -{ - uint32_t deviceaddress; - HAL_NOR_StateTypeDef state; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - state = hnor->State; - if (state == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (state == HAL_NOR_STATE_PROTECTED) - { - return HAL_ERROR; - } - else if (state == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send read ID command */ - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), - NOR_CMD_DATA_AUTO_SELECT); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), - NOR_CMD_DATA_AUTO_SELECT); - } - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - NOR_WRITE(deviceaddress, NOR_CMD_DATA_AUTO_SELECT); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - if (status != HAL_ERROR) - { - /* Read the NOR IDs */ - pNOR_ID->Manufacturer_Code = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, MC_ADDRESS); - pNOR_ID->Device_Code1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, - DEVICE_CODE1_ADDR); - pNOR_ID->Device_Code2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, - DEVICE_CODE2_ADDR); - pNOR_ID->Device_Code3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, - DEVICE_CODE3_ADDR); - } - - /* Check the NOR controller state */ - hnor->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @brief Returns the NOR memory to Read mode. - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor) -{ - uint32_t deviceaddress; - HAL_NOR_StateTypeDef state; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - state = hnor->State; - if (state == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (state == HAL_NOR_STATE_PROTECTED) - { - return HAL_ERROR; - } - else if (state == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - NOR_WRITE(deviceaddress, NOR_CMD_DATA_READ_RESET); - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - /* Check the NOR controller state */ - hnor->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @brief Read data from NOR memory - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @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) -{ - uint32_t deviceaddress; - HAL_NOR_StateTypeDef state; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - state = hnor->State; - if (state == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (state == HAL_NOR_STATE_PROTECTED) - { - return HAL_ERROR; - } - else if (state == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send read data command */ - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), - NOR_CMD_DATA_READ_RESET); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), - NOR_CMD_DATA_READ_RESET); - } - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - NOR_WRITE(pAddress, NOR_CMD_READ_ARRAY); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - if (status != HAL_ERROR) - { - /* Read the data */ - *pData = (uint16_t)(*(__IO uint32_t *)pAddress); - } - - /* Check the NOR controller state */ - hnor->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @brief Program data to NOR memory - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @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) -{ - uint32_t deviceaddress; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - if (hnor->State == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnor->State == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send program data command */ - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), - NOR_CMD_DATA_PROGRAM); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_PROGRAM); - } - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - NOR_WRITE(pAddress, NOR_CMD_WORD_PROGRAM); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - if (status != HAL_ERROR) - { - /* Write the data */ - NOR_WRITE(pAddress, *pData); - } - - /* Check the NOR controller state */ - hnor->State = HAL_NOR_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @brief Reads a half-word buffer from the NOR memory. - * @param hnor pointer to the 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) -{ - uint32_t deviceaddress; - uint32_t size = uwBufferSize; - uint32_t address = uwAddress; - uint16_t *data = pData; - HAL_NOR_StateTypeDef state; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - state = hnor->State; - if (state == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (state == HAL_NOR_STATE_PROTECTED) - { - return HAL_ERROR; - } - else if (state == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send read data command */ - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), - NOR_CMD_DATA_READ_RESET); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), - NOR_CMD_DATA_READ_RESET); - } - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - if (status != HAL_ERROR) - { - /* Read buffer */ - while (size > 0U) - { - *data = *(__IO uint16_t *)address; - data++; - address += 2U; - size--; - } - } - - /* Check the NOR controller state */ - hnor->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @brief Writes a half-word buffer to the NOR memory. This function must be used - only with S29GL128P NOR memory. - * @param hnor pointer to the NOR handle - * @param uwAddress NOR memory internal start write address - * @param pData pointer to source data buffer. - * @param uwBufferSize Size of the buffer to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, - uint32_t uwBufferSize) -{ - uint16_t *p_currentaddress; - const uint16_t *p_endaddress; - uint16_t *data = pData; - uint32_t deviceaddress; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - if (hnor->State == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnor->State == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Initialize variables */ - p_currentaddress = (uint16_t *)(deviceaddress + uwAddress); - p_endaddress = (uint16_t *)(deviceaddress + uwAddress + (2U * (uwBufferSize - 1U))); - - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - /* Issue unlock command sequence */ - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - } - else - { - /* Issue unlock command sequence */ - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - } - /* Write Buffer Load Command */ - NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG); - NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U)); - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - /* Write Buffer Load Command */ - NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_BUFFERED_PROGRAM); - NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U)); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - if (status != HAL_ERROR) - { - /* Load Data into NOR Buffer */ - while (p_currentaddress <= p_endaddress) - { - NOR_WRITE(p_currentaddress, *data); - - data++; - p_currentaddress ++; - } - - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM); - } - else /* => hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET */ - { - NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_CONFIRM); - } - } - - /* Check the NOR controller state */ - hnor->State = HAL_NOR_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; - -} - -/** - * @brief Erase the specified block of the NOR memory - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @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) -{ - uint32_t deviceaddress; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the NOR controller state */ - if (hnor->State == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnor->State == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send block erase command sequence */ - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH); - } - NOR_WRITE((uint32_t)(BlockAddress + Address), NOR_CMD_DATA_BLOCK_ERASE); - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_UNLOCK); - NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM); - NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_ERASE); - NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM); - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - /* Check the NOR memory status and update the controller state */ - hnor->State = HAL_NOR_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; - -} - -/** - * @brief Erase the entire NOR chip. - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @param Address Device address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address) -{ - uint32_t deviceaddress; - HAL_StatusTypeDef status = HAL_OK; - UNUSED(Address); - - /* Check the NOR controller state */ - if (hnor->State == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hnor->State == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send NOR chip erase command sequence */ - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), - NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), - NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH), - NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH); - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SIXTH), - NOR_CMD_DATA_CHIP_ERASE); - } - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_ERROR; - } - - /* Check the NOR memory status and update the controller state */ - hnor->State = HAL_NOR_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return status; -} - -/** - * @brief Read NOR flash CFI IDs - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @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) -{ - uint32_t deviceaddress; - HAL_NOR_StateTypeDef state; - - /* Check the NOR controller state */ - state = hnor->State; - if (state == HAL_NOR_STATE_BUSY) - { - return HAL_BUSY; - } - else if (state == HAL_NOR_STATE_PROTECTED) - { - return HAL_ERROR; - } - else if (state == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Select the NOR device address */ - if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) - { - deviceaddress = NOR_MEMORY_ADRESS1; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) - { - deviceaddress = NOR_MEMORY_ADRESS2; - } - else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) - { - deviceaddress = NOR_MEMORY_ADRESS3; - } - else /* FMC_NORSRAM_BANK4 */ - { - deviceaddress = NOR_MEMORY_ADRESS4; - } - - /* Send read CFI query command */ - if (uwNORMemoryDataWidth == NOR_MEMORY_8B) - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI_BYTE), - NOR_CMD_DATA_CFI); - } - else - { - NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI); - } - /* read the NOR CFI information */ - pNOR_CFI->CFI_1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI1_ADDRESS); - pNOR_CFI->CFI_2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI2_ADDRESS); - pNOR_CFI->CFI_3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI3_ADDRESS); - pNOR_CFI->CFI_4 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI4_ADDRESS); - - /* Check the NOR controller state */ - hnor->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hnor); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User NOR Callback - * To be used to override the weak predefined callback - * @param hnor : NOR handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID - * @arg @ref HAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_NOR_RegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId, - pNOR_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_NOR_StateTypeDef state; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - state = hnor->State; - if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_RESET) || (state == HAL_NOR_STATE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_NOR_MSP_INIT_CB_ID : - hnor->MspInitCallback = pCallback; - break; - case HAL_NOR_MSP_DEINIT_CB_ID : - hnor->MspDeInitCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User NOR Callback - * NOR Callback is redirected to the weak predefined callback - * @param hnor : NOR handle - * @param CallbackId : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID - * @arg @ref HAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_NOR_UnRegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_NOR_StateTypeDef state; - - state = hnor->State; - if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_RESET) || (state == HAL_NOR_STATE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_NOR_MSP_INIT_CB_ID : - hnor->MspInitCallback = HAL_NOR_MspInit; - break; - case HAL_NOR_MSP_DEINIT_CB_ID : - hnor->MspDeInitCallback = HAL_NOR_MspDeInit; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */ - -/** - * @} - */ - -/** @defgroup NOR_Exported_Functions_Group3 NOR 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 a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor) -{ - /* Check the NOR controller state */ - if (hnor->State == HAL_NOR_STATE_PROTECTED) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Enable write operation */ - (void)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); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Disables dynamically NOR write operation. - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor) -{ - /* Check the NOR controller state */ - if (hnor->State == HAL_NOR_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hnor); - - /* Update the NOR controller state */ - hnor->State = HAL_NOR_STATE_BUSY; - - /* Disable write operation */ - (void)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); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup NOR_Exported_Functions_Group4 NOR State functions - * @brief Peripheral State functions - * -@verbatim - ============================================================================== - ##### NOR State functions ##### - ============================================================================== - [..] - This subsection permits 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 a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @retval NOR controller state - */ -HAL_NOR_StateTypeDef HAL_NOR_GetState(const NOR_HandleTypeDef *hnor) -{ - return hnor->State; -} - -/** - * @brief Returns the NOR operation status. - * @param hnor pointer to a NOR_HandleTypeDef structure that contains - * the configuration information for NOR module. - * @param Address Device address - * @param Timeout NOR programming Timeout - * @retval NOR_Status The returned value can be: HAL_NOR_STATUS_SUCCESS, HAL_NOR_STATUS_ERROR - * or HAL_NOR_STATUS_TIMEOUT - */ -HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout) -{ - HAL_NOR_StatusTypeDef status = HAL_NOR_STATUS_ONGOING; - uint16_t tmpsr1; - uint16_t tmpsr2; - uint32_t tickstart; - - /* Poll on NOR memory Ready/Busy signal ------------------------------------*/ - HAL_NOR_MspWait(hnor, Timeout); - - /* Get the NOR memory operation status -------------------------------------*/ - - /* Get tick */ - tickstart = HAL_GetTick(); - - if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) - { - while ((status != HAL_NOR_STATUS_SUCCESS) && (status != HAL_NOR_STATUS_TIMEOUT)) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - status = HAL_NOR_STATUS_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 HAL_NOR_STATUS_SUCCESS */ - if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6)) - { - return HAL_NOR_STATUS_SUCCESS ; - } - - if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5) - { - status = HAL_NOR_STATUS_ONGOING; - } - - tmpsr1 = *(__IO uint16_t *)Address; - tmpsr2 = *(__IO uint16_t *)Address; - - /* If DQ6 did not toggle between the two reads then return HAL_NOR_STATUS_SUCCESS */ - if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6)) - { - return HAL_NOR_STATUS_SUCCESS; - } - if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5) - { - return HAL_NOR_STATUS_ERROR; - } - } - } - else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) - { - do - { - NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); - tmpsr2 = *(__IO uint16_t *)(Address); - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - return HAL_NOR_STATUS_TIMEOUT; - } - } - } while ((tmpsr2 & NOR_MASK_STATUS_DQ7) == 0U); - - NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); - tmpsr1 = *(__IO uint16_t *)(Address); - if ((tmpsr1 & (NOR_MASK_STATUS_DQ5 | NOR_MASK_STATUS_DQ4)) != 0U) - { - /* Clear the Status Register */ - NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); - status = HAL_NOR_STATUS_ERROR; - } - else - { - status = HAL_NOR_STATUS_SUCCESS; - } - } - else - { - /* Primary command set not supported by the driver */ - status = HAL_NOR_STATUS_ERROR; - } - - /* Return the operation status */ - return status; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_NOR_MODULE_ENABLED */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_nor.c + * @author MCD Application Team + * @brief NOR HAL module driver. + * This file provides a generic firmware to drive NOR memories mounted + * as external device. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 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 + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_NOR_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_NOR_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : NOR MspInit. + (+) MspDeInitCallback : NOR MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function HAL_NOR_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) MspInitCallback : NOR MspInit. + (+) MspDeInitCallback : NOR MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + + By default, after the HAL_NOR_Init and if the state is HAL_NOR_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_NOR_Init + and HAL_NOR_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_NOR_Init and HAL_NOR_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_NOR_RegisterCallback before calling HAL_NOR_DeInit + or HAL_NOR_Init function. + + When The compilation define USE_HAL_NOR_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_NOR_MODULE_ENABLED + +/** @defgroup NOR NOR + * @brief NOR driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup NOR_Private_Defines NOR Private Defines + * @{ + */ + +/* Constants to define address to set to write a command */ +#define NOR_CMD_ADDRESS_FIRST_BYTE (uint16_t)0x0AAA +#define NOR_CMD_ADDRESS_FIRST_CFI_BYTE (uint16_t)0x00AA +#define NOR_CMD_ADDRESS_SECOND_BYTE (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_THIRD_BYTE (uint16_t)0x0AAA + +#define NOR_CMD_ADDRESS_FIRST (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_FIRST_CFI (uint16_t)0x0055 +#define NOR_CMD_ADDRESS_SECOND (uint16_t)0x02AA +#define NOR_CMD_ADDRESS_THIRD (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_FOURTH (uint16_t)0x0555 +#define NOR_CMD_ADDRESS_FIFTH (uint16_t)0x02AA +#define NOR_CMD_ADDRESS_SIXTH (uint16_t)0x0555 + +/* Constants to define data to program a command */ +#define NOR_CMD_DATA_READ_RESET (uint16_t)0x00F0 +#define NOR_CMD_DATA_FIRST (uint16_t)0x00AA +#define NOR_CMD_DATA_SECOND (uint16_t)0x0055 +#define NOR_CMD_DATA_AUTO_SELECT (uint16_t)0x0090 +#define NOR_CMD_DATA_PROGRAM (uint16_t)0x00A0 +#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD (uint16_t)0x0080 +#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH (uint16_t)0x00AA +#define NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH (uint16_t)0x0055 +#define NOR_CMD_DATA_CHIP_ERASE (uint16_t)0x0010 +#define NOR_CMD_DATA_CFI (uint16_t)0x0098 + +#define NOR_CMD_DATA_BUFFER_AND_PROG (uint8_t)0x25 +#define NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM (uint8_t)0x29 +#define NOR_CMD_DATA_BLOCK_ERASE (uint8_t)0x30 + +#define NOR_CMD_READ_ARRAY (uint16_t)0x00FF +#define NOR_CMD_WORD_PROGRAM (uint16_t)0x0040 +#define NOR_CMD_BUFFERED_PROGRAM (uint16_t)0x00E8 +#define NOR_CMD_CONFIRM (uint16_t)0x00D0 +#define NOR_CMD_BLOCK_ERASE (uint16_t)0x0020 +#define NOR_CMD_BLOCK_UNLOCK (uint16_t)0x0060 +#define NOR_CMD_READ_STATUS_REG (uint16_t)0x0070 +#define NOR_CMD_CLEAR_STATUS_REG (uint16_t)0x0050 + +/* Mask on NOR STATUS REGISTER */ +#define NOR_MASK_STATUS_DQ4 (uint16_t)0x0010 +#define NOR_MASK_STATUS_DQ5 (uint16_t)0x0020 +#define NOR_MASK_STATUS_DQ6 (uint16_t)0x0040 +#define NOR_MASK_STATUS_DQ7 (uint16_t)0x0080 + +/* Address of the primary command set */ +#define NOR_ADDRESS_COMMAND_SET (uint16_t)0x0013 + +/* Command set code assignment (defined in JEDEC JEP137B version may 2004) */ +#define NOR_INTEL_SHARP_EXT_COMMAND_SET (uint16_t)0x0001 /* Supported in this driver */ +#define NOR_AMD_FUJITSU_COMMAND_SET (uint16_t)0x0002 /* Supported in this driver */ +#define NOR_INTEL_STANDARD_COMMAND_SET (uint16_t)0x0003 /* Not Supported in this driver */ +#define NOR_AMD_FUJITSU_EXT_COMMAND_SET (uint16_t)0x0004 /* Not Supported in this driver */ +#define NOR_WINDBOND_STANDARD_COMMAND_SET (uint16_t)0x0006 /* Not Supported in this driver */ +#define NOR_MITSUBISHI_STANDARD_COMMAND_SET (uint16_t)0x0100 /* Not Supported in this driver */ +#define NOR_MITSUBISHI_EXT_COMMAND_SET (uint16_t)0x0101 /* Not Supported in this driver */ +#define NOR_PAGE_WRITE_COMMAND_SET (uint16_t)0x0102 /* Not Supported in this driver */ +#define NOR_INTEL_PERFORMANCE_COMMAND_SET (uint16_t)0x0200 /* Not Supported in this driver */ +#define NOR_INTEL_DATA_COMMAND_SET (uint16_t)0x0210 /* Not Supported in this driver */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/** @defgroup NOR_Private_Variables NOR Private Variables + * @{ + */ + +static uint32_t uwNORMemoryDataWidth = NOR_MEMORY_8B; + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup NOR_Exported_Functions NOR Exported Functions + * @{ + */ + +/** @defgroup NOR_Exported_Functions_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 a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @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) +{ + uint32_t deviceaddress; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR handle parameter */ + if (hnor == NULL) + { + return HAL_ERROR; + } + + if (hnor->State == HAL_NOR_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hnor->Lock = HAL_UNLOCKED; + +#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) + if (hnor->MspInitCallback == NULL) + { + hnor->MspInitCallback = HAL_NOR_MspInit; + } + + /* Init the low level hardware */ + hnor->MspInitCallback(hnor); +#else + /* Initialize the low level hardware (MSP) */ + HAL_NOR_MspInit(hnor); +#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */ + } + + /* Initialize NOR control Interface */ + (void)FMC_NORSRAM_Init(hnor->Instance, &(hnor->Init)); + + /* Initialize NOR timing Interface */ + (void)FMC_NORSRAM_Timing_Init(hnor->Instance, Timing, hnor->Init.NSBank); + + /* Initialize NOR extended mode timing Interface */ + (void)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); + + /* Initialize NOR Memory Data Width*/ + if (hnor->Init.MemoryDataWidth == FMC_NORSRAM_MEM_BUS_WIDTH_8) + { + uwNORMemoryDataWidth = NOR_MEMORY_8B; + } + else + { + uwNORMemoryDataWidth = NOR_MEMORY_16B; + } + + /* Enable FMC Peripheral */ + __FMC_ENABLE(); + + /* Initialize the NOR controller state */ + hnor->State = HAL_NOR_STATE_READY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + if (hnor->Init.WriteOperation == FMC_WRITE_OPERATION_DISABLE) + { + (void)FMC_NORSRAM_WriteOperation_Disable(hnor->Instance, hnor->Init.NSBank); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_PROTECTED; + } + else + { + /* Get the value of the command set */ + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI_BYTE), + NOR_CMD_DATA_CFI); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI); + } + + hnor->CommandSet = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_ADDRESS_COMMAND_SET); + + status = HAL_NOR_ReturnToReadMode(hnor); + } + + return status; +} + +/** + * @brief Perform NOR memory De-Initialization sequence + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_DeInit(NOR_HandleTypeDef *hnor) +{ +#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) + if (hnor->MspDeInitCallback == NULL) + { + hnor->MspDeInitCallback = HAL_NOR_MspDeInit; + } + + /* DeInit the low level hardware */ + hnor->MspDeInitCallback(hnor); +#else + /* De-Initialize the low level hardware (MSP) */ + HAL_NOR_MspDeInit(hnor); +#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */ + + /* Configure the NOR registers with their reset values */ + (void)FMC_NORSRAM_DeInit(hnor->Instance, hnor->Extended, hnor->Init.NSBank); + + /* Reset 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 a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval None + */ +__weak void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval None + */ +__weak void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 MSP Wait for Ready/Busy signal + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Timeout Maximum timeout value + * @retval None + */ +__weak void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hnor); + UNUSED(Timeout); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_NOR_MspWait could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup NOR_Exported_Functions_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 a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param pNOR_ID pointer to NOR ID structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID) +{ + uint32_t deviceaddress; + HAL_NOR_StateTypeDef state; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (state == HAL_NOR_STATE_PROTECTED) + { + return HAL_ERROR; + } + else if (state == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read ID command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), + NOR_CMD_DATA_AUTO_SELECT); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_AUTO_SELECT); + } + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_DATA_AUTO_SELECT); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + if (status != HAL_ERROR) + { + /* Read the NOR IDs */ + pNOR_ID->Manufacturer_Code = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, MC_ADDRESS); + pNOR_ID->Device_Code1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, + DEVICE_CODE1_ADDR); + pNOR_ID->Device_Code2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, + DEVICE_CODE2_ADDR); + pNOR_ID->Device_Code3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, + DEVICE_CODE3_ADDR); + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @brief Returns the NOR memory to Read mode. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor) +{ + uint32_t deviceaddress; + HAL_NOR_StateTypeDef state; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (state == HAL_NOR_STATE_PROTECTED) + { + return HAL_ERROR; + } + else if (state == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_DATA_READ_RESET); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @brief Read data from NOR memory + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @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) +{ + uint32_t deviceaddress; + HAL_NOR_StateTypeDef state; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (state == HAL_NOR_STATE_PROTECTED) + { + return HAL_ERROR; + } + else if (state == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read data command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), + NOR_CMD_DATA_READ_RESET); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_READ_RESET); + } + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(pAddress, NOR_CMD_READ_ARRAY); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + if (status != HAL_ERROR) + { + /* Read the data */ + *pData = (uint16_t)(*(__IO uint32_t *)pAddress); + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @brief Program data to NOR memory + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @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) +{ + uint32_t deviceaddress; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + if (hnor->State == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnor->State == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send program data command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), + NOR_CMD_DATA_PROGRAM); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), NOR_CMD_DATA_PROGRAM); + } + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(pAddress, NOR_CMD_WORD_PROGRAM); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + if (status != HAL_ERROR) + { + /* Write the data */ + NOR_WRITE(pAddress, *pData); + } + + /* Check the NOR controller state */ + hnor->State = HAL_NOR_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @brief Reads a half-word buffer from the NOR memory. + * @param hnor pointer to the 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) +{ + uint32_t deviceaddress; + uint32_t size = uwBufferSize; + uint32_t address = uwAddress; + uint16_t *data = pData; + HAL_NOR_StateTypeDef state; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (state == HAL_NOR_STATE_PROTECTED) + { + return HAL_ERROR; + } + else if (state == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read data command */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), + NOR_CMD_DATA_READ_RESET); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_READ_RESET); + } + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE(deviceaddress, NOR_CMD_READ_ARRAY); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + if (status != HAL_ERROR) + { + /* Read buffer */ + while (size > 0U) + { + *data = *(__IO uint16_t *)address; + data++; + address += 2U; + size--; + } + } + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @brief Writes a half-word buffer to the NOR memory. This function must be used + only with S29GL128P NOR memory. + * @param hnor pointer to the NOR handle + * @param uwAddress NOR memory internal start write address + * @param pData pointer to source data buffer. + * @param uwBufferSize Size of the buffer to write + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, + uint32_t uwBufferSize) +{ + uint16_t *p_currentaddress; + const uint16_t *p_endaddress; + uint16_t *data = pData; + uint32_t deviceaddress; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + if (hnor->State == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnor->State == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Initialize variables */ + p_currentaddress = (uint16_t *)(deviceaddress + uwAddress); + p_endaddress = (uint16_t *)(deviceaddress + uwAddress + (2U * (uwBufferSize - 1U))); + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + /* Issue unlock command sequence */ + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + } + else + { + /* Issue unlock command sequence */ + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + } + /* Write Buffer Load Command */ + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG); + NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U)); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + /* Write Buffer Load Command */ + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_BUFFERED_PROGRAM); + NOR_WRITE((deviceaddress + uwAddress), (uint16_t)(uwBufferSize - 1U)); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + if (status != HAL_ERROR) + { + /* Load Data into NOR Buffer */ + while (p_currentaddress <= p_endaddress) + { + NOR_WRITE(p_currentaddress, *data); + + data++; + p_currentaddress ++; + } + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_DATA_BUFFER_AND_PROG_CONFIRM); + } + else /* => hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET */ + { + NOR_WRITE((deviceaddress + uwAddress), NOR_CMD_CONFIRM); + } + } + + /* Check the NOR controller state */ + hnor->State = HAL_NOR_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; + +} + +/** + * @brief Erase the specified block of the NOR memory + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @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) +{ + uint32_t deviceaddress; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the NOR controller state */ + if (hnor->State == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnor->State == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send block erase command sequence */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH); + } + NOR_WRITE((uint32_t)(BlockAddress + Address), NOR_CMD_DATA_BLOCK_ERASE); + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_UNLOCK); + NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM); + NOR_WRITE((BlockAddress + Address), NOR_CMD_BLOCK_ERASE); + NOR_WRITE((BlockAddress + Address), NOR_CMD_CONFIRM); + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + /* Check the NOR memory status and update the controller state */ + hnor->State = HAL_NOR_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; + +} + +/** + * @brief Erase the entire NOR chip. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Address Device address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address) +{ + uint32_t deviceaddress; + HAL_StatusTypeDef status = HAL_OK; + UNUSED(Address); + + /* Check the NOR controller state */ + if (hnor->State == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hnor->State == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send NOR chip erase command sequence */ + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_BYTE), + NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND_BYTE), + NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD_BYTE), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST), NOR_CMD_DATA_FIRST); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SECOND), NOR_CMD_DATA_SECOND); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_THIRD), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_THIRD); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FOURTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FOURTH); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIFTH), + NOR_CMD_DATA_CHIP_BLOCK_ERASE_FIFTH); + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_SIXTH), + NOR_CMD_DATA_CHIP_ERASE); + } + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_ERROR; + } + + /* Check the NOR memory status and update the controller state */ + hnor->State = HAL_NOR_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return status; +} + +/** + * @brief Read NOR flash CFI IDs + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @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) +{ + uint32_t deviceaddress; + HAL_NOR_StateTypeDef state; + + /* Check the NOR controller state */ + state = hnor->State; + if (state == HAL_NOR_STATE_BUSY) + { + return HAL_BUSY; + } + else if (state == HAL_NOR_STATE_PROTECTED) + { + return HAL_ERROR; + } + else if (state == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Select the NOR device address */ + if (hnor->Init.NSBank == FMC_NORSRAM_BANK1) + { + deviceaddress = NOR_MEMORY_ADRESS1; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK2) + { + deviceaddress = NOR_MEMORY_ADRESS2; + } + else if (hnor->Init.NSBank == FMC_NORSRAM_BANK3) + { + deviceaddress = NOR_MEMORY_ADRESS3; + } + else /* FMC_NORSRAM_BANK4 */ + { + deviceaddress = NOR_MEMORY_ADRESS4; + } + + /* Send read CFI query command */ + if (uwNORMemoryDataWidth == NOR_MEMORY_8B) + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI_BYTE), + NOR_CMD_DATA_CFI); + } + else + { + NOR_WRITE(NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, NOR_CMD_ADDRESS_FIRST_CFI), NOR_CMD_DATA_CFI); + } + /* read the NOR CFI information */ + pNOR_CFI->CFI_1 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI1_ADDRESS); + pNOR_CFI->CFI_2 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI2_ADDRESS); + pNOR_CFI->CFI_3 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI3_ADDRESS); + pNOR_CFI->CFI_4 = *(__IO uint16_t *) NOR_ADDR_SHIFT(deviceaddress, uwNORMemoryDataWidth, CFI4_ADDRESS); + + /* Check the NOR controller state */ + hnor->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hnor); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +#if (USE_HAL_NOR_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User NOR Callback + * To be used to override the weak predefined callback + * @param hnor : NOR handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID + * @arg @ref HAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_NOR_RegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId, + pNOR_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_NOR_StateTypeDef state; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + state = hnor->State; + if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_RESET) || (state == HAL_NOR_STATE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_NOR_MSP_INIT_CB_ID : + hnor->MspInitCallback = pCallback; + break; + case HAL_NOR_MSP_DEINIT_CB_ID : + hnor->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User NOR Callback + * NOR Callback is redirected to the weak predefined callback + * @param hnor : NOR handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_NOR_MSP_INIT_CB_ID NOR MspInit callback ID + * @arg @ref HAL_NOR_MSP_DEINIT_CB_ID NOR MspDeInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_NOR_UnRegisterCallback(NOR_HandleTypeDef *hnor, HAL_NOR_CallbackIDTypeDef CallbackId) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_NOR_StateTypeDef state; + + state = hnor->State; + if ((state == HAL_NOR_STATE_READY) || (state == HAL_NOR_STATE_RESET) || (state == HAL_NOR_STATE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_NOR_MSP_INIT_CB_ID : + hnor->MspInitCallback = HAL_NOR_MspInit; + break; + case HAL_NOR_MSP_DEINIT_CB_ID : + hnor->MspDeInitCallback = HAL_NOR_MspDeInit; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* (USE_HAL_NOR_REGISTER_CALLBACKS) */ + +/** + * @} + */ + +/** @defgroup NOR_Exported_Functions_Group3 NOR 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 a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_WriteOperation_Enable(NOR_HandleTypeDef *hnor) +{ + /* Check the NOR controller state */ + if (hnor->State == HAL_NOR_STATE_PROTECTED) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Enable write operation */ + (void)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); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Disables dynamically NOR write operation. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_NOR_WriteOperation_Disable(NOR_HandleTypeDef *hnor) +{ + /* Check the NOR controller state */ + if (hnor->State == HAL_NOR_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hnor); + + /* Update the NOR controller state */ + hnor->State = HAL_NOR_STATE_BUSY; + + /* Disable write operation */ + (void)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); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup NOR_Exported_Functions_Group4 NOR State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### NOR State functions ##### + ============================================================================== + [..] + This subsection permits 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 a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @retval NOR controller state + */ +HAL_NOR_StateTypeDef HAL_NOR_GetState(const NOR_HandleTypeDef *hnor) +{ + return hnor->State; +} + +/** + * @brief Returns the NOR operation status. + * @param hnor pointer to a NOR_HandleTypeDef structure that contains + * the configuration information for NOR module. + * @param Address Device address + * @param Timeout NOR programming Timeout + * @retval NOR_Status The returned value can be: HAL_NOR_STATUS_SUCCESS, HAL_NOR_STATUS_ERROR + * or HAL_NOR_STATUS_TIMEOUT + */ +HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Address, uint32_t Timeout) +{ + HAL_NOR_StatusTypeDef status = HAL_NOR_STATUS_ONGOING; + uint16_t tmpsr1; + uint16_t tmpsr2; + uint32_t tickstart; + + /* Poll on NOR memory Ready/Busy signal ------------------------------------*/ + HAL_NOR_MspWait(hnor, Timeout); + + /* Get the NOR memory operation status -------------------------------------*/ + + /* Get tick */ + tickstart = HAL_GetTick(); + + if (hnor->CommandSet == NOR_AMD_FUJITSU_COMMAND_SET) + { + while ((status != HAL_NOR_STATUS_SUCCESS) && (status != HAL_NOR_STATUS_TIMEOUT)) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + status = HAL_NOR_STATUS_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 HAL_NOR_STATUS_SUCCESS */ + if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6)) + { + return HAL_NOR_STATUS_SUCCESS ; + } + + if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5) + { + status = HAL_NOR_STATUS_ONGOING; + } + + tmpsr1 = *(__IO uint16_t *)Address; + tmpsr2 = *(__IO uint16_t *)Address; + + /* If DQ6 did not toggle between the two reads then return HAL_NOR_STATUS_SUCCESS */ + if ((tmpsr1 & NOR_MASK_STATUS_DQ6) == (tmpsr2 & NOR_MASK_STATUS_DQ6)) + { + return HAL_NOR_STATUS_SUCCESS; + } + if ((tmpsr1 & NOR_MASK_STATUS_DQ5) == NOR_MASK_STATUS_DQ5) + { + return HAL_NOR_STATUS_ERROR; + } + } + } + else if (hnor->CommandSet == NOR_INTEL_SHARP_EXT_COMMAND_SET) + { + do + { + NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); + tmpsr2 = *(__IO uint16_t *)(Address); + + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return HAL_NOR_STATUS_TIMEOUT; + } + } + } while ((tmpsr2 & NOR_MASK_STATUS_DQ7) == 0U); + + NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); + tmpsr1 = *(__IO uint16_t *)(Address); + if ((tmpsr1 & (NOR_MASK_STATUS_DQ5 | NOR_MASK_STATUS_DQ4)) != 0U) + { + /* Clear the Status Register */ + NOR_WRITE(Address, NOR_CMD_READ_STATUS_REG); + status = HAL_NOR_STATUS_ERROR; + } + else + { + status = HAL_NOR_STATUS_SUCCESS; + } + } + else + { + /* Primary command set not supported by the driver */ + status = HAL_NOR_STATUS_ERROR; + } + + /* Return the operation status */ + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_NOR_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd.c index 6feedd005..2dcff89a0 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd.c @@ -1,2362 +1,2362 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_pcd.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 PCD 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 - (+++) __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); - (+++) __HAL_RCC_USB_OTG_HS_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 PCD transmission and reception: - (##) HAL_PCD_Start(); - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup PCD PCD - * @brief PCD HAL module driver - * @{ - */ - -#ifdef HAL_PCD_MODULE_ENABLED - -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup PCD_Private_Macros PCD Private Macros - * @{ - */ -#define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b)) -/** - * @} - */ - -/* Private functions prototypes ----------------------------------------------*/ -/** @defgroup PCD_Private_Functions PCD Private Functions - * @{ - */ -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum); -static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum); -static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum); -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup PCD_Exported_Functions PCD Exported Functions - * @{ - */ - -/** @defgroup PCD_Exported_Functions_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 initialize the associated handle. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) -{ -#if defined (USB_OTG_FS) - const USB_OTG_GlobalTypeDef *USBx; -#endif /* defined (USB_OTG_FS) */ - uint8_t i; - - /* Check the PCD handle allocation */ - if (hpcd == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); - -#if defined (USB_OTG_FS) - USBx = hpcd->Instance; -#endif /* defined (USB_OTG_FS) */ - - if (hpcd->State == HAL_PCD_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hpcd->Lock = HAL_UNLOCKED; - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->SOFCallback = HAL_PCD_SOFCallback; - hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback; - hpcd->ResetCallback = HAL_PCD_ResetCallback; - hpcd->SuspendCallback = HAL_PCD_SuspendCallback; - hpcd->ResumeCallback = HAL_PCD_ResumeCallback; - hpcd->ConnectCallback = HAL_PCD_ConnectCallback; - hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback; - hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; - hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; - hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; - hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; - hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; - hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; - - if (hpcd->MspInitCallback == NULL) - { - hpcd->MspInitCallback = HAL_PCD_MspInit; - } - - /* Init the low level hardware */ - hpcd->MspInitCallback(hpcd); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC... */ - HAL_PCD_MspInit(hpcd); -#endif /* (USE_HAL_PCD_REGISTER_CALLBACKS) */ - } - - hpcd->State = HAL_PCD_STATE_BUSY; - -#if defined (USB_OTG_FS) - /* Disable DMA mode for FS instance */ - if (USBx == USB_OTG_FS) - { - hpcd->Init.dma_enable = 0U; - } -#endif /* defined (USB_OTG_FS) */ - - /* Disable the Interrupts */ - __HAL_PCD_DISABLE(hpcd); - - /*Init the Core (common init.) */ - if (USB_CoreInit(hpcd->Instance, hpcd->Init) != HAL_OK) - { - hpcd->State = HAL_PCD_STATE_ERROR; - return HAL_ERROR; - } - - /* Force Device Mode */ - if (USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE) != HAL_OK) - { - hpcd->State = HAL_PCD_STATE_ERROR; - return HAL_ERROR; - } - - /* Init endpoints structures */ - for (i = 0U; i < hpcd->Init.dev_endpoints; i++) - { - /* Init ep structure */ - hpcd->IN_ep[i].is_in = 1U; - hpcd->IN_ep[i].num = i; - hpcd->IN_ep[i].tx_fifo_num = i; - /* Control until ep is activated */ - hpcd->IN_ep[i].type = EP_TYPE_CTRL; - hpcd->IN_ep[i].maxpacket = 0U; - hpcd->IN_ep[i].xfer_buff = 0U; - hpcd->IN_ep[i].xfer_len = 0U; - } - - for (i = 0U; i < hpcd->Init.dev_endpoints; i++) - { - hpcd->OUT_ep[i].is_in = 0U; - hpcd->OUT_ep[i].num = i; - /* Control until ep is activated */ - hpcd->OUT_ep[i].type = EP_TYPE_CTRL; - hpcd->OUT_ep[i].maxpacket = 0U; - hpcd->OUT_ep[i].xfer_buff = 0U; - hpcd->OUT_ep[i].xfer_len = 0U; - } - - /* Init Device */ - if (USB_DevInit(hpcd->Instance, hpcd->Init) != HAL_OK) - { - hpcd->State = HAL_PCD_STATE_ERROR; - return HAL_ERROR; - } - - hpcd->USB_Address = 0U; - hpcd->State = HAL_PCD_STATE_READY; - - /* Activate LPM */ - if (hpcd->Init.lpm_enable == 1U) - { - (void)HAL_PCDEx_ActivateLPM(hpcd); - } - - (void)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 = HAL_PCD_STATE_BUSY; - - /* Stop Device */ - if (USB_StopDevice(hpcd->Instance) != HAL_OK) - { - return HAL_ERROR; - } - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - if (hpcd->MspDeInitCallback == NULL) - { - hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware */ - hpcd->MspDeInitCallback(hpcd); -#else - /* DeInit the low level hardware: CLOCK, NVIC.*/ - HAL_PCD_MspDeInit(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - - hpcd->State = HAL_PCD_STATE_RESET; - - return HAL_OK; -} - -/** - * @brief Initializes the PCD MSP. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitializes PCD MSP. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a User USB PCD Callback - * To be used instead of the weak predefined callback - * @param hpcd USB PCD handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID - * @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID - * @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID - * @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID - * @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID - * @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID - * @arg @ref HAL_PCD_DISCONNECT_CB_ID USB PCD Disconnect callback ID - * @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID - * @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd, - HAL_PCD_CallbackIDTypeDef CallbackID, - pPCD_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - switch (CallbackID) - { - case HAL_PCD_SOF_CB_ID : - hpcd->SOFCallback = pCallback; - break; - - case HAL_PCD_SETUPSTAGE_CB_ID : - hpcd->SetupStageCallback = pCallback; - break; - - case HAL_PCD_RESET_CB_ID : - hpcd->ResetCallback = pCallback; - break; - - case HAL_PCD_SUSPEND_CB_ID : - hpcd->SuspendCallback = pCallback; - break; - - case HAL_PCD_RESUME_CB_ID : - hpcd->ResumeCallback = pCallback; - break; - - case HAL_PCD_CONNECT_CB_ID : - hpcd->ConnectCallback = pCallback; - break; - - case HAL_PCD_DISCONNECT_CB_ID : - hpcd->DisconnectCallback = pCallback; - break; - - case HAL_PCD_MSPINIT_CB_ID : - hpcd->MspInitCallback = pCallback; - break; - - case HAL_PCD_MSPDEINIT_CB_ID : - hpcd->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hpcd->State == HAL_PCD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_PCD_MSPINIT_CB_ID : - hpcd->MspInitCallback = pCallback; - break; - - case HAL_PCD_MSPDEINIT_CB_ID : - hpcd->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - return status; -} - -/** - * @brief Unregister an USB PCD Callback - * USB PCD callback is redirected to the weak predefined callback - * @param hpcd USB PCD handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID - * @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID - * @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID - * @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID - * @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID - * @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID - * @arg @ref HAL_PCD_DISCONNECT_CB_ID USB PCD Disconnect callback ID - * @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID - * @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, HAL_PCD_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - /* Setup Legacy weak Callbacks */ - if (hpcd->State == HAL_PCD_STATE_READY) - { - switch (CallbackID) - { - case HAL_PCD_SOF_CB_ID : - hpcd->SOFCallback = HAL_PCD_SOFCallback; - break; - - case HAL_PCD_SETUPSTAGE_CB_ID : - hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback; - break; - - case HAL_PCD_RESET_CB_ID : - hpcd->ResetCallback = HAL_PCD_ResetCallback; - break; - - case HAL_PCD_SUSPEND_CB_ID : - hpcd->SuspendCallback = HAL_PCD_SuspendCallback; - break; - - case HAL_PCD_RESUME_CB_ID : - hpcd->ResumeCallback = HAL_PCD_ResumeCallback; - break; - - case HAL_PCD_CONNECT_CB_ID : - hpcd->ConnectCallback = HAL_PCD_ConnectCallback; - break; - - case HAL_PCD_DISCONNECT_CB_ID : - hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback; - break; - - case HAL_PCD_MSPINIT_CB_ID : - hpcd->MspInitCallback = HAL_PCD_MspInit; - break; - - case HAL_PCD_MSPDEINIT_CB_ID : - hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; - break; - - default : - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hpcd->State == HAL_PCD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_PCD_MSPINIT_CB_ID : - hpcd->MspInitCallback = HAL_PCD_MspInit; - break; - - case HAL_PCD_MSPDEINIT_CB_ID : - hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; - break; - - default : - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - return status; -} - -/** - * @brief Register USB PCD Data OUT Stage Callback - * To be used instead of the weak HAL_PCD_DataOutStageCallback() predefined callback - * @param hpcd PCD handle - * @param pCallback pointer to the USB PCD Data OUT Stage Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd, - pPCD_DataOutStageCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->DataOutStageCallback = pCallback; - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Unregister the USB PCD Data OUT Stage Callback - * USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataOutStageCallback() predefined callback - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; /* Legacy weak DataOutStageCallback */ - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Register USB PCD Data IN Stage Callback - * To be used instead of the weak HAL_PCD_DataInStageCallback() predefined callback - * @param hpcd PCD handle - * @param pCallback pointer to the USB PCD Data IN Stage Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd, - pPCD_DataInStageCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->DataInStageCallback = pCallback; - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Unregister the USB PCD Data IN Stage Callback - * USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataInStageCallback() predefined callback - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; /* Legacy weak DataInStageCallback */ - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Register USB PCD Iso OUT incomplete Callback - * To be used instead of the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback - * @param hpcd PCD handle - * @param pCallback pointer to the USB PCD Iso OUT incomplete Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd, - pPCD_IsoOutIncpltCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->ISOOUTIncompleteCallback = pCallback; - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Unregister the USB PCD Iso OUT incomplete Callback - * USB PCD Iso OUT incomplete Callback is redirected - * to the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; /* Legacy weak ISOOUTIncompleteCallback */ - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Register USB PCD Iso IN incomplete Callback - * To be used instead of the weak HAL_PCD_ISOINIncompleteCallback() predefined callback - * @param hpcd PCD handle - * @param pCallback pointer to the USB PCD Iso IN incomplete Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd, - pPCD_IsoInIncpltCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->ISOINIncompleteCallback = pCallback; - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Unregister the USB PCD Iso IN incomplete Callback - * USB PCD Iso IN incomplete Callback is redirected - * to the weak HAL_PCD_ISOINIncompleteCallback() predefined callback - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; /* Legacy weak ISOINIncompleteCallback */ - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Register USB PCD BCD Callback - * To be used instead of the weak HAL_PCDEx_BCD_Callback() predefined callback - * @param hpcd PCD handle - * @param pCallback pointer to the USB PCD BCD Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->BCDCallback = pCallback; - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Unregister the USB PCD BCD Callback - * USB BCD Callback is redirected to the weak HAL_PCDEx_BCD_Callback() predefined callback - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; /* Legacy weak HAL_PCDEx_BCD_Callback */ - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Register USB PCD LPM Callback - * To be used instead of the weak HAL_PCDEx_LPM_Callback() predefined callback - * @param hpcd PCD handle - * @param pCallback pointer to the USB PCD LPM Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->LPMCallback = pCallback; - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} - -/** - * @brief Unregister the USB PCD LPM Callback - * USB LPM Callback is redirected to the weak HAL_PCDEx_LPM_Callback() predefined callback - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hpcd); - - if (hpcd->State == HAL_PCD_STATE_READY) - { - hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; /* Legacy weak HAL_PCDEx_LPM_Callback */ - } - else - { - /* Update the error code */ - hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hpcd); - - return status; -} -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup PCD_Exported_Functions_Group2 Input and Output 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 device - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - __HAL_LOCK(hpcd); - - if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && - (hpcd->Init.battery_charging_enable == 1U)) - { - /* Enable USB Transceiver */ - USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN; - } - - __HAL_PCD_ENABLE(hpcd); - (void)USB_DevConnect(hpcd->Instance); - __HAL_UNLOCK(hpcd); - - return HAL_OK; -} - -/** - * @brief Stop the USB device. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - __HAL_LOCK(hpcd); - __HAL_PCD_DISABLE(hpcd); - (void)USB_DevDisconnect(hpcd->Instance); - - (void)USB_FlushTxFifo(hpcd->Instance, 0x10U); - - if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && - (hpcd->Init.battery_charging_enable == 1U)) - { - /* Disable USB Transceiver */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); - } - - __HAL_UNLOCK(hpcd); - - return HAL_OK; -} - -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -/** - * @brief 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 USBx_BASE = (uint32_t)USBx; - USB_OTG_EPTypeDef *ep; - uint32_t i; - uint32_t ep_intr; - uint32_t epint; - uint32_t epnum; - uint32_t fifoemptymsk; - uint32_t RegVal; - - /* ensure that we are in device mode */ - if (USB_GetMode(hpcd->Instance) == USB_OTG_MODE_DEVICE) - { - /* avoid spurious interrupt */ - if (__HAL_PCD_IS_INVALID_INTERRUPT(hpcd)) - { - return; - } - - /* store current frame number */ - hpcd->FrameNumber = (USBx_DEVICE->DSTS & USB_OTG_DSTS_FNSOF_Msk) >> USB_OTG_DSTS_FNSOF_Pos; - - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_MMIS)) - { - /* incorrect mode, acknowledge the interrupt */ - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_MMIS); - } - - /* Handle RxQLevel Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_RXFLVL)) - { - USB_MASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); - - RegVal = USBx->GRXSTSP; - - ep = &hpcd->OUT_ep[RegVal & USB_OTG_GRXSTSP_EPNUM]; - - if (((RegVal & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_DATA_UPDT) - { - if ((RegVal & USB_OTG_GRXSTSP_BCNT) != 0U) - { - (void)USB_ReadPacket(USBx, ep->xfer_buff, - (uint16_t)((RegVal & USB_OTG_GRXSTSP_BCNT) >> 4)); - - ep->xfer_buff += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; - ep->xfer_count += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; - } - } - else if (((RegVal & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_SETUP_UPDT) - { - (void)USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8U); - ep->xfer_count += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; - } - else - { - /* ... */ - } - - USB_UNMASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); - } - - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OEPINT)) - { - epnum = 0U; - - /* Read in the device interrupt bits */ - ep_intr = USB_ReadDevAllOutEpInterrupt(hpcd->Instance); - - while (ep_intr != 0U) - { - if ((ep_intr & 0x1U) != 0U) - { - epint = USB_ReadDevOutEPInterrupt(hpcd->Instance, (uint8_t)epnum); - - if ((epint & USB_OTG_DOEPINT_XFRC) == USB_OTG_DOEPINT_XFRC) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_XFRC); - (void)PCD_EP_OutXfrComplete_int(hpcd, epnum); - } - - if ((epint & USB_OTG_DOEPINT_STUP) == USB_OTG_DOEPINT_STUP) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STUP); - /* Class B setup phase done for previous decoded setup */ - (void)PCD_EP_OutSetupPacket_int(hpcd, epnum); - } - - if ((epint & USB_OTG_DOEPINT_OTEPDIS) == USB_OTG_DOEPINT_OTEPDIS) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPDIS); - } - - /* Clear OUT Endpoint disable interrupt */ - if ((epint & USB_OTG_DOEPINT_EPDISD) == USB_OTG_DOEPINT_EPDISD) - { - if ((USBx->GINTSTS & USB_OTG_GINTSTS_BOUTNAKEFF) == USB_OTG_GINTSTS_BOUTNAKEFF) - { - USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGONAK; - } - - ep = &hpcd->OUT_ep[epnum]; - - if (ep->is_iso_incomplete == 1U) - { - ep->is_iso_incomplete = 0U; - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->ISOOUTIncompleteCallback(hpcd, (uint8_t)epnum); -#else - HAL_PCD_ISOOUTIncompleteCallback(hpcd, (uint8_t)epnum); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_EPDISD); - } - - /* Clear Status Phase Received interrupt */ - if ((epint & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); - } - - /* Clear OUT NAK interrupt */ - if ((epint & USB_OTG_DOEPINT_NAK) == USB_OTG_DOEPINT_NAK) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_NAK); - } - } - epnum++; - ep_intr >>= 1U; - } - } - - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_IEPINT)) - { - /* Read in the device interrupt bits */ - ep_intr = USB_ReadDevAllInEpInterrupt(hpcd->Instance); - - epnum = 0U; - - while (ep_intr != 0U) - { - if ((ep_intr & 0x1U) != 0U) /* In ITR */ - { - epint = USB_ReadDevInEPInterrupt(hpcd->Instance, (uint8_t)epnum); - - if ((epint & USB_OTG_DIEPINT_XFRC) == USB_OTG_DIEPINT_XFRC) - { - fifoemptymsk = (uint32_t)(0x1UL << (epnum & EP_ADDR_MSK)); - USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; - - CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_XFRC); - - if (hpcd->Init.dma_enable == 1U) - { - hpcd->IN_ep[epnum].xfer_buff += hpcd->IN_ep[epnum].maxpacket; - - /* this is ZLP, so prepare EP0 for next setup */ - if ((epnum == 0U) && (hpcd->IN_ep[epnum].xfer_len == 0U)) - { - /* prepare to rx more setup packets */ - (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); - } - } - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->DataInStageCallback(hpcd, (uint8_t)epnum); -#else - HAL_PCD_DataInStageCallback(hpcd, (uint8_t)epnum); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - 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) - { - (void)USB_FlushTxFifo(USBx, epnum); - - ep = &hpcd->IN_ep[epnum]; - - if (ep->is_iso_incomplete == 1U) - { - ep->is_iso_incomplete = 0U; - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->ISOINIncompleteCallback(hpcd, (uint8_t)epnum); -#else - HAL_PCD_ISOINIncompleteCallback(hpcd, (uint8_t)epnum); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - - CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_EPDISD); - } - if ((epint & USB_OTG_DIEPINT_TXFE) == USB_OTG_DIEPINT_TXFE) - { - (void)PCD_WriteEmptyTxFifo(hpcd, epnum); - } - } - epnum++; - ep_intr >>= 1U; - } - } - - /* Handle Resume Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT)) - { - /* Clear the Remote Wake-up Signaling */ - USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; - - if (hpcd->LPM_State == LPM_L1) - { - hpcd->LPM_State = LPM_L0; - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->LPMCallback(hpcd, PCD_LPM_L0_ACTIVE); -#else - HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L0_ACTIVE); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - else - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->ResumeCallback(hpcd); -#else - HAL_PCD_ResumeCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT); - } - - /* Handle Suspend Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP)) - { - if ((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS) - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->SuspendCallback(hpcd); -#else - HAL_PCD_SuspendCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP); - } - - /* Handle LPM Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_LPMINT)) - { - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_LPMINT); - - if (hpcd->LPM_State == LPM_L0) - { - hpcd->LPM_State = LPM_L1; - hpcd->BESL = (hpcd->Instance->GLPMCFG & USB_OTG_GLPMCFG_BESL) >> 2U; - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->LPMCallback(hpcd, PCD_LPM_L1_ACTIVE); -#else - HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L1_ACTIVE); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - else - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->SuspendCallback(hpcd); -#else - HAL_PCD_SuspendCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - } - - /* Handle Reset Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBRST)) - { - USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; - (void)USB_FlushTxFifo(hpcd->Instance, 0x10U); - - for (i = 0U; i < hpcd->Init.dev_endpoints; i++) - { - USBx_INEP(i)->DIEPINT = 0xFB7FU; - USBx_INEP(i)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL; - USBx_OUTEP(i)->DOEPINT = 0xFB7FU; - USBx_OUTEP(i)->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL; - USBx_OUTEP(i)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; - } - USBx_DEVICE->DAINTMSK |= 0x10001U; - - if (hpcd->Init.use_dedicated_ep1 != 0U) - { - 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 | - USB_OTG_DOEPMSK_OTEPSPRM | - USB_OTG_DOEPMSK_NAKM; - - 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 */ - (void)USB_EP0_OutStart(hpcd->Instance, (uint8_t)hpcd->Init.dma_enable, - (uint8_t *)hpcd->Setup); - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBRST); - } - - /* Handle Enumeration done Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE)) - { - (void)USB_ActivateSetup(hpcd->Instance); - hpcd->Init.speed = USB_GetDevSpeed(hpcd->Instance); - - /* Set USB Turnaround time */ - (void)USB_SetTurnaroundTime(hpcd->Instance, - HAL_RCC_GetHCLKFreq(), - (uint8_t)hpcd->Init.speed); - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->ResetCallback(hpcd); -#else - HAL_PCD_ResetCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE); - } - - /* Handle SOF Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_SOF)) - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->SOFCallback(hpcd); -#else - HAL_PCD_SOFCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SOF); - } - - /* Handle Global OUT NAK effective Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_BOUTNAKEFF)) - { - USBx->GINTMSK &= ~USB_OTG_GINTMSK_GONAKEFFM; - - for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) - { - if (hpcd->OUT_ep[epnum].is_iso_incomplete == 1U) - { - /* Abort current transaction and disable the EP */ - (void)HAL_PCD_EP_Abort(hpcd, (uint8_t)epnum); - } - } - } - - /* Handle Incomplete ISO IN Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR)) - { - for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) - { - RegVal = USBx_INEP(epnum)->DIEPCTL; - - if ((hpcd->IN_ep[epnum].type == EP_TYPE_ISOC) && - ((RegVal & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA)) - { - hpcd->IN_ep[epnum].is_iso_incomplete = 1U; - - /* Abort current transaction and disable the EP */ - (void)HAL_PCD_EP_Abort(hpcd, (uint8_t)(epnum | 0x80U)); - } - } - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR); - } - - /* Handle Incomplete ISO OUT Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT)) - { - for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) - { - RegVal = USBx_OUTEP(epnum)->DOEPCTL; - - if ((hpcd->OUT_ep[epnum].type == EP_TYPE_ISOC) && - ((RegVal & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) && - ((RegVal & (0x1U << 16)) == (hpcd->FrameNumber & 0x1U))) - { - hpcd->OUT_ep[epnum].is_iso_incomplete = 1U; - - USBx->GINTMSK |= USB_OTG_GINTMSK_GONAKEFFM; - - if ((USBx->GINTSTS & USB_OTG_GINTSTS_BOUTNAKEFF) == 0U) - { - USBx_DEVICE->DCTL |= USB_OTG_DCTL_SGONAK; - break; - } - } - } - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT); - } - - /* Handle Connection event Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT)) - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->ConnectCallback(hpcd); -#else - HAL_PCD_ConnectCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - - __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT); - } - - /* Handle Disconnection event Interrupt */ - if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OTGINT)) - { - RegVal = hpcd->Instance->GOTGINT; - - if ((RegVal & USB_OTG_GOTGINT_SEDET) == USB_OTG_GOTGINT_SEDET) - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->DisconnectCallback(hpcd); -#else - HAL_PCD_DisconnectCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - hpcd->Instance->GOTGINT |= RegVal; - } - } -} -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ - - -/** - * @brief Data OUT stage callback. - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval None - */ -__weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - UNUSED(epnum); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_DataOutStageCallback could be implemented in the user file - */ -} - -/** - * @brief Data IN stage callback - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval None - */ -__weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - UNUSED(epnum); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_DataInStageCallback could be implemented in the user file - */ -} -/** - * @brief Setup stage callback - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_SetupStageCallback could be implemented in the user file - */ -} - -/** - * @brief USB Start Of Frame callback. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_SOFCallback could be implemented in the user file - */ -} - -/** - * @brief USB Reset callback. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_ResetCallback could be implemented in the user file - */ -} - -/** - * @brief Suspend event callback. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_SuspendCallback could be implemented in the user file - */ -} - -/** - * @brief Resume event callback. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_ResumeCallback could be implemented in the user file - */ -} - -/** - * @brief Incomplete ISO OUT callback. - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval None - */ -__weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - UNUSED(epnum); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file - */ -} - -/** - * @brief Incomplete ISO IN callback. - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval None - */ -__weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - UNUSED(epnum); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_ISOINIncompleteCallback could be implemented in the user file - */ -} - -/** - * @brief Connection event callback. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_ConnectCallback could be implemented in the user file - */ -} - -/** - * @brief Disconnection event callback. - * @param hpcd PCD handle - * @retval None - */ -__weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCD_DisconnectCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup PCD_Exported_Functions_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 Connect the USB device - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - __HAL_LOCK(hpcd); - - if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && - (hpcd->Init.battery_charging_enable == 1U)) - { - /* Enable USB Transceiver */ - USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN; - } - (void)USB_DevConnect(hpcd->Instance); - __HAL_UNLOCK(hpcd); - - return HAL_OK; -} - -/** - * @brief Disconnect the USB device. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - __HAL_LOCK(hpcd); - (void)USB_DevDisconnect(hpcd->Instance); - - if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && - (hpcd->Init.battery_charging_enable == 1U)) - { - /* Disable USB Transceiver */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); - } - - __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); - hpcd->USB_Address = address; - (void)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 packet 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; - PCD_EPTypeDef *ep; - - if ((ep_addr & 0x80U) == 0x80U) - { - ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 1U; - } - else - { - ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 0U; - } - - ep->num = ep_addr & EP_ADDR_MSK; - ep->maxpacket = ep_mps; - ep->type = ep_type; - - if (ep->is_in != 0U) - { - /* Assign a Tx FIFO */ - ep->tx_fifo_num = ep->num; - } - - /* Set initial data PID. */ - if (ep_type == EP_TYPE_BULK) - { - ep->data_pid_start = 0U; - } - - __HAL_LOCK(hpcd); - (void)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) -{ - PCD_EPTypeDef *ep; - - if ((ep_addr & 0x80U) == 0x80U) - { - ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 1U; - } - else - { - ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 0U; - } - ep->num = ep_addr & EP_ADDR_MSK; - - __HAL_LOCK(hpcd); - (void)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) -{ - PCD_EPTypeDef *ep; - - ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; - - /*setup and start the Xfer */ - ep->xfer_buff = pBuf; - ep->xfer_len = len; - ep->xfer_count = 0U; - ep->is_in = 0U; - ep->num = ep_addr & EP_ADDR_MSK; - - if (hpcd->Init.dma_enable == 1U) - { - ep->dma_addr = (uint32_t)pBuf; - } - - (void)USB_EPStartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); - - return HAL_OK; -} - -/** - * @brief Get Received Data Size - * @param hpcd PCD handle - * @param ep_addr endpoint address - * @retval Data Size - */ -uint32_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef const *hpcd, uint8_t ep_addr) -{ - return hpcd->OUT_ep[ep_addr & EP_ADDR_MSK].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) -{ - PCD_EPTypeDef *ep; - - ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; - - /*setup and start the Xfer */ - ep->xfer_buff = pBuf; - ep->xfer_len = len; - ep->xfer_count = 0U; - ep->is_in = 1U; - ep->num = ep_addr & EP_ADDR_MSK; - - if (hpcd->Init.dma_enable == 1U) - { - ep->dma_addr = (uint32_t)pBuf; - } - - (void)USB_EPStartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); - - 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) -{ - PCD_EPTypeDef *ep; - - if (((uint32_t)ep_addr & EP_ADDR_MSK) > hpcd->Init.dev_endpoints) - { - return HAL_ERROR; - } - - if ((0x80U & ep_addr) == 0x80U) - { - ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 1U; - } - else - { - ep = &hpcd->OUT_ep[ep_addr]; - ep->is_in = 0U; - } - - ep->is_stall = 1U; - ep->num = ep_addr & EP_ADDR_MSK; - - __HAL_LOCK(hpcd); - - (void)USB_EPSetStall(hpcd->Instance, ep); - - if ((ep_addr & EP_ADDR_MSK) == 0U) - { - (void)USB_EP0_OutStart(hpcd->Instance, (uint8_t)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) -{ - PCD_EPTypeDef *ep; - - if (((uint32_t)ep_addr & 0x0FU) > hpcd->Init.dev_endpoints) - { - return HAL_ERROR; - } - - if ((0x80U & ep_addr) == 0x80U) - { - ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 1U; - } - else - { - ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; - ep->is_in = 0U; - } - - ep->is_stall = 0U; - ep->num = ep_addr & EP_ADDR_MSK; - - __HAL_LOCK(hpcd); - (void)USB_EPClearStall(hpcd->Instance, ep); - __HAL_UNLOCK(hpcd); - - return HAL_OK; -} - -/** - * @brief Abort an USB EP transaction. - * @param hpcd PCD handle - * @param ep_addr endpoint address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) -{ - HAL_StatusTypeDef ret; - PCD_EPTypeDef *ep; - - if ((0x80U & ep_addr) == 0x80U) - { - ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; - } - else - { - ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; - } - - /* Stop Xfer */ - ret = USB_EPStopXfer(hpcd->Instance, ep); - - return ret; -} - -/** - * @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 & 0x80U) == 0x80U) - { - (void)USB_FlushTxFifo(hpcd->Instance, (uint32_t)ep_addr & EP_ADDR_MSK); - } - else - { - (void)USB_FlushRxFifo(hpcd->Instance); - } - - __HAL_UNLOCK(hpcd); - - return HAL_OK; -} - -/** - * @brief Activate remote wakeup signalling - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) -{ - return (USB_ActivateRemoteWakeup(hpcd->Instance)); -} - -/** - * @brief De-activate remote wakeup signalling. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) -{ - return (USB_DeActivateRemoteWakeup(hpcd->Instance)); -} - -/** - * @} - */ - -/** @defgroup PCD_Exported_Functions_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. - -@endverbatim - * @{ - */ - -/** - * @brief Return the PCD handle state. - * @param hpcd PCD handle - * @retval HAL state - */ -PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef const *hpcd) -{ - return hpcd->State; -} - -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -/** - * @brief Set the USB Device high speed test mode. - * @param hpcd PCD handle - * @param testmode USB Device high speed test mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCD_SetTestMode(const PCD_HandleTypeDef *hpcd, uint8_t testmode) -{ - const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - - switch (testmode) - { - case TEST_J: - case TEST_K: - case TEST_SE0_NAK: - case TEST_PACKET: - case TEST_FORCE_EN: - USBx_DEVICE->DCTL |= (uint32_t)testmode << 4; - break; - - default: - break; - } - - return HAL_OK; -} -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @addtogroup PCD_Private_Functions - * @{ - */ -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -/** - * @brief Check FIFO for the next packet to be loaded. - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval HAL status - */ -static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - USB_OTG_EPTypeDef *ep; - uint32_t len; - uint32_t len32b; - uint32_t fifoemptymsk; - - ep = &hpcd->IN_ep[epnum]; - - if (ep->xfer_count > ep->xfer_len) - { - return HAL_ERROR; - } - - len = ep->xfer_len - ep->xfer_count; - - if (len > ep->maxpacket) - { - len = ep->maxpacket; - } - - len32b = (len + 3U) / 4U; - - while (((USBx_INEP(epnum)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) >= len32b) && - (ep->xfer_count < ep->xfer_len) && (ep->xfer_len != 0U)) - { - /* Write the FIFO */ - len = ep->xfer_len - ep->xfer_count; - - if (len > ep->maxpacket) - { - len = ep->maxpacket; - } - len32b = (len + 3U) / 4U; - - (void)USB_WritePacket(USBx, ep->xfer_buff, (uint8_t)epnum, (uint16_t)len, - (uint8_t)hpcd->Init.dma_enable); - - ep->xfer_buff += len; - ep->xfer_count += len; - } - - if (ep->xfer_len <= ep->xfer_count) - { - fifoemptymsk = (uint32_t)(0x1UL << (epnum & EP_ADDR_MSK)); - USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; - } - - return HAL_OK; -} - - -/** - * @brief process EP OUT transfer complete interrupt. - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval HAL status - */ -static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) -{ - USB_OTG_EPTypeDef *ep; - const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); - uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; - - if (hpcd->Init.dma_enable == 1U) - { - if ((DoepintReg & USB_OTG_DOEPINT_STUP) == USB_OTG_DOEPINT_STUP) /* Class C */ - { - /* StupPktRcvd = 1 this is a setup packet */ - if ((gSNPSiD > USB_OTG_CORE_ID_300A) && - ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); - } - } - else if ((DoepintReg & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) /* Class E */ - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); - } - else if ((DoepintReg & (USB_OTG_DOEPINT_STUP | USB_OTG_DOEPINT_OTEPSPR)) == 0U) - { - /* StupPktRcvd = 1 this is a setup packet */ - if ((gSNPSiD > USB_OTG_CORE_ID_300A) && - ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); - } - else - { - ep = &hpcd->OUT_ep[epnum]; - - /* out data packet received over EP */ - ep->xfer_count = ep->xfer_size - (USBx_OUTEP(epnum)->DOEPTSIZ & USB_OTG_DOEPTSIZ_XFRSIZ); - - if (epnum == 0U) - { - if (ep->xfer_len == 0U) - { - /* this is ZLP, so prepare EP0 for next setup */ - (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); - } - else - { - ep->xfer_buff += ep->xfer_count; - } - } - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); -#else - HAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - } - else - { - /* ... */ - } - } - else - { - if (gSNPSiD == USB_OTG_CORE_ID_310A) - { - /* StupPktRcvd = 1 this is a setup packet */ - if ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); - } - else - { - if ((DoepintReg & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); - } - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); -#else - HAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - } - else - { - if ((epnum == 0U) && (hpcd->OUT_ep[epnum].xfer_len == 0U)) - { - /* this is ZLP, so prepare EP0 for next setup */ - (void)USB_EP0_OutStart(hpcd->Instance, 0U, (uint8_t *)hpcd->Setup); - } - -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); -#else - HAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - } - - return HAL_OK; -} - - -/** - * @brief process EP OUT setup packet received interrupt. - * @param hpcd PCD handle - * @param epnum endpoint number - * @retval HAL status - */ -static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) -{ - const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); - uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; - - if ((gSNPSiD > USB_OTG_CORE_ID_300A) && - ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) - { - CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); - } - - /* Inform the upper layer that a setup packet is available */ -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->SetupStageCallback(hpcd); -#else - HAL_PCD_SetupStageCallback(hpcd); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - - if ((gSNPSiD > USB_OTG_CORE_ID_300A) && (hpcd->Init.dma_enable == 1U)) - { - (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); - } - - return HAL_OK; -} -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ - - -/** - * @} - */ -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ -#endif /* HAL_PCD_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_pcd.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 PCD 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 + (+++) __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + (+++) __HAL_RCC_USB_OTG_HS_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 PCD transmission and reception: + (##) HAL_PCD_Start(); + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup PCD PCD + * @brief PCD HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PCD_Private_Macros PCD Private Macros + * @{ + */ +#define PCD_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define PCD_MAX(a, b) (((a) > (b)) ? (a) : (b)) +/** + * @} + */ + +/* Private functions prototypes ----------------------------------------------*/ +/** @defgroup PCD_Private_Functions PCD Private Functions + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum); +static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum); +static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum); +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Functions PCD Exported Functions + * @{ + */ + +/** @defgroup PCD_Exported_Functions_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 initialize the associated handle. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) +{ +#if defined (USB_OTG_FS) + const USB_OTG_GlobalTypeDef *USBx; +#endif /* defined (USB_OTG_FS) */ + uint8_t i; + + /* Check the PCD handle allocation */ + if (hpcd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); + +#if defined (USB_OTG_FS) + USBx = hpcd->Instance; +#endif /* defined (USB_OTG_FS) */ + + if (hpcd->State == HAL_PCD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hpcd->Lock = HAL_UNLOCKED; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SOFCallback = HAL_PCD_SOFCallback; + hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback; + hpcd->ResetCallback = HAL_PCD_ResetCallback; + hpcd->SuspendCallback = HAL_PCD_SuspendCallback; + hpcd->ResumeCallback = HAL_PCD_ResumeCallback; + hpcd->ConnectCallback = HAL_PCD_ConnectCallback; + hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback; + hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; + hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; + hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; + hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; + hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; + hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; + + if (hpcd->MspInitCallback == NULL) + { + hpcd->MspInitCallback = HAL_PCD_MspInit; + } + + /* Init the low level hardware */ + hpcd->MspInitCallback(hpcd); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_PCD_MspInit(hpcd); +#endif /* (USE_HAL_PCD_REGISTER_CALLBACKS) */ + } + + hpcd->State = HAL_PCD_STATE_BUSY; + +#if defined (USB_OTG_FS) + /* Disable DMA mode for FS instance */ + if (USBx == USB_OTG_FS) + { + hpcd->Init.dma_enable = 0U; + } +#endif /* defined (USB_OTG_FS) */ + + /* Disable the Interrupts */ + __HAL_PCD_DISABLE(hpcd); + + /*Init the Core (common init.) */ + if (USB_CoreInit(hpcd->Instance, hpcd->Init) != HAL_OK) + { + hpcd->State = HAL_PCD_STATE_ERROR; + return HAL_ERROR; + } + + /* Force Device Mode */ + if (USB_SetCurrentMode(hpcd->Instance, USB_DEVICE_MODE) != HAL_OK) + { + hpcd->State = HAL_PCD_STATE_ERROR; + return HAL_ERROR; + } + + /* Init endpoints structures */ + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + /* Init ep structure */ + hpcd->IN_ep[i].is_in = 1U; + hpcd->IN_ep[i].num = i; + hpcd->IN_ep[i].tx_fifo_num = i; + /* Control until ep is activated */ + hpcd->IN_ep[i].type = EP_TYPE_CTRL; + hpcd->IN_ep[i].maxpacket = 0U; + hpcd->IN_ep[i].xfer_buff = 0U; + hpcd->IN_ep[i].xfer_len = 0U; + } + + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + hpcd->OUT_ep[i].is_in = 0U; + hpcd->OUT_ep[i].num = i; + /* Control until ep is activated */ + hpcd->OUT_ep[i].type = EP_TYPE_CTRL; + hpcd->OUT_ep[i].maxpacket = 0U; + hpcd->OUT_ep[i].xfer_buff = 0U; + hpcd->OUT_ep[i].xfer_len = 0U; + } + + /* Init Device */ + if (USB_DevInit(hpcd->Instance, hpcd->Init) != HAL_OK) + { + hpcd->State = HAL_PCD_STATE_ERROR; + return HAL_ERROR; + } + + hpcd->USB_Address = 0U; + hpcd->State = HAL_PCD_STATE_READY; + + /* Activate LPM */ + if (hpcd->Init.lpm_enable == 1U) + { + (void)HAL_PCDEx_ActivateLPM(hpcd); + } + + (void)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 = HAL_PCD_STATE_BUSY; + + /* Stop Device */ + if (USB_StopDevice(hpcd->Instance) != HAL_OK) + { + return HAL_ERROR; + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + if (hpcd->MspDeInitCallback == NULL) + { + hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hpcd->MspDeInitCallback(hpcd); +#else + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_PCD_MspDeInit(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + hpcd->State = HAL_PCD_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initializes the PCD MSP. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes PCD MSP. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User USB PCD Callback + * To be used instead of the weak predefined callback + * @param hpcd USB PCD handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID + * @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID + * @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID + * @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID + * @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID + * @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID + * @arg @ref HAL_PCD_DISCONNECT_CB_ID USB PCD Disconnect callback ID + * @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterCallback(PCD_HandleTypeDef *hpcd, + HAL_PCD_CallbackIDTypeDef CallbackID, + pPCD_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_PCD_SOF_CB_ID : + hpcd->SOFCallback = pCallback; + break; + + case HAL_PCD_SETUPSTAGE_CB_ID : + hpcd->SetupStageCallback = pCallback; + break; + + case HAL_PCD_RESET_CB_ID : + hpcd->ResetCallback = pCallback; + break; + + case HAL_PCD_SUSPEND_CB_ID : + hpcd->SuspendCallback = pCallback; + break; + + case HAL_PCD_RESUME_CB_ID : + hpcd->ResumeCallback = pCallback; + break; + + case HAL_PCD_CONNECT_CB_ID : + hpcd->ConnectCallback = pCallback; + break; + + case HAL_PCD_DISCONNECT_CB_ID : + hpcd->DisconnectCallback = pCallback; + break; + + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = pCallback; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hpcd->State == HAL_PCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = pCallback; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + return status; +} + +/** + * @brief Unregister an USB PCD Callback + * USB PCD callback is redirected to the weak predefined callback + * @param hpcd USB PCD handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_PCD_SOF_CB_ID USB PCD SOF callback ID + * @arg @ref HAL_PCD_SETUPSTAGE_CB_ID USB PCD Setup callback ID + * @arg @ref HAL_PCD_RESET_CB_ID USB PCD Reset callback ID + * @arg @ref HAL_PCD_SUSPEND_CB_ID USB PCD Suspend callback ID + * @arg @ref HAL_PCD_RESUME_CB_ID USB PCD Resume callback ID + * @arg @ref HAL_PCD_CONNECT_CB_ID USB PCD Connect callback ID + * @arg @ref HAL_PCD_DISCONNECT_CB_ID USB PCD Disconnect callback ID + * @arg @ref HAL_PCD_MSPINIT_CB_ID MspDeInit callback ID + * @arg @ref HAL_PCD_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterCallback(PCD_HandleTypeDef *hpcd, HAL_PCD_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + /* Setup Legacy weak Callbacks */ + if (hpcd->State == HAL_PCD_STATE_READY) + { + switch (CallbackID) + { + case HAL_PCD_SOF_CB_ID : + hpcd->SOFCallback = HAL_PCD_SOFCallback; + break; + + case HAL_PCD_SETUPSTAGE_CB_ID : + hpcd->SetupStageCallback = HAL_PCD_SetupStageCallback; + break; + + case HAL_PCD_RESET_CB_ID : + hpcd->ResetCallback = HAL_PCD_ResetCallback; + break; + + case HAL_PCD_SUSPEND_CB_ID : + hpcd->SuspendCallback = HAL_PCD_SuspendCallback; + break; + + case HAL_PCD_RESUME_CB_ID : + hpcd->ResumeCallback = HAL_PCD_ResumeCallback; + break; + + case HAL_PCD_CONNECT_CB_ID : + hpcd->ConnectCallback = HAL_PCD_ConnectCallback; + break; + + case HAL_PCD_DISCONNECT_CB_ID : + hpcd->DisconnectCallback = HAL_PCD_DisconnectCallback; + break; + + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = HAL_PCD_MspInit; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hpcd->State == HAL_PCD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_PCD_MSPINIT_CB_ID : + hpcd->MspInitCallback = HAL_PCD_MspInit; + break; + + case HAL_PCD_MSPDEINIT_CB_ID : + hpcd->MspDeInitCallback = HAL_PCD_MspDeInit; + break; + + default : + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + return status; +} + +/** + * @brief Register USB PCD Data OUT Stage Callback + * To be used instead of the weak HAL_PCD_DataOutStageCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Data OUT Stage Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataOutStageCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataOutStageCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Data OUT Stage Callback + * USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataOutStageCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterDataOutStageCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataOutStageCallback = HAL_PCD_DataOutStageCallback; /* Legacy weak DataOutStageCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Data IN Stage Callback + * To be used instead of the weak HAL_PCD_DataInStageCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Data IN Stage Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterDataInStageCallback(PCD_HandleTypeDef *hpcd, + pPCD_DataInStageCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataInStageCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Data IN Stage Callback + * USB PCD Data OUT Stage Callback is redirected to the weak HAL_PCD_DataInStageCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterDataInStageCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->DataInStageCallback = HAL_PCD_DataInStageCallback; /* Legacy weak DataInStageCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Iso OUT incomplete Callback + * To be used instead of the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Iso OUT incomplete Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoOutIncpltCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOOUTIncompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Iso OUT incomplete Callback + * USB PCD Iso OUT incomplete Callback is redirected + * to the weak HAL_PCD_ISOOUTIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterIsoOutIncpltCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOOUTIncompleteCallback = HAL_PCD_ISOOUTIncompleteCallback; /* Legacy weak ISOOUTIncompleteCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD Iso IN incomplete Callback + * To be used instead of the weak HAL_PCD_ISOINIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD Iso IN incomplete Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd, + pPCD_IsoInIncpltCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOINIncompleteCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD Iso IN incomplete Callback + * USB PCD Iso IN incomplete Callback is redirected + * to the weak HAL_PCD_ISOINIncompleteCallback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterIsoInIncpltCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->ISOINIncompleteCallback = HAL_PCD_ISOINIncompleteCallback; /* Legacy weak ISOINIncompleteCallback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD BCD Callback + * To be used instead of the weak HAL_PCDEx_BCD_Callback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD BCD Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterBcdCallback(PCD_HandleTypeDef *hpcd, pPCD_BcdCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->BCDCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD BCD Callback + * USB BCD Callback is redirected to the weak HAL_PCDEx_BCD_Callback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterBcdCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->BCDCallback = HAL_PCDEx_BCD_Callback; /* Legacy weak HAL_PCDEx_BCD_Callback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Register USB PCD LPM Callback + * To be used instead of the weak HAL_PCDEx_LPM_Callback() predefined callback + * @param hpcd PCD handle + * @param pCallback pointer to the USB PCD LPM Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_RegisterLpmCallback(PCD_HandleTypeDef *hpcd, pPCD_LpmCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->LPMCallback = pCallback; + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} + +/** + * @brief Unregister the USB PCD LPM Callback + * USB LPM Callback is redirected to the weak HAL_PCDEx_LPM_Callback() predefined callback + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_UnRegisterLpmCallback(PCD_HandleTypeDef *hpcd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hpcd); + + if (hpcd->State == HAL_PCD_STATE_READY) + { + hpcd->LPMCallback = HAL_PCDEx_LPM_Callback; /* Legacy weak HAL_PCDEx_LPM_Callback */ + } + else + { + /* Update the error code */ + hpcd->ErrorCode |= HAL_PCD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hpcd); + + return status; +} +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_Group2 Input and Output 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 device + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __HAL_LOCK(hpcd); + + if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && + (hpcd->Init.battery_charging_enable == 1U)) + { + /* Enable USB Transceiver */ + USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN; + } + + __HAL_PCD_ENABLE(hpcd); + (void)USB_DevConnect(hpcd->Instance); + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Stop the USB device. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __HAL_LOCK(hpcd); + __HAL_PCD_DISABLE(hpcd); + (void)USB_DevDisconnect(hpcd->Instance); + + (void)USB_FlushTxFifo(hpcd->Instance, 0x10U); + + if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && + (hpcd->Init.battery_charging_enable == 1U)) + { + /* Disable USB Transceiver */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); + } + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief 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 USBx_BASE = (uint32_t)USBx; + USB_OTG_EPTypeDef *ep; + uint32_t i; + uint32_t ep_intr; + uint32_t epint; + uint32_t epnum; + uint32_t fifoemptymsk; + uint32_t RegVal; + + /* ensure that we are in device mode */ + if (USB_GetMode(hpcd->Instance) == USB_OTG_MODE_DEVICE) + { + /* avoid spurious interrupt */ + if (__HAL_PCD_IS_INVALID_INTERRUPT(hpcd)) + { + return; + } + + /* store current frame number */ + hpcd->FrameNumber = (USBx_DEVICE->DSTS & USB_OTG_DSTS_FNSOF_Msk) >> USB_OTG_DSTS_FNSOF_Pos; + + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_MMIS)) + { + /* incorrect mode, acknowledge the interrupt */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_MMIS); + } + + /* Handle RxQLevel Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_RXFLVL)) + { + USB_MASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); + + RegVal = USBx->GRXSTSP; + + ep = &hpcd->OUT_ep[RegVal & USB_OTG_GRXSTSP_EPNUM]; + + if (((RegVal & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_DATA_UPDT) + { + if ((RegVal & USB_OTG_GRXSTSP_BCNT) != 0U) + { + (void)USB_ReadPacket(USBx, ep->xfer_buff, + (uint16_t)((RegVal & USB_OTG_GRXSTSP_BCNT) >> 4)); + + ep->xfer_buff += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; + ep->xfer_count += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; + } + } + else if (((RegVal & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_SETUP_UPDT) + { + (void)USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8U); + ep->xfer_count += (RegVal & USB_OTG_GRXSTSP_BCNT) >> 4; + } + else + { + /* ... */ + } + + USB_UNMASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); + } + + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OEPINT)) + { + epnum = 0U; + + /* Read in the device interrupt bits */ + ep_intr = USB_ReadDevAllOutEpInterrupt(hpcd->Instance); + + while (ep_intr != 0U) + { + if ((ep_intr & 0x1U) != 0U) + { + epint = USB_ReadDevOutEPInterrupt(hpcd->Instance, (uint8_t)epnum); + + if ((epint & USB_OTG_DOEPINT_XFRC) == USB_OTG_DOEPINT_XFRC) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_XFRC); + (void)PCD_EP_OutXfrComplete_int(hpcd, epnum); + } + + if ((epint & USB_OTG_DOEPINT_STUP) == USB_OTG_DOEPINT_STUP) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STUP); + /* Class B setup phase done for previous decoded setup */ + (void)PCD_EP_OutSetupPacket_int(hpcd, epnum); + } + + if ((epint & USB_OTG_DOEPINT_OTEPDIS) == USB_OTG_DOEPINT_OTEPDIS) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPDIS); + } + + /* Clear OUT Endpoint disable interrupt */ + if ((epint & USB_OTG_DOEPINT_EPDISD) == USB_OTG_DOEPINT_EPDISD) + { + if ((USBx->GINTSTS & USB_OTG_GINTSTS_BOUTNAKEFF) == USB_OTG_GINTSTS_BOUTNAKEFF) + { + USBx_DEVICE->DCTL |= USB_OTG_DCTL_CGONAK; + } + + ep = &hpcd->OUT_ep[epnum]; + + if (ep->is_iso_incomplete == 1U) + { + ep->is_iso_incomplete = 0U; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ISOOUTIncompleteCallback(hpcd, (uint8_t)epnum); +#else + HAL_PCD_ISOOUTIncompleteCallback(hpcd, (uint8_t)epnum); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_EPDISD); + } + + /* Clear Status Phase Received interrupt */ + if ((epint & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); + } + + /* Clear OUT NAK interrupt */ + if ((epint & USB_OTG_DOEPINT_NAK) == USB_OTG_DOEPINT_NAK) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_NAK); + } + } + epnum++; + ep_intr >>= 1U; + } + } + + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_IEPINT)) + { + /* Read in the device interrupt bits */ + ep_intr = USB_ReadDevAllInEpInterrupt(hpcd->Instance); + + epnum = 0U; + + while (ep_intr != 0U) + { + if ((ep_intr & 0x1U) != 0U) /* In ITR */ + { + epint = USB_ReadDevInEPInterrupt(hpcd->Instance, (uint8_t)epnum); + + if ((epint & USB_OTG_DIEPINT_XFRC) == USB_OTG_DIEPINT_XFRC) + { + fifoemptymsk = (uint32_t)(0x1UL << (epnum & EP_ADDR_MSK)); + USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; + + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_XFRC); + + if (hpcd->Init.dma_enable == 1U) + { + hpcd->IN_ep[epnum].xfer_buff += hpcd->IN_ep[epnum].maxpacket; + + /* this is ZLP, so prepare EP0 for next setup */ + if ((epnum == 0U) && (hpcd->IN_ep[epnum].xfer_len == 0U)) + { + /* prepare to rx more setup packets */ + (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); + } + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataInStageCallback(hpcd, (uint8_t)epnum); +#else + HAL_PCD_DataInStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + 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) + { + (void)USB_FlushTxFifo(USBx, epnum); + + ep = &hpcd->IN_ep[epnum]; + + if (ep->is_iso_incomplete == 1U) + { + ep->is_iso_incomplete = 0U; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ISOINIncompleteCallback(hpcd, (uint8_t)epnum); +#else + HAL_PCD_ISOINIncompleteCallback(hpcd, (uint8_t)epnum); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + + CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_EPDISD); + } + if ((epint & USB_OTG_DIEPINT_TXFE) == USB_OTG_DIEPINT_TXFE) + { + (void)PCD_WriteEmptyTxFifo(hpcd, epnum); + } + } + epnum++; + ep_intr >>= 1U; + } + } + + /* Handle Resume Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT)) + { + /* Clear the Remote Wake-up Signaling */ + USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; + + if (hpcd->LPM_State == LPM_L1) + { + hpcd->LPM_State = LPM_L0; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->LPMCallback(hpcd, PCD_LPM_L0_ACTIVE); +#else + HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L0_ACTIVE); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ResumeCallback(hpcd); +#else + HAL_PCD_ResumeCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_WKUINT); + } + + /* Handle Suspend Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP)) + { + if ((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SuspendCallback(hpcd); +#else + HAL_PCD_SuspendCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP); + } + + /* Handle LPM Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_LPMINT)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_LPMINT); + + if (hpcd->LPM_State == LPM_L0) + { + hpcd->LPM_State = LPM_L1; + hpcd->BESL = (hpcd->Instance->GLPMCFG & USB_OTG_GLPMCFG_BESL) >> 2U; + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->LPMCallback(hpcd, PCD_LPM_L1_ACTIVE); +#else + HAL_PCDEx_LPM_Callback(hpcd, PCD_LPM_L1_ACTIVE); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SuspendCallback(hpcd); +#else + HAL_PCD_SuspendCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + + /* Handle Reset Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBRST)) + { + USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; + (void)USB_FlushTxFifo(hpcd->Instance, 0x10U); + + for (i = 0U; i < hpcd->Init.dev_endpoints; i++) + { + USBx_INEP(i)->DIEPINT = 0xFB7FU; + USBx_INEP(i)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL; + USBx_OUTEP(i)->DOEPINT = 0xFB7FU; + USBx_OUTEP(i)->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL; + USBx_OUTEP(i)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; + } + USBx_DEVICE->DAINTMSK |= 0x10001U; + + if (hpcd->Init.use_dedicated_ep1 != 0U) + { + 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 | + USB_OTG_DOEPMSK_OTEPSPRM | + USB_OTG_DOEPMSK_NAKM; + + 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 */ + (void)USB_EP0_OutStart(hpcd->Instance, (uint8_t)hpcd->Init.dma_enable, + (uint8_t *)hpcd->Setup); + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBRST); + } + + /* Handle Enumeration done Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE)) + { + (void)USB_ActivateSetup(hpcd->Instance); + hpcd->Init.speed = USB_GetDevSpeed(hpcd->Instance); + + /* Set USB Turnaround time */ + (void)USB_SetTurnaroundTime(hpcd->Instance, + HAL_RCC_GetHCLKFreq(), + (uint8_t)hpcd->Init.speed); + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ResetCallback(hpcd); +#else + HAL_PCD_ResetCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE); + } + + /* Handle SOF Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_SOF)) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SOFCallback(hpcd); +#else + HAL_PCD_SOFCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SOF); + } + + /* Handle Global OUT NAK effective Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_BOUTNAKEFF)) + { + USBx->GINTMSK &= ~USB_OTG_GINTMSK_GONAKEFFM; + + for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) + { + if (hpcd->OUT_ep[epnum].is_iso_incomplete == 1U) + { + /* Abort current transaction and disable the EP */ + (void)HAL_PCD_EP_Abort(hpcd, (uint8_t)epnum); + } + } + } + + /* Handle Incomplete ISO IN Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR)) + { + for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) + { + RegVal = USBx_INEP(epnum)->DIEPCTL; + + if ((hpcd->IN_ep[epnum].type == EP_TYPE_ISOC) && + ((RegVal & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA)) + { + hpcd->IN_ep[epnum].is_iso_incomplete = 1U; + + /* Abort current transaction and disable the EP */ + (void)HAL_PCD_EP_Abort(hpcd, (uint8_t)(epnum | 0x80U)); + } + } + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_IISOIXFR); + } + + /* Handle Incomplete ISO OUT Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT)) + { + for (epnum = 1U; epnum < hpcd->Init.dev_endpoints; epnum++) + { + RegVal = USBx_OUTEP(epnum)->DOEPCTL; + + if ((hpcd->OUT_ep[epnum].type == EP_TYPE_ISOC) && + ((RegVal & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) && + ((RegVal & (0x1U << 16)) == (hpcd->FrameNumber & 0x1U))) + { + hpcd->OUT_ep[epnum].is_iso_incomplete = 1U; + + USBx->GINTMSK |= USB_OTG_GINTMSK_GONAKEFFM; + + if ((USBx->GINTSTS & USB_OTG_GINTSTS_BOUTNAKEFF) == 0U) + { + USBx_DEVICE->DCTL |= USB_OTG_DCTL_SGONAK; + break; + } + } + } + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT); + } + + /* Handle Connection event Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT)) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->ConnectCallback(hpcd); +#else + HAL_PCD_ConnectCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_SRQINT); + } + + /* Handle Disconnection event Interrupt */ + if (__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OTGINT)) + { + RegVal = hpcd->Instance->GOTGINT; + + if ((RegVal & USB_OTG_GOTGINT_SEDET) == USB_OTG_GOTGINT_SEDET) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DisconnectCallback(hpcd); +#else + HAL_PCD_DisconnectCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + hpcd->Instance->GOTGINT |= RegVal; + } + } +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @brief Data OUT stage callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implemented in the user file + */ +} + +/** + * @brief Data IN stage callback + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_DataInStageCallback could be implemented in the user file + */ +} +/** + * @brief Setup stage callback + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_SetupStageCallback could be implemented in the user file + */ +} + +/** + * @brief USB Start Of Frame callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_SOFCallback could be implemented in the user file + */ +} + +/** + * @brief USB Reset callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ResetCallback could be implemented in the user file + */ +} + +/** + * @brief Suspend event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_SuspendCallback could be implemented in the user file + */ +} + +/** + * @brief Resume event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ResumeCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO OUT callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO IN callback. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval None + */ +__weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(epnum); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ISOINIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Connection event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_ConnectCallback could be implemented in the user file + */ +} + +/** + * @brief Disconnection event callback. + * @param hpcd PCD handle + * @retval None + */ +__weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCD_DisconnectCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_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 Connect the USB device + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __HAL_LOCK(hpcd); + + if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && + (hpcd->Init.battery_charging_enable == 1U)) + { + /* Enable USB Transceiver */ + USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN; + } + (void)USB_DevConnect(hpcd->Instance); + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Disconnect the USB device. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + __HAL_LOCK(hpcd); + (void)USB_DevDisconnect(hpcd->Instance); + + if (((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) && + (hpcd->Init.battery_charging_enable == 1U)) + { + /* Disable USB Transceiver */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); + } + + __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); + hpcd->USB_Address = address; + (void)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 packet 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; + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80U) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + + ep->num = ep_addr & EP_ADDR_MSK; + ep->maxpacket = ep_mps; + ep->type = ep_type; + + if (ep->is_in != 0U) + { + /* Assign a Tx FIFO */ + ep->tx_fifo_num = ep->num; + } + + /* Set initial data PID. */ + if (ep_type == EP_TYPE_BULK) + { + ep->data_pid_start = 0U; + } + + __HAL_LOCK(hpcd); + (void)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) +{ + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80U) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + ep->num = ep_addr & EP_ADDR_MSK; + + __HAL_LOCK(hpcd); + (void)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) +{ + PCD_EPTypeDef *ep; + + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0U; + ep->is_in = 0U; + ep->num = ep_addr & EP_ADDR_MSK; + + if (hpcd->Init.dma_enable == 1U) + { + ep->dma_addr = (uint32_t)pBuf; + } + + (void)USB_EPStartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); + + return HAL_OK; +} + +/** + * @brief Get Received Data Size + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval Data Size + */ +uint32_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef const *hpcd, uint8_t ep_addr) +{ + return hpcd->OUT_ep[ep_addr & EP_ADDR_MSK].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) +{ + PCD_EPTypeDef *ep; + + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0U; + ep->is_in = 1U; + ep->num = ep_addr & EP_ADDR_MSK; + + if (hpcd->Init.dma_enable == 1U) + { + ep->dma_addr = (uint32_t)pBuf; + } + + (void)USB_EPStartXfer(hpcd->Instance, ep, (uint8_t)hpcd->Init.dma_enable); + + 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) +{ + PCD_EPTypeDef *ep; + + if (((uint32_t)ep_addr & EP_ADDR_MSK) > hpcd->Init.dev_endpoints) + { + return HAL_ERROR; + } + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + ep->is_in = 0U; + } + + ep->is_stall = 1U; + ep->num = ep_addr & EP_ADDR_MSK; + + __HAL_LOCK(hpcd); + + (void)USB_EPSetStall(hpcd->Instance, ep); + + if ((ep_addr & EP_ADDR_MSK) == 0U) + { + (void)USB_EP0_OutStart(hpcd->Instance, (uint8_t)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) +{ + PCD_EPTypeDef *ep; + + if (((uint32_t)ep_addr & 0x0FU) > hpcd->Init.dev_endpoints) + { + return HAL_ERROR; + } + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 1U; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + ep->is_in = 0U; + } + + ep->is_stall = 0U; + ep->num = ep_addr & EP_ADDR_MSK; + + __HAL_LOCK(hpcd); + (void)USB_EPClearStall(hpcd->Instance, ep); + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Abort an USB EP transaction. + * @param hpcd PCD handle + * @param ep_addr endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Abort(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + HAL_StatusTypeDef ret; + PCD_EPTypeDef *ep; + + if ((0x80U & ep_addr) == 0x80U) + { + ep = &hpcd->IN_ep[ep_addr & EP_ADDR_MSK]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & EP_ADDR_MSK]; + } + + /* Stop Xfer */ + ret = USB_EPStopXfer(hpcd->Instance, ep); + + return ret; +} + +/** + * @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 & 0x80U) == 0x80U) + { + (void)USB_FlushTxFifo(hpcd->Instance, (uint32_t)ep_addr & EP_ADDR_MSK); + } + else + { + (void)USB_FlushRxFifo(hpcd->Instance); + } + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Activate remote wakeup signalling + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_ActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + return (USB_ActivateRemoteWakeup(hpcd->Instance)); +} + +/** + * @brief De-activate remote wakeup signalling. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DeActivateRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + return (USB_DeActivateRemoteWakeup(hpcd->Instance)); +} + +/** + * @} + */ + +/** @defgroup PCD_Exported_Functions_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. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PCD handle state. + * @param hpcd PCD handle + * @retval HAL state + */ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef const *hpcd) +{ + return hpcd->State; +} + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief Set the USB Device high speed test mode. + * @param hpcd PCD handle + * @param testmode USB Device high speed test mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_SetTestMode(const PCD_HandleTypeDef *hpcd, uint8_t testmode) +{ + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + + switch (testmode) + { + case TEST_J: + case TEST_K: + case TEST_SE0_NAK: + case TEST_PACKET: + case TEST_FORCE_EN: + USBx_DEVICE->DCTL |= (uint32_t)testmode << 4; + break; + + default: + break; + } + + return HAL_OK; +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @addtogroup PCD_Private_Functions + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief Check FIFO for the next packet to be loaded. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval HAL status + */ +static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t epnum) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + USB_OTG_EPTypeDef *ep; + uint32_t len; + uint32_t len32b; + uint32_t fifoemptymsk; + + ep = &hpcd->IN_ep[epnum]; + + if (ep->xfer_count > ep->xfer_len) + { + return HAL_ERROR; + } + + len = ep->xfer_len - ep->xfer_count; + + if (len > ep->maxpacket) + { + len = ep->maxpacket; + } + + len32b = (len + 3U) / 4U; + + while (((USBx_INEP(epnum)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) >= len32b) && + (ep->xfer_count < ep->xfer_len) && (ep->xfer_len != 0U)) + { + /* Write the FIFO */ + len = ep->xfer_len - ep->xfer_count; + + if (len > ep->maxpacket) + { + len = ep->maxpacket; + } + len32b = (len + 3U) / 4U; + + (void)USB_WritePacket(USBx, ep->xfer_buff, (uint8_t)epnum, (uint16_t)len, + (uint8_t)hpcd->Init.dma_enable); + + ep->xfer_buff += len; + ep->xfer_count += len; + } + + if (ep->xfer_len <= ep->xfer_count) + { + fifoemptymsk = (uint32_t)(0x1UL << (epnum & EP_ADDR_MSK)); + USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; + } + + return HAL_OK; +} + + +/** + * @brief process EP OUT transfer complete interrupt. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval HAL status + */ +static HAL_StatusTypeDef PCD_EP_OutXfrComplete_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) +{ + USB_OTG_EPTypeDef *ep; + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); + uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; + + if (hpcd->Init.dma_enable == 1U) + { + if ((DoepintReg & USB_OTG_DOEPINT_STUP) == USB_OTG_DOEPINT_STUP) /* Class C */ + { + /* StupPktRcvd = 1 this is a setup packet */ + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && + ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + } + else if ((DoepintReg & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) /* Class E */ + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); + } + else if ((DoepintReg & (USB_OTG_DOEPINT_STUP | USB_OTG_DOEPINT_OTEPSPR)) == 0U) + { + /* StupPktRcvd = 1 this is a setup packet */ + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && + ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + else + { + ep = &hpcd->OUT_ep[epnum]; + + /* out data packet received over EP */ + ep->xfer_count = ep->xfer_size - (USBx_OUTEP(epnum)->DOEPTSIZ & USB_OTG_DOEPTSIZ_XFRSIZ); + + if (epnum == 0U) + { + if (ep->xfer_len == 0U) + { + /* this is ZLP, so prepare EP0 for next setup */ + (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); + } + else + { + ep->xfer_buff += ep->xfer_count; + } + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); +#else + HAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + else + { + /* ... */ + } + } + else + { + if (gSNPSiD == USB_OTG_CORE_ID_310A) + { + /* StupPktRcvd = 1 this is a setup packet */ + if ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + else + { + if ((DoepintReg & USB_OTG_DOEPINT_OTEPSPR) == USB_OTG_DOEPINT_OTEPSPR) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_OTEPSPR); + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); +#else + HAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + else + { + if ((epnum == 0U) && (hpcd->OUT_ep[epnum].xfer_len == 0U)) + { + /* this is ZLP, so prepare EP0 for next setup */ + (void)USB_EP0_OutStart(hpcd->Instance, 0U, (uint8_t *)hpcd->Setup); + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->DataOutStageCallback(hpcd, (uint8_t)epnum); +#else + HAL_PCD_DataOutStageCallback(hpcd, (uint8_t)epnum); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + + return HAL_OK; +} + + +/** + * @brief process EP OUT setup packet received interrupt. + * @param hpcd PCD handle + * @param epnum endpoint number + * @retval HAL status + */ +static HAL_StatusTypeDef PCD_EP_OutSetupPacket_int(PCD_HandleTypeDef *hpcd, uint32_t epnum) +{ + const USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); + uint32_t DoepintReg = USBx_OUTEP(epnum)->DOEPINT; + + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && + ((DoepintReg & USB_OTG_DOEPINT_STPKTRX) == USB_OTG_DOEPINT_STPKTRX)) + { + CLEAR_OUT_EP_INTR(epnum, USB_OTG_DOEPINT_STPKTRX); + } + + /* Inform the upper layer that a setup packet is available */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->SetupStageCallback(hpcd); +#else + HAL_PCD_SetupStageCallback(hpcd); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + + if ((gSNPSiD > USB_OTG_CORE_ID_300A) && (hpcd->Init.dma_enable == 1U)) + { + (void)USB_EP0_OutStart(hpcd->Instance, 1U, (uint8_t *)hpcd->Setup); + } + + return HAL_OK; +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* HAL_PCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd_ex.c index b412260f1..0ad2a6a5e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pcd_ex.c @@ -1,400 +1,400 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_pcd_ex.c - * @author MCD Application Team - * @brief PCD Extended HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the USB Peripheral Controller: - * + Extended features functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup PCDEx PCDEx - * @brief PCD Extended HAL module driver - * @{ - */ - -#ifdef HAL_PCD_MODULE_ENABLED - -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions - * @{ - */ - -/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions - * @brief PCDEx control functions - * -@verbatim - =============================================================================== - ##### Extended features functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Update FIFO configuration - -@endverbatim - * @{ - */ -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -/** - * @brief Set Tx FIFO - * @param hpcd PCD handle - * @param fifo The number of Tx fifo - * @param size Fifo size - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size) -{ - uint8_t i; - uint32_t Tx_Offset; - - /* 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 == 0U) - { - hpcd->Instance->DIEPTXF0_HNPTXFSIZ = ((uint32_t)size << 16) | Tx_Offset; - } - else - { - Tx_Offset += (hpcd->Instance->DIEPTXF0_HNPTXFSIZ) >> 16; - for (i = 0U; i < (fifo - 1U); i++) - { - Tx_Offset += (hpcd->Instance->DIEPTXF[i] >> 16); - } - - /* Multiply Tx_Size by 2 to get higher performance */ - hpcd->Instance->DIEPTXF[fifo - 1U] = ((uint32_t)size << 16) | Tx_Offset; - } - - return HAL_OK; -} - -/** - * @brief Set Rx FIFO - * @param hpcd PCD handle - * @param size Size of Rx fifo - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size) -{ - hpcd->Instance->GRXFSIZ = size; - - return HAL_OK; -} - -/** - * @brief Activate LPM feature. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - hpcd->lpm_active = 1U; - hpcd->LPM_State = LPM_L0; - USBx->GINTMSK |= USB_OTG_GINTMSK_LPMINTM; - USBx->GLPMCFG |= (USB_OTG_GLPMCFG_LPMEN | USB_OTG_GLPMCFG_LPMACK | USB_OTG_GLPMCFG_ENBESL); - - return HAL_OK; -} - -/** - * @brief Deactivate LPM feature. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - hpcd->lpm_active = 0U; - USBx->GINTMSK &= ~USB_OTG_GINTMSK_LPMINTM; - USBx->GLPMCFG &= ~(USB_OTG_GLPMCFG_LPMEN | USB_OTG_GLPMCFG_LPMACK | USB_OTG_GLPMCFG_ENBESL); - - return HAL_OK; -} - - -/** - * @brief Handle BatteryCharging Process. - * @param hpcd PCD handle - * @retval HAL status - */ -void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - uint32_t gccfg_msk; - uint32_t tickstart = HAL_GetTick(); - - /* Enable DCD : Data Contact Detect */ - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - USBx->GCCFG |= USB_OTG_GCCFG_DCDEN; - } - else - { - USBx->GCCFG |= USB_OTG_GCCFG_DCDETEN; - } - - /* Wait for Min DCD Timeout */ - HAL_Delay(300U); - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - /* Check Detect flag */ - if ((USBx->GCCFG & USB_OTG_GCCFG_DCDET) == USB_OTG_GCCFG_DCDET) - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->BCDCallback(hpcd, PCD_BCD_CONTACT_DETECTION); -#else - HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CONTACT_DETECTION); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - } - - /* Primary detection: checks if connected to Standard Downstream Port - (without charging capability) */ - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - USBx->GCCFG &= ~USB_OTG_GCCFG_DCDEN; - HAL_Delay(50U); - USBx->GCCFG |= USB_OTG_GCCFG_PDEN; - } - else - { - USBx->GCCFG &= ~USB_OTG_GCCFG_DCDETEN; - HAL_Delay(50U); - USBx->GCCFG |= USB_OTG_GCCFG_PDETEN; - } - HAL_Delay(50U); - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - gccfg_msk = USB_OTG_GCCFG_PDET; - } - else - { - gccfg_msk = USB_OTG_GCCFG_CHGDET; - } - - if ((USBx->GCCFG & gccfg_msk) == 0U) - { - /* Case of Standard Downstream Port */ -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->BCDCallback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT); -#else - HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - else - { - /* start secondary detection to check connection to Charging Downstream - Port or Dedicated Charging Port */ - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); - HAL_Delay(50U); - USBx->GCCFG |= USB_OTG_GCCFG_SDEN; - HAL_Delay(50U); - - gccfg_msk = USB_OTG_GCCFG_SDET; - } - else - { - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDETEN); - HAL_Delay(50U); - USBx->GCCFG |= USB_OTG_GCCFG_SDETEN; - HAL_Delay(50U); - - gccfg_msk = USB_OTG_GCCFG_FSVPLUS; - } - - if ((USBx->GCCFG & gccfg_msk) == gccfg_msk) - { - /* case Dedicated Charging Port */ -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->BCDCallback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT); -#else - HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - else - { - /* case Charging Downstream Port */ -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->BCDCallback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT); -#else - HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - } - - /* Battery Charging capability discovery finished */ - (void)HAL_PCDEx_DeActivateBCD(hpcd); - - /* Check for the Timeout, else start USB Device */ - if ((HAL_GetTick() - tickstart) > 1000U) - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->BCDCallback(hpcd, PCD_BCD_ERROR); -#else - HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_ERROR); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } - else - { -#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) - hpcd->BCDCallback(hpcd, PCD_BCD_DISCOVERY_COMPLETED); -#else - HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DISCOVERY_COMPLETED); -#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Activate BatteryCharging feature. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); - USBx->GCCFG &= ~(USB_OTG_GCCFG_SDEN); - - /* Power Down USB transceiver */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); - - /* Enable Battery charging */ - USBx->GCCFG |= USB_OTG_GCCFG_BCDEN; - } - else - { - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDETEN); - USBx->GCCFG &= ~(USB_OTG_GCCFG_SDETEN); - } - - hpcd->battery_charging_active = 1U; - - return HAL_OK; -} - -/** - * @brief Deactivate BatteryCharging feature. - * @param hpcd PCD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd) -{ - USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); - USBx->GCCFG &= ~(USB_OTG_GCCFG_SDEN); - - /* Disable Battery charging */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_BCDEN); - } - else - { - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDETEN); - USBx->GCCFG &= ~(USB_OTG_GCCFG_SDETEN); - } - - hpcd->battery_charging_active = 0U; - - return HAL_OK; -} - -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ - -/** - * @brief Send LPM message to user layer callback. - * @param hpcd PCD handle - * @param msg LPM message - * @retval HAL status - */ -__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - UNUSED(msg); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCDEx_LPM_Callback could be implemented in the user file - */ -} - -/** - * @brief Send BatteryCharging message to user layer callback. - * @param hpcd PCD handle - * @param msg LPM message - * @retval HAL status - */ -__weak void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpcd); - UNUSED(msg); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PCDEx_BCD_Callback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** - * @} - */ -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ -#endif /* HAL_PCD_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_pcd_ex.c + * @author MCD Application Team + * @brief PCD Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Extended features functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup PCDEx PCDEx + * @brief PCD Extended HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PCDEx_Exported_Functions PCDEx Exported Functions + * @{ + */ + +/** @defgroup PCDEx_Exported_Functions_Group1 Peripheral Control functions + * @brief PCDEx control functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Update FIFO configuration + +@endverbatim + * @{ + */ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/** + * @brief Set Tx FIFO + * @param hpcd PCD handle + * @param fifo The number of Tx fifo + * @param size Fifo size + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size) +{ + uint8_t i; + uint32_t Tx_Offset; + + /* 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 == 0U) + { + hpcd->Instance->DIEPTXF0_HNPTXFSIZ = ((uint32_t)size << 16) | Tx_Offset; + } + else + { + Tx_Offset += (hpcd->Instance->DIEPTXF0_HNPTXFSIZ) >> 16; + for (i = 0U; i < (fifo - 1U); i++) + { + Tx_Offset += (hpcd->Instance->DIEPTXF[i] >> 16); + } + + /* Multiply Tx_Size by 2 to get higher performance */ + hpcd->Instance->DIEPTXF[fifo - 1U] = ((uint32_t)size << 16) | Tx_Offset; + } + + return HAL_OK; +} + +/** + * @brief Set Rx FIFO + * @param hpcd PCD handle + * @param size Size of Rx fifo + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_SetRxFiFo(PCD_HandleTypeDef *hpcd, uint16_t size) +{ + hpcd->Instance->GRXFSIZ = size; + + return HAL_OK; +} + +/** + * @brief Activate LPM feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_ActivateLPM(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + hpcd->lpm_active = 1U; + hpcd->LPM_State = LPM_L0; + USBx->GINTMSK |= USB_OTG_GINTMSK_LPMINTM; + USBx->GLPMCFG |= (USB_OTG_GLPMCFG_LPMEN | USB_OTG_GLPMCFG_LPMACK | USB_OTG_GLPMCFG_ENBESL); + + return HAL_OK; +} + +/** + * @brief Deactivate LPM feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_DeActivateLPM(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + hpcd->lpm_active = 0U; + USBx->GINTMSK &= ~USB_OTG_GINTMSK_LPMINTM; + USBx->GLPMCFG &= ~(USB_OTG_GLPMCFG_LPMEN | USB_OTG_GLPMCFG_LPMACK | USB_OTG_GLPMCFG_ENBESL); + + return HAL_OK; +} + + +/** + * @brief Handle BatteryCharging Process. + * @param hpcd PCD handle + * @retval HAL status + */ +void HAL_PCDEx_BCD_VBUSDetect(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + uint32_t gccfg_msk; + uint32_t tickstart = HAL_GetTick(); + + /* Enable DCD : Data Contact Detect */ + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + USBx->GCCFG |= USB_OTG_GCCFG_DCDEN; + } + else + { + USBx->GCCFG |= USB_OTG_GCCFG_DCDETEN; + } + + /* Wait for Min DCD Timeout */ + HAL_Delay(300U); + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + /* Check Detect flag */ + if ((USBx->GCCFG & USB_OTG_GCCFG_DCDET) == USB_OTG_GCCFG_DCDET) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_CONTACT_DETECTION); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CONTACT_DETECTION); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + + /* Primary detection: checks if connected to Standard Downstream Port + (without charging capability) */ + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + USBx->GCCFG &= ~USB_OTG_GCCFG_DCDEN; + HAL_Delay(50U); + USBx->GCCFG |= USB_OTG_GCCFG_PDEN; + } + else + { + USBx->GCCFG &= ~USB_OTG_GCCFG_DCDETEN; + HAL_Delay(50U); + USBx->GCCFG |= USB_OTG_GCCFG_PDETEN; + } + HAL_Delay(50U); + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + gccfg_msk = USB_OTG_GCCFG_PDET; + } + else + { + gccfg_msk = USB_OTG_GCCFG_CHGDET; + } + + if ((USBx->GCCFG & gccfg_msk) == 0U) + { + /* Case of Standard Downstream Port */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_STD_DOWNSTREAM_PORT); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { + /* start secondary detection to check connection to Charging Downstream + Port or Dedicated Charging Port */ + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); + HAL_Delay(50U); + USBx->GCCFG |= USB_OTG_GCCFG_SDEN; + HAL_Delay(50U); + + gccfg_msk = USB_OTG_GCCFG_SDET; + } + else + { + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDETEN); + HAL_Delay(50U); + USBx->GCCFG |= USB_OTG_GCCFG_SDETEN; + HAL_Delay(50U); + + gccfg_msk = USB_OTG_GCCFG_FSVPLUS; + } + + if ((USBx->GCCFG & gccfg_msk) == gccfg_msk) + { + /* case Dedicated Charging Port */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DEDICATED_CHARGING_PORT); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { + /* case Charging Downstream Port */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_CHARGING_DOWNSTREAM_PORT); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + } + + /* Battery Charging capability discovery finished */ + (void)HAL_PCDEx_DeActivateBCD(hpcd); + + /* Check for the Timeout, else start USB Device */ + if ((HAL_GetTick() - tickstart) > 1000U) + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_ERROR); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_ERROR); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } + else + { +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + hpcd->BCDCallback(hpcd, PCD_BCD_DISCOVERY_COMPLETED); +#else + HAL_PCDEx_BCD_Callback(hpcd, PCD_BCD_DISCOVERY_COMPLETED); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Activate BatteryCharging feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_ActivateBCD(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); + USBx->GCCFG &= ~(USB_OTG_GCCFG_SDEN); + + /* Power Down USB transceiver */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); + + /* Enable Battery charging */ + USBx->GCCFG |= USB_OTG_GCCFG_BCDEN; + } + else + { + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDETEN); + USBx->GCCFG &= ~(USB_OTG_GCCFG_SDETEN); + } + + hpcd->battery_charging_active = 1U; + + return HAL_OK; +} + +/** + * @brief Deactivate BatteryCharging feature. + * @param hpcd PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCDEx_DeActivateBCD(PCD_HandleTypeDef *hpcd) +{ + USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); + USBx->GCCFG &= ~(USB_OTG_GCCFG_SDEN); + + /* Disable Battery charging */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_BCDEN); + } + else + { + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDETEN); + USBx->GCCFG &= ~(USB_OTG_GCCFG_SDETEN); + } + + hpcd->battery_charging_active = 0U; + + return HAL_OK; +} + +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +/** + * @brief Send LPM message to user layer callback. + * @param hpcd PCD handle + * @param msg LPM message + * @retval HAL status + */ +__weak void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(msg); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCDEx_LPM_Callback could be implemented in the user file + */ +} + +/** + * @brief Send BatteryCharging message to user layer callback. + * @param hpcd PCD handle + * @param msg LPM message + * @retval HAL status + */ +__weak void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpcd); + UNUSED(msg); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PCDEx_BCD_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* HAL_PCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pka.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pka.c index 5247d8618..1d42545dc 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pka.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pka.c @@ -1,3042 +1,3071 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_pka.c - * @author MCD Application Team - * @brief PKA HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of public key accelerator(PKA): - * + Initialization and de-initialization functions - * + Start an operation - * + Retrieve the operation result - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The PKA HAL driver can be used as follows: - - (#) Declare a PKA_HandleTypeDef handle structure, for example: PKA_HandleTypeDef hpka; - - (#) Initialize the PKA low level resources by implementing the HAL_PKA_MspInit() API: - (##) Enable the PKA interface clock - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the PKA interrupt priority - (+++) Enable the NVIC PKA IRQ Channel - - (#) Initialize the PKA registers by calling the HAL_PKA_Init() API which trig - HAL_PKA_MspInit(). - - (#) Fill entirely the input structure corresponding to your operation: - For instance: PKA_ModExpInTypeDef for HAL_PKA_ModExp(). - - (#) Execute the operation (in polling or interrupt) and check the returned value. - - (#) Retrieve the result of the operation (For instance, HAL_PKA_ModExp_GetResult for - HAL_PKA_ModExp operation). The function to gather the result is different for each - kind of operation. The correspondence can be found in the following section. - - (#) Call the function HAL_PKA_DeInit() to restore the default configuration which trig - HAL_PKA_MspDeInit(). - - *** High level operation *** - ================================= - [..] - (+) Input structure requires buffers as uint8_t array. - - (+) Output structure requires buffers as uint8_t array. - - (+) Modular exponentiation using: - (++) HAL_PKA_ModExp(). - (++) HAL_PKA_ModExp_IT(). - (++) HAL_PKA_ModExpFastMode(). - (++) HAL_PKA_ModExpFastMode_IT(). - (++) HAL_PKA_ModExpProtectMode(). - (++) HAL_PKA_ModExpProtectMode_IT(). - (++) HAL_PKA_ModExp_GetResult() to retrieve the result of the operation. - - (+) RSA Chinese Remainder Theorem (CRT) using: - (++) HAL_PKA_RSACRTExp(). - (++) HAL_PKA_RSACRTExp_IT(). - (++) HAL_PKA_RSACRTExp_GetResult() to retrieve the result of the operation. - - (+) ECC Point Check using: - (++) HAL_PKA_PointCheck(). - (++) HAL_PKA_PointCheck_IT(). - (++) HAL_PKA_PointCheck_IsOnCurve() to retrieve the result of the operation. - - (+) ECDSA Sign - (++) HAL_PKA_ECDSASign(). - (++) HAL_PKA_ECDSASign_IT(). - (++) HAL_PKA_ECDSASign_GetResult() to retrieve the result of the operation. - - (+) ECDSA Verify - (++) HAL_PKA_ECDSAVerif(). - (++) HAL_PKA_ECDSAVerif_IT(). - (++) HAL_PKA_ECDSAVerif_IsValidSignature() to retrieve the result of the operation. - - (+) ECC Scalar Multiplication using: - (++) HAL_PKA_ECCMul(). - (++) HAL_PKA_ECCMul_IT(). - (++) HAL_PKA_ECCMul_GetResult() to retrieve the result of the operation. - - (+) ECC double base ladder using: - (++) HAL_PKA_ECCDoubleBaseLadder(). - (++) HAL_PKA_ECCDoubleBaseLadder_IT(). - (++) HAL_PKA_ECCDoubleBaseLadder_GetResult() to retrieve the result of the operation. - - (+) ECC projective to affine using: - (++) HAL_PKA_ECCProjective2Affine(). - (++) HAL_PKA_ECCProjective2Affine_IT(). - (++) HAL_PKA_ECCProjective2Affine_GetResult() to retrieve the result of the operation. - - (+) ECC complete addition using: - (++) HAL_PKA_ECCCompleteAddition(). - (++) HAL_PKA_ECCCompleteAddition_IT(). - (++) HAL_PKA_ECCCompleteAddition_GetResult() to retrieve the result of the operation. - - *** Low level operation *** - ================================= - [..] - (+) Input structure requires buffers as uint32_t array. - - (+) Output structure requires buffers as uint32_t array. - - (+) Arithmetic addition using: - (++) HAL_PKA_Add(). - (++) HAL_PKA_Add_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - The resulting size can be the input parameter or the input parameter size + 1 (overflow). - - (+) Arithmetic subtraction using: - (++) HAL_PKA_Sub(). - (++) HAL_PKA_Sub_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Arithmetic multiplication using: - (++) HAL_PKA_Mul(). - (++) HAL_PKA_Mul_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Comparison using: - (++) HAL_PKA_Cmp(). - (++) HAL_PKA_Cmp_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Modular addition using: - (++) HAL_PKA_ModAdd(). - (++) HAL_PKA_ModAdd_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Modular subtraction using: - (++) HAL_PKA_ModSub(). - (++) HAL_PKA_ModSub_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Modular inversion using: - (++) HAL_PKA_ModInv(). - (++) HAL_PKA_ModInv_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Modular reduction using: - (++) HAL_PKA_ModRed(). - (++) HAL_PKA_ModRed_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - (+) Montgomery multiplication using: - (++) HAL_PKA_MontgomeryMul(). - (++) HAL_PKA_MontgomeryMul_IT(). - (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. - - *** Montgomery parameter *** - ================================= - (+) For some operation, the computation of the Montgomery parameter is a prerequisite. - (+) Input structure requires buffers as uint8_t array. - (+) Output structure requires buffers as uint32_t array.(Only used inside PKA). - (+) You can compute the Montgomery parameter using: - (++) HAL_PKA_MontgomeryParam(). - (++) HAL_PKA_MontgomeryParam_IT(). - (++) HAL_PKA_MontgomeryParam_GetResult() to retrieve the result of the operation. - - *** Polling mode operation *** - =================================== - [..] - (+) When an operation is started in polling mode, the function returns when: - (++) A timeout is encounter. - (++) The operation is completed. - - *** Interrupt mode operation *** - =================================== - [..] - (+) Add HAL_PKA_IRQHandler to the IRQHandler of PKA. - (+) Enable the IRQ using HAL_NVIC_EnableIRQ(). - (+) When an operation is started in interrupt mode, the function returns immediately. - (+) When the operation is completed, the callback HAL_PKA_OperationCpltCallback is called. - (+) When an error is encountered, the callback HAL_PKA_ErrorCallback is called. - (+) To stop any operation in interrupt mode, use HAL_PKA_Abort(). - - *** Utilities *** - =================================== - [..] - (+) To clear the PKA RAM, use HAL_PKA_RAMReset(). - (+) To get current state, use HAL_PKA_GetState(). - (+) To get current error, use HAL_PKA_GetError(). - - *** Callback registration *** - ============================================= - [..] - - The compilation flag USE_HAL_PKA_REGISTER_CALLBACKS, when set to 1, - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_PKA_RegisterCallback() - to register an interrupt callback. - [..] - - Function HAL_PKA_RegisterCallback() allows to register following callbacks: - (+) OperationCpltCallback : callback for End of operation. - (+) ErrorCallback : callback for error detection. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - [..] - - Use function HAL_PKA_UnRegisterCallback to reset a callback to the default - weak function. - [..] - - HAL_PKA_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) OperationCpltCallback : callback for End of operation. - (+) ErrorCallback : callback for error detection. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - [..] - - By default, after the HAL_PKA_Init() and when the state is HAL_PKA_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_PKA_OperationCpltCallback(), HAL_PKA_ErrorCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the HAL_PKA_Init()/ HAL_PKA_DeInit() only when - these callbacks are null (not registered beforehand). - [..] - - If MspInit or MspDeInit are not null, the HAL_PKA_Init()/ HAL_PKA_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - [..] - - Callbacks can be registered/unregistered in HAL_PKA_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in HAL_PKA_STATE_READY or HAL_PKA_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - [..] - - Then, the user first registers the MspInit/MspDeInit user callbacks - using HAL_PKA_RegisterCallback() before calling HAL_PKA_DeInit() - or HAL_PKA_Init() function. - [..] - - When the compilation flag USE_HAL_PKA_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#if defined(PKA) && defined(HAL_PKA_MODULE_ENABLED) - -/** @defgroup PKA PKA - * @brief PKA HAL module driver. - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup PKA_Private_Define PKA Private Define - * @{ - */ -#define PKA_RAM_SIZE 1334U - -/* Private macro -------------------------------------------------------------*/ -#define __PKA_RAM_PARAM_END(TAB,INDEX) do{ \ - TAB[INDEX] = 0UL; \ - TAB[INDEX + 1U] = 0UL; \ - } while(0) -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -static uint32_t primeordersize; -static uint32_t opsize; -static uint32_t modulussize; -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup PKA_Private_Functions PKA Private Functions - * @{ - */ -uint32_t PKA_GetMode(const PKA_HandleTypeDef *hpka); -HAL_StatusTypeDef PKA_PollEndOfOperation(const PKA_HandleTypeDef *hpka, uint32_t Timeout, uint32_t Tickstart); -uint32_t PKA_CheckError(const PKA_HandleTypeDef *hpka, uint32_t mode); -uint32_t PKA_GetBitSize_u8(uint32_t byteNumber); -uint32_t PKA_GetOptBitSize_u8(uint32_t byteNumber, uint8_t msb); -uint32_t PKA_GetBitSize_u32(uint32_t wordNumber); -uint32_t PKA_GetArraySize_u8(uint32_t bitSize); -void PKA_Memcpy_u32_to_u8(uint8_t dst[], __IO const uint32_t src[], size_t n); -void PKA_Memcpy_u8_to_u32(__IO uint32_t dst[], const uint8_t src[], size_t n); -void PKA_Memcpy_u32_to_u32(__IO uint32_t dst[], __IO const uint32_t src[], size_t n); -HAL_StatusTypeDef PKA_Process(PKA_HandleTypeDef *hpka, uint32_t mode, uint32_t Timeout); -HAL_StatusTypeDef PKA_Process_IT(PKA_HandleTypeDef *hpka, uint32_t mode); -void PKA_ModExp_Set(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in); -void PKA_ModExpFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in); -void PKA_ModExpProtectMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in); -void PKA_ECCMulEx_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in); -void PKA_ECDSASign_Set(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in); -void PKA_ECDSAVerif_Set(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in); -void PKA_RSACRTExp_Set(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in); -void PKA_PointCheck_Set(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in); -void PKA_ECCMul_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in); -void PKA_ModRed_Set(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in); -void PKA_ModInv_Set(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in); -void PKA_MontgomeryParam_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint8_t *pOp1); -void PKA_ARI_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint32_t *pOp1, const uint32_t *pOp2, - const uint8_t *pOp3); -void PKA_ECCDoubleBaseLadder_Set(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in); -void PKA_ECCProjective2Affine_Set(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in); -void PKA_ECCCompleteAddition_Set(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in); -HAL_StatusTypeDef PKA_WaitOnFlagUntilTimeout(PKA_HandleTypeDef *hpka, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout); -uint32_t PKA_Result_GetSize(const PKA_HandleTypeDef *hpka, uint32_t Startindex, uint32_t Maxsize); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup PKA_Exported_Functions PKA Exported Functions - * @{ - */ - -/** @defgroup PKA_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and de-initialization functions - * -@verbatim - =============================================================================== - ##### Initialization and de-initialization functions ##### - =============================================================================== - [..] This subsection provides a set of functions allowing to initialize and - deinitialize the PKAx peripheral: - - (+) User must implement HAL_PKA_MspInit() function in which he configures - all related peripherals resources (CLOCK, IT and NVIC ). - - (+) Call the function HAL_PKA_Init() to configure the device. - - (+) Call the function HAL_PKA_DeInit() to restore the default configuration - of the selected PKAx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the PKA according to the specified - * parameters in the PKA_InitTypeDef and initialize the associated handle. - * @param hpka PKA handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Init(PKA_HandleTypeDef *hpka) -{ - HAL_StatusTypeDef err = HAL_OK; - uint32_t tickstart; - - /* Check the PKA handle allocation */ - if (hpka != NULL) - { - /* Check the parameters */ - assert_param(IS_PKA_ALL_INSTANCE(hpka->Instance)); - - if (hpka->State == HAL_PKA_STATE_RESET) - { - -#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) - /* Init the PKA Callback settings */ - hpka->OperationCpltCallback = HAL_PKA_OperationCpltCallback; /* Legacy weak OperationCpltCallback */ - hpka->ErrorCallback = HAL_PKA_ErrorCallback; /* Legacy weak ErrorCallback */ - - if (hpka->MspInitCallback == NULL) - { - hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware */ - hpka->MspInitCallback(hpka); -#else - /* Init the low level hardware */ - HAL_PKA_MspInit(hpka); -#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ - } - - /* Set the state to busy */ - hpka->State = HAL_PKA_STATE_BUSY; - - /* Reset the control register and enable the PKA */ - hpka->Instance->CR = PKA_CR_EN; - - /* Get current tick */ - tickstart = HAL_GetTick(); - - /* Wait the INITOK flag Setting */ - if (PKA_WaitOnFlagUntilTimeout(hpka, PKA_SR_INITOK, RESET, tickstart, 5000) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Reset any pending flag */ - SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); - - /* Initialize the error code */ - hpka->ErrorCode = HAL_PKA_ERROR_NONE; - - /* Set the state to ready */ - hpka->State = HAL_PKA_STATE_READY; - } - else - { - err = HAL_ERROR; - } - - return err; -} - -/** - * @brief DeInitialize the PKA peripheral. - * @param hpka PKA handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_DeInit(PKA_HandleTypeDef *hpka) -{ - HAL_StatusTypeDef err = HAL_OK; - - /* Check the PKA handle allocation */ - if (hpka != NULL) - { - /* Check the parameters */ - assert_param(IS_PKA_ALL_INSTANCE(hpka->Instance)); - - /* Set the state to busy */ - hpka->State = HAL_PKA_STATE_BUSY; - - /* Reset the control register */ - /* This abort any operation in progress (PKA RAM content is not guaranteed in this case) */ - hpka->Instance->CR = 0; - - /* Reset any pending flag */ - SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); - -#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) - if (hpka->MspDeInitCallback == NULL) - { - hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - hpka->MspDeInitCallback(hpka); -#else - /* DeInit the low level hardware: CLOCK, NVIC */ - HAL_PKA_MspDeInit(hpka); -#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ - - /* Reset the error code */ - hpka->ErrorCode = HAL_PKA_ERROR_NONE; - - /* Reset the state */ - hpka->State = HAL_PKA_STATE_RESET; - } - else - { - err = HAL_ERROR; - } - - return err; -} - -/** - * @brief Initialize the PKA MSP. - * @param hpka PKA handle - * @retval None - */ -__weak void HAL_PKA_MspInit(PKA_HandleTypeDef *hpka) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpka); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PKA_MspInit can be implemented in the user file - */ -} - -/** - * @brief DeInitialize the PKA MSP. - * @param hpka PKA handle - * @retval None - */ -__weak void HAL_PKA_MspDeInit(PKA_HandleTypeDef *hpka) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpka); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PKA_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User PKA Callback - * To be used instead of the weak predefined callback - * @param hpka Pointer to a PKA_HandleTypeDef structure that contains - * the configuration information for the specified PKA. - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_PKA_OPERATION_COMPLETE_CB_ID End of operation callback ID - * @arg @ref HAL_PKA_ERROR_CB_ID Error callback ID - * @arg @ref HAL_PKA_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_PKA_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_RegisterCallback(PKA_HandleTypeDef *hpka, HAL_PKA_CallbackIDTypeDef CallbackID, - pPKA_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (HAL_PKA_STATE_READY == hpka->State) - { - switch (CallbackID) - { - case HAL_PKA_OPERATION_COMPLETE_CB_ID : - hpka->OperationCpltCallback = pCallback; - break; - - case HAL_PKA_ERROR_CB_ID : - hpka->ErrorCallback = pCallback; - break; - - case HAL_PKA_MSPINIT_CB_ID : - hpka->MspInitCallback = pCallback; - break; - - case HAL_PKA_MSPDEINIT_CB_ID : - hpka->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_PKA_STATE_RESET == hpka->State) - { - switch (CallbackID) - { - case HAL_PKA_MSPINIT_CB_ID : - hpka->MspInitCallback = pCallback; - break; - - case HAL_PKA_MSPDEINIT_CB_ID : - hpka->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a PKA Callback - * PKA callback is redirected to the weak predefined callback - * @param hpka Pointer to a PKA_HandleTypeDef structure that contains - * the configuration information for the specified PKA. - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_PKA_OPERATION_COMPLETE_CB_ID End of operation callback ID - * @arg @ref HAL_PKA_ERROR_CB_ID Error callback ID - * @arg @ref HAL_PKA_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_PKA_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_UnRegisterCallback(PKA_HandleTypeDef *hpka, HAL_PKA_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_PKA_STATE_READY == hpka->State) - { - switch (CallbackID) - { - case HAL_PKA_OPERATION_COMPLETE_CB_ID : - hpka->OperationCpltCallback = HAL_PKA_OperationCpltCallback; /* Legacy weak OperationCpltCallback */ - break; - - case HAL_PKA_ERROR_CB_ID : - hpka->ErrorCallback = HAL_PKA_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_PKA_MSPINIT_CB_ID : - hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_PKA_MSPDEINIT_CB_ID : - hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_PKA_STATE_RESET == hpka->State) - { - switch (CallbackID) - { - case HAL_PKA_MSPINIT_CB_ID : - hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_PKA_MSPDEINIT_CB_ID : - hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup PKA_Exported_Functions_Group2 IO operation functions - * @brief IO operation functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the PKA operations. - - (#) There are two modes of operation: - - (++) Blocking mode : The operation is performed in the polling mode. - These functions return when data operation is completed. - (++) No-Blocking mode : The operation is performed using Interrupts. - These functions return immediately. - The end of the operation is indicated by HAL_PKA_ErrorCallback in case of error. - The end of the operation is indicated by HAL_PKA_OperationCpltCallback in case of success. - To stop any operation in interrupt mode, use HAL_PKA_Abort(). - - (#) Blocking mode functions are : - - (++) HAL_PKA_ModExp() - (++) HAL_PKA_ModExpFastMode() - (++) HAL_PKA_ModExpProtectMode() - (++) HAL_PKA_ModExp_GetResult(); - - (++) HAL_PKA_ECDSASign() - (++) HAL_PKA_ECDSASign_GetResult(); - - (++) HAL_PKA_ECDSAVerif() - (++) HAL_PKA_ECDSAVerif_IsValidSignature(); - - (++) HAL_PKA_RSACRTExp() - (++) HAL_PKA_RSACRTExp_GetResult(); - - (++) HAL_PKA_PointCheck() - (++) HAL_PKA_PointCheck_IsOnCurve(); - - (++) HAL_PKA_ECCMul() - (++) HAL_PKA_ECCMulFastMode() - (++) HAL_PKA_ECCMul_GetResult(); - - (++) HAL_PKA_ECCMulEx() - (++) HAL_PKA_ECCDoubleBaseLadder() - (++) HAL_PKA_ECCDoubleBaseLadder_GetResult(); - (++) HAL_PKA_ECCProjective2Affine() - (++) HAL_PKA_ECCProjective2Affine_GetResult(); - (++) HAL_PKA_ECCCompleteAddition() - (++) HAL_PKA_ECCCompleteAddition_GetResult(); - - (++) HAL_PKA_Add() - (++) HAL_PKA_Sub() - (++) HAL_PKA_Cmp() - (++) HAL_PKA_Mul() - (++) HAL_PKA_ModAdd() - (++) HAL_PKA_ModSub() - (++) HAL_PKA_ModInv() - (++) HAL_PKA_ModRed() - (++) HAL_PKA_MontgomeryMul() - (++) HAL_PKA_Arithmetic_GetResult(P); - - (++) HAL_PKA_MontgomeryParam() - (++) HAL_PKA_MontgomeryParam_GetResult(); - - (#) No-Blocking mode functions with Interrupt are : - - (++) HAL_PKA_ModExp_IT(); - (++) HAL_PKA_ModExpFastMode_IT(); - (++) HAL_PKA_ModExpProtectMode_IT() - (++) HAL_PKA_ModExp_GetResult(); - - (++) HAL_PKA_ECDSASign_IT(); - (++) HAL_PKA_ECDSASign_GetResult(); - - (++) HAL_PKA_ECDSAVerif_IT(); - (++) HAL_PKA_ECDSAVerif_IsValidSignature(); - - (++) HAL_PKA_RSACRTExp_IT(); - (++) HAL_PKA_RSACRTExp_GetResult(); - - (++) HAL_PKA_PointCheck_IT(); - (++) HAL_PKA_PointCheck_IsOnCurve(); - - (++) HAL_PKA_ECCMul_IT(); - (++) HAL_PKA_ECCMulFastMode_IT(); - (++) HAL_PKA_ECCMul_GetResult(); - - (++) HAL_PKA_ECCMulEx_IT(); - (++) HAL_PKA_ECCDoubleBaseLadder_IT() - (++) HAL_PKA_ECCDoubleBaseLadder_GetResult(); - (++) HAL_PKA_ECCProjective2Affine_IT() - (++) HAL_PKA_ECCProjective2Affine_GetResult(); - (++) HAL_PKA_ECCCompleteAddition_IT() - (++) HAL_PKA_ECCCompleteAddition_GetResult(); - (++) HAL_PKA_Add_IT(); - (++) HAL_PKA_Sub_IT(); - (++) HAL_PKA_Cmp_IT(); - (++) HAL_PKA_Mul_IT(); - (++) HAL_PKA_ModAdd_IT(); - (++) HAL_PKA_ModSub_IT(); - (++) HAL_PKA_ModInv_IT(); - (++) HAL_PKA_ModRed_IT(); - (++) HAL_PKA_MontgomeryMul_IT(); - (++) HAL_PKA_Arithmetic_GetResult(); - - (++) HAL_PKA_MontgomeryParam_IT(); - (++) HAL_PKA_MontgomeryParam_GetResult(); - - (++) HAL_PKA_Abort(); - -@endverbatim - * @{ - */ - -/** - * @brief Modular exponentiation in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModExp(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ModExp_Set(hpka, in); - - opsize = in->OpSize; - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MODULAR_EXP, Timeout); -} - -/** - * @brief Modular exponentiation in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModExp_IT(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ModExp_Set(hpka, in); - - opsize = in->OpSize; - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP); -} - -/** - * @brief Modular exponentiation in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModExpFastMode(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ModExpFastMode_Set(hpka, in); - - opsize = in->OpSize; - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE, Timeout); -} - -/** - * @brief Modular exponentiation in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModExpFastMode_IT(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ModExpFastMode_Set(hpka, in); - - opsize = in->OpSize; - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE); -} - -/** - * @brief Modular exponentiation (protected) in blocking mode. - * Useful when a secret information is involved (RSA decryption) - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModExpProtectMode(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in, - uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ModExpProtectMode_Set(hpka, in); - - opsize = in->OpSize; - - return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_PROTECT, Timeout); -} - -/** - * @brief Modular exponentiation (protected) in non-blocking mode with Interrupt. - * Useful when a secret information is involved (RSA decryption) - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModExpProtectMode_IT(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ModExpProtectMode_Set(hpka, in); - - opsize = in->OpSize; - - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_PROTECT); -} - - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param pRes Output buffer - * @retval HAL status - */ -void HAL_PKA_ModExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes) -{ - uint32_t size; - - /* Get output result size */ - size = opsize; - - /* Move the result to appropriate location (indicated in out parameter) */ - PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_RESULT], size); -} - -/** - * @brief Sign a message using elliptic curves over prime fields in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECDSASign(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECDSASign_Set(hpka, in); - - primeordersize = in->primeOrderSize; - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ECDSA_SIGNATURE, Timeout); -} - -/** - * @brief Sign a message using elliptic curves over prime fields in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECDSASign_IT(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECDSASign_Set(hpka, in); - - primeordersize = in->primeOrderSize; - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ECDSA_SIGNATURE); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param out Output information - * @param outExt Additional Output information (facultative) - */ -void HAL_PKA_ECDSASign_GetResult(PKA_HandleTypeDef *hpka, PKA_ECDSASignOutTypeDef *out, - PKA_ECDSASignOutExtParamTypeDef *outExt) -{ - uint32_t size; - - /* Get output result size */ - size = primeordersize; - - - if (out != NULL) - { - PKA_Memcpy_u32_to_u8(out->RSign, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_SIGNATURE_R], size); - PKA_Memcpy_u32_to_u8(out->SSign, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_SIGNATURE_S], size); - } - - /* If user requires the additional information */ - if (outExt != NULL) - { - /* Move the result to appropriate location (indicated in outExt parameter) */ - PKA_Memcpy_u32_to_u8(outExt->ptX, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_FINAL_POINT_X], size); - PKA_Memcpy_u32_to_u8(outExt->ptY, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_FINAL_POINT_Y], size); - } -} - -/** - * @brief Verify the validity of a signature using elliptic curves over prime fields in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECDSAVerif(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECDSAVerif_Set(hpka, in); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ECDSA_VERIFICATION, Timeout); -} - -/** - * @brief Verify the validity of a signature using elliptic curves - * over prime fields in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECDSAVerif_IT(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECDSAVerif_Set(hpka, in); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ECDSA_VERIFICATION); -} - -/** - * @brief Return the result of the ECDSA verification operation. - * @param hpka PKA handle - * @retval 1 if signature is verified, 0 in other case - */ -uint32_t HAL_PKA_ECDSAVerif_IsValidSignature(PKA_HandleTypeDef const *const hpka) -{ - return (hpka->Instance->RAM[PKA_ECDSA_VERIF_OUT_RESULT] == 0xD60DU) ? 1UL : 0UL; -} - -/** - * @brief RSA CRT exponentiation in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_RSACRTExp(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_RSACRTExp_Set(hpka, in); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_RSA_CRT_EXP, Timeout); -} - -/** - * @brief RSA CRT exponentiation in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_RSACRTExp_IT(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_RSACRTExp_Set(hpka, in); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_RSA_CRT_EXP); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param pRes Pointer to memory location to receive the result of the operation - * @retval HAL status - */ -void HAL_PKA_RSACRTExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes) -{ - uint32_t size; - - /* Move the result to appropriate location (indicated in out parameter) */ - size = (hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_MOD_NB_BITS] + 7UL) / 8UL; - - PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_RSA_CRT_EXP_OUT_RESULT], size); -} - -/** - * @brief Point on elliptic curve check in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_PointCheck(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_PointCheck_Set(hpka, in); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_POINT_CHECK, Timeout); -} - -/** - * @brief Point on elliptic curve check in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_PointCheck_IT(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_PointCheck_Set(hpka, in); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_POINT_CHECK); -} - -/** - * @brief Return the result of the point check operation. - * @param hpka PKA handle - * @retval 1 if point is on curve, 0 in other case - */ -uint32_t HAL_PKA_PointCheck_IsOnCurve(PKA_HandleTypeDef const *const hpka) -{ -#define PKA_POINT_IS_ON_CURVE 0xD60DUL - /* Invert the value of the PKA RAM containing the result of the operation */ - return (hpka->Instance->RAM[PKA_POINT_CHECK_OUT_ERROR] == PKA_POINT_IS_ON_CURVE) ? 1UL : 0UL; -} - -/** - * @brief ECC scalar multiplication in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCMul(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCMul_Set(hpka, in); - - modulussize = in->modulusSize; - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout); -} - -/** - * @brief ECC scalar multiplication in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCMul_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCMul_Set(hpka, in); - - modulussize = in->modulusSize; - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL); -} -/** - * @brief ECC scalar multiplication extended in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCMulEx(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCMulEx_Set(hpka, in); - - modulussize = in->modulusSize; - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout); -} - -/** - * @brief ECC scalar multiplication extended in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCMulEx_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCMulEx_Set(hpka, in); - - modulussize = in->modulusSize; - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL); -} -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param out Output information - * @retval HAL status - */ -void HAL_PKA_ECCMul_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCMulOutTypeDef *out) -{ - uint32_t size; - - /* Get output result size */ - size = modulussize; - - /* If a destination buffer is provided */ - if (out != NULL) - { - /* Move the result to appropriate location (indicated in out parameter) */ - PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_RESULT_X], size); - PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_RESULT_Y], size); - } -} - -/** - * @brief Arithmetic addition in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Add(PKA_HandleTypeDef *hpka, PKA_AddInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ARITHMETIC_ADD, Timeout); -} - -/** - * @brief Arithmetic addition in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Add_IT(PKA_HandleTypeDef *hpka, PKA_AddInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_ADD); -} - -/** - * @brief Arithmetic subtraction in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Sub(PKA_HandleTypeDef *hpka, PKA_SubInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ARITHMETIC_SUB, Timeout); -} - -/** - * @brief Arithmetic subtraction in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Sub_IT(PKA_HandleTypeDef *hpka, PKA_SubInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_SUB); -} - -/** - * @brief Arithmetic multiplication in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Mul(PKA_HandleTypeDef *hpka, PKA_MulInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_ARITHMETIC_MUL, Timeout); -} - -/** - * @brief Arithmetic multiplication in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Mul_IT(PKA_HandleTypeDef *hpka, PKA_MulInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_MUL); -} - -/** - * @brief Comparison in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Cmp(PKA_HandleTypeDef *hpka, PKA_CmpInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_COMPARISON, Timeout); -} - -/** - * @brief Comparison in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Cmp_IT(PKA_HandleTypeDef *hpka, PKA_CmpInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_COMPARISON); -} - -/** - * @brief Modular addition in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModAdd(PKA_HandleTypeDef *hpka, PKA_ModAddInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MODULAR_ADD, Timeout); -} - -/** - * @brief Modular addition in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModAdd_IT(PKA_HandleTypeDef *hpka, PKA_ModAddInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_ADD); -} - -/** - * @brief Modular inversion in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModInv(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ModInv_Set(hpka, in); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MODULAR_INV, Timeout); -} - -/** - * @brief Modular inversion in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModInv_IT(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ModInv_Set(hpka, in); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_INV); -} - -/** - * @brief Modular subtraction in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModSub(PKA_HandleTypeDef *hpka, PKA_ModSubInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MODULAR_SUB, Timeout); -} - -/** - * @brief Modular subtraction in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModSub_IT(PKA_HandleTypeDef *hpka, PKA_ModSubInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_SUB); -} - -/** - * @brief Modular reduction in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModRed(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ModRed_Set(hpka, in); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MODULAR_RED, Timeout); -} - -/** - * @brief Modular reduction in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ModRed_IT(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ModRed_Set(hpka, in); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MODULAR_RED); -} - -/** - * @brief Montgomery multiplication in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_MontgomeryMul(PKA_HandleTypeDef *hpka, PKA_MontgomeryMulInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MONTGOMERY_MUL, Timeout); -} - -/** - * @brief Montgomery multiplication in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_MontgomeryMul_IT(PKA_HandleTypeDef *hpka, PKA_MontgomeryMulInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MONTGOMERY_MUL); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param pRes Pointer to memory location to receive the result of the operation - */ -void HAL_PKA_Arithmetic_GetResult(PKA_HandleTypeDef *hpka, uint32_t *pRes) -{ - uint32_t mode = (hpka->Instance->CR & PKA_CR_MODE_Msk) >> PKA_CR_MODE_Pos; - uint32_t size = 0; - - /* Move the result to appropriate location (indicated in pRes parameter) */ - switch (mode) - { - case PKA_MODE_MONTGOMERY_PARAM: - case PKA_MODE_ARITHMETIC_SUB: - case PKA_MODE_MODULAR_ADD: - case PKA_MODE_MODULAR_RED: - case PKA_MODE_MODULAR_INV: - case PKA_MODE_MONTGOMERY_MUL: - size = hpka->Instance->RAM[2] / 32UL; - break; - case PKA_MODE_ARITHMETIC_ADD: - case PKA_MODE_MODULAR_SUB: - size = hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_NB_BITS] / 32UL; - - /* Manage the overflow of the addition */ - if (hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_OUT_RESULT + size] != 0UL) - { - size += 1UL; - } - - break; - case PKA_MODE_COMPARISON: - size = 1; - break; - case PKA_MODE_ARITHMETIC_MUL: - size = hpka->Instance->RAM[PKA_ARITHMETIC_MUL_NB_BITS] / 32UL * 2UL; - break; - default: - break; - } - - if (pRes != NULL) - { - switch (mode) - { - case PKA_MODE_ARITHMETIC_SUB: - case PKA_MODE_MODULAR_ADD: - case PKA_MODE_MODULAR_RED: - case PKA_MODE_MODULAR_INV: - case PKA_MODE_MODULAR_SUB: - case PKA_MODE_MONTGOMERY_MUL: - case PKA_MODE_ARITHMETIC_ADD: - case PKA_MODE_COMPARISON: - case PKA_MODE_ARITHMETIC_MUL: - PKA_Memcpy_u32_to_u32(pRes, &hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_OUT_RESULT], size); - break; - default: - break; - } - } -} - -/** - * @brief Montgomery parameter computation in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_MontgomeryParam(PKA_HandleTypeDef *hpka, PKA_MontgomeryParamInTypeDef *in, uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_MontgomeryParam_Set(hpka, in->size, in->pOp1); - - /* Start the operation */ - return PKA_Process(hpka, PKA_MODE_MONTGOMERY_PARAM, Timeout); -} - -/** - * @brief Montgomery parameter computation in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_MontgomeryParam_IT(PKA_HandleTypeDef *hpka, PKA_MontgomeryParamInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_MontgomeryParam_Set(hpka, in->size, in->pOp1); - - /* Start the operation */ - return PKA_Process_IT(hpka, PKA_MODE_MONTGOMERY_PARAM); -} - -/** - * @brief ECC double base ladder in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCDoubleBaseLadder(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in, - uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCDoubleBaseLadder_Set(hpka, in); - - return PKA_Process(hpka, PKA_MODE_DOUBLE_BASE_LADDER, Timeout); -} - -/** - * @brief ECC double base ladder in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCDoubleBaseLadder_IT(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCDoubleBaseLadder_Set(hpka, in); - - return PKA_Process_IT(hpka, PKA_MODE_DOUBLE_BASE_LADDER); -} - -/** - * @brief ECC projective to affine in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCProjective2Affine(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in, - uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCProjective2Affine_Set(hpka, in); - - return PKA_Process(hpka, PKA_MODE_ECC_PROJECTIVE_AFF, Timeout); -} - -/** - * @brief ECC projective to affine in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCProjective2Affine_IT(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCProjective2Affine_Set(hpka, in); - - return PKA_Process_IT(hpka, PKA_MODE_ECC_PROJECTIVE_AFF); -} - -/** - * @brief ECC complete addition in blocking mode. - * @param hpka PKA handle - * @param in Input information - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCCompleteAddition(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in, - uint32_t Timeout) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCCompleteAddition_Set(hpka, in); - - return PKA_Process(hpka, PKA_MODE_ECC_COMPLETE_ADD, Timeout); -} - -/** - * @brief ECC complete addition in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param in Input information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_ECCCompleteAddition_IT(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in) -{ - /* Set input parameter in PKA RAM */ - PKA_ECCCompleteAddition_Set(hpka, in); - - return PKA_Process_IT(hpka, PKA_MODE_ECC_COMPLETE_ADD); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param pRes pointer to buffer where the result will be copied - * @retval HAL status - */ -void HAL_PKA_MontgomeryParam_GetResult(PKA_HandleTypeDef *hpka, uint32_t *pRes) -{ - uint32_t size; - - /* Retrieve the size of the buffer from the PKA RAM */ - size = (hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MOD_NB_BITS] + 31UL) / 32UL; - - /* Move the result to appropriate location (indicated in out parameter) */ - PKA_Memcpy_u32_to_u32(pRes, &hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_OUT_PARAMETER], size); -} - -/** - * @brief Abort any ongoing operation. - * @param hpka PKA handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PKA_Abort(PKA_HandleTypeDef *hpka) -{ - HAL_StatusTypeDef err = HAL_OK; - - /* Clear EN bit */ - /* This abort any operation in progress (PKA RAM content is not guaranteed in this case) */ - CLEAR_BIT(hpka->Instance->CR, PKA_CR_EN); - SET_BIT(hpka->Instance->CR, PKA_CR_EN); - - /* Reset any pending flag */ - SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); - - /* Reset the error code */ - hpka->ErrorCode = HAL_PKA_ERROR_NONE; - - /* Reset the state */ - hpka->State = HAL_PKA_STATE_READY; - - return err; -} - -/** - * @brief Reset the PKA RAM. - * @param hpka PKA handle - * @retval None - */ -void HAL_PKA_RAMReset(PKA_HandleTypeDef *hpka) -{ - uint32_t index; - - /* For each element in the PKA RAM */ - for (index = 0; index < PKA_RAM_SIZE; index++) - { - /* Clear the content */ - hpka->Instance->RAM[index] = 0UL; - } -} - -/** - * @brief This function handles PKA event interrupt request. - * @param hpka PKA handle - * @retval None - */ -void HAL_PKA_IRQHandler(PKA_HandleTypeDef *hpka) -{ - uint32_t mode = PKA_GetMode(hpka); - uint32_t itsource = READ_REG(hpka->Instance->CR); - uint32_t flag = READ_REG(hpka->Instance->SR); - - /* Address error interrupt occurred */ - if (((itsource & PKA_IT_ADDRERR) == PKA_IT_ADDRERR) && ((flag & PKA_FLAG_ADDRERR) == PKA_FLAG_ADDRERR)) - { - hpka->ErrorCode |= HAL_PKA_ERROR_ADDRERR; - - /* Clear ADDRERR flag */ - __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_ADDRERR); - } - - /* RAM access error interrupt occurred */ - if (((itsource & PKA_IT_RAMERR) == PKA_IT_RAMERR) && ((flag & PKA_FLAG_RAMERR) == PKA_FLAG_RAMERR)) - { - hpka->ErrorCode |= HAL_PKA_ERROR_RAMERR; - - /* Clear RAMERR flag */ - __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_RAMERR); - } - - /* OPERATION access error interrupt occurred */ - if (((itsource & PKA_IT_OPERR) == PKA_IT_OPERR) && ((flag & PKA_FLAG_OPERR) == PKA_FLAG_OPERR)) - { - hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; - - /* Clear OPERR flag */ - __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_OPERR); - } - - /* Check the operation success in case of ECDSA signature */ - switch (mode) - { - case PKA_MODE_ECDSA_SIGNATURE : - /* If error output result is different from no error, operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_ERROR] != PKA_NO_ERROR) - { - hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; - } - break; - - case PKA_MODE_DOUBLE_BASE_LADDER : - /* If error output result is different from no error, operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_ERROR] != PKA_NO_ERROR) - { - hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; - } - break; - - case PKA_MODE_ECC_PROJECTIVE_AFF : - /* If error output result is different from no error, operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_ERROR] != PKA_NO_ERROR) - { - hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; - } - break; - - case PKA_MODE_ECC_MUL : - /* If error output result is different from no error, operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_ERROR] != PKA_NO_ERROR) - { - hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; - } - break; - - case PKA_MODE_MODULAR_EXP_PROTECT : - /* If error output result is different from no error, operation need to be repeated */ - if (hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_ERROR] != PKA_NO_ERROR) - { - hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; - } - break; - default : - break; - } - /* Trigger the error callback if an error is present */ - if (hpka->ErrorCode != HAL_PKA_ERROR_NONE) - { -#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) - hpka->ErrorCallback(hpka); -#else - HAL_PKA_ErrorCallback(hpka); -#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ - } - - /* End Of Operation interrupt occurred */ - if (((itsource & PKA_IT_PROCEND) == PKA_IT_PROCEND) && ((flag & PKA_FLAG_PROCEND) == PKA_FLAG_PROCEND)) - { - /* Clear PROCEND flag */ - __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_PROCEND); - - /* Set the state to ready */ - hpka->State = HAL_PKA_STATE_READY; - -#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) - hpka->OperationCpltCallback(hpka); -#else - HAL_PKA_OperationCpltCallback(hpka); -#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Process completed callback. - * @param hpka PKA handle - * @retval None - */ -__weak void HAL_PKA_OperationCpltCallback(PKA_HandleTypeDef *hpka) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpka); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PKA_OperationCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Error callback. - * @param hpka PKA handle - * @retval None - */ -__weak void HAL_PKA_ErrorCallback(PKA_HandleTypeDef *hpka) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpka); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PKA_ErrorCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup PKA_Exported_Functions_Group3 Peripheral State and Error functions - * @brief Peripheral State and Error functions - * - @verbatim - =============================================================================== - ##### Peripheral State and Error functions ##### - =============================================================================== - [..] - This subsection permit to get in run-time the status of the peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Return the PKA handle state. - * @param hpka PKA handle - * @retval HAL status - */ -HAL_PKA_StateTypeDef HAL_PKA_GetState(const PKA_HandleTypeDef *hpka) -{ - /* Return PKA handle state */ - return hpka->State; -} - -/** - * @brief Return the PKA error code. - * @param hpka PKA handle - * @retval PKA error code - */ -uint32_t HAL_PKA_GetError(const PKA_HandleTypeDef *hpka) -{ - /* Return PKA handle error code */ - return hpka->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup PKA_Private_Functions - * @{ - */ - -/** - * @brief Get PKA operating mode. - * @param hpka PKA handle - * @retval Return the current mode - */ -uint32_t PKA_GetMode(const PKA_HandleTypeDef *hpka) -{ - /* return the shifted PKA_CR_MODE value */ - return (uint32_t)(READ_BIT(hpka->Instance->CR, PKA_CR_MODE) >> PKA_CR_MODE_Pos); -} - -/** - * @brief Wait for operation completion or timeout. - * @param hpka PKA handle - * @param Timeout Timeout duration in millisecond. - * @param Tickstart Tick start value - * @retval HAL status - */ -HAL_StatusTypeDef PKA_PollEndOfOperation(const PKA_HandleTypeDef *hpka, uint32_t Timeout, uint32_t Tickstart) -{ - /* Wait for the end of operation or timeout */ - while ((hpka->Instance->SR & PKA_SR_PROCENDF) == 0UL) - { - /* Check if timeout is disabled (set to infinite wait) */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0UL)) - { - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief Return a hal error code based on PKA error flags. - * @param hpka PKA handle - * @param mode PKA operating mode - * @retval error code - */ -uint32_t PKA_CheckError(const PKA_HandleTypeDef *hpka, uint32_t mode) -{ - uint32_t err = HAL_PKA_ERROR_NONE; - - /* Check RAMERR error */ - if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_RAMERR) == SET) - { - err |= HAL_PKA_ERROR_RAMERR; - } - - /* Check ADDRERR error */ - if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_ADDRERR) == SET) - { - err |= HAL_PKA_ERROR_ADDRERR; - } - - /* Check OPEERR error */ - if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_OPERR) == SET) - { - err |= HAL_PKA_ERROR_OPERATION; - } - - /* Check the operation success in case of ECDSA signature */ - if (mode == PKA_MODE_ECDSA_SIGNATURE) - { -#define EDCSA_SIGN_NOERROR PKA_NO_ERROR - /* If error output result is different from no error, ecsa sign operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_ERROR] != EDCSA_SIGN_NOERROR) - { - err |= HAL_PKA_ERROR_OPERATION; - } - } - - /* Check the operation success in case of ECC double base ladder*/ - if (mode == PKA_MODE_DOUBLE_BASE_LADDER) - { - /* If error output result is different from no error, PKA operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_ERROR] != PKA_NO_ERROR) - { - err |= HAL_PKA_ERROR_OPERATION; - } - } - - /* Check the operation success in case of ECC projective to affine*/ - if (mode == PKA_MODE_ECC_PROJECTIVE_AFF) - { - /* If error output result is different from no error, PKA operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_ERROR] != PKA_NO_ERROR) - { - err |= HAL_PKA_ERROR_OPERATION; - } - } - - /* Check the operation success in case of ECC Fp scalar multiplication*/ - if (mode == PKA_MODE_ECC_MUL) - { - /* If error output result is different from no error, PKA operation need to be repeated */ - if (hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_ERROR] != PKA_NO_ERROR) - { - err |= HAL_PKA_ERROR_OPERATION; - } - } - - /* Check the operation success in case of protected modular exponentiation*/ - if (mode == PKA_MODE_MODULAR_EXP_PROTECT) - { - /* If error output result is different from no error, PKA operation need to be repeated */ - if (hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_ERROR] != PKA_NO_ERROR) - { - err |= HAL_PKA_ERROR_OPERATION; - } - } - - return err; -} - -/** - * @brief Get number of bits inside an array of u8. - * @param byteNumber Number of u8 inside the array - */ -uint32_t PKA_GetBitSize_u8(uint32_t byteNumber) -{ - /* Convert from number of uint8_t in an array to the associated number of bits in this array */ - return byteNumber * 8UL; -} - -/** - * @brief Get optimal number of bits inside an array of u8. - * @param byteNumber Number of u8 inside the array - * @param msb Most significant uint8_t of the array - */ -uint32_t PKA_GetOptBitSize_u8(uint32_t byteNumber, uint8_t msb) -{ - uint32_t position; - - position = 32UL - __CLZ(msb); - - return (((byteNumber - 1UL) * 8UL) + position); -} - -/** - * @brief Get number of bits inside an array of u32. - * @param wordNumber Number of u32 inside the array - */ -uint32_t PKA_GetBitSize_u32(uint32_t wordNumber) -{ - /* Convert from number of uint32_t in an array to the associated number of bits in this array */ - return wordNumber * 32UL; -} - -/** - * @brief Get number of uint8_t element in an array of bitSize bits. - * @param bitSize Number of bits in an array - */ -uint32_t PKA_GetArraySize_u8(uint32_t bitSize) -{ - /* Manage the non aligned on uint8_t bitsize: */ - /* 512 bits requires 64 uint8_t */ - /* 521 bits requires 66 uint8_t */ - return ((bitSize + 7UL) / 8UL); -} - -/** - * @brief Copy uint32_t array to uint8_t array to fit PKA number representation. - * @param dst Pointer to destination - * @param src Pointer to source - * @param n Number of uint8_t to copy - * @retval dst - */ -void PKA_Memcpy_u32_to_u8(uint8_t dst[], __IO const uint32_t src[], size_t n) -{ - if (dst != NULL) - { - if (src != NULL) - { - uint32_t index_uint32_t = 0UL; /* This index is used outside of the loop */ - - for (; index_uint32_t < (n / 4UL); index_uint32_t++) - { - /* Avoid casting from uint8_t* to uint32_t* by copying 4 uint8_t in a row */ - /* Apply __REV equivalent */ - uint32_t index_uint8_t = n - 4UL - (index_uint32_t * 4UL); - dst[index_uint8_t + 3UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); - dst[index_uint8_t + 2UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL); - dst[index_uint8_t + 1UL] = (uint8_t)((src[index_uint32_t] & 0x00FF0000U) >> 16UL); - dst[index_uint8_t + 0UL] = (uint8_t)((src[index_uint32_t] & 0xFF000000U) >> 24UL); - } - - /* Manage the buffers not aligned on uint32_t */ - if ((n % 4UL) == 1UL) - { - dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); - } - else if ((n % 4UL) == 2UL) - { - dst[1UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); - dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL); - } - else if ((n % 4UL) == 3UL) - { - dst[2UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); - dst[1UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL); - dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x00FF0000U) >> 16UL); - } - else - { - /* The last element is already handle in the loop */ - } - } - } -} - -/** - * @brief Copy uint8_t array to uint32_t array to fit PKA number representation. - * @param dst Pointer to destination - * @param src Pointer to source - * @param n Number of uint8_t to copy (must be multiple of 4) - * @retval dst - */ -void PKA_Memcpy_u8_to_u32(__IO uint32_t dst[], const uint8_t src[], size_t n) -{ - if (dst != NULL) - { - if (src != NULL) - { - uint32_t index = 0UL; /* This index is used outside of the loop */ - - for (; index < (n / 4UL); index++) - { - /* Apply the equivalent of __REV from uint8_t to uint32_t */ - dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \ - | ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL) \ - | ((uint32_t)src[(n - (index * 4UL) - 3UL)] << 16UL) \ - | ((uint32_t)src[(n - (index * 4UL) - 4UL)] << 24UL); - } - - /* Manage the buffers not aligned on uint32_t */ - if ((n % 4UL) == 1UL) - { - dst[index] = (uint32_t)src[(n - (index * 4UL) - 1UL)]; - } - else if ((n % 4UL) == 2UL) - { - dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \ - | ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL); - } - else if ((n % 4UL) == 3UL) - { - dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \ - | ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL) \ - | ((uint32_t)src[(n - (index * 4UL) - 3UL)] << 16UL); - } - else - { - /* The last element is already handle in the loop */ - } - } - } -} - -/** - * @brief Copy uint32_t array to uint32_t array. - * @param dst Pointer to destination - * @param src Pointer to source - * @param n Number of u32 to be handled - * @retval dst - */ -void PKA_Memcpy_u32_to_u32(__IO uint32_t dst[], __IO const uint32_t src[], size_t n) -{ - /* If a destination buffer is provided */ - if (dst != NULL) - { - /* If a source buffer is provided */ - if (src != NULL) - { - /* For each element in the array */ - for (uint32_t index = 0UL; index < n; index++) - { - /* Copy the content */ - dst[index] = src[index]; - } - } - } -} - -/** - * @brief Generic function to start a PKA operation in blocking mode. - * @param hpka PKA handle - * @param mode PKA operation - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef PKA_Process(PKA_HandleTypeDef *hpka, uint32_t mode, uint32_t Timeout) -{ - HAL_StatusTypeDef err = HAL_OK; - uint32_t tickstart; - - if (hpka->State == HAL_PKA_STATE_READY) - { - /* Set the state to busy */ - hpka->State = HAL_PKA_STATE_BUSY; - - /* Clear any pending error */ - hpka->ErrorCode = HAL_PKA_ERROR_NONE; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Set the mode and deactivate the interrupts */ - MODIFY_REG(hpka->Instance->CR, PKA_CR_MODE | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE | PKA_CR_OPERRIE, - mode << PKA_CR_MODE_Pos); - - /* Start the computation */ - hpka->Instance->CR |= PKA_CR_START; - - /* Wait for the end of operation or timeout */ - if (PKA_PollEndOfOperation(hpka, Timeout, tickstart) != HAL_OK) - { - /* Abort any ongoing operation */ - CLEAR_BIT(hpka->Instance->CR, PKA_CR_EN); - - hpka->ErrorCode |= HAL_PKA_ERROR_TIMEOUT; - - /* Make ready for the next operation */ - SET_BIT(hpka->Instance->CR, PKA_CR_EN); - } - - /* Check error */ - hpka->ErrorCode |= PKA_CheckError(hpka, mode); - - /* Clear all flags */ - hpka->Instance->CLRFR |= (PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); - - /* Set the state to ready */ - hpka->State = HAL_PKA_STATE_READY; - - /* Manage the result based on encountered errors */ - if (hpka->ErrorCode != HAL_PKA_ERROR_NONE) - { - err = HAL_ERROR; - } - } - else - { - err = HAL_ERROR; - } - return err; -} - -/** - * @brief Generic function to start a PKA operation in non-blocking mode with Interrupt. - * @param hpka PKA handle - * @param mode PKA operation - * @retval HAL status - */ -HAL_StatusTypeDef PKA_Process_IT(PKA_HandleTypeDef *hpka, uint32_t mode) -{ - HAL_StatusTypeDef err = HAL_OK; - - if (hpka->State == HAL_PKA_STATE_READY) - { - /* Set the state to busy */ - hpka->State = HAL_PKA_STATE_BUSY; - - /* Clear any pending error */ - hpka->ErrorCode = HAL_PKA_ERROR_NONE; - - /* Set the mode and activate interrupts */ - MODIFY_REG(hpka->Instance->CR, PKA_CR_MODE | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE | PKA_CR_OPERRIE, - (mode << PKA_CR_MODE_Pos) | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE | PKA_CR_OPERRIE); - - /* Start the computation */ - hpka->Instance->CR |= PKA_CR_START; - } - else - { - err = HAL_ERROR; - } - return err; -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ModExp_Set(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in) -{ - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize); - - /* Get the number of bit of the exponent */ - hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize); - - /* Move the input parameters pOp1 to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE], in->pOp1, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT_BASE + ((in->OpSize + 3UL) / 4UL)); - - /* Move the exponent to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT], in->pExp, in->expSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT + ((in->expSize + 3UL) / 4UL)); - - /* Move the modulus to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS], in->pMod, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_MODULUS + ((in->OpSize + 3UL) / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ModExpFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in) -{ - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize); - - /* Get the number of bit of the exponent */ - hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize); - - /* Move the input parameters pOp1 to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE], in->pOp1, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT_BASE + (in->OpSize / 4UL)); - - /* Move the exponent to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT], in->pExp, in->expSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT + (in->expSize / 4UL)); - - /* Move the modulus to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS], in->pMod, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_MODULUS + (in->OpSize / 4UL)); - - /* Move the Montgomery parameter to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MONTGOMERY_PARAM], in->pMontgomeryParam, - in->OpSize / 4UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_MONTGOMERY_PARAM + (in->OpSize / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ModExpProtectMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in) -{ - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize); - - /* Get the number of bit of the exponent */ - hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize); - - /* Move the input parameters pOp1 to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_EXPONENT_BASE], in->pOp1, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_EXPONENT_BASE + (in->OpSize / 4UL)); - - /* Move the exponent to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_EXPONENT], in->pExp, in->expSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_EXPONENT + (in->expSize / 4UL)); - - /* Move the modulus to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_MODULUS], in->pMod, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_MODULUS + (in->OpSize / 4UL)); - - /* Move Phi value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_PHI], in->pPhi, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_PHI + (in->OpSize / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - * @note If the modulus size is bigger than the hash size (with a curve SECP521R1 when using a SHA256 hash - * for example)the hash value should be written at the end of the buffer with zeros padding at beginning. - */ -void PKA_ECDSASign_Set(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in) -{ - /* Get the prime order n length */ - hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder)); - - /* Get the modulus p length */ - hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters coefficient |a| to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF], in->coef, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters coefficient B to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_B_COEFF], in->coefB, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_GF], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters integer k to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_K], in->integer, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_K + ((in->primeOrderSize + 3UL) / 4UL)); - - /* Move the input parameters base point G coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_X], in->basePointX, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters base point G coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_Y], in->basePointY, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters hash of message z to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_HASH_E], in->hash, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_HASH_E + ((in->primeOrderSize + 3UL) / 4UL)); - - /* Move the input parameters private key d to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_PRIVATE_KEY_D], in->privateKey, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_PRIVATE_KEY_D + ((in->primeOrderSize + 3UL) / 4UL)); - - /* Move the input parameters prime order n to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_N], in->primeOrder, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_ORDER_N + ((in->primeOrderSize + 3UL) / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ECDSAVerif_Set(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in) -{ - /* Get the prime order n length */ - hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder)); - - /* Get the modulus p length */ - hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters coefficient |a| to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF], in->coef, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_GF], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters base point G coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_X], in->basePointX, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters base point G coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_Y], in->basePointY, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters public-key curve point Q coordinate xQ to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_X], in->pPubKeyCurvePtX, - in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_X + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters public-key curve point Q coordinate xQ to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_Y], in->pPubKeyCurvePtY, - in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters signature part r to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_R], in->RSign, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_SIGNATURE_R + ((in->primeOrderSize + 3UL) / 4UL)); - - /* Move the input parameters signature part s to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_S], in->SSign, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_SIGNATURE_S + ((in->primeOrderSize + 3UL) / 4UL)); - - /* Move the input parameters hash of message z to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_HASH_E], in->hash, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_HASH_E + ((in->primeOrderSize + 3UL) / 4UL)); - - /* Move the input parameters curve prime order n to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_N], in->primeOrder, in->primeOrderSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_ORDER_N + ((in->primeOrderSize + 3UL) / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_RSACRTExp_Set(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in) -{ - /* Get the operand length M */ - hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->size); - - /* Move the input parameters operand dP to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DP_CRT], in->pOpDp, in->size / 2UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_DP_CRT + (in->size / 8UL)); - - /* Move the input parameters operand dQ to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DQ_CRT], in->pOpDq, in->size / 2UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_DQ_CRT + (in->size / 8UL)); - - /* Move the input parameters operand qinv to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_QINV_CRT], in->pOpQinv, in->size / 2UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_QINV_CRT + (in->size / 8UL)); - - /* Move the input parameters prime p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_P], in->pPrimeP, in->size / 2UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_PRIME_P + (in->size / 8UL)); - - /* Move the input parameters prime q to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_Q], in->pPrimeQ, in->size / 2UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_PRIME_Q + (in->size / 8UL)); - - /* Move the input parameters operand A to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_EXPONENT_BASE], in->popA, in->size); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_EXPONENT_BASE + (in->size / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_PointCheck_Set(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in) -{ - /* Get the modulus length */ - hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters coefficient |a| to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF], in->coefA, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters coefficient b to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_B_COEFF], in->coefB, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_GF], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters Point P coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X], in->pointX, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters Point P coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters montgomery param R2 modulus N to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_MONTGOMERY_PARAM], in->pMontgomeryParam, - (in->modulusSize / 4UL)); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_MONTGOMERY_PARAM + ((in->modulusSize + 3UL) / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ECCMul_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in) -{ - /* Get the prime order n length */ - hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_EXP_NB_BITS] = PKA_GetOptBitSize_u8(in->scalarMulSize, *(in->primeOrder)); - - /* Get the modulus length */ - hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters coefficient |a| to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF], in->coefA, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters coefficient b to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_B_COEFF], in->coefB, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters scalar multiplier k to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K], in->scalarMul, in->scalarMulSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_K + ((in->scalarMulSize + 3UL) / 4UL)); - - /* Move the input parameters Point P coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X], in->pointX, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters Point P coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters curve prime order N to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER], in->primeOrder, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER + ((in->modulusSize + 3UL) / 4UL)); -} -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ECCMulEx_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in) -{ - /* Get the prime order n length */ - hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_EXP_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder)); - - /* Get the modulus length */ - hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters coefficient |a| to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF], in->coefA, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters coefficient b to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_B_COEFF], in->coefB, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters scalar multiplier k to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K], in->scalarMul, in->scalarMulSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_K + ((in->scalarMulSize + 3UL) / 4UL)); - - /* Move the input parameters Point P coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X], in->pointX, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters Point P coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); - - /* Move the input parameters curve prime order N to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER], in->primeOrder, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER + ((in->modulusSize + 3UL) / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ModInv_Set(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in) -{ - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_MODULAR_INV_NB_BITS] = PKA_GetBitSize_u32(in->size); - - /* Move the input parameters operand A to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP1], in->pOp1, in->size); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_INV_IN_OP1 + in->size); - - /* Move the input parameters modulus value n to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP2_MOD], in->pMod, in->size * 4UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_INV_IN_OP2_MOD + in->size); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ModRed_Set(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in) -{ - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OP_LENGTH] = PKA_GetBitSize_u32(in->OpSize); - - /* Get the number of bit per modulus */ - hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MOD_LENGTH] = PKA_GetBitSize_u8(in->modSize); - - /* Move the input parameters operand A to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OPERAND], in->pOp1, in->OpSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_REDUC_IN_OPERAND + in->OpSize); - - /* Move the input parameters modulus value n to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MODULUS], in->pMod, in->modSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_REDUC_IN_MODULUS + ((in->modSize + 3UL) / 4UL)); -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param size Size of the operand - * @param pOp1 Generic pointer to input data - */ -void PKA_MontgomeryParam_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint8_t *pOp1) -{ - uint32_t bytetoskip = 0UL; - uint32_t newSize; - - if (pOp1 != NULL) - { - /* Count the number of zero bytes */ - while ((bytetoskip < size) && (pOp1[bytetoskip] == 0UL)) - { - bytetoskip++; - } - - /* Get new size after skipping zero bytes */ - newSize = size - bytetoskip; - - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(newSize, pOp1[bytetoskip]); - - /* Move the input parameters pOp1 to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MODULUS], pOp1, size); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MONTGOMERY_PARAM_IN_MODULUS + ((size + 3UL) / 4UL)); - } -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ECCDoubleBaseLadder_Set(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in) -{ - /* Get the prime order n length */ - hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_PRIME_ORDER_NB_BITS] = PKA_GetBitSize_u8(in->primeOrderSize); - - /* Get the modulus p length */ - hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->modulusSize); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters coefficient |a| to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_A_COEFF], in->coefA, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_A_COEFF + (in->modulusSize / 4UL)); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_MOD_P], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_MOD_P + (in->modulusSize / 4UL)); - - /* Move the input parameters integer k to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_K_INTEGER], in->integerK, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_K_INTEGER + (in->modulusSize / 4UL)); - - /* Move the input parameters integer m to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_M_INTEGER], in->integerM, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_M_INTEGER + (in->modulusSize / 4UL)); - - /* Move the input parameters first point coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT1_X], in->basePointX1, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT1_X + (in->modulusSize / 4UL)); - - /* Move the input parameters first point coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT1_Y], in->basePointY1, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT1_Y + (in->modulusSize / 4UL)); - - /* Move the input parameters first point coordinate z to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT1_Z], in->basePointZ1, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT1_Z + (in->modulusSize / 4UL)); - - /* Move the input parameters second point coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT2_X], in->basePointX2, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT2_X + (in->modulusSize / 4UL)); - - /* Move the input parameters second point coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT2_Y], in->basePointY2, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT2_Y + (in->modulusSize / 4UL)); - - /* Move the input parameters second point coordinate z to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT2_Z], in->basePointZ2, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT2_Z + (in->modulusSize / 4UL)); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param out Output information - * @retval HAL status - */ -void HAL_PKA_ECCDoubleBaseLadder_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderOutTypeDef *out) -{ - uint32_t size; - - /* Move the result to appropriate location (indicated in out parameter) */ - size = hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_MOD_NB_BITS] / 8UL; - if (out != NULL) - { - PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_RESULT_X], size); - PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_RESULT_Y], size); - } -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ECCProjective2Affine_Set(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in) -{ - /* Get the modulus p length */ - hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->modulusSize); - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MOD_P], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_MOD_P + (in->modulusSize / 4UL)); - - /* Move the input parameters point coordinate x to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_POINT_X], in->basePointX, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_POINT_X + (in->modulusSize / 4UL)); - - /* Move the input parameters point coordinate y to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_POINT_Y], in->basePointY, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_POINT_Y + (in->modulusSize / 4UL)); - - /* Move the input parameters point coordinate z to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_POINT_Z], in->basePointZ, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_POINT_Z + (in->modulusSize / 4UL)); - - /* Move the input parameters montgomery parameter R2 modulus n to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MONTGOMERY_PARAM_R2], in->pMontgomeryParam, - (in->modulusSize / 4UL)); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_MONTGOMERY_PARAM_R2 + (in->modulusSize / 4UL)); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param out Output information - * @retval HAL status - */ -void HAL_PKA_ECCProjective2Affine_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineOutTypeDef *out) -{ - uint32_t size; - - /* Move the result to appropriate location (indicated in out parameter) */ - size = hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MOD_NB_BITS] / 8UL; - if (out != NULL) - { - PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_RESULT_X], size); - PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_RESULT_Y], size); - } -} - -/** - * @brief Set input parameters. - * @param hpka PKA handle - * @param in Input information - */ -void PKA_ECCCompleteAddition_Set(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in) -{ - /* Get the modulus p length */ - hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->modulusSize); - - /* Get the coefficient a sign */ - hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_A_COEFF_SIGN] = in->coefSign; - - /* Move the input parameters modulus value p to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_MOD_P], in->modulus, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_MOD_P + (in->modulusSize / 4UL)); - - /* Move the input parameters coefA value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_A_COEFF], in->coefA, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_A_COEFF + (in->modulusSize / 4UL)); - - /* Move the input parameters first point x value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT1_X], in->basePointX1, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT1_X + (in->modulusSize / 4UL)); - - /* Move the input parameters first point y value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT1_Y], in->basePointY1, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT1_Y + (in->modulusSize / 4UL)); - - /* Move the input parameters first point z value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT1_Z], in->basePointZ1, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT1_Z + (in->modulusSize / 4UL)); - - /* Move the input parameters second point x value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT2_X], in->basePointX2, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT2_X + (in->modulusSize / 4UL)); - - /* Move the input parameters second point y value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT2_Y], in->basePointY2, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT2_Y + (in->modulusSize / 4UL)); - - /* Move the input parameters second point z value to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT2_Z], in->basePointZ2, in->modulusSize); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT2_Z + (in->modulusSize / 4UL)); -} - -/** - * @brief Retrieve operation result. - * @param hpka PKA handle - * @param out Output information - * @retval HAL status - */ -void HAL_PKA_ECCCompleteAddition_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionOutTypeDef *out) -{ - uint32_t size; - - /* Move the result to appropriate location (indicated in out parameter) */ - size = (hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_MOD_NB_BITS] + 7UL) / 8UL; - if (out != NULL) - { - PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_OUT_RESULT_X], size); - PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_OUT_RESULT_Y], size); - PKA_Memcpy_u32_to_u8(out->ptZ, &hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_OUT_RESULT_Z], size); - } -} -/** - * @brief Generic function to set input parameters. - * @param hpka PKA handle - * @param size Size of the operand - * @param pOp1 Generic pointer to input data - * @param pOp2 Generic pointer to input data - * @param pOp3 Generic pointer to input data - */ -void PKA_ARI_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint32_t *pOp1, const uint32_t *pOp2, - const uint8_t *pOp3) -{ - /* Get the number of bit per operand */ - hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_NB_BITS] = PKA_GetBitSize_u32(size); - - if (pOp1 != NULL) - { - /* Move the input parameters pOp1 to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP1], pOp1, size); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ARITHMETIC_ALL_OPS_IN_OP1 + size); - } - - if (pOp2 != NULL) - { - /* Move the input parameters pOp2 to PKA RAM */ - PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP2], pOp2, size); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ARITHMETIC_ALL_OPS_IN_OP2 + size); - } - - if (pOp3 != NULL) - { - /* Move the input parameters pOp3 to PKA RAM */ - PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP3], pOp3, size * 4UL); - __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ARITHMETIC_ALL_OPS_IN_OP3 + size); - } -} -/** - * @brief Handle PKA init Timeout. - * @param hpka PKA handle. - * @param Flag Specifies the PKA flag to check - * @param Status Flag status (SET or RESET) - * @param Tickstart Tick start value - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef PKA_WaitOnFlagUntilTimeout(PKA_HandleTypeDef *hpka, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is set */ - while (__HAL_PKA_GET_FLAG(hpka, Flag) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - /* Set the state to ready */ - hpka->State = HAL_PKA_STATE_READY; - - /* Set the error code to timeout error */ - hpka->ErrorCode = HAL_PKA_ERROR_TIMEOUT; - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief Get the size of output result. - * @param hpka PKA handle - * @param Startindex Specifies the start index of the result in the PKA RAM - * @param Maxsize Specifies the possible max size of the result in words - * @retval size - */ -uint32_t PKA_Result_GetSize(const PKA_HandleTypeDef *hpka, uint32_t Startindex, uint32_t Maxsize) -{ - uint32_t size; - uint32_t current_index = Maxsize - 1UL; - - /* Determinate the last index of the result in the PKA RAM */ - while ((hpka->Instance->RAM[Startindex + current_index] == 0UL) && (current_index != 0UL)) - { - current_index--; - } - /* Get the size in bytes */ - size = (current_index + 1UL) * 4UL; - - return size; -} - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined(PKA) && defined(HAL_PKA_MODULE_ENABLED) */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_pka.c + * @author MCD Application Team + * @brief PKA HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of public key accelerator(PKA): + * + Initialization and de-initialization functions + * + Start an operation + * + Retrieve the operation result + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The PKA HAL driver can be used as follows: + + (#) Declare a PKA_HandleTypeDef handle structure, for example: PKA_HandleTypeDef hpka; + + (#) Initialize the PKA low level resources by implementing the HAL_PKA_MspInit() API: + (##) Enable the PKA interface clock + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the PKA interrupt priority + (+++) Enable the NVIC PKA IRQ Channel + + (#) Initialize the PKA registers by calling the HAL_PKA_Init() API which trig + HAL_PKA_MspInit(). + + (#) Fill entirely the input structure corresponding to your operation: + For instance: PKA_ModExpInTypeDef for HAL_PKA_ModExp(). + + (#) Execute the operation (in polling or interrupt) and check the returned value. + + (#) Retrieve the result of the operation (For instance, HAL_PKA_ModExp_GetResult for + HAL_PKA_ModExp operation). The function to gather the result is different for each + kind of operation. The correspondence can be found in the following section. + + (#) Call the function HAL_PKA_DeInit() to restore the default configuration which trig + HAL_PKA_MspDeInit(). + + *** High level operation *** + ================================= + [..] + (+) Input structure requires buffers as uint8_t array. + + (+) Output structure requires buffers as uint8_t array. + + (+) Modular exponentiation using: + (++) HAL_PKA_ModExp(). + (++) HAL_PKA_ModExp_IT(). + (++) HAL_PKA_ModExpFastMode(). + (++) HAL_PKA_ModExpFastMode_IT(). + (++) HAL_PKA_ModExpProtectMode(). + (++) HAL_PKA_ModExpProtectMode_IT(). + (++) HAL_PKA_ModExp_GetResult() to retrieve the result of the operation. + + (+) RSA Chinese Remainder Theorem (CRT) using: + (++) HAL_PKA_RSACRTExp(). + (++) HAL_PKA_RSACRTExp_IT(). + (++) HAL_PKA_RSACRTExp_GetResult() to retrieve the result of the operation. + + (+) ECC Point Check using: + (++) HAL_PKA_PointCheck(). + (++) HAL_PKA_PointCheck_IT(). + (++) HAL_PKA_PointCheck_IsOnCurve() to retrieve the result of the operation. + + (+) ECDSA Sign + (++) HAL_PKA_ECDSASign(). + (++) HAL_PKA_ECDSASign_IT(). + (++) HAL_PKA_ECDSASign_GetResult() to retrieve the result of the operation. + + (+) ECDSA Verify + (++) HAL_PKA_ECDSAVerif(). + (++) HAL_PKA_ECDSAVerif_IT(). + (++) HAL_PKA_ECDSAVerif_IsValidSignature() to retrieve the result of the operation. + + (+) ECC Scalar Multiplication using: + (++) HAL_PKA_ECCMul(). + (++) HAL_PKA_ECCMul_IT(). + (++) HAL_PKA_ECCMul_GetResult() to retrieve the result of the operation. + + (+) ECC double base ladder using: + (++) HAL_PKA_ECCDoubleBaseLadder(). + (++) HAL_PKA_ECCDoubleBaseLadder_IT(). + (++) HAL_PKA_ECCDoubleBaseLadder_GetResult() to retrieve the result of the operation. + + (+) ECC projective to affine using: + (++) HAL_PKA_ECCProjective2Affine(). + (++) HAL_PKA_ECCProjective2Affine_IT(). + (++) HAL_PKA_ECCProjective2Affine_GetResult() to retrieve the result of the operation. + + (+) ECC complete addition using: + (++) HAL_PKA_ECCCompleteAddition(). + (++) HAL_PKA_ECCCompleteAddition_IT(). + (++) HAL_PKA_ECCCompleteAddition_GetResult() to retrieve the result of the operation. + + *** Low level operation *** + ================================= + [..] + (+) Input structure requires buffers as uint32_t array. + + (+) Output structure requires buffers as uint32_t array. + + (+) Arithmetic addition using: + (++) HAL_PKA_Add(). + (++) HAL_PKA_Add_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + The resulting size can be the input parameter or the input parameter size + 1 (overflow). + + (+) Arithmetic subtraction using: + (++) HAL_PKA_Sub(). + (++) HAL_PKA_Sub_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Arithmetic multiplication using: + (++) HAL_PKA_Mul(). + (++) HAL_PKA_Mul_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Comparison using: + (++) HAL_PKA_Cmp(). + (++) HAL_PKA_Cmp_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Modular addition using: + (++) HAL_PKA_ModAdd(). + (++) HAL_PKA_ModAdd_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Modular subtraction using: + (++) HAL_PKA_ModSub(). + (++) HAL_PKA_ModSub_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Modular inversion using: + (++) HAL_PKA_ModInv(). + (++) HAL_PKA_ModInv_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Modular reduction using: + (++) HAL_PKA_ModRed(). + (++) HAL_PKA_ModRed_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + (+) Montgomery multiplication using: + (++) HAL_PKA_MontgomeryMul(). + (++) HAL_PKA_MontgomeryMul_IT(). + (++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation. + + *** Montgomery parameter *** + ================================= + (+) For some operation, the computation of the Montgomery parameter is a prerequisite. + (+) Input structure requires buffers as uint8_t array. + (+) Output structure requires buffers as uint32_t array.(Only used inside PKA). + (+) You can compute the Montgomery parameter using: + (++) HAL_PKA_MontgomeryParam(). + (++) HAL_PKA_MontgomeryParam_IT(). + (++) HAL_PKA_MontgomeryParam_GetResult() to retrieve the result of the operation. + + *** Polling mode operation *** + =================================== + [..] + (+) When an operation is started in polling mode, the function returns when: + (++) A timeout is encounter. + (++) The operation is completed. + + *** Interrupt mode operation *** + =================================== + [..] + (+) Add HAL_PKA_IRQHandler to the IRQHandler of PKA. + (+) Enable the IRQ using HAL_NVIC_EnableIRQ(). + (+) When an operation is started in interrupt mode, the function returns immediately. + (+) When the operation is completed, the callback HAL_PKA_OperationCpltCallback is called. + (+) When an error is encountered, the callback HAL_PKA_ErrorCallback is called. + (+) To stop any operation in interrupt mode, use HAL_PKA_Abort(). + + *** Utilities *** + =================================== + [..] + (+) To clear the PKA RAM, use HAL_PKA_RAMReset(). + (+) To get current state, use HAL_PKA_GetState(). + (+) To get current error, use HAL_PKA_GetError(). + + *** Callback registration *** + ============================================= + [..] + + The compilation flag USE_HAL_PKA_REGISTER_CALLBACKS, when set to 1, + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_PKA_RegisterCallback() + to register an interrupt callback. + [..] + + Function HAL_PKA_RegisterCallback() allows to register following callbacks: + (+) OperationCpltCallback : callback for End of operation. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + + Use function HAL_PKA_UnRegisterCallback to reset a callback to the default + weak function. + [..] + + HAL_PKA_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) OperationCpltCallback : callback for End of operation. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + [..] + + By default, after the HAL_PKA_Init() and when the state is HAL_PKA_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_PKA_OperationCpltCallback(), HAL_PKA_ErrorCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the HAL_PKA_Init()/ HAL_PKA_DeInit() only when + these callbacks are null (not registered beforehand). + [..] + + If MspInit or MspDeInit are not null, the HAL_PKA_Init()/ HAL_PKA_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + + Callbacks can be registered/unregistered in HAL_PKA_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in HAL_PKA_STATE_READY or HAL_PKA_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + [..] + + Then, the user first registers the MspInit/MspDeInit user callbacks + using HAL_PKA_RegisterCallback() before calling HAL_PKA_DeInit() + or HAL_PKA_Init() function. + [..] + + When the compilation flag USE_HAL_PKA_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#if defined(PKA) && defined(HAL_PKA_MODULE_ENABLED) + +/** @defgroup PKA PKA + * @brief PKA HAL module driver. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup PKA_Private_Define PKA Private Define + * @{ + */ +#define PKA_RAM_SIZE 1334U +#define PKA_RAM_ERASE_TIMEOUT 1000U + +/* Private macro -------------------------------------------------------------*/ +#define __PKA_RAM_PARAM_END(TAB,INDEX) do{ \ + TAB[INDEX] = 0UL; \ + TAB[INDEX + 1U] = 0UL; \ + } while(0) +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +static uint32_t primeordersize; +static uint32_t opsize; +static uint32_t modulussize; +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup PKA_Private_Functions PKA Private Functions + * @{ + */ +uint32_t PKA_GetMode(const PKA_HandleTypeDef *hpka); +HAL_StatusTypeDef PKA_PollEndOfOperation(const PKA_HandleTypeDef *hpka, uint32_t Timeout, uint32_t Tickstart); +uint32_t PKA_CheckError(const PKA_HandleTypeDef *hpka, uint32_t mode); +uint32_t PKA_GetBitSize_u8(uint32_t byteNumber); +uint32_t PKA_GetOptBitSize_u8(uint32_t byteNumber, uint8_t msb); +uint32_t PKA_GetBitSize_u32(uint32_t wordNumber); +uint32_t PKA_GetArraySize_u8(uint32_t bitSize); +void PKA_Memcpy_u32_to_u8(uint8_t dst[], __IO const uint32_t src[], size_t n); +void PKA_Memcpy_u8_to_u32(__IO uint32_t dst[], const uint8_t src[], size_t n); +void PKA_Memcpy_u32_to_u32(__IO uint32_t dst[], __IO const uint32_t src[], size_t n); +HAL_StatusTypeDef PKA_Process(PKA_HandleTypeDef *hpka, uint32_t mode, uint32_t Timeout); +HAL_StatusTypeDef PKA_Process_IT(PKA_HandleTypeDef *hpka, uint32_t mode); +void PKA_ModExp_Set(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in); +void PKA_ModExpFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in); +void PKA_ModExpProtectMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in); +void PKA_ECCMulEx_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in); +void PKA_ECDSASign_Set(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in); +void PKA_ECDSAVerif_Set(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in); +void PKA_RSACRTExp_Set(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in); +void PKA_PointCheck_Set(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in); +void PKA_ECCMul_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in); +void PKA_ModRed_Set(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in); +void PKA_ModInv_Set(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in); +void PKA_MontgomeryParam_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint8_t *pOp1); +void PKA_ARI_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint32_t *pOp1, const uint32_t *pOp2, + const uint8_t *pOp3); +void PKA_ECCDoubleBaseLadder_Set(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in); +void PKA_ECCProjective2Affine_Set(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in); +void PKA_ECCCompleteAddition_Set(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in); +HAL_StatusTypeDef PKA_WaitOnFlagUntilTimeout(PKA_HandleTypeDef *hpka, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout); +uint32_t PKA_Result_GetSize(const PKA_HandleTypeDef *hpka, uint32_t Startindex, uint32_t Maxsize); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PKA_Exported_Functions PKA Exported Functions + * @{ + */ + +/** @defgroup PKA_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + deinitialize the PKAx peripheral: + + (+) User must implement HAL_PKA_MspInit() function in which he configures + all related peripherals resources (CLOCK, IT and NVIC ). + + (+) Call the function HAL_PKA_Init() to configure the device. + + (+) Call the function HAL_PKA_DeInit() to restore the default configuration + of the selected PKAx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the PKA according to the specified + * parameters in the PKA_InitTypeDef and initialize the associated handle. + * @param hpka PKA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Init(PKA_HandleTypeDef *hpka) +{ + HAL_StatusTypeDef err = HAL_OK; + uint32_t tickstart; + + /* Check the PKA handle allocation */ + if (hpka != NULL) + { + /* Check the parameters */ + assert_param(IS_PKA_ALL_INSTANCE(hpka->Instance)); + + if (hpka->State == HAL_PKA_STATE_RESET) + { + +#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) + /* Init the PKA Callback settings */ + hpka->OperationCpltCallback = HAL_PKA_OperationCpltCallback; /* Legacy weak OperationCpltCallback */ + hpka->ErrorCallback = HAL_PKA_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hpka->MspInitCallback == NULL) + { + hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hpka->MspInitCallback(hpka); +#else + /* Init the low level hardware */ + HAL_PKA_MspInit(hpka); +#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ + } + + /* Set the state to busy */ + hpka->State = HAL_PKA_STATE_BUSY; + + /* Get current tick */ + tickstart = HAL_GetTick(); + + /* Reset the control register and enable the PKA (wait the end of PKA RAM erase) */ + while ((hpka->Instance->CR & PKA_CR_EN) != PKA_CR_EN) + { + hpka->Instance->CR = PKA_CR_EN; + + /* Check the Timeout */ + if ((HAL_GetTick() - tickstart) > PKA_RAM_ERASE_TIMEOUT) + { + /* Set timeout status */ + err = HAL_TIMEOUT; + break; + } + } + + /* Get current tick */ + tickstart = HAL_GetTick(); + + /* Wait the INITOK flag Setting */ + if (PKA_WaitOnFlagUntilTimeout(hpka, PKA_SR_INITOK, RESET, tickstart, 5000) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Reset any pending flag */ + SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); + + /* Initialize the error code */ + hpka->ErrorCode = HAL_PKA_ERROR_NONE; + + /* Set the state to ready */ + hpka->State = HAL_PKA_STATE_READY; + } + else + { + err = HAL_ERROR; + } + + return err; +} + +/** + * @brief DeInitialize the PKA peripheral. + * @param hpka PKA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_DeInit(PKA_HandleTypeDef *hpka) +{ + HAL_StatusTypeDef err = HAL_OK; + + /* Check the PKA handle allocation */ + if (hpka != NULL) + { + /* Check the parameters */ + assert_param(IS_PKA_ALL_INSTANCE(hpka->Instance)); + + /* Set the state to busy */ + hpka->State = HAL_PKA_STATE_BUSY; + + /* Reset the control register */ + /* This abort any operation in progress (PKA RAM content is not guaranteed in this case) */ + hpka->Instance->CR = 0; + + /* Reset any pending flag */ + SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); + +#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) + if (hpka->MspDeInitCallback == NULL) + { + hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hpka->MspDeInitCallback(hpka); +#else + /* DeInit the low level hardware: CLOCK, NVIC */ + HAL_PKA_MspDeInit(hpka); +#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ + + /* Reset the error code */ + hpka->ErrorCode = HAL_PKA_ERROR_NONE; + + /* Reset the state */ + hpka->State = HAL_PKA_STATE_RESET; + } + else + { + err = HAL_ERROR; + } + + return err; +} + +/** + * @brief Initialize the PKA MSP. + * @param hpka PKA handle + * @retval None + */ +__weak void HAL_PKA_MspInit(PKA_HandleTypeDef *hpka) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpka); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PKA_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitialize the PKA MSP. + * @param hpka PKA handle + * @retval None + */ +__weak void HAL_PKA_MspDeInit(PKA_HandleTypeDef *hpka) +{ + /* NOTE : This function should not be modified, + the HAL_PKA_MspDeInit can be implemented in the user file + user should take into consideration PKA RAM erase when resetting PKA + */ + uint32_t tickstart = HAL_GetTick(); + + /* Enable PKA reset state */ + __HAL_RCC_PKA_FORCE_RESET(); + + /* Release PKA from reset state */ + __HAL_RCC_PKA_RELEASE_RESET(); + + /* Wait the INITOK flag Setting */ + while (hpka->Instance->CR != PKA_CR_EN) + { + hpka->Instance->CR = PKA_CR_EN; + + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > PKA_RAM_ERASE_TIMEOUT) + { + /* update the state */ + hpka->State = HAL_PKA_STATE_ERROR; + } + } + + /* Get current tick */ + tickstart = HAL_GetTick(); + + /* Wait the INITOK flag Setting */ + if (PKA_WaitOnFlagUntilTimeout(hpka, PKA_SR_INITOK, RESET, tickstart, PKA_RAM_ERASE_TIMEOUT) != HAL_OK) + { + /* update the state */ + hpka->State = HAL_PKA_STATE_ERROR; + } + + /* Reset any pending flag */ + SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); + + /* PKA Periph clock disable */ + hpka->Instance->CR = 0; + __HAL_RCC_PKA_CLK_DISABLE(); + + /* PKA Periph IRQ disable */ + HAL_NVIC_DisableIRQ(PKA_IRQn); +} + +#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User PKA Callback + * To be used instead of the weak predefined callback + * @param hpka Pointer to a PKA_HandleTypeDef structure that contains + * the configuration information for the specified PKA. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_PKA_OPERATION_COMPLETE_CB_ID End of operation callback ID + * @arg @ref HAL_PKA_ERROR_CB_ID Error callback ID + * @arg @ref HAL_PKA_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_PKA_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_RegisterCallback(PKA_HandleTypeDef *hpka, HAL_PKA_CallbackIDTypeDef CallbackID, + pPKA_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (HAL_PKA_STATE_READY == hpka->State) + { + switch (CallbackID) + { + case HAL_PKA_OPERATION_COMPLETE_CB_ID : + hpka->OperationCpltCallback = pCallback; + break; + + case HAL_PKA_ERROR_CB_ID : + hpka->ErrorCallback = pCallback; + break; + + case HAL_PKA_MSPINIT_CB_ID : + hpka->MspInitCallback = pCallback; + break; + + case HAL_PKA_MSPDEINIT_CB_ID : + hpka->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_PKA_STATE_RESET == hpka->State) + { + switch (CallbackID) + { + case HAL_PKA_MSPINIT_CB_ID : + hpka->MspInitCallback = pCallback; + break; + + case HAL_PKA_MSPDEINIT_CB_ID : + hpka->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a PKA Callback + * PKA callback is redirected to the weak predefined callback + * @param hpka Pointer to a PKA_HandleTypeDef structure that contains + * the configuration information for the specified PKA. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_PKA_OPERATION_COMPLETE_CB_ID End of operation callback ID + * @arg @ref HAL_PKA_ERROR_CB_ID Error callback ID + * @arg @ref HAL_PKA_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_PKA_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_UnRegisterCallback(PKA_HandleTypeDef *hpka, HAL_PKA_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_PKA_STATE_READY == hpka->State) + { + switch (CallbackID) + { + case HAL_PKA_OPERATION_COMPLETE_CB_ID : + hpka->OperationCpltCallback = HAL_PKA_OperationCpltCallback; /* Legacy weak OperationCpltCallback */ + break; + + case HAL_PKA_ERROR_CB_ID : + hpka->ErrorCallback = HAL_PKA_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_PKA_MSPINIT_CB_ID : + hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_PKA_MSPDEINIT_CB_ID : + hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_PKA_STATE_RESET == hpka->State) + { + switch (CallbackID) + { + case HAL_PKA_MSPINIT_CB_ID : + hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_PKA_MSPDEINIT_CB_ID : + hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup PKA_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the PKA operations. + + (#) There are two modes of operation: + + (++) Blocking mode : The operation is performed in the polling mode. + These functions return when data operation is completed. + (++) No-Blocking mode : The operation is performed using Interrupts. + These functions return immediately. + The end of the operation is indicated by HAL_PKA_ErrorCallback in case of error. + The end of the operation is indicated by HAL_PKA_OperationCpltCallback in case of success. + To stop any operation in interrupt mode, use HAL_PKA_Abort(). + + (#) Blocking mode functions are : + + (++) HAL_PKA_ModExp() + (++) HAL_PKA_ModExpFastMode() + (++) HAL_PKA_ModExpProtectMode() + (++) HAL_PKA_ModExp_GetResult(); + + (++) HAL_PKA_ECDSASign() + (++) HAL_PKA_ECDSASign_GetResult(); + + (++) HAL_PKA_ECDSAVerif() + (++) HAL_PKA_ECDSAVerif_IsValidSignature(); + + (++) HAL_PKA_RSACRTExp() + (++) HAL_PKA_RSACRTExp_GetResult(); + + (++) HAL_PKA_PointCheck() + (++) HAL_PKA_PointCheck_IsOnCurve(); + + (++) HAL_PKA_ECCMul() + (++) HAL_PKA_ECCMulFastMode() + (++) HAL_PKA_ECCMul_GetResult(); + + (++) HAL_PKA_ECCMulEx() + (++) HAL_PKA_ECCDoubleBaseLadder() + (++) HAL_PKA_ECCDoubleBaseLadder_GetResult(); + (++) HAL_PKA_ECCProjective2Affine() + (++) HAL_PKA_ECCProjective2Affine_GetResult(); + (++) HAL_PKA_ECCCompleteAddition() + (++) HAL_PKA_ECCCompleteAddition_GetResult(); + + (++) HAL_PKA_Add() + (++) HAL_PKA_Sub() + (++) HAL_PKA_Cmp() + (++) HAL_PKA_Mul() + (++) HAL_PKA_ModAdd() + (++) HAL_PKA_ModSub() + (++) HAL_PKA_ModInv() + (++) HAL_PKA_ModRed() + (++) HAL_PKA_MontgomeryMul() + (++) HAL_PKA_Arithmetic_GetResult(P); + + (++) HAL_PKA_MontgomeryParam() + (++) HAL_PKA_MontgomeryParam_GetResult(); + + (#) No-Blocking mode functions with Interrupt are : + + (++) HAL_PKA_ModExp_IT(); + (++) HAL_PKA_ModExpFastMode_IT(); + (++) HAL_PKA_ModExpProtectMode_IT() + (++) HAL_PKA_ModExp_GetResult(); + + (++) HAL_PKA_ECDSASign_IT(); + (++) HAL_PKA_ECDSASign_GetResult(); + + (++) HAL_PKA_ECDSAVerif_IT(); + (++) HAL_PKA_ECDSAVerif_IsValidSignature(); + + (++) HAL_PKA_RSACRTExp_IT(); + (++) HAL_PKA_RSACRTExp_GetResult(); + + (++) HAL_PKA_PointCheck_IT(); + (++) HAL_PKA_PointCheck_IsOnCurve(); + + (++) HAL_PKA_ECCMul_IT(); + (++) HAL_PKA_ECCMulFastMode_IT(); + (++) HAL_PKA_ECCMul_GetResult(); + + (++) HAL_PKA_ECCMulEx_IT(); + (++) HAL_PKA_ECCDoubleBaseLadder_IT() + (++) HAL_PKA_ECCDoubleBaseLadder_GetResult(); + (++) HAL_PKA_ECCProjective2Affine_IT() + (++) HAL_PKA_ECCProjective2Affine_GetResult(); + (++) HAL_PKA_ECCCompleteAddition_IT() + (++) HAL_PKA_ECCCompleteAddition_GetResult(); + (++) HAL_PKA_Add_IT(); + (++) HAL_PKA_Sub_IT(); + (++) HAL_PKA_Cmp_IT(); + (++) HAL_PKA_Mul_IT(); + (++) HAL_PKA_ModAdd_IT(); + (++) HAL_PKA_ModSub_IT(); + (++) HAL_PKA_ModInv_IT(); + (++) HAL_PKA_ModRed_IT(); + (++) HAL_PKA_MontgomeryMul_IT(); + (++) HAL_PKA_Arithmetic_GetResult(); + + (++) HAL_PKA_MontgomeryParam_IT(); + (++) HAL_PKA_MontgomeryParam_GetResult(); + + (++) HAL_PKA_Abort(); + +@endverbatim + * @{ + */ + +/** + * @brief Modular exponentiation in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModExp(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ModExp_Set(hpka, in); + opsize = in->OpSize; + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MODULAR_EXP, Timeout); +} + +/** + * @brief Modular exponentiation in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModExp_IT(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ModExp_Set(hpka, in); + opsize = in->OpSize; + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP); +} + +/** + * @brief Modular exponentiation in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModExpFastMode(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ModExpFastMode_Set(hpka, in); + opsize = in->OpSize; + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE, Timeout); +} + +/** + * @brief Modular exponentiation in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModExpFastMode_IT(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ModExpFastMode_Set(hpka, in); + opsize = in->OpSize; + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE); +} + +/** + * @brief Modular exponentiation (protected) in blocking mode. + * Useful when a secret information is involved (RSA decryption) + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModExpProtectMode(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in, + uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ModExpProtectMode_Set(hpka, in); + opsize = in->OpSize; + return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_PROTECT, Timeout); +} + +/** + * @brief Modular exponentiation (protected) in non-blocking mode with Interrupt. + * Useful when a secret information is involved (RSA decryption) + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModExpProtectMode_IT(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ModExpProtectMode_Set(hpka, in); + opsize = in->OpSize; + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_PROTECT); +} + + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param pRes Output buffer + * @retval HAL status + */ +void HAL_PKA_ModExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes) +{ + uint32_t size; + + /* Get output result size */ + size = opsize; + + /* Move the result to appropriate location (indicated in out parameter) */ + PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_RESULT], size); +} + +/** + * @brief Sign a message using elliptic curves over prime fields in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECDSASign(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECDSASign_Set(hpka, in); + primeordersize = in->primeOrderSize; + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ECDSA_SIGNATURE, Timeout); +} + +/** + * @brief Sign a message using elliptic curves over prime fields in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECDSASign_IT(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECDSASign_Set(hpka, in); + primeordersize = in->primeOrderSize; + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ECDSA_SIGNATURE); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param out Output information + * @param outExt Additional Output information (facultative) + */ +void HAL_PKA_ECDSASign_GetResult(PKA_HandleTypeDef *hpka, PKA_ECDSASignOutTypeDef *out, + PKA_ECDSASignOutExtParamTypeDef *outExt) +{ + uint32_t size; + + /* Get output result size */ + size = primeordersize; + + + if (out != NULL) + { + PKA_Memcpy_u32_to_u8(out->RSign, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_SIGNATURE_R], size); + PKA_Memcpy_u32_to_u8(out->SSign, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_SIGNATURE_S], size); + } + + /* If user requires the additional information */ + if (outExt != NULL) + { + /* Move the result to appropriate location (indicated in outExt parameter) */ + PKA_Memcpy_u32_to_u8(outExt->ptX, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_FINAL_POINT_X], size); + PKA_Memcpy_u32_to_u8(outExt->ptY, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_FINAL_POINT_Y], size); + } +} + +/** + * @brief Verify the validity of a signature using elliptic curves over prime fields in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECDSAVerif(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECDSAVerif_Set(hpka, in); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ECDSA_VERIFICATION, Timeout); +} + +/** + * @brief Verify the validity of a signature using elliptic curves + * over prime fields in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECDSAVerif_IT(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECDSAVerif_Set(hpka, in); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ECDSA_VERIFICATION); +} + +/** + * @brief Return the result of the ECDSA verification operation. + * @param hpka PKA handle + * @retval 1 if signature is verified, 0 in other case + */ +uint32_t HAL_PKA_ECDSAVerif_IsValidSignature(PKA_HandleTypeDef const *const hpka) +{ + return (hpka->Instance->RAM[PKA_ECDSA_VERIF_OUT_RESULT] == 0xD60DU) ? 1UL : 0UL; +} + +/** + * @brief RSA CRT exponentiation in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_RSACRTExp(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_RSACRTExp_Set(hpka, in); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_RSA_CRT_EXP, Timeout); +} + +/** + * @brief RSA CRT exponentiation in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_RSACRTExp_IT(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_RSACRTExp_Set(hpka, in); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_RSA_CRT_EXP); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param pRes Pointer to memory location to receive the result of the operation + * @retval HAL status + */ +void HAL_PKA_RSACRTExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes) +{ + uint32_t size; + + /* Move the result to appropriate location (indicated in out parameter) */ + size = (hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_MOD_NB_BITS] + 7UL) / 8UL; + + PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_RSA_CRT_EXP_OUT_RESULT], size); +} + +/** + * @brief Point on elliptic curve check in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_PointCheck(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_PointCheck_Set(hpka, in); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_POINT_CHECK, Timeout); +} + +/** + * @brief Point on elliptic curve check in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_PointCheck_IT(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_PointCheck_Set(hpka, in); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_POINT_CHECK); +} + +/** + * @brief Return the result of the point check operation. + * @param hpka PKA handle + * @retval 1 if point is on curve, 0 in other case + */ +uint32_t HAL_PKA_PointCheck_IsOnCurve(PKA_HandleTypeDef const *const hpka) +{ +#define PKA_POINT_IS_ON_CURVE 0xD60DUL + /* Invert the value of the PKA RAM containing the result of the operation */ + return (hpka->Instance->RAM[PKA_POINT_CHECK_OUT_ERROR] == PKA_POINT_IS_ON_CURVE) ? 1UL : 0UL; +} + +/** + * @brief ECC scalar multiplication in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCMul(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCMul_Set(hpka, in); + modulussize = in->modulusSize; + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout); +} + +/** + * @brief ECC scalar multiplication in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCMul_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCMul_Set(hpka, in); + modulussize = in->modulusSize; + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL); +} +/** + * @brief ECC scalar multiplication extended in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCMulEx(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCMulEx_Set(hpka, in); + modulussize = in->modulusSize; + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout); +} + +/** + * @brief ECC scalar multiplication extended in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCMulEx_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCMulEx_Set(hpka, in); + modulussize = in->modulusSize; + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL); +} +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param out Output information + * @retval HAL status + */ +void HAL_PKA_ECCMul_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCMulOutTypeDef *out) +{ + uint32_t size; + + /* Get output result size */ + size = modulussize; + + /* If a destination buffer is provided */ + if (out != NULL) + { + /* Move the result to appropriate location (indicated in out parameter) */ + PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_RESULT_X], size); + PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_RESULT_Y], size); + } +} + +/** + * @brief Arithmetic addition in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Add(PKA_HandleTypeDef *hpka, PKA_AddInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ARITHMETIC_ADD, Timeout); +} + +/** + * @brief Arithmetic addition in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Add_IT(PKA_HandleTypeDef *hpka, PKA_AddInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_ADD); +} + +/** + * @brief Arithmetic subtraction in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Sub(PKA_HandleTypeDef *hpka, PKA_SubInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ARITHMETIC_SUB, Timeout); +} + +/** + * @brief Arithmetic subtraction in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Sub_IT(PKA_HandleTypeDef *hpka, PKA_SubInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_SUB); +} + +/** + * @brief Arithmetic multiplication in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Mul(PKA_HandleTypeDef *hpka, PKA_MulInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_ARITHMETIC_MUL, Timeout); +} + +/** + * @brief Arithmetic multiplication in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Mul_IT(PKA_HandleTypeDef *hpka, PKA_MulInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_MUL); +} + +/** + * @brief Comparison in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Cmp(PKA_HandleTypeDef *hpka, PKA_CmpInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_COMPARISON, Timeout); +} + +/** + * @brief Comparison in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Cmp_IT(PKA_HandleTypeDef *hpka, PKA_CmpInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_COMPARISON); +} + +/** + * @brief Modular addition in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModAdd(PKA_HandleTypeDef *hpka, PKA_ModAddInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MODULAR_ADD, Timeout); +} + +/** + * @brief Modular addition in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModAdd_IT(PKA_HandleTypeDef *hpka, PKA_ModAddInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_ADD); +} + +/** + * @brief Modular inversion in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModInv(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ModInv_Set(hpka, in); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MODULAR_INV, Timeout); +} + +/** + * @brief Modular inversion in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModInv_IT(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ModInv_Set(hpka, in); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_INV); +} + +/** + * @brief Modular subtraction in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModSub(PKA_HandleTypeDef *hpka, PKA_ModSubInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MODULAR_SUB, Timeout); +} + +/** + * @brief Modular subtraction in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModSub_IT(PKA_HandleTypeDef *hpka, PKA_ModSubInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_SUB); +} + +/** + * @brief Modular reduction in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModRed(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ModRed_Set(hpka, in); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MODULAR_RED, Timeout); +} + +/** + * @brief Modular reduction in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ModRed_IT(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ModRed_Set(hpka, in); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MODULAR_RED); +} + +/** + * @brief Montgomery multiplication in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_MontgomeryMul(PKA_HandleTypeDef *hpka, PKA_MontgomeryMulInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MONTGOMERY_MUL, Timeout); +} + +/** + * @brief Montgomery multiplication in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_MontgomeryMul_IT(PKA_HandleTypeDef *hpka, PKA_MontgomeryMulInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MONTGOMERY_MUL); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param pRes Pointer to memory location to receive the result of the operation + */ +void HAL_PKA_Arithmetic_GetResult(PKA_HandleTypeDef *hpka, uint32_t *pRes) +{ + uint32_t mode = (hpka->Instance->CR & PKA_CR_MODE_Msk) >> PKA_CR_MODE_Pos; + uint32_t size = 0; + + /* Move the result to appropriate location (indicated in pRes parameter) */ + switch (mode) + { + case PKA_MODE_MONTGOMERY_PARAM: + case PKA_MODE_ARITHMETIC_SUB: + case PKA_MODE_MODULAR_ADD: + case PKA_MODE_MODULAR_RED: + case PKA_MODE_MODULAR_INV: + case PKA_MODE_MONTGOMERY_MUL: + size = hpka->Instance->RAM[2] / 32UL; + break; + case PKA_MODE_ARITHMETIC_ADD: + case PKA_MODE_MODULAR_SUB: + size = hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_NB_BITS] / 32UL; + + /* Manage the overflow of the addition */ + if (hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_OUT_RESULT + size] != 0UL) + { + size += 1UL; + } + + break; + case PKA_MODE_COMPARISON: + size = 1; + break; + case PKA_MODE_ARITHMETIC_MUL: + size = hpka->Instance->RAM[PKA_ARITHMETIC_MUL_NB_BITS] / 32UL * 2UL; + break; + default: + break; + } + + if (pRes != NULL) + { + switch (mode) + { + case PKA_MODE_ARITHMETIC_SUB: + case PKA_MODE_MODULAR_ADD: + case PKA_MODE_MODULAR_RED: + case PKA_MODE_MODULAR_INV: + case PKA_MODE_MODULAR_SUB: + case PKA_MODE_MONTGOMERY_MUL: + case PKA_MODE_ARITHMETIC_ADD: + case PKA_MODE_COMPARISON: + case PKA_MODE_ARITHMETIC_MUL: + PKA_Memcpy_u32_to_u32(pRes, &hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_OUT_RESULT], size); + break; + default: + break; + } + } +} + +/** + * @brief Montgomery parameter computation in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_MontgomeryParam(PKA_HandleTypeDef *hpka, PKA_MontgomeryParamInTypeDef *in, uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_MontgomeryParam_Set(hpka, in->size, in->pOp1); + + /* Start the operation */ + return PKA_Process(hpka, PKA_MODE_MONTGOMERY_PARAM, Timeout); +} + +/** + * @brief Montgomery parameter computation in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_MontgomeryParam_IT(PKA_HandleTypeDef *hpka, PKA_MontgomeryParamInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_MontgomeryParam_Set(hpka, in->size, in->pOp1); + + /* Start the operation */ + return PKA_Process_IT(hpka, PKA_MODE_MONTGOMERY_PARAM); +} + +/** + * @brief ECC double base ladder in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCDoubleBaseLadder(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in, + uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCDoubleBaseLadder_Set(hpka, in); + + return PKA_Process(hpka, PKA_MODE_DOUBLE_BASE_LADDER, Timeout); +} + +/** + * @brief ECC double base ladder in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCDoubleBaseLadder_IT(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCDoubleBaseLadder_Set(hpka, in); + + return PKA_Process_IT(hpka, PKA_MODE_DOUBLE_BASE_LADDER); +} + +/** + * @brief ECC projective to affine in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCProjective2Affine(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in, + uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCProjective2Affine_Set(hpka, in); + + return PKA_Process(hpka, PKA_MODE_ECC_PROJECTIVE_AFF, Timeout); +} + +/** + * @brief ECC projective to affine in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCProjective2Affine_IT(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCProjective2Affine_Set(hpka, in); + + return PKA_Process_IT(hpka, PKA_MODE_ECC_PROJECTIVE_AFF); +} + +/** + * @brief ECC complete addition in blocking mode. + * @param hpka PKA handle + * @param in Input information + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCCompleteAddition(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in, + uint32_t Timeout) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCCompleteAddition_Set(hpka, in); + + return PKA_Process(hpka, PKA_MODE_ECC_COMPLETE_ADD, Timeout); +} + +/** + * @brief ECC complete addition in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param in Input information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_ECCCompleteAddition_IT(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in) +{ + /* Set input parameter in PKA RAM */ + PKA_ECCCompleteAddition_Set(hpka, in); + + return PKA_Process_IT(hpka, PKA_MODE_ECC_COMPLETE_ADD); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param pRes pointer to buffer where the result will be copied + * @retval HAL status + */ +void HAL_PKA_MontgomeryParam_GetResult(PKA_HandleTypeDef *hpka, uint32_t *pRes) +{ + uint32_t size; + + /* Retrieve the size of the buffer from the PKA RAM */ + size = (hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MOD_NB_BITS] + 31UL) / 32UL; + + /* Move the result to appropriate location (indicated in out parameter) */ + PKA_Memcpy_u32_to_u32(pRes, &hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_OUT_PARAMETER], size); +} + +/** + * @brief Abort any ongoing operation. + * @param hpka PKA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PKA_Abort(PKA_HandleTypeDef *hpka) +{ + HAL_StatusTypeDef err = HAL_OK; + + /* Clear EN bit */ + /* This abort any operation in progress (PKA RAM content is not guaranteed in this case) */ + CLEAR_BIT(hpka->Instance->CR, PKA_CR_EN); + SET_BIT(hpka->Instance->CR, PKA_CR_EN); + + /* Reset any pending flag */ + SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); + + /* Reset the error code */ + hpka->ErrorCode = HAL_PKA_ERROR_NONE; + + /* Reset the state */ + hpka->State = HAL_PKA_STATE_READY; + + return err; +} + +/** + * @brief Reset the PKA RAM. + * @param hpka PKA handle + * @retval None + */ +void HAL_PKA_RAMReset(PKA_HandleTypeDef *hpka) +{ + uint32_t index; + + /* For each element in the PKA RAM */ + for (index = 0; index < PKA_RAM_SIZE; index++) + { + /* Clear the content */ + hpka->Instance->RAM[index] = 0UL; + } +} + +/** + * @brief This function handles PKA event interrupt request. + * @param hpka PKA handle + * @retval None + */ +void HAL_PKA_IRQHandler(PKA_HandleTypeDef *hpka) +{ + uint32_t mode = PKA_GetMode(hpka); + uint32_t itsource = READ_REG(hpka->Instance->CR); + uint32_t flag = READ_REG(hpka->Instance->SR); + + /* Address error interrupt occurred */ + if (((itsource & PKA_IT_ADDRERR) == PKA_IT_ADDRERR) && ((flag & PKA_FLAG_ADDRERR) == PKA_FLAG_ADDRERR)) + { + hpka->ErrorCode |= HAL_PKA_ERROR_ADDRERR; + + /* Clear ADDRERR flag */ + __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_ADDRERR); + } + + /* RAM access error interrupt occurred */ + if (((itsource & PKA_IT_RAMERR) == PKA_IT_RAMERR) && ((flag & PKA_FLAG_RAMERR) == PKA_FLAG_RAMERR)) + { + hpka->ErrorCode |= HAL_PKA_ERROR_RAMERR; + + /* Clear RAMERR flag */ + __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_RAMERR); + } + + /* OPERATION access error interrupt occurred */ + if (((itsource & PKA_IT_OPERR) == PKA_IT_OPERR) && ((flag & PKA_FLAG_OPERR) == PKA_FLAG_OPERR)) + { + hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; + + /* Clear OPERR flag */ + __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_OPERR); + } + + /* Check the operation success in case of ECDSA signature */ + switch (mode) + { + case PKA_MODE_ECDSA_SIGNATURE : + /* If error output result is different from no error, operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_ERROR] != PKA_NO_ERROR) + { + hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; + } + break; + + case PKA_MODE_DOUBLE_BASE_LADDER : + /* If error output result is different from no error, operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_ERROR] != PKA_NO_ERROR) + { + hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; + } + break; + + case PKA_MODE_ECC_PROJECTIVE_AFF : + /* If error output result is different from no error, operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_ERROR] != PKA_NO_ERROR) + { + hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; + } + break; + + case PKA_MODE_ECC_MUL : + /* If error output result is different from no error, operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_ERROR] != PKA_NO_ERROR) + { + hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; + } + break; + + case PKA_MODE_MODULAR_EXP_PROTECT : + /* If error output result is different from no error, operation need to be repeated */ + if (hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_ERROR] != PKA_NO_ERROR) + { + hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION; + } + break; + default : + break; + } + /* Trigger the error callback if an error is present */ + if (hpka->ErrorCode != HAL_PKA_ERROR_NONE) + { +#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) + hpka->ErrorCallback(hpka); +#else + HAL_PKA_ErrorCallback(hpka); +#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ + } + + /* End Of Operation interrupt occurred */ + if (((itsource & PKA_IT_PROCEND) == PKA_IT_PROCEND) && ((flag & PKA_FLAG_PROCEND) == PKA_FLAG_PROCEND)) + { + /* Clear PROCEND flag */ + __HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_PROCEND); + + /* Set the state to ready */ + hpka->State = HAL_PKA_STATE_READY; + +#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) + hpka->OperationCpltCallback(hpka); +#else + HAL_PKA_OperationCpltCallback(hpka); +#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Process completed callback. + * @param hpka PKA handle + * @retval None + */ +__weak void HAL_PKA_OperationCpltCallback(PKA_HandleTypeDef *hpka) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpka); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PKA_OperationCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Error callback. + * @param hpka PKA handle + * @retval None + */ +__weak void HAL_PKA_ErrorCallback(PKA_HandleTypeDef *hpka) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpka); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PKA_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PKA_Exported_Functions_Group3 Peripheral State and Error functions + * @brief Peripheral State and Error functions + * + @verbatim + =============================================================================== + ##### Peripheral State and Error functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PKA handle state. + * @param hpka PKA handle + * @retval HAL status + */ +HAL_PKA_StateTypeDef HAL_PKA_GetState(const PKA_HandleTypeDef *hpka) +{ + /* Return PKA handle state */ + return hpka->State; +} + +/** + * @brief Return the PKA error code. + * @param hpka PKA handle + * @retval PKA error code + */ +uint32_t HAL_PKA_GetError(const PKA_HandleTypeDef *hpka) +{ + /* Return PKA handle error code */ + return hpka->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup PKA_Private_Functions + * @{ + */ + +/** + * @brief Get PKA operating mode. + * @param hpka PKA handle + * @retval Return the current mode + */ +uint32_t PKA_GetMode(const PKA_HandleTypeDef *hpka) +{ + /* return the shifted PKA_CR_MODE value */ + return (uint32_t)(READ_BIT(hpka->Instance->CR, PKA_CR_MODE) >> PKA_CR_MODE_Pos); +} + +/** + * @brief Wait for operation completion or timeout. + * @param hpka PKA handle + * @param Timeout Timeout duration in millisecond. + * @param Tickstart Tick start value + * @retval HAL status + */ +HAL_StatusTypeDef PKA_PollEndOfOperation(const PKA_HandleTypeDef *hpka, uint32_t Timeout, uint32_t Tickstart) +{ + /* Wait for the end of operation or timeout */ + while ((hpka->Instance->SR & PKA_SR_PROCENDF) == 0UL) + { + /* Check if timeout is disabled (set to infinite wait) */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0UL)) + { + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + +/** + * @brief Return a hal error code based on PKA error flags. + * @param hpka PKA handle + * @param mode PKA operating mode + * @retval error code + */ +uint32_t PKA_CheckError(const PKA_HandleTypeDef *hpka, uint32_t mode) +{ + uint32_t err = HAL_PKA_ERROR_NONE; + + /* Check RAMERR error */ + if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_RAMERR) == SET) + { + err |= HAL_PKA_ERROR_RAMERR; + } + + /* Check ADDRERR error */ + if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_ADDRERR) == SET) + { + err |= HAL_PKA_ERROR_ADDRERR; + } + + /* Check OPEERR error */ + if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_OPERR) == SET) + { + err |= HAL_PKA_ERROR_OPERATION; + } + + /* Check the operation success in case of ECDSA signature */ + if (mode == PKA_MODE_ECDSA_SIGNATURE) + { +#define EDCSA_SIGN_NOERROR PKA_NO_ERROR + /* If error output result is different from no error, ecsa sign operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_ERROR] != EDCSA_SIGN_NOERROR) + { + err |= HAL_PKA_ERROR_OPERATION; + } + } + + /* Check the operation success in case of ECC double base ladder*/ + if (mode == PKA_MODE_DOUBLE_BASE_LADDER) + { + /* If error output result is different from no error, PKA operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_ERROR] != PKA_NO_ERROR) + { + err |= HAL_PKA_ERROR_OPERATION; + } + } + + /* Check the operation success in case of ECC projective to affine*/ + if (mode == PKA_MODE_ECC_PROJECTIVE_AFF) + { + /* If error output result is different from no error, PKA operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_ERROR] != PKA_NO_ERROR) + { + err |= HAL_PKA_ERROR_OPERATION; + } + } + + /* Check the operation success in case of ECC Fp scalar multiplication*/ + if (mode == PKA_MODE_ECC_MUL) + { + /* If error output result is different from no error, PKA operation need to be repeated */ + if (hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_ERROR] != PKA_NO_ERROR) + { + err |= HAL_PKA_ERROR_OPERATION; + } + } + + /* Check the operation success in case of protected modular exponentiation*/ + if (mode == PKA_MODE_MODULAR_EXP_PROTECT) + { + /* If error output result is different from no error, PKA operation need to be repeated */ + if (hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_ERROR] != PKA_NO_ERROR) + { + err |= HAL_PKA_ERROR_OPERATION; + } + } + + return err; +} + +/** + * @brief Get number of bits inside an array of u8. + * @param byteNumber Number of u8 inside the array + */ +uint32_t PKA_GetBitSize_u8(uint32_t byteNumber) +{ + /* Convert from number of uint8_t in an array to the associated number of bits in this array */ + return byteNumber * 8UL; +} + +/** + * @brief Get optimal number of bits inside an array of u8. + * @param byteNumber Number of u8 inside the array + * @param msb Most significant uint8_t of the array + */ +uint32_t PKA_GetOptBitSize_u8(uint32_t byteNumber, uint8_t msb) +{ + uint32_t position; + + position = 32UL - __CLZ(msb); + + return (((byteNumber - 1UL) * 8UL) + position); +} + +/** + * @brief Get number of bits inside an array of u32. + * @param wordNumber Number of u32 inside the array + */ +uint32_t PKA_GetBitSize_u32(uint32_t wordNumber) +{ + /* Convert from number of uint32_t in an array to the associated number of bits in this array */ + return wordNumber * 32UL; +} + +/** + * @brief Get number of uint8_t element in an array of bitSize bits. + * @param bitSize Number of bits in an array + */ +uint32_t PKA_GetArraySize_u8(uint32_t bitSize) +{ + /* Manage the non aligned on uint8_t bitsize: */ + /* 512 bits requires 64 uint8_t */ + /* 521 bits requires 66 uint8_t */ + return ((bitSize + 7UL) / 8UL); +} + +/** + * @brief Copy uint32_t array to uint8_t array to fit PKA number representation. + * @param dst Pointer to destination + * @param src Pointer to source + * @param n Number of uint8_t to copy + * @retval dst + */ +void PKA_Memcpy_u32_to_u8(uint8_t dst[], __IO const uint32_t src[], size_t n) +{ + if (dst != NULL) + { + if (src != NULL) + { + uint32_t index_uint32_t = 0UL; /* This index is used outside of the loop */ + + for (; index_uint32_t < (n / 4UL); index_uint32_t++) + { + /* Avoid casting from uint8_t* to uint32_t* by copying 4 uint8_t in a row */ + /* Apply __REV equivalent */ + uint32_t index_uint8_t = n - 4UL - (index_uint32_t * 4UL); + dst[index_uint8_t + 3UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); + dst[index_uint8_t + 2UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL); + dst[index_uint8_t + 1UL] = (uint8_t)((src[index_uint32_t] & 0x00FF0000U) >> 16UL); + dst[index_uint8_t + 0UL] = (uint8_t)((src[index_uint32_t] & 0xFF000000U) >> 24UL); + } + + /* Manage the buffers not aligned on uint32_t */ + if ((n % 4UL) == 1UL) + { + dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); + } + else if ((n % 4UL) == 2UL) + { + dst[1UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); + dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL); + } + else if ((n % 4UL) == 3UL) + { + dst[2UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU)); + dst[1UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL); + dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x00FF0000U) >> 16UL); + } + else + { + /* The last element is already handle in the loop */ + } + } + } +} + +/** + * @brief Copy uint8_t array to uint32_t array to fit PKA number representation. + * @param dst Pointer to destination + * @param src Pointer to source + * @param n Number of uint8_t to copy (must be multiple of 4) + * @retval dst + */ +void PKA_Memcpy_u8_to_u32(__IO uint32_t dst[], const uint8_t src[], size_t n) +{ + if (dst != NULL) + { + if (src != NULL) + { + uint32_t index = 0UL; /* This index is used outside of the loop */ + + for (; index < (n / 4UL); index++) + { + /* Apply the equivalent of __REV from uint8_t to uint32_t */ + dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \ + | ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL) \ + | ((uint32_t)src[(n - (index * 4UL) - 3UL)] << 16UL) \ + | ((uint32_t)src[(n - (index * 4UL) - 4UL)] << 24UL); + } + + /* Manage the buffers not aligned on uint32_t */ + if ((n % 4UL) == 1UL) + { + dst[index] = (uint32_t)src[(n - (index * 4UL) - 1UL)]; + } + else if ((n % 4UL) == 2UL) + { + dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \ + | ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL); + } + else if ((n % 4UL) == 3UL) + { + dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \ + | ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL) \ + | ((uint32_t)src[(n - (index * 4UL) - 3UL)] << 16UL); + } + else + { + /* The last element is already handle in the loop */ + } + } + } +} + +/** + * @brief Copy uint32_t array to uint32_t array. + * @param dst Pointer to destination + * @param src Pointer to source + * @param n Number of u32 to be handled + * @retval dst + */ +void PKA_Memcpy_u32_to_u32(__IO uint32_t dst[], __IO const uint32_t src[], size_t n) +{ + /* If a destination buffer is provided */ + if (dst != NULL) + { + /* If a source buffer is provided */ + if (src != NULL) + { + /* For each element in the array */ + for (uint32_t index = 0UL; index < n; index++) + { + /* Copy the content */ + dst[index] = src[index]; + } + } + } +} + +/** + * @brief Generic function to start a PKA operation in blocking mode. + * @param hpka PKA handle + * @param mode PKA operation + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef PKA_Process(PKA_HandleTypeDef *hpka, uint32_t mode, uint32_t Timeout) +{ + HAL_StatusTypeDef err = HAL_OK; + uint32_t tickstart; + + if (hpka->State == HAL_PKA_STATE_READY) + { + /* Set the state to busy */ + hpka->State = HAL_PKA_STATE_BUSY; + + /* Clear any pending error */ + hpka->ErrorCode = HAL_PKA_ERROR_NONE; + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + /* Set the mode and deactivate the interrupts */ + MODIFY_REG(hpka->Instance->CR, PKA_CR_MODE | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE | PKA_CR_OPERRIE, + mode << PKA_CR_MODE_Pos); + + /* Start the computation */ + hpka->Instance->CR |= PKA_CR_START; + + /* Wait for the end of operation or timeout */ + if (PKA_PollEndOfOperation(hpka, Timeout, tickstart) != HAL_OK) + { + /* Abort any ongoing operation */ + CLEAR_BIT(hpka->Instance->CR, PKA_CR_EN); + + hpka->ErrorCode |= HAL_PKA_ERROR_TIMEOUT; + + /* Make ready for the next operation */ + SET_BIT(hpka->Instance->CR, PKA_CR_EN); + } + + /* Check error */ + hpka->ErrorCode |= PKA_CheckError(hpka, mode); + + /* Clear all flags */ + hpka->Instance->CLRFR |= (PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); + + /* Set the state to ready */ + hpka->State = HAL_PKA_STATE_READY; + + /* Manage the result based on encountered errors */ + if (hpka->ErrorCode != HAL_PKA_ERROR_NONE) + { + err = HAL_ERROR; + } + } + else + { + err = HAL_ERROR; + } + return err; +} + +/** + * @brief Generic function to start a PKA operation in non-blocking mode with Interrupt. + * @param hpka PKA handle + * @param mode PKA operation + * @retval HAL status + */ +HAL_StatusTypeDef PKA_Process_IT(PKA_HandleTypeDef *hpka, uint32_t mode) +{ + HAL_StatusTypeDef err = HAL_OK; + + if (hpka->State == HAL_PKA_STATE_READY) + { + /* Set the state to busy */ + hpka->State = HAL_PKA_STATE_BUSY; + + /* Clear any pending error */ + hpka->ErrorCode = HAL_PKA_ERROR_NONE; + + /* Set the mode and activate interrupts */ + MODIFY_REG(hpka->Instance->CR, PKA_CR_MODE | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE | PKA_CR_OPERRIE, + (mode << PKA_CR_MODE_Pos) | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE | PKA_CR_OPERRIE); + + /* Start the computation */ + hpka->Instance->CR |= PKA_CR_START; + } + else + { + err = HAL_ERROR; + } + return err; +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ModExp_Set(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in) +{ + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize); + + /* Get the number of bit of the exponent */ + hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize); + + /* Move the input parameters pOp1 to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE], in->pOp1, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT_BASE + ((in->OpSize + 3UL) / 4UL)); + + /* Move the exponent to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT], in->pExp, in->expSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT + ((in->expSize + 3UL) / 4UL)); + + /* Move the modulus to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS], in->pMod, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_MODULUS + ((in->OpSize + 3UL) / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ModExpFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in) +{ + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize); + + /* Get the number of bit of the exponent */ + hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize); + + /* Move the input parameters pOp1 to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE], in->pOp1, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT_BASE + (in->OpSize / 4UL)); + + /* Move the exponent to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT], in->pExp, in->expSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_EXPONENT + (in->expSize / 4UL)); + + /* Move the modulus to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS], in->pMod, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_MODULUS + (in->OpSize / 4UL)); + + /* Move the Montgomery parameter to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MONTGOMERY_PARAM], in->pMontgomeryParam, + in->OpSize / 4UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_IN_MONTGOMERY_PARAM + (in->OpSize / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ModExpProtectMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpProtectModeInTypeDef *in) +{ + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize); + + /* Get the number of bit of the exponent */ + hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize); + + /* Move the input parameters pOp1 to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_EXPONENT_BASE], in->pOp1, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_EXPONENT_BASE + (in->OpSize / 4UL)); + + /* Move the exponent to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_EXPONENT], in->pExp, in->expSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_EXPONENT + (in->expSize / 4UL)); + + /* Move the modulus to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_MODULUS], in->pMod, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_MODULUS + (in->OpSize / 4UL)); + + /* Move Phi value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_PROTECT_IN_PHI], in->pPhi, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_EXP_PROTECT_IN_PHI + (in->OpSize / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + * @note If the modulus size is bigger than the hash size (with a curve SECP521R1 when using a SHA256 hash + * for example)the hash value should be written at the end of the buffer with zeros padding at beginning. + */ +void PKA_ECDSASign_Set(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in) +{ + /* Get the prime order n length */ + hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder)); + + /* Get the modulus p length */ + hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters coefficient |a| to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF], in->coef, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters coefficient B to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_B_COEFF], in->coefB, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_GF], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters integer k to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_K], in->integer, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_K + ((in->primeOrderSize + 3UL) / 4UL)); + + /* Move the input parameters base point G coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_X], in->basePointX, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters base point G coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_Y], in->basePointY, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters hash of message z to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_HASH_E], in->hash, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_HASH_E + ((in->primeOrderSize + 3UL) / 4UL)); + + /* Move the input parameters private key d to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_PRIVATE_KEY_D], in->privateKey, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_PRIVATE_KEY_D + ((in->primeOrderSize + 3UL) / 4UL)); + + /* Move the input parameters prime order n to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_N], in->primeOrder, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_SIGN_IN_ORDER_N + ((in->primeOrderSize + 3UL) / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ECDSAVerif_Set(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in) +{ + /* Get the prime order n length */ + hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder)); + + /* Get the modulus p length */ + hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters coefficient |a| to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF], in->coef, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_GF], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters base point G coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_X], in->basePointX, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters base point G coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_Y], in->basePointY, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters public-key curve point Q coordinate xQ to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_X], in->pPubKeyCurvePtX, + in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_X + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters public-key curve point Q coordinate xQ to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_Y], in->pPubKeyCurvePtY, + in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters signature part r to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_R], in->RSign, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_SIGNATURE_R + ((in->primeOrderSize + 3UL) / 4UL)); + + /* Move the input parameters signature part s to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_S], in->SSign, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_SIGNATURE_S + ((in->primeOrderSize + 3UL) / 4UL)); + + /* Move the input parameters hash of message z to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_HASH_E], in->hash, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_HASH_E + ((in->primeOrderSize + 3UL) / 4UL)); + + /* Move the input parameters curve prime order n to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_N], in->primeOrder, in->primeOrderSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECDSA_VERIF_IN_ORDER_N + ((in->primeOrderSize + 3UL) / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_RSACRTExp_Set(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in) +{ + /* Get the operand length M */ + hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->size); + + /* Move the input parameters operand dP to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DP_CRT], in->pOpDp, in->size / 2UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_DP_CRT + (in->size / 8UL)); + + /* Move the input parameters operand dQ to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DQ_CRT], in->pOpDq, in->size / 2UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_DQ_CRT + (in->size / 8UL)); + + /* Move the input parameters operand qinv to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_QINV_CRT], in->pOpQinv, in->size / 2UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_QINV_CRT + (in->size / 8UL)); + + /* Move the input parameters prime p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_P], in->pPrimeP, in->size / 2UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_PRIME_P + (in->size / 8UL)); + + /* Move the input parameters prime q to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_Q], in->pPrimeQ, in->size / 2UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_PRIME_Q + (in->size / 8UL)); + + /* Move the input parameters operand A to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_EXPONENT_BASE], in->popA, in->size); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_RSA_CRT_EXP_IN_EXPONENT_BASE + (in->size / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_PointCheck_Set(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in) +{ + /* Get the modulus length */ + hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters coefficient |a| to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF], in->coefA, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters coefficient b to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_B_COEFF], in->coefB, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_GF], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters Point P coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X], in->pointX, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters Point P coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters montgomery param R2 modulus N to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_MONTGOMERY_PARAM], in->pMontgomeryParam, + (in->modulusSize / 4UL)); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_POINT_CHECK_IN_MONTGOMERY_PARAM + ((in->modulusSize + 3UL) / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ECCMul_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in) +{ + /* Get the prime order n length */ + hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_EXP_NB_BITS] = PKA_GetOptBitSize_u8(in->scalarMulSize, *(in->primeOrder)); + + /* Get the modulus length */ + hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters coefficient |a| to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF], in->coefA, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters coefficient b to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_B_COEFF], in->coefB, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters scalar multiplier k to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K], in->scalarMul, in->scalarMulSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_K + ((in->scalarMulSize + 3UL) / 4UL)); + + /* Move the input parameters Point P coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X], in->pointX, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters Point P coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters curve prime order N to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER], in->primeOrder, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER + ((in->modulusSize + 3UL) / 4UL)); +} +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ECCMulEx_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDef *in) +{ + /* Get the prime order n length */ + hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_EXP_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder)); + + /* Get the modulus length */ + hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus)); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters coefficient |a| to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF], in->coefA, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters coefficient b to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_B_COEFF], in->coefB, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters scalar multiplier k to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K], in->scalarMul, in->scalarMulSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_K + ((in->scalarMulSize + 3UL) / 4UL)); + + /* Move the input parameters Point P coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X], in->pointX, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters Point P coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)); + + /* Move the input parameters curve prime order N to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER], in->primeOrder, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_SCALAR_MUL_IN_N_PRIME_ORDER + ((in->modulusSize + 3UL) / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ModInv_Set(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in) +{ + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_MODULAR_INV_NB_BITS] = PKA_GetBitSize_u32(in->size); + + /* Move the input parameters operand A to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP1], in->pOp1, in->size); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_INV_IN_OP1 + in->size); + + /* Move the input parameters modulus value n to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP2_MOD], in->pMod, in->size * 4UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_INV_IN_OP2_MOD + in->size); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ModRed_Set(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in) +{ + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OP_LENGTH] = PKA_GetBitSize_u32(in->OpSize); + + /* Get the number of bit per modulus */ + hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MOD_LENGTH] = PKA_GetBitSize_u8(in->modSize); + + /* Move the input parameters operand A to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OPERAND], in->pOp1, in->OpSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_REDUC_IN_OPERAND + in->OpSize); + + /* Move the input parameters modulus value n to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MODULUS], in->pMod, in->modSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MODULAR_REDUC_IN_MODULUS + ((in->modSize + 3UL) / 4UL)); +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param size Size of the operand + * @param pOp1 Generic pointer to input data + */ +void PKA_MontgomeryParam_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint8_t *pOp1) +{ + uint32_t bytetoskip = 0UL; + uint32_t newSize; + + if (pOp1 != NULL) + { + /* Count the number of zero bytes */ + while ((bytetoskip < size) && (pOp1[bytetoskip] == 0UL)) + { + bytetoskip++; + } + + /* Get new size after skipping zero bytes */ + newSize = size - bytetoskip; + + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(newSize, pOp1[bytetoskip]); + + /* Move the input parameters pOp1 to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MODULUS], pOp1, size); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_MONTGOMERY_PARAM_IN_MODULUS + ((size + 3UL) / 4UL)); + } +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ECCDoubleBaseLadder_Set(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderInTypeDef *in) +{ + /* Get the prime order n length */ + hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_PRIME_ORDER_NB_BITS] = PKA_GetBitSize_u8(in->primeOrderSize); + + /* Get the modulus p length */ + hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->modulusSize); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters coefficient |a| to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_A_COEFF], in->coefA, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_A_COEFF + (in->modulusSize / 4UL)); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_MOD_P], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_MOD_P + (in->modulusSize / 4UL)); + + /* Move the input parameters integer k to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_K_INTEGER], in->integerK, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_K_INTEGER + (in->modulusSize / 4UL)); + + /* Move the input parameters integer m to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_M_INTEGER], in->integerM, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_M_INTEGER + (in->modulusSize / 4UL)); + + /* Move the input parameters first point coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT1_X], in->basePointX1, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT1_X + (in->modulusSize / 4UL)); + + /* Move the input parameters first point coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT1_Y], in->basePointY1, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT1_Y + (in->modulusSize / 4UL)); + + /* Move the input parameters first point coordinate z to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT1_Z], in->basePointZ1, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT1_Z + (in->modulusSize / 4UL)); + + /* Move the input parameters second point coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT2_X], in->basePointX2, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT2_X + (in->modulusSize / 4UL)); + + /* Move the input parameters second point coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT2_Y], in->basePointY2, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT2_Y + (in->modulusSize / 4UL)); + + /* Move the input parameters second point coordinate z to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_POINT2_Z], in->basePointZ2, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_DOUBLE_LADDER_IN_POINT2_Z + (in->modulusSize / 4UL)); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param out Output information + * @retval HAL status + */ +void HAL_PKA_ECCDoubleBaseLadder_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCDoubleBaseLadderOutTypeDef *out) +{ + uint32_t size; + + /* Move the result to appropriate location (indicated in out parameter) */ + size = hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_MOD_NB_BITS] / 8UL; + if (out != NULL) + { + PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_RESULT_X], size); + PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_OUT_RESULT_Y], size); + } +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ECCProjective2Affine_Set(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineInTypeDef *in) +{ + /* Get the modulus p length */ + hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->modulusSize); + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MOD_P], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_MOD_P + (in->modulusSize / 4UL)); + + /* Move the input parameters point coordinate x to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_POINT_X], in->basePointX, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_POINT_X + (in->modulusSize / 4UL)); + + /* Move the input parameters point coordinate y to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_POINT_Y], in->basePointY, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_POINT_Y + (in->modulusSize / 4UL)); + + /* Move the input parameters point coordinate z to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_POINT_Z], in->basePointZ, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_POINT_Z + (in->modulusSize / 4UL)); + + /* Move the input parameters montgomery parameter R2 modulus n to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MONTGOMERY_PARAM_R2], in->pMontgomeryParam, + (in->modulusSize / 4UL)); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_PROJECTIVE_AFF_IN_MONTGOMERY_PARAM_R2 + (in->modulusSize / 4UL)); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param out Output information + * @retval HAL status + */ +void HAL_PKA_ECCProjective2Affine_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCProjective2AffineOutTypeDef *out) +{ + uint32_t size; + + /* Move the result to appropriate location (indicated in out parameter) */ + size = hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_IN_MOD_NB_BITS] / 8UL; + if (out != NULL) + { + PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_RESULT_X], size); + PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_PROJECTIVE_AFF_OUT_RESULT_Y], size); + } +} + +/** + * @brief Set input parameters. + * @param hpka PKA handle + * @param in Input information + */ +void PKA_ECCCompleteAddition_Set(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionInTypeDef *in) +{ + /* Get the modulus p length */ + hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->modulusSize); + + /* Get the coefficient a sign */ + hpka->Instance->RAM[PKA_ECC_DOUBLE_LADDER_IN_A_COEFF_SIGN] = in->coefSign; + + /* Move the input parameters modulus value p to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_MOD_P], in->modulus, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_MOD_P + (in->modulusSize / 4UL)); + + /* Move the input parameters coefA value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_A_COEFF], in->coefA, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_A_COEFF + (in->modulusSize / 4UL)); + + /* Move the input parameters first point x value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT1_X], in->basePointX1, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT1_X + (in->modulusSize / 4UL)); + + /* Move the input parameters first point y value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT1_Y], in->basePointY1, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT1_Y + (in->modulusSize / 4UL)); + + /* Move the input parameters first point z value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT1_Z], in->basePointZ1, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT1_Z + (in->modulusSize / 4UL)); + + /* Move the input parameters second point x value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT2_X], in->basePointX2, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT2_X + (in->modulusSize / 4UL)); + + /* Move the input parameters second point y value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT2_Y], in->basePointY2, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT2_Y + (in->modulusSize / 4UL)); + + /* Move the input parameters second point z value to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_POINT2_Z], in->basePointZ2, in->modulusSize); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ECC_COMPLETE_ADD_IN_POINT2_Z + (in->modulusSize / 4UL)); +} + +/** + * @brief Retrieve operation result. + * @param hpka PKA handle + * @param out Output information + * @retval HAL status + */ +void HAL_PKA_ECCCompleteAddition_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCCompleteAdditionOutTypeDef *out) +{ + uint32_t size; + + /* Move the result to appropriate location (indicated in out parameter) */ + size = (hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_IN_MOD_NB_BITS] + 7UL) / 8UL; + if (out != NULL) + { + PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_OUT_RESULT_X], size); + PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_OUT_RESULT_Y], size); + PKA_Memcpy_u32_to_u8(out->ptZ, &hpka->Instance->RAM[PKA_ECC_COMPLETE_ADD_OUT_RESULT_Z], size); + } +} +/** + * @brief Generic function to set input parameters. + * @param hpka PKA handle + * @param size Size of the operand + * @param pOp1 Generic pointer to input data + * @param pOp2 Generic pointer to input data + * @param pOp3 Generic pointer to input data + */ +void PKA_ARI_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint32_t *pOp1, const uint32_t *pOp2, + const uint8_t *pOp3) +{ + /* Get the number of bit per operand */ + hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_NB_BITS] = PKA_GetBitSize_u32(size); + + if (pOp1 != NULL) + { + /* Move the input parameters pOp1 to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP1], pOp1, size); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ARITHMETIC_ALL_OPS_IN_OP1 + size); + } + + if (pOp2 != NULL) + { + /* Move the input parameters pOp2 to PKA RAM */ + PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP2], pOp2, size); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ARITHMETIC_ALL_OPS_IN_OP2 + size); + } + + if (pOp3 != NULL) + { + /* Move the input parameters pOp3 to PKA RAM */ + PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP3], pOp3, size * 4UL); + __PKA_RAM_PARAM_END(hpka->Instance->RAM, PKA_ARITHMETIC_ALL_OPS_IN_OP3 + size); + } +} +/** + * @brief Handle PKA init Timeout. + * @param hpka PKA handle. + * @param Flag Specifies the PKA flag to check + * @param Status Flag status (SET or RESET) + * @param Tickstart Tick start value + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef PKA_WaitOnFlagUntilTimeout(PKA_HandleTypeDef *hpka, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while (__HAL_PKA_GET_FLAG(hpka, Flag) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + /* Set the state to ready */ + hpka->State = HAL_PKA_STATE_READY; + + /* Set the error code to timeout error */ + hpka->ErrorCode = HAL_PKA_ERROR_TIMEOUT; + + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + +/** + * @brief Get the size of output result. + * @param hpka PKA handle + * @param Startindex Specifies the start index of the result in the PKA RAM + * @param Maxsize Specifies the possible max size of the result in words + * @retval size + */ +uint32_t PKA_Result_GetSize(const PKA_HandleTypeDef *hpka, uint32_t Startindex, uint32_t Maxsize) +{ + uint32_t size; + uint32_t current_index = Maxsize - 1UL; + + /* Determinate the last index of the result in the PKA RAM */ + while ((hpka->Instance->RAM[Startindex + current_index] == 0UL) && (current_index != 0UL)) + { + current_index--; + } + /* Get the size in bytes */ + size = (current_index + 1UL) * 4UL; + + return size; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(PKA) && defined(HAL_PKA_MODULE_ENABLED) */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pssi.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pssi.c index 4c23e143a..d554dca2d 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pssi.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pssi.c @@ -1,1929 +1,1929 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_pssi.c - * @author MCD Application Team - * @brief PSSI HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Parallel Synchronous Slave Interface (PSSI) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State and Errors functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The PSSI HAL driver can be used as follows: - - (#) Declare a PSSI_HandleTypeDef handle structure, for example: - PSSI_HandleTypeDef hpssi; - - (#) Initialize the PSSI low level resources by implementing the @ref HAL_PSSI_MspInit() API: - (##) Enable the PSSIx interface clock - (##) PSSI pins configuration - (+++) Enable the clock for the PSSI GPIOs - (+++) Configure PSSI pins as alternate function open-drain - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the PSSIx interrupt priority - (+++) Enable the NVIC PSSI IRQ Channel - (##) DMA Configuration if you need to use DMA process - (+++) Declare DMA_HandleTypeDef handles structure for the transmit and receive - (+++) Enable the DMAx interface clock - (+++) Configure the DMA handle parameters - (+++) Configure the DMA Tx and Rx - (+++) Associate the initialized DMA handle to the hpssi DMA Tx and Rx handle - (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on - the DMA Tx and Rx - - (#) Configure the Communication Bus Width, Control Signals, Input Polarity and Output Polarity - in the hpssi Init structure. - - (#) Initialize the PSSI registers by calling the @ref HAL_PSSI_Init(), configure also the low level Hardware - (GPIO, CLOCK, NVIC...etc) by calling the customized @ref HAL_PSSI_MspInit(&hpssi) API. - - (#) Configure the PSSI clock as internal or external by calling the @ref HAL_PSSI_ClockConfig(). - - (#) For PSSI IO operations, two operation modes are available within this driver : - - *** Polling mode IO operation *** - ================================= - [..] - (+) Transmit an amount of data by byte in blocking mode using @ref HAL_PSSI_Transmit() - (+) Receive an amount of data by byte in blocking mode using @ref HAL_PSSI_Receive() - - *** DMA mode IO operation *** - ============================== - [..] - (+) Transmit an amount of data in non-blocking mode (DMA) using - @ref HAL_PSSI_Transmit_DMA() - (+) At transmission end of transfer, @ref HAL_PSSI_TxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_PSSI_TxCpltCallback() - (+) Receive an amount of data in non-blocking mode (DMA) using - @ref HAL_PSSI_Receive_DMA() - (+) At reception end of transfer, @ref HAL_PSSI_RxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_PSSI_RxCpltCallback() - (+) In case of transfer Error, @ref HAL_PSSI_ErrorCallback() function is executed and user can - add his own code by customization of function pointer @ref HAL_PSSI_ErrorCallback() - (+) Abort a PSSI process communication with Interrupt using @ref HAL_PSSI_Abort_IT() - (+) End of abort process, @ref HAL_PSSI_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_PSSI_AbortCpltCallback() - - *** PSSI HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in PSSI HAL driver. - - (+) @ref HAL_PSSI_ENABLE : Enable the PSSI peripheral - (+) @ref HAL_PSSI_DISABLE : Disable the PSSI peripheral - (+) @ref HAL_PSSI_GET_FLAG : Check whether the specified PSSI flag is set or not - (+) @ref HAL_PSSI_CLEAR_FLAG : Clear the specified PSSI pending flag - (+) @ref HAL_PSSI_ENABLE_IT : Enable the specified PSSI interrupt - (+) @ref HAL_PSSI_DISABLE_IT : Disable the specified PSSI interrupt - - *** Callback registration *** - ============================================= - Use Functions @ref HAL_PSSI_RegisterCallback() or @ref HAL_PSSI_RegisterAddrCallback() - to register an interrupt callback. - - Function @ref HAL_PSSI_RegisterCallback() allows to register following callbacks: - (+) TxCpltCallback : callback for transmission end of transfer. - (+) RxCpltCallback : callback for reception end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - - Use function @ref HAL_PSSI_UnRegisterCallback to reset a callback to the default - weak function. - @ref HAL_PSSI_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxCpltCallback : callback for transmission end of transfer. - (+) RxCpltCallback : callback for reception end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - - - By default, after the @ref HAL_PSSI_Init() and when the state is @ref HAL_PSSI_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples @ref HAL_PSSI_TxCpltCallback(), @ref HAL_PSSI_RxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the @ref HAL_PSSI_Init()/ @ref HAL_PSSI_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the @ref HAL_PSSI_Init()/ @ref HAL_PSSI_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - - Callbacks can be registered/unregistered in @ref HAL_PSSI_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in @ref HAL_PSSI_STATE_READY or @ref HAL_PSSI_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using @ref HAL_PSSI_RegisterCallback() before calling @ref HAL_PSSI_DeInit() - or @ref HAL_PSSI_Init() function. - - - [..] - (@) You can refer to the PSSI HAL driver header file for more useful macros - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup PSSI PSSI - * @brief PSSI HAL module driver - * @{ - */ - -#ifdef HAL_PSSI_MODULE_ENABLED -#if defined(PSSI) -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ - -/** @defgroup PSSI_Private_Define PSSI Private Define - * @{ - */ - - - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/** @defgroup PSSI_Private_Functions PSSI Private Functions - * @{ - */ -/* Private functions to handle DMA transfer */ -#if defined(HAL_DMA_MODULE_ENABLED) -void PSSI_DMATransmitCplt(DMA_HandleTypeDef *hdma); -void PSSI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -void PSSI_DMAError(DMA_HandleTypeDef *hdma); -void PSSI_DMAAbort(DMA_HandleTypeDef *hdma); -#endif /*HAL_DMA_MODULE_ENABLED*/ - -/* Private functions to handle IT transfer */ -static void PSSI_Error(PSSI_HandleTypeDef *hpssi, uint32_t ErrorCode); - - -/* Private functions for PSSI transfer IRQ handler */ - - -/* Private functions to handle flags during polling transfer */ -static HAL_StatusTypeDef PSSI_WaitOnStatusUntilTimeout(PSSI_HandleTypeDef *hpssi, uint32_t Flag, FlagStatus Status, - uint32_t Timeout, uint32_t Tickstart); - -/* Private functions to centralize the enable/disable of Interrupts */ - - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup PSSI_Exported_Functions PSSI Exported Functions - * @{ - */ - -/** @defgroup PSSI_Exported_Functions_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 - deinitialize the PSSIx peripheral: - - (+) User must implement HAL_PSSI_MspInit() function in which he configures - all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). - - (+) Call the function HAL_PSSI_Init() to configure the selected device with - the selected configuration: - (++) Data Width - (++) Control Signals - (++) Input Clock polarity - (++) Output Clock polarity - - (+) Call the function HAL_PSSI_DeInit() to restore the default configuration - of the selected PSSIx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the PSSI according to the specified parameters - * in the PSSI_InitTypeDef and initialize the associated handle. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_Init(PSSI_HandleTypeDef *hpssi) -{ - /* Check the PSSI handle allocation */ - if (hpssi == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_PSSI_ALL_INSTANCE(hpssi->Instance)); - assert_param(IS_PSSI_CONTROL_SIGNAL(hpssi->Init.ControlSignal)); - assert_param(IS_PSSI_BUSWIDTH(hpssi->Init.BusWidth)); - assert_param(IS_PSSI_CLOCK_POLARITY(hpssi->Init.ClockPolarity)); - assert_param(IS_PSSI_DE_POLARITY(hpssi->Init.DataEnablePolarity)); - assert_param(IS_PSSI_RDY_POLARITY(hpssi->Init.ReadyPolarity)); - - if (hpssi->State == HAL_PSSI_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hpssi->Lock = HAL_UNLOCKED; - -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - /* Init the PSSI Callback settings */ - hpssi->TxCpltCallback = HAL_PSSI_TxCpltCallback; /* Legacy weak TxCpltCallback */ - hpssi->RxCpltCallback = HAL_PSSI_RxCpltCallback; /* Legacy weak RxCpltCallback */ - hpssi->ErrorCallback = HAL_PSSI_ErrorCallback; /* Legacy weak ErrorCallback */ - hpssi->AbortCpltCallback = HAL_PSSI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - - if (hpssi->MspInitCallback == NULL) - { - hpssi->MspInitCallback = HAL_PSSI_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - hpssi->MspInitCallback(hpssi); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_PSSI_MspInit(hpssi); -#endif /*USE_HAL_PSSI_REGISTER_CALLBACKS*/ - } - - hpssi->State = HAL_PSSI_STATE_BUSY; - - /* Disable the selected PSSI peripheral */ - HAL_PSSI_DISABLE(hpssi); - - /*---------------------------- PSSIx CR Configuration ----------------------*/ - /* Configure PSSIx: Control Signal and Bus Width*/ - - MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DERDYCFG | PSSI_CR_EDM | PSSI_CR_DEPOL | PSSI_CR_RDYPOL, - hpssi->Init.ControlSignal | hpssi->Init.DataEnablePolarity | - hpssi->Init.ReadyPolarity | hpssi->Init.BusWidth); - - hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; - hpssi->State = HAL_PSSI_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitialize the PSSI peripheral. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_DeInit(PSSI_HandleTypeDef *hpssi) -{ - /* Check the PSSI handle allocation */ - if (hpssi == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_PSSI_ALL_INSTANCE(hpssi->Instance)); - - hpssi->State = HAL_PSSI_STATE_BUSY; - - /* Disable the PSSI Peripheral Clock */ - HAL_PSSI_DISABLE(hpssi); - -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - if (hpssi->MspDeInitCallback == NULL) - { - hpssi->MspDeInitCallback = HAL_PSSI_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - hpssi->MspDeInitCallback(hpssi); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_PSSI_MspDeInit(hpssi); -#endif /*USE_HAL_PSSI_REGISTER_CALLBACKS*/ - - hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; - hpssi->State = HAL_PSSI_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hpssi); - - return HAL_OK; -} - -/** - * @brief Initialize the PSSI MSP. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -__weak void HAL_PSSI_MspInit(PSSI_HandleTypeDef *hpssi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpssi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PSSI_MspInit can be implemented in the user file - */ -} - -/** - * @brief De-Initialize the PSSI MSP. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -__weak void HAL_PSSI_MspDeInit(PSSI_HandleTypeDef *hpssi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpssi); - - /* NOTE : This function should not be modified; when the callback is needed, - the HAL_PSSI_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User PSSI Callback - * To be used instead of the weak predefined callback - * @note The HAL_PSSI_RegisterCallback() may be called before HAL_PSSI_Init() in - * HAL_PSSI_STATE_RESET to register callbacks for HAL_PSSI_MSPINIT_CB_ID - * and HAL_PSSI_MSPDEINIT_CB_ID. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_PSSI_TX_COMPLETE_CB_ID Tx Transfer completed callback ID - * @arg @ref HAL_PSSI_RX_COMPLETE_CB_ID Rx Transfer completed callback ID - * @arg @ref HAL_PSSI_ERROR_CB_ID Error callback ID - * @arg @ref HAL_PSSI_ABORT_CB_ID Abort callback ID - * @arg @ref HAL_PSSI_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_PSSI_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_RegisterCallback(PSSI_HandleTypeDef *hpssi, HAL_PSSI_CallbackIDTypeDef CallbackID, - pPSSI_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (HAL_PSSI_STATE_READY == hpssi->State) - { - switch (CallbackID) - { - case HAL_PSSI_TX_COMPLETE_CB_ID : - hpssi->TxCpltCallback = pCallback; - break; - - case HAL_PSSI_RX_COMPLETE_CB_ID : - hpssi->RxCpltCallback = pCallback; - break; - - case HAL_PSSI_ERROR_CB_ID : - hpssi->ErrorCallback = pCallback; - break; - - case HAL_PSSI_ABORT_CB_ID : - hpssi->AbortCpltCallback = pCallback; - break; - - case HAL_PSSI_MSPINIT_CB_ID : - hpssi->MspInitCallback = pCallback; - break; - - case HAL_PSSI_MSPDEINIT_CB_ID : - hpssi->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_PSSI_STATE_RESET == hpssi->State) - { - switch (CallbackID) - { - case HAL_PSSI_MSPINIT_CB_ID : - hpssi->MspInitCallback = pCallback; - break; - - case HAL_PSSI_MSPDEINIT_CB_ID : - hpssi->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an PSSI Callback - * PSSI callback is redirected to the weak predefined callback - * @note The HAL_PSSI_UnRegisterCallback() may be called before HAL_PSSI_Init() in - * HAL_PSSI_STATE_RESET to un-register callbacks for HAL_PSSI_MSPINIT_CB_ID - * and HAL_PSSI_MSPDEINIT_CB_ID. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_PSSI_TX_COMPLETE_CB_ID Tx Transfer completed callback ID - * @arg @ref HAL_PSSI_RX_COMPLETE_CB_ID Rx Transfer completed callback ID - * @arg @ref HAL_PSSI_ERROR_CB_ID Error callback ID - * @arg @ref HAL_PSSI_ABORT_CB_ID Abort callback ID - * @arg @ref HAL_PSSI_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_PSSI_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_UnRegisterCallback(PSSI_HandleTypeDef *hpssi, HAL_PSSI_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_PSSI_STATE_READY == hpssi->State) - { - switch (CallbackID) - { - case HAL_PSSI_TX_COMPLETE_CB_ID : - hpssi->TxCpltCallback = HAL_PSSI_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_PSSI_RX_COMPLETE_CB_ID : - hpssi->RxCpltCallback = HAL_PSSI_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_PSSI_ERROR_CB_ID : - hpssi->ErrorCallback = HAL_PSSI_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_PSSI_ABORT_CB_ID : - hpssi->AbortCpltCallback = HAL_PSSI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_PSSI_MSPINIT_CB_ID : - hpssi->MspInitCallback = HAL_PSSI_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_PSSI_MSPDEINIT_CB_ID : - hpssi->MspDeInitCallback = HAL_PSSI_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_PSSI_STATE_RESET == hpssi->State) - { - switch (CallbackID) - { - case HAL_PSSI_MSPINIT_CB_ID : - hpssi->MspInitCallback = HAL_PSSI_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_PSSI_MSPDEINIT_CB_ID : - hpssi->MspDeInitCallback = HAL_PSSI_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup PSSI_Exported_Functions_Group2 Input and Output operation functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the PSSI data - transfers. - - (#) There are two modes 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 DMA. - These functions return the status of the transfer startup. - The end of the data processing will be indicated through the - dedicated the DMA IRQ . - - (#) Blocking mode functions are : - (++) HAL_PSSI_Transmit() - (++) HAL_PSSI_Receive() - - (#) No-Blocking mode functions with DMA are : - (++) HAL_PSSI_Transmit_DMA() - (++) HAL_PSSI_Receive_DMA() - - (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (++) HAL_PSSI_TxCpltCallback() - (++) HAL_PSSI_RxCpltCallback() - (++) HAL_PSSI_ErrorCallback() - (++) HAL_PSSI_AbortCpltCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Transmits in master mode an amount of data in blocking mode. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent (in bytes) - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_Transmit(PSSI_HandleTypeDef *hpssi, uint8_t *pData, uint32_t Size, uint32_t Timeout) -{ - uint32_t tickstart; - uint32_t transfer_size = Size; - - if (((hpssi->Init.DataWidth == HAL_PSSI_8BITS) && (hpssi->Init.BusWidth != HAL_PSSI_8LINES)) || - ((hpssi->Init.DataWidth == HAL_PSSI_16BITS) && ((Size % 2U) != 0U)) || - ((hpssi->Init.DataWidth == HAL_PSSI_32BITS) && ((Size % 4U) != 0U))) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; - return HAL_ERROR; - } - if (hpssi->State == HAL_PSSI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hpssi); - - hpssi->State = HAL_PSSI_STATE_BUSY; - hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; - - /* Disable the selected PSSI peripheral */ - HAL_PSSI_DISABLE(hpssi); - - /* Configure transfer parameters */ - MODIFY_REG(hpssi->Instance->CR, (PSSI_CR_OUTEN | PSSI_CR_CKPOL), - (PSSI_CR_OUTEN_OUTPUT | ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? 0U : PSSI_CR_CKPOL))); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* DMA Disable */ - hpssi->Instance->CR &= PSSI_CR_DMA_DISABLE; -#endif /*HAL_DMA_MODULE_ENABLED*/ - - /* Enable the selected PSSI peripheral */ - HAL_PSSI_ENABLE(hpssi); - - if (hpssi->Init.DataWidth == HAL_PSSI_8BITS) - { - uint8_t *pbuffer = pData; - while (transfer_size > 0U) - { - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - /* Wait until Fifo is ready to transfer one byte flag is set */ - if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT1B, RESET, Timeout, tickstart) != HAL_OK) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - /* Write data to DR */ - *(__IO uint8_t *)(&hpssi->Instance->DR) = *(uint8_t *)pbuffer; - - /* Increment Buffer pointer */ - pbuffer++; - - transfer_size--; - } - } - else if (hpssi->Init.DataWidth == HAL_PSSI_16BITS) - { - uint16_t *pbuffer = (uint16_t *)pData; - __IO uint16_t *dr = (__IO uint16_t *)(&hpssi->Instance->DR); - - while (transfer_size > 0U) - { - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - /* Wait until Fifo is ready to transfer four bytes flag is set */ - if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - /* Write data to DR */ - *dr = *pbuffer; - - /* Increment Buffer pointer */ - pbuffer++; - transfer_size -= 2U; - } - } - else if (hpssi->Init.DataWidth == HAL_PSSI_32BITS) - { - uint32_t *pbuffer = (uint32_t *)pData; - while (transfer_size > 0U) - { - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - /* Wait until Fifo is ready to transfer four bytes flag is set */ - if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - /* Write data to DR */ - *(__IO uint32_t *)(&hpssi->Instance->DR) = *pbuffer; - - /* Increment Buffer pointer */ - pbuffer++; - transfer_size -= 4U; - } - } - else - { - hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - - /* Check Errors Flags */ - if (HAL_PSSI_GET_FLAG(hpssi, PSSI_FLAG_OVR_RIS) != 0U) - { - HAL_PSSI_CLEAR_FLAG(hpssi, PSSI_FLAG_OVR_RIS); - HAL_PSSI_DISABLE(hpssi); - hpssi->ErrorCode = HAL_PSSI_ERROR_UNDER_RUN; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receives an amount of data in blocking mode. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param pData Pointer to data buffer - * @param Size Amount of data to be received (in bytes) - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_Receive(PSSI_HandleTypeDef *hpssi, uint8_t *pData, uint32_t Size, uint32_t Timeout) -{ - uint32_t tickstart; - uint32_t transfer_size = Size; - - if (((hpssi->Init.DataWidth == HAL_PSSI_8BITS) && (hpssi->Init.BusWidth != HAL_PSSI_8LINES)) || - ((hpssi->Init.DataWidth == HAL_PSSI_16BITS) && ((Size % 2U) != 0U)) || - ((hpssi->Init.DataWidth == HAL_PSSI_32BITS) && ((Size % 4U) != 0U))) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; - return HAL_ERROR; - } - - if (hpssi->State == HAL_PSSI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hpssi); - - hpssi->State = HAL_PSSI_STATE_BUSY; - hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; - - /* Disable the selected PSSI peripheral */ - HAL_PSSI_DISABLE(hpssi); - /* Configure transfer parameters */ - MODIFY_REG(hpssi->Instance->CR, (PSSI_CR_OUTEN | PSSI_CR_CKPOL), - (PSSI_CR_OUTEN_INPUT | ((hpssi->Init.ClockPolarity == HAL_PSSI_FALLING_EDGE) ? 0U : PSSI_CR_CKPOL))); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* DMA Disable */ - hpssi->Instance->CR &= PSSI_CR_DMA_DISABLE; -#endif /*HAL_DMA_MODULE_ENABLED*/ - - /* Enable the selected PSSI peripheral */ - HAL_PSSI_ENABLE(hpssi); - if (hpssi->Init.DataWidth == HAL_PSSI_8BITS) - { - uint8_t *pbuffer = pData; - - while (transfer_size > 0U) - { - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - /* Wait until Fifo is ready to receive one byte flag is set */ - if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT1B, RESET, Timeout, tickstart) != HAL_OK) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - /* Read data from DR */ - *pbuffer = *(__IO uint8_t *)(&hpssi->Instance->DR); - pbuffer++; - transfer_size--; - } - } - else if (hpssi->Init.DataWidth == HAL_PSSI_16BITS) - { - uint16_t *pbuffer = (uint16_t *)pData; - __IO uint16_t *dr = (__IO uint16_t *)(&hpssi->Instance->DR); - - while (transfer_size > 0U) - { - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - /* Wait until Fifo is ready to receive four bytes flag is set */ - if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - - /* Read data from DR */ - *pbuffer = *dr; - pbuffer++; - transfer_size -= 2U; - } - } - else if (hpssi->Init.DataWidth == HAL_PSSI_32BITS) - { - uint32_t *pbuffer = (uint32_t *)pData; - - while (transfer_size > 0U) - { - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - /* Wait until Fifo is ready to receive four bytes flag is set */ - if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) - { - hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - - /* Read data from DR */ - *pbuffer = *(__IO uint32_t *)(&hpssi->Instance->DR); - pbuffer++; - transfer_size -= 4U; - } - } - else - { - hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - /* Check Errors Flags */ - - if (HAL_PSSI_GET_FLAG(hpssi, PSSI_FLAG_OVR_RIS) != 0U) - { - HAL_PSSI_CLEAR_FLAG(hpssi, PSSI_FLAG_OVR_RIS); - hpssi->ErrorCode = HAL_PSSI_ERROR_OVER_RUN; - __HAL_UNLOCK(hpssi); - return HAL_ERROR; - } - - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Transmit an amount of data in non-blocking mode with DMA - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent (in bytes) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_Transmit_DMA(PSSI_HandleTypeDef *hpssi, uint32_t *pData, uint32_t Size) -{ - HAL_StatusTypeDef dmaxferstatus; - - if (hpssi->State == HAL_PSSI_STATE_READY) - { - - /* Process Locked */ - __HAL_LOCK(hpssi); - - hpssi->State = HAL_PSSI_STATE_BUSY_TX; - hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; - - /* Disable the selected PSSI peripheral */ - HAL_PSSI_DISABLE(hpssi); - - /* Prepare transfer parameters */ - hpssi->pBuffPtr = pData; - hpssi->XferCount = Size; - - if (hpssi->XferCount > PSSI_MAX_NBYTE_SIZE) - { - hpssi->XferSize = PSSI_MAX_NBYTE_SIZE; - } - else - { - hpssi->XferSize = hpssi->XferCount; - } - - if (hpssi->XferSize > 0U) - { - if (hpssi->hdmatx != NULL) - { - - /* Configure BusWidth */ - if (hpssi->hdmatx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_BYTE) - { - MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, - PSSI_CR_DMA_ENABLE | PSSI_CR_OUTEN_OUTPUT | - ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? 0U : PSSI_CR_CKPOL)); - } - else - { - MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, - PSSI_CR_DMA_ENABLE | hpssi->Init.BusWidth | PSSI_CR_OUTEN_OUTPUT | - ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? 0U : PSSI_CR_CKPOL)); - } - - /* Set the PSSI DMA transfer complete callback */ - hpssi->hdmatx->XferCpltCallback = PSSI_DMATransmitCplt; - - /* Set the DMA error callback */ - hpssi->hdmatx->XferErrorCallback = PSSI_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hpssi->hdmatx->XferHalfCpltCallback = NULL; - hpssi->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA */ - if ((hpssi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hpssi->hdmatx->LinkedListQueue != NULL) - { - /* Enable the DMA channel */ - /* Set DMA data size */ - hpssi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hpssi->XferSize; - /* Set DMA source address */ - hpssi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; - /* Set DMA destination address */ - hpssi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&hpssi->Instance->DR; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hpssi->hdmatx); - } - else - { - /* Return error status */ - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hpssi->hdmatx, (uint32_t)pData, (uint32_t)&hpssi->Instance->DR, - hpssi->XferSize); - } - } - else - { - /* Update PSSI state */ - hpssi->State = HAL_PSSI_STATE_READY; - - /* Update PSSI error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Update XferCount value */ - hpssi->XferCount -= hpssi->XferSize; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Note : The PSSI interrupts must be enabled after unlocking current process - to avoid the risk of PSSI interrupt handle execution before current - process unlock */ - /* Enable ERR interrupt */ - HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - /* Enable DMA Request */ - hpssi->Instance->CR |= PSSI_CR_DMA_ENABLE; - /* Enable the selected PSSI peripheral */ - HAL_PSSI_ENABLE(hpssi); - } - else - { - /* Update PSSI state */ - hpssi->State = HAL_PSSI_STATE_READY; - - /* Update PSSI error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_ERROR; - } - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Note : The PSSI interrupts must be enabled after unlocking current process - to avoid the risk of PSSI interrupt handle execution before current - process unlock */ - /* Enable ERRinterrupt */ - /* possible to enable all of these */ - - HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - } - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in non-blocking mode with DMA - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param pData Pointer to data buffer - * @param Size Amount of data to be received (in bytes) - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_Receive_DMA(PSSI_HandleTypeDef *hpssi, uint32_t *pData, uint32_t Size) -{ - - HAL_StatusTypeDef dmaxferstatus; - - if (hpssi->State == HAL_PSSI_STATE_READY) - { - - /* Disable the selected PSSI peripheral */ - HAL_PSSI_DISABLE(hpssi); - /* Process Locked */ - __HAL_LOCK(hpssi); - - hpssi->State = HAL_PSSI_STATE_BUSY_RX; - hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; - - /* Prepare transfer parameters */ - hpssi->pBuffPtr = pData; - hpssi->XferCount = Size; - - if (hpssi->XferCount > PSSI_MAX_NBYTE_SIZE) - { - hpssi->XferSize = PSSI_MAX_NBYTE_SIZE; - } - else - { - hpssi->XferSize = hpssi->XferCount; - } - - if (hpssi->XferSize > 0U) - { - if (hpssi->hdmarx != NULL) - { - /* Configure BusWidth */ - if (hpssi->hdmarx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_BYTE) - { - MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, PSSI_CR_DMA_ENABLE | - ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? PSSI_CR_CKPOL : 0U)); - } - else - { - MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, - PSSI_CR_DMA_ENABLE | hpssi->Init.BusWidth | - ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? PSSI_CR_CKPOL : 0U)); - } - - /* Set the PSSI DMA transfer complete callback */ - hpssi->hdmarx->XferCpltCallback = PSSI_DMAReceiveCplt; - - /* Set the DMA error callback */ - hpssi->hdmarx->XferErrorCallback = PSSI_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hpssi->hdmarx->XferHalfCpltCallback = NULL; - hpssi->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA */ - if ((hpssi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hpssi->hdmarx->LinkedListQueue != NULL) - { - /* Enable the DMA channel */ - /* Set DMA data size */ - hpssi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hpssi->XferSize; - /* Set DMA source address */ - hpssi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)&hpssi->Instance->DR; - /* Set DMA destination address */ - hpssi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - dmaxferstatus = HAL_DMAEx_List_Start_IT(hpssi->hdmarx); - } - else - { - /* Return error status */ - return HAL_ERROR; - } - } - else - { - dmaxferstatus = HAL_DMA_Start_IT(hpssi->hdmarx, (uint32_t)&hpssi->Instance->DR, (uint32_t)pData, - hpssi->XferSize); - } - } - else - { - /* Update PSSI state */ - hpssi->State = HAL_PSSI_STATE_READY; - - /* Update PSSI error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_ERROR; - } - - if (dmaxferstatus == HAL_OK) - { - /* Update XferCount value */ - hpssi->XferCount -= hpssi->XferSize; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Note : The PSSI interrupts must be enabled after unlocking current process - to avoid the risk of PSSI interrupt handle execution before current - process unlock */ - /* Enable ERR interrupt */ - HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - /* Enable DMA Request */ - hpssi->Instance->CR |= PSSI_CR_DMA_ENABLE; - /* Enable the selected PSSI peripheral */ - HAL_PSSI_ENABLE(hpssi); - } - else - { - /* Update PSSI state */ - hpssi->State = HAL_PSSI_STATE_READY; - - /* Update PSSI error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_ERROR; - } - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Enable ERR,interrupt */ - HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Abort a DMA process communication with Interrupt. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_Abort_DMA(PSSI_HandleTypeDef *hpssi) -{ - /* Process Locked */ - __HAL_LOCK(hpssi); - - /* Disable Interrupts */ - HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - /* Set State at HAL_PSSI_STATE_ABORT */ - hpssi->State = HAL_PSSI_STATE_ABORT; - - /* Abort DMA TX transfer if any */ - if ((hpssi->Instance->CR & PSSI_CR_DMAEN) == PSSI_CR_DMAEN) - { - if (hpssi->State == HAL_PSSI_STATE_BUSY_TX) - { - hpssi->Instance->CR &= ~PSSI_CR_DMAEN; - - if (hpssi->hdmatx != NULL) - { - /* Set the PSSI DMA Abort callback : - will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ - hpssi->hdmatx->XferAbortCallback = PSSI_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hpssi->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hpssi->hdmatx->XferAbortCallback(hpssi->hdmatx); - } - } - } - /* Abort DMA RX transfer if any */ - else if (hpssi->State == HAL_PSSI_STATE_BUSY_RX) - { - hpssi->Instance->CR &= ~PSSI_CR_DMAEN; - - if (hpssi->hdmarx != NULL) - { - /* Set the PSSI DMA Abort callback : - will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ - hpssi->hdmarx->XferAbortCallback = PSSI_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hpssi->hdmarx) != HAL_OK) - { - /* Call Directly hpssi->hdma->XferAbortCallback function in case of error */ - hpssi->hdmarx->XferAbortCallback(hpssi->hdmarx); - } - } - } - else - { - - /* Call the error callback */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->ErrorCallback(hpssi); -#else - HAL_PSSI_ErrorCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Note : The PSSI interrupts must be enabled after unlocking current process - to avoid the risk of PSSI interrupt handle execution before current - process unlock */ - HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - return HAL_OK; -} -#endif /*HAL_DMA_MODULE_ENABLED*/ - -/** - * @} - */ - -/** @addtogroup PSSI_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks - * @{ - */ - -/** - * @brief This function handles PSSI event interrupt request. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -void HAL_PSSI_IRQHandler(PSSI_HandleTypeDef *hpssi) -{ - /* Overrun/ Underrun Errors */ - if (HAL_PSSI_GET_FLAG(hpssi, PSSI_FLAG_OVR_MIS) != 0U) - { - /* Reset handle parameters */ - hpssi->XferCount = 0U; - - /* Disable all interrupts */ - HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort DMA TX transfer if any */ - if ((hpssi->Instance->CR & PSSI_CR_DMAEN) == PSSI_CR_DMAEN) - { - if (hpssi->State == HAL_PSSI_STATE_BUSY_TX) - { - /* Set new error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_UNDER_RUN; - - hpssi->Instance->CR &= ~PSSI_CR_DMAEN; - - if (hpssi->hdmatx != NULL) - { - /* Set the PSSI DMA Abort callback : - will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ - hpssi->hdmatx->XferAbortCallback = PSSI_DMAAbort; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hpssi->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hpssi->hdmatx->XferAbortCallback(hpssi->hdmatx); - } - } - } - /* Abort DMA RX transfer if any */ - else if (hpssi->State == HAL_PSSI_STATE_BUSY_RX) - { - /* Set new error code */ - hpssi->ErrorCode |= HAL_PSSI_ERROR_OVER_RUN; - - hpssi->Instance->CR &= ~PSSI_CR_DMAEN; - - if (hpssi->hdmarx != NULL) - { - /* Set the PSSI DMA Abort callback : - will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ - hpssi->hdmarx->XferAbortCallback = PSSI_DMAAbort; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hpssi->hdmarx) != HAL_OK) - { - /* Call Directly hpssi->hdma->XferAbortCallback function in case of error */ - hpssi->hdmarx->XferAbortCallback(hpssi->hdmarx); - } - } - } - else - { -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - /* Call the corresponding callback to inform upper layer of the error */ - hpssi->ErrorCallback(hpssi); -#else - HAL_PSSI_ErrorCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } - } -#endif /*HAL_DMA_MODULE_ENABLED*/ - - /* If state is an abort treatment on going, don't change state */ - if (hpssi->State == HAL_PSSI_STATE_ABORT) - { - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - /* Call the corresponding callback to inform upper layer of End of Transfer */ - hpssi->AbortCpltCallback(hpssi); -#else - HAL_PSSI_AbortCpltCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } - else - { - /* Set HAL_PSSI_STATE_READY */ - hpssi->State = HAL_PSSI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - /* Call the corresponding callback to inform upper layer of End of Transfer */ - hpssi->ErrorCallback(hpssi); -#else - HAL_PSSI_ErrorCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Tx Transfer complete callback. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -__weak void HAL_PSSI_TxCpltCallback(PSSI_HandleTypeDef *hpssi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpssi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PSSI_TxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Rx Transfer complete callback. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -__weak void HAL_PSSI_RxCpltCallback(PSSI_HandleTypeDef *hpssi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpssi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PSSI_RxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief PSSI error callback. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -__weak void HAL_PSSI_ErrorCallback(PSSI_HandleTypeDef *hpssi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpssi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PSSI_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief PSSI abort callback. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval None - */ -__weak void HAL_PSSI_AbortCpltCallback(PSSI_HandleTypeDef *hpssi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpssi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PSSI_AbortCpltCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup PSSI_Exported_Functions_Group3 Peripheral State and Error functions - * @brief Peripheral State, Mode and Error functions - * -@verbatim - =============================================================================== - ##### Peripheral State, Mode and Error functions ##### - =============================================================================== - [..] - This subsection permit to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the PSSI handle state. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval HAL state - */ -HAL_PSSI_StateTypeDef HAL_PSSI_GetState(const PSSI_HandleTypeDef *hpssi) -{ - /* Return PSSI handle state */ - return hpssi->State; -} - -/** - * @brief Return the PSSI error code. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @retval PSSI Error Code - */ -uint32_t HAL_PSSI_GetError(const PSSI_HandleTypeDef *hpssi) -{ - return hpssi->ErrorCode; -} - -/** - * @} - */ - -/** @defgroup PSSI_Exported_Functions_Group4 Clock Source Selection function - * @brief Clock Source Selection function to pick between an internal or - * external clock. - * -@verbatim - =============================================================================== - ##### Clock Source Selection function ##### - =============================================================================== - [..] This subsection provides a function allowing to: - (+) Configure Clock source - (++) The clock source could be external (default) or internal (the clock - is generated by the device RCC). - (++) The AHB clock frequency must be at least 2.5 times higher than the - PSSI_PDCK frequency - -@endverbatim - * @{ - */ - -/** - * @brief Configure PSSI Clock Source. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI peripheral. - * @param ClockSource New Clock Configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_PSSI_ClockConfig(PSSI_HandleTypeDef *hpssi, uint32_t ClockSource) -{ - /* Check the parameter */ - assert_param(IS_PSSI_CLOCK_SOURCE(ClockSource)); - - if (hpssi->State == HAL_PSSI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hpssi); - - HAL_PSSI_DISABLE(hpssi); - - /* Set CKSRC to ClockSource */ - MODIFY_REG(hpssi->Instance->CR, PSSI_CR_CKSRC, ClockSource); - - HAL_PSSI_ENABLE(hpssi); - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup PSSI_Private_Functions - * @{ - */ - -/** - * @brief PSSI Errors process. - * @param hpssi PSSI handle. - * @param ErrorCode Error code to handle. - * @retval None - */ -static void PSSI_Error(PSSI_HandleTypeDef *hpssi, uint32_t ErrorCode) -{ - /* Reset handle parameters */ - hpssi->XferCount = 0U; - - /* Set new error code */ - hpssi->ErrorCode |= ErrorCode; - - /* Disable all interrupts */ - HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort DMA TX transfer if any */ - if ((hpssi->Instance->CR & PSSI_CR_DMAEN) == PSSI_CR_DMAEN) - { - if (hpssi->State == HAL_PSSI_STATE_BUSY_TX) - { - hpssi->Instance->CR &= ~PSSI_CR_DMAEN; - - if (hpssi->hdmatx != NULL) - { - /* Set the PSSI DMA Abort callback : - will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ - hpssi->hdmatx->XferAbortCallback = PSSI_DMAAbort; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hpssi->hdmatx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hpssi->hdmatx->XferAbortCallback(hpssi->hdmatx); - } - } - } - /* Abort DMA RX transfer if any */ - else if (hpssi->State == HAL_PSSI_STATE_BUSY_RX) - { - hpssi->Instance->CR &= ~PSSI_CR_DMAEN; - - if (hpssi->hdmarx != NULL) - { - /* Set the PSSI DMA Abort callback : - will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ - hpssi->hdmarx->XferAbortCallback = PSSI_DMAAbort; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hpssi->hdmarx) != HAL_OK) - { - /* Call Directly hpssi->hdma->XferAbortCallback function in case of error */ - hpssi->hdmarx->XferAbortCallback(hpssi->hdmarx); - } - } - } - else - { - /*Nothing to do*/ - } - } -#endif /*HAL_DMA_MODULE_ENABLED*/ - - /* If state is an abort treatment on going, don't change state */ - if (hpssi->State == HAL_PSSI_STATE_ABORT) - { - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->AbortCpltCallback(hpssi); -#else - HAL_PSSI_AbortCpltCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } - else - { - /* Set HAL_PSSI_STATE_READY */ - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->ErrorCallback(hpssi); -#else - HAL_PSSI_ErrorCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief DMA PSSI slave transmit process complete callback. - * @param hdma DMA handle - * @retval None - */ -void PSSI_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - uint32_t tmperror; - - /* Disable Interrupts */ - HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - /* Store current volatile hpssi->ErrorCode, misra rule */ - tmperror = hpssi->ErrorCode; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if ((hpssi->State == HAL_PSSI_STATE_ABORT) || (tmperror != HAL_PSSI_ERROR_NONE)) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - PSSI_Error(hpssi, hpssi->ErrorCode); - } - /* hpssi->State == HAL_PSSI_STATE_BUSY_TX */ - else - { - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->TxCpltCallback(hpssi); -#else - HAL_PSSI_TxCpltCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DMA PSSI master receive process complete callback. - * @param hdma DMA handle - * @retval None - */ -void PSSI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - uint32_t tmperror; - - /* Disable Interrupts */ - HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - /* Store current volatile hpssi->ErrorCode, misra rule */ - tmperror = hpssi->ErrorCode; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if ((hpssi->State == HAL_PSSI_STATE_ABORT) || (tmperror != HAL_PSSI_ERROR_NONE)) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - PSSI_Error(hpssi, hpssi->ErrorCode); - } - /* hpssi->State == HAL_PSSI_STATE_BUSY_RX */ - else - { - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->RxCpltCallback(hpssi); -#else - HAL_PSSI_RxCpltCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DMA PSSI communication abort callback - * (To be called at end of DMA Abort procedure). - * @param hdma DMA handle. - * @retval None - */ -void PSSI_DMAAbort(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - /* Reset AbortCpltCallback */ - hpssi->hdmatx->XferAbortCallback = NULL; - hpssi->hdmarx->XferAbortCallback = NULL; - - /* Check if come from abort from user */ - if (hpssi->State == HAL_PSSI_STATE_ABORT) - { - hpssi->State = HAL_PSSI_STATE_READY; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->AbortCpltCallback(hpssi); -#else - HAL_PSSI_AbortCpltCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } - else - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->ErrorCallback(hpssi); -#else - HAL_PSSI_ErrorCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } -} -#endif /*HAL_DMA_MODULE_ENABLED*/ - -/** - * @brief This function handles PSSI Communication Timeout. - * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains - * the configuration information for the specified PSSI. - * @param Flag Specifies the PSSI flag to check. - * @param Status The new Flag status (SET or RESET). - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef PSSI_WaitOnStatusUntilTimeout(PSSI_HandleTypeDef *hpssi, uint32_t Flag, FlagStatus Status, - uint32_t Timeout, uint32_t Tickstart) -{ - while ((HAL_PSSI_GET_STATUS(hpssi, Flag) & Flag) == (uint32_t)Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - hpssi->ErrorCode |= HAL_PSSI_ERROR_TIMEOUT; - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -void PSSI_DMAError(DMA_HandleTypeDef *hdma) -{ - /* Derogation MISRAC2012-Rule-11.5 */ - PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); - - uint32_t tmperror; - - /* Disable the selected PSSI peripheral */ - HAL_PSSI_DISABLE(hpssi); - - /* Disable Interrupts */ - HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); - - /* Store current volatile hpssi->ErrorCode, misra rule */ - tmperror = hpssi->ErrorCode; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if ((hpssi->State == HAL_PSSI_STATE_ABORT) || (tmperror != HAL_PSSI_ERROR_NONE)) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - PSSI_Error(hpssi, hpssi->ErrorCode); - } - else - { - hpssi->State = HAL_PSSI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hpssi); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) - hpssi->ErrorCallback(hpssi); -#else - HAL_PSSI_ErrorCallback(hpssi); -#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ - } -} -#endif /*HAL_DMA_MODULE_ENABLED*/ - - -/** - * @} - */ -#endif /* PSSI */ -#endif /* HAL_PSSI_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_pssi.c + * @author MCD Application Team + * @brief PSSI HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Parallel Synchronous Slave Interface (PSSI) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The PSSI HAL driver can be used as follows: + + (#) Declare a PSSI_HandleTypeDef handle structure, for example: + PSSI_HandleTypeDef hpssi; + + (#) Initialize the PSSI low level resources by implementing the @ref HAL_PSSI_MspInit() API: + (##) Enable the PSSIx interface clock + (##) PSSI pins configuration + (+++) Enable the clock for the PSSI GPIOs + (+++) Configure PSSI pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the PSSIx interrupt priority + (+++) Enable the NVIC PSSI IRQ Channel + (##) DMA Configuration if you need to use DMA process + (+++) Declare DMA_HandleTypeDef handles structure for the transmit and receive + (+++) Enable the DMAx interface clock + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx and Rx + (+++) Associate the initialized DMA handle to the hpssi DMA Tx and Rx handle + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on + the DMA Tx and Rx + + (#) Configure the Communication Bus Width, Control Signals, Input Polarity and Output Polarity + in the hpssi Init structure. + + (#) Initialize the PSSI registers by calling the @ref HAL_PSSI_Init(), configure also the low level Hardware + (GPIO, CLOCK, NVIC...etc) by calling the customized @ref HAL_PSSI_MspInit(&hpssi) API. + + (#) Configure the PSSI clock as internal or external by calling the @ref HAL_PSSI_ClockConfig(). + + (#) For PSSI IO operations, two operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Transmit an amount of data by byte in blocking mode using @ref HAL_PSSI_Transmit() + (+) Receive an amount of data by byte in blocking mode using @ref HAL_PSSI_Receive() + + *** DMA mode IO operation *** + ============================== + [..] + (+) Transmit an amount of data in non-blocking mode (DMA) using + @ref HAL_PSSI_Transmit_DMA() + (+) At transmission end of transfer, @ref HAL_PSSI_TxCpltCallback() is executed and user can + add his own code by customization of function pointer @ref HAL_PSSI_TxCpltCallback() + (+) Receive an amount of data in non-blocking mode (DMA) using + @ref HAL_PSSI_Receive_DMA() + (+) At reception end of transfer, @ref HAL_PSSI_RxCpltCallback() is executed and user can + add his own code by customization of function pointer @ref HAL_PSSI_RxCpltCallback() + (+) In case of transfer Error, @ref HAL_PSSI_ErrorCallback() function is executed and user can + add his own code by customization of function pointer @ref HAL_PSSI_ErrorCallback() + (+) Abort a PSSI process communication with Interrupt using @ref HAL_PSSI_Abort_IT() + (+) End of abort process, @ref HAL_PSSI_AbortCpltCallback() is executed and user can + add his own code by customization of function pointer @ref HAL_PSSI_AbortCpltCallback() + + *** PSSI HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in PSSI HAL driver. + + (+) @ref HAL_PSSI_ENABLE : Enable the PSSI peripheral + (+) @ref HAL_PSSI_DISABLE : Disable the PSSI peripheral + (+) @ref HAL_PSSI_GET_FLAG : Check whether the specified PSSI flag is set or not + (+) @ref HAL_PSSI_CLEAR_FLAG : Clear the specified PSSI pending flag + (+) @ref HAL_PSSI_ENABLE_IT : Enable the specified PSSI interrupt + (+) @ref HAL_PSSI_DISABLE_IT : Disable the specified PSSI interrupt + + *** Callback registration *** + ============================================= + Use Functions @ref HAL_PSSI_RegisterCallback() or @ref HAL_PSSI_RegisterAddrCallback() + to register an interrupt callback. + + Function @ref HAL_PSSI_RegisterCallback() allows to register following callbacks: + (+) TxCpltCallback : callback for transmission end of transfer. + (+) RxCpltCallback : callback for reception end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + + Use function @ref HAL_PSSI_UnRegisterCallback to reset a callback to the default + weak function. + @ref HAL_PSSI_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxCpltCallback : callback for transmission end of transfer. + (+) RxCpltCallback : callback for reception end of transfer. + (+) ErrorCallback : callback for error detection. + (+) AbortCpltCallback : callback for abort completion process. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + + + By default, after the @ref HAL_PSSI_Init() and when the state is @ref HAL_PSSI_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples @ref HAL_PSSI_TxCpltCallback(), @ref HAL_PSSI_RxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the @ref HAL_PSSI_Init()/ @ref HAL_PSSI_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the @ref HAL_PSSI_Init()/ @ref HAL_PSSI_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + + Callbacks can be registered/unregistered in @ref HAL_PSSI_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in @ref HAL_PSSI_STATE_READY or @ref HAL_PSSI_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using @ref HAL_PSSI_RegisterCallback() before calling @ref HAL_PSSI_DeInit() + or @ref HAL_PSSI_Init() function. + + + [..] + (@) You can refer to the PSSI HAL driver header file for more useful macros + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup PSSI PSSI + * @brief PSSI HAL module driver + * @{ + */ + +#ifdef HAL_PSSI_MODULE_ENABLED +#if defined(PSSI) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup PSSI_Private_Define PSSI Private Define + * @{ + */ + + + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/** @defgroup PSSI_Private_Functions PSSI Private Functions + * @{ + */ +/* Private functions to handle DMA transfer */ +#if defined(HAL_DMA_MODULE_ENABLED) +void PSSI_DMATransmitCplt(DMA_HandleTypeDef *hdma); +void PSSI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +void PSSI_DMAError(DMA_HandleTypeDef *hdma); +void PSSI_DMAAbort(DMA_HandleTypeDef *hdma); +#endif /*HAL_DMA_MODULE_ENABLED*/ + +/* Private functions to handle IT transfer */ +static void PSSI_Error(PSSI_HandleTypeDef *hpssi, uint32_t ErrorCode); + + +/* Private functions for PSSI transfer IRQ handler */ + + +/* Private functions to handle flags during polling transfer */ +static HAL_StatusTypeDef PSSI_WaitOnStatusUntilTimeout(PSSI_HandleTypeDef *hpssi, uint32_t Flag, FlagStatus Status, + uint32_t Timeout, uint32_t Tickstart); + +/* Private functions to centralize the enable/disable of Interrupts */ + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PSSI_Exported_Functions PSSI Exported Functions + * @{ + */ + +/** @defgroup PSSI_Exported_Functions_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 + deinitialize the PSSIx peripheral: + + (+) User must implement HAL_PSSI_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function HAL_PSSI_Init() to configure the selected device with + the selected configuration: + (++) Data Width + (++) Control Signals + (++) Input Clock polarity + (++) Output Clock polarity + + (+) Call the function HAL_PSSI_DeInit() to restore the default configuration + of the selected PSSIx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the PSSI according to the specified parameters + * in the PSSI_InitTypeDef and initialize the associated handle. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_Init(PSSI_HandleTypeDef *hpssi) +{ + /* Check the PSSI handle allocation */ + if (hpssi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_PSSI_ALL_INSTANCE(hpssi->Instance)); + assert_param(IS_PSSI_CONTROL_SIGNAL(hpssi->Init.ControlSignal)); + assert_param(IS_PSSI_BUSWIDTH(hpssi->Init.BusWidth)); + assert_param(IS_PSSI_CLOCK_POLARITY(hpssi->Init.ClockPolarity)); + assert_param(IS_PSSI_DE_POLARITY(hpssi->Init.DataEnablePolarity)); + assert_param(IS_PSSI_RDY_POLARITY(hpssi->Init.ReadyPolarity)); + + if (hpssi->State == HAL_PSSI_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hpssi->Lock = HAL_UNLOCKED; + +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + /* Init the PSSI Callback settings */ + hpssi->TxCpltCallback = HAL_PSSI_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hpssi->RxCpltCallback = HAL_PSSI_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hpssi->ErrorCallback = HAL_PSSI_ErrorCallback; /* Legacy weak ErrorCallback */ + hpssi->AbortCpltCallback = HAL_PSSI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + + if (hpssi->MspInitCallback == NULL) + { + hpssi->MspInitCallback = HAL_PSSI_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + hpssi->MspInitCallback(hpssi); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_PSSI_MspInit(hpssi); +#endif /*USE_HAL_PSSI_REGISTER_CALLBACKS*/ + } + + hpssi->State = HAL_PSSI_STATE_BUSY; + + /* Disable the selected PSSI peripheral */ + HAL_PSSI_DISABLE(hpssi); + + /*---------------------------- PSSIx CR Configuration ----------------------*/ + /* Configure PSSIx: Control Signal and Bus Width*/ + + MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DERDYCFG | PSSI_CR_EDM | PSSI_CR_DEPOL | PSSI_CR_RDYPOL, + hpssi->Init.ControlSignal | hpssi->Init.DataEnablePolarity | + hpssi->Init.ReadyPolarity | hpssi->Init.BusWidth); + + hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; + hpssi->State = HAL_PSSI_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitialize the PSSI peripheral. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_DeInit(PSSI_HandleTypeDef *hpssi) +{ + /* Check the PSSI handle allocation */ + if (hpssi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_PSSI_ALL_INSTANCE(hpssi->Instance)); + + hpssi->State = HAL_PSSI_STATE_BUSY; + + /* Disable the PSSI Peripheral Clock */ + HAL_PSSI_DISABLE(hpssi); + +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + if (hpssi->MspDeInitCallback == NULL) + { + hpssi->MspDeInitCallback = HAL_PSSI_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hpssi->MspDeInitCallback(hpssi); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_PSSI_MspDeInit(hpssi); +#endif /*USE_HAL_PSSI_REGISTER_CALLBACKS*/ + + hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; + hpssi->State = HAL_PSSI_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hpssi); + + return HAL_OK; +} + +/** + * @brief Initialize the PSSI MSP. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +__weak void HAL_PSSI_MspInit(PSSI_HandleTypeDef *hpssi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpssi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PSSI_MspInit can be implemented in the user file + */ +} + +/** + * @brief De-Initialize the PSSI MSP. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +__weak void HAL_PSSI_MspDeInit(PSSI_HandleTypeDef *hpssi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpssi); + + /* NOTE : This function should not be modified; when the callback is needed, + the HAL_PSSI_MspDeInit can be implemented in the user file + */ +} + +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User PSSI Callback + * To be used instead of the weak predefined callback + * @note The HAL_PSSI_RegisterCallback() may be called before HAL_PSSI_Init() in + * HAL_PSSI_STATE_RESET to register callbacks for HAL_PSSI_MSPINIT_CB_ID + * and HAL_PSSI_MSPDEINIT_CB_ID. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_PSSI_TX_COMPLETE_CB_ID Tx Transfer completed callback ID + * @arg @ref HAL_PSSI_RX_COMPLETE_CB_ID Rx Transfer completed callback ID + * @arg @ref HAL_PSSI_ERROR_CB_ID Error callback ID + * @arg @ref HAL_PSSI_ABORT_CB_ID Abort callback ID + * @arg @ref HAL_PSSI_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_PSSI_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_RegisterCallback(PSSI_HandleTypeDef *hpssi, HAL_PSSI_CallbackIDTypeDef CallbackID, + pPSSI_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (HAL_PSSI_STATE_READY == hpssi->State) + { + switch (CallbackID) + { + case HAL_PSSI_TX_COMPLETE_CB_ID : + hpssi->TxCpltCallback = pCallback; + break; + + case HAL_PSSI_RX_COMPLETE_CB_ID : + hpssi->RxCpltCallback = pCallback; + break; + + case HAL_PSSI_ERROR_CB_ID : + hpssi->ErrorCallback = pCallback; + break; + + case HAL_PSSI_ABORT_CB_ID : + hpssi->AbortCpltCallback = pCallback; + break; + + case HAL_PSSI_MSPINIT_CB_ID : + hpssi->MspInitCallback = pCallback; + break; + + case HAL_PSSI_MSPDEINIT_CB_ID : + hpssi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_PSSI_STATE_RESET == hpssi->State) + { + switch (CallbackID) + { + case HAL_PSSI_MSPINIT_CB_ID : + hpssi->MspInitCallback = pCallback; + break; + + case HAL_PSSI_MSPDEINIT_CB_ID : + hpssi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an PSSI Callback + * PSSI callback is redirected to the weak predefined callback + * @note The HAL_PSSI_UnRegisterCallback() may be called before HAL_PSSI_Init() in + * HAL_PSSI_STATE_RESET to un-register callbacks for HAL_PSSI_MSPINIT_CB_ID + * and HAL_PSSI_MSPDEINIT_CB_ID. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_PSSI_TX_COMPLETE_CB_ID Tx Transfer completed callback ID + * @arg @ref HAL_PSSI_RX_COMPLETE_CB_ID Rx Transfer completed callback ID + * @arg @ref HAL_PSSI_ERROR_CB_ID Error callback ID + * @arg @ref HAL_PSSI_ABORT_CB_ID Abort callback ID + * @arg @ref HAL_PSSI_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_PSSI_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_UnRegisterCallback(PSSI_HandleTypeDef *hpssi, HAL_PSSI_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_PSSI_STATE_READY == hpssi->State) + { + switch (CallbackID) + { + case HAL_PSSI_TX_COMPLETE_CB_ID : + hpssi->TxCpltCallback = HAL_PSSI_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_PSSI_RX_COMPLETE_CB_ID : + hpssi->RxCpltCallback = HAL_PSSI_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_PSSI_ERROR_CB_ID : + hpssi->ErrorCallback = HAL_PSSI_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_PSSI_ABORT_CB_ID : + hpssi->AbortCpltCallback = HAL_PSSI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_PSSI_MSPINIT_CB_ID : + hpssi->MspInitCallback = HAL_PSSI_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_PSSI_MSPDEINIT_CB_ID : + hpssi->MspDeInitCallback = HAL_PSSI_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_PSSI_STATE_RESET == hpssi->State) + { + switch (CallbackID) + { + case HAL_PSSI_MSPINIT_CB_ID : + hpssi->MspInitCallback = HAL_PSSI_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_PSSI_MSPDEINIT_CB_ID : + hpssi->MspDeInitCallback = HAL_PSSI_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup PSSI_Exported_Functions_Group2 Input and Output operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the PSSI data + transfers. + + (#) There are two modes 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 DMA. + These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated the DMA IRQ . + + (#) Blocking mode functions are : + (++) HAL_PSSI_Transmit() + (++) HAL_PSSI_Receive() + + (#) No-Blocking mode functions with DMA are : + (++) HAL_PSSI_Transmit_DMA() + (++) HAL_PSSI_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) HAL_PSSI_TxCpltCallback() + (++) HAL_PSSI_RxCpltCallback() + (++) HAL_PSSI_ErrorCallback() + (++) HAL_PSSI_AbortCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmits in master mode an amount of data in blocking mode. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent (in bytes) + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_Transmit(PSSI_HandleTypeDef *hpssi, uint8_t *pData, uint32_t Size, uint32_t Timeout) +{ + uint32_t tickstart; + uint32_t transfer_size = Size; + + if (((hpssi->Init.DataWidth == HAL_PSSI_8BITS) && (hpssi->Init.BusWidth != HAL_PSSI_8LINES)) || + ((hpssi->Init.DataWidth == HAL_PSSI_16BITS) && ((Size % 2U) != 0U)) || + ((hpssi->Init.DataWidth == HAL_PSSI_32BITS) && ((Size % 4U) != 0U))) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; + return HAL_ERROR; + } + if (hpssi->State == HAL_PSSI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hpssi); + + hpssi->State = HAL_PSSI_STATE_BUSY; + hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; + + /* Disable the selected PSSI peripheral */ + HAL_PSSI_DISABLE(hpssi); + + /* Configure transfer parameters */ + MODIFY_REG(hpssi->Instance->CR, (PSSI_CR_OUTEN | PSSI_CR_CKPOL), + (PSSI_CR_OUTEN_OUTPUT | ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? 0U : PSSI_CR_CKPOL))); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* DMA Disable */ + hpssi->Instance->CR &= PSSI_CR_DMA_DISABLE; +#endif /*HAL_DMA_MODULE_ENABLED*/ + + /* Enable the selected PSSI peripheral */ + HAL_PSSI_ENABLE(hpssi); + + if (hpssi->Init.DataWidth == HAL_PSSI_8BITS) + { + uint8_t *pbuffer = pData; + while (transfer_size > 0U) + { + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + /* Wait until Fifo is ready to transfer one byte flag is set */ + if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT1B, RESET, Timeout, tickstart) != HAL_OK) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + /* Write data to DR */ + *(__IO uint8_t *)(&hpssi->Instance->DR) = *(uint8_t *)pbuffer; + + /* Increment Buffer pointer */ + pbuffer++; + + transfer_size--; + } + } + else if (hpssi->Init.DataWidth == HAL_PSSI_16BITS) + { + uint16_t *pbuffer = (uint16_t *)pData; + __IO uint16_t *dr = (__IO uint16_t *)(&hpssi->Instance->DR); + + while (transfer_size > 0U) + { + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + /* Wait until Fifo is ready to transfer four bytes flag is set */ + if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + /* Write data to DR */ + *dr = *pbuffer; + + /* Increment Buffer pointer */ + pbuffer++; + transfer_size -= 2U; + } + } + else if (hpssi->Init.DataWidth == HAL_PSSI_32BITS) + { + uint32_t *pbuffer = (uint32_t *)pData; + while (transfer_size > 0U) + { + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + /* Wait until Fifo is ready to transfer four bytes flag is set */ + if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + /* Write data to DR */ + *(__IO uint32_t *)(&hpssi->Instance->DR) = *pbuffer; + + /* Increment Buffer pointer */ + pbuffer++; + transfer_size -= 4U; + } + } + else + { + hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + + /* Check Errors Flags */ + if (HAL_PSSI_GET_FLAG(hpssi, PSSI_FLAG_OVR_RIS) != 0U) + { + HAL_PSSI_CLEAR_FLAG(hpssi, PSSI_FLAG_OVR_RIS); + HAL_PSSI_DISABLE(hpssi); + hpssi->ErrorCode = HAL_PSSI_ERROR_UNDER_RUN; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receives an amount of data in blocking mode. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received (in bytes) + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_Receive(PSSI_HandleTypeDef *hpssi, uint8_t *pData, uint32_t Size, uint32_t Timeout) +{ + uint32_t tickstart; + uint32_t transfer_size = Size; + + if (((hpssi->Init.DataWidth == HAL_PSSI_8BITS) && (hpssi->Init.BusWidth != HAL_PSSI_8LINES)) || + ((hpssi->Init.DataWidth == HAL_PSSI_16BITS) && ((Size % 2U) != 0U)) || + ((hpssi->Init.DataWidth == HAL_PSSI_32BITS) && ((Size % 4U) != 0U))) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; + return HAL_ERROR; + } + + if (hpssi->State == HAL_PSSI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hpssi); + + hpssi->State = HAL_PSSI_STATE_BUSY; + hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; + + /* Disable the selected PSSI peripheral */ + HAL_PSSI_DISABLE(hpssi); + /* Configure transfer parameters */ + MODIFY_REG(hpssi->Instance->CR, (PSSI_CR_OUTEN | PSSI_CR_CKPOL), + (PSSI_CR_OUTEN_INPUT | ((hpssi->Init.ClockPolarity == HAL_PSSI_FALLING_EDGE) ? 0U : PSSI_CR_CKPOL))); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* DMA Disable */ + hpssi->Instance->CR &= PSSI_CR_DMA_DISABLE; +#endif /*HAL_DMA_MODULE_ENABLED*/ + + /* Enable the selected PSSI peripheral */ + HAL_PSSI_ENABLE(hpssi); + if (hpssi->Init.DataWidth == HAL_PSSI_8BITS) + { + uint8_t *pbuffer = pData; + + while (transfer_size > 0U) + { + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + /* Wait until Fifo is ready to receive one byte flag is set */ + if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT1B, RESET, Timeout, tickstart) != HAL_OK) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + /* Read data from DR */ + *pbuffer = *(__IO uint8_t *)(&hpssi->Instance->DR); + pbuffer++; + transfer_size--; + } + } + else if (hpssi->Init.DataWidth == HAL_PSSI_16BITS) + { + uint16_t *pbuffer = (uint16_t *)pData; + __IO uint16_t *dr = (__IO uint16_t *)(&hpssi->Instance->DR); + + while (transfer_size > 0U) + { + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + /* Wait until Fifo is ready to receive four bytes flag is set */ + if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + + /* Read data from DR */ + *pbuffer = *dr; + pbuffer++; + transfer_size -= 2U; + } + } + else if (hpssi->Init.DataWidth == HAL_PSSI_32BITS) + { + uint32_t *pbuffer = (uint32_t *)pData; + + while (transfer_size > 0U) + { + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + /* Wait until Fifo is ready to receive four bytes flag is set */ + if (PSSI_WaitOnStatusUntilTimeout(hpssi, PSSI_FLAG_RTT4B, RESET, Timeout, tickstart) != HAL_OK) + { + hpssi->ErrorCode = HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + + /* Read data from DR */ + *pbuffer = *(__IO uint32_t *)(&hpssi->Instance->DR); + pbuffer++; + transfer_size -= 4U; + } + } + else + { + hpssi->ErrorCode = HAL_PSSI_ERROR_NOT_SUPPORTED; + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + /* Check Errors Flags */ + + if (HAL_PSSI_GET_FLAG(hpssi, PSSI_FLAG_OVR_RIS) != 0U) + { + HAL_PSSI_CLEAR_FLAG(hpssi, PSSI_FLAG_OVR_RIS); + hpssi->ErrorCode = HAL_PSSI_ERROR_OVER_RUN; + __HAL_UNLOCK(hpssi); + return HAL_ERROR; + } + + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Transmit an amount of data in non-blocking mode with DMA + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent (in bytes) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_Transmit_DMA(PSSI_HandleTypeDef *hpssi, uint32_t *pData, uint32_t Size) +{ + HAL_StatusTypeDef dmaxferstatus; + + if (hpssi->State == HAL_PSSI_STATE_READY) + { + + /* Process Locked */ + __HAL_LOCK(hpssi); + + hpssi->State = HAL_PSSI_STATE_BUSY_TX; + hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; + + /* Disable the selected PSSI peripheral */ + HAL_PSSI_DISABLE(hpssi); + + /* Prepare transfer parameters */ + hpssi->pBuffPtr = pData; + hpssi->XferCount = Size; + + if (hpssi->XferCount > PSSI_MAX_NBYTE_SIZE) + { + hpssi->XferSize = PSSI_MAX_NBYTE_SIZE; + } + else + { + hpssi->XferSize = hpssi->XferCount; + } + + if (hpssi->XferSize > 0U) + { + if (hpssi->hdmatx != NULL) + { + + /* Configure BusWidth */ + if (hpssi->hdmatx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_BYTE) + { + MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, + PSSI_CR_DMA_ENABLE | PSSI_CR_OUTEN_OUTPUT | + ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? 0U : PSSI_CR_CKPOL)); + } + else + { + MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, + PSSI_CR_DMA_ENABLE | hpssi->Init.BusWidth | PSSI_CR_OUTEN_OUTPUT | + ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? 0U : PSSI_CR_CKPOL)); + } + + /* Set the PSSI DMA transfer complete callback */ + hpssi->hdmatx->XferCpltCallback = PSSI_DMATransmitCplt; + + /* Set the DMA error callback */ + hpssi->hdmatx->XferErrorCallback = PSSI_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hpssi->hdmatx->XferHalfCpltCallback = NULL; + hpssi->hdmatx->XferAbortCallback = NULL; + + /* Enable the DMA */ + if ((hpssi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hpssi->hdmatx->LinkedListQueue != NULL) + { + /* Enable the DMA channel */ + /* Set DMA data size */ + hpssi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hpssi->XferSize; + /* Set DMA source address */ + hpssi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; + /* Set DMA destination address */ + hpssi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&hpssi->Instance->DR; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hpssi->hdmatx); + } + else + { + /* Return error status */ + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hpssi->hdmatx, (uint32_t)pData, (uint32_t)&hpssi->Instance->DR, + hpssi->XferSize); + } + } + else + { + /* Update PSSI state */ + hpssi->State = HAL_PSSI_STATE_READY; + + /* Update PSSI error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Update XferCount value */ + hpssi->XferCount -= hpssi->XferSize; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Note : The PSSI interrupts must be enabled after unlocking current process + to avoid the risk of PSSI interrupt handle execution before current + process unlock */ + /* Enable ERR interrupt */ + HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + /* Enable DMA Request */ + hpssi->Instance->CR |= PSSI_CR_DMA_ENABLE; + /* Enable the selected PSSI peripheral */ + HAL_PSSI_ENABLE(hpssi); + } + else + { + /* Update PSSI state */ + hpssi->State = HAL_PSSI_STATE_READY; + + /* Update PSSI error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_ERROR; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Note : The PSSI interrupts must be enabled after unlocking current process + to avoid the risk of PSSI interrupt handle execution before current + process unlock */ + /* Enable ERRinterrupt */ + /* possible to enable all of these */ + + HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + } + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received (in bytes) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_Receive_DMA(PSSI_HandleTypeDef *hpssi, uint32_t *pData, uint32_t Size) +{ + + HAL_StatusTypeDef dmaxferstatus; + + if (hpssi->State == HAL_PSSI_STATE_READY) + { + + /* Disable the selected PSSI peripheral */ + HAL_PSSI_DISABLE(hpssi); + /* Process Locked */ + __HAL_LOCK(hpssi); + + hpssi->State = HAL_PSSI_STATE_BUSY_RX; + hpssi->ErrorCode = HAL_PSSI_ERROR_NONE; + + /* Prepare transfer parameters */ + hpssi->pBuffPtr = pData; + hpssi->XferCount = Size; + + if (hpssi->XferCount > PSSI_MAX_NBYTE_SIZE) + { + hpssi->XferSize = PSSI_MAX_NBYTE_SIZE; + } + else + { + hpssi->XferSize = hpssi->XferCount; + } + + if (hpssi->XferSize > 0U) + { + if (hpssi->hdmarx != NULL) + { + /* Configure BusWidth */ + if (hpssi->hdmarx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_BYTE) + { + MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, PSSI_CR_DMA_ENABLE | + ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? PSSI_CR_CKPOL : 0U)); + } + else + { + MODIFY_REG(hpssi->Instance->CR, PSSI_CR_DMAEN | PSSI_CR_OUTEN | PSSI_CR_CKPOL, + PSSI_CR_DMA_ENABLE | hpssi->Init.BusWidth | + ((hpssi->Init.ClockPolarity == HAL_PSSI_RISING_EDGE) ? PSSI_CR_CKPOL : 0U)); + } + + /* Set the PSSI DMA transfer complete callback */ + hpssi->hdmarx->XferCpltCallback = PSSI_DMAReceiveCplt; + + /* Set the DMA error callback */ + hpssi->hdmarx->XferErrorCallback = PSSI_DMAError; + + /* Set the unused DMA callbacks to NULL */ + hpssi->hdmarx->XferHalfCpltCallback = NULL; + hpssi->hdmarx->XferAbortCallback = NULL; + + /* Enable the DMA */ + if ((hpssi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hpssi->hdmarx->LinkedListQueue != NULL) + { + /* Enable the DMA channel */ + /* Set DMA data size */ + hpssi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hpssi->XferSize; + /* Set DMA source address */ + hpssi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)&hpssi->Instance->DR; + /* Set DMA destination address */ + hpssi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + dmaxferstatus = HAL_DMAEx_List_Start_IT(hpssi->hdmarx); + } + else + { + /* Return error status */ + return HAL_ERROR; + } + } + else + { + dmaxferstatus = HAL_DMA_Start_IT(hpssi->hdmarx, (uint32_t)&hpssi->Instance->DR, (uint32_t)pData, + hpssi->XferSize); + } + } + else + { + /* Update PSSI state */ + hpssi->State = HAL_PSSI_STATE_READY; + + /* Update PSSI error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_ERROR; + } + + if (dmaxferstatus == HAL_OK) + { + /* Update XferCount value */ + hpssi->XferCount -= hpssi->XferSize; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Note : The PSSI interrupts must be enabled after unlocking current process + to avoid the risk of PSSI interrupt handle execution before current + process unlock */ + /* Enable ERR interrupt */ + HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + /* Enable DMA Request */ + hpssi->Instance->CR |= PSSI_CR_DMA_ENABLE; + /* Enable the selected PSSI peripheral */ + HAL_PSSI_ENABLE(hpssi); + } + else + { + /* Update PSSI state */ + hpssi->State = HAL_PSSI_STATE_READY; + + /* Update PSSI error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_ERROR; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Enable ERR,interrupt */ + HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Abort a DMA process communication with Interrupt. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_Abort_DMA(PSSI_HandleTypeDef *hpssi) +{ + /* Process Locked */ + __HAL_LOCK(hpssi); + + /* Disable Interrupts */ + HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + /* Set State at HAL_PSSI_STATE_ABORT */ + hpssi->State = HAL_PSSI_STATE_ABORT; + + /* Abort DMA TX transfer if any */ + if ((hpssi->Instance->CR & PSSI_CR_DMAEN) == PSSI_CR_DMAEN) + { + if (hpssi->State == HAL_PSSI_STATE_BUSY_TX) + { + hpssi->Instance->CR &= ~PSSI_CR_DMAEN; + + if (hpssi->hdmatx != NULL) + { + /* Set the PSSI DMA Abort callback : + will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ + hpssi->hdmatx->XferAbortCallback = PSSI_DMAAbort; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hpssi->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hpssi->hdmatx->XferAbortCallback(hpssi->hdmatx); + } + } + } + /* Abort DMA RX transfer if any */ + else if (hpssi->State == HAL_PSSI_STATE_BUSY_RX) + { + hpssi->Instance->CR &= ~PSSI_CR_DMAEN; + + if (hpssi->hdmarx != NULL) + { + /* Set the PSSI DMA Abort callback : + will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ + hpssi->hdmarx->XferAbortCallback = PSSI_DMAAbort; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hpssi->hdmarx) != HAL_OK) + { + /* Call Directly hpssi->hdma->XferAbortCallback function in case of error */ + hpssi->hdmarx->XferAbortCallback(hpssi->hdmarx); + } + } + } + else + { + + /* Call the error callback */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->ErrorCallback(hpssi); +#else + HAL_PSSI_ErrorCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Note : The PSSI interrupts must be enabled after unlocking current process + to avoid the risk of PSSI interrupt handle execution before current + process unlock */ + HAL_PSSI_ENABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + return HAL_OK; +} +#endif /*HAL_DMA_MODULE_ENABLED*/ + +/** + * @} + */ + +/** @addtogroup PSSI_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks + * @{ + */ + +/** + * @brief This function handles PSSI event interrupt request. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +void HAL_PSSI_IRQHandler(PSSI_HandleTypeDef *hpssi) +{ + /* Overrun/ Underrun Errors */ + if (HAL_PSSI_GET_FLAG(hpssi, PSSI_FLAG_OVR_MIS) != 0U) + { + /* Reset handle parameters */ + hpssi->XferCount = 0U; + + /* Disable all interrupts */ + HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort DMA TX transfer if any */ + if ((hpssi->Instance->CR & PSSI_CR_DMAEN) == PSSI_CR_DMAEN) + { + if (hpssi->State == HAL_PSSI_STATE_BUSY_TX) + { + /* Set new error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_UNDER_RUN; + + hpssi->Instance->CR &= ~PSSI_CR_DMAEN; + + if (hpssi->hdmatx != NULL) + { + /* Set the PSSI DMA Abort callback : + will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ + hpssi->hdmatx->XferAbortCallback = PSSI_DMAAbort; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hpssi->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hpssi->hdmatx->XferAbortCallback(hpssi->hdmatx); + } + } + } + /* Abort DMA RX transfer if any */ + else if (hpssi->State == HAL_PSSI_STATE_BUSY_RX) + { + /* Set new error code */ + hpssi->ErrorCode |= HAL_PSSI_ERROR_OVER_RUN; + + hpssi->Instance->CR &= ~PSSI_CR_DMAEN; + + if (hpssi->hdmarx != NULL) + { + /* Set the PSSI DMA Abort callback : + will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ + hpssi->hdmarx->XferAbortCallback = PSSI_DMAAbort; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hpssi->hdmarx) != HAL_OK) + { + /* Call Directly hpssi->hdma->XferAbortCallback function in case of error */ + hpssi->hdmarx->XferAbortCallback(hpssi->hdmarx); + } + } + } + else + { +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + /* Call the corresponding callback to inform upper layer of the error */ + hpssi->ErrorCallback(hpssi); +#else + HAL_PSSI_ErrorCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } + } +#endif /*HAL_DMA_MODULE_ENABLED*/ + + /* If state is an abort treatment on going, don't change state */ + if (hpssi->State == HAL_PSSI_STATE_ABORT) + { + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + /* Call the corresponding callback to inform upper layer of End of Transfer */ + hpssi->AbortCpltCallback(hpssi); +#else + HAL_PSSI_AbortCpltCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } + else + { + /* Set HAL_PSSI_STATE_READY */ + hpssi->State = HAL_PSSI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + /* Call the corresponding callback to inform upper layer of End of Transfer */ + hpssi->ErrorCallback(hpssi); +#else + HAL_PSSI_ErrorCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief Tx Transfer complete callback. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +__weak void HAL_PSSI_TxCpltCallback(PSSI_HandleTypeDef *hpssi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpssi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PSSI_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer complete callback. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +__weak void HAL_PSSI_RxCpltCallback(PSSI_HandleTypeDef *hpssi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpssi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PSSI_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief PSSI error callback. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +__weak void HAL_PSSI_ErrorCallback(PSSI_HandleTypeDef *hpssi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpssi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PSSI_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief PSSI abort callback. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval None + */ +__weak void HAL_PSSI_AbortCpltCallback(PSSI_HandleTypeDef *hpssi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hpssi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PSSI_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PSSI_Exported_Functions_Group3 Peripheral State and Error functions + * @brief Peripheral State, Mode and Error functions + * +@verbatim + =============================================================================== + ##### Peripheral State, Mode and Error functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PSSI handle state. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval HAL state + */ +HAL_PSSI_StateTypeDef HAL_PSSI_GetState(const PSSI_HandleTypeDef *hpssi) +{ + /* Return PSSI handle state */ + return hpssi->State; +} + +/** + * @brief Return the PSSI error code. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @retval PSSI Error Code + */ +uint32_t HAL_PSSI_GetError(const PSSI_HandleTypeDef *hpssi) +{ + return hpssi->ErrorCode; +} + +/** + * @} + */ + +/** @defgroup PSSI_Exported_Functions_Group4 Clock Source Selection function + * @brief Clock Source Selection function to pick between an internal or + * external clock. + * +@verbatim + =============================================================================== + ##### Clock Source Selection function ##### + =============================================================================== + [..] This subsection provides a function allowing to: + (+) Configure Clock source + (++) The clock source could be external (default) or internal (the clock + is generated by the device RCC). + (++) The AHB clock frequency must be at least 2.5 times higher than the + PSSI_PDCK frequency + +@endverbatim + * @{ + */ + +/** + * @brief Configure PSSI Clock Source. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI peripheral. + * @param ClockSource New Clock Configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PSSI_ClockConfig(PSSI_HandleTypeDef *hpssi, uint32_t ClockSource) +{ + /* Check the parameter */ + assert_param(IS_PSSI_CLOCK_SOURCE(ClockSource)); + + if (hpssi->State == HAL_PSSI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hpssi); + + HAL_PSSI_DISABLE(hpssi); + + /* Set CKSRC to ClockSource */ + MODIFY_REG(hpssi->Instance->CR, PSSI_CR_CKSRC, ClockSource); + + HAL_PSSI_ENABLE(hpssi); + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup PSSI_Private_Functions + * @{ + */ + +/** + * @brief PSSI Errors process. + * @param hpssi PSSI handle. + * @param ErrorCode Error code to handle. + * @retval None + */ +static void PSSI_Error(PSSI_HandleTypeDef *hpssi, uint32_t ErrorCode) +{ + /* Reset handle parameters */ + hpssi->XferCount = 0U; + + /* Set new error code */ + hpssi->ErrorCode |= ErrorCode; + + /* Disable all interrupts */ + HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort DMA TX transfer if any */ + if ((hpssi->Instance->CR & PSSI_CR_DMAEN) == PSSI_CR_DMAEN) + { + if (hpssi->State == HAL_PSSI_STATE_BUSY_TX) + { + hpssi->Instance->CR &= ~PSSI_CR_DMAEN; + + if (hpssi->hdmatx != NULL) + { + /* Set the PSSI DMA Abort callback : + will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ + hpssi->hdmatx->XferAbortCallback = PSSI_DMAAbort; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hpssi->hdmatx) != HAL_OK) + { + /* Call Directly XferAbortCallback function in case of error */ + hpssi->hdmatx->XferAbortCallback(hpssi->hdmatx); + } + } + } + /* Abort DMA RX transfer if any */ + else if (hpssi->State == HAL_PSSI_STATE_BUSY_RX) + { + hpssi->Instance->CR &= ~PSSI_CR_DMAEN; + + if (hpssi->hdmarx != NULL) + { + /* Set the PSSI DMA Abort callback : + will lead to call HAL_PSSI_ErrorCallback() at end of DMA abort procedure */ + hpssi->hdmarx->XferAbortCallback = PSSI_DMAAbort; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hpssi->hdmarx) != HAL_OK) + { + /* Call Directly hpssi->hdma->XferAbortCallback function in case of error */ + hpssi->hdmarx->XferAbortCallback(hpssi->hdmarx); + } + } + } + else + { + /*Nothing to do*/ + } + } +#endif /*HAL_DMA_MODULE_ENABLED*/ + + /* If state is an abort treatment on going, don't change state */ + if (hpssi->State == HAL_PSSI_STATE_ABORT) + { + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->AbortCpltCallback(hpssi); +#else + HAL_PSSI_AbortCpltCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } + else + { + /* Set HAL_PSSI_STATE_READY */ + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->ErrorCallback(hpssi); +#else + HAL_PSSI_ErrorCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief DMA PSSI slave transmit process complete callback. + * @param hdma DMA handle + * @retval None + */ +void PSSI_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + uint32_t tmperror; + + /* Disable Interrupts */ + HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + /* Store current volatile hpssi->ErrorCode, misra rule */ + tmperror = hpssi->ErrorCode; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if ((hpssi->State == HAL_PSSI_STATE_ABORT) || (tmperror != HAL_PSSI_ERROR_NONE)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + PSSI_Error(hpssi, hpssi->ErrorCode); + } + /* hpssi->State == HAL_PSSI_STATE_BUSY_TX */ + else + { + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->TxCpltCallback(hpssi); +#else + HAL_PSSI_TxCpltCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA PSSI master receive process complete callback. + * @param hdma DMA handle + * @retval None + */ +void PSSI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + uint32_t tmperror; + + /* Disable Interrupts */ + HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + /* Store current volatile hpssi->ErrorCode, misra rule */ + tmperror = hpssi->ErrorCode; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if ((hpssi->State == HAL_PSSI_STATE_ABORT) || (tmperror != HAL_PSSI_ERROR_NONE)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + PSSI_Error(hpssi, hpssi->ErrorCode); + } + /* hpssi->State == HAL_PSSI_STATE_BUSY_RX */ + else + { + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->RxCpltCallback(hpssi); +#else + HAL_PSSI_RxCpltCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA PSSI communication abort callback + * (To be called at end of DMA Abort procedure). + * @param hdma DMA handle. + * @retval None + */ +void PSSI_DMAAbort(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + /* Reset AbortCpltCallback */ + hpssi->hdmatx->XferAbortCallback = NULL; + hpssi->hdmarx->XferAbortCallback = NULL; + + /* Check if come from abort from user */ + if (hpssi->State == HAL_PSSI_STATE_ABORT) + { + hpssi->State = HAL_PSSI_STATE_READY; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->AbortCpltCallback(hpssi); +#else + HAL_PSSI_AbortCpltCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } + else + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->ErrorCallback(hpssi); +#else + HAL_PSSI_ErrorCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } +} +#endif /*HAL_DMA_MODULE_ENABLED*/ + +/** + * @brief This function handles PSSI Communication Timeout. + * @param hpssi Pointer to a PSSI_HandleTypeDef structure that contains + * the configuration information for the specified PSSI. + * @param Flag Specifies the PSSI flag to check. + * @param Status The new Flag status (SET or RESET). + * @param Timeout Timeout duration + * @param Tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef PSSI_WaitOnStatusUntilTimeout(PSSI_HandleTypeDef *hpssi, uint32_t Flag, FlagStatus Status, + uint32_t Timeout, uint32_t Tickstart) +{ + while ((HAL_PSSI_GET_STATUS(hpssi, Flag) & Flag) == (uint32_t)Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hpssi->ErrorCode |= HAL_PSSI_ERROR_TIMEOUT; + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + return HAL_ERROR; + } + } + } + return HAL_OK; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +void PSSI_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + PSSI_HandleTypeDef *hpssi = (PSSI_HandleTypeDef *)(((DMA_HandleTypeDef *)hdma)->Parent); + + uint32_t tmperror; + + /* Disable the selected PSSI peripheral */ + HAL_PSSI_DISABLE(hpssi); + + /* Disable Interrupts */ + HAL_PSSI_DISABLE_IT(hpssi, PSSI_FLAG_OVR_RIS); + + /* Store current volatile hpssi->ErrorCode, misra rule */ + tmperror = hpssi->ErrorCode; + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if ((hpssi->State == HAL_PSSI_STATE_ABORT) || (tmperror != HAL_PSSI_ERROR_NONE)) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + PSSI_Error(hpssi, hpssi->ErrorCode); + } + else + { + hpssi->State = HAL_PSSI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hpssi); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_PSSI_REGISTER_CALLBACKS == 1) + hpssi->ErrorCallback(hpssi); +#else + HAL_PSSI_ErrorCallback(hpssi); +#endif /* USE_HAL_PSSI_REGISTER_CALLBACKS */ + } +} +#endif /*HAL_DMA_MODULE_ENABLED*/ + + +/** + * @} + */ +#endif /* PSSI */ +#endif /* HAL_PSSI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr.c index 5c1c37c6c..b069f01a9 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr.c @@ -1,692 +1,691 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_pwr.c - * @author MCD Application Team - * @brief PWR HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Power Controller (PWR) peripheral: - * + Initialization/De-Initialization Functions. - * + Peripheral Control Functions. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### PWR peripheral overview ##### - ============================================================================== - [..] - (#) The Power control (PWR) provides an overview of the supply architecture - for the different power domains and of the supply configuration - controller. - - (#) Several low-power modes are available to save power when the CPU does not need to - execute code : - (+) Sleep (CPU clock stopped and still in RUN mode) - (+) Stop (System clock stopped) - (+) Standby (System powered down) - - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - - (#) Call HAL_PWR_EnableBkUpAccess() and HAL_PWR_DisableBkUpAccess() functions - to enable/disable access to the backup domain (RCC Backup domain control - register RCC_BDCR, RTC registers, TAMP registers, backup registers and - backup SRAM). - - (#) Call HAL_PWR_ConfigPVD() after setting parameters to be configured (event - mode and voltage threshold) in order to set up the Programmed Voltage - Detector, then use HAL_PWR_EnablePVD() and HAL_PWR_DisablePVD() - functions to start and stop the PVD detection. - (+) PVD level can be one of the following values : - (++) 2V0 - (++) 2V2 - (++) 2V4 - (++) 2V5 - (++) 2V6 - (++) 2V8 - (++) 2V9 - (++) External input analog voltage PVD_IN (compared internally to - VREFINT) - - (#) Call HAL_PWR_EnableWakeUpPin() and HAL_PWR_DisableWakeUpPin() functions - with the right parameter to configure the wake up pin polarity (Low or - High), the wake up pin selection and to enable and disable it. - - (#) Call HAL_PWR_EnterSLEEPMode() function to enter the CPU in Sleep mode. - Wake-up from Sleep mode could be following to an event or an - interrupt according to low power mode intrinsic request called (__WFI() - or __WFE()). - - (#) Call HAL_PWR_EnterSTOPMode() function to enter the whole system to Stop - mode. Wake-up from Stop mode could be following to an event or an - interrupt according to low power mode intrinsic request called (__WFI() - or __WFE()). - - (#) Call HAL_PWR_EnterSTANDBYMode() function to enter the whole system in - Standby mode. Wake-up from Standby mode can be following only by an - interrupt. - - (#) Call HAL_PWR_EnableSleepOnExit() and HAL_PWR_DisableSleepOnExit() APIs to - enable and disable the Cortex-M7 re-entry in Sleep mode after an - interruption handling is over. - - (#) Call HAL_PWR_EnableSEVOnPend() and HAL_PWR_DisableSEVOnPend() functions - to configure the Cortex-M7 to wake-up after any pending event / interrupt - even if it's disabled or has insufficient priority to cause exception - entry. - - *** PWR HAL driver macros list *** - ============================================= - [..] - Below the list of most used macros in PWR HAL driver. - - (+) __HAL_PWR_GET_FLAG() : Get the PWR pending flags. - (+) __HAL_PWR_CLEAR_FLAG() : Clear the PWR pending flags. - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup PWR PWR - * @brief PWR HAL module driver - * @{ - */ - -#ifdef HAL_PWR_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ - -/** @defgroup PWR_Private_Defines PWR Private Defines - * @{ - */ - -/** @defgroup PWR_PVD_Mode_Mask PWR PVD Mode Mask - * @{ - */ -#define PVD_MODE_IT (0x00010000U) -#define PVD_MODE_EVT (0x00020000U) -#define PVD_RISING_EDGE (0x00000001U) -#define PVD_FALLING_EDGE (0x00000002U) -#define PVD_RISING_FALLING_EDGE (0x00000003U) -/** - * @} - */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup PWR_Exported_Functions PWR Exported Functions - * @{ - */ - -/** @defgroup PWR_Exported_Functions_Group1 Initialization and De-Initialization Functions - * @brief Initialization and de-Initialization functions - * -@verbatim - =============================================================================== - ##### Initialization and De-Initialization Functions ##### - =============================================================================== - [..] - This section provides functions allowing to deinitialize power peripheral. - - [..] - After system reset, the backup domain (RCC Backup domain control register - RCC_BDCR, RTC registers, TAMP registers, backup registers and backup SRAM) - is protected against possible unwanted write accesses. - The HAL_PWR_EnableBkUpAccess() function enables the access to the backup - domain. - The HAL_PWR_DisableBkUpAccess() function disables the access to the backup - domain. - -@endverbatim - * @{ - */ - -/** - * @brief Deinitialize the HAL PWR peripheral registers to their default reset - * values. - * @note This functionality is not available in this product. - * The prototype is kept just to maintain compatibility with other - * products. - * @retval None. - */ -void HAL_PWR_DeInit(void) -{ -} - -/** - * @brief Enable access to the backup domain (RCC Backup domain control - * register RCC_BDCR, RTC registers, TAMP registers, backup registers - * and backup SRAM). - * @note After a system reset, the backup domain is protected against - * possible unwanted write accesses. - * @retval None. - */ -void HAL_PWR_EnableBkUpAccess(void) -{ - SET_BIT(PWR->CR1, PWR_CR1_DBP); -} - -/** - * @brief Disable access to the backup domain (RCC Backup domain control - * register RCC_BDCR, RTC registers, TAMP registers, backup registers - * and backup SRAM). - * @retval None. - */ -void HAL_PWR_DisableBkUpAccess(void) -{ - CLEAR_BIT(PWR->CR1, PWR_CR1_DBP); -} -/** - * @} - */ - - -/** @defgroup PWR_Exported_Functions_Group2 Peripheral Control Functions - * @brief Power Control functions - * -@verbatim - =============================================================================== - ##### Peripheral Control Functions ##### - =============================================================================== - [..] - This section provides functions allowing to control power peripheral. - - *** 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_CR1 - register). - - (+) A PVDO flag is available to indicate if VDD is higher or lower - than the PVD threshold. This event is internally connected to the EXTI - line 16 to generate an interrupt if enabled. - It is configurable through __HAL_PWR_PVD_EXTI_ENABLE_IT() macro. - - (+) The PVD is stopped in STANDBY mode. - - *** Wake-up pin configuration *** - ================================= - [..] - (+) Wake-up pin is used to wake up the system from STANDBY mode. - The pin pull is configurable through the WKUPEPR register to be in - No-pull, Pull-up and Pull-down. - The pin polarity is configurable through the WKUPEPR register to be - active on rising or falling edges. - - (+) There are up to four Wake-up pin in the STM32H7RS devices family. - - *** Low Power modes configuration *** - ===================================== - [..] - The device present 3 principles low-power modes : - (+) SLEEP mode : Cortex-M7 is stopped and all PWR domains are remaining - active (Powered and Clocked). - - (+) STOP mode : Cortex-M7 is stopped, clocks are stopped and the - regulator is running. The Main regulator or the LP - regulator could be selected. - - (+) STANDBY mode : All PWR domains enter DSTANDBY mode and the VCORE - supply regulator is powered off. - - *** SLEEP mode *** - ================== - [..] - (+) Entry: - The SLEEP mode is entered by using the HAL_PWR_EnterSLEEPMode(Regulator, - SLEEPEntry) function. - - (++) PWR_SLEEPENTRY_WFI : Enter SLEEP mode with WFI instruction. - (++) PWR_SLEEPENTRY_WFE : Enter SLEEP mode with WFE instruction and - clear of pending events before. - (++) PWR_SLEEPENTRY_WFE_NO_EVT_CLEAR: Enter SLEEP mode with WFE instruction and - no clear of pending event before. - -@@- The Regulator parameter is not used for the STM32H7RS 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 system STOP mode, the CPU clock is stopped. All CPU subsystem peripheral - clocks are stopped too. - 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_PWREx_EnableFlashPowerDown() function. - It can be switched on again by software after exiting the STOP mode using - the HAL_PWREx_DisableFlashPowerDown() function. - (+) Entry: - The STOP mode is entered using the HAL_PWR_EnterSTOPMode(Regulator, - STOPEntry) function with: - (++) Regulator: - (+++) PWR_MAINREGULATOR_ON: Main regulator ON. - This parameter is not used for the STM32H7RS family and is kept as parameter - just to maintain compatibility with the lower power families. - (++) STOPEntry: - (+++) PWR_STOPENTRY_WFI : Enter STOP mode with WFI instruction. - (+++) PWR_STOPENTRY_WFE : Enter STOP mode with WFE instruction and - clear of pending events before. - (+++) PWR_STOPENTRY_WFE_NO_EVT_CLEAR: Enter STOP mode with WFE instruction and - no clear of pending event before. - (+) Exit: - Any EXTI Line (Internal or External) configured in Interrupt/Event mode. - - *** STANDBY mode *** - ==================== - [..] - (+) - The system STANDBY mode allows to achieve the lowest power consumption. - It is based on the Cortex-M7 deep SLEEP mode, with the voltage regulator - disabled. The system 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 or falling 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 Configure the voltage threshold detected by the Programmed Voltage - * Detector (PVD). - * @param sConfigPVD : Pointer to a PWR_PVDTypeDef structure that contains the - * PVD configuration information (PVDLevel and EventMode). - * @note Refer to the electrical characteristics of your device datasheet for - * more details about the voltage threshold corresponding to each - * detection level. - * @note As PVD and AVD share the same EXTI line, the EXTI operating mode to - * configure will replace a possible previous configuration done through - * HAL_PWREx_ConfigAVD. - * @retval None. - */ -void HAL_PWR_ConfigPVD(const PWR_PVDTypeDef *sConfigPVD) -{ - /* Check the PVD configuration parameter */ - if (sConfigPVD == NULL) - { - return; - } - - /* Check the parameters */ - assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel)); - assert_param(IS_PWR_PVD_MODE(sConfigPVD->Mode)); - - /* Set PLS[7:5] bits according to PVDLevel value */ - MODIFY_REG(PWR->CR1, PWR_CR1_PLS, sConfigPVD->PVDLevel); - - /* Clear any previous config. Keep it clear if no event or IT mode is selected */ - __HAL_PWR_PVD_EXTI_DISABLE_EVENT(); - __HAL_PWR_PVD_EXTI_DISABLE_IT(); - __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE(); - __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE(); - - /* Configure the PVD in interrupt mode */ - if ((sConfigPVD->Mode & PVD_MODE_IT) == PVD_MODE_IT) - { - __HAL_PWR_PVD_EXTI_ENABLE_IT(); - } - - /* Configure the PVD in event mode */ - if ((sConfigPVD->Mode & PVD_MODE_EVT) == PVD_MODE_EVT) - { - __HAL_PWR_PVD_EXTI_ENABLE_EVENT(); - } - - /* Rising edge configuration */ - if ((sConfigPVD->Mode & PVD_RISING_EDGE) == PVD_RISING_EDGE) - { - __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE(); - } - - /* Falling edge configuration */ - if ((sConfigPVD->Mode & PVD_FALLING_EDGE) == PVD_FALLING_EDGE) - { - __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE(); - } -} - -/** - * @brief Enable the programmable voltage detector (PVD). - * @retval None. - */ -void HAL_PWR_EnablePVD(void) -{ - SET_BIT(PWR->CR1, PWR_CR1_PVDE); -} - -/** - * @brief Disable the programmable voltage detector (PVD). - * @retval None. - */ -void HAL_PWR_DisablePVD(void) -{ - CLEAR_BIT(PWR->CR1, PWR_CR1_PVDE); -} - -/** - * @brief Enable the WakeUp PINx functionality. - * @param WakeUpPinPolarity : Specifies which Wake-Up pin to enable. - * This parameter can be one of the following legacy values, which - * sets the default (rising edge): - * @arg PWR_WAKEUP_PIN1, - * PWR_WAKEUP_PIN2, - * PWR_WAKEUP_PIN3, - * PWR_WAKEUP_PIN4. - * or one of the following values where the user can explicitly states - * the enabled pin and the chosen polarity: - * @arg PWR_WAKEUP_PIN1_HIGH, PWR_WAKEUP_PIN1_LOW, - * PWR_WAKEUP_PIN2_HIGH, PWR_WAKEUP_PIN2_LOW, - * PWR_WAKEUP_PIN3_HIGH, PWR_WAKEUP_PIN3_LOW, - * PWR_WAKEUP_PIN4_HIGH, PWR_WAKEUP_PIN4_LOW. - * @note PWR_WAKEUP_PINx and PWR_WAKEUP_PINx_HIGH are equivalent. - * @retval None. - */ -void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinPolarity) -{ - /* Check the parameters */ - assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinPolarity)); - - /* - Enable and Specify the Wake-Up pin polarity and the pull configuration - for the event detection (rising or falling edge). - */ - MODIFY_REG(PWR->WKUPEPR, PWR_WKUPEPR_WKUPEN | PWR_WKUPEPR_WKUPP, WakeUpPinPolarity); -} - -/** - * @brief Disable 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, - * PWR_WAKEUP_PIN2, - * PWR_WAKEUP_PIN3, - * PWR_WAKEUP_PIN4, - * PWR_WAKEUP_PIN1_HIGH, PWR_WAKEUP_PIN1_LOW, - * PWR_WAKEUP_PIN2_HIGH, PWR_WAKEUP_PIN2_LOW, - * PWR_WAKEUP_PIN3_HIGH, PWR_WAKEUP_PIN3_LOW, - * PWR_WAKEUP_PIN4_HIGH, PWR_WAKEUP_PIN4_LOW. - * @retval None. - */ -void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) -{ - /* Check the parameters */ - assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); - - /* Disable the wake up pin selected */ - CLEAR_BIT(PWR->WKUPEPR, (PWR_WKUPEPR_WKUPEN & WakeUpPinx)); -} - -/** - * @brief Enter the current core in SLEEP mode (CSLEEP). - * @param Regulator : NA in this family project - * Specifies the regulator state in SLEEP mode. - * @note This parameter is not used for the STM32H7RS family and is kept as - * parameter just to maintain compatibility with the lower power - * families. - * @param SLEEPEntry : Specifies if SLEEP mode is entered with WFI or WFE - * intrinsic 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 and - * clear of pending events before. - * @arg PWR_SLEEPENTRY_WFE_NO_EVT_CLEAR : Enter SLEEP mode with WFE instruction and - * no clear of pending event before. - * @retval None. - */ -void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(Regulator); - - /* Check the parameters */ - assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); - - /* Clear SLEEPDEEP bit of Cortex System Control Register */ - CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); - - /* Select Sleep mode entry */ - if (SLEEPEntry == PWR_SLEEPENTRY_WFI) - { - /* Request Wait For Interrupt */ - __WFI(); - } - else - { - if (SLEEPEntry != PWR_SLEEPENTRY_WFE_NO_EVT_CLEAR) - { - /* Clear all pending event */ - __SEV(); - __WFE(); - } - - /* Request Wait For Event */ - __WFE(); - } -} - -/** - * @brief Enter the whole system to Stop mode. - * @note This API will enter the system in STOP mode - * @param Regulator : This parameter is not used for this product family. - and is kept as parameter just to maintain compatibility with the - lower power families. - * @param STOPEntry : Specifies if STOP mode in entered with WFI or WFE - * intrinsic 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 and - * clear of pending events before. - * @arg PWR_STOPENTRY_WFE_NO_EVT_CLEAR : Enter STOP mode with WFE instruction and - * no clear of pending event before. - * @note In System STOP mode, all I/O pins keep the same state as in Run mode. - * @note When exiting System STOP mode by issuing an interrupt or a wakeup - * event, the HSI RC oscillator is selected as default system wakeup - * clock. - * @note In System STOP mode, when the voltage regulator operates in low - * power mode, an additional startup delay is incurred when the system - * is waking up. By keeping the internal regulator ON during STOP mode, - * the consumption is higher although the startup time is reduced. - * @retval None. - */ -void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) -{ - - /* Prevent unused argument(s) compilation warning */ - UNUSED(Regulator); - - /* Check the parameters */ - assert_param(IS_PWR_STOP_ENTRY(STOPEntry)); - - /* Select Stop mode when device enters Deepsleep */ - CLEAR_BIT(PWR->CSR3, PWR_CSR3_PDDS); - - /* Set SLEEPDEEP bit of Cortex System Control Register */ - SET_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); - - /* Ensure that all instructions are done before entering STOP mode */ - __DSB(); - __ISB(); - - /* Select Stop mode entry */ - if (STOPEntry == PWR_STOPENTRY_WFI) - { - /* Request Wait For Interrupt */ - __WFI(); - } - else - { - if (STOPEntry != PWR_STOPENTRY_WFE_NO_EVT_CLEAR) - { - /* Clear all pending event */ - __SEV(); - __WFE(); - } - /* Request Wait For Event */ - __WFE(); - } - - /* Clear SLEEPDEEP bit of Cortex-M7 in the System Control Register */ - CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); -} - -/** - * @brief Enter the whole system to Standby mode. - * @note The Standby mode allows achieving the lowest power consumption. - * @note When the system enters in Standby mode, the voltage regulator is disabled. - * The complete VCORE domain is consequently powered off. - * The PLLs, HSI oscillator, CSI oscillator, HSI48 and the HSE oscillator are - * also switched off. - * SRAM and register contents are lost except for backup domain registers - * (RTC registers, RTC backup register and backup RAM), and Standby circuitry. - * @note When the System exit STANDBY mode by issuing an interrupt or a - * wakeup event, the HSI RC oscillator is selected as system clock. - * @retval None. - */ -void HAL_PWR_EnterSTANDBYMode(void) -{ - /* Select Standby when device enters Deepsleep */ - SET_BIT(PWR->CSR3, PWR_CSR3_PDDS); - - /* Set SLEEPDEEP bit of Cortex System Control Register */ - SET_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); - - /* Ensure that all instructions are done before entering STANDBY mode */ - __DSB(); - __ISB(); - - /* Request Wait For Interrupt */ - __WFI(); -} - -/** - * @brief Indicate SLEEP-ON-EXIT feature when returning from handler mode to - * thread mode. - * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the - * processor re-enters Sleep mode when an interruption handling is over. - * Setting this bit is useful when the processor is expected to run - * only on interruptions handling. - * @retval None. - */ -void HAL_PWR_EnableSleepOnExit(void) -{ - /* Set SLEEPONEXIT bit of Cortex-M7 System Control Register */ - SET_BIT(SCB->SCR, SCB_SCR_SLEEPONEXIT_Msk); -} - -/** - * @brief Disable SLEEP-ON-EXIT feature when returning from handler mode to - * thread mode. - * @note Clears SLEEPONEXIT bit of SCR register. When this bit is set, the - * processor re-enters Sleep mode when an interruption handling is over. - * @retval None. - */ -void HAL_PWR_DisableSleepOnExit(void) -{ - /* Clear SLEEPONEXIT bit of Cortex-M7 System Control Register */ - CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPONEXIT_Msk); -} - -/** - * @brief Enable CORTEX SEV-ON-PEND feature. - * @note Sets SEVONPEND bit of SCR register. When this bit is set, any - * pending event / interrupt even if it's disabled or has insufficient - * priority to cause exception entry wakes up the Cortex-M7. - * @retval None. - */ -void HAL_PWR_EnableSEVOnPend(void) -{ - /* Set SEVONPEND bit of Cortex-M7 System Control Register */ - SET_BIT(SCB->SCR, SCB_SCR_SEVONPEND_Msk); -} - -/** - * @brief Disable CORTEX SEVONPEND feature. - * @note Resets SEVONPEND bit of SCR register. When this bit is reset, only - * enabled pending causes exception entry wakes up the Cortex-M7. - * @retval None. - */ -void HAL_PWR_DisableSEVOnPend(void) -{ - /* Clear SEVONPEND bit of Cortex-M7 System Control Register */ - CLEAR_BIT(SCB->SCR, SCB_SCR_SEVONPEND_Msk); -} -/** - * @} - */ - -/** - * @} - */ -#endif /* HAL_PWR_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_pwr.c + * @author MCD Application Team + * @brief PWR HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Power Controller (PWR) peripheral: + * + Initialization/De-Initialization Functions. + * + Peripheral Control Functions. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### PWR peripheral overview ##### + ============================================================================== + [..] + (#) The Power control (PWR) provides an overview of the supply architecture + for the different power domains and of the supply configuration + controller. + + (#) Several low-power modes are available to save power when the CPU does not need to + execute code : + (+) Sleep (CPU clock stopped and still in RUN mode) + (+) Stop (System clock stopped) + (+) Standby (System powered down) + + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Call HAL_PWR_EnableBkUpAccess() and HAL_PWR_DisableBkUpAccess() functions + to enable/disable access to the backup domain (RCC Backup domain control + register RCC_BDCR, RTC registers, TAMP registers, backup registers and + backup SRAM). + + (#) Call HAL_PWR_ConfigPVD() after setting parameters to be configured (event + mode and voltage threshold) in order to set up the Programmed Voltage + Detector, then use HAL_PWR_EnablePVD() and HAL_PWR_DisablePVD() + functions to start and stop the PVD detection. + (+) PVD level can be one of the following values : + (++) 2V0 + (++) 2V2 + (++) 2V4 + (++) 2V5 + (++) 2V6 + (++) 2V8 + (++) 2V9 + (++) External input analog voltage PVD_IN (compared internally to + VREFINT) + + (#) Call HAL_PWR_EnableWakeUpPin() and HAL_PWR_DisableWakeUpPin() functions + with the right parameter to configure the wake up pin polarity (Low or + High), the wake up pin selection and to enable and disable it. + + (#) Call HAL_PWR_EnterSLEEPMode() function to enter the CPU in Sleep mode. + Wake-up from Sleep mode could be following to an event or an + interrupt according to low power mode intrinsic request called (__WFI() + or __WFE()). + + (#) Call HAL_PWR_EnterSTOPMode() function to enter the whole system to Stop + mode. Wake-up from Stop mode could be following to an event or an + interrupt according to low power mode intrinsic request called (__WFI() + or __WFE()). + + (#) Call HAL_PWR_EnterSTANDBYMode() function to enter the whole system in + Standby mode. Wake-up from Standby mode can be following only by an + interrupt. + + (#) Call HAL_PWR_EnableSleepOnExit() and HAL_PWR_DisableSleepOnExit() APIs to + enable and disable the Cortex-M7 re-entry in Sleep mode after an + interruption handling is over. + + (#) Call HAL_PWR_EnableSEVOnPend() and HAL_PWR_DisableSEVOnPend() functions + to configure the Cortex-M7 to wake-up after any pending event / interrupt + even if it's disabled or has insufficient priority to cause exception + entry. + + *** PWR HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in PWR HAL driver. + + (+) __HAL_PWR_GET_FLAG() : Get the PWR pending flags. + (+) __HAL_PWR_CLEAR_FLAG() : Clear the PWR pending flags. + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup PWR PWR + * @brief PWR HAL module driver + * @{ + */ + +#ifdef HAL_PWR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup PWR_Private_Defines PWR Private Defines + * @{ + */ + +/** @defgroup PWR_PVD_Mode_Mask PWR PVD Mode Mask + * @{ + */ +#define PVD_MODE_IT (0x00010000U) +#define PVD_MODE_EVT (0x00020000U) +#define PVD_RISING_EDGE (0x00000001U) +#define PVD_FALLING_EDGE (0x00000002U) +#define PVD_RISING_FALLING_EDGE (0x00000003U) +/** + * @} + */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PWR_Exported_Functions PWR Exported Functions + * @{ + */ + +/** @defgroup PWR_Exported_Functions_Group1 Initialization and De-Initialization Functions + * @brief Initialization and de-Initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and De-Initialization Functions ##### + =============================================================================== + [..] + This section provides functions allowing to deinitialize power peripheral. + + [..] + After system reset, the backup domain (RCC Backup domain control register + RCC_BDCR, RTC registers, TAMP registers, backup registers and backup SRAM) + is protected against possible unwanted write accesses. + The HAL_PWR_EnableBkUpAccess() function enables the access to the backup + domain. + The HAL_PWR_DisableBkUpAccess() function disables the access to the backup + domain. + +@endverbatim + * @{ + */ + +/** + * @brief Deinitialize the HAL PWR peripheral registers to their default reset + * values. + * @note This functionality is not available in this product. + * The prototype is kept just to maintain compatibility with other + * products. + * @retval None. + */ +void HAL_PWR_DeInit(void) +{ +} + +/** + * @brief Enable access to the backup domain (RCC Backup domain control + * register RCC_BDCR, RTC registers, TAMP registers, backup registers + * and backup SRAM). + * @note After a system reset, the backup domain is protected against + * possible unwanted write accesses. + * @retval None. + */ +void HAL_PWR_EnableBkUpAccess(void) +{ + SET_BIT(PWR->CR1, PWR_CR1_DBP); +} + +/** + * @brief Disable access to the backup domain (RCC Backup domain control + * register RCC_BDCR, RTC registers, TAMP registers, backup registers + * and backup SRAM). + * @retval None. + */ +void HAL_PWR_DisableBkUpAccess(void) +{ + CLEAR_BIT(PWR->CR1, PWR_CR1_DBP); +} +/** + * @} + */ + + +/** @defgroup PWR_Exported_Functions_Group2 Peripheral Control Functions + * @brief Power Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control Functions ##### + =============================================================================== + [..] + This section provides functions allowing to control power peripheral. + + *** 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_CR1 + register). + + (+) A PVDO flag is available to indicate if VDD is higher or lower + than the PVD threshold. This event is internally connected to the EXTI + line 16 to generate an interrupt if enabled. + It is configurable through __HAL_PWR_PVD_EXTI_ENABLE_IT() macro. + + (+) The PVD is stopped in STANDBY mode. + + *** Wake-up pin configuration *** + ================================= + [..] + (+) Wake-up pin is used to wake up the system from STANDBY mode. + The pin pull is configurable through the WKUPEPR register to be in + No-pull, Pull-up and Pull-down. + The pin polarity is configurable through the WKUPEPR register to be + active on rising or falling edges. + + (+) There are up to four Wake-up pin in the STM32H7RS devices family. + + *** Low Power modes configuration *** + ===================================== + [..] + The device present 3 principles low-power modes : + (+) SLEEP mode : Cortex-M7 is stopped and all PWR domains are remaining + active (Powered and Clocked). + + (+) STOP mode : Cortex-M7 is stopped, clocks are stopped and the + regulator is running. The Main regulator or the LP + regulator could be selected. + + (+) STANDBY mode : All PWR domains enter DSTANDBY mode and the VCORE + supply regulator is powered off. + + *** SLEEP mode *** + ================== + [..] + (+) Entry: + The SLEEP mode is entered by using the HAL_PWR_EnterSLEEPMode(Regulator, + SLEEPEntry) function. + + (++) PWR_SLEEPENTRY_WFI : Enter SLEEP mode with WFI instruction. + (++) PWR_SLEEPENTRY_WFE : Enter SLEEP mode with WFE instruction and + clear of pending events before. + (++) PWR_SLEEPENTRY_WFE_NO_EVT_CLEAR: Enter SLEEP mode with WFE instruction and + no clear of pending event before. + -@@- The Regulator parameter is not used for the STM32H7RS 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 system STOP mode, the CPU clock is stopped. All CPU subsystem peripheral + clocks are stopped too. + 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_PWREx_EnableFlashPowerDown() function. + It can be switched on again by software after exiting the STOP mode using + the HAL_PWREx_DisableFlashPowerDown() function. + (+) Entry: + The STOP mode is entered using the HAL_PWR_EnterSTOPMode(Regulator, + STOPEntry) function with: + (++) Regulator: + (+++) PWR_MAINREGULATOR_ON: Main regulator ON. + This parameter is not used for the STM32H7RS family and is kept as parameter + just to maintain compatibility with the lower power families. + (++) STOPEntry: + (+++) PWR_STOPENTRY_WFI : Enter STOP mode with WFI instruction. + (+++) PWR_STOPENTRY_WFE : Enter STOP mode with WFE instruction and + clear of pending events before. + (+++) PWR_STOPENTRY_WFE_NO_EVT_CLEAR: Enter STOP mode with WFE instruction and + no clear of pending event before. + (+) Exit: + Any EXTI Line (Internal or External) configured in Interrupt/Event mode. + + *** STANDBY mode *** + ==================== + [..] + (+) + The system STANDBY mode allows to achieve the lowest power consumption. + It is based on the Cortex-M7 deep SLEEP mode, with the voltage regulator + disabled. The system 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 or falling 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 Configure the voltage threshold detected by the Programmed Voltage + * Detector (PVD). + * @param sConfigPVD : Pointer to a PWR_PVDTypeDef structure that contains the + * PVD configuration information (PVDLevel and EventMode). + * @note Refer to the electrical characteristics of your device datasheet for + * more details about the voltage threshold corresponding to each + * detection level. + * @note As PVD and AVD share the same EXTI line, the EXTI operating mode to + * configure will replace a possible previous configuration done through + * HAL_PWREx_ConfigAVD. + * @retval None. + */ +void HAL_PWR_ConfigPVD(const PWR_PVDTypeDef *sConfigPVD) +{ + /* Check the PVD configuration parameter */ + if (sConfigPVD == NULL) + { + return; + } + + /* Check the parameters */ + assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel)); + assert_param(IS_PWR_PVD_MODE(sConfigPVD->Mode)); + + /* Set PLS[7:5] bits according to PVDLevel value */ + MODIFY_REG(PWR->CR1, PWR_CR1_PLS, sConfigPVD->PVDLevel); + + /* Clear any previous config. Keep it clear if no event or IT mode is selected */ + __HAL_PWR_PVD_EXTI_DISABLE_EVENT(); + __HAL_PWR_PVD_EXTI_DISABLE_IT(); + __HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE(); + __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE(); + + /* Configure the PVD in interrupt mode */ + if ((sConfigPVD->Mode & PVD_MODE_IT) == PVD_MODE_IT) + { + __HAL_PWR_PVD_EXTI_ENABLE_IT(); + } + + /* Configure the PVD in event mode */ + if ((sConfigPVD->Mode & PVD_MODE_EVT) == PVD_MODE_EVT) + { + __HAL_PWR_PVD_EXTI_ENABLE_EVENT(); + } + + /* Rising edge configuration */ + if ((sConfigPVD->Mode & PVD_RISING_EDGE) == PVD_RISING_EDGE) + { + __HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE(); + } + + /* Falling edge configuration */ + if ((sConfigPVD->Mode & PVD_FALLING_EDGE) == PVD_FALLING_EDGE) + { + __HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE(); + } +} + +/** + * @brief Enable the programmable voltage detector (PVD). + * @retval None. + */ +void HAL_PWR_EnablePVD(void) +{ + SET_BIT(PWR->CR1, PWR_CR1_PVDE); +} + +/** + * @brief Disable the programmable voltage detector (PVD). + * @retval None. + */ +void HAL_PWR_DisablePVD(void) +{ + CLEAR_BIT(PWR->CR1, PWR_CR1_PVDE); +} + +/** + * @brief Enable the WakeUp PINx functionality. + * @param WakeUpPinPolarity : Specifies which Wake-Up pin to enable. + * This parameter can be one of the following legacy values, which + * sets the default (rising edge): + * @arg PWR_WAKEUP_PIN1, + * PWR_WAKEUP_PIN2, + * PWR_WAKEUP_PIN3, + * PWR_WAKEUP_PIN4. + * or one of the following values where the user can explicitly states + * the enabled pin and the chosen polarity: + * @arg PWR_WAKEUP_PIN1_HIGH, PWR_WAKEUP_PIN1_LOW, + * PWR_WAKEUP_PIN2_HIGH, PWR_WAKEUP_PIN2_LOW, + * PWR_WAKEUP_PIN3_HIGH, PWR_WAKEUP_PIN3_LOW, + * PWR_WAKEUP_PIN4_HIGH, PWR_WAKEUP_PIN4_LOW. + * @note PWR_WAKEUP_PINx and PWR_WAKEUP_PINx_HIGH are equivalent. + * @retval None. + */ +void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinPolarity) +{ + /* Check the parameters */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinPolarity)); + + /* + Enable and Specify the Wake-Up pin polarity and the pull configuration + for the event detection (rising or falling edge). + */ + MODIFY_REG(PWR->WKUPEPR, PWR_WKUPEPR_WKUPEN | PWR_WKUPEPR_WKUPP, WakeUpPinPolarity); +} + +/** + * @brief Disable 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, + * PWR_WAKEUP_PIN2, + * PWR_WAKEUP_PIN3, + * PWR_WAKEUP_PIN4, + * PWR_WAKEUP_PIN1_HIGH, PWR_WAKEUP_PIN1_LOW, + * PWR_WAKEUP_PIN2_HIGH, PWR_WAKEUP_PIN2_LOW, + * PWR_WAKEUP_PIN3_HIGH, PWR_WAKEUP_PIN3_LOW, + * PWR_WAKEUP_PIN4_HIGH, PWR_WAKEUP_PIN4_LOW. + * @retval None. + */ +void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameters */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); + + /* Disable the wake up pin selected */ + CLEAR_BIT(PWR->WKUPEPR, (PWR_WKUPEPR_WKUPEN & WakeUpPinx)); +} + +/** + * @brief Enter the current core in SLEEP mode (CSLEEP). + * @param Regulator : NA in this family project + * Specifies the regulator state in SLEEP mode. + * @note This parameter is not used for the STM32H7RS family and is kept as + * parameter just to maintain compatibility with the lower power + * families. + * @param SLEEPEntry : Specifies if SLEEP mode is entered with WFI or WFE + * intrinsic 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 and + * clear of pending events before. + * @arg PWR_SLEEPENTRY_WFE_NO_EVT_CLEAR : Enter SLEEP mode with WFE instruction and + * no clear of pending event before. + * @retval None. + */ +void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(Regulator); + + /* Check the parameters */ + assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); + + /* Clear SLEEPDEEP bit of Cortex System Control Register */ + CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); + + /* Select Sleep mode entry */ + if (SLEEPEntry == PWR_SLEEPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + if (SLEEPEntry != PWR_SLEEPENTRY_WFE_NO_EVT_CLEAR) + { + /* Clear all pending event */ + __SEV(); + __WFE(); + } + + /* Request Wait For Event */ + __WFE(); + } +} + +/** + * @brief Enter the whole system to Stop mode. + * @note This API will enter the system in STOP mode + * @param Regulator : This parameter is not used for this product family. + and is kept as parameter just to maintain compatibility with the + lower power families. + * @param STOPEntry : Specifies if STOP mode in entered with WFI or WFE + * intrinsic 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 and + * clear of pending events before. + * @arg PWR_STOPENTRY_WFE_NO_EVT_CLEAR : Enter STOP mode with WFE instruction and + * no clear of pending event before. + * @note In System STOP mode, all I/O pins keep the same state as in Run mode. + * @note When exiting System STOP mode by issuing an interrupt or a wakeup + * event, the HSI RC oscillator is selected as default system wakeup + * clock. + * @note In System STOP mode, when the voltage regulator operates in low + * power mode, an additional startup delay is incurred when the system + * is waking up. By keeping the internal regulator ON during STOP mode, + * the consumption is higher although the startup time is reduced. + * @retval None. + */ +void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) +{ + + /* Prevent unused argument(s) compilation warning */ + UNUSED(Regulator); + + /* Check the parameters */ + assert_param(IS_PWR_STOP_ENTRY(STOPEntry)); + + /* Select Stop mode when device enters Deepsleep */ + CLEAR_BIT(PWR->CSR3, PWR_CSR3_PDDS); + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); + + /* Ensure that all instructions are done before entering STOP mode */ + __DSB(); + __ISB(); + + /* Select Stop mode entry */ + if (STOPEntry == PWR_STOPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + if (STOPEntry != PWR_STOPENTRY_WFE_NO_EVT_CLEAR) + { + /* Clear all pending event */ + __SEV(); + __WFE(); + } + /* Request Wait For Event */ + __WFE(); + } + + /* Clear SLEEPDEEP bit of Cortex-M7 in the System Control Register */ + CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); +} + +/** + * @brief Enter the whole system to Standby mode. + * @note The Standby mode allows achieving the lowest power consumption. + * @note When the system enters in Standby mode, the voltage regulator is disabled. + * The complete VCORE domain is consequently powered off. + * The PLLs, HSI oscillator, CSI oscillator, HSI48 and the HSE oscillator are + * also switched off. + * SRAM and register contents are lost except for backup domain registers + * (RTC registers, RTC backup register and backup RAM), and Standby circuitry. + * @note When the System exit STANDBY mode by issuing an interrupt or a + * wakeup event, the HSI RC oscillator is selected as system clock. + * @retval None. + */ +void HAL_PWR_EnterSTANDBYMode(void) +{ + /* Select Standby when device enters Deepsleep */ + SET_BIT(PWR->CSR3, PWR_CSR3_PDDS); + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SET_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); + + /* Ensure that all instructions are done before entering STANDBY mode */ + __DSB(); + __ISB(); + + /* Request Wait For Interrupt */ + __WFI(); +} + +/** + * @brief Indicate SLEEP-ON-EXIT feature when returning from handler mode to + * thread mode. + * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the + * processor re-enters Sleep mode when an interruption handling is over. + * Setting this bit is useful when the processor is expected to run + * only on interruptions handling. + * @retval None. + */ +void HAL_PWR_EnableSleepOnExit(void) +{ + /* Set SLEEPONEXIT bit of Cortex-M7 System Control Register */ + SET_BIT(SCB->SCR, SCB_SCR_SLEEPONEXIT_Msk); +} + +/** + * @brief Disable SLEEP-ON-EXIT feature when returning from handler mode to + * thread mode. + * @note Clears SLEEPONEXIT bit of SCR register. When this bit is set, the + * processor re-enters Sleep mode when an interruption handling is over. + * @retval None. + */ +void HAL_PWR_DisableSleepOnExit(void) +{ + /* Clear SLEEPONEXIT bit of Cortex-M7 System Control Register */ + CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPONEXIT_Msk); +} + +/** + * @brief Enable CORTEX SEV-ON-PEND feature. + * @note Sets SEVONPEND bit of SCR register. When this bit is set, any + * pending event / interrupt even if it's disabled or has insufficient + * priority to cause exception entry wakes up the Cortex-M7. + * @retval None. + */ +void HAL_PWR_EnableSEVOnPend(void) +{ + /* Set SEVONPEND bit of Cortex-M7 System Control Register */ + SET_BIT(SCB->SCR, SCB_SCR_SEVONPEND_Msk); +} + +/** + * @brief Disable CORTEX SEVONPEND feature. + * @note Resets SEVONPEND bit of SCR register. When this bit is reset, only + * enabled pending causes exception entry wakes up the Cortex-M7. + * @retval None. + */ +void HAL_PWR_DisableSEVOnPend(void) +{ + /* Clear SEVONPEND bit of Cortex-M7 System Control Register */ + CLEAR_BIT(SCB->SCR, SCB_SCR_SEVONPEND_Msk); +} +/** + * @} + */ + +/** + * @} + */ +#endif /* HAL_PWR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr_ex.c index 8e2ef435b..b5d43803a 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_pwr_ex.c @@ -1,1601 +1,1600 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_pwr_ex.c - * @author MCD Application Team - * @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 - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Call HAL_PWREx_ConfigSupply() function to configure the regulator supply - with the following different setups according to hardware (support SMPS): - (+) PWR_DIRECT_SMPS_SUPPLY - (+) PWR_SMPS_1V8_SUPPLIES_LDO - (+) PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO - (+) PWR_SMPS_1V8_SUPPLIES_EXT - (+) PWR_LDO_SUPPLY - (+) PWR_EXTERNAL_SOURCE_SUPPLY - - (#) Call HAL_PWREx_GetSupplyConfig() function to get the current supply setup. - - (#) Call HAL_PWREx_ControlVoltageScaling() function to configure the main - internal regulator output voltage. The voltage scaling could be one of - the following scales : - (+) PWR_REGULATOR_VOLTAGE_SCALE0 - (+) PWR_REGULATOR_VOLTAGE_SCALE1 - - (#) Call HAL_PWREx_GetVoltageRange() function to get the current output - voltage applied to the main regulator. - - (#) Call HAL_PWREx_ControlStopModeVoltageScaling() function to configure the main - internal regulator output voltage in STOP mode. The voltage scaling could be one of - the following scales : - (+) PWR_REGULATOR_STOP_VOLTAGE_SCALE3 - (+) PWR_REGULATOR_STOP_VOLTAGE_SCALE5 - - (#) Call HAL_PWREx_GetStopModeVoltageRange() function to get the current output - voltage applied to the main regulator in STOP mode. - - (#) Call HAL_PWREx_EnableFlashPowerDown() and - HAL_PWREx_DisableFlashPowerDown() functions to enable and disable the - Flash Power Down in STOP mode. - - (#) Call HAL_PWREx_EnableWakeUpPin() and HAL_PWREx_DisableWakeUpPin() - functions to enable and disable the Wake-up pin functionality for - the selected pin. - - (#) Call HAL_PWREx_GetWakeupFlag() and HAL_PWREx_ClearWakeupFlag() - functions to manage wake-up flag for the selected pin. - - (#) Call HAL_PWREx_WAKEUP_PIN_IRQHandler() function to handle all wake-up - pins interrupts. - - (#) Call HAL_PWREx_EnableBkUpReg() and HAL_PWREx_DisableBkUpReg() functions - to enable and disable the backup domain regulator. - - (#) Call HAL_PWREx_EnableUSBReg(), HAL_PWREx_DisableUSBReg(), - HAL_PWREx_EnableUSBVoltageDetector() and - HAL_PWREx_DisableUSBVoltageDetector() functions to manage USB power - regulation functionalities. - - (#) Call HAL_PWREx_EnableUCPDStandbyMode() and HAL_PWREx_DisableUCPDStandbyMode() functions - to enable and disable UCPD Standby mode. - - (#) Call HAL_PWREx_EnableUCPDDeadBattery() and HAL_PWREx_DisableUCPDDeadBattery() functions - to enable and disable UCPD dead battery. - - (#) Call HAL_PWREx_EnableBatteryCharging() and - HAL_PWREx_DisableBatteryCharging() functions to enable and disable the - battery charging feature with the selected resistor. - - (#) Call HAL_PWREx_EnableAnalogBooster() and HAL_PWREx_DisableAnalogBooster() functions - to enable and disable the AVD boost feature when the VDD supply voltage is below 2V7. - - (#) Call HAL_PWREx_EnableXSPIM1() and HAL_PWREx_DisableXSPIM1() functions - to enable and disable the XSPIM1. - - (#) Call HAL_PWREx_EnableXSPIM2() and HAL_PWREx_DisableXSPIM2() functions - to enable and disable the XSPIM2. - - (#) Call HAL_PWREx_ConfigXSPIPortCap() functions to configure the XSPI capacitor port 1 and 2. - The capacitor setting could be one of the following values : - (+) PWR_CAPACITOR_OFF - (+) PWR_CAPACITOR_ONE_THIRD_CAPACITANCE - (+) PWR_CAPACITOR_TWO_THIRD_CAPACITANCE - (+) PWR_CAPACITOR_FULL_CAPACITANCE - - (#) Call HAL_PWREx_GetConfigXSPIPortCap() function to get the current - capacitor port setting. - - (#) Call HAL_PWREx_EnableMonitoring() and HAL_PWREx_DisableMonitoring() - functions to enable and disable the VBAT and Temperature monitoring. - When VBAT and Temperature monitoring feature is enables, use - HAL_PWREx_GetTemperatureLevel() and HAL_PWREx_GetVBATLevel() to get - respectively the Temperature level and VBAT level. - - (#) Call HAL_PWREx_ConfigAVD() after setting parameter to be configured - (event mode and voltage threshold) in order to set up the Analog Voltage - Detector then use HAL_PWREx_EnableAVD() and HAL_PWREx_DisableAVD() - functions to start and stop the AVD detection. - (+) AVD level could be one of the following values : - (++) 1V7 - (++) 2V1 - (++) 2V5 - (++) 2V8 - - (#) Call HAL_PWREx_PVD_AVD_IRQHandler() function to handle the PWR PVD and - AVD interrupt request. - - (#) Call HAL_PWREx_EnablePullUpPullDownConfig() and - HAL_PWREx_DisablePullUpPullDownConfig() to I/O enable / disable pull-up - and pull-down configuration. - - (#) Call HAL_PWREx_EnableGPIOPullUp() and HAL_PWREx_EnableGPIOPullDown() to - apply respectively pull-up and pull-down to selected I/O. - Call HAL_PWREx_DisableGPIOPullUp() and HAL_PWREx_DisableGPIOPullDown() to - disable applied respectively pull-up and pull-down to selected I/O. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup PWREx PWREx - * @brief PWR Extended HAL module driver - * @{ - */ - -#ifdef HAL_PWR_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ - -/** @addtogroup PWREx_Private_Constants - * @{ - */ - -/** @defgroup PWREx_AVD_Mode_Mask PWR Extended AVD Mode Mask - * @{ - */ -#define AVD_MODE_IT (0x00010000U) -#define AVD_MODE_EVT (0x00020000U) -#define AVD_RISING_EDGE (0x00000001U) -#define AVD_FALLING_EDGE (0x00000002U) -#define AVD_RISING_FALLING_EDGE (0x00000003U) -/** - * @} - */ - -/** @defgroup PWREx_REG_SET_TIMEOUT PWR Extended Flag Setting Time Out Value - * @{ - */ -#define PWR_FLAG_SETTING_DELAY (1000U) -/** - * @} - */ - -/** @defgroup PWREx_WakeUp_Pins_Offsets PWREx Wake-Up Pins masks and offsets - * @{ - */ -/* Wake-Up Pins EXTI register mask */ -#define PWR_EXTI_WAKEUP_PINS_MASK (EXTI_IMR2_IM55 | EXTI_IMR2_IM56 |\ - EXTI_IMR2_IM57 | EXTI_IMR2_IM58 ) - -/* Wake-Up Pins PWR Pin Pull shift offsets */ -#define PWR_WAKEUP_PINS_PULL_SHIFT_OFFSET (2U) -/** - * @} - */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported types ------------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup PWREx_Exported_Functions PWREx Exported Functions - * @{ - */ - -/** @defgroup PWREx_Exported_Functions_Group1 Power Supply Control Functions - * @brief Power supply control functions - * -@verbatim - =============================================================================== - ##### Power supply control functions ##### - =============================================================================== - [..] - (#) When the system is powered on, the POR monitors VDD supply. Once VDD is - above the POR threshold level, the SMPS step-down converter and voltage - regulator are enabled in the default supply configuration: - - (+) The SMPS step-down converter output level is set at 1.35 V. - The voltage regulator LDO output level is set at 1.11 V. - Depending on the package and configuration the SMPS provides the - voltage to internal power domain and/or LDO or external supply. - - (+) The system is kept in reset mode as long as VCORE is not stable. - - (+) Once VCORE is stable, the system is taken out of reset and the HSI - oscillator is enabled. - - (+) Once the oscillator is stable, the system is initialized: Flash memory - is ready, option bytes are loaded and the CPU starts in limited run mode. - - (+) The software must then initialize the system including supply - configuration programming in PWR control register 2 (PWR_CSR2). - Once the supply configuration has been configured, the ACTVOSRDY bit in - the PWR control status register 1 (PWR_SR1) must be checked to guarantee - valid voltage levels: - a) As long as ACTVOSRDY indicates that voltage levels are invalid, the - system is in Run mode, write accesses to the RAMs are not permitted and - VOS must not be changed. - b) Once ACTVOSRDY indicates that voltage levels are valid, the system is - in normal Run mode, write accesses to RAMs are allowed and VOS can be - changed. - -@endverbatim - * @{ - */ - -/** - * @brief Configure the system Power Supply. - * @param SupplySource : Specifies the Power Supply source to set after a - * system startup. - * This parameter can be one of the following values : - * @arg PWR_DIRECT_SMPS_SUPPLY : The SMPS supplies the Vcore Power - * Domains. The LDO is Bypassed. - * @arg PWR_SMPS_1V8_SUPPLIES_LDO : The SMPS 1.8V output supplies - * the LDO. The Vcore Power Domains - * are supplied from the LDO. - * @arg PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO : The SMPS 1.8V output - * supplies external - * circuits and the LDO. - * The Vcore Power Domains - * are supplied from the - * LDO. - * @arg PWR_SMPS_1V8_SUPPLIES_EXT : The SMPS 1.8V output supplies - * external circuits. The LDO is - * Bypassed. The Vcore Power - * Domains are supplied from - * external source. - * @arg PWR_LDO_SUPPLY : The LDO regulator supplies the Vcore Power - * Domains. The SMPS regulator is Bypassed. - * @arg PWR_EXTERNAL_SOURCE_SUPPLY : The SMPS is disabled and the LDO are - * Bypassed. The Vcore Power - * Domains are supplied from - * external source. - * @note The SMPS step-down converter is not available on all packages, - * and the Bypass mode is available only when the SMPS is available. - * @note The PWR_DIRECT_SMPS_SUPPLY, PWR_SMPS_1V8_SUPPLIES_LDO, - * PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO and PWR_SMPS_1V8_SUPPLIES_EXT are used - * only for lines that supports SMPS regulator. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_PWREx_ConfigSupply(uint32_t SupplySource) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_PWR_SUPPLY(SupplySource)); - - /* Check if supply source was configured */ - if ((PWR->CSR2 & (PWR_CSR2_SDEN | PWR_CSR2_LDOEN | PWR_CSR2_BYPASS)) != (PWR_CSR2_SDEN | PWR_CSR2_LDOEN)) - { - /* Check supply configuration */ - if ((PWR->CSR2 & PWR_SUPPLY_CONFIG_MASK) != SupplySource) - { - /* Supply configuration update locked, can't apply a new supply config */ - return HAL_ERROR; - } - else - { - /* Supply configuration update locked, but new supply configuration - matches with old supply configuration : nothing to do - */ - return HAL_OK; - } - } - - /* Set the power supply configuration */ - MODIFY_REG(PWR->CSR2, PWR_SUPPLY_CONFIG_MASK, SupplySource); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait till voltage level flag is set */ - while ((PWR->SR1 & PWR_SR1_ACTVOSRDY) == 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - - /* When the SMPS supplies external circuits verify that SDEXTRDY flag is set */ - if ((SupplySource == PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO) || - (SupplySource == PWR_SMPS_1V8_SUPPLIES_EXT)) - { - /* Get the current tick number */ - tickstart = HAL_GetTick(); - - /* Wait till SMPS external supply ready flag is set */ - while ((PWR->CSR2 & PWR_CSR2_SDEXTRDY) == 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -/** - * @brief Get the power supply configuration. - * @retval The supply configuration. - */ -uint32_t HAL_PWREx_GetSupplyConfig(void) -{ - return (PWR->CSR2 & PWR_SUPPLY_CONFIG_MASK); -} - -/** - * @brief Configure the main internal regulator output voltage. - * @param VoltageScaling : Specifies the regulator output voltage to achieve - * a tradeoff between performance and power - * consumption. - * This parameter can be one of the following values : - * @arg PWR_REGULATOR_VOLTAGE_SCALE0 : Regulator voltage scaling range 0 (highest frequency). - * @arg PWR_REGULATOR_VOLTAGE_SCALE1 : Regulator voltage scaling range 1 (lowest power). - * @note When increasing the performance, the voltage scaling must be changed - * before increasing the system frequency. - * When decreasing performance, the system frequency must first be decreased - * before changing the voltage scaling. - * @note When exiting from Stop mode or Standby mode, the Run mode voltage - * scaling is reset to the default VOS low value. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_PWREx_ControlVoltageScaling(uint32_t VoltageScaling) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_PWR_REGULATOR_VOLTAGE(VoltageScaling)); - - /* Set the voltage range */ - MODIFY_REG(PWR->CSR4, PWR_CSR4_VOS, VoltageScaling); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait till voltage level flag is set */ - while ((PWR->CSR4 & PWR_CSR4_VOSRDY) == 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Get the main internal regulator output voltage. Reflecting the last - * VOS value applied to the PMU. - * @retval The current applied VOS selection. - */ -uint32_t HAL_PWREx_GetVoltageRange(void) -{ - /* Get the active voltage scaling */ - return (PWR->SR1 & PWR_SR1_ACTVOS); -} - -/** - * @brief Configure the main internal regulator output voltage in STOP mode. - * @param VoltageScaling : Specifies the regulator output voltage when the - * system enters Stop mode to achieve a tradeoff between performance - * and power consumption. - * This parameter can be one of the following values: - * @arg PWR_REGULATOR_STOP_VOLTAGE_SCALE3 : System Stop mode voltage scaling range 3 (highest frequency). - * @arg PWR_REGULATOR_STOP_VOLTAGE_SCALE5 : System Stop mode voltage scaling range 5 (lowest power). - * @retval HAL Status. - */ -HAL_StatusTypeDef HAL_PWREx_ControlStopModeVoltageScaling(uint32_t VoltageScaling) -{ - /* Check the parameters */ - assert_param(IS_PWR_STOP_MODE_REGULATOR_VOLTAGE(VoltageScaling)); - - /* Return the stop mode voltage range */ - MODIFY_REG(PWR->CR1, PWR_CR1_SVOS, VoltageScaling); - - return HAL_OK; -} - -/** - * @brief Get the main internal regulator output voltage in STOP mode. - * @retval The actual applied SVOS selection. - */ -uint32_t HAL_PWREx_GetStopModeVoltageRange(void) -{ - /* Return the stop voltage scaling */ - return (PWR->CR1 & PWR_CR1_SVOS); -} -/** - * @} - */ - -/** @defgroup PWREx_Exported_Functions_Group2 Low Power Control Functions - * @brief Low Power Control Functions - * -@verbatim - =============================================================================== - ##### Low Power Control Functions ##### - =============================================================================== - - *** FLASH Power Down configuration **** - ======================================= - [..] - By setting the FLPS bit in the PWR_CR1 register using the - HAL_PWREx_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. - - *** Wakeup Pins configuration **** - =================================== - [..] - Wakeup pins allow the system to exit from Standby mode. The configuration - of wakeup pins is done with the HAL_PWREx_EnableWakeUpPin(sPinParams) - function with: - (+) sPinParams: structure to enable and configure a wakeup pin: - (++) WakeUpPin: Wakeup pin to be enabled. - (++) PinPolarity: Wakeup pin polarity (rising or falling edge). - (++) PinPull: Wakeup pin pull (no pull, pull-up or pull-down). - [..] - The wakeup pins are internally connected to the EXTI lines [55-58] to - generate an interrupt if enabled. The EXTI lines configuration is done by - the HAL_EXTI_Dx_EventInputConfig() functions defined in the stm32h7rsxxhal.c - file. - [..] - When a wakeup pin event is received the HAL_PWREx_WAKEUP_PIN_IRQHandler is - called and the appropriate flag is set in the PWR_WKUPFR register. Then in - the HAL_PWREx_WAKEUP_PIN_IRQHandler function the wakeup pin flag will be - cleared and the appropriate user callback will be called. The user can add - his own code by customization of function pointer HAL_PWREx_WKUPx_Callback. - -@endverbatim - * @{ - */ - -/** - * @brief Enable the Flash Power Down in Stop mode. - * @note When Flash Power Down is enabled the Flash memory enters low-power - * mode when device is in Stop mode. This feature allows to - * obtain the best trade-off between low-power consumption and restart - * time when exiting from Stop mode. - * @retval None. - */ -void HAL_PWREx_EnableFlashPowerDown(void) -{ - /* Enable the Flash Power Down */ - SET_BIT(PWR->CR1, PWR_CR1_FLPS); -} - -/** - * @brief Disable the Flash Power Down in Stop mode. - * @note When Flash Power Down is disabled the Flash memory is kept on - * normal mode when device is in Stop mode. This feature allows - * to obtain the best trade-off between low-power consumption and - * restart time when exiting from Stop mode. - * @retval None. - */ -void HAL_PWREx_DisableFlashPowerDown(void) -{ - /* Disable the Flash Power Down */ - CLEAR_BIT(PWR->CR1, PWR_CR1_FLPS); -} - -/** - * @brief Enable the Wake-up PINx functionality. - * @param sPinParams : Pointer to a PWREx_WakeupPinTypeDef structure that - * contains the configuration information for the wake-up - * Pin. - * @retval None. - */ -void HAL_PWREx_EnableWakeUpPin(const PWREx_WakeupPinTypeDef *sPinParams) -{ - uint32_t pinConfig; - uint32_t regMask; - const uint32_t pullMask = PWR_WKUPEPR_WKUPPUPD1; - - /* Check the parameters */ - assert_param(IS_PWR_WAKEUP_PIN(sPinParams->WakeUpPin)); - assert_param(IS_PWR_WAKEUP_PIN_POLARITY(sPinParams->PinPolarity)); - assert_param(IS_PWR_WAKEUP_PIN_PULL(sPinParams->PinPull)); - - pinConfig = sPinParams->WakeUpPin | \ - (sPinParams->PinPolarity << ((POSITION_VAL(sPinParams->WakeUpPin) + PWR_WKUPEPR_WKUPP1_Pos) & 0x1FU)) | \ - (sPinParams->PinPull << (((POSITION_VAL(sPinParams->WakeUpPin) * PWR_WAKEUP_PINS_PULL_SHIFT_OFFSET) + PWR_WKUPEPR_WKUPPUPD1_Pos) & 0x1FU)); - - regMask = sPinParams->WakeUpPin | \ - (PWR_WKUPEPR_WKUPP1 << (POSITION_VAL(sPinParams->WakeUpPin) & 0x1FU)) | \ - (pullMask << ((POSITION_VAL(sPinParams->WakeUpPin) * PWR_WAKEUP_PINS_PULL_SHIFT_OFFSET) & 0x1FU)); - - /* Enable and Specify the Wake-Up pin polarity and the pull configuration - for the event detection (rising or falling edge) */ - MODIFY_REG(PWR->WKUPEPR, regMask, pinConfig); - - /* Configure the Wakeup Pin EXTI Line */ - MODIFY_REG(EXTI->IMR2, PWR_EXTI_WAKEUP_PINS_MASK, (sPinParams->WakeUpPin << EXTI_IMR2_IM55_Pos)); -} - -/** - * @brief Disable the Wake-up PINx functionality. - * @param WakeUpPin : Specifies the Wake-Up pin to be disabled. - * This parameter can be one of the following values: - * @arg PWR_WAKEUP_PIN1 : Disable PA0 wake-up PIN. - * @arg PWR_WAKEUP_PIN2 : Disable PA2 wake-up PIN. - * @arg PWR_WAKEUP_PIN3 : Disable PC13 wake-up PIN. - * @arg PWR_WAKEUP_PIN4 : Disable PC1 wake-up PIN. - * @retval None - */ -void HAL_PWREx_DisableWakeUpPin(uint32_t WakeUpPin) -{ - /* Check the parameter */ - assert_param(IS_PWR_WAKEUP_PIN(WakeUpPin)); - - /* Disable the WakeUpPin */ - CLEAR_BIT(PWR->WKUPEPR, WakeUpPin); -} - -/** - * @brief Get the Wake-Up Pin pending flags. - * @param WakeUpFlag : Specifies the Wake-Up PIN flag to be checked. - * This parameter can be one of the following values: - * @arg PWR_WAKEUP_FLAG1 : Get wakeup event received from PA0. - * @arg PWR_WAKEUP_FLAG2 : Get wakeup event received from PA2. - * @arg PWR_WAKEUP_FLAG3 : Get wakeup event received from PC13. - * @arg PWR_WAKEUP_FLAG4 : Get wakeup event received from PC1. - * @arg PWR_WAKEUP_FLAG_ALL : Get Wakeup event received from all - * wake up pins. - * @retval The Wake-Up pin flag. - */ -uint32_t HAL_PWREx_GetWakeupFlag(uint32_t WakeUpFlag) -{ - /* Check the parameters */ - assert_param(IS_PWR_WAKEUP_FLAG(WakeUpFlag)); - - /* Return the wake up pin flag */ - return (PWR->WKUPFR & WakeUpFlag); -} - -/** - * @brief Clear the Wake-Up pin pending flag. - * @param WakeUpFlag: Specifies the Wake-Up PIN flag to clear. - * This parameter can be one of the following values: - * @arg PWR_WAKEUP_FLAG1 : Clear the wakeup event received from PA0. - * @arg PWR_WAKEUP_FLAG2 : Clear the wakeup event received from PA2. - * @arg PWR_WAKEUP_FLAG3 : Clear the wakeup event received from PC13. - * @arg PWR_WAKEUP_FLAG4 : Clear the wakeup event received from PC1. - * @arg PWR_WAKEUP_FLAG_ALL : Clear the wakeup events received from all - * wake up pins. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_PWREx_ClearWakeupFlag(uint32_t WakeUpFlag) -{ - /* Check the parameter */ - assert_param(IS_PWR_WAKEUP_FLAG(WakeUpFlag)); - - /* Clear the wake up event received from wake up pin x */ - WRITE_REG(PWR->WKUPCR, WakeUpFlag); - - /* Check if the wake up event is well cleared */ - if ((PWR->WKUPFR & WakeUpFlag) != 0U) - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief This function handles the PWR WAKEUP PIN interrupt request. - * @note This API should be called under the WAKEUP_PIN_IRQHandler(). - * @retval None. - */ -void HAL_PWREx_WAKEUP_PIN_IRQHandler(void) -{ - /* Wakeup pin EXTI line interrupt detected */ - if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF1) != 0U) - { - /* Clear PWR WKUPF1 flag */ - __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP1); - - /* PWR WKUP1 interrupt user callback */ - HAL_PWREx_WKUP1_Callback(); - } - - if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF2) != 0U) - { - /* Clear PWR WKUPF2 flag */ - __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP2); - - /* PWR WKUP2 interrupt user callback */ - HAL_PWREx_WKUP2_Callback(); - } - - if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF3) != 0U) - { - /* Clear PWR WKUPF3 flag */ - __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP3); - - /* PWR WKUP3 interrupt user callback */ - HAL_PWREx_WKUP3_Callback(); - } - - if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF4) != 0U) - { - /* Clear PWR WKUPF4 flag */ - __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP4); - - /* PWR WKUP4 interrupt user callback */ - HAL_PWREx_WKUP4_Callback(); - } -} - -/** - * @brief PWR WKUP1 interrupt callback. - * @retval None. - */ -__weak void HAL_PWREx_WKUP1_Callback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PWREx_WKUP1Callback can be implemented in the user file - */ -} - -/** - * @brief PWR WKUP2 interrupt callback. - * @retval None. - */ -__weak void HAL_PWREx_WKUP2_Callback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PWREx_WKUP2Callback can be implemented in the user file - */ -} - -/** - * @brief PWR WKUP3 interrupt callback. - * @retval None. - */ -__weak void HAL_PWREx_WKUP3_Callback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PWREx_WKUP3Callback can be implemented in the user file - */ -} - -/** - * @brief PWR WKUP4 interrupt callback. - * @retval None. - */ -__weak void HAL_PWREx_WKUP4_Callback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PWREx_WKUP4Callback can be implemented in the user file - */ -} -/** - * @} - */ - -/** @defgroup PWREx_Exported_Functions_Group3 Peripherals Control Functions - * @brief Peripherals Control Functions - * -@verbatim - =============================================================================== - ##### Peripherals Control Functions ##### - =============================================================================== - - *** Main and Backup Regulators configuration *** - ================================================ - [..] - (+) The backup domain includes 4 Kbytes of backup SRAM accessible only - from the CPU, and addressed 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_PWREx_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_PWREx_ControlVoltageScaling(VOS) function which configure the VOS - bit in PWR_CSR4 register. - (+) The main internal regulator can be configured to operate in Low Power - mode when the system enters STOP mode to further reduce power - consumption. - This is done through HAL_PWREx_ControlStopModeVoltageScaling(SVOS) - function which configure the SVOS bit in PWR_CR1 register. - -@- Refer to the product datasheets for more details. - - *** USB Regulator configuration *** - =================================== - [..] - (+) The USB transceivers are supplied from a dedicated VDD33USB supply - that can be provided either by the integrated USB regulator, or by an - external USB supply. - (+) The USB regulator is enabled by HAL_PWREx_EnableUSBReg() function, the - VDD33USB is then provided from the USB regulator. - (+) When the USB regulator is enabled, the VDD33USB supply level detector - shall be enabled through HAL_PWREx_EnableUSBVoltageDetector() - function. - (+) The USB regulator is disabled through HAL_PWREx_DisableUSBReg() - function and VDD33USB can be provided from an external supply. In this - case VDD33USB and VDD50USB shall be connected together. - - *** VBAT battery charging *** - ============================= - [..] - (+) When VDD is present, the external battery connected to VBAT can be - charged through an internal resistance. VBAT charging can be performed - either through a 5 KOhm resistor or through a 1.5 KOhm resistor. - (+) VBAT charging is enabled by HAL_PWREx_EnableBatteryCharging - (ResistorValue) function with: - (++) ResistorValue: - (+++) PWR_BATTERY_CHARGING_RESISTOR_5: 5 KOhm resistor. - (+++) PWR_BATTERY_CHARGING_RESISTOR_1_5: 1.5 KOhm resistor. - (+) VBAT charging is disabled by HAL_PWREx_DisableBatteryCharging() - function. - -@endverbatim - * @{ - */ - -/** - * @brief Enable the Backup Regulator. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_PWREx_EnableBkUpReg(void) -{ - uint32_t tickstart; - - /* Enable the Backup regulator */ - SET_BIT(PWR->CSR1, PWR_CSR1_BREN); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait till Backup regulator ready flag is set */ - while ((PWR->CSR1 & PWR_CSR1_BRRDY) == 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Disable the Backup Regulator. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_PWREx_DisableBkUpReg(void) -{ - uint32_t tickstart; - - /* Disable the Backup regulator */ - CLEAR_BIT(PWR->CSR1, PWR_CSR1_BREN); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait till Backup regulator ready flag is reset */ - while ((PWR->CSR1 & PWR_CSR1_BRRDY) != 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Enable the USB Regulator. - * @retval None. - */ -void HAL_PWREx_EnableUSBReg(void) -{ - /* Enable the USB regulator */ - SET_BIT(PWR->CSR2, PWR_CSR2_USBREGEN); -} - -/** - * @brief Disable the USB Regulator. - * @retval None. - */ -void HAL_PWREx_DisableUSBReg(void) -{ - /* Disable the USB regulator */ - CLEAR_BIT(PWR->CSR2, PWR_CSR2_USBREGEN); -} - -/** - * @brief Enable the USB voltage level detector. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_PWREx_EnableUSBVoltageDetector(void) -{ - uint32_t tickstart; - - /* Enable the USB voltage detector */ - SET_BIT(PWR->CSR2, PWR_CSR2_USB33DEN); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait till the USB regulator ready flag is set */ - while ((PWR->CSR2 & PWR_CSR2_USB33RDY) == 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - return HAL_OK; -} - -/** - * @brief Disable the USB voltage level detector. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_PWREx_DisableUSBVoltageDetector(void) -{ - uint32_t tickstart; - - /* Disable the USB voltage detector */ - CLEAR_BIT(PWR->CSR2, PWR_CSR2_USB33DEN); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait till the USB regulator ready flag is reset */ - while ((PWR->CSR2 & PWR_CSR2_USB33RDY) != 0U) - { - if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) - { - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Enable the USB HS regulator. - * @retval None. - */ -void HAL_PWREx_EnableUSBHSregulator(void) -{ - /* Enable the USB HS regulator */ - SET_BIT(PWR->CSR2, PWR_CSR2_USBHSREGEN); -} - -/** - * @brief Disable the USB HS regulator. - * @retval None. - */ -void HAL_PWREx_DisableUSBHSregulator(void) -{ - /* Disable the USB HS regulator */ - CLEAR_BIT(PWR->CSR2, PWR_CSR2_USBHSREGEN); -} - -/** - * @brief Enable UCPD configuration memorization in Standby. - * @retval None - * @note This function must be called just before entering Standby mode when using UCPD. - */ -void HAL_PWREx_EnableUCPDStandbyMode(void) -{ - /* Memorize UCPD configuration when entering standby mode */ - SET_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_STBY); -} - -/** - * @brief Disable UCPD configuration memorization in Standby. - * @note This function must be called on exiting the Standby mode and before any UCPD - * configuration update. - * @retval None - */ -void HAL_PWREx_DisableUCPDStandbyMode(void) -{ - CLEAR_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_STBY); -} - -/** - * @brief Enable dead battery behavior. - * @retval None - */ -void HAL_PWREx_EnableUCPDDeadBattery(void) -{ - /* Enable dead battery behavior */ - CLEAR_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_DBDIS); -} - -/** - * @brief Disable dead battery behavior. - * @retval None - */ -void HAL_PWREx_DisableUCPDDeadBattery(void) -{ - /* Disable dead battery behavior */ - SET_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_DBDIS); -} - -/** - * @brief Enable the Battery charging. - * @note When VDD is present, charge the external battery through an internal - * resistor. - * It is automatically disabled in VBAT mode. - * @param ResistorValue : Specifies the charging resistor. - * This parameter can be one of the following values : - * @arg PWR_BATTERY_CHARGING_RESISTOR_5 : 5 KOhm resistor. - * @arg PWR_BATTERY_CHARGING_RESISTOR_1_5 : 1.5 KOhm resistor. - * @retval None. - */ -void HAL_PWREx_EnableBatteryCharging(uint32_t ResistorValue) -{ - /* Check the parameter */ - assert_param(IS_PWR_BATTERY_RESISTOR_SELECT(ResistorValue)); - - /* Specify the charging resistor and enable the Battery charging */ - MODIFY_REG(PWR->CSR2, (PWR_CSR2_VBRS | PWR_CSR2_VBE), (ResistorValue | PWR_CSR2_VBE)); - -} - -/** - * @brief Disable the Battery charging. - * @retval None. - */ -void HAL_PWREx_DisableBatteryCharging(void) -{ - /* Disable the Battery charging and restore default charging resistor value */ - CLEAR_BIT(PWR->CSR2, (PWR_CSR2_VBE | PWR_CSR2_VBRS)); -} - -/** - * @brief Enable the booster to guarantee the analog switch AC performance when - * the VDD supply voltage is below 2V7. - * @note The VDD supply voltage can be monitored through the PVD and the PLS - * field bits. - * @retval None. - */ -void HAL_PWREx_EnableAnalogBooster(void) -{ - /* Enable the Analog voltage */ - SET_BIT(PWR->CR1, PWR_CR1_AVDREADY); - - /* Enable VDDA booster */ - SET_BIT(PWR->CR1, PWR_CR1_BOOSTE); -} - -/** - * @brief Disable the analog booster. - * @retval None. - */ -void HAL_PWREx_DisableAnalogBooster(void) -{ - /* Disable VDDA booster */ - CLEAR_BIT(PWR->CR1, PWR_CR1_BOOSTE); - - /* Disable the Analog voltage */ - CLEAR_BIT(PWR->CR1, PWR_CR1_AVDREADY); -} - -/** - * @brief Enable the XSPIM_P1 interface. - * @note The XSPIM_P1 supply must be stable prior to setting - this bit. - * @retval None. - */ -void HAL_PWREx_EnableXSPIM1(void) -{ - SET_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM1); -} - -/** - * @brief Disable the XSPIM_P1 interface. - * @retval None. - */ -void HAL_PWREx_DisableXSPIM1(void) -{ - CLEAR_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM1); -} - -/** - * @brief Enable the XSPIM_P2 interface. - * @note The XSPIM_P2 supply must be stable prior to setting - this bit. - * @retval None. - */ -void HAL_PWREx_EnableXSPIM2(void) -{ - SET_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM2); -} - -/** - * @brief Disable the XSPIM_P2 interface. - * @retval None. - */ -void HAL_PWREx_DisableXSPIM2(void) -{ - CLEAR_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM2); -} - -/** - * @brief Configure the capacitor port - * @param PortCapacitor Select the Port - * This parameter can be one of the following values: - * @arg @ref PWR_CAPACITOR_PORT1 XSPI port 1 capacitor - * @arg @ref PWR_CAPACITOR_PORT2 XSPI port 2 capacitor - * @param PortCapacitorSetting Select the capacitor setting - * This parameter can be one of the following values: - * @arg @ref PWR_CAPACITOR_OFF XSPI Capacitor OFF - * @arg @ref PWR_CAPACITOR_ONE_THIRD_CAPACITANCE XSPI Capacitor set to 1/3 - * @arg @ref PWR_CAPACITOR_TWO_THIRD_CAPACITANCE XSPI Capacitor set to 2/3 - * @arg @ref PWR_CAPACITOR_FULL_CAPACITANCE XSPI Capacitor set to full capacitance - * @retval None. - */ -void HAL_PWREx_ConfigXSPIPortCap(uint32_t PortCapacitor, uint32_t PortCapacitorSetting) -{ - /* Check the parameters */ - assert_param(IS_PWR_CAPACITOR(PortCapacitor)); - assert_param(IS_PWR_CAPACITOR_SETTING(PortCapacitorSetting)); - - if (PortCapacitor == PWR_CAPACITOR_PORT1) - { - /* Set Port1 Capacitor setting */ - MODIFY_REG(PWR->CSR2, PWR_CSR2_XSPICAP1, PortCapacitorSetting); - } - else - { - /* Set Port2 Capacitor setting */ - MODIFY_REG(PWR->CSR2, PWR_CSR2_XSPICAP2, PortCapacitorSetting << (PWR_CSR2_XSPICAP2_Pos - PWR_CSR2_XSPICAP1_Pos)); - } -} - -/** - * @brief Get the capacitor port setting - * @param PortCapacitor Select the Port - * This parameter can be one of the following values: - * @arg @ref PWR_CAPACITOR_PORT1 XSPI port 1 capacitor - * @arg @ref PWR_CAPACITOR_PORT2 XSPI port 2 capacitor - * @retval The capacitor setting: - * @arg @ref PWR_CAPACITOR_OFF XSPI Capacitor OFF - * @arg @ref PWR_CAPACITOR_ONE_THIRD_CAPACITANCE XSPI Capacitor set to 1/3 - * @arg @ref PWR_CAPACITOR_TWO_THIRD_CAPACITANCE XSPI Capacitor set to 2/3 - * @arg @ref PWR_CAPACITOR_FULL_CAPACITANCE XSPI Capacitor set to full capacitance - */ -uint32_t HAL_PWREx_GetConfigXSPIPortCap(uint32_t PortCapacitor) -{ - uint32_t PortCapacitorSetting; - - /* Check the parameter */ - assert_param(IS_PWR_CAPACITOR(PortCapacitor)); - - if (PortCapacitor == PWR_CAPACITOR_PORT1) - { - /* Get Port1 Capacitor setting */ - PortCapacitorSetting = READ_BIT(PWR->CSR2, PWR_CSR2_XSPICAP1); - } - else - { - /* Get Port2 Capacitor setting */ - PortCapacitorSetting = (READ_BIT(PWR->CSR2, PWR_CSR2_XSPICAP2) >> (PWR_CSR2_XSPICAP2_Pos - PWR_CSR2_XSPICAP1_Pos)); - } - - return PortCapacitorSetting; -} - -/** - * @} - */ - -/** @defgroup PWREx_Exported_Functions_Group4 Power Monitoring functions - * @brief Power Monitoring functions - * -@verbatim - =============================================================================== - ##### Power Monitoring functions ##### - =============================================================================== - - *** VBAT and Temperature supervision *** - ======================================== - [..] - (+) The VBAT battery voltage supply can be monitored by comparing it with - two threshold levels: VBAThigh and VBATlow. VBATH flag and VBATL flags - in the PWR control register 2 (PWR_CR2), indicate if VBAT is higher or - lower than the threshold. - (+) The temperature can be monitored by comparing it with two threshold - levels, TEMPhigh and TEMPlow. TEMPH and TEMPL flags, in the PWR - control register 2 (PWR_CR2), indicate whether the device temperature - is higher or lower than the threshold. - (+) The VBAT and the temperature monitoring is enabled by - HAL_PWREx_EnableMonitoring() function and disabled by - HAL_PWREx_DisableMonitoring() function. - (+) The HAL_PWREx_GetVBATLevel() function returns the VBAT level which can - be : PWR_VBAT_BELOW_LOW_THRESHOLD or PWR_VBAT_ABOVE_HIGH_THRESHOLD or - PWR_VBAT_BETWEEN_HIGH_LOW_THRESHOLD. - (+) The HAL_PWREx_GetTemperatureLevel() function returns the Temperature - level which can be : - PWR_TEMP_BELOW_LOW_THRESHOLD or PWR_TEMP_ABOVE_HIGH_THRESHOLD or - PWR_TEMP_BETWEEN_HIGH_LOW_THRESHOLD. - - *** AVD configuration *** - ========================= - [..] - (+) The AVD is used to monitor the VDDA power supply by comparing it to a - threshold selected by the AVD Level (ALS[3:0] bits in the PWR_CR1 - register). - (+) A AVDO flag is available to indicate if VDDA is higher or lower - than the AVD threshold. This event is internally connected to the EXTI - line 16 to generate an interrupt if enabled. - It is configurable through __HAL_PWR_AVD_EXTI_ENABLE_IT() macro. - (+) The AVD is stopped in System Standby mode. - -@endverbatim - * @{ - */ - -/** - * @brief Enable the VBAT and temperature monitoring. - * @retval HAL status. - */ -void HAL_PWREx_EnableMonitoring(void) -{ - /* Enable the VBAT and Temperature monitoring */ - SET_BIT(PWR->CSR1, PWR_CSR1_MONEN); -} - -/** - * @brief Disable the VBAT and temperature monitoring. - * @retval HAL status. - */ -void HAL_PWREx_DisableMonitoring(void) -{ - /* Disable the VBAT and Temperature monitoring */ - CLEAR_BIT(PWR->CSR1, PWR_CSR1_MONEN); -} - -/** - * @brief Indicate whether the junction temperature is between, above or below - * the thresholds. - * @retval Temperature level. - */ -uint32_t HAL_PWREx_GetTemperatureLevel(void) -{ - uint32_t tempLevel; - uint32_t regValue; - - /* Read the temperature flags */ - regValue = READ_BIT(PWR->CSR1, (PWR_CSR1_TEMPH | PWR_CSR1_TEMPL)); - - /* Check if the temperature is below the threshold */ - if (regValue == PWR_CSR1_TEMPL) - { - tempLevel = PWR_TEMP_BELOW_LOW_THRESHOLD; - } - /* Check if the temperature is above the threshold */ - else if (regValue == PWR_CSR1_TEMPH) - { - tempLevel = PWR_TEMP_ABOVE_HIGH_THRESHOLD; - } - /* The temperature is between the thresholds */ - else - { - tempLevel = PWR_TEMP_BETWEEN_HIGH_LOW_THRESHOLD; - } - - return tempLevel; -} - -/** - * @brief Indicate whether the Battery voltage level is between, above or below - * the thresholds. - * @retval VBAT level. - */ -uint32_t HAL_PWREx_GetVBATLevel(void) -{ - uint32_t vbatLevel; - uint32_t regValue; - - /* Read the VBAT flags */ - regValue = READ_BIT(PWR->CSR1, (PWR_CSR1_VBATH | PWR_CSR1_VBATL)); - - /* Check if the VBAT is below the threshold */ - if (regValue == PWR_CSR1_VBATL) - { - vbatLevel = PWR_VBAT_BELOW_LOW_THRESHOLD; - } - /* Check if the VBAT is above the threshold */ - else if (regValue == PWR_CSR1_VBATH) - { - vbatLevel = PWR_VBAT_ABOVE_HIGH_THRESHOLD; - } - /* The VBAT is between the thresholds */ - else - { - vbatLevel = PWR_VBAT_BETWEEN_HIGH_LOW_THRESHOLD; - } - - return vbatLevel; -} - -/** - * @brief Configure the event mode and the voltage threshold detected by the - * Analog Voltage Detector (AVD). - * @param sConfigAVD : Pointer to an PWREx_AVDTypeDef structure that contains - * the configuration information for the AVD. - * @note Refer to the electrical characteristics of your device datasheet for - * more details about the voltage threshold corresponding to each - * detection level. - * @note As PVD and AVD share the same EXTI line, the EXTI operating mode to - * configure will replace a possible previous configuration done through - * HAL_PWR_ConfigPVD. - * @retval None. - */ -void HAL_PWREx_ConfigAVD(const PWREx_AVDTypeDef *sConfigAVD) -{ - /* Check the parameters */ - assert_param(IS_PWR_AVD_LEVEL(sConfigAVD->AVDLevel)); - assert_param(IS_PWR_AVD_MODE(sConfigAVD->Mode)); - - /* Set the ALS[18:17] bits according to AVDLevel value */ - MODIFY_REG(PWR->CR1, PWR_CR1_ALS, sConfigAVD->AVDLevel); - - /* Clear any previous config */ - __HAL_PWR_AVD_EXTI_DISABLE_EVENT(); - __HAL_PWR_AVD_EXTI_DISABLE_IT(); - - __HAL_PWR_AVD_EXTI_DISABLE_RISING_EDGE(); - __HAL_PWR_AVD_EXTI_DISABLE_FALLING_EDGE(); - - /* Configure the interrupt mode */ - if ((sConfigAVD->Mode & AVD_MODE_IT) == AVD_MODE_IT) - { - __HAL_PWR_AVD_EXTI_ENABLE_IT(); - } - - /* Configure the event mode */ - if ((sConfigAVD->Mode & AVD_MODE_EVT) == AVD_MODE_EVT) - { - __HAL_PWR_AVD_EXTI_ENABLE_EVENT(); - } - - /* Rising edge configuration */ - if ((sConfigAVD->Mode & AVD_RISING_EDGE) == AVD_RISING_EDGE) - { - __HAL_PWR_AVD_EXTI_ENABLE_RISING_EDGE(); - } - - /* Falling edge configuration */ - if ((sConfigAVD->Mode & AVD_FALLING_EDGE) == AVD_FALLING_EDGE) - { - __HAL_PWR_AVD_EXTI_ENABLE_FALLING_EDGE(); - } -} - -/** - * @brief Enable the Analog Voltage Detector (AVD). - * @retval None. - */ -void HAL_PWREx_EnableAVD(void) -{ - /* Enable the Analog Voltage Detector */ - SET_BIT(PWR->CR1, PWR_CR1_AVDEN); -} - -/** - * @brief Disable the Analog Voltage Detector(AVD). - * @retval None. - */ -void HAL_PWREx_DisableAVD(void) -{ - /* Disable the Analog Voltage Detector */ - CLEAR_BIT(PWR->CR1, PWR_CR1_AVDEN); -} - -/** - * @brief This function handles the PWR PVD/AVD interrupt request. - * @note This API should be called under the PVD_AVD_IRQHandler(). - * @retval None - */ -void HAL_PWREx_PVD_AVD_IRQHandler(void) -{ - /* Check PWR EXTI flags for PVD/AVD */ - if (((EXTI->PR1) & EXTI_PR1_PR16) != 0U) - { - /* Clear PVD/AVD exti pending bit */ - WRITE_REG(EXTI->PR1, EXTI_PR1_PR16); - - /* PWR PVD/AVD interrupt user callback */ - HAL_PWREx_PVD_AVD_Callback(); - } -} - -/** - * @brief PWR PVD/AVD interrupt callback. - * @retval None. - */ -__weak void HAL_PWREx_PVD_AVD_Callback(void) -{ - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_PWREx_PVD_AVD_Callback can be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup PWREx_Exported_Functions_Group5 I/O Pull-Up Pull-Down Configuration Functions - * @brief I/O pull-up / pull-down configuration functions - * -@verbatim - =============================================================================== - ##### Voltage monitoring Functions ##### - =============================================================================== - [..] - In Standby mode, pull up and pull down can be configured to - maintain an I/O in the selected state. If the APC bit in the PWR_APCR - register is set, the I/Os can be configured either with a pull-up through - PWR_PUCRx registers (x=N,O), or with a pull-down through - PWR_PDCRx registers (x=N,O,P), or can be kept in analog state - if none of the PWR_PUCRx or PWR_PDCRx register is set. - - [..] - The pull-down configuration has highest priority over pull-up - configuration in case both PWR_PUCRx and PWR_PDCRx are set for the same - I/O. - -@endverbatim - * @{ - */ - -/** - * @brief Enable pull-up and pull-down configuration. - * @note When APC bit is set, the I/O pull-up and pull-down configurations - * defined in PWR_PUCRx and PWR_PDCRx registers are applied in Standby - * mode. - * @note Pull-up set by PUy bit of PWR_PUCRx register is not activated if the - * corresponding PDy bit of PWR_PDCRx register is also set (pull-down - * configuration priority is higher). HAL_PWREx_EnableGPIOPullUp() and - * HAL_PWREx_EnableGPIOPullDown() API's ensure there is no conflict - * when setting PUy or PDy bit. - * @retval None. - */ -void HAL_PWREx_EnablePullUpPullDownConfig(void) -{ - SET_BIT(PWR->APCR, PWR_APCR_APC); -} - -/** - * @brief Disable pull-up and pull-down configuration. - * @note When APC bit is cleared, the I/O pull-up and pull-down configurations - * defined in PWR_PUCRx and PWR_PDCRx registers are not applied in - * Standby mode. - * @retval None. - */ -void HAL_PWREx_DisablePullUpPullDownConfig(void) -{ - CLEAR_BIT(PWR->APCR, PWR_APCR_APC); -} - -/** - * @brief Enable GPIO pull-up state in Standby mode. - * @note Set the relevant PUy bits of PWR_PUCRx register to configure the I/O in - * pull-up state in Standby mode. - * @note This state is effective in Standby mode only if APC bit - * is set through HAL_PWREx_EnablePullUpPullDownConfig() API. - * @note The configuration is maintained when exiting the Standby mode. - * @note Even if a PUy bit to set is reserved, the other PUy bits entered as - * input parameter at the same time are set. - * @note The pullup is not activated if the corresponding PDy bit is also set. - * @param GPIO_Port : Specify the IO port. - * This parameter can be a value of @ref PWREx_GPIO_PullUp_Port. - * @param GPIO_Pin : Specify the I/O pins numbers. - * This parameter can be a combination of @ref PWREx_GPIO_PullUp_Pin_Mask. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullUp(uint32_t GPIO_Port, uint32_t GPIO_Pin) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_PWR_GPIO_PULLPUP_PORT(GPIO_Port)); - assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); - - switch (GPIO_Port) - { - case PWR_GPIO_PULLUP_PORT_N: - SET_BIT(PWR->PUCRN, GPIO_Pin); - break; - - case PWR_GPIO_PULLUP_PORT_O: - SET_BIT(PWR->PUCRO, GPIO_Pin); - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @brief Disable GPIO pull-up state in Standby mode. - * @note Reset the relevant PUy bits of PWR_PUCRx register used to configure the I/O - * in pull-up state in Standby mode. - * @note Even if a PUy bit to reset is reserved, the other PUy bits entered as input - * parameter at the same time are reset. - * @param GPIO_Port : Specify the IO port. - * This parameter can be a value of @ref PWREx_GPIO_PullUp_Port. - * @param GPIO_Pin : Specify the I/O pins numbers. - * This parameter can be a combination of @ref PWREx_GPIO_PullUp_Pin_Mask. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullUp(uint32_t GPIO_Port, uint32_t GPIO_Pin) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_PWR_GPIO_PULLPUP_PORT(GPIO_Port)); - assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); - - switch (GPIO_Port) - { - case PWR_GPIO_PULLUP_PORT_N: - CLEAR_BIT(PWR->PUCRN, GPIO_Pin); - break; - - case PWR_GPIO_PULLUP_PORT_O: - CLEAR_BIT(PWR->PUCRO, GPIO_Pin); - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @brief Enable GPIO pull-down state in Standby mode. - * @note Set the relevant PDy bits of PWR_PDCRx register to configure the I/O in - * pull-down state in Standby mode. - * @note This state is effective in Standby mode only if APC bit - * is set through HAL_PWREx_EnablePullUpPullDownConfig() API. - * @note The configuration is maintained when exiting the Standby mode. - * @note Even if a PDy bit to set is reserved, the other PDy bits entered as input - * parameter at the same time are set. - * @param GPIO_Port : Specify the IO port. - * This parameter can be a value of @ref PWREx_GPIO_PullDown_Port. - * @param GPIO_Pin : Specify the I/O pins numbers. - * This parameter can be a combination of @ref PWREx_GPIO_PullDown_Pin_Mask. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullDown(uint32_t GPIO_Port, uint32_t GPIO_Pin) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_PWR_GPIO_PULLDOWN_PORT(GPIO_Port)); - assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); - - switch (GPIO_Port) - { - case PWR_GPIO_PULLDOWN_PORT_N: - SET_BIT(PWR->PDCRN, GPIO_Pin); - break; - - case PWR_GPIO_PULLDOWN_PORT_O: - SET_BIT(PWR->PDCRO, GPIO_Pin); - break; - - case PWR_GPIO_PULLDOWN_PORT_P: - SET_BIT(PWR->PDCRP, GPIO_Pin); - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @brief Disable GPIO pull-down state in Standby mode. - * @note Reset the relevant PDy bits of PWR_PDCRx register used to configure the I/O - * in pull-down state in Standby mode. - * @note Even if a PDy bit to reset is reserved, the other PDy bits entered as input - * parameter at the same time are reset. - * @param GPIO_Port : Specify the IO port. - * This parameter can be a value of @ref PWREx_GPIO_PullDown_Port. - * @param GPIO_Pin : Specify the I/O pins numbers. - * This parameter can be a value of @ref PWREx_GPIO_PullDown_Pin_Mask. - * @retval HAL Status - */ -HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullDown(uint32_t GPIO_Port, uint32_t GPIO_Pin) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_PWR_GPIO_PULLDOWN_PORT(GPIO_Port)); - assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); - - switch (GPIO_Port) - { - case PWR_GPIO_PULLDOWN_PORT_N: - CLEAR_BIT(PWR->PDCRN, GPIO_Pin); - break; - - case PWR_GPIO_PULLDOWN_PORT_O: - CLEAR_BIT(PWR->PDCRO, GPIO_Pin); - break; - - case PWR_GPIO_PULLDOWN_PORT_P: - CLEAR_BIT(PWR->PDCRP, GPIO_Pin); - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_PWR_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_pwr_ex.c + * @author MCD Application Team + * @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 + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Call HAL_PWREx_ConfigSupply() function to configure the regulator supply + with the following different setups according to hardware (support SMPS): + (+) PWR_DIRECT_SMPS_SUPPLY + (+) PWR_SMPS_1V8_SUPPLIES_LDO + (+) PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO + (+) PWR_SMPS_1V8_SUPPLIES_EXT + (+) PWR_LDO_SUPPLY + (+) PWR_EXTERNAL_SOURCE_SUPPLY + + (#) Call HAL_PWREx_GetSupplyConfig() function to get the current supply setup. + + (#) Call HAL_PWREx_ControlVoltageScaling() function to configure the main + internal regulator output voltage. The voltage scaling could be one of + the following scales : + (+) PWR_REGULATOR_VOLTAGE_SCALE0 + (+) PWR_REGULATOR_VOLTAGE_SCALE1 + + (#) Call HAL_PWREx_GetVoltageRange() function to get the current output + voltage applied to the main regulator. + + (#) Call HAL_PWREx_ControlStopModeVoltageScaling() function to configure the main + internal regulator output voltage in STOP mode. The voltage scaling could be one of + the following scales : + (+) PWR_REGULATOR_STOP_VOLTAGE_SCALE3 + (+) PWR_REGULATOR_STOP_VOLTAGE_SCALE5 + + (#) Call HAL_PWREx_GetStopModeVoltageRange() function to get the current output + voltage applied to the main regulator in STOP mode. + + (#) Call HAL_PWREx_EnableFlashPowerDown() and + HAL_PWREx_DisableFlashPowerDown() functions to enable and disable the + Flash Power Down in STOP mode. + + (#) Call HAL_PWREx_EnableWakeUpPin() and HAL_PWREx_DisableWakeUpPin() + functions to enable and disable the Wake-up pin functionality for + the selected pin. + + (#) Call HAL_PWREx_GetWakeupFlag() and HAL_PWREx_ClearWakeupFlag() + functions to manage wake-up flag for the selected pin. + + (#) Call HAL_PWREx_WAKEUP_PIN_IRQHandler() function to handle all wake-up + pins interrupts. + + (#) Call HAL_PWREx_EnableBkUpReg() and HAL_PWREx_DisableBkUpReg() functions + to enable and disable the backup domain regulator. + + (#) Call HAL_PWREx_EnableUSBReg(), HAL_PWREx_DisableUSBReg(), + HAL_PWREx_EnableUSBVoltageDetector() and + HAL_PWREx_DisableUSBVoltageDetector() functions to manage USB power + regulation functionalities. + + (#) Call HAL_PWREx_EnableUCPDStandbyMode() and HAL_PWREx_DisableUCPDStandbyMode() functions + to enable and disable UCPD Standby mode. + + (#) Call HAL_PWREx_EnableUCPDDeadBattery() and HAL_PWREx_DisableUCPDDeadBattery() functions + to enable and disable UCPD dead battery. + + (#) Call HAL_PWREx_EnableBatteryCharging() and + HAL_PWREx_DisableBatteryCharging() functions to enable and disable the + battery charging feature with the selected resistor. + + (#) Call HAL_PWREx_EnableAnalogBooster() and HAL_PWREx_DisableAnalogBooster() functions + to enable and disable the AVD boost feature when the VDD supply voltage is below 2V7. + + (#) Call HAL_PWREx_EnableXSPIM1() and HAL_PWREx_DisableXSPIM1() functions + to enable and disable the XSPIM1. + + (#) Call HAL_PWREx_EnableXSPIM2() and HAL_PWREx_DisableXSPIM2() functions + to enable and disable the XSPIM2. + + (#) Call HAL_PWREx_ConfigXSPIPortCap() functions to configure the XSPI capacitor port 1 and 2. + The capacitor setting could be one of the following values : + (+) PWR_CAPACITOR_OFF + (+) PWR_CAPACITOR_ONE_THIRD_CAPACITANCE + (+) PWR_CAPACITOR_TWO_THIRD_CAPACITANCE + (+) PWR_CAPACITOR_FULL_CAPACITANCE + + (#) Call HAL_PWREx_GetConfigXSPIPortCap() function to get the current + capacitor port setting. + + (#) Call HAL_PWREx_EnableMonitoring() and HAL_PWREx_DisableMonitoring() + functions to enable and disable the VBAT and Temperature monitoring. + When VBAT and Temperature monitoring feature is enables, use + HAL_PWREx_GetTemperatureLevel() and HAL_PWREx_GetVBATLevel() to get + respectively the Temperature level and VBAT level. + + (#) Call HAL_PWREx_ConfigAVD() after setting parameter to be configured + (event mode and voltage threshold) in order to set up the Analog Voltage + Detector then use HAL_PWREx_EnableAVD() and HAL_PWREx_DisableAVD() + functions to start and stop the AVD detection. + (+) AVD level could be one of the following values : + (++) 1V7 + (++) 2V1 + (++) 2V5 + (++) 2V8 + + (#) Call HAL_PWREx_PVD_AVD_IRQHandler() function to handle the PWR PVD and + AVD interrupt request. + + (#) Call HAL_PWREx_EnablePullUpPullDownConfig() and + HAL_PWREx_DisablePullUpPullDownConfig() to I/O enable / disable pull-up + and pull-down configuration. + + (#) Call HAL_PWREx_EnableGPIOPullUp() and HAL_PWREx_EnableGPIOPullDown() to + apply respectively pull-up and pull-down to selected I/O. + Call HAL_PWREx_DisableGPIOPullUp() and HAL_PWREx_DisableGPIOPullDown() to + disable applied respectively pull-up and pull-down to selected I/O. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup PWREx PWREx + * @brief PWR Extended HAL module driver + * @{ + */ + +#ifdef HAL_PWR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @addtogroup PWREx_Private_Constants + * @{ + */ + +/** @defgroup PWREx_AVD_Mode_Mask PWR Extended AVD Mode Mask + * @{ + */ +#define AVD_MODE_IT (0x00010000U) +#define AVD_MODE_EVT (0x00020000U) +#define AVD_RISING_EDGE (0x00000001U) +#define AVD_FALLING_EDGE (0x00000002U) +#define AVD_RISING_FALLING_EDGE (0x00000003U) +/** + * @} + */ + +/** @defgroup PWREx_REG_SET_TIMEOUT PWR Extended Flag Setting Time Out Value + * @{ + */ +#define PWR_FLAG_SETTING_DELAY (1000U) +/** + * @} + */ + +/** @defgroup PWREx_WakeUp_Pins_Offsets PWREx Wake-Up Pins masks and offsets + * @{ + */ +/* Wake-Up Pins EXTI register mask */ +#define PWR_EXTI_WAKEUP_PINS_MASK (EXTI_IMR2_IM55 | EXTI_IMR2_IM56 |\ + EXTI_IMR2_IM57 | EXTI_IMR2_IM58 ) + +/* Wake-Up Pins PWR Pin Pull shift offsets */ +#define PWR_WAKEUP_PINS_PULL_SHIFT_OFFSET (2U) +/** + * @} + */ + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup PWREx_Exported_Functions PWREx Exported Functions + * @{ + */ + +/** @defgroup PWREx_Exported_Functions_Group1 Power Supply Control Functions + * @brief Power supply control functions + * +@verbatim + =============================================================================== + ##### Power supply control functions ##### + =============================================================================== + [..] + (#) When the system is powered on, the POR monitors VDD supply. Once VDD is + above the POR threshold level, the SMPS step-down converter and voltage + regulator are enabled in the default supply configuration: + + (+) The SMPS step-down converter output level is set at 1.35 V. + The voltage regulator LDO output level is set at 1.11 V. + Depending on the package and configuration the SMPS provides the + voltage to internal power domain and/or LDO or external supply. + + (+) The system is kept in reset mode as long as VCORE is not stable. + + (+) Once VCORE is stable, the system is taken out of reset and the HSI + oscillator is enabled. + + (+) Once the oscillator is stable, the system is initialized: Flash memory + is ready, option bytes are loaded and the CPU starts in limited run mode. + + (+) The software must then initialize the system including supply + configuration programming in PWR control register 2 (PWR_CSR2). + Once the supply configuration has been configured, the ACTVOSRDY bit in + the PWR control status register 1 (PWR_SR1) must be checked to guarantee + valid voltage levels: + a) As long as ACTVOSRDY indicates that voltage levels are invalid, the + system is in Run mode, write accesses to the RAMs are not permitted and + VOS must not be changed. + b) Once ACTVOSRDY indicates that voltage levels are valid, the system is + in normal Run mode, write accesses to RAMs are allowed and VOS can be + changed. + +@endverbatim + * @{ + */ + +/** + * @brief Configure the system Power Supply. + * @param SupplySource : Specifies the Power Supply source to set after a + * system startup. + * This parameter can be one of the following values : + * @arg PWR_DIRECT_SMPS_SUPPLY : The SMPS supplies the Vcore Power + * Domains. The LDO is Bypassed. + * @arg PWR_SMPS_1V8_SUPPLIES_LDO : The SMPS 1.8V output supplies + * the LDO. The Vcore Power Domains + * are supplied from the LDO. + * @arg PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO : The SMPS 1.8V output + * supplies external + * circuits and the LDO. + * The Vcore Power Domains + * are supplied from the + * LDO. + * @arg PWR_SMPS_1V8_SUPPLIES_EXT : The SMPS 1.8V output supplies + * external circuits. The LDO is + * Bypassed. The Vcore Power + * Domains are supplied from + * external source. + * @arg PWR_LDO_SUPPLY : The LDO regulator supplies the Vcore Power + * Domains. The SMPS regulator is Bypassed. + * @arg PWR_EXTERNAL_SOURCE_SUPPLY : The SMPS is disabled and the LDO are + * Bypassed. The Vcore Power + * Domains are supplied from + * external source. + * @note The SMPS step-down converter is not available on all packages, + * and the Bypass mode is available only when the SMPS is available. + * @note The PWR_DIRECT_SMPS_SUPPLY, PWR_SMPS_1V8_SUPPLIES_LDO, + * PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO and PWR_SMPS_1V8_SUPPLIES_EXT are used + * only for lines that supports SMPS regulator. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_PWREx_ConfigSupply(uint32_t SupplySource) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_PWR_SUPPLY(SupplySource)); + + /* Check if supply source was configured */ + if ((PWR->CSR2 & (PWR_CSR2_SDEN | PWR_CSR2_LDOEN | PWR_CSR2_BYPASS)) != (PWR_CSR2_SDEN | PWR_CSR2_LDOEN)) + { + /* Check supply configuration */ + if ((PWR->CSR2 & PWR_SUPPLY_CONFIG_MASK) != SupplySource) + { + /* Supply configuration update locked, can't apply a new supply config */ + return HAL_ERROR; + } + else + { + /* Supply configuration update locked, but new supply configuration + matches with old supply configuration : nothing to do + */ + return HAL_OK; + } + } + + /* Set the power supply configuration */ + MODIFY_REG(PWR->CSR2, PWR_SUPPLY_CONFIG_MASK, SupplySource); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait till voltage level flag is set */ + while ((PWR->SR1 & PWR_SR1_ACTVOSRDY) == 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + + /* When the SMPS supplies external circuits verify that SDEXTRDY flag is set */ + if ((SupplySource == PWR_SMPS_1V8_SUPPLIES_EXT_AND_LDO) || + (SupplySource == PWR_SMPS_1V8_SUPPLIES_EXT)) + { + /* Get the current tick number */ + tickstart = HAL_GetTick(); + + /* Wait till SMPS external supply ready flag is set */ + while ((PWR->CSR2 & PWR_CSR2_SDEXTRDY) == 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + } + return HAL_OK; +} + +/** + * @brief Get the power supply configuration. + * @retval The supply configuration. + */ +uint32_t HAL_PWREx_GetSupplyConfig(void) +{ + return (PWR->CSR2 & PWR_SUPPLY_CONFIG_MASK); +} + +/** + * @brief Configure the main internal regulator output voltage. + * @param VoltageScaling : Specifies the regulator output voltage to achieve + * a tradeoff between performance and power + * consumption. + * This parameter can be one of the following values : + * @arg PWR_REGULATOR_VOLTAGE_SCALE0 : Regulator voltage scaling range 0 (highest frequency). + * @arg PWR_REGULATOR_VOLTAGE_SCALE1 : Regulator voltage scaling range 1 (lowest power). + * @note When increasing the performance, the voltage scaling must be changed + * before increasing the system frequency. + * When decreasing performance, the system frequency must first be decreased + * before changing the voltage scaling. + * @note When exiting from Stop mode or Standby mode, the Run mode voltage + * scaling is reset to the default VOS low value. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_PWREx_ControlVoltageScaling(uint32_t VoltageScaling) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_PWR_REGULATOR_VOLTAGE(VoltageScaling)); + + /* Set the voltage range */ + MODIFY_REG(PWR->CSR4, PWR_CSR4_VOS, VoltageScaling); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait till voltage level flag is set */ + while ((PWR->CSR4 & PWR_CSR4_VOSRDY) == 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Get the main internal regulator output voltage. Reflecting the last + * VOS value applied to the PMU. + * @retval The current applied VOS selection. + */ +uint32_t HAL_PWREx_GetVoltageRange(void) +{ + /* Get the active voltage scaling */ + return (PWR->SR1 & PWR_SR1_ACTVOS); +} + +/** + * @brief Configure the main internal regulator output voltage in STOP mode. + * @param VoltageScaling : Specifies the regulator output voltage when the + * system enters Stop mode to achieve a tradeoff between performance + * and power consumption. + * This parameter can be one of the following values: + * @arg PWR_REGULATOR_STOP_VOLTAGE_SCALE3 : System Stop mode voltage scaling range 3 (highest frequency). + * @arg PWR_REGULATOR_STOP_VOLTAGE_SCALE5 : System Stop mode voltage scaling range 5 (lowest power). + * @retval HAL Status. + */ +HAL_StatusTypeDef HAL_PWREx_ControlStopModeVoltageScaling(uint32_t VoltageScaling) +{ + /* Check the parameters */ + assert_param(IS_PWR_STOP_MODE_REGULATOR_VOLTAGE(VoltageScaling)); + + /* Return the stop mode voltage range */ + MODIFY_REG(PWR->CR1, PWR_CR1_SVOS, VoltageScaling); + + return HAL_OK; +} + +/** + * @brief Get the main internal regulator output voltage in STOP mode. + * @retval The actual applied SVOS selection. + */ +uint32_t HAL_PWREx_GetStopModeVoltageRange(void) +{ + /* Return the stop voltage scaling */ + return (PWR->CR1 & PWR_CR1_SVOS); +} +/** + * @} + */ + +/** @defgroup PWREx_Exported_Functions_Group2 Low Power Control Functions + * @brief Low Power Control Functions + * +@verbatim + =============================================================================== + ##### Low Power Control Functions ##### + =============================================================================== + + *** FLASH Power Down configuration **** + ======================================= + [..] + By setting the FLPS bit in the PWR_CR1 register using the + HAL_PWREx_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. + + *** Wakeup Pins configuration **** + =================================== + [..] + Wakeup pins allow the system to exit from Standby mode. The configuration + of wakeup pins is done with the HAL_PWREx_EnableWakeUpPin(sPinParams) + function with: + (+) sPinParams: structure to enable and configure a wakeup pin: + (++) WakeUpPin: Wakeup pin to be enabled. + (++) PinPolarity: Wakeup pin polarity (rising or falling edge). + (++) PinPull: Wakeup pin pull (no pull, pull-up or pull-down). + [..] + The wakeup pins are internally connected to the EXTI lines [55-58] to + generate an interrupt if enabled. The EXTI lines configuration is done by + the HAL_EXTI_Dx_EventInputConfig() functions defined in the stm32h7rsxxhal.c + file. + [..] + When a wakeup pin event is received the HAL_PWREx_WAKEUP_PIN_IRQHandler is + called and the appropriate flag is set in the PWR_WKUPFR register. Then in + the HAL_PWREx_WAKEUP_PIN_IRQHandler function the wakeup pin flag will be + cleared and the appropriate user callback will be called. The user can add + his own code by customization of function pointer HAL_PWREx_WKUPx_Callback. + +@endverbatim + * @{ + */ + +/** + * @brief Enable the Flash Power Down in Stop mode. + * @note When Flash Power Down is enabled the Flash memory enters low-power + * mode when device is in Stop mode. This feature allows to + * obtain the best trade-off between low-power consumption and restart + * time when exiting from Stop mode. + * @retval None. + */ +void HAL_PWREx_EnableFlashPowerDown(void) +{ + /* Enable the Flash Power Down */ + SET_BIT(PWR->CR1, PWR_CR1_FLPS); +} + +/** + * @brief Disable the Flash Power Down in Stop mode. + * @note When Flash Power Down is disabled the Flash memory is kept on + * normal mode when device is in Stop mode. This feature allows + * to obtain the best trade-off between low-power consumption and + * restart time when exiting from Stop mode. + * @retval None. + */ +void HAL_PWREx_DisableFlashPowerDown(void) +{ + /* Disable the Flash Power Down */ + CLEAR_BIT(PWR->CR1, PWR_CR1_FLPS); +} + +/** + * @brief Enable the Wake-up PINx functionality. + * @param sPinParams : Pointer to a PWREx_WakeupPinTypeDef structure that + * contains the configuration information for the wake-up + * Pin. + * @retval None. + */ +void HAL_PWREx_EnableWakeUpPin(const PWREx_WakeupPinTypeDef *sPinParams) +{ + uint32_t pinConfig; + uint32_t regMask; + const uint32_t pullMask = PWR_WKUPEPR_WKUPPUPD1; + + /* Check the parameters */ + assert_param(IS_PWR_WAKEUP_PIN(sPinParams->WakeUpPin)); + assert_param(IS_PWR_WAKEUP_PIN_POLARITY(sPinParams->PinPolarity)); + assert_param(IS_PWR_WAKEUP_PIN_PULL(sPinParams->PinPull)); + + pinConfig = sPinParams->WakeUpPin | \ + (sPinParams->PinPolarity << ((POSITION_VAL(sPinParams->WakeUpPin) + PWR_WKUPEPR_WKUPP1_Pos) & 0x1FU)) | \ + (sPinParams->PinPull << (((POSITION_VAL(sPinParams->WakeUpPin) * PWR_WAKEUP_PINS_PULL_SHIFT_OFFSET) + PWR_WKUPEPR_WKUPPUPD1_Pos) & 0x1FU)); + + regMask = sPinParams->WakeUpPin | \ + (PWR_WKUPEPR_WKUPP1 << (POSITION_VAL(sPinParams->WakeUpPin) & 0x1FU)) | \ + (pullMask << ((POSITION_VAL(sPinParams->WakeUpPin) * PWR_WAKEUP_PINS_PULL_SHIFT_OFFSET) & 0x1FU)); + + /* Enable and Specify the Wake-Up pin polarity and the pull configuration + for the event detection (rising or falling edge) */ + MODIFY_REG(PWR->WKUPEPR, regMask, pinConfig); + + /* Configure the Wakeup Pin EXTI Line */ + MODIFY_REG(EXTI->IMR2, PWR_EXTI_WAKEUP_PINS_MASK, (sPinParams->WakeUpPin << EXTI_IMR2_IM55_Pos)); +} + +/** + * @brief Disable the Wake-up PINx functionality. + * @param WakeUpPin : Specifies the Wake-Up pin to be disabled. + * This parameter can be one of the following values: + * @arg PWR_WAKEUP_PIN1 : Disable PA0 wake-up PIN. + * @arg PWR_WAKEUP_PIN2 : Disable PA2 wake-up PIN. + * @arg PWR_WAKEUP_PIN3 : Disable PC13 wake-up PIN. + * @arg PWR_WAKEUP_PIN4 : Disable PC1 wake-up PIN. + * @retval None + */ +void HAL_PWREx_DisableWakeUpPin(uint32_t WakeUpPin) +{ + /* Check the parameter */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPin)); + + /* Disable the WakeUpPin */ + CLEAR_BIT(PWR->WKUPEPR, WakeUpPin); +} + +/** + * @brief Get the Wake-Up Pin pending flags. + * @param WakeUpFlag : Specifies the Wake-Up PIN flag to be checked. + * This parameter can be one of the following values: + * @arg PWR_WAKEUP_FLAG1 : Get wakeup event received from PA0. + * @arg PWR_WAKEUP_FLAG2 : Get wakeup event received from PA2. + * @arg PWR_WAKEUP_FLAG3 : Get wakeup event received from PC13. + * @arg PWR_WAKEUP_FLAG4 : Get wakeup event received from PC1. + * @arg PWR_WAKEUP_FLAG_ALL : Get Wakeup event received from all + * wake up pins. + * @retval The Wake-Up pin flag. + */ +uint32_t HAL_PWREx_GetWakeupFlag(uint32_t WakeUpFlag) +{ + /* Check the parameters */ + assert_param(IS_PWR_WAKEUP_FLAG(WakeUpFlag)); + + /* Return the wake up pin flag */ + return (PWR->WKUPFR & WakeUpFlag); +} + +/** + * @brief Clear the Wake-Up pin pending flag. + * @param WakeUpFlag: Specifies the Wake-Up PIN flag to clear. + * This parameter can be one of the following values: + * @arg PWR_WAKEUP_FLAG1 : Clear the wakeup event received from PA0. + * @arg PWR_WAKEUP_FLAG2 : Clear the wakeup event received from PA2. + * @arg PWR_WAKEUP_FLAG3 : Clear the wakeup event received from PC13. + * @arg PWR_WAKEUP_FLAG4 : Clear the wakeup event received from PC1. + * @arg PWR_WAKEUP_FLAG_ALL : Clear the wakeup events received from all + * wake up pins. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_PWREx_ClearWakeupFlag(uint32_t WakeUpFlag) +{ + /* Check the parameter */ + assert_param(IS_PWR_WAKEUP_FLAG(WakeUpFlag)); + + /* Clear the wake up event received from wake up pin x */ + WRITE_REG(PWR->WKUPCR, WakeUpFlag); + + /* Check if the wake up event is well cleared */ + if ((PWR->WKUPFR & WakeUpFlag) != 0U) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief This function handles the PWR WAKEUP PIN interrupt request. + * @note This API should be called under the WAKEUP_PIN_IRQHandler(). + * @retval None. + */ +void HAL_PWREx_WAKEUP_PIN_IRQHandler(void) +{ + /* Wakeup pin EXTI line interrupt detected */ + if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF1) != 0U) + { + /* Clear PWR WKUPF1 flag */ + __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP1); + + /* PWR WKUP1 interrupt user callback */ + HAL_PWREx_WKUP1_Callback(); + } + + if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF2) != 0U) + { + /* Clear PWR WKUPF2 flag */ + __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP2); + + /* PWR WKUP2 interrupt user callback */ + HAL_PWREx_WKUP2_Callback(); + } + + if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF3) != 0U) + { + /* Clear PWR WKUPF3 flag */ + __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP3); + + /* PWR WKUP3 interrupt user callback */ + HAL_PWREx_WKUP3_Callback(); + } + + if (READ_BIT(PWR->WKUPFR, PWR_WKUPFR_WKUPF4) != 0U) + { + /* Clear PWR WKUPF4 flag */ + __HAL_PWR_CLEAR_WAKEUPFLAG(PWR_FLAG_WKUP4); + + /* PWR WKUP4 interrupt user callback */ + HAL_PWREx_WKUP4_Callback(); + } +} + +/** + * @brief PWR WKUP1 interrupt callback. + * @retval None. + */ +__weak void HAL_PWREx_WKUP1_Callback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PWREx_WKUP1Callback can be implemented in the user file + */ +} + +/** + * @brief PWR WKUP2 interrupt callback. + * @retval None. + */ +__weak void HAL_PWREx_WKUP2_Callback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PWREx_WKUP2Callback can be implemented in the user file + */ +} + +/** + * @brief PWR WKUP3 interrupt callback. + * @retval None. + */ +__weak void HAL_PWREx_WKUP3_Callback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PWREx_WKUP3Callback can be implemented in the user file + */ +} + +/** + * @brief PWR WKUP4 interrupt callback. + * @retval None. + */ +__weak void HAL_PWREx_WKUP4_Callback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PWREx_WKUP4Callback can be implemented in the user file + */ +} +/** + * @} + */ + +/** @defgroup PWREx_Exported_Functions_Group3 Peripherals Control Functions + * @brief Peripherals Control Functions + * +@verbatim + =============================================================================== + ##### Peripherals Control Functions ##### + =============================================================================== + + *** Main and Backup Regulators configuration *** + ================================================ + [..] + (+) The backup domain includes 4 Kbytes of backup SRAM accessible only + from the CPU, and addressed 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_PWREx_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_PWREx_ControlVoltageScaling(VOS) function which configure the VOS + bit in PWR_CSR4 register. + (+) The main internal regulator can be configured to operate in Low Power + mode when the system enters STOP mode to further reduce power + consumption. + This is done through HAL_PWREx_ControlStopModeVoltageScaling(SVOS) + function which configure the SVOS bit in PWR_CR1 register. + -@- Refer to the product datasheets for more details. + + *** USB Regulator configuration *** + =================================== + [..] + (+) The USB transceivers are supplied from a dedicated VDD33USB supply + that can be provided either by the integrated USB regulator, or by an + external USB supply. + (+) The USB regulator is enabled by HAL_PWREx_EnableUSBReg() function, the + VDD33USB is then provided from the USB regulator. + (+) When the USB regulator is enabled, the VDD33USB supply level detector + shall be enabled through HAL_PWREx_EnableUSBVoltageDetector() + function. + (+) The USB regulator is disabled through HAL_PWREx_DisableUSBReg() + function and VDD33USB can be provided from an external supply. In this + case VDD33USB and VDD50USB shall be connected together. + + *** VBAT battery charging *** + ============================= + [..] + (+) When VDD is present, the external battery connected to VBAT can be + charged through an internal resistance. VBAT charging can be performed + either through a 5 KOhm resistor or through a 1.5 KOhm resistor. + (+) VBAT charging is enabled by HAL_PWREx_EnableBatteryCharging + (ResistorValue) function with: + (++) ResistorValue: + (+++) PWR_BATTERY_CHARGING_RESISTOR_5: 5 KOhm resistor. + (+++) PWR_BATTERY_CHARGING_RESISTOR_1_5: 1.5 KOhm resistor. + (+) VBAT charging is disabled by HAL_PWREx_DisableBatteryCharging() + function. + +@endverbatim + * @{ + */ + +/** + * @brief Enable the Backup Regulator. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_PWREx_EnableBkUpReg(void) +{ + uint32_t tickstart; + + /* Enable the Backup regulator */ + SET_BIT(PWR->CSR1, PWR_CSR1_BREN); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait till Backup regulator ready flag is set */ + while ((PWR->CSR1 & PWR_CSR1_BRRDY) == 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Disable the Backup Regulator. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_PWREx_DisableBkUpReg(void) +{ + uint32_t tickstart; + + /* Disable the Backup regulator */ + CLEAR_BIT(PWR->CSR1, PWR_CSR1_BREN); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait till Backup regulator ready flag is reset */ + while ((PWR->CSR1 & PWR_CSR1_BRRDY) != 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Enable the USB Regulator. + * @retval None. + */ +void HAL_PWREx_EnableUSBReg(void) +{ + /* Enable the USB regulator */ + SET_BIT(PWR->CSR2, PWR_CSR2_USBREGEN); +} + +/** + * @brief Disable the USB Regulator. + * @retval None. + */ +void HAL_PWREx_DisableUSBReg(void) +{ + /* Disable the USB regulator */ + CLEAR_BIT(PWR->CSR2, PWR_CSR2_USBREGEN); +} + +/** + * @brief Enable the USB voltage level detector. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_PWREx_EnableUSBVoltageDetector(void) +{ + uint32_t tickstart; + + /* Enable the USB voltage detector */ + SET_BIT(PWR->CSR2, PWR_CSR2_USB33DEN); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait till the USB regulator ready flag is set */ + while ((PWR->CSR2 & PWR_CSR2_USB33RDY) == 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + return HAL_OK; +} + +/** + * @brief Disable the USB voltage level detector. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_PWREx_DisableUSBVoltageDetector(void) +{ + uint32_t tickstart; + + /* Disable the USB voltage detector */ + CLEAR_BIT(PWR->CSR2, PWR_CSR2_USB33DEN); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait till the USB regulator ready flag is reset */ + while ((PWR->CSR2 & PWR_CSR2_USB33RDY) != 0U) + { + if ((HAL_GetTick() - tickstart) > PWR_FLAG_SETTING_DELAY) + { + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Enable the USB HS regulator. + * @retval None. + */ +void HAL_PWREx_EnableUSBHSregulator(void) +{ + /* Enable the USB HS regulator */ + SET_BIT(PWR->CSR2, PWR_CSR2_USBHSREGEN); +} + +/** + * @brief Disable the USB HS regulator. + * @retval None. + */ +void HAL_PWREx_DisableUSBHSregulator(void) +{ + /* Disable the USB HS regulator */ + CLEAR_BIT(PWR->CSR2, PWR_CSR2_USBHSREGEN); +} + +/** + * @brief Enable UCPD configuration memorization in Standby. + * @retval None + * @note This function must be called just before entering Standby mode when using UCPD. + */ +void HAL_PWREx_EnableUCPDStandbyMode(void) +{ + /* Memorize UCPD configuration when entering standby mode */ + SET_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_STBY); +} + +/** + * @brief Disable UCPD configuration memorization in Standby. + * @note This function must be called on exiting the Standby mode and before any UCPD + * configuration update. + * @retval None + */ +void HAL_PWREx_DisableUCPDStandbyMode(void) +{ + CLEAR_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_STBY); +} + +/** + * @brief Enable dead battery behavior. + * @retval None + */ +void HAL_PWREx_EnableUCPDDeadBattery(void) +{ + /* Enable dead battery behavior */ + CLEAR_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_DBDIS); +} + +/** + * @brief Disable dead battery behavior. + * @retval None + */ +void HAL_PWREx_DisableUCPDDeadBattery(void) +{ + /* Disable dead battery behavior */ + SET_BIT(PWR->UCPDR, PWR_UCPDR_UCPD_DBDIS); +} + +/** + * @brief Enable the Battery charging. + * @note When VDD is present, charge the external battery through an internal + * resistor. + * It is automatically disabled in VBAT mode. + * @param ResistorValue : Specifies the charging resistor. + * This parameter can be one of the following values : + * @arg PWR_BATTERY_CHARGING_RESISTOR_5 : 5 KOhm resistor. + * @arg PWR_BATTERY_CHARGING_RESISTOR_1_5 : 1.5 KOhm resistor. + * @retval None. + */ +void HAL_PWREx_EnableBatteryCharging(uint32_t ResistorValue) +{ + /* Check the parameter */ + assert_param(IS_PWR_BATTERY_RESISTOR_SELECT(ResistorValue)); + + /* Specify the charging resistor and enable the Battery charging */ + MODIFY_REG(PWR->CSR2, (PWR_CSR2_VBRS | PWR_CSR2_VBE), (ResistorValue | PWR_CSR2_VBE)); + +} + +/** + * @brief Disable the Battery charging. + * @retval None. + */ +void HAL_PWREx_DisableBatteryCharging(void) +{ + /* Disable the Battery charging and restore default charging resistor value */ + CLEAR_BIT(PWR->CSR2, (PWR_CSR2_VBE | PWR_CSR2_VBRS)); +} + +/** + * @brief Enable the booster to guarantee the analog switch AC performance when + * the VDD supply voltage is below 2V7. + * @note The VDD supply voltage can be monitored through the PVD and the PLS + * field bits. + * @retval None. + */ +void HAL_PWREx_EnableAnalogBooster(void) +{ + /* Enable the Analog voltage */ + SET_BIT(PWR->CR1, PWR_CR1_AVDREADY); + + /* Enable VDDA booster */ + SET_BIT(PWR->CR1, PWR_CR1_BOOSTE); +} + +/** + * @brief Disable the analog booster. + * @retval None. + */ +void HAL_PWREx_DisableAnalogBooster(void) +{ + /* Disable VDDA booster */ + CLEAR_BIT(PWR->CR1, PWR_CR1_BOOSTE); + + /* Disable the Analog voltage */ + CLEAR_BIT(PWR->CR1, PWR_CR1_AVDREADY); +} + +/** + * @brief Enable the XSPIM_P1 interface. + * @note The XSPIM_P1 supply must be stable prior to setting + this bit. + * @retval None. + */ +void HAL_PWREx_EnableXSPIM1(void) +{ + SET_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM1); +} + +/** + * @brief Disable the XSPIM_P1 interface. + * @retval None. + */ +void HAL_PWREx_DisableXSPIM1(void) +{ + CLEAR_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM1); +} + +/** + * @brief Enable the XSPIM_P2 interface. + * @note The XSPIM_P2 supply must be stable prior to setting + this bit. + * @retval None. + */ +void HAL_PWREx_EnableXSPIM2(void) +{ + SET_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM2); +} + +/** + * @brief Disable the XSPIM_P2 interface. + * @retval None. + */ +void HAL_PWREx_DisableXSPIM2(void) +{ + CLEAR_BIT(PWR->CSR2, PWR_CSR2_EN_XSPIM2); +} + +/** + * @brief Configure the capacitor port + * @param PortCapacitor Select the Port + * This parameter can be one of the following values: + * @arg @ref PWR_CAPACITOR_PORT1 XSPI port 1 capacitor + * @arg @ref PWR_CAPACITOR_PORT2 XSPI port 2 capacitor + * @param PortCapacitorSetting Select the capacitor setting + * This parameter can be one of the following values: + * @arg @ref PWR_CAPACITOR_OFF XSPI Capacitor OFF + * @arg @ref PWR_CAPACITOR_ONE_THIRD_CAPACITANCE XSPI Capacitor set to 1/3 + * @arg @ref PWR_CAPACITOR_TWO_THIRD_CAPACITANCE XSPI Capacitor set to 2/3 + * @arg @ref PWR_CAPACITOR_FULL_CAPACITANCE XSPI Capacitor set to full capacitance + * @retval None. + */ +void HAL_PWREx_ConfigXSPIPortCap(uint32_t PortCapacitor, uint32_t PortCapacitorSetting) +{ + /* Check the parameters */ + assert_param(IS_PWR_CAPACITOR(PortCapacitor)); + assert_param(IS_PWR_CAPACITOR_SETTING(PortCapacitorSetting)); + + if (PortCapacitor == PWR_CAPACITOR_PORT1) + { + /* Set Port1 Capacitor setting */ + MODIFY_REG(PWR->CSR2, PWR_CSR2_XSPICAP1, PortCapacitorSetting); + } + else + { + /* Set Port2 Capacitor setting */ + MODIFY_REG(PWR->CSR2, PWR_CSR2_XSPICAP2, PortCapacitorSetting << (PWR_CSR2_XSPICAP2_Pos - PWR_CSR2_XSPICAP1_Pos)); + } +} + +/** + * @brief Get the capacitor port setting + * @param PortCapacitor Select the Port + * This parameter can be one of the following values: + * @arg @ref PWR_CAPACITOR_PORT1 XSPI port 1 capacitor + * @arg @ref PWR_CAPACITOR_PORT2 XSPI port 2 capacitor + * @retval The capacitor setting: + * @arg @ref PWR_CAPACITOR_OFF XSPI Capacitor OFF + * @arg @ref PWR_CAPACITOR_ONE_THIRD_CAPACITANCE XSPI Capacitor set to 1/3 + * @arg @ref PWR_CAPACITOR_TWO_THIRD_CAPACITANCE XSPI Capacitor set to 2/3 + * @arg @ref PWR_CAPACITOR_FULL_CAPACITANCE XSPI Capacitor set to full capacitance + */ +uint32_t HAL_PWREx_GetConfigXSPIPortCap(uint32_t PortCapacitor) +{ + uint32_t PortCapacitorSetting; + + /* Check the parameter */ + assert_param(IS_PWR_CAPACITOR(PortCapacitor)); + + if (PortCapacitor == PWR_CAPACITOR_PORT1) + { + /* Get Port1 Capacitor setting */ + PortCapacitorSetting = READ_BIT(PWR->CSR2, PWR_CSR2_XSPICAP1); + } + else + { + /* Get Port2 Capacitor setting */ + PortCapacitorSetting = (READ_BIT(PWR->CSR2, PWR_CSR2_XSPICAP2) >> (PWR_CSR2_XSPICAP2_Pos - PWR_CSR2_XSPICAP1_Pos)); + } + + return PortCapacitorSetting; +} + +/** + * @} + */ + +/** @defgroup PWREx_Exported_Functions_Group4 Power Monitoring functions + * @brief Power Monitoring functions + * +@verbatim + =============================================================================== + ##### Power Monitoring functions ##### + =============================================================================== + + *** VBAT and Temperature supervision *** + ======================================== + [..] + (+) The VBAT battery voltage supply can be monitored by comparing it with + two threshold levels: VBAThigh and VBATlow. VBATH flag and VBATL flags + in the PWR control register 2 (PWR_CR2), indicate if VBAT is higher or + lower than the threshold. + (+) The temperature can be monitored by comparing it with two threshold + levels, TEMPhigh and TEMPlow. TEMPH and TEMPL flags, in the PWR + control register 2 (PWR_CR2), indicate whether the device temperature + is higher or lower than the threshold. + (+) The VBAT and the temperature monitoring is enabled by + HAL_PWREx_EnableMonitoring() function and disabled by + HAL_PWREx_DisableMonitoring() function. + (+) The HAL_PWREx_GetVBATLevel() function returns the VBAT level which can + be : PWR_VBAT_BELOW_LOW_THRESHOLD or PWR_VBAT_ABOVE_HIGH_THRESHOLD or + PWR_VBAT_BETWEEN_HIGH_LOW_THRESHOLD. + (+) The HAL_PWREx_GetTemperatureLevel() function returns the Temperature + level which can be : + PWR_TEMP_BELOW_LOW_THRESHOLD or PWR_TEMP_ABOVE_HIGH_THRESHOLD or + PWR_TEMP_BETWEEN_HIGH_LOW_THRESHOLD. + + *** AVD configuration *** + ========================= + [..] + (+) The AVD is used to monitor the VDDA power supply by comparing it to a + threshold selected by the AVD Level (ALS[3:0] bits in the PWR_CR1 + register). + (+) A AVDO flag is available to indicate if VDDA is higher or lower + than the AVD threshold. This event is internally connected to the EXTI + line 16 to generate an interrupt if enabled. + It is configurable through __HAL_PWR_AVD_EXTI_ENABLE_IT() macro. + (+) The AVD is stopped in System Standby mode. + +@endverbatim + * @{ + */ + +/** + * @brief Enable the VBAT and temperature monitoring. + * @retval HAL status. + */ +void HAL_PWREx_EnableMonitoring(void) +{ + /* Enable the VBAT and Temperature monitoring */ + SET_BIT(PWR->CSR1, PWR_CSR1_MONEN); +} + +/** + * @brief Disable the VBAT and temperature monitoring. + * @retval HAL status. + */ +void HAL_PWREx_DisableMonitoring(void) +{ + /* Disable the VBAT and Temperature monitoring */ + CLEAR_BIT(PWR->CSR1, PWR_CSR1_MONEN); +} + +/** + * @brief Indicate whether the junction temperature is between, above or below + * the thresholds. + * @retval Temperature level. + */ +uint32_t HAL_PWREx_GetTemperatureLevel(void) +{ + uint32_t tempLevel; + uint32_t regValue; + + /* Read the temperature flags */ + regValue = READ_BIT(PWR->CSR1, (PWR_CSR1_TEMPH | PWR_CSR1_TEMPL)); + + /* Check if the temperature is below the threshold */ + if (regValue == PWR_CSR1_TEMPL) + { + tempLevel = PWR_TEMP_BELOW_LOW_THRESHOLD; + } + /* Check if the temperature is above the threshold */ + else if (regValue == PWR_CSR1_TEMPH) + { + tempLevel = PWR_TEMP_ABOVE_HIGH_THRESHOLD; + } + /* The temperature is between the thresholds */ + else + { + tempLevel = PWR_TEMP_BETWEEN_HIGH_LOW_THRESHOLD; + } + + return tempLevel; +} + +/** + * @brief Indicate whether the Battery voltage level is between, above or below + * the thresholds. + * @retval VBAT level. + */ +uint32_t HAL_PWREx_GetVBATLevel(void) +{ + uint32_t vbatLevel; + uint32_t regValue; + + /* Read the VBAT flags */ + regValue = READ_BIT(PWR->CSR1, (PWR_CSR1_VBATH | PWR_CSR1_VBATL)); + + /* Check if the VBAT is below the threshold */ + if (regValue == PWR_CSR1_VBATL) + { + vbatLevel = PWR_VBAT_BELOW_LOW_THRESHOLD; + } + /* Check if the VBAT is above the threshold */ + else if (regValue == PWR_CSR1_VBATH) + { + vbatLevel = PWR_VBAT_ABOVE_HIGH_THRESHOLD; + } + /* The VBAT is between the thresholds */ + else + { + vbatLevel = PWR_VBAT_BETWEEN_HIGH_LOW_THRESHOLD; + } + + return vbatLevel; +} + +/** + * @brief Configure the event mode and the voltage threshold detected by the + * Analog Voltage Detector (AVD). + * @param sConfigAVD : Pointer to an PWREx_AVDTypeDef structure that contains + * the configuration information for the AVD. + * @note Refer to the electrical characteristics of your device datasheet for + * more details about the voltage threshold corresponding to each + * detection level. + * @note As PVD and AVD share the same EXTI line, the EXTI operating mode to + * configure will replace a possible previous configuration done through + * HAL_PWR_ConfigPVD. + * @retval None. + */ +void HAL_PWREx_ConfigAVD(const PWREx_AVDTypeDef *sConfigAVD) +{ + /* Check the parameters */ + assert_param(IS_PWR_AVD_LEVEL(sConfigAVD->AVDLevel)); + assert_param(IS_PWR_AVD_MODE(sConfigAVD->Mode)); + + /* Set the ALS[18:17] bits according to AVDLevel value */ + MODIFY_REG(PWR->CR1, PWR_CR1_ALS, sConfigAVD->AVDLevel); + + /* Clear any previous config */ + __HAL_PWR_AVD_EXTI_DISABLE_EVENT(); + __HAL_PWR_AVD_EXTI_DISABLE_IT(); + + __HAL_PWR_AVD_EXTI_DISABLE_RISING_EDGE(); + __HAL_PWR_AVD_EXTI_DISABLE_FALLING_EDGE(); + + /* Configure the interrupt mode */ + if ((sConfigAVD->Mode & AVD_MODE_IT) == AVD_MODE_IT) + { + __HAL_PWR_AVD_EXTI_ENABLE_IT(); + } + + /* Configure the event mode */ + if ((sConfigAVD->Mode & AVD_MODE_EVT) == AVD_MODE_EVT) + { + __HAL_PWR_AVD_EXTI_ENABLE_EVENT(); + } + + /* Rising edge configuration */ + if ((sConfigAVD->Mode & AVD_RISING_EDGE) == AVD_RISING_EDGE) + { + __HAL_PWR_AVD_EXTI_ENABLE_RISING_EDGE(); + } + + /* Falling edge configuration */ + if ((sConfigAVD->Mode & AVD_FALLING_EDGE) == AVD_FALLING_EDGE) + { + __HAL_PWR_AVD_EXTI_ENABLE_FALLING_EDGE(); + } +} + +/** + * @brief Enable the Analog Voltage Detector (AVD). + * @retval None. + */ +void HAL_PWREx_EnableAVD(void) +{ + /* Enable the Analog Voltage Detector */ + SET_BIT(PWR->CR1, PWR_CR1_AVDEN); +} + +/** + * @brief Disable the Analog Voltage Detector(AVD). + * @retval None. + */ +void HAL_PWREx_DisableAVD(void) +{ + /* Disable the Analog Voltage Detector */ + CLEAR_BIT(PWR->CR1, PWR_CR1_AVDEN); +} + +/** + * @brief This function handles the PWR PVD/AVD interrupt request. + * @note This API should be called under the PVD_AVD_IRQHandler(). + * @retval None + */ +void HAL_PWREx_PVD_AVD_IRQHandler(void) +{ + /* Check PWR EXTI flags for PVD/AVD */ + if (((EXTI->PR1) & EXTI_PR1_PR16) != 0U) + { + /* Clear PVD/AVD exti pending bit */ + WRITE_REG(EXTI->PR1, EXTI_PR1_PR16); + + /* PWR PVD/AVD interrupt user callback */ + HAL_PWREx_PVD_AVD_Callback(); + } +} + +/** + * @brief PWR PVD/AVD interrupt callback. + * @retval None. + */ +__weak void HAL_PWREx_PVD_AVD_Callback(void) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_PWREx_PVD_AVD_Callback can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PWREx_Exported_Functions_Group5 I/O Pull-Up Pull-Down Configuration Functions + * @brief I/O pull-up / pull-down configuration functions + * +@verbatim + =============================================================================== + ##### Voltage monitoring Functions ##### + =============================================================================== + [..] + In Standby mode, pull up and pull down can be configured to + maintain an I/O in the selected state. If the APC bit in the PWR_APCR + register is set, the I/Os can be configured either with a pull-up through + PWR_PUCRx registers (x=N,O), or with a pull-down through + PWR_PDCRx registers (x=N,O,P), or can be kept in analog state + if none of the PWR_PUCRx or PWR_PDCRx register is set. + + [..] + The pull-down configuration has highest priority over pull-up + configuration in case both PWR_PUCRx and PWR_PDCRx are set for the same + I/O. + +@endverbatim + * @{ + */ + +/** + * @brief Enable pull-up and pull-down configuration. + * @note When APC bit is set, the I/O pull-up and pull-down configurations + * defined in PWR_PUCRx and PWR_PDCRx registers are applied in Standby + * mode. + * @note Pull-up set by PUy bit of PWR_PUCRx register is not activated if the + * corresponding PDy bit of PWR_PDCRx register is also set (pull-down + * configuration priority is higher). HAL_PWREx_EnableGPIOPullUp() and + * HAL_PWREx_EnableGPIOPullDown() API's ensure there is no conflict + * when setting PUy or PDy bit. + * @retval None. + */ +void HAL_PWREx_EnablePullUpPullDownConfig(void) +{ + SET_BIT(PWR->APCR, PWR_APCR_APC); +} + +/** + * @brief Disable pull-up and pull-down configuration. + * @note When APC bit is cleared, the I/O pull-up and pull-down configurations + * defined in PWR_PUCRx and PWR_PDCRx registers are not applied in + * Standby mode. + * @retval None. + */ +void HAL_PWREx_DisablePullUpPullDownConfig(void) +{ + CLEAR_BIT(PWR->APCR, PWR_APCR_APC); +} + +/** + * @brief Enable GPIO pull-up state in Standby mode. + * @note Set the relevant PUy bits of PWR_PUCRx register to configure the I/O in + * pull-up state in Standby mode. + * @note This state is effective in Standby mode only if APC bit + * is set through HAL_PWREx_EnablePullUpPullDownConfig() API. + * @note The configuration is maintained when exiting the Standby mode. + * @note Even if a PUy bit to set is reserved, the other PUy bits entered as + * input parameter at the same time are set. + * @note The pullup is not activated if the corresponding PDy bit is also set. + * @param GPIO_Port : Specify the IO port. + * This parameter can be a value of @ref PWREx_GPIO_PullUp_Port. + * @param GPIO_Pin : Specify the I/O pins numbers. + * This parameter can be a combination of @ref PWREx_GPIO_PullUp_Pin_Mask. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullUp(uint32_t GPIO_Port, uint32_t GPIO_Pin) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_PWR_GPIO_PULLPUP_PORT(GPIO_Port)); + assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); + + switch (GPIO_Port) + { + case PWR_GPIO_PULLUP_PORT_N: + SET_BIT(PWR->PUCRN, GPIO_Pin); + break; + + case PWR_GPIO_PULLUP_PORT_O: + SET_BIT(PWR->PUCRO, GPIO_Pin); + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Disable GPIO pull-up state in Standby mode. + * @note Reset the relevant PUy bits of PWR_PUCRx register used to configure the I/O + * in pull-up state in Standby mode. + * @note Even if a PUy bit to reset is reserved, the other PUy bits entered as input + * parameter at the same time are reset. + * @param GPIO_Port : Specify the IO port. + * This parameter can be a value of @ref PWREx_GPIO_PullUp_Port. + * @param GPIO_Pin : Specify the I/O pins numbers. + * This parameter can be a combination of @ref PWREx_GPIO_PullUp_Pin_Mask. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullUp(uint32_t GPIO_Port, uint32_t GPIO_Pin) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_PWR_GPIO_PULLPUP_PORT(GPIO_Port)); + assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); + + switch (GPIO_Port) + { + case PWR_GPIO_PULLUP_PORT_N: + CLEAR_BIT(PWR->PUCRN, GPIO_Pin); + break; + + case PWR_GPIO_PULLUP_PORT_O: + CLEAR_BIT(PWR->PUCRO, GPIO_Pin); + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Enable GPIO pull-down state in Standby mode. + * @note Set the relevant PDy bits of PWR_PDCRx register to configure the I/O in + * pull-down state in Standby mode. + * @note This state is effective in Standby mode only if APC bit + * is set through HAL_PWREx_EnablePullUpPullDownConfig() API. + * @note The configuration is maintained when exiting the Standby mode. + * @note Even if a PDy bit to set is reserved, the other PDy bits entered as input + * parameter at the same time are set. + * @param GPIO_Port : Specify the IO port. + * This parameter can be a value of @ref PWREx_GPIO_PullDown_Port. + * @param GPIO_Pin : Specify the I/O pins numbers. + * This parameter can be a combination of @ref PWREx_GPIO_PullDown_Pin_Mask. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_PWREx_EnableGPIOPullDown(uint32_t GPIO_Port, uint32_t GPIO_Pin) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_PWR_GPIO_PULLDOWN_PORT(GPIO_Port)); + assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); + + switch (GPIO_Port) + { + case PWR_GPIO_PULLDOWN_PORT_N: + SET_BIT(PWR->PDCRN, GPIO_Pin); + break; + + case PWR_GPIO_PULLDOWN_PORT_O: + SET_BIT(PWR->PDCRO, GPIO_Pin); + break; + + case PWR_GPIO_PULLDOWN_PORT_P: + SET_BIT(PWR->PDCRP, GPIO_Pin); + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Disable GPIO pull-down state in Standby mode. + * @note Reset the relevant PDy bits of PWR_PDCRx register used to configure the I/O + * in pull-down state in Standby mode. + * @note Even if a PDy bit to reset is reserved, the other PDy bits entered as input + * parameter at the same time are reset. + * @param GPIO_Port : Specify the IO port. + * This parameter can be a value of @ref PWREx_GPIO_PullDown_Port. + * @param GPIO_Pin : Specify the I/O pins numbers. + * This parameter can be a value of @ref PWREx_GPIO_PullDown_Pin_Mask. + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_PWREx_DisableGPIOPullDown(uint32_t GPIO_Port, uint32_t GPIO_Pin) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_PWR_GPIO_PULLDOWN_PORT(GPIO_Port)); + assert_param(IS_PWR_GPIO_PIN_MASK(GPIO_Pin)); + + switch (GPIO_Port) + { + case PWR_GPIO_PULLDOWN_PORT_N: + CLEAR_BIT(PWR->PDCRN, GPIO_Pin); + break; + + case PWR_GPIO_PULLDOWN_PORT_O: + CLEAR_BIT(PWR->PDCRO, GPIO_Pin); + break; + + case PWR_GPIO_PULLDOWN_PORT_P: + CLEAR_BIT(PWR->PDCRP, GPIO_Pin); + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_PWR_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ramecc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ramecc.c index c1b69e253..c696f4edf 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ramecc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_ramecc.c @@ -1,966 +1,965 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_ramecc.c - * @author MCD Application Team - * @brief RAMECC HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the RAM ECC monitoring (RAMECC) peripheral: - * + Initialization and de-initialization functions - * + Monitoring operation functions - * + Error information functions - * + State and error functions - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Enable and latch error information through HAL_RAMECC_Init(). - - (#) For a given Monitor, enable and disable interrupt through - HAL_RAMECC_EnableNotification(). - To enable a notification for a given RAMECC instance, use global - interrupts. - To enable a notification for only RAMECC monitor, use monitor interrupts. - All possible notifications are defined in the driver header file under - RAMECC_Interrupt group. - - *** Silent mode *** - =================== - [..] - (+) Use HAL_RAMECC_StartMonitor() to start RAMECC latch failing - information without enabling any notification. - - *** Interrupt mode *** - ====================== - [..] - (+) Use HAL_RAMECC_EnableNotification() to enable interrupts for a - given error. - (+) Configure the RAMECC interrupt priority using - HAL_NVIC_SetPriority(). - (+) Enable the RAMECC IRQ handler using HAL_NVIC_EnableIRQ(). - (+) Start RAMECC latch failing information using HAL_RAMECC_StartMonitor(). - - *** Failing information *** - ====================== - [..] - (#) Use HAL_RAMECC_GetFailingAddress() function to return the RAMECC - failing address. - (#) Use HAL_RAMECC_GetFailingDataLow() function to return the RAMECC - failing data low. - (#) Use HAL_RAMECC_GetFailingDataHigh() function to return the RAMECC - failing data high. - (#) Use HAL_RAMECC_GetHammingErrorCode() function to return the RAMECC - Hamming bits injected. - (#) Use HAL_RAMECC_IsECCSingleErrorDetected() function to check if a single - error was detected and corrected. - (#) Use HAL_RAMECC_IsECCDoubleErrorDetected() function to check if a double - error was dedetected. - - *** RAMECC HAL driver macros list *** - ============================================= - [..] - Below the list of used macros in RAMECC HAL driver. - - (+) __HAL_RAMECC_ENABLE_IT : Enable the specified ECCRAM Monitor - interrupts. - (+) __HAL_RAMECC_DISABLE_IT : Disable the specified ECCRAM Monitor - interrupts. - (+) __HAL_RAMECC_GET_FLAG : Return the current RAMECC Monitor selected - flag. - (+) __HAL_RAMECC_CLEAR_FLAG : Clear the current RAMECC Monitor selected - flag. - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup RAMECC RAMECC - * @brief RAMECC HAL module driver - * @{ - */ - -#ifdef HAL_RAMECC_MODULE_ENABLED - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup RAMECC_Exported_Functions - * @{ - */ - -/** @addtogroup RAMECC_Exported_Functions_Group1 - * -@verbatim - =============================================================================== - ##### Initialization and de-initialization functions ##### - =============================================================================== - [..] - This section provides functions allowing to initialize the RAMECC Monitor. - [..] - The HAL_RAMECC_Init() function follows the RAMECC configuration procedures - as described in reference manual. - The HAL_RAMECC_DeInit() function allows to deinitialize the RAMECC monitor. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the RAMECC by clearing flags and disabling interrupts. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_Init(RAMECC_HandleTypeDef *hramecc) -{ - /* Check the RAMECC peripheral handle */ - if (hramecc == NULL) - { - /* Return HAL status */ - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_BUSY; - -#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) - /* Check if a valid MSP API was registered */ - if (hramecc->MspInitCallback == NULL) - { - /* Init the low level hardware */ - hramecc->MspInitCallback = HAL_RAMECC_MspInit; - } - - /* Init the low level hardware */ - hramecc->MspInitCallback(hramecc); -#else - HAL_RAMECC_MspInit(hramecc); -#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ - - /* Disable RAMECC monitor */ - hramecc->Instance->CR &= ~RAMECC_CR_ECCELEN; - - /* Disable all global interrupts */ - ((RAMECC_TypeDef *)((uint32_t)hramecc->Instance & 0xFFFFFF00U))->IER &= \ - ~(RAMECC_IER_GIE | RAMECC_IER_GECCSEIE | RAMECC_IER_GECCDEIE | RAMECC_IER_GECCDEBWIE); - - /* Disable all interrupts monitor */ - hramecc->Instance->CR &= ~(RAMECC_CR_ECCSEIE | RAMECC_CR_ECCDEIE | RAMECC_CR_ECCDEBWIE); - - /* Clear RAMECC monitor flags */ - __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAGS_ALL); - - /* Initialise the RAMECC error code */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_NONE; - - /* Update the RAMECC state */ - hramecc->State = HAL_RAMECC_STATE_READY; - - /* Return HAL status */ - return HAL_OK; -} - - -/** - * @brief DeInitializes the RAMECC peripheral. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_DeInit(RAMECC_HandleTypeDef *hramecc) -{ - /* Check the RAMECC peripheral handle */ - if (hramecc == NULL) - { - /* Return HAL status */ - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Disable RAMECC monitor */ - hramecc->Instance->CR &= ~RAMECC_CR_ECCELEN; - - /* Disable all global interrupts */ - ((RAMECC_TypeDef *)((uint32_t)hramecc->Instance & 0xFFFFFF00U))->IER &= \ - ~(RAMECC_IER_GIE | RAMECC_IER_GECCSEIE | RAMECC_IER_GECCDEIE | RAMECC_IER_GECCDEBWIE); - - /* Disable all interrupts monitor */ - hramecc->Instance->CR &= ~(RAMECC_CR_ECCSEIE | RAMECC_CR_ECCDEIE | RAMECC_CR_ECCDEBWIE); - - /* Clear RAMECC monitor flags */ - __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAGS_ALL); - - -#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) - /* Check if a valid MSP API was registered */ - if (hramecc->MspDeInitCallback != NULL) - { - /* Init the low level hardware */ - hramecc->MspDeInitCallback(hramecc); - } - - /* Clean callbacks */ - hramecc->DetectSingleErrorCallback = NULL; - hramecc->DetectDoubleErrorCallback = NULL; -#else - HAL_RAMECC_MspDeInit(hramecc); -#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ - - /* Initialise the RAMECC error code */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_NONE; - - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_RESET; - - /* Return HAL status */ - return HAL_OK; -} - -/** - * @brief Initialize the RAMECC MSP. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC. - * @retval None. - */ -__weak void HAL_RAMECC_MspInit(RAMECC_HandleTypeDef *hramecc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hramecc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RAMECC_MspInit can be implemented in the user file */ -} - -/** - * @brief DeInitialize the RAMECC MSP. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC. - * @retval None. - */ -__weak void HAL_RAMECC_MspDeInit(RAMECC_HandleTypeDef *hramecc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hramecc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RAMECC_MspDeInit can be implemented in the user file */ -} -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup RAMECC_Exported_Functions_Group2 - * -@verbatim - =============================================================================== - ##### Monitoring operation functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure latching error information. - (+) Configure RAMECC Global/Monitor interrupts. - (+) Register and Unregister RAMECC callbacks - (+) Handle RAMECC interrupt request - -@endverbatim - * @{ - */ - -/** - * @brief Starts the RAMECC latching error information. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_StartMonitor(RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Check RAMECC state */ - if (hramecc->State == HAL_RAMECC_STATE_READY) - { - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_BUSY; - - /* Enable RAMECC monitor */ - hramecc->Instance->CR |= RAMECC_CR_ECCELEN; - - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_READY; - } - else - { - /* Update the error code */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; - - /* Return HAL status */ - return HAL_ERROR; - } - - /* Return HAL status */ - return HAL_OK; -} - - -/** - * @brief Stop the RAMECC latching error information. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_StopMonitor(RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Check RAMECC state */ - if (hramecc->State == HAL_RAMECC_STATE_READY) - { - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_BUSY; - - /* Disable RAMECC monitor */ - hramecc->Instance->CR &= ~RAMECC_CR_ECCELEN; - - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_READY; - } - else - { - /* Update the error code */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; - - /* Return HAL status */ - return HAL_ERROR; - } - - /* Return HAL status */ - return HAL_OK; -} - - -/** - * @brief Enable the RAMECC error interrupts. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that - * contains the configuration information for the - * specified RAMECC Monitor. - * @param Notifications Select the notification. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_EnableNotification(RAMECC_HandleTypeDef *hramecc, uint32_t Notifications) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - assert_param(IS_RAMECC_INTERRUPT(Notifications)); - - /* Check RAMECC state */ - if (hramecc->State == HAL_RAMECC_STATE_READY) - { - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_BUSY; - - /* Enable RAMECC interrupts */ - __HAL_RAMECC_ENABLE_IT(hramecc, Notifications); - - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_READY; - } - else - { - /* Update the error code */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; - - /* Return HAL status */ - return HAL_ERROR; - } - - /* Return HAL status */ - return HAL_OK; -} - - -/** - * @brief Disable the RAMECC error interrupts. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that - * contains the configuration information for the - * specified RAMECC Monitor. - * @param Notifications Select the notification. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_DisableNotification(RAMECC_HandleTypeDef *hramecc, uint32_t Notifications) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - assert_param(IS_RAMECC_INTERRUPT(Notifications)); - - /* Check RAMECC state */ - if (hramecc->State == HAL_RAMECC_STATE_READY) - { - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_BUSY; - - /* Disable RAMECC interrupts */ - __HAL_RAMECC_DISABLE_IT(hramecc, Notifications); - - /* Change RAMECC peripheral state */ - hramecc->State = HAL_RAMECC_STATE_READY; - } - else - { - /* Update the error code */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; - - /* Return HAL status */ - return HAL_ERROR; - } - - /* Return HAL status */ - return HAL_OK; -} - - -/** @addtogroup RAMCECC_Exported_Functions_Group3 - * -@verbatim - =============================================================================== - ##### Handle Interrupt and Callbacks Functions ##### - =============================================================================== - [..] - This section provides functions to handle RAMECC interrupts and - Register / UnRegister the different callbacks. - [..] - The HAL_RAMECC_IRQHandler() function allows handling the active RAMECC - interrupt request. - The HAL_RAMECC_RegisterCallback() function allows registering the selected - RAMECC callbacks. - The HAL_RAMECC_UnRegisterCallback() function allows unregistering the - selected RAMECC callbacks. -@endverbatim - * @{ - */ - -/** - * @brief Handles RAMECC interrupt request. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval None. - */ -void HAL_RAMECC_IRQHandler(RAMECC_HandleTypeDef *hramecc) -{ - uint32_t monitor_it_source; - uint32_t global_it_source; - - monitor_it_source = READ_REG(hramecc->Instance->CR); - global_it_source = READ_REG(((RAMECC_TypeDef *)((uint32_t)hramecc->Instance & 0xFFFFFF00U))->IER); - - /* Single Error Interrupt Management ****************************************/ - if (((monitor_it_source & RAMECC_CR_ECCSEIE) == RAMECC_CR_ECCSEIE) || - ((global_it_source & RAMECC_IER_GECCSEIE) == RAMECC_IER_GECCSEIE) || - ((global_it_source & RAMECC_IER_GIE) == RAMECC_IER_GIE)) - { - if (__HAL_RAMECC_GET_FLAG(hramecc, RAMECC_FLAG_SINGLEERR_R) != 0U) - { - /* Clear active flags */ - __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAG_SINGLEERR_R); - -#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) - /* Check if a valid single error callback is registered */ - if (hramecc->DetectSingleErrorCallback != NULL) - { - /* Single error detection callback */ - hramecc->DetectSingleErrorCallback(hramecc); - } -#else - HAL_RAMECC_DetectSingleErrorCallback(hramecc); -#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ - } - } - - /* Double Error Interrupt Management ****************************************/ - if (((monitor_it_source & RAMECC_CR_ECCDEIE) == RAMECC_CR_ECCDEIE) || - ((monitor_it_source & RAMECC_CR_ECCDEBWIE) == RAMECC_CR_ECCDEBWIE) || - ((global_it_source & RAMECC_IER_GECCDEIE) == RAMECC_IER_GECCDEIE) || - ((global_it_source & RAMECC_IER_GECCDEBWIE) == RAMECC_IER_GECCDEBWIE) || - ((global_it_source & RAMECC_IER_GIE) == RAMECC_IER_GIE)) - { - /* ECC double error detected flag */ - if (__HAL_RAMECC_GET_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_R) != 0U) - { - /* Clear active flags */ - __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_R); - -#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) - /* Check if a valid Double error callback is registered */ - if (hramecc->DetectDoubleErrorCallback != NULL) - { - /* Double error detection callback */ - hramecc->DetectDoubleErrorCallback(hramecc); - } -#else - HAL_RAMECC_DetectDoubleErrorCallback(hramecc); -#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ - } - - /* ECC double error on byte write */ - if (__HAL_RAMECC_GET_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_W) != 0U) - { - /* Clear active flags */ - __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_W); - -#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) - /* Check if a valid Double error callback is registered */ - if (hramecc->DetectDoubleErrorCallback != NULL) - { - /* Double error detection callback */ - hramecc->DetectDoubleErrorCallback(hramecc); - } -#else - HAL_RAMECC_DetectDoubleErrorCallback(hramecc); -#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief RAMECC single error detection callback. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC. - * @retval None. - */ -__weak void HAL_RAMECC_DetectSingleErrorCallback(RAMECC_HandleTypeDef *hramecc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hramecc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RAMECC_DetectSingleErrorCallback can be implemented in - the user file. */ -} - -/** - * @brief RAMECC double error detection callback. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC. - * @retval None. - */ -__weak void HAL_RAMECC_DetectDoubleErrorCallback(RAMECC_HandleTypeDef *hramecc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hramecc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RAMECC_DetectDoubleErrorCallback can be implemented in - the user file. */ -} - -#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) -/** - * @brief Register RAMECC callbacks. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that - * contains the configuration information for the - * specified RAMECC instance. - * @param CallbackID : User Callback identifier a HAL_RAMECC_CallbackIDTypeDef - * ENUM as parameter. - * @param pCallback : Pointer to private callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_RegisterCallback(RAMECC_HandleTypeDef *hramecc, - HAL_RAMECC_CallbackIDTypeDef CallbackID, - void (* pCallback)(RAMECC_HandleTypeDef *_hramecc)) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code and return error */ - hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Check RAMECC state */ - if (hramecc->State == HAL_RAMECC_STATE_READY) - { - switch (CallbackID) - { - case HAL_RAMECC_SE_DETECT_CB_ID: - /* Register single error callback */ - hramecc->DetectSingleErrorCallback = pCallback; - break; - - case HAL_RAMECC_DE_DETECT_CB_ID: - /* Register double error callback */ - hramecc->DetectDoubleErrorCallback = pCallback; - break; - - case HAL_RAMECC_MSPINIT_CB_ID : - /* Register msp init callback */ - hramecc->MspInitCallback = pCallback; - break; - - case HAL_RAMECC_MSPDEINIT_CB_ID : - /* Register msp de-init callback */ - hramecc->MspDeInitCallback = pCallback; - break; - - default: - /* Update the error code and return error */ - hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else if (hramecc->State == HAL_RAMECC_STATE_RESET) - { - switch (CallbackID) - { - case HAL_RAMECC_MSPINIT_CB_ID : - /* Register msp init callback */ - hramecc->MspInitCallback = pCallback; - break; - - case HAL_RAMECC_MSPDEINIT_CB_ID : - /* Register msp de-init callback */ - hramecc->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code and return error */ - hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code and return error */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister RAMECC callbacks. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that - * contains the configuration information for the - * specified RAMECC instance. - * @param CallbackID : User Callback identifier a HAL_RAMECC_CallbackIDTypeDef - * ENUM as parameter. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_RAMECC_UnRegisterCallback(RAMECC_HandleTypeDef *hramecc, HAL_RAMECC_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Check RAMECC state */ - if (hramecc->State == HAL_RAMECC_STATE_READY) - { - switch (CallbackID) - { - case HAL_RAMECC_SE_DETECT_CB_ID: - /* UnRegister single error callback */ - hramecc->DetectSingleErrorCallback = NULL; - break; - - case HAL_RAMECC_DE_DETECT_CB_ID: - /* UnRegister double error callback */ - hramecc->DetectDoubleErrorCallback = NULL; - break; - - case HAL_RAMECC_MSPINIT_CB_ID : - /* UnRegister msp init callback */ - hramecc->MspInitCallback = NULL; - break; - - case HAL_RAMECC_MSPDEINIT_CB_ID : - /* UnRegister msp de-init callback */ - hramecc->MspDeInitCallback = NULL; - break; - - case HAL_RAMECC_ALL_CB_ID: - /* UnRegister all available callbacks */ - hramecc->DetectSingleErrorCallback = NULL; - hramecc->DetectDoubleErrorCallback = NULL; - hramecc->MspDeInitCallback = NULL; - hramecc->MspInitCallback = NULL; - break; - - default: - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hramecc->State == HAL_RAMECC_STATE_RESET) - { - switch (CallbackID) - { - case HAL_RAMECC_MSPINIT_CB_ID : - /* UnRegister msp init callback */ - hramecc->MspInitCallback = NULL; - break; - - case HAL_RAMECC_MSPDEINIT_CB_ID : - /* UnRegister msp de-init callback */ - hramecc->MspDeInitCallback = NULL; - break; - - case HAL_RAMECC_ALL_CB_ID: - /* UnRegister all available callbacks */ - hramecc->MspDeInitCallback = NULL; - hramecc->MspInitCallback = NULL; - break; - - default : - /* Update the error code */ - hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; - - /* Update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code and return error */ - hramecc->ErrorCode = HAL_RAMECC_ERROR_INVALID_CALLBACK; - status = HAL_ERROR; - } - - return status; -} -/** - * @} - */ -#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ -/** - * @} - */ - -/** @addtogroup RAMECC_Exported_Functions_Group4 - * -@verbatim - =============================================================================== - ##### Error information functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Get failing address. - (+) Get failing data low. - (+) Get failing data high. - (+) Get hamming bits injected. - (+) Check single error flag. - (+) Check double error flag. - -@endverbatim - * @{ - */ - -/** - * @brief Return the RAMECC failing address. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval Failing address offset. - */ -uint32_t HAL_RAMECC_GetFailingAddress(const RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Return failing address */ - return hramecc->Instance->FAR; -} - - -/** - * @brief Return the RAMECC data low. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval Failing data low. - */ -uint32_t HAL_RAMECC_GetFailingDataLow(const RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Return failing data low */ - return hramecc->Instance->FDRL; -} - - -/** - * @brief Return the RAMECC data high. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval Failing data high. - */ -uint32_t HAL_RAMECC_GetFailingDataHigh(const RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Return failing data high */ - return hramecc->Instance->FDRH; -} - - -/** - * @brief Return the RAMECC Hamming bits injected. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval Hamming bits injected. - */ -uint32_t HAL_RAMECC_GetHammingErrorCode(const RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Return hamming bits injected */ - return hramecc->Instance->FECR; -} - -/** - * @brief Check if an ECC single error was occurred. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval State of bit (1 or 0). - */ -uint32_t HAL_RAMECC_IsECCSingleErrorDetected(const RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Return the state of SEDC flag */ - return ((READ_BIT(hramecc->Instance->SR, RAMECC_SR_SEDCF) == (RAMECC_SR_SEDCF)) ? 1UL : 0UL); -} - -/** - * @brief Check if an ECC double error was occurred. - * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains - * the configuration information for the specified RAMECC - * Monitor. - * @retval State of bit (1 or 0). - */ -uint32_t HAL_RAMECC_IsECCDoubleErrorDetected(const RAMECC_HandleTypeDef *hramecc) -{ - /* Check the parameters */ - assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); - - /* Return the state of DEDF | DEBWDF flags */ - return ((READ_BIT(hramecc->Instance->SR, (RAMECC_SR_DEDF | RAMECC_SR_DEBWDF)) != 0U) ? 1UL : 0UL); -} -/** - * @} - */ - - -/** @addtogroup RAMECC_Exported_Functions_Group5 - * -@verbatim - =============================================================================== - ##### State and Error Functions ##### - =============================================================================== - [..] - This section provides functions allowing to check and get the RAMECC state - and the error code . - [..] - The HAL_RAMECC_GetState() function allows to get the RAMECC peripheral - state. - The HAL_RAMECC_GetError() function allows to Get the RAMECC peripheral error - code. - -@endverbatim - * @{ - */ - -/** - * @brief Get the RAMECC peripheral state. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that - * contains the configuration information for the - * specified RAMECC instance. - * @retval RAMECC state. - */ -HAL_RAMECC_StateTypeDef HAL_RAMECC_GetState(const RAMECC_HandleTypeDef *hramecc) -{ - /* Return the RAMECC state */ - return hramecc->State; -} - -/** - * @brief Get the RAMECC peripheral error code. - * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that - * contains the configuration information for the - * specified RAMECC instance. - * @retval RAMECC error code. - */ -uint32_t HAL_RAMECC_GetError(const RAMECC_HandleTypeDef *hramecc) -{ - /* Return the RAMECC error code */ - return hramecc->ErrorCode; -} -/** - * @} - */ -#endif /* HAL_RAMECC_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_ramecc.c + * @author MCD Application Team + * @brief RAMECC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the RAM ECC monitoring (RAMECC) peripheral: + * + Initialization and de-initialization functions + * + Monitoring operation functions + * + Error information functions + * + State and error functions + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable and latch error information through HAL_RAMECC_Init(). + + (#) For a given Monitor, enable and disable interrupt through + HAL_RAMECC_EnableNotification(). + To enable a notification for a given RAMECC instance, use global + interrupts. + To enable a notification for only RAMECC monitor, use monitor interrupts. + All possible notifications are defined in the driver header file under + RAMECC_Interrupt group. + + *** Silent mode *** + =================== + [..] + (+) Use HAL_RAMECC_StartMonitor() to start RAMECC latch failing + information without enabling any notification. + + *** Interrupt mode *** + ====================== + [..] + (+) Use HAL_RAMECC_EnableNotification() to enable interrupts for a + given error. + (+) Configure the RAMECC interrupt priority using + HAL_NVIC_SetPriority(). + (+) Enable the RAMECC IRQ handler using HAL_NVIC_EnableIRQ(). + (+) Start RAMECC latch failing information using HAL_RAMECC_StartMonitor(). + + *** Failing information *** + ====================== + [..] + (#) Use HAL_RAMECC_GetFailingAddress() function to return the RAMECC + failing address. + (#) Use HAL_RAMECC_GetFailingDataLow() function to return the RAMECC + failing data low. + (#) Use HAL_RAMECC_GetFailingDataHigh() function to return the RAMECC + failing data high. + (#) Use HAL_RAMECC_GetHammingErrorCode() function to return the RAMECC + Hamming bits injected. + (#) Use HAL_RAMECC_IsECCSingleErrorDetected() function to check if a single + error was detected and corrected. + (#) Use HAL_RAMECC_IsECCDoubleErrorDetected() function to check if a double + error was dedetected. + + *** RAMECC HAL driver macros list *** + ============================================= + [..] + Below the list of used macros in RAMECC HAL driver. + + (+) __HAL_RAMECC_ENABLE_IT : Enable the specified ECCRAM Monitor + interrupts. + (+) __HAL_RAMECC_DISABLE_IT : Disable the specified ECCRAM Monitor + interrupts. + (+) __HAL_RAMECC_GET_FLAG : Return the current RAMECC Monitor selected + flag. + (+) __HAL_RAMECC_CLEAR_FLAG : Clear the current RAMECC Monitor selected + flag. + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup RAMECC RAMECC + * @brief RAMECC HAL module driver + * @{ + */ + +#ifdef HAL_RAMECC_MODULE_ENABLED + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup RAMECC_Exported_Functions + * @{ + */ + +/** @addtogroup RAMECC_Exported_Functions_Group1 + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + This section provides functions allowing to initialize the RAMECC Monitor. + [..] + The HAL_RAMECC_Init() function follows the RAMECC configuration procedures + as described in reference manual. + The HAL_RAMECC_DeInit() function allows to deinitialize the RAMECC monitor. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the RAMECC by clearing flags and disabling interrupts. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_Init(RAMECC_HandleTypeDef *hramecc) +{ + /* Check the RAMECC peripheral handle */ + if (hramecc == NULL) + { + /* Return HAL status */ + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_BUSY; + +#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) + /* Check if a valid MSP API was registered */ + if (hramecc->MspInitCallback == NULL) + { + /* Init the low level hardware */ + hramecc->MspInitCallback = HAL_RAMECC_MspInit; + } + + /* Init the low level hardware */ + hramecc->MspInitCallback(hramecc); +#else + HAL_RAMECC_MspInit(hramecc); +#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ + + /* Disable RAMECC monitor */ + hramecc->Instance->CR &= ~RAMECC_CR_ECCELEN; + + /* Disable all global interrupts */ + ((RAMECC_TypeDef *)((uint32_t)hramecc->Instance & 0xFFFFFF00U))->IER &= \ + ~(RAMECC_IER_GIE | RAMECC_IER_GECCSEIE | RAMECC_IER_GECCDEIE | RAMECC_IER_GECCDEBWIE); + + /* Disable all interrupts monitor */ + hramecc->Instance->CR &= ~(RAMECC_CR_ECCSEIE | RAMECC_CR_ECCDEIE | RAMECC_CR_ECCDEBWIE); + + /* Clear RAMECC monitor flags */ + __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAGS_ALL); + + /* Initialise the RAMECC error code */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_NONE; + + /* Update the RAMECC state */ + hramecc->State = HAL_RAMECC_STATE_READY; + + /* Return HAL status */ + return HAL_OK; +} + + +/** + * @brief DeInitializes the RAMECC peripheral. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_DeInit(RAMECC_HandleTypeDef *hramecc) +{ + /* Check the RAMECC peripheral handle */ + if (hramecc == NULL) + { + /* Return HAL status */ + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Disable RAMECC monitor */ + hramecc->Instance->CR &= ~RAMECC_CR_ECCELEN; + + /* Disable all global interrupts */ + ((RAMECC_TypeDef *)((uint32_t)hramecc->Instance & 0xFFFFFF00U))->IER &= \ + ~(RAMECC_IER_GIE | RAMECC_IER_GECCSEIE | RAMECC_IER_GECCDEIE | RAMECC_IER_GECCDEBWIE); + + /* Disable all interrupts monitor */ + hramecc->Instance->CR &= ~(RAMECC_CR_ECCSEIE | RAMECC_CR_ECCDEIE | RAMECC_CR_ECCDEBWIE); + + /* Clear RAMECC monitor flags */ + __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAGS_ALL); + + +#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) + /* Check if a valid MSP API was registered */ + if (hramecc->MspDeInitCallback != NULL) + { + /* Init the low level hardware */ + hramecc->MspDeInitCallback(hramecc); + } + + /* Clean callbacks */ + hramecc->DetectSingleErrorCallback = NULL; + hramecc->DetectDoubleErrorCallback = NULL; +#else + HAL_RAMECC_MspDeInit(hramecc); +#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ + + /* Initialise the RAMECC error code */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_NONE; + + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_RESET; + + /* Return HAL status */ + return HAL_OK; +} + +/** + * @brief Initialize the RAMECC MSP. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC. + * @retval None. + */ +__weak void HAL_RAMECC_MspInit(RAMECC_HandleTypeDef *hramecc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hramecc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RAMECC_MspInit can be implemented in the user file */ +} + +/** + * @brief DeInitialize the RAMECC MSP. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC. + * @retval None. + */ +__weak void HAL_RAMECC_MspDeInit(RAMECC_HandleTypeDef *hramecc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hramecc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RAMECC_MspDeInit can be implemented in the user file */ +} +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup RAMECC_Exported_Functions_Group2 + * +@verbatim + =============================================================================== + ##### Monitoring operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure latching error information. + (+) Configure RAMECC Global/Monitor interrupts. + (+) Register and Unregister RAMECC callbacks + (+) Handle RAMECC interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Starts the RAMECC latching error information. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_StartMonitor(RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Check RAMECC state */ + if (hramecc->State == HAL_RAMECC_STATE_READY) + { + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_BUSY; + + /* Enable RAMECC monitor */ + hramecc->Instance->CR |= RAMECC_CR_ECCELEN; + + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_READY; + } + else + { + /* Update the error code */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; + + /* Return HAL status */ + return HAL_ERROR; + } + + /* Return HAL status */ + return HAL_OK; +} + + +/** + * @brief Stop the RAMECC latching error information. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_StopMonitor(RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Check RAMECC state */ + if (hramecc->State == HAL_RAMECC_STATE_READY) + { + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_BUSY; + + /* Disable RAMECC monitor */ + hramecc->Instance->CR &= ~RAMECC_CR_ECCELEN; + + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_READY; + } + else + { + /* Update the error code */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; + + /* Return HAL status */ + return HAL_ERROR; + } + + /* Return HAL status */ + return HAL_OK; +} + + +/** + * @brief Enable the RAMECC error interrupts. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that + * contains the configuration information for the + * specified RAMECC Monitor. + * @param Notifications Select the notification. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_EnableNotification(RAMECC_HandleTypeDef *hramecc, uint32_t Notifications) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + assert_param(IS_RAMECC_INTERRUPT(Notifications)); + + /* Check RAMECC state */ + if (hramecc->State == HAL_RAMECC_STATE_READY) + { + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_BUSY; + + /* Enable RAMECC interrupts */ + __HAL_RAMECC_ENABLE_IT(hramecc, Notifications); + + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_READY; + } + else + { + /* Update the error code */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; + + /* Return HAL status */ + return HAL_ERROR; + } + + /* Return HAL status */ + return HAL_OK; +} + + +/** + * @brief Disable the RAMECC error interrupts. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that + * contains the configuration information for the + * specified RAMECC Monitor. + * @param Notifications Select the notification. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_DisableNotification(RAMECC_HandleTypeDef *hramecc, uint32_t Notifications) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + assert_param(IS_RAMECC_INTERRUPT(Notifications)); + + /* Check RAMECC state */ + if (hramecc->State == HAL_RAMECC_STATE_READY) + { + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_BUSY; + + /* Disable RAMECC interrupts */ + __HAL_RAMECC_DISABLE_IT(hramecc, Notifications); + + /* Change RAMECC peripheral state */ + hramecc->State = HAL_RAMECC_STATE_READY; + } + else + { + /* Update the error code */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_BUSY; + + /* Return HAL status */ + return HAL_ERROR; + } + + /* Return HAL status */ + return HAL_OK; +} + + +/** @addtogroup RAMCECC_Exported_Functions_Group3 + * +@verbatim + =============================================================================== + ##### Handle Interrupt and Callbacks Functions ##### + =============================================================================== + [..] + This section provides functions to handle RAMECC interrupts and + Register / UnRegister the different callbacks. + [..] + The HAL_RAMECC_IRQHandler() function allows handling the active RAMECC + interrupt request. + The HAL_RAMECC_RegisterCallback() function allows registering the selected + RAMECC callbacks. + The HAL_RAMECC_UnRegisterCallback() function allows unregistering the + selected RAMECC callbacks. +@endverbatim + * @{ + */ + +/** + * @brief Handles RAMECC interrupt request. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval None. + */ +void HAL_RAMECC_IRQHandler(RAMECC_HandleTypeDef *hramecc) +{ + uint32_t monitor_it_source; + uint32_t global_it_source; + + monitor_it_source = READ_REG(hramecc->Instance->CR); + global_it_source = READ_REG(((RAMECC_TypeDef *)((uint32_t)hramecc->Instance & 0xFFFFFF00U))->IER); + + /* Single Error Interrupt Management ****************************************/ + if (((monitor_it_source & RAMECC_CR_ECCSEIE) == RAMECC_CR_ECCSEIE) || + ((global_it_source & RAMECC_IER_GECCSEIE) == RAMECC_IER_GECCSEIE) || + ((global_it_source & RAMECC_IER_GIE) == RAMECC_IER_GIE)) + { + if (__HAL_RAMECC_GET_FLAG(hramecc, RAMECC_FLAG_SINGLEERR_R) != 0U) + { + /* Clear active flags */ + __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAG_SINGLEERR_R); + +#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) + /* Check if a valid single error callback is registered */ + if (hramecc->DetectSingleErrorCallback != NULL) + { + /* Single error detection callback */ + hramecc->DetectSingleErrorCallback(hramecc); + } +#else + HAL_RAMECC_DetectSingleErrorCallback(hramecc); +#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ + } + } + + /* Double Error Interrupt Management ****************************************/ + if (((monitor_it_source & RAMECC_CR_ECCDEIE) == RAMECC_CR_ECCDEIE) || + ((monitor_it_source & RAMECC_CR_ECCDEBWIE) == RAMECC_CR_ECCDEBWIE) || + ((global_it_source & RAMECC_IER_GECCDEIE) == RAMECC_IER_GECCDEIE) || + ((global_it_source & RAMECC_IER_GECCDEBWIE) == RAMECC_IER_GECCDEBWIE) || + ((global_it_source & RAMECC_IER_GIE) == RAMECC_IER_GIE)) + { + /* ECC double error detected flag */ + if (__HAL_RAMECC_GET_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_R) != 0U) + { + /* Clear active flags */ + __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_R); + +#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) + /* Check if a valid Double error callback is registered */ + if (hramecc->DetectDoubleErrorCallback != NULL) + { + /* Double error detection callback */ + hramecc->DetectDoubleErrorCallback(hramecc); + } +#else + HAL_RAMECC_DetectDoubleErrorCallback(hramecc); +#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ + } + + /* ECC double error on byte write */ + if (__HAL_RAMECC_GET_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_W) != 0U) + { + /* Clear active flags */ + __HAL_RAMECC_CLEAR_FLAG(hramecc, RAMECC_FLAG_DOUBLEERR_W); + +#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) + /* Check if a valid Double error callback is registered */ + if (hramecc->DetectDoubleErrorCallback != NULL) + { + /* Double error detection callback */ + hramecc->DetectDoubleErrorCallback(hramecc); + } +#else + HAL_RAMECC_DetectDoubleErrorCallback(hramecc); +#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ + } + } +} + +/** + * @brief RAMECC single error detection callback. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC. + * @retval None. + */ +__weak void HAL_RAMECC_DetectSingleErrorCallback(RAMECC_HandleTypeDef *hramecc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hramecc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RAMECC_DetectSingleErrorCallback can be implemented in + the user file. */ +} + +/** + * @brief RAMECC double error detection callback. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC. + * @retval None. + */ +__weak void HAL_RAMECC_DetectDoubleErrorCallback(RAMECC_HandleTypeDef *hramecc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hramecc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RAMECC_DetectDoubleErrorCallback can be implemented in + the user file. */ +} + +#if (USE_HAL_RAMECC_REGISTER_CALLBACKS == 1) +/** + * @brief Register RAMECC callbacks. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that + * contains the configuration information for the + * specified RAMECC instance. + * @param CallbackID : User Callback identifier a HAL_RAMECC_CallbackIDTypeDef + * ENUM as parameter. + * @param pCallback : Pointer to private callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_RegisterCallback(RAMECC_HandleTypeDef *hramecc, + HAL_RAMECC_CallbackIDTypeDef CallbackID, + void (* pCallback)(RAMECC_HandleTypeDef *_hramecc)) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code and return error */ + hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Check RAMECC state */ + if (hramecc->State == HAL_RAMECC_STATE_READY) + { + switch (CallbackID) + { + case HAL_RAMECC_SE_DETECT_CB_ID: + /* Register single error callback */ + hramecc->DetectSingleErrorCallback = pCallback; + break; + + case HAL_RAMECC_DE_DETECT_CB_ID: + /* Register double error callback */ + hramecc->DetectDoubleErrorCallback = pCallback; + break; + + case HAL_RAMECC_MSPINIT_CB_ID : + /* Register msp init callback */ + hramecc->MspInitCallback = pCallback; + break; + + case HAL_RAMECC_MSPDEINIT_CB_ID : + /* Register msp de-init callback */ + hramecc->MspDeInitCallback = pCallback; + break; + + default: + /* Update the error code and return error */ + hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (hramecc->State == HAL_RAMECC_STATE_RESET) + { + switch (CallbackID) + { + case HAL_RAMECC_MSPINIT_CB_ID : + /* Register msp init callback */ + hramecc->MspInitCallback = pCallback; + break; + + case HAL_RAMECC_MSPDEINIT_CB_ID : + /* Register msp de-init callback */ + hramecc->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code and return error */ + hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code and return error */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister RAMECC callbacks. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that + * contains the configuration information for the + * specified RAMECC instance. + * @param CallbackID : User Callback identifier a HAL_RAMECC_CallbackIDTypeDef + * ENUM as parameter. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_RAMECC_UnRegisterCallback(RAMECC_HandleTypeDef *hramecc, HAL_RAMECC_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Check RAMECC state */ + if (hramecc->State == HAL_RAMECC_STATE_READY) + { + switch (CallbackID) + { + case HAL_RAMECC_SE_DETECT_CB_ID: + /* UnRegister single error callback */ + hramecc->DetectSingleErrorCallback = NULL; + break; + + case HAL_RAMECC_DE_DETECT_CB_ID: + /* UnRegister double error callback */ + hramecc->DetectDoubleErrorCallback = NULL; + break; + + case HAL_RAMECC_MSPINIT_CB_ID : + /* UnRegister msp init callback */ + hramecc->MspInitCallback = NULL; + break; + + case HAL_RAMECC_MSPDEINIT_CB_ID : + /* UnRegister msp de-init callback */ + hramecc->MspDeInitCallback = NULL; + break; + + case HAL_RAMECC_ALL_CB_ID: + /* UnRegister all available callbacks */ + hramecc->DetectSingleErrorCallback = NULL; + hramecc->DetectDoubleErrorCallback = NULL; + hramecc->MspDeInitCallback = NULL; + hramecc->MspInitCallback = NULL; + break; + + default: + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hramecc->State == HAL_RAMECC_STATE_RESET) + { + switch (CallbackID) + { + case HAL_RAMECC_MSPINIT_CB_ID : + /* UnRegister msp init callback */ + hramecc->MspInitCallback = NULL; + break; + + case HAL_RAMECC_MSPDEINIT_CB_ID : + /* UnRegister msp de-init callback */ + hramecc->MspDeInitCallback = NULL; + break; + + case HAL_RAMECC_ALL_CB_ID: + /* UnRegister all available callbacks */ + hramecc->MspDeInitCallback = NULL; + hramecc->MspInitCallback = NULL; + break; + + default : + /* Update the error code */ + hramecc->ErrorCode |= HAL_RAMECC_ERROR_INVALID_CALLBACK; + + /* Update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code and return error */ + hramecc->ErrorCode = HAL_RAMECC_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + + return status; +} +/** + * @} + */ +#endif /* USE_HAL_RAMECC_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup RAMECC_Exported_Functions_Group4 + * +@verbatim + =============================================================================== + ##### Error information functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Get failing address. + (+) Get failing data low. + (+) Get failing data high. + (+) Get hamming bits injected. + (+) Check single error flag. + (+) Check double error flag. + +@endverbatim + * @{ + */ + +/** + * @brief Return the RAMECC failing address. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval Failing address offset. + */ +uint32_t HAL_RAMECC_GetFailingAddress(const RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Return failing address */ + return hramecc->Instance->FAR; +} + + +/** + * @brief Return the RAMECC data low. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval Failing data low. + */ +uint32_t HAL_RAMECC_GetFailingDataLow(const RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Return failing data low */ + return hramecc->Instance->FDRL; +} + + +/** + * @brief Return the RAMECC data high. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval Failing data high. + */ +uint32_t HAL_RAMECC_GetFailingDataHigh(const RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Return failing data high */ + return hramecc->Instance->FDRH; +} + + +/** + * @brief Return the RAMECC Hamming bits injected. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval Hamming bits injected. + */ +uint32_t HAL_RAMECC_GetHammingErrorCode(const RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Return hamming bits injected */ + return hramecc->Instance->FECR; +} + +/** + * @brief Check if an ECC single error was occurred. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval State of bit (1 or 0). + */ +uint32_t HAL_RAMECC_IsECCSingleErrorDetected(const RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Return the state of SEDC flag */ + return ((READ_BIT(hramecc->Instance->SR, RAMECC_SR_SEDCF) == (RAMECC_SR_SEDCF)) ? 1UL : 0UL); +} + +/** + * @brief Check if an ECC double error was occurred. + * @param hramecc Pointer to a RAMECC_HandleTypeDef structure that contains + * the configuration information for the specified RAMECC + * Monitor. + * @retval State of bit (1 or 0). + */ +uint32_t HAL_RAMECC_IsECCDoubleErrorDetected(const RAMECC_HandleTypeDef *hramecc) +{ + /* Check the parameters */ + assert_param(IS_RAMECC_MONITOR_ALL_INSTANCE(hramecc->Instance)); + + /* Return the state of DEDF | DEBWDF flags */ + return ((READ_BIT(hramecc->Instance->SR, (RAMECC_SR_DEDF | RAMECC_SR_DEBWDF)) != 0U) ? 1UL : 0UL); +} +/** + * @} + */ + + +/** @addtogroup RAMECC_Exported_Functions_Group5 + * +@verbatim + =============================================================================== + ##### State and Error Functions ##### + =============================================================================== + [..] + This section provides functions allowing to check and get the RAMECC state + and the error code . + [..] + The HAL_RAMECC_GetState() function allows to get the RAMECC peripheral + state. + The HAL_RAMECC_GetError() function allows to Get the RAMECC peripheral error + code. + +@endverbatim + * @{ + */ + +/** + * @brief Get the RAMECC peripheral state. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that + * contains the configuration information for the + * specified RAMECC instance. + * @retval RAMECC state. + */ +HAL_RAMECC_StateTypeDef HAL_RAMECC_GetState(const RAMECC_HandleTypeDef *hramecc) +{ + /* Return the RAMECC state */ + return hramecc->State; +} + +/** + * @brief Get the RAMECC peripheral error code. + * @param hramecc : Pointer to a RAMECC_HandleTypeDef structure that + * contains the configuration information for the + * specified RAMECC instance. + * @retval RAMECC error code. + */ +uint32_t HAL_RAMECC_GetError(const RAMECC_HandleTypeDef *hramecc) +{ + /* Return the RAMECC error code */ + return hramecc->ErrorCode; +} +/** + * @} + */ +#endif /* HAL_RAMECC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rcc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rcc.c index a258fad82..aeae5922e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rcc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rcc.c @@ -2155,7 +2155,9 @@ static uint32_t RCC_PLL1_GetVCOOutputFreq(void) } /* Compute VCO output frequency */ - return ((pllsrc / pllm) * (plln + (pllfracn / 0x2000U))); + frequency = ((float_t)pllsrc / (float_t)pllm) * ((float_t)plln + ((float_t)pllfracn / (float_t)0x2000U)); + + return (uint32_t)frequency; } /** @@ -2227,7 +2229,9 @@ static uint32_t RCC_PLL2_GetVCOOutputFreq(void) } /* Compute VCO output frequency */ - return ((pllsrc / pllm) * (plln + (pllfracn / 0x2000U))); + frequency = ((float_t)pllsrc / (float_t)pllm) * ((float_t)plln + ((float_t)pllfracn / (float_t)0x2000U)); + + return (uint32_t)frequency; } /** @@ -2299,7 +2303,9 @@ static uint32_t RCC_PLL3_GetVCOOutputFreq(void) } /* Compute VCO output frequency */ - return ((pllsrc / pllm) * (plln + (pllfracn / 0x2000U))); + frequency = ((float_t)pllsrc / (float_t)pllm) * ((float_t)plln + ((float_t)pllfracn / (float_t)0x2000U)); + + return (uint32_t)frequency; } /** diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rng.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rng.c index 76367f887..3e40ab518 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rng.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rng.c @@ -238,7 +238,7 @@ HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng) if ((HAL_GetTick() - tickstart) > RNG_TIMEOUT_VALUE) { /* New check to avoid false timeout detection in case of preemption */ - if (__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_SECS) != RESET) + if (__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) != SET) { hrng->State = HAL_RNG_STATE_ERROR; hrng->ErrorCode = HAL_RNG_ERROR_TIMEOUT; diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc.c index 13b2a89e0..049658928 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc.c @@ -1,2270 +1,2269 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_rtc.c - * @author MCD Application Team - * @brief RTC HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Real-Time Clock (RTC) peripheral: - * + Initialization/de-initialization functions - * + Calendar (Time and Date) configuration - * + Alarms (Alarm A and Alarm B) configuration - * + WakeUp Timer configuration - * + TimeStamp configuration - * + Tampers configuration - * + Backup Data Registers configuration - * + RTC Tamper and TimeStamp Pins Selection - * + Interrupts and flags management - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - =============================================================================== - ##### RTC Operating Condition ##### - =============================================================================== - [..] The real-time clock (RTC) and the RTC backup registers can be powered - from the VBAT voltage when the main VDD supply is powered off. - To retain the content of the RTC backup registers 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. - - ##### Backup Domain Reset ##### - =============================================================================== - [..] The backup domain reset sets all RTC registers and the RCC_BDCR register - to their reset values. - 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. - (#) Tamper detection event resets all data backup registers. - - ##### Backup Domain Access ##### - ================================================================== - [..] After reset, the backup domain (RTC registers and RTC backup data registers) - is protected against possible unwanted write accesses. - [..] To enable access to the RTC Domain and RTC registers, proceed as follows: - (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. - (+) Call the function HAL_RCCEx_PeriphCLKConfig with RCC_PERIPHCLK_RTC for - PeriphClockSelection and select RTCClockSelection (LSE, LSI or HSEdiv32) - (+) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function. - - ##### How to use RTC 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. - - *** Callback registration *** - ============================================= - When The compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. This is the recommended configuration - in order to optimize memory/code consumption footprint/performances. - - The compilation define USE_RTC_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Function HAL_RTC_RegisterCallback() to register an interrupt callback. - - Function HAL_RTC_RegisterCallback() allows to register following callbacks: - (+) AlarmAEventCallback : RTC Alarm A Event callback. - (+) AlarmBEventCallback : RTC Alarm B Event callback. - (+) TimeStampEventCallback : RTC TimeStamp Event callback. - (+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback. - (+) SSRUEventCallback : RTC SSRU Event callback. - (+) Tamper1EventCallback : RTC Tamper 1 Event callback. - (+) Tamper2EventCallback : RTC Tamper 2 Event callback. - (+) Tamper3EventCallback : RTC Tamper 3 Event callback. - (+) Tamper4EventCallback : RTC Tamper 4 Event callback. - (+) Tamper5EventCallback : RTC Tamper 5 Event callback. - (+) Tamper6EventCallback : RTC Tamper 6 Event callback. - (+) Tamper7EventCallback : RTC Tamper 7 Event callback. - (+) Tamper8EventCallback : RTC Tamper 8 Event callback. - (+) InternalTamper1EventCallback : RTC InternalTamper 1 Event callback. - (+) InternalTamper2EventCallback : RTC InternalTamper 2 Event callback. - (+) InternalTamper3EventCallback : RTC InternalTamper 3 Event callback. - (+) InternalTamper4EventCallback : RTC InternalTamper 4 Event callback. - (+) InternalTamper5EventCallback : RTC InternalTamper 5 Event callback. - (+) InternalTamper6EventCallback : RTC InternalTamper 6 Event callback. - (+) InternalTamper7EventCallback : RTC InternalTamper 7 Event callback. - (+) InternalTamper8EventCallback : RTC InternalTamper 8 Event callback. - (+) InternalTamper9EventCallback : RTC InternalTamper 9 Event callback. - (+) InternalTamper11EventCallback : RTC InternalTamper 11 Event callback. - (+) InternalTamper15EventCallback : RTC InternalTamper 15 Event callback. - (+) MspInitCallback : RTC MspInit callback. - (+) MspDeInitCallback : RTC MspDeInit callback. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function HAL_RTC_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_RTC_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) AlarmAEventCallback : RTC Alarm A Event callback. - (+) AlarmBEventCallback : RTC Alarm B Event callback. - (+) TimeStampEventCallback : RTC TimeStamp Event callback. - (+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback. - (+) SSRUEventCallback : RTC SSRU Event callback. - (+) Tamper1EventCallback : RTC Tamper 1 Event callback. - (+) Tamper2EventCallback : RTC Tamper 2 Event callback. - (+) Tamper3EventCallback : RTC Tamper 3 Event callback. - (+) Tamper4EventCallback : RTC Tamper 4 Event callback. - (+) Tamper5EventCallback : RTC Tamper 5 Event callback. - (+) Tamper6EventCallback : RTC Tamper 6 Event callback. - (+) Tamper7EventCallback : RTC Tamper 7 Event callback. - (+) Tamper8EventCallback : RTC Tamper 8 Event callback. - (+) InternalTamper1EventCallback : RTC InternalTamper 1 Event callback. - (+) InternalTamper2EventCallback : RTC InternalTamper 2 Event callback. - (+) InternalTamper3EventCallback : RTC InternalTamper 3 Event callback. - (+) InternalTamper4EventCallback : RTC InternalTamper 4 Event callback. - (+) InternalTamper5EventCallback : RTC InternalTamper 5 Event callback. - (+) InternalTamper6EventCallback : RTC InternalTamper 6 Event callback. - (+) InternalTamper7EventCallback : RTC InternalTamper 7 Event callback. - (+) InternalTamper8EventCallback : RTC InternalTamper 8 Event callback. - (+) InternalTamper9EventCallback : RTC InternalTamper 9 Event callback. - (+) InternalTamper11EventCallback : RTC InternalTamper 11 Event callback. - (+) InternalTamper15EventCallback : RTC InternalTamper 15 Event callback. - (+) MspInitCallback : RTC MspInit callback. - (+) MspDeInitCallback : RTC MspDeInit callback. - - By default, after the HAL_RTC_Init() and when the state is HAL_RTC_STATE_RESET, - all callbacks are set to the corresponding weak functions : - examples AlarmAEventCallback(), TimeStampEventCallback(). - Exception done for MspInit and MspDeInit callbacks that are reset to the legacy weak function - in the HAL_RTC_Init()/HAL_RTC_DeInit() only when these callbacks are null - (not registered beforehand). - If not, MspInit or MspDeInit are not null, HAL_RTC_Init()/HAL_RTC_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in HAL_RTC_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_RTC_STATE_READY or HAL_RTC_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_RTC_RegisterCallback() before calling HAL_RTC_DeInit() - or HAL_RTC_Init() function. - - When The compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - - -/** @addtogroup RTC - * @brief RTC HAL module driver - * @{ - */ - -#ifdef HAL_RTC_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup RTC_Exported_Functions - * @{ - */ - -/** @addtogroup RTC_Exported_Functions_Group1 - * @brief Initialization and Configuration functions - * -@verbatim - =============================================================================== - ##### Initialization and de-initialization functions ##### - =============================================================================== - [..] This section provides 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 15-bit synchronous prescaler. - (++) When both prescalers are used, it is recommended to configure the - asynchronous prescaler to a high value to minimize power 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 Initialize the RTC peripheral - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) -{ - HAL_StatusTypeDef status = HAL_ERROR; - - /* Check the RTC peripheral state */ - if (hrtc != NULL) - { - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance)); - 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)); -#if defined(RTC_CR_OSEL) - 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)); - assert_param(IS_RTC_OUTPUT_PULLUP(hrtc->Init.OutPutPullUp)); -#endif /* RTC_CR_OSEL */ -#if defined(RTC_CR_OUT2EN) - assert_param(IS_RTC_OUTPUT_REMAP(hrtc->Init.OutPutRemap)); -#endif /* RTC_CR_OUT2EN */ - assert_param(IS_RTC_BINARY_MODE(hrtc->Init.BinMode)); - assert_param(IS_RTC_BINARY_MIX_BCDU(hrtc->Init.BinMixBcdU)); - -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - if (hrtc->State == HAL_RTC_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hrtc->Lock = HAL_UNLOCKED; - - /* Legacy weak AlarmAEventCallback */ - hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; - /* Legacy weak AlarmBEventCallback */ - hrtc->AlarmBEventCallback = HAL_RTCEx_AlarmBEventCallback; - /* Legacy weak TimeStampEventCallback */ - hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; - /* Legacy weak WakeUpTimerEventCallback */ - hrtc->WakeUpTimerEventCallback = HAL_RTCEx_WakeUpTimerEventCallback; - /* Legacy weak SSRUEventCallback */ - hrtc->SSRUEventCallback = HAL_RTCEx_SSRUEventCallback; - /* Legacy weak Tamper1EventCallback */ - hrtc->Tamper1EventCallback = HAL_RTCEx_Tamper1EventCallback; - /* Legacy weak Tamper2EventCallback */ - hrtc->Tamper2EventCallback = HAL_RTCEx_Tamper2EventCallback; - /* Legacy weak Tamper3EventCallback */ - hrtc->Tamper3EventCallback = HAL_RTCEx_Tamper3EventCallback; - /* Legacy weak Tamper4EventCallback */ - hrtc->Tamper4EventCallback = HAL_RTCEx_Tamper4EventCallback; - /* Legacy weak Tamper5EventCallback */ - hrtc->Tamper5EventCallback = HAL_RTCEx_Tamper5EventCallback; - /* Legacy weak Tamper6EventCallback */ - hrtc->Tamper6EventCallback = HAL_RTCEx_Tamper6EventCallback; - /* Legacy weak Tamper7EventCallback */ - hrtc->Tamper7EventCallback = HAL_RTCEx_Tamper7EventCallback; - /* Legacy weak Tamper8EventCallback */ - hrtc->Tamper8EventCallback = HAL_RTCEx_Tamper8EventCallback; - /* Legacy weak InternalTamper1EventCallback */ - hrtc->InternalTamper1EventCallback = HAL_RTCEx_InternalTamper1EventCallback; - /* Legacy weak InternalTamper2EventCallback */ - hrtc->InternalTamper2EventCallback = HAL_RTCEx_InternalTamper2EventCallback; - /* Legacy weak InternalTamper3EventCallback */ - hrtc->InternalTamper3EventCallback = HAL_RTCEx_InternalTamper3EventCallback; - /* Legacy weak InternalTamper4EventCallback */ - hrtc->InternalTamper4EventCallback = HAL_RTCEx_InternalTamper4EventCallback; - /* Legacy weak InternalTamper5EventCallback */ - hrtc->InternalTamper5EventCallback = HAL_RTCEx_InternalTamper5EventCallback; - /* Legacy weak InternalTamper6EventCallback */ - hrtc->InternalTamper6EventCallback = HAL_RTCEx_InternalTamper6EventCallback; - /* Legacy weak InternalTamper7EventCallback */ - hrtc->InternalTamper7EventCallback = HAL_RTCEx_InternalTamper7EventCallback; - /* Legacy weak InternalTamper8EventCallback */ - hrtc->InternalTamper8EventCallback = HAL_RTCEx_InternalTamper8EventCallback; - /* Legacy weak InternalTamper9EventCallback */ - hrtc->InternalTamper9EventCallback = HAL_RTCEx_InternalTamper9EventCallback; - /* Legacy weak InternalTamper11EventCallback */ - hrtc->InternalTamper11EventCallback = HAL_RTCEx_InternalTamper11EventCallback; - /* Legacy weak InternalTamper15EventCallback */ - hrtc->InternalTamper15EventCallback = HAL_RTCEx_InternalTamper15EventCallback; - - if (hrtc->MspInitCallback == NULL) - { - hrtc->MspInitCallback = HAL_RTC_MspInit; - } - /* Init the low level hardware */ - hrtc->MspInitCallback(hrtc); - - if (hrtc->MspDeInitCallback == NULL) - { - hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; - } - } -#else - if (hrtc->State == HAL_RTC_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hrtc->Lock = HAL_UNLOCKED; - - /* Initialize RTC MSP */ - HAL_RTC_MspInit(hrtc); - } -#endif /* (USE_HAL_RTC_REGISTER_CALLBACKS) */ - - /* Set RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Check if the calendar has been not initialized */ - if (__HAL_RTC_IS_CALENDAR_INITIALIZED(hrtc) == 0U) - { - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Enter Initialization mode */ - status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { -#if defined(RTC_CR_OSEL) - /* Clear RTC_CR FMT, OSEL and POL Bits */ - CLEAR_BIT(RTC->CR, (RTC_CR_FMT | RTC_CR_POL | RTC_CR_OSEL | RTC_CR_TAMPOE)); - - /* Set RTC_CR register */ - SET_BIT(RTC->CR, (hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity)); -#else - /* Clear RTC_CR FMT Bits */ - CLEAR_BIT(RTC->CR, RTC_CR_FMT); - - /* Set RTC_CR register */ - SET_BIT(RTC->CR, hrtc->Init.HourFormat); -#endif /* RTC_CR_OSEL */ - - /* Configure the RTC PRER */ - WRITE_REG(RTC->PRER, ((hrtc->Init.SynchPrediv) | (hrtc->Init.AsynchPrediv << RTC_PRER_PREDIV_A_Pos))); - - /* Configure the Binary mode */ - MODIFY_REG(RTC->ICSR, RTC_ICSR_BIN | RTC_ICSR_BCDU, hrtc->Init.BinMode | hrtc->Init.BinMixBcdU); - - /* Exit Initialization mode */ - status = RTC_ExitInitMode(hrtc); - -#if defined(RTC_CR_OSEL) - if (status == HAL_OK) - { -#if defined(RTC_CR_OUT2EN) - MODIFY_REG(RTC->CR, \ - RTC_CR_TAMPALRM_PU | RTC_CR_TAMPALRM_TYPE | RTC_CR_OUT2EN, \ - hrtc->Init.OutPutPullUp | hrtc->Init.OutPutType | hrtc->Init.OutPutRemap); -#else - MODIFY_REG(RTC->CR, \ - RTC_CR_TAMPALRM_PU | RTC_CR_TAMPALRM_TYPE, \ - hrtc->Init.OutPutPullUp | hrtc->Init.OutPutType); -#endif /* RTC_CR_OUT2EN */ - } -#endif /* RTC_CR_OSEL */ - } - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - - } - else - { - /* Calendar is already initialized */ - /* Set flag to OK */ - status = HAL_OK; - } - - if (status == HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - } - } - - return status; -} - -/** - * @brief DeInitialize the RTC peripheral. - * @note This function does not reset the RTC Backup Data registers. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) -{ - HAL_StatusTypeDef status = HAL_ERROR; - uint32_t tickstart; - - /* Check RTC handler */ - if (hrtc != NULL) - { - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance)); - - /* Set RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Enter Initialization mode */ - status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { - /* Reset All CR bits except CR[2:0] (which cannot be written before bit - WUTE of CR is cleared) */ - CLEAR_REG(RTC->CR); - - /* Reset TR and DR registers */ - WRITE_REG(RTC->DR, (uint32_t)(RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); - CLEAR_REG(RTC->TR); - - /* Reset other RTC registers */ - WRITE_REG(RTC->PRER, ((uint32_t)(RTC_PRER_PREDIV_A | 0xFFU))); - CLEAR_REG(RTC->ALRMAR); - CLEAR_REG(RTC->ALRMBR); - CLEAR_REG(RTC->SHIFTR); - CLEAR_REG(RTC->CALR); - CLEAR_REG(RTC->ALRMASSR); - CLEAR_REG(RTC->ALRMBSSR); - CLEAR_BIT(RTC->ICSR, (RTC_ICSR_BCDU_Msk | RTC_ICSR_BIN_Msk)); - WRITE_REG(RTC->SCR, RTC_SCR_CITSF | RTC_SCR_CTSOVF | RTC_SCR_CTSF | RTC_SCR_CWUTF | RTC_SCR_CALRBF | \ - RTC_SCR_CALRAF); -#if defined (RTC_PRIVCFGR_ALRAPRIV) - CLEAR_REG(RTC->PRIVCFGR); -#endif /* RTC_PRIVCFGR_ALRAPRIV */ - - /* Exit initialization mode */ - status = RTC_ExitInitMode(hrtc); - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - } - - if (status == HAL_OK) - { - /* Wait till WUTWF is set (to be able to reset CR[2:0] and WUTR) and if - timeout is reached exit */ - tickstart = HAL_GetTick(); - - while ((((hrtc->Instance->ICSR) & RTC_ICSR_WUTWF) == 0U) && (status != HAL_TIMEOUT)) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) - { - /* Set RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - status = HAL_TIMEOUT; - } - else - { - break; - } - } - } - - /* Reset RTC CR register bits [2:0] */ - CLEAR_REG(RTC->CR); - - /* Reset RTC WUTR register */ - WRITE_REG(RTC->WUTR, RTC_WUTR_WUT); - - /* Reset TAMP registers */ - CLEAR_REG(TAMP->CR1); - CLEAR_REG(TAMP->CR2); - CLEAR_REG(TAMP->CR3); - CLEAR_REG(TAMP->FLTCR); - WRITE_REG(TAMP->ATCR1, TAMP_ATCR1_ATCKSEL); - CLEAR_REG(TAMP->ATOR); - CLEAR_REG(TAMP->ATCR2); - CLEAR_REG(TAMP->PRIVCFGR); - -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - if (hrtc->MspDeInitCallback == NULL) - { - hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; - } - - /* DeInit the low level hardware: CLOCK, NVIC.*/ - hrtc->MspDeInitCallback(hrtc); - -#else - /* De-Initialize RTC MSP */ - HAL_RTC_MspDeInit(hrtc); -#endif /* (USE_HAL_RTC_REGISTER_CALLBACKS) */ - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hrtc); - - } - } - - return status; -} - -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User RTC Callback - * To be used instead of the weak predefined callback - * @param hrtc RTC handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_RTC_ALARM_A_EVENT_CB_ID Alarm A Event Callback ID - * @arg @ref HAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID - * @arg @ref HAL_RTC_TIMESTAMP_EVENT_CB_ID TimeStamp Event Callback ID - * @arg @ref HAL_RTC_WAKEUPTIMER_EVENT_CB_ID WakeUp Timer Event Callback ID - * @arg @ref HAL_RTC_SSRU_EVENT_CB_ID SSRU Event Callback ID - * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID - * @arg @ref HAL_RTC_TAMPER2_EVENT_CB_ID Tamper 2 Callback ID - * @arg @ref HAL_RTC_TAMPER3_EVENT_CB_ID Tamper 3 Callback ID - * @arg @ref HAL_RTC_TAMPER4_EVENT_CB_ID Tamper 4 Callback ID - * @arg @ref HAL_RTC_TAMPER5_EVENT_CB_ID Tamper 5 Callback ID - * @arg @ref HAL_RTC_TAMPER6_EVENT_CB_ID Tamper 6 Callback ID - * @arg @ref HAL_RTC_TAMPER7_EVENT_CB_ID Tamper 7 Callback ID - * @arg @ref HAL_RTC_TAMPER8_EVENT_CB_ID Tamper 8 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID Internal Tamper 1 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID Internal Tamper 2 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID Internal Tamper 3 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID Internal Tamper 4 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID Internal Tamper 5 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID Internal Tamper 6 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID Internal Tamper 7 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID Internal Tamper 8 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID Internal Tamper 9 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID Internal Tamper 11 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID Internal Tamper 15 Callback ID - * @arg @ref HAL_RTC_MSPINIT_CB_ID Msp Init callback ID - * @arg @ref HAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID - * @param pCallback pointer to the Callback function - * @note The HAL_RTC_RegisterCallback() may be called before HAL_RTC_Init() in HAL_RTC_STATE_RESET - * to register callbacks for HAL_RTC_MSPINIT_CB_ID and HAL_RTC_MSPDEINIT_CB_ID. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_RegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_CallbackIDTypeDef CallbackID, - pRTC_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - if (HAL_RTC_STATE_READY == hrtc->State) - { - switch (CallbackID) - { - case HAL_RTC_ALARM_A_EVENT_CB_ID : - hrtc->AlarmAEventCallback = pCallback; - break; - - case HAL_RTC_ALARM_B_EVENT_CB_ID : - hrtc->AlarmBEventCallback = pCallback; - break; - - case HAL_RTC_TIMESTAMP_EVENT_CB_ID : - hrtc->TimeStampEventCallback = pCallback; - break; - - case HAL_RTC_WAKEUPTIMER_EVENT_CB_ID : - hrtc->WakeUpTimerEventCallback = pCallback; - break; - - case HAL_RTC_SSRU_EVENT_CB_ID : - hrtc->SSRUEventCallback = pCallback; - break; - - case HAL_RTC_TAMPER1_EVENT_CB_ID : - hrtc->Tamper1EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER2_EVENT_CB_ID : - hrtc->Tamper2EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER3_EVENT_CB_ID : - hrtc->Tamper3EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER4_EVENT_CB_ID : - hrtc->Tamper4EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER5_EVENT_CB_ID : - hrtc->Tamper5EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER6_EVENT_CB_ID : - hrtc->Tamper6EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER7_EVENT_CB_ID : - hrtc->Tamper7EventCallback = pCallback; - break; - - case HAL_RTC_TAMPER8_EVENT_CB_ID : - hrtc->Tamper8EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID : - hrtc->InternalTamper1EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID : - hrtc->InternalTamper2EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID : - hrtc->InternalTamper3EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID : - hrtc->InternalTamper4EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID : - hrtc->InternalTamper5EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID : - hrtc->InternalTamper6EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID : - hrtc->InternalTamper7EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID : - hrtc->InternalTamper8EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID : - hrtc->InternalTamper9EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID : - hrtc->InternalTamper11EventCallback = pCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID : - hrtc->InternalTamper15EventCallback = pCallback; - break; - - case HAL_RTC_MSPINIT_CB_ID : - hrtc->MspInitCallback = pCallback; - break; - - case HAL_RTC_MSPDEINIT_CB_ID : - hrtc->MspDeInitCallback = pCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_RTC_STATE_RESET == hrtc->State) - { - switch (CallbackID) - { - case HAL_RTC_MSPINIT_CB_ID : - hrtc->MspInitCallback = pCallback; - break; - - case HAL_RTC_MSPDEINIT_CB_ID : - hrtc->MspDeInitCallback = pCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an RTC Callback - * RTC callback is redirected to the weak predefined callback - * @param hrtc RTC handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * This parameter can be one of the following values: - * @arg @ref HAL_RTC_ALARM_A_EVENT_CB_ID Alarm A Event Callback ID - * @arg @ref HAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID - * @arg @ref HAL_RTC_TIMESTAMP_EVENT_CB_ID TimeStamp Event Callback ID - * @arg @ref HAL_RTC_SSRU_EVENT_CB_ID SSRU Callback ID - * @arg @ref HAL_RTC_WAKEUPTIMER_EVENT_CB_ID WakeUp Timer Event Callback ID - * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID - * @arg @ref HAL_RTC_TAMPER2_EVENT_CB_ID Tamper 2 Callback ID - * @arg @ref HAL_RTC_TAMPER3_EVENT_CB_ID Tamper 3 Callback ID - * @arg @ref HAL_RTC_TAMPER4_EVENT_CB_ID Tamper 4 Callback ID - * @arg @ref HAL_RTC_TAMPER5_EVENT_CB_ID Tamper 5 Callback ID - * @arg @ref HAL_RTC_TAMPER6_EVENT_CB_ID Tamper 6 Callback ID - * @arg @ref HAL_RTC_TAMPER7_EVENT_CB_ID Tamper 7 Callback ID - * @arg @ref HAL_RTC_TAMPER8_EVENT_CB_ID Tamper 8 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID Internal Tamper 1 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID Internal Tamper 2 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID Internal Tamper 3 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID Internal Tamper 4 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID Internal Tamper 5 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID Internal Tamper 6 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID Internal Tamper 7 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID Internal Tamper 8 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID Internal Tamper 9 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID Internal Tamper 11 Callback ID - * @arg @ref HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID Internal Tamper 15 Callback ID - * @arg @ref HAL_RTC_MSPINIT_CB_ID Msp Init callback ID - * @arg @ref HAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID - * @note The HAL_RTC_UnRegisterCallback() may be called before HAL_RTC_Init() in HAL_RTC_STATE_RESET - * to un-register callbacks for HAL_RTC_MSPINIT_CB_ID and HAL_RTC_MSPDEINIT_CB_ID. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_UnRegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_RTC_STATE_READY == hrtc->State) - { - switch (CallbackID) - { - case HAL_RTC_ALARM_A_EVENT_CB_ID : - /* Legacy weak AlarmAEventCallback */ - hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; - break; - - case HAL_RTC_ALARM_B_EVENT_CB_ID : - /* Legacy weak AlarmBEventCallback */ - hrtc->AlarmBEventCallback = HAL_RTCEx_AlarmBEventCallback; - break; - - case HAL_RTC_TIMESTAMP_EVENT_CB_ID : - /* Legacy weak TimeStampEventCallback */ - hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; - break; - - case HAL_RTC_WAKEUPTIMER_EVENT_CB_ID : - /* Legacy weak WakeUpTimerEventCallback */ - hrtc->WakeUpTimerEventCallback = HAL_RTCEx_WakeUpTimerEventCallback; - break; - - case HAL_RTC_SSRU_EVENT_CB_ID : - /* Legacy weak SSRUEventCallback */ - hrtc->SSRUEventCallback = HAL_RTCEx_SSRUEventCallback; - break; - - case HAL_RTC_TAMPER1_EVENT_CB_ID : - /* Legacy weak Tamper1EventCallback */ - hrtc->Tamper1EventCallback = HAL_RTCEx_Tamper1EventCallback; - break; - - case HAL_RTC_TAMPER2_EVENT_CB_ID : - /* Legacy weak Tamper2EventCallback */ - hrtc->Tamper2EventCallback = HAL_RTCEx_Tamper2EventCallback; - break; - - case HAL_RTC_TAMPER3_EVENT_CB_ID : - /* Legacy weak Tamper3EventCallback */ - hrtc->Tamper3EventCallback = HAL_RTCEx_Tamper3EventCallback; - break; - - case HAL_RTC_TAMPER4_EVENT_CB_ID : - /* Legacy weak Tamper4EventCallback */ - hrtc->Tamper4EventCallback = HAL_RTCEx_Tamper4EventCallback; - break; - - case HAL_RTC_TAMPER5_EVENT_CB_ID : - /* Legacy weak Tamper5EventCallback */ - hrtc->Tamper5EventCallback = HAL_RTCEx_Tamper5EventCallback; - break; - - case HAL_RTC_TAMPER6_EVENT_CB_ID : - /* Legacy weak Tamper6EventCallback */ - hrtc->Tamper6EventCallback = HAL_RTCEx_Tamper6EventCallback; - break; - - case HAL_RTC_TAMPER7_EVENT_CB_ID : - /* Legacy weak Tamper7EventCallback */ - hrtc->Tamper7EventCallback = HAL_RTCEx_Tamper7EventCallback; - break; - - case HAL_RTC_TAMPER8_EVENT_CB_ID : - /* Legacy weak Tamper8EventCallback */ - hrtc->Tamper8EventCallback = HAL_RTCEx_Tamper8EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID : - /* Legacy weak InternalTamper1EventCallback */ - hrtc->InternalTamper1EventCallback = HAL_RTCEx_InternalTamper1EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID : - /* Legacy weak InternalTamper2EventCallback */ - hrtc->InternalTamper2EventCallback = HAL_RTCEx_InternalTamper2EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID : - /* Legacy weak InternalTamper3EventCallback */ - hrtc->InternalTamper3EventCallback = HAL_RTCEx_InternalTamper3EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID : - /* Legacy weak InternalTamper4EventCallback */ - hrtc->InternalTamper4EventCallback = HAL_RTCEx_InternalTamper4EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID : - /* Legacy weak InternalTamper5EventCallback */ - hrtc->InternalTamper5EventCallback = HAL_RTCEx_InternalTamper5EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID : - /* Legacy weak InternalTamper6EventCallback */ - hrtc->InternalTamper6EventCallback = HAL_RTCEx_InternalTamper6EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID : - /* Legacy weak InternalTamper7EventCallback */ - hrtc->InternalTamper7EventCallback = HAL_RTCEx_InternalTamper7EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID : - /* Legacy weak InternalTamper8EventCallback */ - hrtc->InternalTamper8EventCallback = HAL_RTCEx_InternalTamper8EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID : - /* Legacy weak InternalTamper9EventCallback */ - hrtc->InternalTamper9EventCallback = HAL_RTCEx_InternalTamper9EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID : - /* Legacy weak InternalTamper11EventCallback */ - hrtc->InternalTamper11EventCallback = HAL_RTCEx_InternalTamper11EventCallback; - break; - - case HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID : - /* Legacy weak InternalTamper15EventCallback */ - hrtc->InternalTamper15EventCallback = HAL_RTCEx_InternalTamper15EventCallback; - break; - - case HAL_RTC_MSPINIT_CB_ID : - hrtc->MspInitCallback = HAL_RTC_MspInit; - break; - - case HAL_RTC_MSPDEINIT_CB_ID : - hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_RTC_STATE_RESET == hrtc->State) - { - switch (CallbackID) - { - case HAL_RTC_MSPINIT_CB_ID : - hrtc->MspInitCallback = HAL_RTC_MspInit; - break; - - case HAL_RTC_MSPDEINIT_CB_ID : - hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - -/** - * @brief Initialize the RTC MSP. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTC_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitialize the RTC MSP. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTC_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @addtogroup RTC_Exported_Functions_Group2 - * @brief RTC Time and Date functions - * -@verbatim - =============================================================================== - ##### RTC Time and Date functions ##### - =============================================================================== - - [..] This section provides functions allowing to configure Time and Date features - -@endverbatim - * @{ - */ - -/** - * @brief Set RTC current time. - * @param hrtc RTC handle - * @param sTime Pointer to Time structure - * if Binary mode is RTC_BINARY_ONLY, this parameter is not used and RTC_SSR will be automatically - * reset to 0xFFFFFFFF - * else sTime->SubSeconds is not used and RTC_SSR will be automatically reset to the - * A 7-bit async prescaler (RTC_PRER_PREDIV_A) - * @param Format Format of sTime->Hours, sTime->Minutes and sTime->Seconds. - * if Binary mode is RTC_BINARY_ONLY, this parameter is not used - * else this parameter can be one of the following values - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) -{ - uint32_t tmpreg; - HAL_StatusTypeDef status; - -#ifdef USE_FULL_ASSERT - /* Check the parameters depending of the Binary mode with 32-bit free-running counter configuration */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_NONE) - { - /* Check the parameters */ - assert_param(IS_RTC_FORMAT(Format)); - } -#endif /* USE_FULL_ASSERT */ - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Enter Initialization mode */ - status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { - /* Check Binary mode ((32-bit free-running counter) */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) != RTC_BINARY_ONLY) - { - if (Format == RTC_FORMAT_BIN) - { - if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) - { - assert_param(IS_RTC_HOUR12(sTime->Hours)); - assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); - } - else - { - sTime->TimeFormat = 0x00U; - 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) << RTC_TR_HU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sTime->Minutes) << RTC_TR_MNU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sTime->Seconds) << RTC_TR_SU_Pos) | \ - (((uint32_t)sTime->TimeFormat) << RTC_TR_PM_Pos)); - } - else - { - if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) - { - assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sTime->Hours))); - assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); - } - else - { - sTime->TimeFormat = 0x00U; - 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) << RTC_TR_HU_Pos) | \ - ((uint32_t)(sTime->Minutes) << RTC_TR_MNU_Pos) | \ - ((uint32_t)(sTime->Seconds) << RTC_TR_SU_Pos) | \ - ((uint32_t)(sTime->TimeFormat) << RTC_TR_PM_Pos)); - } - - /* Set the RTC_TR register */ - WRITE_REG(RTC->TR, (tmpreg & RTC_TR_RESERVED_MASK)); - - /* Clear the bits to be configured */ - CLEAR_BIT(RTC->CR, RTC_CR_BKP); - } - - /* Exit Initialization mode */ - status = RTC_ExitInitMode(hrtc); - } - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - - if (status == HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - } - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return status; -} - -/** - * @brief Get RTC current time. - * @note You can use SubSeconds and SecondFraction (sTime structure fields returned) to convert SubSeconds - * value in second fraction ratio with time unit following generic formula: - * Second fraction ratio * time_unit= [(SecondFraction-SubSeconds)/(SecondFraction+1)] * time_unit - * This conversion can be performed only if no shift operation is pending (ie. SHFP=0) when PREDIV_S >= SS - * @note You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values - * in the higher-order calendar shadow registers to ensure consistency between the time and date values. - * Reading RTC current time locks the values in calendar shadow registers until Current date is read - * to ensure consistency between the time and date values. - * @param hrtc RTC handle - * @param sTime - * if Binary mode is RTC_BINARY_ONLY, sTime->SubSeconds only is updated - * else - * Pointer to Time structure with Hours, Minutes and Seconds fields returned - * with input format (BIN or BCD), also SubSeconds field returning the - * RTC_SSR register content and SecondFraction field the Synchronous pre-scaler - * factor to be used for second fraction ratio computation. - * @param Format Format of sTime->Hours, sTime->Minutes and sTime->Seconds. - * if Binary mode is RTC_BINARY_ONLY, this parameter is not used - * else this parameter can be one of the following values: - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_GetTime(const RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) -{ - uint32_t tmpreg; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Get subseconds structure field from the corresponding register */ - sTime->SubSeconds = READ_REG(RTC->SSR); - - if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) != RTC_BINARY_ONLY) - { - /* Check the parameters */ - assert_param(IS_RTC_FORMAT(Format)); - - /* Get SecondFraction structure field from the corresponding register field */ - sTime->SecondFraction = (uint32_t)(READ_REG(RTC->PRER) & RTC_PRER_PREDIV_S); - - /* Get the TR register */ - tmpreg = (uint32_t)(READ_REG(RTC->TR) & RTC_TR_RESERVED_MASK); - - /* Fill the structure fields with the read parameters */ - sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> RTC_TR_HU_Pos); - sTime->Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >> RTC_TR_MNU_Pos); - sTime->Seconds = (uint8_t)((tmpreg & (RTC_TR_ST | RTC_TR_SU)) >> RTC_TR_SU_Pos); - sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TR_PM)) >> RTC_TR_PM_Pos); - - /* Check the input parameters format */ - if (Format == RTC_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 Set RTC current date. - * @param hrtc RTC handle - * @param sDate Pointer to date structure - * @param Format Format of sDate->Year, sDate->Month and sDate->Weekday. - * This parameter can be one of the following values: - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) -{ - uint32_t datetmpreg; - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_RTC_FORMAT(Format)); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - if ((Format == RTC_FORMAT_BIN) && ((sDate->Month & 0x10U) == 0x10U)) - { - sDate->Month = (uint8_t)((sDate->Month & (uint8_t)~(0x10U)) + (uint8_t)0x0AU); - } - - assert_param(IS_RTC_WEEKDAY(sDate->WeekDay)); - - if (Format == RTC_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) << RTC_DR_YU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sDate->Month) << RTC_DR_MU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sDate->Date) << RTC_DR_DU_Pos) | \ - ((uint32_t)sDate->WeekDay << RTC_DR_WDU_Pos)); - } - else - { - assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year))); - assert_param(IS_RTC_MONTH(RTC_Bcd2ToByte(sDate->Month))); - assert_param(IS_RTC_DATE(RTC_Bcd2ToByte(sDate->Date))); - - datetmpreg = ((((uint32_t)sDate->Year) << RTC_DR_YU_Pos) | \ - (((uint32_t)sDate->Month) << RTC_DR_MU_Pos) | \ - (((uint32_t)sDate->Date) << RTC_DR_DU_Pos) | \ - (((uint32_t)sDate->WeekDay) << RTC_DR_WDU_Pos)); - } - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Enter Initialization mode */ - status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { - /* Set the RTC_DR register */ - WRITE_REG(RTC->DR, (uint32_t)(datetmpreg & RTC_DR_RESERVED_MASK)); - - /* Exit Initialization mode */ - status = RTC_ExitInitMode(hrtc); - } - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - - if (status == HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - } - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return status; -} - -/** - * @brief Get RTC current date. - * @note You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values - * in the higher-order calendar shadow registers to ensure consistency between the time and date values. - * Reading RTC current time locks the values in calendar shadow registers until Current date is read. - * @param hrtc RTC handle - * @param sDate Pointer to Date structure - * @param Format Format of sDate->Year, sDate->Month and sDate->Weekday. - * This parameter can be one of the following values: - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_GetDate(const RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) -{ - uint32_t datetmpreg; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_FORMAT(Format)); - - /* Get the DR register */ - datetmpreg = (uint32_t)(READ_REG(RTC->DR) & RTC_DR_RESERVED_MASK); - - /* Fill the structure fields with the read parameters */ - sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> RTC_DR_YU_Pos); - sDate->Month = (uint8_t)((datetmpreg & (RTC_DR_MT | RTC_DR_MU)) >> RTC_DR_MU_Pos); - sDate->Date = (uint8_t)((datetmpreg & (RTC_DR_DT | RTC_DR_DU)) >> RTC_DR_DU_Pos); - sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DR_WDU)) >> RTC_DR_WDU_Pos); - - /* Check the input parameters format */ - if (Format == RTC_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; -} - -/** - * @brief Daylight Saving Time, Add one hour to the calendar in one single operation - * without going through the initialization procedure. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTC_DST_Add1Hour(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Set RTC_CR_ADD1H Bit */ - SET_BIT(RTC->CR, RTC_CR_ADD1H); - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); -} - -/** - * @brief Daylight Saving Time, Subtract one hour from the calendar in one - * single operation without going through the initialization procedure. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTC_DST_Sub1Hour(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Set RTC_CR_SUB1H Bit */ - SET_BIT(RTC->CR, RTC_CR_SUB1H); - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); -} - -/** - * @brief Daylight Saving Time, Set the store operation bit. - * @note It can be used by the software in order to memorize the DST status. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTC_DST_SetStoreOperation(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Set RTC_CR_BKP Bit */ - SET_BIT(RTC->CR, RTC_CR_BKP); -} - -/** - * @brief Daylight Saving Time, Clear the store operation bit. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTC_DST_ClearStoreOperation(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Clear RTC_CR_BKP Bit */ - CLEAR_BIT(RTC->CR, RTC_CR_BKP); -} - -/** - * @brief Daylight Saving Time, Read the store operation bit. - * @param hrtc RTC handle - * @retval operation see RTC_StoreOperation_Definitions - */ -uint32_t HAL_RTC_DST_ReadStoreOperation(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Get RTC_CR_BKP Bit */ - return READ_BIT(RTC->CR, RTC_CR_BKP); -} - - -/** - * @} - */ - -/** @addtogroup RTC_Exported_Functions_Group3 - * @brief RTC Alarm functions - * -@verbatim - =============================================================================== - ##### RTC Alarm functions ##### - =============================================================================== - - [..] This section provides functions allowing to configure Alarm feature - -@endverbatim - * @{ - */ -/** - * @brief Set the specified RTC Alarm. - * @param hrtc RTC handle - * @param sAlarm Pointer to Alarm structure - * if Binary mode is RTC_BINARY_ONLY, 3 fields only are used - * sAlarm->AlarmTime.SubSeconds - * sAlarm->AlarmSubSecondMask - * sAlarm->BinaryAutoClr - * @param Format of the entered parameters. - * if Binary mode is RTC_BINARY_ONLY, this parameter is not used - * else this parameter can be one of the following values - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) -{ - uint32_t tmpreg = 0; - uint32_t binary_mode; - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - -#ifdef USE_FULL_ASSERT - /* Check the parameters depending of the Binary mode (32-bit free-running counter configuration) */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_NONE) - { - assert_param(IS_RTC_FORMAT(Format)); - assert_param(IS_RTC_ALARM(sAlarm->Alarm)); - assert_param(IS_RTC_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)); - } - else if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_ONLY) - { - assert_param(IS_RTC_ALARM_SUB_SECOND_BINARY_MASK(sAlarm->AlarmSubSecondMask)); - assert_param(IS_RTC_ALARMSUBSECONDBIN_AUTOCLR(sAlarm->BinaryAutoClr)); - } - else /* RTC_BINARY_MIX */ - { - assert_param(IS_RTC_FORMAT(Format)); - assert_param(IS_RTC_ALARM(sAlarm->Alarm)); - assert_param(IS_RTC_ALARM_MASK(sAlarm->AlarmMask)); - assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); - /* In Binary Mix Mode, the RTC can not generate an alarm on a match - involving all calendar items + the upper SSR bits */ - assert_param((sAlarm->AlarmSubSecondMask >> RTC_ALRMASSR_MASKSS_Pos) <= - (8U + (READ_BIT(RTC->ICSR, RTC_ICSR_BCDU) >> RTC_ICSR_BCDU_Pos))); - } -#endif /* USE_FULL_ASSERT */ - - /* Get Binary mode (32-bit free-running counter configuration) */ - binary_mode = READ_BIT(RTC->ICSR, RTC_ICSR_BIN); - - if (binary_mode != RTC_BINARY_ONLY) - { - if (Format == RTC_FORMAT_BIN) - { - if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) - { - assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); - assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); - } - else - { - sAlarm->AlarmTime.TimeFormat = 0x00U; - 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) << RTC_ALRMAR_HU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ - ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ - ((uint32_t)sAlarm->AlarmMask)); - } - else /* format BCD */ - { - if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) - { - assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); - assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); - } - else - { - sAlarm->AlarmTime.TimeFormat = 0x00U; - 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))); - -#ifdef USE_FULL_ASSERT - if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) - { - assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); - } - else - { - assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); - } - -#endif /* USE_FULL_ASSERT */ - tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ - ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ - ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ - ((uint32_t)sAlarm->AlarmMask)); - } - } - - /* Configure the Alarm register */ - if (sAlarm->Alarm == RTC_ALARM_A) - { - /* Disable the Alarm A interrupt */ - - /* In case of interrupt mode is used, the interrupt source must disabled */ - CLEAR_BIT(RTC->CR, (RTC_CR_ALRAE | RTC_CR_ALRAIE)); - - /* Clear flag alarm A */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); - - if (binary_mode == RTC_BINARY_ONLY) - { - WRITE_REG(RTC->ALRMASSR, sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr); - } - else - { - WRITE_REG(RTC->ALRMAR, tmpreg); - WRITE_REG(RTC->ALRMASSR, sAlarm->AlarmSubSecondMask); - } - - WRITE_REG(RTC->ALRABINR, sAlarm->AlarmTime.SubSeconds); - - if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) - { - /* Configure the Alarm A output clear */ - SET_BIT(RTC->CR, RTC_CR_ALRAFCLR); - } - else - { - /* Disable the Alarm A output clear */ - CLEAR_BIT(RTC->CR, RTC_CR_ALRAFCLR); - } - /* Configure the Alarm state: Enable Alarm */ - SET_BIT(RTC->CR, RTC_CR_ALRAE); - } - else - { - /* Disable the Alarm B interrupt */ - - /* In case of interrupt mode is used, the interrupt source must disabled */ - CLEAR_BIT(RTC->CR, (RTC_CR_ALRBE | RTC_CR_ALRBIE)); - - /* Clear flag alarm B */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); - - if (binary_mode == RTC_BINARY_ONLY) - { - WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr); - } - else - { - WRITE_REG(RTC->ALRMBR, tmpreg); - - WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask); - } - - WRITE_REG(RTC->ALRBBINR, sAlarm->AlarmTime.SubSeconds); - - if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) - { - /* Configure the Alarm B output clear */ - SET_BIT(RTC->CR, RTC_CR_ALRBFCLR); - } - else - { - /* Disable the Alarm B output clear */ - CLEAR_BIT(RTC->CR, RTC_CR_ALRBFCLR); - } - - /* Configure the Alarm state: Enable Alarm */ - SET_BIT(RTC->CR, RTC_CR_ALRBE); - } - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Set the specified RTC Alarm with Interrupt. - * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. - * @param hrtc RTC handle - * @param sAlarm Pointer to Alarm structure - * if Binary mode is RTC_BINARY_ONLY, 3 fields only are used - * sAlarm->AlarmTime.SubSeconds - * sAlarm->AlarmSubSecondMask - * sAlarm->BinaryAutoClr - * @param Format Specifies the format of the entered parameters. - * if Binary mode is RTC_BINARY_ONLY, this parameter is not used - * else this parameter can be one of the following values - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) -{ - uint32_t tmpreg = 0; - uint32_t binary_mode; - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - -#ifdef USE_FULL_ASSERT - /* Check the parameters depending of the Binary mode (32-bit free-running counter configuration) */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_NONE) - { - assert_param(IS_RTC_FORMAT(Format)); - assert_param(IS_RTC_ALARM(sAlarm->Alarm)); - assert_param(IS_RTC_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)); - } - else if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_ONLY) - { - assert_param(IS_RTC_ALARM_SUB_SECOND_BINARY_MASK(sAlarm->AlarmSubSecondMask)); - assert_param(IS_RTC_ALARMSUBSECONDBIN_AUTOCLR(sAlarm->BinaryAutoClr)); - } - else /* RTC_BINARY_MIX */ - { - assert_param(IS_RTC_FORMAT(Format)); - assert_param(IS_RTC_ALARM(sAlarm->Alarm)); - assert_param(IS_RTC_ALARM_MASK(sAlarm->AlarmMask)); - assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); - /* In Binary Mix Mode, the RTC can not generate an alarm on a match - involving all calendar items + the upper SSR bits */ - assert_param((sAlarm->AlarmSubSecondMask >> RTC_ALRMASSR_MASKSS_Pos) <= - (8U + (READ_BIT(RTC->ICSR, RTC_ICSR_BCDU) >> RTC_ICSR_BCDU_Pos))); - } -#endif /* USE_FULL_ASSERT */ - - /* Get Binary mode (32-bit free-running counter configuration) */ - binary_mode = READ_BIT(RTC->ICSR, RTC_ICSR_BIN); - - if (binary_mode != RTC_BINARY_ONLY) - { - if (Format == RTC_FORMAT_BIN) - { - if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) - { - assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); - assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); - } - else - { - sAlarm->AlarmTime.TimeFormat = 0x00U; - 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) << RTC_ALRMAR_HU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ - ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ - ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ - ((uint32_t)sAlarm->AlarmMask)); - } - else /* Format BCD */ - { - if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) - { - assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); - assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); - } - else - { - sAlarm->AlarmTime.TimeFormat = 0x00U; - 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))); - -#ifdef USE_FULL_ASSERT - if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) - { - assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); - } - else - { - assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); - } - -#endif /* USE_FULL_ASSERT */ - tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ - ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ - ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ - ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ - ((uint32_t)sAlarm->AlarmMask)); - - } - } - - /* Configure the Alarm registers */ - if (sAlarm->Alarm == RTC_ALARM_A) - { - /* Disable the Alarm A interrupt */ - CLEAR_BIT(RTC->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE); - - /* Clear flag alarm A */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); - - if (binary_mode == RTC_BINARY_ONLY) - { - RTC->ALRMASSR = sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr; - } - else - { - WRITE_REG(RTC->ALRMAR, tmpreg); - - WRITE_REG(RTC->ALRMASSR, sAlarm->AlarmSubSecondMask); - } - - WRITE_REG(RTC->ALRABINR, sAlarm->AlarmTime.SubSeconds); - - if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) - { - /* Configure the Alarm A output clear */ - SET_BIT(RTC->CR, RTC_CR_ALRAFCLR); - } - else - { - /* Disable the Alarm A output clear */ - CLEAR_BIT(RTC->CR, RTC_CR_ALRAFCLR); - } - - /* Configure the Alarm interrupt */ - SET_BIT(RTC->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE); - } - else - { - /* Disable the Alarm B interrupt */ - CLEAR_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE); - - /* Clear flag alarm B */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); - - if (binary_mode == RTC_BINARY_ONLY) - { - WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr); - } - else - { - WRITE_REG(RTC->ALRMBR, tmpreg); - - WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask); - } - - WRITE_REG(RTC->ALRBBINR, sAlarm->AlarmTime.SubSeconds); - - if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) - { - /* Configure the Alarm B Output clear */ - SET_BIT(RTC->CR, RTC_CR_ALRBFCLR); - } - else - { - /* Disable the Alarm B Output clear */ - CLEAR_BIT(RTC->CR, RTC_CR_ALRBFCLR); - } - - /* Configure the Alarm interrupt */ - SET_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE); - } - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Deactivate the specified RTC Alarm. - * @param hrtc RTC handle - * @param Alarm Specifies the Alarm. - * This parameter can be one of the following values: - * @arg RTC_ALARM_A: AlarmA - * @arg RTC_ALARM_B: AlarmB - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm) -{ - /* Check the parameters */ - assert_param(IS_RTC_ALARM(Alarm)); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* In case of interrupt mode is used, the interrupt source must disabled */ - if (Alarm == RTC_ALARM_A) - { - CLEAR_BIT(RTC->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE); - - /* AlarmA, Clear SSCLR */ - CLEAR_BIT(RTC->ALRMASSR, RTC_ALRMASSR_SSCLR); - } - else - { - CLEAR_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE); - - /* AlarmB, Clear SSCLR */ - CLEAR_BIT(RTC->ALRMBSSR, RTC_ALRMBSSR_SSCLR); - } - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Get 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 RTC_ALARM_A: AlarmA - * @arg RTC_ALARM_B: AlarmB - * @param Format Specifies the format of the entered parameters. - * This parameter can be one of the following values: - * @arg RTC_FORMAT_BIN: Binary format - * @arg RTC_FORMAT_BCD: BCD format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_GetAlarm(const RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, - uint32_t Format) -{ - uint32_t tmpreg; - uint32_t subsecondtmpreg; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_FORMAT(Format)); - assert_param(IS_RTC_ALARM(Alarm)); - - if (Alarm == RTC_ALARM_A) - { - /* AlarmA */ - sAlarm->Alarm = RTC_ALARM_A; - - tmpreg = READ_REG(RTC->ALRMAR); - subsecondtmpreg = (uint32_t)(READ_REG(RTC->ALRMASSR) & RTC_ALRMASSR_SS); - - /* Fill the structure with the read parameters */ - sAlarm->AlarmTime.Hours = (uint8_t)((tmpreg & (RTC_ALRMAR_HT | RTC_ALRMAR_HU)) >> RTC_ALRMAR_HU_Pos); - sAlarm->AlarmTime.Minutes = (uint8_t)((tmpreg & (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU)) >> RTC_ALRMAR_MNU_Pos); - sAlarm->AlarmTime.Seconds = (uint8_t)((tmpreg & (RTC_ALRMAR_ST | RTC_ALRMAR_SU)) >> RTC_ALRMAR_SU_Pos); - sAlarm->AlarmTime.TimeFormat = (uint8_t)((tmpreg & RTC_ALRMAR_PM) >> RTC_ALRMAR_PM_Pos); - sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; - sAlarm->AlarmDateWeekDay = (uint8_t)((tmpreg & (RTC_ALRMAR_DT | RTC_ALRMAR_DU)) >> RTC_ALRMAR_DU_Pos); - sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMAR_WDSEL); - sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL); - } - else - { - sAlarm->Alarm = RTC_ALARM_B; - - tmpreg = READ_REG(RTC->ALRMBR); - subsecondtmpreg = (uint32_t)(READ_REG(RTC->ALRMBSSR) & RTC_ALRMBSSR_SS); - - /* Fill the structure with the read parameters */ - sAlarm->AlarmTime.Hours = (uint8_t)((tmpreg & (RTC_ALRMBR_HT | RTC_ALRMBR_HU)) >> RTC_ALRMBR_HU_Pos); - sAlarm->AlarmTime.Minutes = (uint8_t)((tmpreg & (RTC_ALRMBR_MNT | RTC_ALRMBR_MNU)) >> RTC_ALRMBR_MNU_Pos); - sAlarm->AlarmTime.Seconds = (uint8_t)((tmpreg & (RTC_ALRMBR_ST | RTC_ALRMBR_SU)) >> RTC_ALRMBR_SU_Pos); - sAlarm->AlarmTime.TimeFormat = (uint8_t)((tmpreg & RTC_ALRMBR_PM) >> RTC_ALRMBR_PM_Pos); - sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; - sAlarm->AlarmDateWeekDay = (uint8_t)((tmpreg & (RTC_ALRMBR_DT | RTC_ALRMBR_DU)) >> RTC_ALRMBR_DU_Pos); - sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMBR_WDSEL); - sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL); - } - - if (Format == RTC_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 Handle Alarm interrupt request. - * @note Alarm is available in driver. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc) -{ - /* Get interrupt status */ - uint32_t tmp = READ_REG(RTC->MISR); - - if ((tmp & RTC_MISR_ALRAMF) != 0U) - { - /* Clear the AlarmA interrupt pending bit */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); - -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Compare Match registered Callback */ - hrtc->AlarmAEventCallback(hrtc); -#else - HAL_RTC_AlarmAEventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - if ((tmp & RTC_MISR_ALRBMF) != 0U) - { - /* Clear the AlarmB interrupt pending bit */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); - -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Compare Match registered Callback */ - hrtc->AlarmBEventCallback(hrtc); -#else - HAL_RTCEx_AlarmBEventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Handle Alarm A Polling request. - * @param hrtc RTC handle - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - uint32_t tickstart = HAL_GetTick(); - - while (READ_BIT(RTC->SR, RTC_SR_ALRAF) == 0U) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->SR, RTC_SR_ALRAF) == 0U) - { - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Clear the Alarm interrupt pending bit */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); - - return HAL_OK; -} - -/** - * @} - */ - -/** @addtogroup RTC_Exported_Functions_Group4 - * @brief Peripheral Control functions - * -@verbatim - =============================================================================== - ##### Peripheral Control functions ##### - =============================================================================== - [..] - This subsection provides functions allowing to - (+) Wait for RTC Time and Date Synchronization - -@endverbatim - * @{ - */ - -/** - * @brief Wait 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 tickstart; - - /* Clear RSF flag */ - CLEAR_BIT(RTC->ICSR, RTC_ICSR_RSF); - - tickstart = HAL_GetTick(); - - /* Wait the registers to be synchronised */ - while (READ_BIT(RTC->ICSR, RTC_ICSR_RSF) == 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_RSF) == 0U) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - - return HAL_OK; -} - -/** - * @} - */ - -/** @addtogroup RTC_Exported_Functions_Group5 - * @brief Peripheral State functions - * -@verbatim - =============================================================================== - ##### Peripheral State functions ##### - =============================================================================== - [..] - This subsection provides functions allowing to - (+) Get RTC state - -@endverbatim - * @{ - */ -/** - * @brief Return the RTC handle state. - * @param hrtc RTC handle - * @retval HAL state - */ -HAL_RTCStateTypeDef HAL_RTC_GetState(const RTC_HandleTypeDef *hrtc) -{ - /* Return RTC handle state */ - return hrtc->State; -} - -/** - * @} - */ -/** - * @} - */ - -/** @addtogroup RTC_Private_Functions - * @{ - */ -/** - * @brief Enter 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 tickstart; - HAL_StatusTypeDef status = HAL_OK; - - /* Check if the Initialization mode is set */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) - { - /* Set the Initialization mode */ - SET_BIT(RTC->ICSR, RTC_ICSR_INIT); - - tickstart = HAL_GetTick(); - /* Wait till RTC is in INIT state and if Time out is reached exit */ - while ((READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) && (status != HAL_TIMEOUT)) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) - { - status = HAL_TIMEOUT; - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - } - else - { - break; - } - } - } - } - - return status; -} - -/** - * @brief Exit the RTC Initialization mode. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef *hrtc) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Exit Initialization mode */ - CLEAR_BIT(RTC->ICSR, RTC_ICSR_INIT); - - /* If CR_BYPSHAD bit = 0, wait for synchro */ - if (READ_BIT(RTC->CR, RTC_CR_BYPSHAD) == 0U) - { - if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - status = HAL_TIMEOUT; - } - } - else /* WA 2.9.6 Calendar initialization may fail in case of consecutive INIT mode entry. */ - { - /* Clear BYPSHAD bit */ - CLEAR_BIT(RTC->CR, RTC_CR_BYPSHAD); - if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - status = HAL_TIMEOUT; - } - /* Restore BYPSHAD bit */ - SET_BIT(RTC->CR, RTC_CR_BYPSHAD); - } - return status; -} - -/** - * @brief Convert 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 bcd_high = 0U; - uint8_t tmp_value = Value; - - while (tmp_value >= 10U) - { - bcd_high++; - tmp_value -= 10U; - } - - return ((uint8_t)(bcd_high << 4U) | tmp_value); -} - -/** - * @brief Convert 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; - - tmp = (((uint32_t)Value & 0xF0U) >> 4) * 10U; - - return (uint8_t)(tmp + ((uint32_t)Value & 0x0FU)); -} - -/** - * @} - */ - -#endif /* HAL_RTC_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_rtc.c + * @author MCD Application Team + * @brief RTC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Real-Time Clock (RTC) peripheral: + * + Initialization/de-initialization functions + * + Calendar (Time and Date) configuration + * + Alarms (Alarm A and Alarm B) configuration + * + WakeUp Timer configuration + * + TimeStamp configuration + * + Tampers configuration + * + Backup Data Registers configuration + * + RTC Tamper and TimeStamp Pins Selection + * + Interrupts and flags management + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + =============================================================================== + ##### RTC Operating Condition ##### + =============================================================================== + [..] The real-time clock (RTC) and the RTC backup registers can be powered + from the VBAT voltage when the main VDD supply is powered off. + To retain the content of the RTC backup registers 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. + + ##### Backup Domain Reset ##### + =============================================================================== + [..] The backup domain reset sets all RTC registers and the RCC_BDCR register + to their reset values. + 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. + (#) Tamper detection event resets all data backup registers. + + ##### Backup Domain Access ##### + ================================================================== + [..] After reset, the backup domain (RTC registers and RTC backup data registers) + is protected against possible unwanted write accesses. + [..] To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + (+) Call the function HAL_RCCEx_PeriphCLKConfig with RCC_PERIPHCLK_RTC for + PeriphClockSelection and select RTCClockSelection (LSE, LSI or HSEdiv32) + (+) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function. + + ##### How to use RTC 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. + + *** Callback registration *** + ============================================= + When The compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. This is the recommended configuration + in order to optimize memory/code consumption footprint/performances. + + The compilation define USE_RTC_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Function HAL_RTC_RegisterCallback() to register an interrupt callback. + + Function HAL_RTC_RegisterCallback() allows to register following callbacks: + (+) AlarmAEventCallback : RTC Alarm A Event callback. + (+) AlarmBEventCallback : RTC Alarm B Event callback. + (+) TimeStampEventCallback : RTC TimeStamp Event callback. + (+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback. + (+) SSRUEventCallback : RTC SSRU Event callback. + (+) Tamper1EventCallback : RTC Tamper 1 Event callback. + (+) Tamper2EventCallback : RTC Tamper 2 Event callback. + (+) Tamper3EventCallback : RTC Tamper 3 Event callback. + (+) Tamper4EventCallback : RTC Tamper 4 Event callback. + (+) Tamper5EventCallback : RTC Tamper 5 Event callback. + (+) Tamper6EventCallback : RTC Tamper 6 Event callback. + (+) Tamper7EventCallback : RTC Tamper 7 Event callback. + (+) Tamper8EventCallback : RTC Tamper 8 Event callback. + (+) InternalTamper1EventCallback : RTC InternalTamper 1 Event callback. + (+) InternalTamper2EventCallback : RTC InternalTamper 2 Event callback. + (+) InternalTamper3EventCallback : RTC InternalTamper 3 Event callback. + (+) InternalTamper4EventCallback : RTC InternalTamper 4 Event callback. + (+) InternalTamper5EventCallback : RTC InternalTamper 5 Event callback. + (+) InternalTamper6EventCallback : RTC InternalTamper 6 Event callback. + (+) InternalTamper7EventCallback : RTC InternalTamper 7 Event callback. + (+) InternalTamper8EventCallback : RTC InternalTamper 8 Event callback. + (+) InternalTamper9EventCallback : RTC InternalTamper 9 Event callback. + (+) InternalTamper11EventCallback : RTC InternalTamper 11 Event callback. + (+) InternalTamper15EventCallback : RTC InternalTamper 15 Event callback. + (+) MspInitCallback : RTC MspInit callback. + (+) MspDeInitCallback : RTC MspDeInit callback. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function HAL_RTC_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_RTC_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) AlarmAEventCallback : RTC Alarm A Event callback. + (+) AlarmBEventCallback : RTC Alarm B Event callback. + (+) TimeStampEventCallback : RTC TimeStamp Event callback. + (+) WakeUpTimerEventCallback : RTC WakeUpTimer Event callback. + (+) SSRUEventCallback : RTC SSRU Event callback. + (+) Tamper1EventCallback : RTC Tamper 1 Event callback. + (+) Tamper2EventCallback : RTC Tamper 2 Event callback. + (+) Tamper3EventCallback : RTC Tamper 3 Event callback. + (+) Tamper4EventCallback : RTC Tamper 4 Event callback. + (+) Tamper5EventCallback : RTC Tamper 5 Event callback. + (+) Tamper6EventCallback : RTC Tamper 6 Event callback. + (+) Tamper7EventCallback : RTC Tamper 7 Event callback. + (+) Tamper8EventCallback : RTC Tamper 8 Event callback. + (+) InternalTamper1EventCallback : RTC InternalTamper 1 Event callback. + (+) InternalTamper2EventCallback : RTC InternalTamper 2 Event callback. + (+) InternalTamper3EventCallback : RTC InternalTamper 3 Event callback. + (+) InternalTamper4EventCallback : RTC InternalTamper 4 Event callback. + (+) InternalTamper5EventCallback : RTC InternalTamper 5 Event callback. + (+) InternalTamper6EventCallback : RTC InternalTamper 6 Event callback. + (+) InternalTamper7EventCallback : RTC InternalTamper 7 Event callback. + (+) InternalTamper8EventCallback : RTC InternalTamper 8 Event callback. + (+) InternalTamper9EventCallback : RTC InternalTamper 9 Event callback. + (+) InternalTamper11EventCallback : RTC InternalTamper 11 Event callback. + (+) InternalTamper15EventCallback : RTC InternalTamper 15 Event callback. + (+) MspInitCallback : RTC MspInit callback. + (+) MspDeInitCallback : RTC MspDeInit callback. + + By default, after the HAL_RTC_Init() and when the state is HAL_RTC_STATE_RESET, + all callbacks are set to the corresponding weak functions : + examples AlarmAEventCallback(), TimeStampEventCallback(). + Exception done for MspInit and MspDeInit callbacks that are reset to the legacy weak function + in the HAL_RTC_Init()/HAL_RTC_DeInit() only when these callbacks are null + (not registered beforehand). + If not, MspInit or MspDeInit are not null, HAL_RTC_Init()/HAL_RTC_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in HAL_RTC_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_RTC_STATE_READY or HAL_RTC_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_RTC_RegisterCallback() before calling HAL_RTC_DeInit() + or HAL_RTC_Init() function. + + When The compilation define USE_HAL_RTC_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + + +/** @addtogroup RTC + * @brief RTC HAL module driver + * @{ + */ + +#ifdef HAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup RTC_Exported_Functions + * @{ + */ + +/** @addtogroup RTC_Exported_Functions_Group1 + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides 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 15-bit synchronous prescaler. + (++) When both prescalers are used, it is recommended to configure the + asynchronous prescaler to a high value to minimize power 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 Initialize the RTC peripheral + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the RTC peripheral state */ + if (hrtc != NULL) + { + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance)); + 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)); +#if defined(RTC_CR_OSEL) + 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)); + assert_param(IS_RTC_OUTPUT_PULLUP(hrtc->Init.OutPutPullUp)); +#endif /* RTC_CR_OSEL */ +#if defined(RTC_CR_OUT2EN) + assert_param(IS_RTC_OUTPUT_REMAP(hrtc->Init.OutPutRemap)); +#endif /* RTC_CR_OUT2EN */ + assert_param(IS_RTC_BINARY_MODE(hrtc->Init.BinMode)); + assert_param(IS_RTC_BINARY_MIX_BCDU(hrtc->Init.BinMixBcdU)); + +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + if (hrtc->State == HAL_RTC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrtc->Lock = HAL_UNLOCKED; + + /* Legacy weak AlarmAEventCallback */ + hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; + /* Legacy weak AlarmBEventCallback */ + hrtc->AlarmBEventCallback = HAL_RTCEx_AlarmBEventCallback; + /* Legacy weak TimeStampEventCallback */ + hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; + /* Legacy weak WakeUpTimerEventCallback */ + hrtc->WakeUpTimerEventCallback = HAL_RTCEx_WakeUpTimerEventCallback; + /* Legacy weak SSRUEventCallback */ + hrtc->SSRUEventCallback = HAL_RTCEx_SSRUEventCallback; + /* Legacy weak Tamper1EventCallback */ + hrtc->Tamper1EventCallback = HAL_RTCEx_Tamper1EventCallback; + /* Legacy weak Tamper2EventCallback */ + hrtc->Tamper2EventCallback = HAL_RTCEx_Tamper2EventCallback; + /* Legacy weak Tamper3EventCallback */ + hrtc->Tamper3EventCallback = HAL_RTCEx_Tamper3EventCallback; + /* Legacy weak Tamper4EventCallback */ + hrtc->Tamper4EventCallback = HAL_RTCEx_Tamper4EventCallback; + /* Legacy weak Tamper5EventCallback */ + hrtc->Tamper5EventCallback = HAL_RTCEx_Tamper5EventCallback; + /* Legacy weak Tamper6EventCallback */ + hrtc->Tamper6EventCallback = HAL_RTCEx_Tamper6EventCallback; + /* Legacy weak Tamper7EventCallback */ + hrtc->Tamper7EventCallback = HAL_RTCEx_Tamper7EventCallback; + /* Legacy weak Tamper8EventCallback */ + hrtc->Tamper8EventCallback = HAL_RTCEx_Tamper8EventCallback; + /* Legacy weak InternalTamper1EventCallback */ + hrtc->InternalTamper1EventCallback = HAL_RTCEx_InternalTamper1EventCallback; + /* Legacy weak InternalTamper2EventCallback */ + hrtc->InternalTamper2EventCallback = HAL_RTCEx_InternalTamper2EventCallback; + /* Legacy weak InternalTamper3EventCallback */ + hrtc->InternalTamper3EventCallback = HAL_RTCEx_InternalTamper3EventCallback; + /* Legacy weak InternalTamper4EventCallback */ + hrtc->InternalTamper4EventCallback = HAL_RTCEx_InternalTamper4EventCallback; + /* Legacy weak InternalTamper5EventCallback */ + hrtc->InternalTamper5EventCallback = HAL_RTCEx_InternalTamper5EventCallback; + /* Legacy weak InternalTamper6EventCallback */ + hrtc->InternalTamper6EventCallback = HAL_RTCEx_InternalTamper6EventCallback; + /* Legacy weak InternalTamper7EventCallback */ + hrtc->InternalTamper7EventCallback = HAL_RTCEx_InternalTamper7EventCallback; + /* Legacy weak InternalTamper8EventCallback */ + hrtc->InternalTamper8EventCallback = HAL_RTCEx_InternalTamper8EventCallback; + /* Legacy weak InternalTamper9EventCallback */ + hrtc->InternalTamper9EventCallback = HAL_RTCEx_InternalTamper9EventCallback; + /* Legacy weak InternalTamper11EventCallback */ + hrtc->InternalTamper11EventCallback = HAL_RTCEx_InternalTamper11EventCallback; + /* Legacy weak InternalTamper15EventCallback */ + hrtc->InternalTamper15EventCallback = HAL_RTCEx_InternalTamper15EventCallback; + + if (hrtc->MspInitCallback == NULL) + { + hrtc->MspInitCallback = HAL_RTC_MspInit; + } + /* Init the low level hardware */ + hrtc->MspInitCallback(hrtc); + + if (hrtc->MspDeInitCallback == NULL) + { + hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; + } + } +#else + if (hrtc->State == HAL_RTC_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrtc->Lock = HAL_UNLOCKED; + + /* Initialize RTC MSP */ + HAL_RTC_MspInit(hrtc); + } +#endif /* (USE_HAL_RTC_REGISTER_CALLBACKS) */ + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Check if the calendar has been not initialized */ + if (__HAL_RTC_IS_CALENDAR_INITIALIZED(hrtc) == 0U) + { + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + if (status == HAL_OK) + { +#if defined(RTC_CR_OSEL) + /* Clear RTC_CR FMT, OSEL and POL Bits */ + CLEAR_BIT(RTC->CR, (RTC_CR_FMT | RTC_CR_POL | RTC_CR_OSEL | RTC_CR_TAMPOE)); + + /* Set RTC_CR register */ + SET_BIT(RTC->CR, (hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity)); +#else + /* Clear RTC_CR FMT Bits */ + CLEAR_BIT(RTC->CR, RTC_CR_FMT); + + /* Set RTC_CR register */ + SET_BIT(RTC->CR, hrtc->Init.HourFormat); +#endif /* RTC_CR_OSEL */ + + /* Configure the RTC PRER */ + WRITE_REG(RTC->PRER, ((hrtc->Init.SynchPrediv) | (hrtc->Init.AsynchPrediv << RTC_PRER_PREDIV_A_Pos))); + + /* Configure the Binary mode */ + MODIFY_REG(RTC->ICSR, RTC_ICSR_BIN | RTC_ICSR_BCDU, hrtc->Init.BinMode | hrtc->Init.BinMixBcdU); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + +#if defined(RTC_CR_OSEL) + if (status == HAL_OK) + { +#if defined(RTC_CR_OUT2EN) + MODIFY_REG(RTC->CR, \ + RTC_CR_TAMPALRM_PU | RTC_CR_TAMPALRM_TYPE | RTC_CR_OUT2EN, \ + hrtc->Init.OutPutPullUp | hrtc->Init.OutPutType | hrtc->Init.OutPutRemap); +#else + MODIFY_REG(RTC->CR, \ + RTC_CR_TAMPALRM_PU | RTC_CR_TAMPALRM_TYPE, \ + hrtc->Init.OutPutPullUp | hrtc->Init.OutPutType); +#endif /* RTC_CR_OUT2EN */ + } +#endif /* RTC_CR_OSEL */ + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + } + else + { + /* Calendar is already initialized */ + /* Set flag to OK */ + status = HAL_OK; + } + + if (status == HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + } + } + + return status; +} + +/** + * @brief DeInitialize the RTC peripheral. + * @note This function does not reset the RTC Backup Data registers. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) +{ + HAL_StatusTypeDef status = HAL_ERROR; + uint32_t tickstart; + + /* Check RTC handler */ + if (hrtc != NULL) + { + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance)); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + if (status == HAL_OK) + { + /* Reset All CR bits except CR[2:0] (which cannot be written before bit + WUTE of CR is cleared) */ + CLEAR_REG(RTC->CR); + + /* Reset TR and DR registers */ + WRITE_REG(RTC->DR, (uint32_t)(RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); + CLEAR_REG(RTC->TR); + + /* Reset other RTC registers */ + WRITE_REG(RTC->PRER, ((uint32_t)(RTC_PRER_PREDIV_A | 0xFFU))); + CLEAR_REG(RTC->ALRMAR); + CLEAR_REG(RTC->ALRMBR); + CLEAR_REG(RTC->SHIFTR); + CLEAR_REG(RTC->CALR); + CLEAR_REG(RTC->ALRMASSR); + CLEAR_REG(RTC->ALRMBSSR); + CLEAR_BIT(RTC->ICSR, (RTC_ICSR_BCDU_Msk | RTC_ICSR_BIN_Msk)); + WRITE_REG(RTC->SCR, RTC_SCR_CITSF | RTC_SCR_CTSOVF | RTC_SCR_CTSF | RTC_SCR_CWUTF | RTC_SCR_CALRBF | \ + RTC_SCR_CALRAF); +#if defined (RTC_PRIVCFGR_ALRAPRIV) + CLEAR_REG(RTC->PRIVCFGR); +#endif /* RTC_PRIVCFGR_ALRAPRIV */ + + /* Exit initialization mode */ + status = RTC_ExitInitMode(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + } + + if (status == HAL_OK) + { + /* Wait till WUTWF is set (to be able to reset CR[2:0] and WUTR) and if + timeout is reached exit */ + tickstart = HAL_GetTick(); + + while ((((hrtc->Instance->ICSR) & RTC_ICSR_WUTWF) == 0U) && (status != HAL_TIMEOUT)) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) + { + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + status = HAL_TIMEOUT; + } + else + { + break; + } + } + } + + /* Reset RTC CR register bits [2:0] */ + CLEAR_REG(RTC->CR); + + /* Reset RTC WUTR register */ + WRITE_REG(RTC->WUTR, RTC_WUTR_WUT); + + /* Reset TAMP registers */ + CLEAR_REG(TAMP->CR1); + CLEAR_REG(TAMP->CR2); + CLEAR_REG(TAMP->CR3); + CLEAR_REG(TAMP->FLTCR); + WRITE_REG(TAMP->ATCR1, TAMP_ATCR1_ATCKSEL); + CLEAR_REG(TAMP->ATOR); + CLEAR_REG(TAMP->ATCR2); + CLEAR_REG(TAMP->PRIVCFGR); + +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + if (hrtc->MspDeInitCallback == NULL) + { + hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; + } + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + hrtc->MspDeInitCallback(hrtc); + +#else + /* De-Initialize RTC MSP */ + HAL_RTC_MspDeInit(hrtc); +#endif /* (USE_HAL_RTC_REGISTER_CALLBACKS) */ + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hrtc); + + } + } + + return status; +} + +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User RTC Callback + * To be used instead of the weak predefined callback + * @param hrtc RTC handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_RTC_ALARM_A_EVENT_CB_ID Alarm A Event Callback ID + * @arg @ref HAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID + * @arg @ref HAL_RTC_TIMESTAMP_EVENT_CB_ID TimeStamp Event Callback ID + * @arg @ref HAL_RTC_WAKEUPTIMER_EVENT_CB_ID WakeUp Timer Event Callback ID + * @arg @ref HAL_RTC_SSRU_EVENT_CB_ID SSRU Event Callback ID + * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID + * @arg @ref HAL_RTC_TAMPER2_EVENT_CB_ID Tamper 2 Callback ID + * @arg @ref HAL_RTC_TAMPER3_EVENT_CB_ID Tamper 3 Callback ID + * @arg @ref HAL_RTC_TAMPER4_EVENT_CB_ID Tamper 4 Callback ID + * @arg @ref HAL_RTC_TAMPER5_EVENT_CB_ID Tamper 5 Callback ID + * @arg @ref HAL_RTC_TAMPER6_EVENT_CB_ID Tamper 6 Callback ID + * @arg @ref HAL_RTC_TAMPER7_EVENT_CB_ID Tamper 7 Callback ID + * @arg @ref HAL_RTC_TAMPER8_EVENT_CB_ID Tamper 8 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID Internal Tamper 1 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID Internal Tamper 2 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID Internal Tamper 3 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID Internal Tamper 4 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID Internal Tamper 5 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID Internal Tamper 6 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID Internal Tamper 7 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID Internal Tamper 8 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID Internal Tamper 9 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID Internal Tamper 11 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID Internal Tamper 15 Callback ID + * @arg @ref HAL_RTC_MSPINIT_CB_ID Msp Init callback ID + * @arg @ref HAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID + * @param pCallback pointer to the Callback function + * @note The HAL_RTC_RegisterCallback() may be called before HAL_RTC_Init() in HAL_RTC_STATE_RESET + * to register callbacks for HAL_RTC_MSPINIT_CB_ID and HAL_RTC_MSPDEINIT_CB_ID. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_RegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_CallbackIDTypeDef CallbackID, + pRTC_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + if (HAL_RTC_STATE_READY == hrtc->State) + { + switch (CallbackID) + { + case HAL_RTC_ALARM_A_EVENT_CB_ID : + hrtc->AlarmAEventCallback = pCallback; + break; + + case HAL_RTC_ALARM_B_EVENT_CB_ID : + hrtc->AlarmBEventCallback = pCallback; + break; + + case HAL_RTC_TIMESTAMP_EVENT_CB_ID : + hrtc->TimeStampEventCallback = pCallback; + break; + + case HAL_RTC_WAKEUPTIMER_EVENT_CB_ID : + hrtc->WakeUpTimerEventCallback = pCallback; + break; + + case HAL_RTC_SSRU_EVENT_CB_ID : + hrtc->SSRUEventCallback = pCallback; + break; + + case HAL_RTC_TAMPER1_EVENT_CB_ID : + hrtc->Tamper1EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER2_EVENT_CB_ID : + hrtc->Tamper2EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER3_EVENT_CB_ID : + hrtc->Tamper3EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER4_EVENT_CB_ID : + hrtc->Tamper4EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER5_EVENT_CB_ID : + hrtc->Tamper5EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER6_EVENT_CB_ID : + hrtc->Tamper6EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER7_EVENT_CB_ID : + hrtc->Tamper7EventCallback = pCallback; + break; + + case HAL_RTC_TAMPER8_EVENT_CB_ID : + hrtc->Tamper8EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID : + hrtc->InternalTamper1EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID : + hrtc->InternalTamper2EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID : + hrtc->InternalTamper3EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID : + hrtc->InternalTamper4EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID : + hrtc->InternalTamper5EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID : + hrtc->InternalTamper6EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID : + hrtc->InternalTamper7EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID : + hrtc->InternalTamper8EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID : + hrtc->InternalTamper9EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID : + hrtc->InternalTamper11EventCallback = pCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID : + hrtc->InternalTamper15EventCallback = pCallback; + break; + + case HAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = pCallback; + break; + + case HAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_RTC_STATE_RESET == hrtc->State) + { + switch (CallbackID) + { + case HAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = pCallback; + break; + + case HAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an RTC Callback + * RTC callback is redirected to the weak predefined callback + * @param hrtc RTC handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * This parameter can be one of the following values: + * @arg @ref HAL_RTC_ALARM_A_EVENT_CB_ID Alarm A Event Callback ID + * @arg @ref HAL_RTC_ALARM_B_EVENT_CB_ID Alarm B Event Callback ID + * @arg @ref HAL_RTC_TIMESTAMP_EVENT_CB_ID TimeStamp Event Callback ID + * @arg @ref HAL_RTC_SSRU_EVENT_CB_ID SSRU Callback ID + * @arg @ref HAL_RTC_WAKEUPTIMER_EVENT_CB_ID WakeUp Timer Event Callback ID + * @arg @ref HAL_RTC_TAMPER1_EVENT_CB_ID Tamper 1 Callback ID + * @arg @ref HAL_RTC_TAMPER2_EVENT_CB_ID Tamper 2 Callback ID + * @arg @ref HAL_RTC_TAMPER3_EVENT_CB_ID Tamper 3 Callback ID + * @arg @ref HAL_RTC_TAMPER4_EVENT_CB_ID Tamper 4 Callback ID + * @arg @ref HAL_RTC_TAMPER5_EVENT_CB_ID Tamper 5 Callback ID + * @arg @ref HAL_RTC_TAMPER6_EVENT_CB_ID Tamper 6 Callback ID + * @arg @ref HAL_RTC_TAMPER7_EVENT_CB_ID Tamper 7 Callback ID + * @arg @ref HAL_RTC_TAMPER8_EVENT_CB_ID Tamper 8 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID Internal Tamper 1 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID Internal Tamper 2 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID Internal Tamper 3 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID Internal Tamper 4 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID Internal Tamper 5 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID Internal Tamper 6 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID Internal Tamper 7 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID Internal Tamper 8 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID Internal Tamper 9 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID Internal Tamper 11 Callback ID + * @arg @ref HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID Internal Tamper 15 Callback ID + * @arg @ref HAL_RTC_MSPINIT_CB_ID Msp Init callback ID + * @arg @ref HAL_RTC_MSPDEINIT_CB_ID Msp DeInit callback ID + * @note The HAL_RTC_UnRegisterCallback() may be called before HAL_RTC_Init() in HAL_RTC_STATE_RESET + * to un-register callbacks for HAL_RTC_MSPINIT_CB_ID and HAL_RTC_MSPDEINIT_CB_ID. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_UnRegisterCallback(RTC_HandleTypeDef *hrtc, HAL_RTC_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_RTC_STATE_READY == hrtc->State) + { + switch (CallbackID) + { + case HAL_RTC_ALARM_A_EVENT_CB_ID : + /* Legacy weak AlarmAEventCallback */ + hrtc->AlarmAEventCallback = HAL_RTC_AlarmAEventCallback; + break; + + case HAL_RTC_ALARM_B_EVENT_CB_ID : + /* Legacy weak AlarmBEventCallback */ + hrtc->AlarmBEventCallback = HAL_RTCEx_AlarmBEventCallback; + break; + + case HAL_RTC_TIMESTAMP_EVENT_CB_ID : + /* Legacy weak TimeStampEventCallback */ + hrtc->TimeStampEventCallback = HAL_RTCEx_TimeStampEventCallback; + break; + + case HAL_RTC_WAKEUPTIMER_EVENT_CB_ID : + /* Legacy weak WakeUpTimerEventCallback */ + hrtc->WakeUpTimerEventCallback = HAL_RTCEx_WakeUpTimerEventCallback; + break; + + case HAL_RTC_SSRU_EVENT_CB_ID : + /* Legacy weak SSRUEventCallback */ + hrtc->SSRUEventCallback = HAL_RTCEx_SSRUEventCallback; + break; + + case HAL_RTC_TAMPER1_EVENT_CB_ID : + /* Legacy weak Tamper1EventCallback */ + hrtc->Tamper1EventCallback = HAL_RTCEx_Tamper1EventCallback; + break; + + case HAL_RTC_TAMPER2_EVENT_CB_ID : + /* Legacy weak Tamper2EventCallback */ + hrtc->Tamper2EventCallback = HAL_RTCEx_Tamper2EventCallback; + break; + + case HAL_RTC_TAMPER3_EVENT_CB_ID : + /* Legacy weak Tamper3EventCallback */ + hrtc->Tamper3EventCallback = HAL_RTCEx_Tamper3EventCallback; + break; + + case HAL_RTC_TAMPER4_EVENT_CB_ID : + /* Legacy weak Tamper4EventCallback */ + hrtc->Tamper4EventCallback = HAL_RTCEx_Tamper4EventCallback; + break; + + case HAL_RTC_TAMPER5_EVENT_CB_ID : + /* Legacy weak Tamper5EventCallback */ + hrtc->Tamper5EventCallback = HAL_RTCEx_Tamper5EventCallback; + break; + + case HAL_RTC_TAMPER6_EVENT_CB_ID : + /* Legacy weak Tamper6EventCallback */ + hrtc->Tamper6EventCallback = HAL_RTCEx_Tamper6EventCallback; + break; + + case HAL_RTC_TAMPER7_EVENT_CB_ID : + /* Legacy weak Tamper7EventCallback */ + hrtc->Tamper7EventCallback = HAL_RTCEx_Tamper7EventCallback; + break; + + case HAL_RTC_TAMPER8_EVENT_CB_ID : + /* Legacy weak Tamper8EventCallback */ + hrtc->Tamper8EventCallback = HAL_RTCEx_Tamper8EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER1_EVENT_CB_ID : + /* Legacy weak InternalTamper1EventCallback */ + hrtc->InternalTamper1EventCallback = HAL_RTCEx_InternalTamper1EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER2_EVENT_CB_ID : + /* Legacy weak InternalTamper2EventCallback */ + hrtc->InternalTamper2EventCallback = HAL_RTCEx_InternalTamper2EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER3_EVENT_CB_ID : + /* Legacy weak InternalTamper3EventCallback */ + hrtc->InternalTamper3EventCallback = HAL_RTCEx_InternalTamper3EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER4_EVENT_CB_ID : + /* Legacy weak InternalTamper4EventCallback */ + hrtc->InternalTamper4EventCallback = HAL_RTCEx_InternalTamper4EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER5_EVENT_CB_ID : + /* Legacy weak InternalTamper5EventCallback */ + hrtc->InternalTamper5EventCallback = HAL_RTCEx_InternalTamper5EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER6_EVENT_CB_ID : + /* Legacy weak InternalTamper6EventCallback */ + hrtc->InternalTamper6EventCallback = HAL_RTCEx_InternalTamper6EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER7_EVENT_CB_ID : + /* Legacy weak InternalTamper7EventCallback */ + hrtc->InternalTamper7EventCallback = HAL_RTCEx_InternalTamper7EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER8_EVENT_CB_ID : + /* Legacy weak InternalTamper8EventCallback */ + hrtc->InternalTamper8EventCallback = HAL_RTCEx_InternalTamper8EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER9_EVENT_CB_ID : + /* Legacy weak InternalTamper9EventCallback */ + hrtc->InternalTamper9EventCallback = HAL_RTCEx_InternalTamper9EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER11_EVENT_CB_ID : + /* Legacy weak InternalTamper11EventCallback */ + hrtc->InternalTamper11EventCallback = HAL_RTCEx_InternalTamper11EventCallback; + break; + + case HAL_RTC_INTERNAL_TAMPER15_EVENT_CB_ID : + /* Legacy weak InternalTamper15EventCallback */ + hrtc->InternalTamper15EventCallback = HAL_RTCEx_InternalTamper15EventCallback; + break; + + case HAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = HAL_RTC_MspInit; + break; + + case HAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_RTC_STATE_RESET == hrtc->State) + { + switch (CallbackID) + { + case HAL_RTC_MSPINIT_CB_ID : + hrtc->MspInitCallback = HAL_RTC_MspInit; + break; + + case HAL_RTC_MSPDEINIT_CB_ID : + hrtc->MspDeInitCallback = HAL_RTC_MspDeInit; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + +/** + * @brief Initialize the RTC MSP. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the RTC MSP. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group2 + * @brief RTC Time and Date functions + * +@verbatim + =============================================================================== + ##### RTC Time and Date functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Time and Date features + +@endverbatim + * @{ + */ + +/** + * @brief Set RTC current time. + * @param hrtc RTC handle + * @param sTime Pointer to Time structure + * if Binary mode is RTC_BINARY_ONLY, this parameter is not used and RTC_SSR will be automatically + * reset to 0xFFFFFFFF + * else sTime->SubSeconds is not used and RTC_SSR will be automatically reset to the + * A 7-bit async prescaler (RTC_PRER_PREDIV_A) + * @param Format Format of sTime->Hours, sTime->Minutes and sTime->Seconds. + * if Binary mode is RTC_BINARY_ONLY, this parameter is not used + * else this parameter can be one of the following values + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg; + HAL_StatusTypeDef status; + +#ifdef USE_FULL_ASSERT + /* Check the parameters depending of the Binary mode with 32-bit free-running counter configuration */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_NONE) + { + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + } +#endif /* USE_FULL_ASSERT */ + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + if (status == HAL_OK) + { + /* Check Binary mode ((32-bit free-running counter) */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) != RTC_BINARY_ONLY) + { + if (Format == RTC_FORMAT_BIN) + { + if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) + { + assert_param(IS_RTC_HOUR12(sTime->Hours)); + assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00U; + 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) << RTC_TR_HU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sTime->Minutes) << RTC_TR_MNU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sTime->Seconds) << RTC_TR_SU_Pos) | \ + (((uint32_t)sTime->TimeFormat) << RTC_TR_PM_Pos)); + } + else + { + if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) + { + assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sTime->Hours))); + assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00U; + 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) << RTC_TR_HU_Pos) | \ + ((uint32_t)(sTime->Minutes) << RTC_TR_MNU_Pos) | \ + ((uint32_t)(sTime->Seconds) << RTC_TR_SU_Pos) | \ + ((uint32_t)(sTime->TimeFormat) << RTC_TR_PM_Pos)); + } + + /* Set the RTC_TR register */ + WRITE_REG(RTC->TR, (tmpreg & RTC_TR_RESERVED_MASK)); + + /* Clear the bits to be configured */ + CLEAR_BIT(RTC->CR, RTC_CR_BKP); + } + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + if (status == HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Get RTC current time. + * @note You can use SubSeconds and SecondFraction (sTime structure fields returned) to convert SubSeconds + * value in second fraction ratio with time unit following generic formula: + * Second fraction ratio * time_unit= [(SecondFraction-SubSeconds)/(SecondFraction+1)] * time_unit + * This conversion can be performed only if no shift operation is pending (ie. SHFP=0) when PREDIV_S >= SS + * @note You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values + * in the higher-order calendar shadow registers to ensure consistency between the time and date values. + * Reading RTC current time locks the values in calendar shadow registers until Current date is read + * to ensure consistency between the time and date values. + * @param hrtc RTC handle + * @param sTime + * if Binary mode is RTC_BINARY_ONLY, sTime->SubSeconds only is updated + * else + * Pointer to Time structure with Hours, Minutes and Seconds fields returned + * with input format (BIN or BCD), also SubSeconds field returning the + * RTC_SSR register content and SecondFraction field the Synchronous pre-scaler + * factor to be used for second fraction ratio computation. + * @param Format Format of sTime->Hours, sTime->Minutes and sTime->Seconds. + * if Binary mode is RTC_BINARY_ONLY, this parameter is not used + * else this parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetTime(const RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Get subseconds structure field from the corresponding register */ + sTime->SubSeconds = READ_REG(RTC->SSR); + + if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) != RTC_BINARY_ONLY) + { + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get SecondFraction structure field from the corresponding register field */ + sTime->SecondFraction = (uint32_t)(READ_REG(RTC->PRER) & RTC_PRER_PREDIV_S); + + /* Get the TR register */ + tmpreg = (uint32_t)(READ_REG(RTC->TR) & RTC_TR_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> RTC_TR_HU_Pos); + sTime->Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >> RTC_TR_MNU_Pos); + sTime->Seconds = (uint8_t)((tmpreg & (RTC_TR_ST | RTC_TR_SU)) >> RTC_TR_SU_Pos); + sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TR_PM)) >> RTC_TR_PM_Pos); + + /* Check the input parameters format */ + if (Format == RTC_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 Set RTC current date. + * @param hrtc RTC handle + * @param sDate Pointer to date structure + * @param Format Format of sDate->Year, sDate->Month and sDate->Weekday. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg; + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + if ((Format == RTC_FORMAT_BIN) && ((sDate->Month & 0x10U) == 0x10U)) + { + sDate->Month = (uint8_t)((sDate->Month & (uint8_t)~(0x10U)) + (uint8_t)0x0AU); + } + + assert_param(IS_RTC_WEEKDAY(sDate->WeekDay)); + + if (Format == RTC_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) << RTC_DR_YU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Month) << RTC_DR_MU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Date) << RTC_DR_DU_Pos) | \ + ((uint32_t)sDate->WeekDay << RTC_DR_WDU_Pos)); + } + else + { + assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year))); + assert_param(IS_RTC_MONTH(RTC_Bcd2ToByte(sDate->Month))); + assert_param(IS_RTC_DATE(RTC_Bcd2ToByte(sDate->Date))); + + datetmpreg = ((((uint32_t)sDate->Year) << RTC_DR_YU_Pos) | \ + (((uint32_t)sDate->Month) << RTC_DR_MU_Pos) | \ + (((uint32_t)sDate->Date) << RTC_DR_DU_Pos) | \ + (((uint32_t)sDate->WeekDay) << RTC_DR_WDU_Pos)); + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + if (status == HAL_OK) + { + /* Set the RTC_DR register */ + WRITE_REG(RTC->DR, (uint32_t)(datetmpreg & RTC_DR_RESERVED_MASK)); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + if (status == HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Get RTC current date. + * @note You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values + * in the higher-order calendar shadow registers to ensure consistency between the time and date values. + * Reading RTC current time locks the values in calendar shadow registers until Current date is read. + * @param hrtc RTC handle + * @param sDate Pointer to Date structure + * @param Format Format of sDate->Year, sDate->Month and sDate->Weekday. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetDate(const RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get the DR register */ + datetmpreg = (uint32_t)(READ_REG(RTC->DR) & RTC_DR_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> RTC_DR_YU_Pos); + sDate->Month = (uint8_t)((datetmpreg & (RTC_DR_MT | RTC_DR_MU)) >> RTC_DR_MU_Pos); + sDate->Date = (uint8_t)((datetmpreg & (RTC_DR_DT | RTC_DR_DU)) >> RTC_DR_DU_Pos); + sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DR_WDU)) >> RTC_DR_WDU_Pos); + + /* Check the input parameters format */ + if (Format == RTC_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; +} + +/** + * @brief Daylight Saving Time, Add one hour to the calendar in one single operation + * without going through the initialization procedure. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTC_DST_Add1Hour(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set RTC_CR_ADD1H Bit */ + SET_BIT(RTC->CR, RTC_CR_ADD1H); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief Daylight Saving Time, Subtract one hour from the calendar in one + * single operation without going through the initialization procedure. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTC_DST_Sub1Hour(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set RTC_CR_SUB1H Bit */ + SET_BIT(RTC->CR, RTC_CR_SUB1H); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); +} + +/** + * @brief Daylight Saving Time, Set the store operation bit. + * @note It can be used by the software in order to memorize the DST status. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTC_DST_SetStoreOperation(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Set RTC_CR_BKP Bit */ + SET_BIT(RTC->CR, RTC_CR_BKP); +} + +/** + * @brief Daylight Saving Time, Clear the store operation bit. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTC_DST_ClearStoreOperation(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Clear RTC_CR_BKP Bit */ + CLEAR_BIT(RTC->CR, RTC_CR_BKP); +} + +/** + * @brief Daylight Saving Time, Read the store operation bit. + * @param hrtc RTC handle + * @retval operation see RTC_StoreOperation_Definitions + */ +uint32_t HAL_RTC_DST_ReadStoreOperation(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Get RTC_CR_BKP Bit */ + return READ_BIT(RTC->CR, RTC_CR_BKP); +} + + +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group3 + * @brief RTC Alarm functions + * +@verbatim + =============================================================================== + ##### RTC Alarm functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Alarm feature + +@endverbatim + * @{ + */ +/** + * @brief Set the specified RTC Alarm. + * @param hrtc RTC handle + * @param sAlarm Pointer to Alarm structure + * if Binary mode is RTC_BINARY_ONLY, 3 fields only are used + * sAlarm->AlarmTime.SubSeconds + * sAlarm->AlarmSubSecondMask + * sAlarm->BinaryAutoClr + * @param Format of the entered parameters. + * if Binary mode is RTC_BINARY_ONLY, this parameter is not used + * else this parameter can be one of the following values + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t tmpreg = 0; + uint32_t binary_mode; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + +#ifdef USE_FULL_ASSERT + /* Check the parameters depending of the Binary mode (32-bit free-running counter configuration) */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_NONE) + { + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_ALARM(sAlarm->Alarm)); + assert_param(IS_RTC_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)); + } + else if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_ONLY) + { + assert_param(IS_RTC_ALARM_SUB_SECOND_BINARY_MASK(sAlarm->AlarmSubSecondMask)); + assert_param(IS_RTC_ALARMSUBSECONDBIN_AUTOCLR(sAlarm->BinaryAutoClr)); + } + else /* RTC_BINARY_MIX */ + { + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_ALARM(sAlarm->Alarm)); + assert_param(IS_RTC_ALARM_MASK(sAlarm->AlarmMask)); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + /* In Binary Mix Mode, the RTC can not generate an alarm on a match + involving all calendar items + the upper SSR bits */ + assert_param((sAlarm->AlarmSubSecondMask >> RTC_ALRMASSR_MASKSS_Pos) <= + (8U + (READ_BIT(RTC->ICSR, RTC_ICSR_BCDU) >> RTC_ICSR_BCDU_Pos))); + } +#endif /* USE_FULL_ASSERT */ + + /* Get Binary mode (32-bit free-running counter configuration) */ + binary_mode = READ_BIT(RTC->ICSR, RTC_ICSR_BIN); + + if (binary_mode != RTC_BINARY_ONLY) + { + if (Format == RTC_FORMAT_BIN) + { + if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) + { + assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + 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) << RTC_ALRMAR_HU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else /* format BCD */ + { + if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) + { + assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + 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))); + +#ifdef USE_FULL_ASSERT + if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + else + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + +#endif /* USE_FULL_ASSERT */ + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + } + + /* Configure the Alarm register */ + if (sAlarm->Alarm == RTC_ALARM_A) + { + /* Disable the Alarm A interrupt */ + + /* In case of interrupt mode is used, the interrupt source must disabled */ + CLEAR_BIT(RTC->CR, (RTC_CR_ALRAE | RTC_CR_ALRAIE)); + + /* Clear flag alarm A */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); + + if (binary_mode == RTC_BINARY_ONLY) + { + WRITE_REG(RTC->ALRMASSR, sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr); + } + else + { + WRITE_REG(RTC->ALRMAR, tmpreg); + WRITE_REG(RTC->ALRMASSR, sAlarm->AlarmSubSecondMask); + } + + WRITE_REG(RTC->ALRABINR, sAlarm->AlarmTime.SubSeconds); + + if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) + { + /* Configure the Alarm A output clear */ + SET_BIT(RTC->CR, RTC_CR_ALRAFCLR); + } + else + { + /* Disable the Alarm A output clear */ + CLEAR_BIT(RTC->CR, RTC_CR_ALRAFCLR); + } + /* Configure the Alarm state: Enable Alarm */ + SET_BIT(RTC->CR, RTC_CR_ALRAE); + } + else + { + /* Disable the Alarm B interrupt */ + + /* In case of interrupt mode is used, the interrupt source must disabled */ + CLEAR_BIT(RTC->CR, (RTC_CR_ALRBE | RTC_CR_ALRBIE)); + + /* Clear flag alarm B */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); + + if (binary_mode == RTC_BINARY_ONLY) + { + WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr); + } + else + { + WRITE_REG(RTC->ALRMBR, tmpreg); + + WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask); + } + + WRITE_REG(RTC->ALRBBINR, sAlarm->AlarmTime.SubSeconds); + + if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) + { + /* Configure the Alarm B output clear */ + SET_BIT(RTC->CR, RTC_CR_ALRBFCLR); + } + else + { + /* Disable the Alarm B output clear */ + CLEAR_BIT(RTC->CR, RTC_CR_ALRBFCLR); + } + + /* Configure the Alarm state: Enable Alarm */ + SET_BIT(RTC->CR, RTC_CR_ALRBE); + } + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Set the specified RTC Alarm with Interrupt. + * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. + * @param hrtc RTC handle + * @param sAlarm Pointer to Alarm structure + * if Binary mode is RTC_BINARY_ONLY, 3 fields only are used + * sAlarm->AlarmTime.SubSeconds + * sAlarm->AlarmSubSecondMask + * sAlarm->BinaryAutoClr + * @param Format Specifies the format of the entered parameters. + * if Binary mode is RTC_BINARY_ONLY, this parameter is not used + * else this parameter can be one of the following values + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t tmpreg = 0; + uint32_t binary_mode; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + +#ifdef USE_FULL_ASSERT + /* Check the parameters depending of the Binary mode (32-bit free-running counter configuration) */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_NONE) + { + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_ALARM(sAlarm->Alarm)); + assert_param(IS_RTC_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)); + } + else if (READ_BIT(RTC->ICSR, RTC_ICSR_BIN) == RTC_BINARY_ONLY) + { + assert_param(IS_RTC_ALARM_SUB_SECOND_BINARY_MASK(sAlarm->AlarmSubSecondMask)); + assert_param(IS_RTC_ALARMSUBSECONDBIN_AUTOCLR(sAlarm->BinaryAutoClr)); + } + else /* RTC_BINARY_MIX */ + { + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_ALARM(sAlarm->Alarm)); + assert_param(IS_RTC_ALARM_MASK(sAlarm->AlarmMask)); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + /* In Binary Mix Mode, the RTC can not generate an alarm on a match + involving all calendar items + the upper SSR bits */ + assert_param((sAlarm->AlarmSubSecondMask >> RTC_ALRMASSR_MASKSS_Pos) <= + (8U + (READ_BIT(RTC->ICSR, RTC_ICSR_BCDU) >> RTC_ICSR_BCDU_Pos))); + } +#endif /* USE_FULL_ASSERT */ + + /* Get Binary mode (32-bit free-running counter configuration) */ + binary_mode = READ_BIT(RTC->ICSR, RTC_ICSR_BIN); + + if (binary_mode != RTC_BINARY_ONLY) + { + if (Format == RTC_FORMAT_BIN) + { + if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) + { + assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + 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) << RTC_ALRMAR_HU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else /* Format BCD */ + { + if (READ_BIT(RTC->CR, RTC_CR_FMT) != 0U) + { + assert_param(IS_RTC_HOUR12(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00U; + 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))); + +#ifdef USE_FULL_ASSERT + if (sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + else + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay))); + } + +#endif /* USE_FULL_ASSERT */ + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << RTC_ALRMAR_HU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << RTC_ALRMAR_MNU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.Seconds) << RTC_ALRMAR_SU_Pos) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << RTC_ALRMAR_PM_Pos) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << RTC_ALRMAR_DU_Pos) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + + } + } + + /* Configure the Alarm registers */ + if (sAlarm->Alarm == RTC_ALARM_A) + { + /* Disable the Alarm A interrupt */ + CLEAR_BIT(RTC->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE); + + /* Clear flag alarm A */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); + + if (binary_mode == RTC_BINARY_ONLY) + { + RTC->ALRMASSR = sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr; + } + else + { + WRITE_REG(RTC->ALRMAR, tmpreg); + + WRITE_REG(RTC->ALRMASSR, sAlarm->AlarmSubSecondMask); + } + + WRITE_REG(RTC->ALRABINR, sAlarm->AlarmTime.SubSeconds); + + if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) + { + /* Configure the Alarm A output clear */ + SET_BIT(RTC->CR, RTC_CR_ALRAFCLR); + } + else + { + /* Disable the Alarm A output clear */ + CLEAR_BIT(RTC->CR, RTC_CR_ALRAFCLR); + } + + /* Configure the Alarm interrupt */ + SET_BIT(RTC->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE); + } + else + { + /* Disable the Alarm B interrupt */ + CLEAR_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE); + + /* Clear flag alarm B */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); + + if (binary_mode == RTC_BINARY_ONLY) + { + WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask | sAlarm->BinaryAutoClr); + } + else + { + WRITE_REG(RTC->ALRMBR, tmpreg); + + WRITE_REG(RTC->ALRMBSSR, sAlarm->AlarmSubSecondMask); + } + + WRITE_REG(RTC->ALRBBINR, sAlarm->AlarmTime.SubSeconds); + + if (sAlarm->FlagAutoClr == ALARM_FLAG_AUTOCLR_ENABLE) + { + /* Configure the Alarm B Output clear */ + SET_BIT(RTC->CR, RTC_CR_ALRBFCLR); + } + else + { + /* Disable the Alarm B Output clear */ + CLEAR_BIT(RTC->CR, RTC_CR_ALRBFCLR); + } + + /* Configure the Alarm interrupt */ + SET_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE); + } + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivate the specified RTC Alarm. + * @param hrtc RTC handle + * @param Alarm Specifies the Alarm. + * This parameter can be one of the following values: + * @arg RTC_ALARM_A: AlarmA + * @arg RTC_ALARM_B: AlarmB + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm) +{ + /* Check the parameters */ + assert_param(IS_RTC_ALARM(Alarm)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* In case of interrupt mode is used, the interrupt source must disabled */ + if (Alarm == RTC_ALARM_A) + { + CLEAR_BIT(RTC->CR, RTC_CR_ALRAE | RTC_CR_ALRAIE); + + /* AlarmA, Clear SSCLR */ + CLEAR_BIT(RTC->ALRMASSR, RTC_ALRMASSR_SSCLR); + } + else + { + CLEAR_BIT(RTC->CR, RTC_CR_ALRBE | RTC_CR_ALRBIE); + + /* AlarmB, Clear SSCLR */ + CLEAR_BIT(RTC->ALRMBSSR, RTC_ALRMBSSR_SSCLR); + } + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Get 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 RTC_ALARM_A: AlarmA + * @arg RTC_ALARM_B: AlarmB + * @param Format Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg RTC_FORMAT_BIN: Binary format + * @arg RTC_FORMAT_BCD: BCD format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetAlarm(const RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, + uint32_t Format) +{ + uint32_t tmpreg; + uint32_t subsecondtmpreg; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_ALARM(Alarm)); + + if (Alarm == RTC_ALARM_A) + { + /* AlarmA */ + sAlarm->Alarm = RTC_ALARM_A; + + tmpreg = READ_REG(RTC->ALRMAR); + subsecondtmpreg = (uint32_t)(READ_REG(RTC->ALRMASSR) & RTC_ALRMASSR_SS); + + /* Fill the structure with the read parameters */ + sAlarm->AlarmTime.Hours = (uint8_t)((tmpreg & (RTC_ALRMAR_HT | RTC_ALRMAR_HU)) >> RTC_ALRMAR_HU_Pos); + sAlarm->AlarmTime.Minutes = (uint8_t)((tmpreg & (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU)) >> RTC_ALRMAR_MNU_Pos); + sAlarm->AlarmTime.Seconds = (uint8_t)((tmpreg & (RTC_ALRMAR_ST | RTC_ALRMAR_SU)) >> RTC_ALRMAR_SU_Pos); + sAlarm->AlarmTime.TimeFormat = (uint8_t)((tmpreg & RTC_ALRMAR_PM) >> RTC_ALRMAR_PM_Pos); + sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; + sAlarm->AlarmDateWeekDay = (uint8_t)((tmpreg & (RTC_ALRMAR_DT | RTC_ALRMAR_DU)) >> RTC_ALRMAR_DU_Pos); + sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMAR_WDSEL); + sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL); + } + else + { + sAlarm->Alarm = RTC_ALARM_B; + + tmpreg = READ_REG(RTC->ALRMBR); + subsecondtmpreg = (uint32_t)(READ_REG(RTC->ALRMBSSR) & RTC_ALRMBSSR_SS); + + /* Fill the structure with the read parameters */ + sAlarm->AlarmTime.Hours = (uint8_t)((tmpreg & (RTC_ALRMBR_HT | RTC_ALRMBR_HU)) >> RTC_ALRMBR_HU_Pos); + sAlarm->AlarmTime.Minutes = (uint8_t)((tmpreg & (RTC_ALRMBR_MNT | RTC_ALRMBR_MNU)) >> RTC_ALRMBR_MNU_Pos); + sAlarm->AlarmTime.Seconds = (uint8_t)((tmpreg & (RTC_ALRMBR_ST | RTC_ALRMBR_SU)) >> RTC_ALRMBR_SU_Pos); + sAlarm->AlarmTime.TimeFormat = (uint8_t)((tmpreg & RTC_ALRMBR_PM) >> RTC_ALRMBR_PM_Pos); + sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; + sAlarm->AlarmDateWeekDay = (uint8_t)((tmpreg & (RTC_ALRMBR_DT | RTC_ALRMBR_DU)) >> RTC_ALRMBR_DU_Pos); + sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMBR_WDSEL); + sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL); + } + + if (Format == RTC_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 Handle Alarm interrupt request. + * @note Alarm is available in driver. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get interrupt status */ + uint32_t tmp = READ_REG(RTC->MISR); + + if ((tmp & RTC_MISR_ALRAMF) != 0U) + { + /* Clear the AlarmA interrupt pending bit */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); + +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Compare Match registered Callback */ + hrtc->AlarmAEventCallback(hrtc); +#else + HAL_RTC_AlarmAEventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + if ((tmp & RTC_MISR_ALRBMF) != 0U) + { + /* Clear the AlarmB interrupt pending bit */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); + +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Compare Match registered Callback */ + hrtc->AlarmBEventCallback(hrtc); +#else + HAL_RTCEx_AlarmBEventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Handle Alarm A Polling request. + * @param hrtc RTC handle + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + uint32_t tickstart = HAL_GetTick(); + + while (READ_BIT(RTC->SR, RTC_SR_ALRAF) == 0U) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->SR, RTC_SR_ALRAF) == 0U) + { + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Clear the Alarm interrupt pending bit */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRAF); + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group4 + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Wait for RTC Time and Date Synchronization + +@endverbatim + * @{ + */ + +/** + * @brief Wait 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 tickstart; + + /* Clear RSF flag */ + CLEAR_BIT(RTC->ICSR, RTC_ICSR_RSF); + + tickstart = HAL_GetTick(); + + /* Wait the registers to be synchronised */ + while (READ_BIT(RTC->ICSR, RTC_ICSR_RSF) == 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_RSF) == 0U) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup RTC_Exported_Functions_Group5 + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Get RTC state + +@endverbatim + * @{ + */ +/** + * @brief Return the RTC handle state. + * @param hrtc RTC handle + * @retval HAL state + */ +HAL_RTCStateTypeDef HAL_RTC_GetState(const RTC_HandleTypeDef *hrtc) +{ + /* Return RTC handle state */ + return hrtc->State; +} + +/** + * @} + */ +/** + * @} + */ + +/** @addtogroup RTC_Private_Functions + * @{ + */ +/** + * @brief Enter 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 tickstart; + HAL_StatusTypeDef status = HAL_OK; + + /* Check if the Initialization mode is set */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) + { + /* Set the Initialization mode */ + SET_BIT(RTC->ICSR, RTC_ICSR_INIT); + + tickstart = HAL_GetTick(); + /* Wait till RTC is in INIT state and if Time out is reached exit */ + while ((READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) && (status != HAL_TIMEOUT)) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) + { + status = HAL_TIMEOUT; + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + } + else + { + break; + } + } + } + } + + return status; +} + +/** + * @brief Exit the RTC Initialization mode. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef *hrtc) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Exit Initialization mode */ + CLEAR_BIT(RTC->ICSR, RTC_ICSR_INIT); + + /* If CR_BYPSHAD bit = 0, wait for synchro */ + if (READ_BIT(RTC->CR, RTC_CR_BYPSHAD) == 0U) + { + if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + status = HAL_TIMEOUT; + } + } + else /* WA 2.9.6 Calendar initialization may fail in case of consecutive INIT mode entry. */ + { + /* Clear BYPSHAD bit */ + CLEAR_BIT(RTC->CR, RTC_CR_BYPSHAD); + if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + status = HAL_TIMEOUT; + } + /* Restore BYPSHAD bit */ + SET_BIT(RTC->CR, RTC_CR_BYPSHAD); + } + return status; +} + +/** + * @brief Convert 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 bcd_high = 0U; + uint8_t tmp_value = Value; + + while (tmp_value >= 10U) + { + bcd_high++; + tmp_value -= 10U; + } + + return ((uint8_t)(bcd_high << 4U) | tmp_value); +} + +/** + * @brief Convert 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; + + tmp = (((uint32_t)Value & 0xF0U) >> 4) * 10U; + + return (uint8_t)(tmp + ((uint32_t)Value & 0x0FU)); +} + +/** + * @} + */ + +#endif /* HAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc_ex.c index 5d4406b81..a0b11c619 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_rtc_ex.c @@ -1,2934 +1,2933 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_rtc_ex.c - * @author GPM Application Team - * @brief Extended RTC HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Real Time Clock (RTC) Extended peripheral: - * + RTC Time Stamp functions - * + RTC Tamper functions - * + RTC Wake-up functions - * + Extended Control functions - * + Extended RTC features functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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_RTCEx_SetWakeUpTimer() - function. You can also configure the RTC Wakeup timer with interrupt mode - using the HAL_RTCEx_SetWakeUpTimer_IT() function. - (+) To read the RTC WakeUp Counter register, use the HAL_RTCEx_GetWakeUpTimer() - function. - - *** Outputs configuration *** - ============================= - [..] The RTC has 2 outputs pins (RTC_OUT1 & RTC_OUT2). - To configure the outputs, use the HAL_RTC_Init() function. - (+) RTC_OUT1 and RTC_OUT2 which select one of the following two outputs: - (+) CALIB: 512Hz or 1Hz clock output (with an LSE frequency of 32.768kHz). - To enable the CALIB, use the HAL_RTCEx_SetCalibrationOutPut() function. - (+) TAMPALRM: This output is the OR between rtc_tamp_evt and ALARM signals. - ALARM is enabled by configuring the OSEL[1:0] bits in the RTC_CR register - which select the alarm A, alarm B or wakeup outputs. - rtc_tamp_evt is enabled by setting the TAMPOE bit - in the RTC_CR register which selects the tamper event outputs. - - *** Smooth digital Calibration configuration *** - ================================================ - [..] - (+) Configure the RTC Original Digital Calibration Value and the corresponding - calibration cycle period (32s,16s and 8s) using the HAL_RTCEx_SetSmoothCalib() - function. - - *** RTC synchronization *** - ================================================ - [..] - (+) The RTC can be finely adjusted using HAL_RTCEx_SetSynchroShift() function. - Writing to RTC_SHIFTR can shift (either delay or advance) the clock with - a resolution of 1 ck_apre period. - The shift operation consists in adding the SUBFS[14:0] value to the synchronous - prescaler counter SS[15:0]: this delays the clock. - - *** Bypass shadow registers *** - ================================================ - [..] - (+) Enable bypass shadow registers using the HAL_RTCEx_EnableBypassShadow(). - When the Bypass Shadow is enabled the calendar value are taken directly - from the Calendar counter. - Thus eliminating the need to wait for the RSF bit to be set. - This is especially useful after exiting from low-power modes (Stop or Standby), - since the shadow registers are not updated during these modes. - - *** RTC ultra-low-power mode *** - ================================================ - [..] - (+) Configure the RTC ultra-low-power mode using HAL_RTCEx_SetLowPowerCalib() function. - In this case, the calibration mechanism is applied on ck_apre instead of RTCCLK. - The resulting accuracy is the same, but the calibration is performed during a - calibration cycle of about 220 x PREDIV_A x RTCCLK pulses instead of 220 RTCCLK pulses. - - *** RTC subsecond register underflow interruption *** - ================================================ - [..] - (+) Enable the RTC SSRU interruption mode using HAL_RTCEx_SetSSRU_IT() function. - In this case, when the SSR rolls under 0, an SSRU interruption is triggered. - Disable the RTC SSRU interruption mode using HAL_RTCEx_DeactivateSSRU() function. - - *** TimeStamp configuration *** - =============================== - [..] - (+) Enable the RTC TimeStamp using the HAL_RTCEx_SetTimeStamp() function. - You can also configure the RTC TimeStamp with interrupt mode using the - HAL_RTCEx_SetTimeStamp_IT() function. - (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTCEx_GetTimeStamp() - function. - - *** Internal TimeStamp configuration *** - =============================== - [..] - (+) Enable the RTC internal TimeStamp using the HAL_RTCEx_SetInternalTimeStamp() function. - User has to check internal timestamp occurrence using __HAL_RTC_INTERNAL_TIMESTAMP_GET_FLAG. - (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTCEx_GetTimeStamp() - 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, NoErase, MaskFlag, precharge or discharge and - Pull-UP using the HAL_RTCEx_SetTamper() function. You can configure RTC Tamper - with interrupt mode using HAL_RTCEx_SetTamper_IT() function. - (+) The default configuration of the Tamper erases the backup registers. To avoid - erase, enable the TAMPxPOM field on the TAMP_CR2 register. - (+) With new RTC tamper configuration, you have to call HAL_RTC_Init() in order to - perform TAMP base address offset calculation. - (+) Enable Internal tamper using HAL_RTCEx_SetInternalTamper. IT mode can be chosen using - setting Interrupt field. - - *** Backup Data Registers and Device Secrets configuration *** - =========================================== - [..] - (+) To write to the RTC Backup Data registers, use the HAL_RTCEx_BKUPWrite() - function. - (+) To read the RTC Backup registers, use the HAL_RTCEx_BKUPRead() - function. - (+) To reset the RTC Backup registers and erase the device secrets, - use HAL_RTCEx_BKUPErase() function. - (+) Enable the lock of the Boot hardware Key using the HAL_RTCEx_LockBootHardwareKey() - function. - The backup registers from TAMP_BKP0R to TAMP_BKP7R cannot be accessed neither in - read nor in write (they are read as 0 and write ignore). - (+) Configure the erase of the Device Secrets using HAL_RTCEx_ConfigEraseDeviceSecrets() - function. - (+) Block the access to the RTC Backup registers and all the device secrets - using HAL_RTCEx_BKUPBlock() function. - - *** Monotonic counter *** - ================================================ - [..] - (+) To increment the Monotonic counter, use the HAL_RTCEx_MonotonicCounterIncrement() - function. - (+) To get the current value of the Monotonic counter, use the HAL_RTCEx_MonotonicCounterGet() - function. - - *** RTC & TAMP privilege protection modes *** - ================================================ - [..] - (+) Set the privilege level of the RTC/TAMP/Backup registers using HAL_RTCEx_PrivilegeModeSet() - function. - +) Get the privilege level of the RTC/TAMP/Backup registers using HAL_RTCEx_PrivilegeModeGet() - function. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @addtogroup RTCEx - * @brief RTC Extended HAL module driver - * @{ - */ - -#ifdef HAL_RTC_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -#define TAMP_ALL RTC_TAMPER_ALL - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup RTCEx_Exported_Functions - * @{ - */ - - -/** @addtogroup RTCEx_Exported_Functions_Group1 - * @brief RTC TimeStamp and Tamper functions - * -@verbatim - =============================================================================== - ##### RTC TimeStamp and Tamper functions ##### - =============================================================================== - - [..] This section provides functions allowing to configure TimeStamp feature - -@endverbatim - * @{ - */ - -#ifdef RTC_CR_TSE -/** - * @brief Set 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 values: - * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the - * rising edge of the related pin. - * @arg RTC_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_DEFAULT: PC13 is selected as RTC TimeStamp Pin. - * The RTC TimeStamp Pin is per default PC13, but for reasons of - * compatibility, this parameter is required. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) -{ - /* Check the parameters */ -#if defined(RTC_CR_TSEDGE) - assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); -#endif /* RTC_CR_TSEDGE */ - assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); - UNUSED(RTC_TimeStampPin); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Get the RTC_CR register and clear the bits to be configured */ -#if defined(RTC_CR_TSEDGE) - CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE)); -#else - CLEAR_BIT(RTC->CR, RTC_CR_TSE); -#endif /* RTC_CR_TSEDGE */ - - /* Configure the Time Stamp TSEDGE and Enable bits */ - SET_BIT(RTC->CR, (uint32_t)TimeStampEdge | RTC_CR_TSE); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Set TimeStamp with Interrupt. - * @note This API must be called before enabling the TimeStamp feature. - * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. - * @param hrtc RTC handle - * @param TimeStampEdge Specifies the pin edge on which the TimeStamp is - * activated. - * This parameter can be one of the following values: - * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the - * rising edge of the related pin. - * @arg RTC_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_DEFAULT: PC13 is selected as RTC TimeStamp Pin. - * The RTC TimeStamp Pin is per default PC13, but for reasons of - * compatibility, this parameter is required. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) -{ - /* Check the parameters */ -#if defined(RTC_CR_TSEDGE) - assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); -#endif /* RTC_CR_TSEDGE */ - assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); - UNUSED(RTC_TimeStampPin); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Get the RTC_CR register and clear the bits to be configured */ -#if defined(RTC_CR_TSEDGE) - CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE)); -#else - CLEAR_BIT(RTC->CR, (RTC_CR_TSE | RTC_CR_TSIE)); -#endif /* RTC_CR_TSEDGE */ - - /* Configure the Time Stamp TSEDGE before Enable bit to avoid unwanted TSF setting. */ - SET_BIT(RTC->CR, (uint32_t)TimeStampEdge); - - /* Enable timestamp and IT */ - SET_BIT(RTC->CR, RTC_CR_TSE | RTC_CR_TSIE); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Deactivate TimeStamp. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* In case of interrupt mode is used, the interrupt source must disabled */ -#if defined(RTC_CR_TSEDGE) - CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE)); -#else - CLEAR_BIT(RTC->CR, (RTC_CR_TSE | RTC_CR_TSIE)); -#endif /* RTC_CR_TSEDGE */ - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} -#endif /* RTC_CR_TSE */ - -/** - * @brief Set Internal TimeStamp. - * @note This API must be called before enabling the internal TimeStamp feature. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetInternalTimeStamp(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Configure the internal Time Stamp Enable bits */ - SET_BIT(RTC->CR, RTC_CR_ITSE); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Deactivate Internal TimeStamp. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTimeStamp(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Configure the internal Time Stamp Enable bits */ - CLEAR_BIT(RTC->CR, RTC_CR_ITSE); - - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Get 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 RTC_FORMAT_BIN: Binary data format - * @arg RTC_FORMAT_BCD: BCD data format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(const RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, - RTC_DateTypeDef *sTimeStampDate, uint32_t Format) -{ - uint32_t tmptime; - uint32_t tmpdate; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_FORMAT(Format)); - - /* Get the TimeStamp time and date registers values */ - tmptime = READ_BIT(RTC->TSTR, RTC_TR_RESERVED_MASK); - tmpdate = READ_BIT(RTC->TSDR, RTC_DR_RESERVED_MASK); - - /* Fill the Time structure fields with the read parameters */ - sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TSTR_HT | RTC_TSTR_HU)) >> RTC_TSTR_HU_Pos); - sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TSTR_MNT | RTC_TSTR_MNU)) >> RTC_TSTR_MNU_Pos); - sTimeStamp->Seconds = (uint8_t)((tmptime & (RTC_TSTR_ST | RTC_TSTR_SU)) >> RTC_TSTR_SU_Pos); - sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TSTR_PM)) >> RTC_TSTR_PM_Pos); - sTimeStamp->SubSeconds = READ_BIT(RTC->TSSSR, RTC_TSSSR_SS); - - /* Fill the Date structure fields with the read parameters */ - sTimeStampDate->Year = 0U; - sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_TSDR_MT | RTC_TSDR_MU)) >> RTC_TSDR_MU_Pos); - sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_TSDR_DT | RTC_TSDR_DU)); - sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_TSDR_WDU)) >> RTC_TSDR_WDU_Pos); - - /* Check the input parameters format */ - if (Format == RTC_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); - } - - /* Check if TIMESTAMP flag is set */ - if (READ_BIT(RTC->SR, RTC_SR_TSF) != 0U) - { - /* Clear the TIMESTAMP Flags */ - WRITE_REG(RTC->SCR, (RTC_SCR_CITSF | RTC_SCR_CTSF)); - - /* Check if TIMESTAMP OverRun flag is set */ - if (READ_BIT(RTC->SR, RTC_SR_TSOVF) != 0U) - { - /* Clear the TIMESTAMP OverRun Flag */ - WRITE_REG(RTC->SCR, RTC_SCR_CTSOVF); - - return HAL_ERROR; - } - } - - return HAL_OK; -} - -/** - * @brief Handle TimeStamp interrupt request. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc) -{ - /* Get the pending status of the TimeStamp Interrupt */ - if (READ_BIT(RTC->MISR, RTC_MISR_TSMF) != 0U) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call TimeStampEvent registered Callback */ - hrtc->TimeStampEventCallback(hrtc); -#else - HAL_RTCEx_TimeStampEventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - - /* Clearing flags after the Callback because the content of RTC_TSTR and RTC_TSDR are cleared when - TSF bit is reset.*/ - WRITE_REG(RTC->SCR, RTC_SCR_CITSF | RTC_SCR_CTSF); - } - - /* 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_TimeStampEventCallback could be implemented in the user file - */ -} - -/** - * @brief Handle TimeStamp polling request. - * @param hrtc RTC handle - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - uint32_t tickstart = HAL_GetTick(); - - while (READ_BIT(RTC->SR, RTC_SR_TSF) == 0U) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->SR, RTC_SR_TSF) == 0U) - { - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - return HAL_OK; -} - -/** - * @} - */ - -/** @addtogroup RTCEx_Exported_Functions_Group2 - * @brief RTC Wake-up functions - * -@verbatim - =============================================================================== - ##### RTC Wake-up functions ##### - =============================================================================== - - [..] This section provides functions allowing to configure Wake-up feature - -@endverbatim - * @{ - */ - -/** - * @brief Set 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 tickstart; - - /* Check the parameters */ - assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); - assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Clear WUTE in RTC_CR to disable the wakeup timer */ - CLEAR_BIT(RTC->CR, RTC_CR_WUTE); - - /* Poll WUTWF until it is set in RTC_ICSR to make sure the access to wakeup autoreload - counter and to WUCKSEL[2:0] bits is allowed. This step must be skipped in - calendar initialization mode. */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) - { - tickstart = HAL_GetTick(); - - while (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Configure the clock source */ - MODIFY_REG(RTC->CR, RTC_CR_WUCKSEL, (uint32_t)WakeUpClock); - - /* Configure the Wakeup Timer counter */ - WRITE_REG(RTC->WUTR, (uint32_t)WakeUpCounter); - - /* Enable the Wakeup Timer */ - SET_BIT(RTC->CR, RTC_CR_WUTE); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Set wake up timer with interrupt. - * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. - * @param hrtc RTC handle - * @param WakeUpCounter Wake up counter - * @param WakeUpClock Wake up clock - * @param WakeUpAutoClr Wake up auto clear value (look at WUTOCLR in reference manual) - * - No effect if WakeUpAutoClr is set to zero - * - This feature is meaningful in case of Low power mode to avoid any RTC software execution - * after Wake Up. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock, - uint32_t WakeUpAutoClr) -{ - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); - assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); - /* (0x0000<=WUTOCLR<=WUT) */ - assert_param(WakeUpAutoClr <= WakeUpCounter); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Clear WUTE in RTC_CR to disable the wakeup timer */ - CLEAR_BIT(RTC->CR, RTC_CR_WUTE); - - /* Clear flag Wake-Up */ - WRITE_REG(RTC->SCR, RTC_SCR_CWUTF); - - /* Poll WUTWF until it is set in RTC_ICSR to make sure the access to wakeup autoreload - counter and to WUCKSEL[2:0] bits is allowed. This step must be skipped in - calendar initialization mode. */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) - { - tickstart = HAL_GetTick(); - while (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Configure the Wakeup Timer counter and auto clear value */ - WRITE_REG(RTC->WUTR, (uint32_t)(WakeUpCounter | (WakeUpAutoClr << RTC_WUTR_WUTOCLR_Pos))); - - /* Configure the clock source */ - MODIFY_REG(RTC->CR, RTC_CR_WUCKSEL, (uint32_t)WakeUpClock); - - /* Configure the Interrupt in the RTC_CR register and Enable the Wakeup Timer*/ - SET_BIT(RTC->CR, (RTC_CR_WUTIE | RTC_CR_WUTE)); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Deactivate wake up timer counter. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable the Wakeup Timer */ - /* In case of interrupt mode is used, the interrupt source must disabled */ - CLEAR_BIT(RTC->CR, (RTC_CR_WUTE | RTC_CR_WUTIE)); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Get wake up timer counter. - * @param hrtc RTC handle - * @retval Counter value - */ -uint32_t HAL_RTCEx_GetWakeUpTimer(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Get the counter value */ - return (uint32_t)(READ_BIT(RTC->WUTR, RTC_WUTR_WUT)); -} - -/** - * @brief Handle Wake Up Timer interrupt request. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) -{ - /* Get the pending status of the Wake-Up Timer Interrupt */ - if (READ_BIT(RTC->MISR, RTC_MISR_WUTMF) != 0U) - { - /* Immediately clear flags */ - WRITE_REG(RTC->SCR, RTC_SCR_CWUTF); -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call wake up timer registered Callback */ - hrtc->WakeUpTimerEventCallback(hrtc); -#else - HAL_RTCEx_WakeUpTimerEventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_WakeUpTimerEventCallback could be implemented in the user file - */ -} - -/** - * @brief Handle Wake Up Timer Polling. - * @param hrtc RTC handle - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - uint32_t tickstart = HAL_GetTick(); - - while (READ_BIT(RTC->SR, RTC_SR_WUTF) == 0U) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->SR, RTC_SR_WUTF) == 0U) - { - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Clear the WAKEUPTIMER Flag */ - WRITE_REG(RTC->SCR, RTC_SCR_CWUTF); - - return HAL_OK; -} - -/** - * @} - */ - -/** @addtogroup RTCEx_Exported_Functions_Group3 - * @brief Extended Peripheral Control functions - * -@verbatim - =============================================================================== - ##### Extended Peripheral Control functions ##### - =============================================================================== - [..] - This subsection provides functions allowing to - (+) Write a data in a specified RTC Backup data register - (+) Read a data in a specified RTC Backup data register - (+) Set the Coarse calibration parameters. - (+) Deactivate the Coarse calibration parameters - (+) Set the Smooth calibration parameters. - (+) Set Low Power calibration parameter. - (+) Configure the Synchronization Shift Control Settings. - (+) Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). - (+) Deactivate the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). - (+) Enable the RTC reference clock detection. - (+) Disable the RTC reference clock detection. - (+) Enable the Bypass Shadow feature. - (+) Disable the Bypass Shadow feature. - -@endverbatim - * @{ - */ - -/** - * @brief Set the Smooth calibration parameters. - * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses - * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field - * SmoothCalibMinusPulsesValue must be equal to 0. - * @param hrtc RTC handle - * @param SmoothCalibPeriod Select the Smooth Calibration Period. - * This parameter can be one of the following values : - * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration period is 32s. - * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration period is 16s. - * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibration period 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 pulse every 2*11 pulses. - * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added. - * @param SmoothCalibMinusPulsesValue Select the value of CALM[8:0] bits. - * This parameter can be one any value from 0 to 0x000001FF. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, - uint32_t SmoothCalibPlusPulses, uint32_t SmoothCalibMinusPulsesValue) -{ - uint32_t tickstart; - - /* 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(SmoothCalibMinusPulsesValue)); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - tickstart = HAL_GetTick(); - - /* check if a calibration is pending */ - while (READ_BIT(RTC->ICSR, RTC_ICSR_RECALPF) != 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_RECALPF) != 0U) - { - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Configure the Smooth calibration settings */ - MODIFY_REG(RTC->CALR, (RTC_CALR_CALP | RTC_CALR_CALW8 | RTC_CALR_CALW16 | RTC_CALR_CALM), - (uint32_t)(SmoothCalibPeriod | SmoothCalibPlusPulses | SmoothCalibMinusPulsesValue)); - - /* 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 Select the low power Calibration mode. - * @param hrtc: RTC handle - * @param LowPowerCalib: Low power Calibration mode. - * This parameter can be one of the following values : - * @arg RTC_LPCAL_SET: Low power mode. - * @arg RTC_LPCAL_RESET: High consumption mode. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetLowPowerCalib(RTC_HandleTypeDef *hrtc, uint32_t LowPowerCalib) -{ - /* Check the parameters */ - assert_param(IS_RTC_LOW_POWER_CALIB(LowPowerCalib)); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Configure the Smooth calibration settings */ - MODIFY_REG(RTC->CALR, RTC_CALR_LPCAL, LowPowerCalib); - - /* 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 Configure 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 tickstart; - - /* Check the parameters */ - assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S)); - assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS)); - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - tickstart = HAL_GetTick(); - - /* Wait until the shift is completed */ - while (READ_BIT(RTC->ICSR, RTC_ICSR_SHPF) != 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->ICSR, RTC_ICSR_SHPF) != 0U) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - -#if defined(RTC_CR_REFCKON) - /* Check if the reference clock detection is disabled */ - if (READ_BIT(RTC->CR, RTC_CR_REFCKON) == 0U) - { -#endif /* RTC_CR_REFCKON */ - /* Configure the Shift settings */ - MODIFY_REG(RTC->SHIFTR, RTC_SHIFTR_SUBFS, (uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S)); - - /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ - if (READ_BIT(RTC->CR, RTC_CR_BYPSHAD) == 0U) - { - if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) - { - /* 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; - } - } -#if defined(RTC_CR_REFCKON) - } - 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; - } -#endif /* RTC_CR_REFCKON */ - - /* 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; -} - -#if defined(RTC_CR_COSEL) -/** - * @brief Configure 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); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Configure the RTC_CR register */ - MODIFY_REG(RTC->CR, RTC_CR_COSEL, CalibOutput); - - /* Enable calibration output */ - SET_BIT(RTC->CR, RTC_CR_COE); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Deactivate 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); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable calibration output */ - CLEAR_BIT(RTC->CR, RTC_CR_COE); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} -#endif /* RTC_CR_COSEL */ - -#if defined(RTC_CR_REFCKON) -/** - * @brief Enable the RTC reference clock detection. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc) -{ - HAL_StatusTypeDef status; - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Enter Initialization mode */ - status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { - /* Enable clockref detection */ - SET_BIT(RTC->CR, RTC_CR_REFCKON); - - /* Exit Initialization mode */ - status = RTC_ExitInitMode(hrtc); - } - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - - if (status == HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - } - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return status; -} - -/** - * @brief Disable the RTC reference clock detection. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc) -{ - HAL_StatusTypeDef status; - - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Disable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); - - /* Enter Initialization mode */ - status = RTC_EnterInitMode(hrtc); - if (status == HAL_OK) - { - /* Disable clockref detection */ - CLEAR_BIT(RTC->CR, RTC_CR_REFCKON); - - /* Exit Initialization mode */ - status = RTC_ExitInitMode(hrtc); - } - - /* Enable the write protection for RTC registers */ - __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); - - if (status == HAL_OK) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - } - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return status; -} -#endif /* RTC_CR_REFCKON */ - -/** - * @brief Enable the Bypass Shadow feature. - * @note When the Bypass Shadow is enabled the calendar value are taken - * directly from the Calendar counter. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Set the BYPSHAD bit */ - SET_BIT(RTC->CR, RTC_CR_BYPSHAD); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Disable the Bypass Shadow feature. - * @note When the Bypass Shadow is enabled the calendar value are taken - * directly from the Calendar counter. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Reset the BYPSHAD bit */ - CLEAR_BIT(RTC->CR, RTC_CR_BYPSHAD); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Increment Monotonic counter. - * @param hrtc RTC handle - * @param Instance Monotonic counter Instance - * This parameter can be one of the following values : - * @arg RTC_MONOTONIC_COUNTER_1 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_MonotonicCounterIncrement(const RTC_HandleTypeDef *hrtc, uint32_t Instance) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - UNUSED(Instance); - - /* This register is read-only only and is incremented by one when a write access is done to this - register. This register cannot roll-over and is frozen when reaching the maximum value. */ - CLEAR_REG(TAMP->COUNT1R); - - return HAL_OK; -} - -/** - * @brief Monotonic counter. - * @param hrtc RTC handle - * @param Instance Monotonic counter Instance - * This parameter can be one of the following values : - * @arg RTC_MONOTONIC_COUNTER_1 - * @param pValue Pointer to the counter monotonic counter value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_MonotonicCounterGet(const RTC_HandleTypeDef *hrtc, uint32_t Instance, uint32_t *pValue) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - UNUSED(Instance); - - /* This register is read-only only and is incremented by one when a write access is done to this - register. This register cannot roll-over and is frozen when reaching the maximum value. */ - *pValue = READ_REG(TAMP->COUNT1R); - - return HAL_OK; -} - -/** - * @brief Set SSR Underflow detection with Interrupt. - * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetSSRU_IT(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* Enable IT SSRU */ - __HAL_RTC_SSRU_ENABLE_IT(hrtc, RTC_IT_SSRU); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Deactivate SSR Underflow. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateSSRU(RTC_HandleTypeDef *hrtc) -{ - /* Process Locked */ - __HAL_LOCK(hrtc); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_BUSY; - - /* In case of interrupt mode is used, the interrupt source must disabled */ - __HAL_RTC_SSRU_DISABLE_IT(hrtc, RTC_IT_SSRU); - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hrtc); - - return HAL_OK; -} - -/** - * @brief Handle SSR underflow interrupt request. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_SSRUIRQHandler(RTC_HandleTypeDef *hrtc) -{ - /* Get the pending status of the SSR Underflow Interrupt */ - if (READ_BIT(RTC->MISR, RTC_MISR_SSRUMF) != 0U) - { - /* Immediately clear SSR underflow flag */ - WRITE_REG(RTC->SCR, RTC_SCR_CSSRUF); - - /* SSRU callback */ -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call SSRUEvent registered Callback */ - hrtc->SSRUEventCallback(hrtc); -#else - HAL_RTCEx_SSRUEventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - - } - - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_READY; -} - -/** - * @brief SSR underflow callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_SSRUEventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_SSRUEventCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @addtogroup RTCEx_Exported_Functions_Group4 - * @brief Extended features functions - * -@verbatim - =============================================================================== - ##### Extended features functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) RTC Alarm 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_AlarmBEventCallback could be implemented in the user file - */ -} - -/** - * @brief Handle Alarm B Polling request. - * @param hrtc RTC handle - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - uint32_t tickstart = HAL_GetTick(); - - while (READ_BIT(RTC->SR, RTC_SR_ALRBF) == 0U) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(RTC->SR, RTC_SR_ALRBF) == 0U) - { - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Clear the Alarm Flag */ - WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); - - return HAL_OK; -} - -/** - * @} - */ - -/** @addtogroup RTCEx_Exported_Functions_Group5 - * @brief Extended RTC Tamper functions - * -@verbatim - ============================================================================== - ##### Tamper functions ##### - ============================================================================== - [..] - (+) Before calling any tamper or internal tamper function, you have to call first - HAL_RTC_Init() function. - (+) In that one you can select to output tamper event on RTC pin. - [..] - (+) Enable the 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, NoErase, MaskFlag, precharge or discharge and - Pull-UP, timestamp using the HAL_RTCEx_SetTamper() function. - You can configure Tamper with interrupt mode using HAL_RTCEx_SetTamper_IT() function. - (+) The default configuration of the Tamper erases the backup registers. To avoid - erase, enable the NoErase field on the TAMP_TAMPCR register. - [..] - (+) Enable Internal Tamper and configure it with interrupt, timestamp using - the HAL_RTCEx_SetInternalTamper() function. - -@endverbatim - * @{ - */ - - -/** - * @brief Set Tamper - * @param hrtc RTC handle - * @param sTamper Pointer to Tamper Structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetTamper(const RTC_HandleTypeDef *hrtc, const RTC_TamperTypeDef *sTamper) -{ - uint32_t tmpreg; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_TAMPER(sTamper->Tamper)); - assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); - assert_param(IS_RTC_TAMPER_ERASE_MODE(sTamper->NoErase)); - assert_param(IS_RTC_TAMPER_MASKFLAG_STATE(sTamper->MaskFlag)); - assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); -#if (RTC_TAMP_NB > 2U) - /* Mask flag only supported by TAMPER 1, 2 and 3 */ - assert_param(!((sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) && (sTamper->Tamper > RTC_TAMPER_3))); -#else - assert_param(!((sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) && (sTamper->Tamper > RTC_TAMPER_2))); -#endif /* (RTC_TAMP_NB > 2U) */ - assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter)); - assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); - assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); - assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); - /* Trigger and Filter have exclusive configurations */ - assert_param(((sTamper->Filter != RTC_TAMPERFILTER_DISABLE) && - ((sTamper->Trigger == RTC_TAMPERTRIGGER_LOWLEVEL) || - (sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL))) || - ((sTamper->Filter == RTC_TAMPERFILTER_DISABLE) && - ((sTamper->Trigger == RTC_TAMPERTRIGGER_RISINGEDGE) || - (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)))); - - /* Configuration register 2 */ - tmpreg = READ_REG(TAMP->CR2); - tmpreg &= ~((sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos) | (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos) | - (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos)); - - if ((sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL) || (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)) - { - tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos); - } - - if (sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) - { - tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos); - } - - if (sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) - { - tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos); - } - WRITE_REG(TAMP->CR2, tmpreg); - - /* Filter control register */ - WRITE_REG(TAMP->FLTCR, sTamper->Filter | sTamper->SamplingFrequency | sTamper->PrechargeDuration | - sTamper->TamperPullUp); - - /* Timestamp on tamper */ - if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sTamper->TimeStampOnTamperDetection) - { - MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection); - } - - /* Control register 1 */ - SET_BIT(TAMP->CR1, sTamper->Tamper); - - return HAL_OK; -} - - -/** - * @brief Set Tamper in IT mode - * @note The application must ensure that the EXTI TAMP interrupt line is configured and enabled. - * @param hrtc RTC handle - * @param sTamper Pointer to Tamper Structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(const RTC_HandleTypeDef *hrtc, const RTC_TamperTypeDef *sTamper) -{ - uint32_t tmpreg; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_TAMPER(sTamper->Tamper)); - assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); - assert_param(IS_RTC_TAMPER_ERASE_MODE(sTamper->NoErase)); - assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); - /* The interrupt must not be enabled when TAMPxMSK is set. */ - assert_param(sTamper->MaskFlag == RTC_TAMPERMASK_FLAG_DISABLE); - assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter)); - assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); - assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); - assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); - /* Trigger and Filter have exclusive configurations */ - assert_param(((sTamper->Filter != RTC_TAMPERFILTER_DISABLE) && - ((sTamper->Trigger == RTC_TAMPERTRIGGER_LOWLEVEL) || - (sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL))) || - ((sTamper->Filter == RTC_TAMPERFILTER_DISABLE) && - ((sTamper->Trigger == RTC_TAMPERTRIGGER_RISINGEDGE) || - (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)))); - - /* Configuration register 2 */ - tmpreg = READ_REG(TAMP->CR2); - tmpreg &= ~((sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos) | (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos) | - (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos)); - - if ((sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL) || (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)) - { - tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos); - } - - if (sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) - { - tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos); - } - WRITE_REG(TAMP->CR2, tmpreg); - - /* Filter control register */ - WRITE_REG(TAMP->FLTCR, sTamper->Filter | sTamper->SamplingFrequency | sTamper->PrechargeDuration | - sTamper->TamperPullUp); - - /* Timestamp on tamper */ - if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sTamper->TimeStampOnTamperDetection) - { - MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection); - } - - /* Interrupt enable register */ - SET_BIT(TAMP->IER, sTamper->Tamper); - - /* Control register 1 */ - SET_BIT(TAMP->CR1, sTamper->Tamper); - - return HAL_OK; -} - -/** - * @brief Deactivate Tamper. - * @param hrtc RTC handle - * @param Tamper Selected tamper pin. - * This parameter can be a combination of the following values: - * @arg RTC_TAMPER_1 - * @arg RTC_TAMPER_2 - * @arg RTC_TAMPER_3 - * @arg RTC_TAMPER_4 - * @arg RTC_TAMPER_5 - * @arg RTC_TAMPER_6 - * @arg RTC_TAMPER_7 - * @arg RTC_TAMPER_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(const RTC_HandleTypeDef *hrtc, uint32_t Tamper) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - assert_param(IS_RTC_TAMPER(Tamper)); - - /* Disable the selected Tamper pin */ - CLEAR_BIT(TAMP->CR1, Tamper); - - /* Clear tamper interrupt and event flags (WO register) */ - WRITE_REG(TAMP->SCR, Tamper); - - /* Clear tamper mask/noerase/trigger configuration */ - CLEAR_BIT(TAMP->CR2, (Tamper << TAMP_CR2_TAMP1TRG_Pos) | (Tamper << TAMP_CR2_TAMP1MSK_Pos) | \ - (Tamper << TAMP_CR2_TAMP1POM_Pos)); - - /* Clear tamper interrupt mode configuration */ - CLEAR_BIT(TAMP->IER, Tamper); - - return HAL_OK; -} - -/** - * @brief Set all active Tampers at the same time. - * @note For interrupt mode, the application must ensure that the EXTI RTC interrupt line is configured and enabled. - * @param hrtc RTC handle - * @param sAllTamper Pointer to active Tamper Structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetActiveTampers(RTC_HandleTypeDef *hrtc, const RTC_ActiveTampersTypeDef *sAllTamper) -{ - uint32_t tmp_ier; - uint32_t tmp_cr1; - uint32_t tmp_cr2; - uint32_t tmp_atcr1; - uint32_t tmp_atcr2; - uint32_t tmp_cr; - uint32_t i; - uint32_t tickstart; - -#ifdef USE_FULL_ASSERT - for (i = 0; i < RTC_TAMP_NB; i++) - { - assert_param(IS_RTC_TAMPER_ERASE_MODE(sAllTamper->TampInput[i].NoErase)); - assert_param(IS_RTC_TAMPER_MASKFLAG_STATE(sAllTamper->TampInput[i].MaskFlag)); - /* Mask flag only supported by TAMPER 1, 2 and 3 */ - assert_param(!((sAllTamper->TampInput[i].MaskFlag == RTC_TAMPERMASK_FLAG_ENABLE) && - (i >= RTC_TAMPER_MASKABLE_NB))); - } - assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sAllTamper->TimeStampOnTamperDetection)); - assert_param(IS_RTC_ATAMPER_FILTER(sAllTamper->ActiveFilter)); - assert_param(IS_RTC_ATAMPER_OUTPUT_CHANGE_PERIOD(sAllTamper->ActiveOutputChangePeriod)); - assert_param(IS_RTC_ATAMPER_ASYNCPRES_RTCCLK(sAllTamper->ActiveAsyncPrescaler)); -#endif /* USE_FULL_ASSERT */ - - /* Active Tampers must not be already enabled */ - if (READ_BIT(TAMP->ATOR, TAMP_ATOR_INITS) != 0U) - { - /* Disable all actives tampers with HAL_RTCEx_DeactivateActiveTampers. - No need to check return value because it returns always HAL_OK */ - (void) HAL_RTCEx_DeactivateActiveTampers(hrtc); - } - - /* Set TimeStamp on tamper detection */ - tmp_cr = READ_REG(RTC->CR); - if ((tmp_cr & RTC_CR_TAMPTS) != (sAllTamper->TimeStampOnTamperDetection)) - { - MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sAllTamper->TimeStampOnTamperDetection); - } - - tmp_cr1 = READ_REG(TAMP->CR1); - tmp_cr2 = READ_REG(TAMP->CR2); - tmp_atcr2 = 0U; - tmp_ier = READ_REG(TAMP->IER); - - /* Set common parameters */ - tmp_atcr1 = (sAllTamper->ActiveFilter | (sAllTamper->ActiveOutputChangePeriod << TAMP_ATCR1_ATPER_Pos) | - sAllTamper->ActiveAsyncPrescaler); - - /* Set specific parameters for each active tamper inputs if enable */ - for (i = 0; i < RTC_TAMP_NB; i++) - { - if (sAllTamper->TampInput[i].Enable != RTC_ATAMP_DISABLE) - { - tmp_cr1 |= (TAMP_CR1_TAMP1E << i); - tmp_atcr1 |= (TAMP_ATCR1_TAMP1AM << i); - - if (sAllTamper->TampInput[i].Interrupt != RTC_ATAMP_INTERRUPT_DISABLE) - { - /* Interrupt enable register */ - tmp_ier |= (TAMP_IER_TAMP1IE << i); - } - - if (sAllTamper->TampInput[i].MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) - { - tmp_cr2 |= (TAMP_CR2_TAMP1MSK << i); - } - - if (sAllTamper->TampInput[i].NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) - { - tmp_cr2 |= (TAMP_CR2_TAMP1POM << i); - } - - /* Configure ATOSELx[] in case of output sharing */ - tmp_atcr2 |= sAllTamper->TampInput[i].Output << ((3U * i) + TAMP_ATCR2_ATOSEL1_Pos); - - if (i != sAllTamper->TampInput[i].Output) - { - tmp_atcr1 |= TAMP_ATCR1_ATOSHARE; - } - } - } - - WRITE_REG(TAMP->IER, tmp_ier); - WRITE_REG(TAMP->ATCR1, tmp_atcr1); - WRITE_REG(TAMP->ATCR2, tmp_atcr2); - WRITE_REG(TAMP->CR2, tmp_cr2); - WRITE_REG(TAMP->CR1, tmp_cr1); - - /* Write seed */ - for (i = 0; i < RTC_ATAMP_SEED_NB_UINT32; i++) - { - WRITE_REG(TAMP->ATSEEDR, sAllTamper->Seed[i]); - } - - /* Wait till RTC SEEDF flag is cleared and if Time out is reached exit */ - tickstart = HAL_GetTick(); - while (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - - return HAL_OK; -} - -/** - * @brief Write a new seed. Active tamper must be enabled. - * @param hrtc RTC handle - * @param pSeed Pointer to active tamper seed values. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetActiveSeed(RTC_HandleTypeDef *hrtc, const uint32_t *pSeed) -{ - uint32_t i; - uint32_t tickstart; - - /* Active Tampers must be enabled */ - if (READ_BIT(TAMP->ATOR, TAMP_ATOR_INITS) == 0U) - { - return HAL_ERROR; - } - - for (i = 0; i < RTC_ATAMP_SEED_NB_UINT32; i++) - { - WRITE_REG(TAMP->ATSEEDR, pSeed[i]); - } - - /* Wait till RTC SEEDF flag is cleared and if Time out is reached exit */ - tickstart = HAL_GetTick(); - while (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) - { - if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) - { - /* Change RTC state */ - hrtc->State = HAL_RTC_STATE_TIMEOUT; - - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - - return HAL_OK; -} - -#if defined(TAMP_CFGR_BHKLOCK) -/** - * @brief Lock the Boot hardware Key - * @param hrtc RTC handle - * @note The backup registers from TAMP_BKP0R to TAMP_BKP7R cannot be accessed neither in - * read nor in write (they are read as 0 and write ignore). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_LockBootHardwareKey(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - WRITE_REG(TAMP->CFGR, TAMP_CFGR_BHKLOCK); - - return HAL_OK; -} -#endif /* TAMP_CFGR_BHKLOCK */ - -/** - * @brief Deactivate all Active Tampers at the same time. - * @param hrtc RTC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateActiveTampers(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Get Active tampers */ - uint32_t atamp_mask = READ_BIT(TAMP->ATCR1, TAMP_ALL); - - /* Disable all actives tampers but not passives tampers */ - CLEAR_BIT(TAMP->CR1, atamp_mask); - - /* Clear tamper interrupt and event flags (WO register) of all actives tampers but not passives tampers */ - WRITE_REG(TAMP->SCR, atamp_mask); - - /* Disable no erase and mask */ - CLEAR_BIT(TAMP->CR2, (atamp_mask | ((atamp_mask & (TAMP_ATCR1_TAMP1AM | TAMP_ATCR1_TAMP2AM | TAMP_ATCR1_TAMP3AM)) << - TAMP_CR2_TAMP1MSK_Pos))); - - /* Clear all active tampers interrupt mode configuration but not passives tampers */ - CLEAR_BIT(TAMP->IER, atamp_mask); - - /* Set reset value for active tamper control register 1 */ - WRITE_REG(TAMP->ATCR1, TAMP_ATCR1_ATCKSEL_0 | TAMP_ATCR1_ATCKSEL_1 | TAMP_ATCR1_ATCKSEL_2); - - /* Set reset value for active tamper control register 2 */ - CLEAR_REG(TAMP->ATCR2); - - return HAL_OK; -} - -/** - * @brief Tamper event polling. - * @param hrtc RTC handle - * @param Tamper Selected tamper pin. - * This parameter can be a combination of the following values: - * @arg RTC_TAMPER_1 - * @arg RTC_TAMPER_2 - * @arg RTC_TAMPER_3 - * @arg RTC_TAMPER_4 - * @arg RTC_TAMPER_5 - * @arg RTC_TAMPER_6 - * @arg RTC_TAMPER_7 - * @arg RTC_TAMPER_8 - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_PollForTamperEvent(const RTC_HandleTypeDef *hrtc, uint32_t Tamper, uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - assert_param(IS_RTC_TAMPER(Tamper)); - - uint32_t tickstart = HAL_GetTick(); - - /* Get the status of the Interrupt */ - while (READ_BIT(TAMP->SR, Tamper) != Tamper) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(TAMP->SR, Tamper) != Tamper) - { - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Clear the Tamper Flag */ - WRITE_REG(TAMP->SCR, Tamper); - - return HAL_OK; -} - - -/** - * @brief Set Internal Tamper - * @param hrtc RTC handle - * @param sIntTamper Pointer to Internal Tamper Structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetInternalTamper(const RTC_HandleTypeDef *hrtc, - const RTC_InternalTamperTypeDef *sIntTamper) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_INTERNAL_TAMPER(sIntTamper->IntTamper)); - assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sIntTamper->TimeStampOnTamperDetection)); - assert_param(IS_RTC_TAMPER_ERASE_MODE(sIntTamper->NoErase)); - - /* Timestamp enable on internal tamper */ - if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection) - { - MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection); - } - - /* No Erase Backup register enable for Internal Tamper */ - if (sIntTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) - { - SET_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); - } - else - { - CLEAR_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); - } - - /* Enable Internal Tamper */ - SET_BIT(TAMP->CR1, sIntTamper->IntTamper); - - return HAL_OK; -} - - -/** - * @brief Set Internal Tamper in interrupt mode - * @note The application must ensure that the EXTI RTC tamper interrupt line is configured and enabled. - * @param hrtc RTC handle - * @param sIntTamper Pointer to Internal Tamper Structure. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_SetInternalTamper_IT(const RTC_HandleTypeDef *hrtc, - const RTC_InternalTamperTypeDef *sIntTamper) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_INTERNAL_TAMPER(sIntTamper->IntTamper)); - assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sIntTamper->TimeStampOnTamperDetection)); - assert_param(IS_RTC_TAMPER_ERASE_MODE(sIntTamper->NoErase)); - - /* Timestamp enable on internal tamper */ - if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection) - { - MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection); - } - - /* Interrupt enable register */ - SET_BIT(TAMP->IER, sIntTamper->IntTamper); - - /* No Erase Backup register enable for Internal Tamper */ - if (sIntTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) - { - SET_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); - } - else - { - CLEAR_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); - } - - /* Enable Internal Tamper */ - SET_BIT(TAMP->CR1, sIntTamper->IntTamper); - - return HAL_OK; -} - -/** - * @brief Deactivate Internal Tamper. - * @param hrtc RTC handle - * @param IntTamper Selected internal tamper event. - * This parameter can be any combination of existing internal tampers. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTamper(const RTC_HandleTypeDef *hrtc, uint32_t IntTamper) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - assert_param(IS_RTC_INTERNAL_TAMPER(IntTamper)); - - /* Disable the selected Tamper pin */ - CLEAR_BIT(TAMP->CR1, IntTamper); - - /* Clear internal tamper interrupt mode configuration */ - CLEAR_BIT(TAMP->IER, IntTamper); - - /* Clear internal tamper interrupt */ - WRITE_REG(TAMP->SCR, IntTamper); - - return HAL_OK; -} - -/** - * @brief Internal Tamper event polling. - * @param hrtc RTC handle - * @param IntTamper selected tamper. - * This parameter can be any combination of existing internal tampers. - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RTCEx_PollForInternalTamperEvent(const RTC_HandleTypeDef *hrtc, uint32_t IntTamper, - uint32_t Timeout) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - assert_param(IS_RTC_INTERNAL_TAMPER(IntTamper)); - - uint32_t tickstart = HAL_GetTick(); - - /* Get the status of the Interrupt */ - while (READ_BIT(TAMP->SR, IntTamper) != IntTamper) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(TAMP->SR, IntTamper) != IntTamper) - { - return HAL_TIMEOUT; - } - else - { - break; - } - } - } - } - - /* Clear the Tamper Flag */ - WRITE_REG(TAMP->SCR, IntTamper); - - return HAL_OK; -} - -/** - * @brief Handle Tamper interrupt request. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_TamperIRQHandler(RTC_HandleTypeDef *hrtc) -{ - /* Get the pending status of the Tampers Interrupt */ - uint32_t tmp = READ_REG(TAMP->MISR); - - /* Check Tamper1 status */ - if ((tmp & RTC_TAMPER_1) == RTC_TAMPER_1) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 1 Event registered Callback */ - hrtc->Tamper1EventCallback(hrtc); -#else - /* Tamper1 callback */ - HAL_RTCEx_Tamper1EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Tamper2 status */ - if ((tmp & RTC_TAMPER_2) == RTC_TAMPER_2) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 2 Event registered Callback */ - hrtc->Tamper2EventCallback(hrtc); -#else - /* Tamper2 callback */ - HAL_RTCEx_Tamper2EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - -#if (RTC_TAMP_NB > 2U) - - /* Check Tamper3 status */ - if ((tmp & RTC_TAMPER_3) == RTC_TAMPER_3) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 3 Event registered Callback */ - hrtc->Tamper3EventCallback(hrtc); -#else - /* Tamper3 callback */ - HAL_RTCEx_Tamper3EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Tamper4 status */ - if ((tmp & RTC_TAMPER_4) == RTC_TAMPER_4) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 4 Event registered Callback */ - hrtc->Tamper4EventCallback(hrtc); -#else - /* Tamper4 callback */ - HAL_RTCEx_Tamper4EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Tamper5 status */ - if ((tmp & RTC_TAMPER_5) == RTC_TAMPER_5) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 5 Event registered Callback */ - hrtc->Tamper5EventCallback(hrtc); -#else - /* Tamper5 callback */ - HAL_RTCEx_Tamper5EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Tamper6 status */ - if ((tmp & RTC_TAMPER_6) == RTC_TAMPER_6) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 6 Event registered Callback */ - hrtc->Tamper6EventCallback(hrtc); -#else - /* Tamper6 callback */ - HAL_RTCEx_Tamper6EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - -#endif /* (RTC_TAMP_NB > 2U) */ -#if (RTC_TAMP_NB > 6U) - - /* Check Tamper7 status */ - if ((tmp & RTC_TAMPER_7) == RTC_TAMPER_7) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 7 Event registered Callback */ - hrtc->Tamper7EventCallback(hrtc); -#else - /* Tamper7 callback */ - HAL_RTCEx_Tamper7EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Tamper8 status */ - if ((tmp & RTC_TAMPER_8) == RTC_TAMPER_8) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Tamper 8 Event registered Callback */ - hrtc->Tamper8EventCallback(hrtc); -#else - /* Tamper8 callback */ - HAL_RTCEx_Tamper8EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - -#endif /* (RTC_TAMP_NB > 6U) */ - - /* Check Internal Tamper1 status */ - if ((tmp & RTC_INT_TAMPER_1) == RTC_INT_TAMPER_1) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 1 Event registered Callback */ - hrtc->InternalTamper1EventCallback(hrtc); -#else - /* Internal Tamper1 callback */ - HAL_RTCEx_InternalTamper1EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper2 status */ - if ((tmp & RTC_INT_TAMPER_2) == RTC_INT_TAMPER_2) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 2 Event registered Callback */ - hrtc->InternalTamper2EventCallback(hrtc); -#else - /* Internal Tamper2 callback */ - HAL_RTCEx_InternalTamper2EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper3 status */ - if ((tmp & RTC_INT_TAMPER_3) == RTC_INT_TAMPER_3) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 3 Event registered Callback */ - hrtc->InternalTamper3EventCallback(hrtc); -#else - /* Internal Tamper3 callback */ - HAL_RTCEx_InternalTamper3EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper4 status */ - if ((tmp & RTC_INT_TAMPER_4) == RTC_INT_TAMPER_4) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 4 Event registered Callback */ - hrtc->InternalTamper4EventCallback(hrtc); -#else - /* Internal Tamper4 callback */ - HAL_RTCEx_InternalTamper4EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper5 status */ - if ((tmp & RTC_INT_TAMPER_5) == RTC_INT_TAMPER_5) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 5 Event registered Callback */ - hrtc->InternalTamper5EventCallback(hrtc); -#else - /* Internal Tamper5 callback */ - HAL_RTCEx_InternalTamper5EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper6 status */ - if ((tmp & RTC_INT_TAMPER_6) == RTC_INT_TAMPER_6) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 6 Event registered Callback */ - hrtc->InternalTamper6EventCallback(hrtc); -#else - /* Internal Tamper6 callback */ - HAL_RTCEx_InternalTamper6EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper7 status */ - if ((tmp & RTC_INT_TAMPER_7) == RTC_INT_TAMPER_7) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 7 Event registered Callback */ - hrtc->InternalTamper7EventCallback(hrtc); -#else - /* Internal Tamper7 callback */ - HAL_RTCEx_InternalTamper7EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper8 status */ - if ((tmp & RTC_INT_TAMPER_8) == RTC_INT_TAMPER_8) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 8 Event registered Callback */ - hrtc->InternalTamper8EventCallback(hrtc); -#else - /* Internal Tamper8 callback */ - HAL_RTCEx_InternalTamper8EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper9 status */ - if ((tmp & RTC_INT_TAMPER_9) == RTC_INT_TAMPER_9) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 9 Event registered Callback */ - hrtc->InternalTamper9EventCallback(hrtc); -#else - /* Internal Tamper9 callback */ - HAL_RTCEx_InternalTamper9EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper11 status */ - if ((tmp & RTC_INT_TAMPER_11) == RTC_INT_TAMPER_11) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 11 Event registered Callback */ - hrtc->InternalTamper11EventCallback(hrtc); -#else - /* Internal Tamper11 callback */ - HAL_RTCEx_InternalTamper11EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Check Internal Tamper15 status */ - if ((tmp & RTC_INT_TAMPER_15) == RTC_INT_TAMPER_15) - { -#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) - /* Call Internal Tamper 15 Event registered Callback */ - hrtc->InternalTamper15EventCallback(hrtc); -#else - /* Internal Tamper15 callback */ - HAL_RTCEx_InternalTamper15EventCallback(hrtc); -#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ - } - - /* Clear flags after treatment to allow the potential tamper feature */ - WRITE_REG(TAMP->SCR, tmp); -} - -/** - * @brief Tamper 1 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper2EventCallback could be implemented in the user file - */ -} - -/** - * @brief Tamper 3 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper3EventCallback could be implemented in the user file - */ -} - -/** - * @brief Tamper 4 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper4EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper4EventCallback could be implemented in the user file - */ -} - -/** - * @brief Tamper 5 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper5EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper5EventCallback could be implemented in the user file - */ -} - -/** - * @brief Tamper 6 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper6EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper6EventCallback could be implemented in the user file - */ -} - -/** - * @brief Tamper 7 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper7EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper7EventCallback could be implemented in the user file - */ -} - -/** - * @brief Tamper 8 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_Tamper8EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_Tamper8EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 1 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper1EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper1EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 2 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper2EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper2EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 3 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper3EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper3EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 4 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper4EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper4EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 5 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper5EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper5EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 6 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper6EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper6EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 7 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper7EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper7EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 8 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper8EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper8EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 9 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper9EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper9EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 11 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper11EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper11EventCallback could be implemented in the user file - */ -} - -/** - * @brief Internal Tamper 15 callback. - * @param hrtc RTC handle - * @retval None - */ -__weak void HAL_RTCEx_InternalTamper15EventCallback(RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_RTCEx_InternalTamper15EventCallback could be implemented in the user file - */ -} -/** - * @} - */ - - -/** @addtogroup RTCEx_Exported_Functions_Group6 - * @brief Extended RTC Backup register functions - * -@verbatim - =============================================================================== - ##### Extended RTC Backup register functions ##### - =============================================================================== - [..] - (+) Before calling any tamper or internal tamper function, you have to call first - HAL_RTC_Init() function. - (+) In that one you can select to output tamper event on RTC pin. - [..] - This subsection provides functions allowing to - (+) Write a data in a specified RTC Backup data register - (+) Read a data in a specified RTC Backup data register -@endverbatim - * @{ - */ - - -/** - * @brief Write 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 RTC_BACKUP_NB - * @param Data Data to be written in the specified Backup data register. - * @retval None - */ -void HAL_RTCEx_BKUPWrite(const RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) -{ - uint32_t tmp; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_BKP(BackupRegister)); - - /* Determine address of the specified Backup register */ - tmp = (uint32_t)(&(TAMP->BKP0R)); - tmp += (BackupRegister * 4U); - - /* Write data in the specified register Backup 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 RTC_BACKUP_NB - * @retval Read value - */ -uint32_t HAL_RTCEx_BKUPRead(const RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) -{ - uint32_t tmp; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Check the parameters */ - assert_param(IS_RTC_BKP(BackupRegister)); - - /* Determine address of the specified Backup register */ - tmp = (uint32_t)(&(TAMP->BKP0R)); - tmp += (BackupRegister * 4U); - - /* Read the data from the specified register */ - return (*(__IO uint32_t *)tmp); -} - -/** - * @brief Reset the RTC Backup data Registers and the device secrets. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_BKUPErase(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - SET_BIT(TAMP->CR2, TAMP_CR2_BKERASE); -} - -/** - * @brief Block the access to the RTC Backup data Register and all the device secrets. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_BKUPBlock(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - WRITE_REG(TAMP->CR2, TAMP_CR2_BKBLOCK); -} - -/** - * @brief Disable the Block to the access to the RTC Backup data Register and the device secrets. - * @param hrtc RTC handle - * @retval None - */ -void HAL_RTCEx_BKUPUnblock(const RTC_HandleTypeDef *hrtc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - CLEAR_BIT(TAMP->CR2, TAMP_CR2_BKBLOCK); -} - -#ifdef TAMP_RPCFGR_RPCFG0 -/** - * @brief Enable and Disable the erase of the configurable Device Secrets - * @note This API must be called before enabling the Tamper. - * @param hrtc RTC handle - * @param DeviceSecretConf Specifies the configuration of the Device Secrets - * This parameter can be a combination of the following values: - * @arg TAMP_DEVICESECRETS_ERASE_NONE - * @arg TAMP_DEVICESECRETS_ERASE_BKPSRAM - * - * @retval None - */ -void HAL_RTCEx_ConfigEraseDeviceSecrets(const RTC_HandleTypeDef *hrtc, uint32_t DeviceSecretConf) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - MODIFY_REG(TAMP->RPCFGR, TAMP_RPCFGR_RPCFG0, DeviceSecretConf); -} -#endif /* TAMP_RPCFGR_RPCFG0 */ - -/** - * @} - */ - -#if defined(TAMP_PRIVCFGR_TAMPPRIV) -/** @addtogroup RTCEx_Exported_Functions_Group8 - * @brief Extended RTC privilege functions - * -@verbatim - =============================================================================== - ##### Extended RTC privilege functions ##### - =============================================================================== - [..] - (+) Before calling privilege function, you have to call first - HAL_RTC_Init() function. -@endverbatim - * @{ - */ - -/** - * @brief Set the privilege level of the RTC/TAMP/Backup registers. - * To get the current privilege level call HAL_RTCEx_PrivilegeModeGet. - * @param hrtc RTC handle - * @param privilegeState Privilege state - * @retval HAL_StatusTypeDef - */ -HAL_StatusTypeDef HAL_RTCEx_PrivilegeModeSet(const RTC_HandleTypeDef *hrtc, - const RTC_PrivilegeStateTypeDef *privilegeState) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - assert_param(IS_RTC_PRIVILEGE_FULL(privilegeState->rtcPrivilegeFull)); - assert_param(IS_RTC_PRIVILEGE_FEATURES(privilegeState->rtcPrivilegeFeatures)); - assert_param(IS_TAMP_PRIVILEGE_FULL(privilegeState->tampPrivilegeFull)); - assert_param(IS_TAMP_MONOTONIC_CNT_PRIVILEGE(privilegeState->MonotonicCounterPrivilege)); - assert_param(IS_RTC_PRIVILEGE_BKUP_ZONE(privilegeState->backupRegisterPrivZone)); - assert_param(IS_RTC_BKP(privilegeState->backupRegisterStartZone2)); - assert_param(IS_RTC_BKP(privilegeState->backupRegisterStartZone3)); - - /* RTC privilege configuration */ - WRITE_REG(RTC->PRIVCFGR, privilegeState->rtcPrivilegeFull | privilegeState->rtcPrivilegeFeatures); - - /* TAMP, Monotonic counter and Backup registers privilege configuration */ - WRITE_REG(TAMP->PRIVCFGR, privilegeState->tampPrivilegeFull | privilegeState->backupRegisterPrivZone | \ - privilegeState->MonotonicCounterPrivilege); - - /* Backup register start zone */ - MODIFY_REG(TAMP->CFGR, - (TAMP_CFGR_BKPRW | TAMP_CFGR_BKPW), - ((privilegeState->backupRegisterStartZone2 << TAMP_CFGR_BKPRW_Pos) | (privilegeState->backupRegisterStartZone3 << TAMP_CFGR_BKPW_Pos))); - - return HAL_OK; -} - -/** - * @brief Get the privilege level of the RTC/TAMP/Backup registers. - * To set the privilege level please call HAL_RTCEx_PrivilegeModeSet. - * @param hrtc RTC handle - * @param privilegeState Privilege state - * @retval HAL_StatusTypeDef - */ -HAL_StatusTypeDef HAL_RTCEx_PrivilegeModeGet(const RTC_HandleTypeDef *hrtc, RTC_PrivilegeStateTypeDef *privilegeState) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); - - /* Read registers */ - uint32_t rtc_privcfgr = READ_REG(RTC->PRIVCFGR); - uint32_t tamp_privcfgr = READ_REG(TAMP->PRIVCFGR); - uint32_t tamp_cfgr = READ_REG(TAMP->CFGR); - - /* RTC privilege configuration */ - privilegeState->rtcPrivilegeFull = READ_BIT(rtc_privcfgr, RTC_PRIVCFGR_PRIV); - - /* Warning, rtcPrivilegeFeatures is only relevant if privilegeState->rtcPrivilegeFull == RTC_PRIVILEGE_FULL_NO */ - privilegeState->rtcPrivilegeFeatures = READ_BIT(rtc_privcfgr, RTC_PRIVILEGE_FEATURE_ALL); - - /* TAMP and Backup registers privilege configuration */ - privilegeState->tampPrivilegeFull = READ_BIT(tamp_privcfgr, TAMP_PRIVCFGR_TAMPPRIV); - - /* Monotonic registers privilege configuration */ - privilegeState->MonotonicCounterPrivilege = READ_BIT(tamp_privcfgr, TAMP_PRIVCFGR_CNT1PRIV); - - /* Backup registers Zones */ - privilegeState->backupRegisterPrivZone = READ_BIT(tamp_privcfgr, (TAMP_PRIVCFGR_BKPWPRIV | TAMP_PRIVCFGR_BKPRWPRIV)); - - /* Backup registers start zones */ - privilegeState->backupRegisterStartZone2 = READ_BIT(tamp_cfgr, TAMP_CFGR_BKPRW) >> TAMP_CFGR_BKPRW_Pos; - privilegeState->backupRegisterStartZone3 = READ_BIT(tamp_cfgr, TAMP_CFGR_BKPW) >> TAMP_CFGR_BKPW_Pos; - - return HAL_OK; -} - -/** - * @} - */ -#endif /* TAMP_PRIVCFGR_TAMPPRIV */ - -/** - * @} - */ - -#endif /* HAL_RTC_MODULE_ENABLED */ - -/** - * @} - */ - - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_rtc_ex.c + * @author GPM Application Team + * @brief Extended RTC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Real Time Clock (RTC) Extended peripheral: + * + RTC Time Stamp functions + * + RTC Tamper functions + * + RTC Wake-up functions + * + Extended Control functions + * + Extended RTC features functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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_RTCEx_SetWakeUpTimer() + function. You can also configure the RTC Wakeup timer with interrupt mode + using the HAL_RTCEx_SetWakeUpTimer_IT() function. + (+) To read the RTC WakeUp Counter register, use the HAL_RTCEx_GetWakeUpTimer() + function. + + *** Outputs configuration *** + ============================= + [..] The RTC has 2 outputs pins (RTC_OUT1 & RTC_OUT2). + To configure the outputs, use the HAL_RTC_Init() function. + (+) RTC_OUT1 and RTC_OUT2 which select one of the following two outputs: + (+) CALIB: 512Hz or 1Hz clock output (with an LSE frequency of 32.768kHz). + To enable the CALIB, use the HAL_RTCEx_SetCalibrationOutPut() function. + (+) TAMPALRM: This output is the OR between rtc_tamp_evt and ALARM signals. + ALARM is enabled by configuring the OSEL[1:0] bits in the RTC_CR register + which select the alarm A, alarm B or wakeup outputs. + rtc_tamp_evt is enabled by setting the TAMPOE bit + in the RTC_CR register which selects the tamper event outputs. + + *** Smooth digital Calibration configuration *** + ================================================ + [..] + (+) Configure the RTC Original Digital Calibration Value and the corresponding + calibration cycle period (32s,16s and 8s) using the HAL_RTCEx_SetSmoothCalib() + function. + + *** RTC synchronization *** + ================================================ + [..] + (+) The RTC can be finely adjusted using HAL_RTCEx_SetSynchroShift() function. + Writing to RTC_SHIFTR can shift (either delay or advance) the clock with + a resolution of 1 ck_apre period. + The shift operation consists in adding the SUBFS[14:0] value to the synchronous + prescaler counter SS[15:0]: this delays the clock. + + *** Bypass shadow registers *** + ================================================ + [..] + (+) Enable bypass shadow registers using the HAL_RTCEx_EnableBypassShadow(). + When the Bypass Shadow is enabled the calendar value are taken directly + from the Calendar counter. + Thus eliminating the need to wait for the RSF bit to be set. + This is especially useful after exiting from low-power modes (Stop or Standby), + since the shadow registers are not updated during these modes. + + *** RTC ultra-low-power mode *** + ================================================ + [..] + (+) Configure the RTC ultra-low-power mode using HAL_RTCEx_SetLowPowerCalib() function. + In this case, the calibration mechanism is applied on ck_apre instead of RTCCLK. + The resulting accuracy is the same, but the calibration is performed during a + calibration cycle of about 220 x PREDIV_A x RTCCLK pulses instead of 220 RTCCLK pulses. + + *** RTC subsecond register underflow interruption *** + ================================================ + [..] + (+) Enable the RTC SSRU interruption mode using HAL_RTCEx_SetSSRU_IT() function. + In this case, when the SSR rolls under 0, an SSRU interruption is triggered. + Disable the RTC SSRU interruption mode using HAL_RTCEx_DeactivateSSRU() function. + + *** TimeStamp configuration *** + =============================== + [..] + (+) Enable the RTC TimeStamp using the HAL_RTCEx_SetTimeStamp() function. + You can also configure the RTC TimeStamp with interrupt mode using the + HAL_RTCEx_SetTimeStamp_IT() function. + (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTCEx_GetTimeStamp() + function. + + *** Internal TimeStamp configuration *** + =============================== + [..] + (+) Enable the RTC internal TimeStamp using the HAL_RTCEx_SetInternalTimeStamp() function. + User has to check internal timestamp occurrence using __HAL_RTC_INTERNAL_TIMESTAMP_GET_FLAG. + (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTCEx_GetTimeStamp() + 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, NoErase, MaskFlag, precharge or discharge and + Pull-UP using the HAL_RTCEx_SetTamper() function. You can configure RTC Tamper + with interrupt mode using HAL_RTCEx_SetTamper_IT() function. + (+) The default configuration of the Tamper erases the backup registers. To avoid + erase, enable the TAMPxPOM field on the TAMP_CR2 register. + (+) With new RTC tamper configuration, you have to call HAL_RTC_Init() in order to + perform TAMP base address offset calculation. + (+) Enable Internal tamper using HAL_RTCEx_SetInternalTamper. IT mode can be chosen using + setting Interrupt field. + + *** Backup Data Registers and Device Secrets configuration *** + =========================================== + [..] + (+) To write to the RTC Backup Data registers, use the HAL_RTCEx_BKUPWrite() + function. + (+) To read the RTC Backup registers, use the HAL_RTCEx_BKUPRead() + function. + (+) To reset the RTC Backup registers and erase the device secrets, + use HAL_RTCEx_BKUPErase() function. + (+) Enable the lock of the Boot hardware Key using the HAL_RTCEx_LockBootHardwareKey() + function. + The backup registers from TAMP_BKP0R to TAMP_BKP7R cannot be accessed neither in + read nor in write (they are read as 0 and write ignore). + (+) Configure the erase of the Device Secrets using HAL_RTCEx_ConfigEraseDeviceSecrets() + function. + (+) Block the access to the RTC Backup registers and all the device secrets + using HAL_RTCEx_BKUPBlock() function. + + *** Monotonic counter *** + ================================================ + [..] + (+) To increment the Monotonic counter, use the HAL_RTCEx_MonotonicCounterIncrement() + function. + (+) To get the current value of the Monotonic counter, use the HAL_RTCEx_MonotonicCounterGet() + function. + + *** RTC & TAMP privilege protection modes *** + ================================================ + [..] + (+) Set the privilege level of the RTC/TAMP/Backup registers using HAL_RTCEx_PrivilegeModeSet() + function. + +) Get the privilege level of the RTC/TAMP/Backup registers using HAL_RTCEx_PrivilegeModeGet() + function. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @addtogroup RTCEx + * @brief RTC Extended HAL module driver + * @{ + */ + +#ifdef HAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TAMP_ALL RTC_TAMPER_ALL + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup RTCEx_Exported_Functions + * @{ + */ + + +/** @addtogroup RTCEx_Exported_Functions_Group1 + * @brief RTC TimeStamp and Tamper functions + * +@verbatim + =============================================================================== + ##### RTC TimeStamp and Tamper functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure TimeStamp feature + +@endverbatim + * @{ + */ + +#ifdef RTC_CR_TSE +/** + * @brief Set 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 values: + * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the + * rising edge of the related pin. + * @arg RTC_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_DEFAULT: PC13 is selected as RTC TimeStamp Pin. + * The RTC TimeStamp Pin is per default PC13, but for reasons of + * compatibility, this parameter is required. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + /* Check the parameters */ +#if defined(RTC_CR_TSEDGE) + assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); +#endif /* RTC_CR_TSEDGE */ + assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + UNUSED(RTC_TimeStampPin); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Get the RTC_CR register and clear the bits to be configured */ +#if defined(RTC_CR_TSEDGE) + CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE)); +#else + CLEAR_BIT(RTC->CR, RTC_CR_TSE); +#endif /* RTC_CR_TSEDGE */ + + /* Configure the Time Stamp TSEDGE and Enable bits */ + SET_BIT(RTC->CR, (uint32_t)TimeStampEdge | RTC_CR_TSE); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Set TimeStamp with Interrupt. + * @note This API must be called before enabling the TimeStamp feature. + * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. + * @param hrtc RTC handle + * @param TimeStampEdge Specifies the pin edge on which the TimeStamp is + * activated. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the + * rising edge of the related pin. + * @arg RTC_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_DEFAULT: PC13 is selected as RTC TimeStamp Pin. + * The RTC TimeStamp Pin is per default PC13, but for reasons of + * compatibility, this parameter is required. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + /* Check the parameters */ +#if defined(RTC_CR_TSEDGE) + assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); +#endif /* RTC_CR_TSEDGE */ + assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + UNUSED(RTC_TimeStampPin); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Get the RTC_CR register and clear the bits to be configured */ +#if defined(RTC_CR_TSEDGE) + CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE)); +#else + CLEAR_BIT(RTC->CR, (RTC_CR_TSE | RTC_CR_TSIE)); +#endif /* RTC_CR_TSEDGE */ + + /* Configure the Time Stamp TSEDGE before Enable bit to avoid unwanted TSF setting. */ + SET_BIT(RTC->CR, (uint32_t)TimeStampEdge); + + /* Enable timestamp and IT */ + SET_BIT(RTC->CR, RTC_CR_TSE | RTC_CR_TSIE); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivate TimeStamp. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* In case of interrupt mode is used, the interrupt source must disabled */ +#if defined(RTC_CR_TSEDGE) + CLEAR_BIT(RTC->CR, (RTC_CR_TSEDGE | RTC_CR_TSE | RTC_CR_TSIE)); +#else + CLEAR_BIT(RTC->CR, (RTC_CR_TSE | RTC_CR_TSIE)); +#endif /* RTC_CR_TSEDGE */ + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} +#endif /* RTC_CR_TSE */ + +/** + * @brief Set Internal TimeStamp. + * @note This API must be called before enabling the internal TimeStamp feature. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetInternalTimeStamp(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Configure the internal Time Stamp Enable bits */ + SET_BIT(RTC->CR, RTC_CR_ITSE); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivate Internal TimeStamp. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTimeStamp(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Configure the internal Time Stamp Enable bits */ + CLEAR_BIT(RTC->CR, RTC_CR_ITSE); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Get 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 RTC_FORMAT_BIN: Binary data format + * @arg RTC_FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(const RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, + RTC_DateTypeDef *sTimeStampDate, uint32_t Format) +{ + uint32_t tmptime; + uint32_t tmpdate; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get the TimeStamp time and date registers values */ + tmptime = READ_BIT(RTC->TSTR, RTC_TR_RESERVED_MASK); + tmpdate = READ_BIT(RTC->TSDR, RTC_DR_RESERVED_MASK); + + /* Fill the Time structure fields with the read parameters */ + sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TSTR_HT | RTC_TSTR_HU)) >> RTC_TSTR_HU_Pos); + sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TSTR_MNT | RTC_TSTR_MNU)) >> RTC_TSTR_MNU_Pos); + sTimeStamp->Seconds = (uint8_t)((tmptime & (RTC_TSTR_ST | RTC_TSTR_SU)) >> RTC_TSTR_SU_Pos); + sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TSTR_PM)) >> RTC_TSTR_PM_Pos); + sTimeStamp->SubSeconds = READ_BIT(RTC->TSSSR, RTC_TSSSR_SS); + + /* Fill the Date structure fields with the read parameters */ + sTimeStampDate->Year = 0U; + sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_TSDR_MT | RTC_TSDR_MU)) >> RTC_TSDR_MU_Pos); + sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_TSDR_DT | RTC_TSDR_DU)); + sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_TSDR_WDU)) >> RTC_TSDR_WDU_Pos); + + /* Check the input parameters format */ + if (Format == RTC_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); + } + + /* Check if TIMESTAMP flag is set */ + if (READ_BIT(RTC->SR, RTC_SR_TSF) != 0U) + { + /* Clear the TIMESTAMP Flags */ + WRITE_REG(RTC->SCR, (RTC_SCR_CITSF | RTC_SCR_CTSF)); + + /* Check if TIMESTAMP OverRun flag is set */ + if (READ_BIT(RTC->SR, RTC_SR_TSOVF) != 0U) + { + /* Clear the TIMESTAMP OverRun Flag */ + WRITE_REG(RTC->SCR, RTC_SCR_CTSOVF); + + return HAL_ERROR; + } + } + + return HAL_OK; +} + +/** + * @brief Handle TimeStamp interrupt request. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_TimeStampIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the pending status of the TimeStamp Interrupt */ + if (READ_BIT(RTC->MISR, RTC_MISR_TSMF) != 0U) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call TimeStampEvent registered Callback */ + hrtc->TimeStampEventCallback(hrtc); +#else + HAL_RTCEx_TimeStampEventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + + /* Clearing flags after the Callback because the content of RTC_TSTR and RTC_TSDR are cleared when + TSF bit is reset.*/ + WRITE_REG(RTC->SCR, RTC_SCR_CITSF | RTC_SCR_CTSF); + } + + /* 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_TimeStampEventCallback could be implemented in the user file + */ +} + +/** + * @brief Handle TimeStamp polling request. + * @param hrtc RTC handle + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + uint32_t tickstart = HAL_GetTick(); + + while (READ_BIT(RTC->SR, RTC_SR_TSF) == 0U) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->SR, RTC_SR_TSF) == 0U) + { + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group2 + * @brief RTC Wake-up functions + * +@verbatim + =============================================================================== + ##### RTC Wake-up functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Wake-up feature + +@endverbatim + * @{ + */ + +/** + * @brief Set 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 tickstart; + + /* Check the parameters */ + assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); + assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Clear WUTE in RTC_CR to disable the wakeup timer */ + CLEAR_BIT(RTC->CR, RTC_CR_WUTE); + + /* Poll WUTWF until it is set in RTC_ICSR to make sure the access to wakeup autoreload + counter and to WUCKSEL[2:0] bits is allowed. This step must be skipped in + calendar initialization mode. */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) + { + tickstart = HAL_GetTick(); + + while (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Configure the clock source */ + MODIFY_REG(RTC->CR, RTC_CR_WUCKSEL, (uint32_t)WakeUpClock); + + /* Configure the Wakeup Timer counter */ + WRITE_REG(RTC->WUTR, (uint32_t)WakeUpCounter); + + /* Enable the Wakeup Timer */ + SET_BIT(RTC->CR, RTC_CR_WUTE); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Set wake up timer with interrupt. + * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. + * @param hrtc RTC handle + * @param WakeUpCounter Wake up counter + * @param WakeUpClock Wake up clock + * @param WakeUpAutoClr Wake up auto clear value (look at WUTOCLR in reference manual) + * - No effect if WakeUpAutoClr is set to zero + * - This feature is meaningful in case of Low power mode to avoid any RTC software execution + * after Wake Up. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock, + uint32_t WakeUpAutoClr) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); + assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); + /* (0x0000<=WUTOCLR<=WUT) */ + assert_param(WakeUpAutoClr <= WakeUpCounter); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Clear WUTE in RTC_CR to disable the wakeup timer */ + CLEAR_BIT(RTC->CR, RTC_CR_WUTE); + + /* Clear flag Wake-Up */ + WRITE_REG(RTC->SCR, RTC_SCR_CWUTF); + + /* Poll WUTWF until it is set in RTC_ICSR to make sure the access to wakeup autoreload + counter and to WUCKSEL[2:0] bits is allowed. This step must be skipped in + calendar initialization mode. */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_INITF) == 0U) + { + tickstart = HAL_GetTick(); + while (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_WUTWF) == 0U) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Configure the Wakeup Timer counter and auto clear value */ + WRITE_REG(RTC->WUTR, (uint32_t)(WakeUpCounter | (WakeUpAutoClr << RTC_WUTR_WUTOCLR_Pos))); + + /* Configure the clock source */ + MODIFY_REG(RTC->CR, RTC_CR_WUCKSEL, (uint32_t)WakeUpClock); + + /* Configure the Interrupt in the RTC_CR register and Enable the Wakeup Timer*/ + SET_BIT(RTC->CR, (RTC_CR_WUTIE | RTC_CR_WUTE)); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivate wake up timer counter. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the Wakeup Timer */ + /* In case of interrupt mode is used, the interrupt source must disabled */ + CLEAR_BIT(RTC->CR, (RTC_CR_WUTE | RTC_CR_WUTIE)); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Get wake up timer counter. + * @param hrtc RTC handle + * @retval Counter value + */ +uint32_t HAL_RTCEx_GetWakeUpTimer(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Get the counter value */ + return (uint32_t)(READ_BIT(RTC->WUTR, RTC_WUTR_WUT)); +} + +/** + * @brief Handle Wake Up Timer interrupt request. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the pending status of the Wake-Up Timer Interrupt */ + if (READ_BIT(RTC->MISR, RTC_MISR_WUTMF) != 0U) + { + /* Immediately clear flags */ + WRITE_REG(RTC->SCR, RTC_SCR_CWUTF); +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call wake up timer registered Callback */ + hrtc->WakeUpTimerEventCallback(hrtc); +#else + HAL_RTCEx_WakeUpTimerEventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_WakeUpTimerEventCallback could be implemented in the user file + */ +} + +/** + * @brief Handle Wake Up Timer Polling. + * @param hrtc RTC handle + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + uint32_t tickstart = HAL_GetTick(); + + while (READ_BIT(RTC->SR, RTC_SR_WUTF) == 0U) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->SR, RTC_SR_WUTF) == 0U) + { + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Clear the WAKEUPTIMER Flag */ + WRITE_REG(RTC->SCR, RTC_SCR_CWUTF); + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group3 + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Extended Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Write a data in a specified RTC Backup data register + (+) Read a data in a specified RTC Backup data register + (+) Set the Coarse calibration parameters. + (+) Deactivate the Coarse calibration parameters + (+) Set the Smooth calibration parameters. + (+) Set Low Power calibration parameter. + (+) Configure the Synchronization Shift Control Settings. + (+) Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + (+) Deactivate the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + (+) Enable the RTC reference clock detection. + (+) Disable the RTC reference clock detection. + (+) Enable the Bypass Shadow feature. + (+) Disable the Bypass Shadow feature. + +@endverbatim + * @{ + */ + +/** + * @brief Set the Smooth calibration parameters. + * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses + * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field + * SmoothCalibMinusPulsesValue must be equal to 0. + * @param hrtc RTC handle + * @param SmoothCalibPeriod Select the Smooth Calibration Period. + * This parameter can be one of the following values : + * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration period is 32s. + * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration period is 16s. + * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibration period 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 pulse every 2*11 pulses. + * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added. + * @param SmoothCalibMinusPulsesValue Select the value of CALM[8:0] bits. + * This parameter can be one any value from 0 to 0x000001FF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, + uint32_t SmoothCalibPlusPulses, uint32_t SmoothCalibMinusPulsesValue) +{ + uint32_t tickstart; + + /* 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(SmoothCalibMinusPulsesValue)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + tickstart = HAL_GetTick(); + + /* check if a calibration is pending */ + while (READ_BIT(RTC->ICSR, RTC_ICSR_RECALPF) != 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_RECALPF) != 0U) + { + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Smooth calibration settings */ + MODIFY_REG(RTC->CALR, (RTC_CALR_CALP | RTC_CALR_CALW8 | RTC_CALR_CALW16 | RTC_CALR_CALM), + (uint32_t)(SmoothCalibPeriod | SmoothCalibPlusPulses | SmoothCalibMinusPulsesValue)); + + /* 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 Select the low power Calibration mode. + * @param hrtc: RTC handle + * @param LowPowerCalib: Low power Calibration mode. + * This parameter can be one of the following values : + * @arg RTC_LPCAL_SET: Low power mode. + * @arg RTC_LPCAL_RESET: High consumption mode. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetLowPowerCalib(RTC_HandleTypeDef *hrtc, uint32_t LowPowerCalib) +{ + /* Check the parameters */ + assert_param(IS_RTC_LOW_POWER_CALIB(LowPowerCalib)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Smooth calibration settings */ + MODIFY_REG(RTC->CALR, RTC_CALR_LPCAL, LowPowerCalib); + + /* 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 Configure 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 tickstart; + + /* Check the parameters */ + assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S)); + assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + tickstart = HAL_GetTick(); + + /* Wait until the shift is completed */ + while (READ_BIT(RTC->ICSR, RTC_ICSR_SHPF) != 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->ICSR, RTC_ICSR_SHPF) != 0U) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + +#if defined(RTC_CR_REFCKON) + /* Check if the reference clock detection is disabled */ + if (READ_BIT(RTC->CR, RTC_CR_REFCKON) == 0U) + { +#endif /* RTC_CR_REFCKON */ + /* Configure the Shift settings */ + MODIFY_REG(RTC->SHIFTR, RTC_SHIFTR_SUBFS, (uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S)); + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if (READ_BIT(RTC->CR, RTC_CR_BYPSHAD) == 0U) + { + if (HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* 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; + } + } +#if defined(RTC_CR_REFCKON) + } + 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; + } +#endif /* RTC_CR_REFCKON */ + + /* 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; +} + +#if defined(RTC_CR_COSEL) +/** + * @brief Configure 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); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Configure the RTC_CR register */ + MODIFY_REG(RTC->CR, RTC_CR_COSEL, CalibOutput); + + /* Enable calibration output */ + SET_BIT(RTC->CR, RTC_CR_COE); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivate 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); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable calibration output */ + CLEAR_BIT(RTC->CR, RTC_CR_COE); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} +#endif /* RTC_CR_COSEL */ + +#if defined(RTC_CR_REFCKON) +/** + * @brief Enable the RTC reference clock detection. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc) +{ + HAL_StatusTypeDef status; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + if (status == HAL_OK) + { + /* Enable clockref detection */ + SET_BIT(RTC->CR, RTC_CR_REFCKON); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + if (status == HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return status; +} + +/** + * @brief Disable the RTC reference clock detection. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc) +{ + HAL_StatusTypeDef status; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Enter Initialization mode */ + status = RTC_EnterInitMode(hrtc); + if (status == HAL_OK) + { + /* Disable clockref detection */ + CLEAR_BIT(RTC->CR, RTC_CR_REFCKON); + + /* Exit Initialization mode */ + status = RTC_ExitInitMode(hrtc); + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + if (status == HAL_OK) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return status; +} +#endif /* RTC_CR_REFCKON */ + +/** + * @brief Enable the Bypass Shadow feature. + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Set the BYPSHAD bit */ + SET_BIT(RTC->CR, RTC_CR_BYPSHAD); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Disable the Bypass Shadow feature. + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Reset the BYPSHAD bit */ + CLEAR_BIT(RTC->CR, RTC_CR_BYPSHAD); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Increment Monotonic counter. + * @param hrtc RTC handle + * @param Instance Monotonic counter Instance + * This parameter can be one of the following values : + * @arg RTC_MONOTONIC_COUNTER_1 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_MonotonicCounterIncrement(const RTC_HandleTypeDef *hrtc, uint32_t Instance) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + UNUSED(Instance); + + /* This register is read-only only and is incremented by one when a write access is done to this + register. This register cannot roll-over and is frozen when reaching the maximum value. */ + CLEAR_REG(TAMP->COUNT1R); + + return HAL_OK; +} + +/** + * @brief Monotonic counter. + * @param hrtc RTC handle + * @param Instance Monotonic counter Instance + * This parameter can be one of the following values : + * @arg RTC_MONOTONIC_COUNTER_1 + * @param pValue Pointer to the counter monotonic counter value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_MonotonicCounterGet(const RTC_HandleTypeDef *hrtc, uint32_t Instance, uint32_t *pValue) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + UNUSED(Instance); + + /* This register is read-only only and is incremented by one when a write access is done to this + register. This register cannot roll-over and is frozen when reaching the maximum value. */ + *pValue = READ_REG(TAMP->COUNT1R); + + return HAL_OK; +} + +/** + * @brief Set SSR Underflow detection with Interrupt. + * @note The application must ensure that the EXTI RTC interrupt line is configured and enabled. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetSSRU_IT(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Enable IT SSRU */ + __HAL_RTC_SSRU_ENABLE_IT(hrtc, RTC_IT_SSRU); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivate SSR Underflow. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateSSRU(RTC_HandleTypeDef *hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_SSRU_DISABLE_IT(hrtc, RTC_IT_SSRU); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Handle SSR underflow interrupt request. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_SSRUIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the pending status of the SSR Underflow Interrupt */ + if (READ_BIT(RTC->MISR, RTC_MISR_SSRUMF) != 0U) + { + /* Immediately clear SSR underflow flag */ + WRITE_REG(RTC->SCR, RTC_SCR_CSSRUF); + + /* SSRU callback */ +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call SSRUEvent registered Callback */ + hrtc->SSRUEventCallback(hrtc); +#else + HAL_RTCEx_SSRUEventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + + } + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief SSR underflow callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_SSRUEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_SSRUEventCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group4 + * @brief Extended features functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) RTC Alarm 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_AlarmBEventCallback could be implemented in the user file + */ +} + +/** + * @brief Handle Alarm B Polling request. + * @param hrtc RTC handle + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(const RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + uint32_t tickstart = HAL_GetTick(); + + while (READ_BIT(RTC->SR, RTC_SR_ALRBF) == 0U) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(RTC->SR, RTC_SR_ALRBF) == 0U) + { + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Clear the Alarm Flag */ + WRITE_REG(RTC->SCR, RTC_SCR_CALRBF); + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup RTCEx_Exported_Functions_Group5 + * @brief Extended RTC Tamper functions + * +@verbatim + ============================================================================== + ##### Tamper functions ##### + ============================================================================== + [..] + (+) Before calling any tamper or internal tamper function, you have to call first + HAL_RTC_Init() function. + (+) In that one you can select to output tamper event on RTC pin. + [..] + (+) Enable the 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, NoErase, MaskFlag, precharge or discharge and + Pull-UP, timestamp using the HAL_RTCEx_SetTamper() function. + You can configure Tamper with interrupt mode using HAL_RTCEx_SetTamper_IT() function. + (+) The default configuration of the Tamper erases the backup registers. To avoid + erase, enable the NoErase field on the TAMP_TAMPCR register. + [..] + (+) Enable Internal Tamper and configure it with interrupt, timestamp using + the HAL_RTCEx_SetInternalTamper() function. + +@endverbatim + * @{ + */ + + +/** + * @brief Set Tamper + * @param hrtc RTC handle + * @param sTamper Pointer to Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTamper(const RTC_HandleTypeDef *hrtc, const RTC_TamperTypeDef *sTamper) +{ + uint32_t tmpreg; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_TAMPER(sTamper->Tamper)); + assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); + assert_param(IS_RTC_TAMPER_ERASE_MODE(sTamper->NoErase)); + assert_param(IS_RTC_TAMPER_MASKFLAG_STATE(sTamper->MaskFlag)); + assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); +#if (RTC_TAMP_NB > 2U) + /* Mask flag only supported by TAMPER 1, 2 and 3 */ + assert_param(!((sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) && (sTamper->Tamper > RTC_TAMPER_3))); +#else + assert_param(!((sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) && (sTamper->Tamper > RTC_TAMPER_2))); +#endif /* (RTC_TAMP_NB > 2U) */ + assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter)); + assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + /* Trigger and Filter have exclusive configurations */ + assert_param(((sTamper->Filter != RTC_TAMPERFILTER_DISABLE) && + ((sTamper->Trigger == RTC_TAMPERTRIGGER_LOWLEVEL) || + (sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL))) || + ((sTamper->Filter == RTC_TAMPERFILTER_DISABLE) && + ((sTamper->Trigger == RTC_TAMPERTRIGGER_RISINGEDGE) || + (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)))); + + /* Configuration register 2 */ + tmpreg = READ_REG(TAMP->CR2); + tmpreg &= ~((sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos) | (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos) | + (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos)); + + if ((sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL) || (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)) + { + tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos); + } + + if (sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) + { + tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos); + } + + if (sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) + { + tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos); + } + WRITE_REG(TAMP->CR2, tmpreg); + + /* Filter control register */ + WRITE_REG(TAMP->FLTCR, sTamper->Filter | sTamper->SamplingFrequency | sTamper->PrechargeDuration | + sTamper->TamperPullUp); + + /* Timestamp on tamper */ + if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sTamper->TimeStampOnTamperDetection) + { + MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection); + } + + /* Control register 1 */ + SET_BIT(TAMP->CR1, sTamper->Tamper); + + return HAL_OK; +} + + +/** + * @brief Set Tamper in IT mode + * @note The application must ensure that the EXTI TAMP interrupt line is configured and enabled. + * @param hrtc RTC handle + * @param sTamper Pointer to Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(const RTC_HandleTypeDef *hrtc, const RTC_TamperTypeDef *sTamper) +{ + uint32_t tmpreg; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_TAMPER(sTamper->Tamper)); + assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); + assert_param(IS_RTC_TAMPER_ERASE_MODE(sTamper->NoErase)); + assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + /* The interrupt must not be enabled when TAMPxMSK is set. */ + assert_param(sTamper->MaskFlag == RTC_TAMPERMASK_FLAG_DISABLE); + assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter)); + assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + /* Trigger and Filter have exclusive configurations */ + assert_param(((sTamper->Filter != RTC_TAMPERFILTER_DISABLE) && + ((sTamper->Trigger == RTC_TAMPERTRIGGER_LOWLEVEL) || + (sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL))) || + ((sTamper->Filter == RTC_TAMPERFILTER_DISABLE) && + ((sTamper->Trigger == RTC_TAMPERTRIGGER_RISINGEDGE) || + (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)))); + + /* Configuration register 2 */ + tmpreg = READ_REG(TAMP->CR2); + tmpreg &= ~((sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos) | (sTamper->Tamper << TAMP_CR2_TAMP1MSK_Pos) | + (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos)); + + if ((sTamper->Trigger == RTC_TAMPERTRIGGER_HIGHLEVEL) || (sTamper->Trigger == RTC_TAMPERTRIGGER_FALLINGEDGE)) + { + tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1TRG_Pos); + } + + if (sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) + { + tmpreg |= (sTamper->Tamper << TAMP_CR2_TAMP1POM_Pos); + } + WRITE_REG(TAMP->CR2, tmpreg); + + /* Filter control register */ + WRITE_REG(TAMP->FLTCR, sTamper->Filter | sTamper->SamplingFrequency | sTamper->PrechargeDuration | + sTamper->TamperPullUp); + + /* Timestamp on tamper */ + if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sTamper->TimeStampOnTamperDetection) + { + MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sTamper->TimeStampOnTamperDetection); + } + + /* Interrupt enable register */ + SET_BIT(TAMP->IER, sTamper->Tamper); + + /* Control register 1 */ + SET_BIT(TAMP->CR1, sTamper->Tamper); + + return HAL_OK; +} + +/** + * @brief Deactivate Tamper. + * @param hrtc RTC handle + * @param Tamper Selected tamper pin. + * This parameter can be a combination of the following values: + * @arg RTC_TAMPER_1 + * @arg RTC_TAMPER_2 + * @arg RTC_TAMPER_3 + * @arg RTC_TAMPER_4 + * @arg RTC_TAMPER_5 + * @arg RTC_TAMPER_6 + * @arg RTC_TAMPER_7 + * @arg RTC_TAMPER_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(const RTC_HandleTypeDef *hrtc, uint32_t Tamper) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + assert_param(IS_RTC_TAMPER(Tamper)); + + /* Disable the selected Tamper pin */ + CLEAR_BIT(TAMP->CR1, Tamper); + + /* Clear tamper interrupt and event flags (WO register) */ + WRITE_REG(TAMP->SCR, Tamper); + + /* Clear tamper mask/noerase/trigger configuration */ + CLEAR_BIT(TAMP->CR2, (Tamper << TAMP_CR2_TAMP1TRG_Pos) | (Tamper << TAMP_CR2_TAMP1MSK_Pos) | \ + (Tamper << TAMP_CR2_TAMP1POM_Pos)); + + /* Clear tamper interrupt mode configuration */ + CLEAR_BIT(TAMP->IER, Tamper); + + return HAL_OK; +} + +/** + * @brief Set all active Tampers at the same time. + * @note For interrupt mode, the application must ensure that the EXTI RTC interrupt line is configured and enabled. + * @param hrtc RTC handle + * @param sAllTamper Pointer to active Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetActiveTampers(RTC_HandleTypeDef *hrtc, const RTC_ActiveTampersTypeDef *sAllTamper) +{ + uint32_t tmp_ier; + uint32_t tmp_cr1; + uint32_t tmp_cr2; + uint32_t tmp_atcr1; + uint32_t tmp_atcr2; + uint32_t tmp_cr; + uint32_t i; + uint32_t tickstart; + +#ifdef USE_FULL_ASSERT + for (i = 0; i < RTC_TAMP_NB; i++) + { + assert_param(IS_RTC_TAMPER_ERASE_MODE(sAllTamper->TampInput[i].NoErase)); + assert_param(IS_RTC_TAMPER_MASKFLAG_STATE(sAllTamper->TampInput[i].MaskFlag)); + /* Mask flag only supported by TAMPER 1, 2 and 3 */ + assert_param(!((sAllTamper->TampInput[i].MaskFlag == RTC_TAMPERMASK_FLAG_ENABLE) && + (i >= RTC_TAMPER_MASKABLE_NB))); + } + assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sAllTamper->TimeStampOnTamperDetection)); + assert_param(IS_RTC_ATAMPER_FILTER(sAllTamper->ActiveFilter)); + assert_param(IS_RTC_ATAMPER_OUTPUT_CHANGE_PERIOD(sAllTamper->ActiveOutputChangePeriod)); + assert_param(IS_RTC_ATAMPER_ASYNCPRES_RTCCLK(sAllTamper->ActiveAsyncPrescaler)); +#endif /* USE_FULL_ASSERT */ + + /* Active Tampers must not be already enabled */ + if (READ_BIT(TAMP->ATOR, TAMP_ATOR_INITS) != 0U) + { + /* Disable all actives tampers with HAL_RTCEx_DeactivateActiveTampers. + No need to check return value because it returns always HAL_OK */ + (void) HAL_RTCEx_DeactivateActiveTampers(hrtc); + } + + /* Set TimeStamp on tamper detection */ + tmp_cr = READ_REG(RTC->CR); + if ((tmp_cr & RTC_CR_TAMPTS) != (sAllTamper->TimeStampOnTamperDetection)) + { + MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sAllTamper->TimeStampOnTamperDetection); + } + + tmp_cr1 = READ_REG(TAMP->CR1); + tmp_cr2 = READ_REG(TAMP->CR2); + tmp_atcr2 = 0U; + tmp_ier = READ_REG(TAMP->IER); + + /* Set common parameters */ + tmp_atcr1 = (sAllTamper->ActiveFilter | (sAllTamper->ActiveOutputChangePeriod << TAMP_ATCR1_ATPER_Pos) | + sAllTamper->ActiveAsyncPrescaler); + + /* Set specific parameters for each active tamper inputs if enable */ + for (i = 0; i < RTC_TAMP_NB; i++) + { + if (sAllTamper->TampInput[i].Enable != RTC_ATAMP_DISABLE) + { + tmp_cr1 |= (TAMP_CR1_TAMP1E << i); + tmp_atcr1 |= (TAMP_ATCR1_TAMP1AM << i); + + if (sAllTamper->TampInput[i].Interrupt != RTC_ATAMP_INTERRUPT_DISABLE) + { + /* Interrupt enable register */ + tmp_ier |= (TAMP_IER_TAMP1IE << i); + } + + if (sAllTamper->TampInput[i].MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) + { + tmp_cr2 |= (TAMP_CR2_TAMP1MSK << i); + } + + if (sAllTamper->TampInput[i].NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) + { + tmp_cr2 |= (TAMP_CR2_TAMP1POM << i); + } + + /* Configure ATOSELx[] in case of output sharing */ + tmp_atcr2 |= sAllTamper->TampInput[i].Output << ((3U * i) + TAMP_ATCR2_ATOSEL1_Pos); + + if (i != sAllTamper->TampInput[i].Output) + { + tmp_atcr1 |= TAMP_ATCR1_ATOSHARE; + } + } + } + + WRITE_REG(TAMP->IER, tmp_ier); + WRITE_REG(TAMP->ATCR1, tmp_atcr1); + WRITE_REG(TAMP->ATCR2, tmp_atcr2); + WRITE_REG(TAMP->CR2, tmp_cr2); + WRITE_REG(TAMP->CR1, tmp_cr1); + + /* Write seed */ + for (i = 0; i < RTC_ATAMP_SEED_NB_UINT32; i++) + { + WRITE_REG(TAMP->ATSEEDR, sAllTamper->Seed[i]); + } + + /* Wait till RTC SEEDF flag is cleared and if Time out is reached exit */ + tickstart = HAL_GetTick(); + while (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + + return HAL_OK; +} + +/** + * @brief Write a new seed. Active tamper must be enabled. + * @param hrtc RTC handle + * @param pSeed Pointer to active tamper seed values. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetActiveSeed(RTC_HandleTypeDef *hrtc, const uint32_t *pSeed) +{ + uint32_t i; + uint32_t tickstart; + + /* Active Tampers must be enabled */ + if (READ_BIT(TAMP->ATOR, TAMP_ATOR_INITS) == 0U) + { + return HAL_ERROR; + } + + for (i = 0; i < RTC_ATAMP_SEED_NB_UINT32; i++) + { + WRITE_REG(TAMP->ATSEEDR, pSeed[i]); + } + + /* Wait till RTC SEEDF flag is cleared and if Time out is reached exit */ + tickstart = HAL_GetTick(); + while (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) + { + if ((HAL_GetTick() - tickstart) > RTC_TIMEOUT_VALUE) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(TAMP->ATOR, TAMP_ATOR_SEEDF) != 0U) + { + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + + return HAL_OK; +} + +#if defined(TAMP_CFGR_BHKLOCK) +/** + * @brief Lock the Boot hardware Key + * @param hrtc RTC handle + * @note The backup registers from TAMP_BKP0R to TAMP_BKP7R cannot be accessed neither in + * read nor in write (they are read as 0 and write ignore). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_LockBootHardwareKey(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + WRITE_REG(TAMP->CFGR, TAMP_CFGR_BHKLOCK); + + return HAL_OK; +} +#endif /* TAMP_CFGR_BHKLOCK */ + +/** + * @brief Deactivate all Active Tampers at the same time. + * @param hrtc RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateActiveTampers(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Get Active tampers */ + uint32_t atamp_mask = READ_BIT(TAMP->ATCR1, TAMP_ALL); + + /* Disable all actives tampers but not passives tampers */ + CLEAR_BIT(TAMP->CR1, atamp_mask); + + /* Clear tamper interrupt and event flags (WO register) of all actives tampers but not passives tampers */ + WRITE_REG(TAMP->SCR, atamp_mask); + + /* Disable no erase and mask */ + CLEAR_BIT(TAMP->CR2, (atamp_mask | ((atamp_mask & (TAMP_ATCR1_TAMP1AM | TAMP_ATCR1_TAMP2AM | TAMP_ATCR1_TAMP3AM)) << + TAMP_CR2_TAMP1MSK_Pos))); + + /* Clear all active tampers interrupt mode configuration but not passives tampers */ + CLEAR_BIT(TAMP->IER, atamp_mask); + + /* Set reset value for active tamper control register 1 */ + WRITE_REG(TAMP->ATCR1, TAMP_ATCR1_ATCKSEL_0 | TAMP_ATCR1_ATCKSEL_1 | TAMP_ATCR1_ATCKSEL_2); + + /* Set reset value for active tamper control register 2 */ + CLEAR_REG(TAMP->ATCR2); + + return HAL_OK; +} + +/** + * @brief Tamper event polling. + * @param hrtc RTC handle + * @param Tamper Selected tamper pin. + * This parameter can be a combination of the following values: + * @arg RTC_TAMPER_1 + * @arg RTC_TAMPER_2 + * @arg RTC_TAMPER_3 + * @arg RTC_TAMPER_4 + * @arg RTC_TAMPER_5 + * @arg RTC_TAMPER_6 + * @arg RTC_TAMPER_7 + * @arg RTC_TAMPER_8 + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTamperEvent(const RTC_HandleTypeDef *hrtc, uint32_t Tamper, uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + assert_param(IS_RTC_TAMPER(Tamper)); + + uint32_t tickstart = HAL_GetTick(); + + /* Get the status of the Interrupt */ + while (READ_BIT(TAMP->SR, Tamper) != Tamper) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(TAMP->SR, Tamper) != Tamper) + { + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Clear the Tamper Flag */ + WRITE_REG(TAMP->SCR, Tamper); + + return HAL_OK; +} + + +/** + * @brief Set Internal Tamper + * @param hrtc RTC handle + * @param sIntTamper Pointer to Internal Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetInternalTamper(const RTC_HandleTypeDef *hrtc, + const RTC_InternalTamperTypeDef *sIntTamper) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_INTERNAL_TAMPER(sIntTamper->IntTamper)); + assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sIntTamper->TimeStampOnTamperDetection)); + assert_param(IS_RTC_TAMPER_ERASE_MODE(sIntTamper->NoErase)); + + /* Timestamp enable on internal tamper */ + if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection) + { + MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection); + } + + /* No Erase Backup register enable for Internal Tamper */ + if (sIntTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) + { + SET_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); + } + else + { + CLEAR_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); + } + + /* Enable Internal Tamper */ + SET_BIT(TAMP->CR1, sIntTamper->IntTamper); + + return HAL_OK; +} + + +/** + * @brief Set Internal Tamper in interrupt mode + * @note The application must ensure that the EXTI RTC tamper interrupt line is configured and enabled. + * @param hrtc RTC handle + * @param sIntTamper Pointer to Internal Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetInternalTamper_IT(const RTC_HandleTypeDef *hrtc, + const RTC_InternalTamperTypeDef *sIntTamper) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_INTERNAL_TAMPER(sIntTamper->IntTamper)); + assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sIntTamper->TimeStampOnTamperDetection)); + assert_param(IS_RTC_TAMPER_ERASE_MODE(sIntTamper->NoErase)); + + /* Timestamp enable on internal tamper */ + if (READ_BIT(RTC->CR, RTC_CR_TAMPTS) != sIntTamper->TimeStampOnTamperDetection) + { + MODIFY_REG(RTC->CR, RTC_CR_TAMPTS, sIntTamper->TimeStampOnTamperDetection); + } + + /* Interrupt enable register */ + SET_BIT(TAMP->IER, sIntTamper->IntTamper); + + /* No Erase Backup register enable for Internal Tamper */ + if (sIntTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) + { + SET_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); + } + else + { + CLEAR_BIT(TAMP->CR3, (sIntTamper->IntTamper >> (TAMP_CR1_ITAMP1E_Pos - TAMP_CR3_ITAMP1POM_Pos))); + } + + /* Enable Internal Tamper */ + SET_BIT(TAMP->CR1, sIntTamper->IntTamper); + + return HAL_OK; +} + +/** + * @brief Deactivate Internal Tamper. + * @param hrtc RTC handle + * @param IntTamper Selected internal tamper event. + * This parameter can be any combination of existing internal tampers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTamper(const RTC_HandleTypeDef *hrtc, uint32_t IntTamper) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + assert_param(IS_RTC_INTERNAL_TAMPER(IntTamper)); + + /* Disable the selected Tamper pin */ + CLEAR_BIT(TAMP->CR1, IntTamper); + + /* Clear internal tamper interrupt mode configuration */ + CLEAR_BIT(TAMP->IER, IntTamper); + + /* Clear internal tamper interrupt */ + WRITE_REG(TAMP->SCR, IntTamper); + + return HAL_OK; +} + +/** + * @brief Internal Tamper event polling. + * @param hrtc RTC handle + * @param IntTamper selected tamper. + * This parameter can be any combination of existing internal tampers. + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForInternalTamperEvent(const RTC_HandleTypeDef *hrtc, uint32_t IntTamper, + uint32_t Timeout) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + assert_param(IS_RTC_INTERNAL_TAMPER(IntTamper)); + + uint32_t tickstart = HAL_GetTick(); + + /* Get the status of the Interrupt */ + while (READ_BIT(TAMP->SR, IntTamper) != IntTamper) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(TAMP->SR, IntTamper) != IntTamper) + { + return HAL_TIMEOUT; + } + else + { + break; + } + } + } + } + + /* Clear the Tamper Flag */ + WRITE_REG(TAMP->SCR, IntTamper); + + return HAL_OK; +} + +/** + * @brief Handle Tamper interrupt request. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_TamperIRQHandler(RTC_HandleTypeDef *hrtc) +{ + /* Get the pending status of the Tampers Interrupt */ + uint32_t tmp = READ_REG(TAMP->MISR); + + /* Check Tamper1 status */ + if ((tmp & RTC_TAMPER_1) == RTC_TAMPER_1) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 1 Event registered Callback */ + hrtc->Tamper1EventCallback(hrtc); +#else + /* Tamper1 callback */ + HAL_RTCEx_Tamper1EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Tamper2 status */ + if ((tmp & RTC_TAMPER_2) == RTC_TAMPER_2) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 2 Event registered Callback */ + hrtc->Tamper2EventCallback(hrtc); +#else + /* Tamper2 callback */ + HAL_RTCEx_Tamper2EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + +#if (RTC_TAMP_NB > 2U) + + /* Check Tamper3 status */ + if ((tmp & RTC_TAMPER_3) == RTC_TAMPER_3) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 3 Event registered Callback */ + hrtc->Tamper3EventCallback(hrtc); +#else + /* Tamper3 callback */ + HAL_RTCEx_Tamper3EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Tamper4 status */ + if ((tmp & RTC_TAMPER_4) == RTC_TAMPER_4) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 4 Event registered Callback */ + hrtc->Tamper4EventCallback(hrtc); +#else + /* Tamper4 callback */ + HAL_RTCEx_Tamper4EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Tamper5 status */ + if ((tmp & RTC_TAMPER_5) == RTC_TAMPER_5) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 5 Event registered Callback */ + hrtc->Tamper5EventCallback(hrtc); +#else + /* Tamper5 callback */ + HAL_RTCEx_Tamper5EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Tamper6 status */ + if ((tmp & RTC_TAMPER_6) == RTC_TAMPER_6) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 6 Event registered Callback */ + hrtc->Tamper6EventCallback(hrtc); +#else + /* Tamper6 callback */ + HAL_RTCEx_Tamper6EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + +#endif /* (RTC_TAMP_NB > 2U) */ +#if (RTC_TAMP_NB > 6U) + + /* Check Tamper7 status */ + if ((tmp & RTC_TAMPER_7) == RTC_TAMPER_7) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 7 Event registered Callback */ + hrtc->Tamper7EventCallback(hrtc); +#else + /* Tamper7 callback */ + HAL_RTCEx_Tamper7EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Tamper8 status */ + if ((tmp & RTC_TAMPER_8) == RTC_TAMPER_8) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Tamper 8 Event registered Callback */ + hrtc->Tamper8EventCallback(hrtc); +#else + /* Tamper8 callback */ + HAL_RTCEx_Tamper8EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + +#endif /* (RTC_TAMP_NB > 6U) */ + + /* Check Internal Tamper1 status */ + if ((tmp & RTC_INT_TAMPER_1) == RTC_INT_TAMPER_1) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 1 Event registered Callback */ + hrtc->InternalTamper1EventCallback(hrtc); +#else + /* Internal Tamper1 callback */ + HAL_RTCEx_InternalTamper1EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper2 status */ + if ((tmp & RTC_INT_TAMPER_2) == RTC_INT_TAMPER_2) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 2 Event registered Callback */ + hrtc->InternalTamper2EventCallback(hrtc); +#else + /* Internal Tamper2 callback */ + HAL_RTCEx_InternalTamper2EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper3 status */ + if ((tmp & RTC_INT_TAMPER_3) == RTC_INT_TAMPER_3) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 3 Event registered Callback */ + hrtc->InternalTamper3EventCallback(hrtc); +#else + /* Internal Tamper3 callback */ + HAL_RTCEx_InternalTamper3EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper4 status */ + if ((tmp & RTC_INT_TAMPER_4) == RTC_INT_TAMPER_4) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 4 Event registered Callback */ + hrtc->InternalTamper4EventCallback(hrtc); +#else + /* Internal Tamper4 callback */ + HAL_RTCEx_InternalTamper4EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper5 status */ + if ((tmp & RTC_INT_TAMPER_5) == RTC_INT_TAMPER_5) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 5 Event registered Callback */ + hrtc->InternalTamper5EventCallback(hrtc); +#else + /* Internal Tamper5 callback */ + HAL_RTCEx_InternalTamper5EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper6 status */ + if ((tmp & RTC_INT_TAMPER_6) == RTC_INT_TAMPER_6) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 6 Event registered Callback */ + hrtc->InternalTamper6EventCallback(hrtc); +#else + /* Internal Tamper6 callback */ + HAL_RTCEx_InternalTamper6EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper7 status */ + if ((tmp & RTC_INT_TAMPER_7) == RTC_INT_TAMPER_7) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 7 Event registered Callback */ + hrtc->InternalTamper7EventCallback(hrtc); +#else + /* Internal Tamper7 callback */ + HAL_RTCEx_InternalTamper7EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper8 status */ + if ((tmp & RTC_INT_TAMPER_8) == RTC_INT_TAMPER_8) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 8 Event registered Callback */ + hrtc->InternalTamper8EventCallback(hrtc); +#else + /* Internal Tamper8 callback */ + HAL_RTCEx_InternalTamper8EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper9 status */ + if ((tmp & RTC_INT_TAMPER_9) == RTC_INT_TAMPER_9) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 9 Event registered Callback */ + hrtc->InternalTamper9EventCallback(hrtc); +#else + /* Internal Tamper9 callback */ + HAL_RTCEx_InternalTamper9EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper11 status */ + if ((tmp & RTC_INT_TAMPER_11) == RTC_INT_TAMPER_11) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 11 Event registered Callback */ + hrtc->InternalTamper11EventCallback(hrtc); +#else + /* Internal Tamper11 callback */ + HAL_RTCEx_InternalTamper11EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Check Internal Tamper15 status */ + if ((tmp & RTC_INT_TAMPER_15) == RTC_INT_TAMPER_15) + { +#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1) + /* Call Internal Tamper 15 Event registered Callback */ + hrtc->InternalTamper15EventCallback(hrtc); +#else + /* Internal Tamper15 callback */ + HAL_RTCEx_InternalTamper15EventCallback(hrtc); +#endif /* USE_HAL_RTC_REGISTER_CALLBACKS */ + } + + /* Clear flags after treatment to allow the potential tamper feature */ + WRITE_REG(TAMP->SCR, tmp); +} + +/** + * @brief Tamper 1 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper2EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 3 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper3EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 4 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper4EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper4EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 5 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper5EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper5EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 6 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper6EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper6EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 7 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper7EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper7EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 8 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper8EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper8EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 1 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper1EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper1EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 2 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper2EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper2EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 3 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper3EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper3EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 4 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper4EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper4EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 5 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper5EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper5EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 6 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper6EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper6EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 7 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper7EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper7EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 8 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper8EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper8EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 9 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper9EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper9EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 11 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper11EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper11EventCallback could be implemented in the user file + */ +} + +/** + * @brief Internal Tamper 15 callback. + * @param hrtc RTC handle + * @retval None + */ +__weak void HAL_RTCEx_InternalTamper15EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_RTCEx_InternalTamper15EventCallback could be implemented in the user file + */ +} +/** + * @} + */ + + +/** @addtogroup RTCEx_Exported_Functions_Group6 + * @brief Extended RTC Backup register functions + * +@verbatim + =============================================================================== + ##### Extended RTC Backup register functions ##### + =============================================================================== + [..] + (+) Before calling any tamper or internal tamper function, you have to call first + HAL_RTC_Init() function. + (+) In that one you can select to output tamper event on RTC pin. + [..] + This subsection provides functions allowing to + (+) Write a data in a specified RTC Backup data register + (+) Read a data in a specified RTC Backup data register +@endverbatim + * @{ + */ + + +/** + * @brief Write 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 RTC_BACKUP_NB + * @param Data Data to be written in the specified Backup data register. + * @retval None + */ +void HAL_RTCEx_BKUPWrite(const RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) +{ + uint32_t tmp; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_BKP(BackupRegister)); + + /* Determine address of the specified Backup register */ + tmp = (uint32_t)(&(TAMP->BKP0R)); + tmp += (BackupRegister * 4U); + + /* Write data in the specified register Backup 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 RTC_BACKUP_NB + * @retval Read value + */ +uint32_t HAL_RTCEx_BKUPRead(const RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) +{ + uint32_t tmp; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Check the parameters */ + assert_param(IS_RTC_BKP(BackupRegister)); + + /* Determine address of the specified Backup register */ + tmp = (uint32_t)(&(TAMP->BKP0R)); + tmp += (BackupRegister * 4U); + + /* Read the data from the specified register */ + return (*(__IO uint32_t *)tmp); +} + +/** + * @brief Reset the RTC Backup data Registers and the device secrets. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_BKUPErase(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + SET_BIT(TAMP->CR2, TAMP_CR2_BKERASE); +} + +/** + * @brief Block the access to the RTC Backup data Register and all the device secrets. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_BKUPBlock(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + WRITE_REG(TAMP->CR2, TAMP_CR2_BKBLOCK); +} + +/** + * @brief Disable the Block to the access to the RTC Backup data Register and the device secrets. + * @param hrtc RTC handle + * @retval None + */ +void HAL_RTCEx_BKUPUnblock(const RTC_HandleTypeDef *hrtc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + CLEAR_BIT(TAMP->CR2, TAMP_CR2_BKBLOCK); +} + +#ifdef TAMP_RPCFGR_RPCFG0 +/** + * @brief Enable and Disable the erase of the configurable Device Secrets + * @note This API must be called before enabling the Tamper. + * @param hrtc RTC handle + * @param DeviceSecretConf Specifies the configuration of the Device Secrets + * This parameter can be a combination of the following values: + * @arg TAMP_DEVICESECRETS_ERASE_NONE + * @arg TAMP_DEVICESECRETS_ERASE_BKPSRAM + * + * @retval None + */ +void HAL_RTCEx_ConfigEraseDeviceSecrets(const RTC_HandleTypeDef *hrtc, uint32_t DeviceSecretConf) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + MODIFY_REG(TAMP->RPCFGR, TAMP_RPCFGR_RPCFG0, DeviceSecretConf); +} +#endif /* TAMP_RPCFGR_RPCFG0 */ + +/** + * @} + */ + +#if defined(TAMP_PRIVCFGR_TAMPPRIV) +/** @addtogroup RTCEx_Exported_Functions_Group8 + * @brief Extended RTC privilege functions + * +@verbatim + =============================================================================== + ##### Extended RTC privilege functions ##### + =============================================================================== + [..] + (+) Before calling privilege function, you have to call first + HAL_RTC_Init() function. +@endverbatim + * @{ + */ + +/** + * @brief Set the privilege level of the RTC/TAMP/Backup registers. + * To get the current privilege level call HAL_RTCEx_PrivilegeModeGet. + * @param hrtc RTC handle + * @param privilegeState Privilege state + * @retval HAL_StatusTypeDef + */ +HAL_StatusTypeDef HAL_RTCEx_PrivilegeModeSet(const RTC_HandleTypeDef *hrtc, + const RTC_PrivilegeStateTypeDef *privilegeState) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + assert_param(IS_RTC_PRIVILEGE_FULL(privilegeState->rtcPrivilegeFull)); + assert_param(IS_RTC_PRIVILEGE_FEATURES(privilegeState->rtcPrivilegeFeatures)); + assert_param(IS_TAMP_PRIVILEGE_FULL(privilegeState->tampPrivilegeFull)); + assert_param(IS_TAMP_MONOTONIC_CNT_PRIVILEGE(privilegeState->MonotonicCounterPrivilege)); + assert_param(IS_RTC_PRIVILEGE_BKUP_ZONE(privilegeState->backupRegisterPrivZone)); + assert_param(IS_RTC_BKP(privilegeState->backupRegisterStartZone2)); + assert_param(IS_RTC_BKP(privilegeState->backupRegisterStartZone3)); + + /* RTC privilege configuration */ + WRITE_REG(RTC->PRIVCFGR, privilegeState->rtcPrivilegeFull | privilegeState->rtcPrivilegeFeatures); + + /* TAMP, Monotonic counter and Backup registers privilege configuration */ + WRITE_REG(TAMP->PRIVCFGR, privilegeState->tampPrivilegeFull | privilegeState->backupRegisterPrivZone | \ + privilegeState->MonotonicCounterPrivilege); + + /* Backup register start zone */ + MODIFY_REG(TAMP->CFGR, + (TAMP_CFGR_BKPRW | TAMP_CFGR_BKPW), + ((privilegeState->backupRegisterStartZone2 << TAMP_CFGR_BKPRW_Pos) | (privilegeState->backupRegisterStartZone3 << TAMP_CFGR_BKPW_Pos))); + + return HAL_OK; +} + +/** + * @brief Get the privilege level of the RTC/TAMP/Backup registers. + * To set the privilege level please call HAL_RTCEx_PrivilegeModeSet. + * @param hrtc RTC handle + * @param privilegeState Privilege state + * @retval HAL_StatusTypeDef + */ +HAL_StatusTypeDef HAL_RTCEx_PrivilegeModeGet(const RTC_HandleTypeDef *hrtc, RTC_PrivilegeStateTypeDef *privilegeState) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrtc); + + /* Read registers */ + uint32_t rtc_privcfgr = READ_REG(RTC->PRIVCFGR); + uint32_t tamp_privcfgr = READ_REG(TAMP->PRIVCFGR); + uint32_t tamp_cfgr = READ_REG(TAMP->CFGR); + + /* RTC privilege configuration */ + privilegeState->rtcPrivilegeFull = READ_BIT(rtc_privcfgr, RTC_PRIVCFGR_PRIV); + + /* Warning, rtcPrivilegeFeatures is only relevant if privilegeState->rtcPrivilegeFull == RTC_PRIVILEGE_FULL_NO */ + privilegeState->rtcPrivilegeFeatures = READ_BIT(rtc_privcfgr, RTC_PRIVILEGE_FEATURE_ALL); + + /* TAMP and Backup registers privilege configuration */ + privilegeState->tampPrivilegeFull = READ_BIT(tamp_privcfgr, TAMP_PRIVCFGR_TAMPPRIV); + + /* Monotonic registers privilege configuration */ + privilegeState->MonotonicCounterPrivilege = READ_BIT(tamp_privcfgr, TAMP_PRIVCFGR_CNT1PRIV); + + /* Backup registers Zones */ + privilegeState->backupRegisterPrivZone = READ_BIT(tamp_privcfgr, (TAMP_PRIVCFGR_BKPWPRIV | TAMP_PRIVCFGR_BKPRWPRIV)); + + /* Backup registers start zones */ + privilegeState->backupRegisterStartZone2 = READ_BIT(tamp_cfgr, TAMP_CFGR_BKPRW) >> TAMP_CFGR_BKPRW_Pos; + privilegeState->backupRegisterStartZone3 = READ_BIT(tamp_cfgr, TAMP_CFGR_BKPW) >> TAMP_CFGR_BKPW_Pos; + + return HAL_OK; +} + +/** + * @} + */ +#endif /* TAMP_PRIVCFGR_TAMPPRIV */ + +/** + * @} + */ + +#endif /* HAL_RTC_MODULE_ENABLED */ + +/** + * @} + */ + + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai.c index 62c876560..6e2221c17 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai.c @@ -1,2898 +1,2898 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_sai.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - - [..] - The SAI HAL driver can be used as follows: - - (#) Declare a SAI_HandleTypeDef handle structure (eg. SAI_HandleTypeDef hsai). - (#) Initialize the SAI low level resources by implementing 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. - - (#) The initialization can be done by two ways - (##) Expert mode : Initialize the structures Init, FrameInit and SlotInit and call HAL_SAI_Init(). - (##) Simplified mode : Initialize the high part of Init Structure and call HAL_SAI_InitProtocol(). - - [..] - (@) The specific SAI interrupts (FIFO request and Overrun underrun interrupt) - will be managed using the macros __HAL_SAI_ENABLE_IT() and __HAL_SAI_DISABLE_IT() - inside the transmit and receive process. - [..] - (@) Make sure that either: - (+@) PLLSAI1CLK output is configured or - (+@) PLLSAI2CLK output is configured or - (+@) PLLSAI3CLK output is configured or - (+@) External clock source is configured after setting correctly - the define constant EXTERNAL_SAI1_CLOCK_VALUE or EXTERNAL_SAI2_CLOCK_VALUE - in the stm32h7rsxx_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. - - [..] - (@) PDM interface can be activated through HAL_SAI_Init function. - Please note that PDM interface is only available for SAI1 sub-block A. - PDM microphone delays can be tuned with HAL_SAIEx_ConfigPdmMicDelay function. - - [..] - Three operation modes 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 flag 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 flag 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 additional function list *** - =============================================== - [..] - Below the list the others API available SAI HAL driver : - - (+) HAL_SAI_EnableTxMuteMode(): Enable the mute in tx mode - (+) HAL_SAI_DisableTxMuteMode(): Disable the mute in tx mode - (+) HAL_SAI_EnableRxMuteMode(): Enable the mute in Rx mode - (+) HAL_SAI_DisableRxMuteMode(): Disable the mute in Rx mode - (+) HAL_SAI_FlushRxFifo(): Flush the rx fifo. - (+) HAL_SAI_Abort(): Abort the current transfer - - *** SAI HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in SAI 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 - - *** Callback registration *** - ============================= - [..] - The compilation define USE_HAL_SAI_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use functions HAL_SAI_RegisterCallback() to register a user callback. - - [..] - Function HAL_SAI_RegisterCallback() allows to register following callbacks: - (+) RxCpltCallback : SAI receive complete. - (+) RxHalfCpltCallback : SAI receive half complete. - (+) TxCpltCallback : SAI transmit complete. - (+) TxHalfCpltCallback : SAI transmit half complete. - (+) ErrorCallback : SAI error. - (+) MspInitCallback : SAI MspInit. - (+) MspDeInitCallback : SAI MspDeInit. - [..] - This function takes as parameters the HAL peripheral handle, the callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_SAI_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_SAI_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the callback ID. - [..] - This function allows to reset following callbacks: - (+) RxCpltCallback : SAI receive complete. - (+) RxHalfCpltCallback : SAI receive half complete. - (+) TxCpltCallback : SAI transmit complete. - (+) TxHalfCpltCallback : SAI transmit half complete. - (+) ErrorCallback : SAI error. - (+) MspInitCallback : SAI MspInit. - (+) MspDeInitCallback : SAI MspDeInit. - - [..] - By default, after the HAL_SAI_Init and if the state is HAL_SAI_STATE_RESET - all callbacks are reset to the corresponding legacy weak functions: - examples HAL_SAI_RxCpltCallback(), HAL_SAI_ErrorCallback(). - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak functions in the HAL_SAI_Init - and HAL_SAI_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_SAI_Init and HAL_SAI_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_SAI_RegisterCallback before calling HAL_SAI_DeInit - or HAL_SAI_Init function. - - [..] - When the compilation define USE_HAL_SAI_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak callbacks are used. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SAI SAI - * @brief SAI HAL module driver - * @{ - */ - -#ifdef HAL_SAI_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/** @defgroup SAI_Private_Typedefs SAI Private Typedefs - * @{ - */ -typedef enum -{ - SAI_MODE_DMA, - SAI_MODE_IT -} SAI_ModeTypedef; -/** - * @} - */ - -/* Private define ------------------------------------------------------------*/ -/** @defgroup SAI_Private_Constants SAI Private Constants - * @{ - */ -#define SAI_DEFAULT_TIMEOUT 4U -#define SAI_LONG_TIMEOUT 1000U -#define SAI_SPDIF_FRAME_LENGTH 64U -#define SAI_AC97_FRAME_LENGTH 256U -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup SAI_Private_Functions SAI Private Functions - * @{ - */ -static void SAI_FillFifo(SAI_HandleTypeDef *hsai); -static uint32_t SAI_InterruptFlag(const SAI_HandleTypeDef *hsai, SAI_ModeTypedef mode); -static HAL_StatusTypeDef SAI_InitI2S(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot); -static HAL_StatusTypeDef SAI_InitPCM(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot); - -static HAL_StatusTypeDef SAI_Disable(SAI_HandleTypeDef *hsai); -static void SAI_Transmit_IT8Bit(SAI_HandleTypeDef *hsai); -static void SAI_Transmit_IT16Bit(SAI_HandleTypeDef *hsai); -static void SAI_Transmit_IT32Bit(SAI_HandleTypeDef *hsai); -static void SAI_Receive_IT8Bit(SAI_HandleTypeDef *hsai); -static void SAI_Receive_IT16Bit(SAI_HandleTypeDef *hsai); -static void SAI_Receive_IT32Bit(SAI_HandleTypeDef *hsai); - -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); -static void SAI_DMAAbort(DMA_HandleTypeDef *hdma); -/** - * @} - */ - -/* Exported functions ---------------------------------------------------------*/ -/** @defgroup SAI_Exported_Functions SAI Exported Functions - * @{ - */ - -/** @defgroup SAI_Exported_Functions_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 - (++) PDM Config - - (+) Call the function HAL_SAI_DeInit() to restore the default configuration - of the selected SAI peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the structure FrameInit, SlotInit and the low part of - * Init according to the specified parameters and call the function - * HAL_SAI_Init to initialize the SAI block. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @param protocol one of the supported protocol @ref SAI_Protocol - * @param datasize one of the supported datasize @ref SAI_Protocol_DataSize - * the configuration information for SAI module. - * @param nbslot Number of slot. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_InitProtocol(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot) -{ - HAL_StatusTypeDef status; - - /* Check the parameters */ - assert_param(IS_SAI_SUPPORTED_PROTOCOL(protocol)); - assert_param(IS_SAI_PROTOCOL_DATASIZE(datasize)); - - switch (protocol) - { - case SAI_I2S_STANDARD : - case SAI_I2S_MSBJUSTIFIED : - case SAI_I2S_LSBJUSTIFIED : - status = SAI_InitI2S(hsai, protocol, datasize, nbslot); - break; - case SAI_PCM_LONG : - case SAI_PCM_SHORT : - status = SAI_InitPCM(hsai, protocol, datasize, nbslot); - break; - default : - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - status = HAL_SAI_Init(hsai); - } - - return status; -} - -/** - * @brief Initialize the SAI according to the specified parameters. - * in the SAI_InitTypeDef structure and initialize the associated handle. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_Init(SAI_HandleTypeDef *hsai) -{ - uint32_t tmpregisterGCR; - uint32_t ckstr_bits; - uint32_t syncen_bits; - - /* Check the SAI handle allocation */ - if (hsai == NULL) - { - return HAL_ERROR; - } - - /* check the instance */ - assert_param(IS_SAI_ALL_INSTANCE(hsai->Instance)); - - /* Check the SAI Block parameters */ - assert_param(IS_SAI_AUDIO_FREQUENCY(hsai->Init.AudioFrequency)); - 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_MCK_OUTPUT(hsai->Init.MckOutput)); - 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_MONO_STEREO_MODE(hsai->Init.MonoStereoMode)); - assert_param(IS_SAI_BLOCK_COMPANDING_MODE(hsai->Init.CompandingMode)); - assert_param(IS_SAI_BLOCK_TRISTATE_MANAGEMENT(hsai->Init.TriState)); - assert_param(IS_SAI_BLOCK_SYNCEXT(hsai->Init.SynchroExt)); - assert_param(IS_SAI_BLOCK_MCK_OVERSAMPLING(hsai->Init.MckOverSampling)); - - /* 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)); - - /* Check the SAI PDM parameters */ - assert_param(IS_FUNCTIONAL_STATE(hsai->Init.PdmInit.Activation)); - if (hsai->Init.PdmInit.Activation == ENABLE) - { - assert_param(IS_SAI_PDM_MIC_PAIRS_NUMBER(hsai->Init.PdmInit.MicPairsNbr)); - assert_param(IS_SAI_PDM_CLOCK_ENABLE(hsai->Init.PdmInit.ClockEnable)); - /* Check that SAI sub-block is SAI1 sub-block A, in master RX mode with free protocol */ - if ((hsai->Instance != SAI1_Block_A) || - (hsai->Init.AudioMode != SAI_MODEMASTER_RX) || - (hsai->Init.Protocol != SAI_FREE_PROTOCOL)) - { - return HAL_ERROR; - } - } - - if (hsai->State == HAL_SAI_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hsai->Lock = HAL_UNLOCKED; - -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - /* Reset callback pointers to the weak predefined callbacks */ - hsai->RxCpltCallback = HAL_SAI_RxCpltCallback; - hsai->RxHalfCpltCallback = HAL_SAI_RxHalfCpltCallback; - hsai->TxCpltCallback = HAL_SAI_TxCpltCallback; - hsai->TxHalfCpltCallback = HAL_SAI_TxHalfCpltCallback; - hsai->ErrorCallback = HAL_SAI_ErrorCallback; - - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - if (hsai->MspInitCallback == NULL) - { - hsai->MspInitCallback = HAL_SAI_MspInit; - } - hsai->MspInitCallback(hsai); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_SAI_MspInit(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - - /* Disable the selected SAI peripheral */ - if (SAI_Disable(hsai) != HAL_OK) - { - return HAL_ERROR; - } - - hsai->State = HAL_SAI_STATE_BUSY; - - /* SAI Block Synchro Configuration -----------------------------------------*/ - /* This setting must be done with both audio block (A & B) disabled */ - switch (hsai->Init.SynchroExt) - { - case SAI_SYNCEXT_DISABLE : - tmpregisterGCR = 0; - break; - case SAI_SYNCEXT_OUTBLOCKA_ENABLE : - tmpregisterGCR = SAI_GCR_SYNCOUT_0; - break; - case SAI_SYNCEXT_OUTBLOCKB_ENABLE : - tmpregisterGCR = SAI_GCR_SYNCOUT_1; - break; - default : - tmpregisterGCR = 0; - break; - } - - switch (hsai->Init.Synchro) - { - case SAI_ASYNCHRONOUS : - syncen_bits = 0; - break; - case SAI_SYNCHRONOUS : - syncen_bits = SAI_xCR1_SYNCEN_0; - break; - case SAI_SYNCHRONOUS_EXT_SAI1 : - syncen_bits = SAI_xCR1_SYNCEN_1; - break; - case SAI_SYNCHRONOUS_EXT_SAI2 : - syncen_bits = SAI_xCR1_SYNCEN_1; - tmpregisterGCR |= SAI_GCR_SYNCIN_0; - break; - default : - syncen_bits = 0; - break; - } - - if ((hsai->Instance == SAI1_Block_A) || (hsai->Instance == SAI1_Block_B)) - { - SAI1->GCR = tmpregisterGCR; - } - else - { - SAI2->GCR = tmpregisterGCR; - } - - if (hsai->Init.AudioFrequency != SAI_AUDIO_FREQUENCY_MCKDIV) - { - uint32_t freq = 0; - uint32_t tmpval; - - /* In this case, the MCKDIV value is calculated to get AudioFrequency */ - if ((hsai->Instance == SAI1_Block_A) || (hsai->Instance == SAI1_Block_B)) - { - freq = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SAI1); - } - if ((hsai->Instance == SAI2_Block_A) || (hsai->Instance == SAI2_Block_B)) - { - freq = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SAI2); - } - - /* Configure Master Clock Divider using the following formula : - - If NODIV = 1 : - MCKDIV[5:0] = SAI_CK_x / (FS * (FRL + 1)) - - If NODIV = 0 : - MCKDIV[5:0] = SAI_CK_x / (FS * (OSR + 1) * 256) */ - if (hsai->Init.NoDivider == SAI_MASTERDIVIDER_DISABLE) - { - /* NODIV = 1 */ - uint32_t tmpframelength; - - if (hsai->Init.Protocol == SAI_SPDIF_PROTOCOL) - { - /* For SPDIF protocol, frame length is set by hardware to 64 */ - tmpframelength = SAI_SPDIF_FRAME_LENGTH; - } - else if (hsai->Init.Protocol == SAI_AC97_PROTOCOL) - { - /* For AC97 protocol, frame length is set by hardware to 256 */ - tmpframelength = SAI_AC97_FRAME_LENGTH; - } - else - { - /* For free protocol, frame length is set by user */ - tmpframelength = hsai->FrameInit.FrameLength; - } - - /* (freq x 10) to keep Significant digits */ - tmpval = (freq * 10U) / (hsai->Init.AudioFrequency * tmpframelength); - } - else - { - /* NODIV = 0 */ - uint32_t tmposr; - tmposr = (hsai->Init.MckOverSampling == SAI_MCK_OVERSAMPLING_ENABLE) ? 2U : 1U; - /* (freq x 10) to keep Significant digits */ - tmpval = (freq * 10U) / (hsai->Init.AudioFrequency * tmposr * 256U); - } - hsai->Init.Mckdiv = tmpval / 10U; - - /* Round result to the nearest integer */ - if ((tmpval % 10U) > 8U) - { - hsai->Init.Mckdiv += 1U; - } - - /* For SPDIF protocol, SAI shall provide a bit clock twice faster the symbol-rate */ - if (hsai->Init.Protocol == SAI_SPDIF_PROTOCOL) - { - hsai->Init.Mckdiv = hsai->Init.Mckdiv >> 1; - } - } - - /* Check the SAI Block master clock divider parameter */ - assert_param(IS_SAI_BLOCK_MASTER_DIVIDER(hsai->Init.Mckdiv)); - - /* Compute CKSTR bits of SAI CR1 according ClockStrobing and AudioMode */ - if ((hsai->Init.AudioMode == SAI_MODEMASTER_TX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) - { - /* Transmit */ - ckstr_bits = (hsai->Init.ClockStrobing == SAI_CLOCKSTROBING_RISINGEDGE) ? 0U : SAI_xCR1_CKSTR; - } - else - { - /* Receive */ - ckstr_bits = (hsai->Init.ClockStrobing == SAI_CLOCKSTROBING_RISINGEDGE) ? SAI_xCR1_CKSTR : 0U; - } - - /* SAI Block Configuration -------------------------------------------------*/ - /* SAI CR1 Configuration */ - hsai->Instance->CR1 &= ~(SAI_xCR1_MODE | SAI_xCR1_PRTCFG | SAI_xCR1_DS | \ - SAI_xCR1_LSBFIRST | SAI_xCR1_CKSTR | SAI_xCR1_SYNCEN | \ - SAI_xCR1_MONO | SAI_xCR1_OUTDRIV | SAI_xCR1_DMAEN | \ - SAI_xCR1_NODIV | SAI_xCR1_MCKDIV | SAI_xCR1_OSR | \ - SAI_xCR1_MCKEN); - - hsai->Instance->CR1 |= (hsai->Init.AudioMode | hsai->Init.Protocol | \ - hsai->Init.DataSize | hsai->Init.FirstBit | \ - ckstr_bits | syncen_bits | \ - hsai->Init.MonoStereoMode | hsai->Init.OutputDrive | \ - hsai->Init.NoDivider | (hsai->Init.Mckdiv << 20) | \ - hsai->Init.MckOverSampling | hsai->Init.MckOutput); - - /* SAI CR2 Configuration */ - hsai->Instance->CR2 &= ~(SAI_xCR2_FTH | SAI_xCR2_FFLUSH | SAI_xCR2_COMP | SAI_xCR2_CPL); - hsai->Instance->CR2 |= (hsai->Init.FIFOThreshold | hsai->Init.CompandingMode | hsai->Init.TriState); - - /* SAI Frame Configuration -----------------------------------------*/ - hsai->Instance->FRCR &= (~(SAI_xFRCR_FRL | SAI_xFRCR_FSALL | SAI_xFRCR_FSDEF | \ - SAI_xFRCR_FSPOL | SAI_xFRCR_FSOFF)); - hsai->Instance->FRCR |= ((hsai->FrameInit.FrameLength - 1U) | - hsai->FrameInit.FSOffset | - hsai->FrameInit.FSDefinition | - hsai->FrameInit.FSPolarity | - ((hsai->FrameInit.ActiveFrameLength - 1U) << 8)); - - /* SAI Block_x SLOT Configuration ------------------------------------------*/ - /* This register has no meaning in AC 97 and SPDIF audio protocol */ - hsai->Instance->SLOTR &= (~(SAI_xSLOTR_FBOFF | SAI_xSLOTR_SLOTSZ | \ - SAI_xSLOTR_NBSLOT | SAI_xSLOTR_SLOTEN)); - - hsai->Instance->SLOTR |= hsai->SlotInit.FirstBitOffset | hsai->SlotInit.SlotSize | \ - (hsai->SlotInit.SlotActive << 16) | ((hsai->SlotInit.SlotNumber - 1U) << 8); - - /* SAI PDM Configuration ---------------------------------------------------*/ - if (hsai->Instance == SAI1_Block_A) - { - /* Disable PDM interface */ - SAI1->PDMCR &= ~(SAI_PDMCR_PDMEN); - if (hsai->Init.PdmInit.Activation == ENABLE) - { - /* Configure and enable PDM interface */ - SAI1->PDMCR = (hsai->Init.PdmInit.ClockEnable | - ((hsai->Init.PdmInit.MicPairsNbr - 1U) << SAI_PDMCR_MICNBR_Pos)); - SAI1->PDMCR |= SAI_PDMCR_PDMEN; - } - } - - /* Initialize the error code */ - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - - /* Initialize the SAI state */ - hsai->State = HAL_SAI_STATE_READY; - - /* Release Lock */ - __HAL_UNLOCK(hsai); - - return HAL_OK; -} - -/** - * @brief DeInitialize the SAI peripheral. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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; - - /* Disabled All interrupt and clear all the flag */ - hsai->Instance->IMR = 0; - hsai->Instance->CLRFR = 0xFFFFFFFFU; - - /* Disable the SAI */ - if (SAI_Disable(hsai) != HAL_OK) - { - /* Reset SAI state to ready */ - hsai->State = HAL_SAI_STATE_READY; - - /* Release Lock */ - __HAL_UNLOCK(hsai); - - return HAL_ERROR; - } - - /* Flush the fifo */ - SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); - - /* Disable SAI PDM interface */ - if (hsai->Instance == SAI1_Block_A) - { - /* Reset PDM delays */ - SAI1->PDMDLY = 0U; - - /* Disable PDM interface */ - SAI1->PDMCR &= ~(SAI_PDMCR_PDMEN); - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - if (hsai->MspDeInitCallback == NULL) - { - hsai->MspDeInitCallback = HAL_SAI_MspDeInit; - } - hsai->MspDeInitCallback(hsai); -#else - HAL_SAI_MspDeInit(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - - /* 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 Initialize the SAI MSP. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_MspInit(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 DeInitialize the SAI MSP. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_MspDeInit(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsai); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SAI_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) -/** - * @brief Register a user SAI callback - * to be used instead of the weak predefined callback. - * @param hsai SAI handle. - * @param CallbackID ID of the callback to be registered. - * This parameter can be one of the following values: - * @arg @ref HAL_SAI_RX_COMPLETE_CB_ID receive complete callback ID. - * @arg @ref HAL_SAI_RX_HALFCOMPLETE_CB_ID receive half complete callback ID. - * @arg @ref HAL_SAI_TX_COMPLETE_CB_ID transmit complete callback ID. - * @arg @ref HAL_SAI_TX_HALFCOMPLETE_CB_ID transmit half complete callback ID. - * @arg @ref HAL_SAI_ERROR_CB_ID error callback ID. - * @arg @ref HAL_SAI_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_SAI_MSPDEINIT_CB_ID MSP de-init callback ID. - * @param pCallback pointer to the callback function. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_SAI_RegisterCallback(SAI_HandleTypeDef *hsai, - HAL_SAI_CallbackIDTypeDef CallbackID, - pSAI_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - else - { - if (HAL_SAI_STATE_READY == hsai->State) - { - switch (CallbackID) - { - case HAL_SAI_RX_COMPLETE_CB_ID : - hsai->RxCpltCallback = pCallback; - break; - case HAL_SAI_RX_HALFCOMPLETE_CB_ID : - hsai->RxHalfCpltCallback = pCallback; - break; - case HAL_SAI_TX_COMPLETE_CB_ID : - hsai->TxCpltCallback = pCallback; - break; - case HAL_SAI_TX_HALFCOMPLETE_CB_ID : - hsai->TxHalfCpltCallback = pCallback; - break; - case HAL_SAI_ERROR_CB_ID : - hsai->ErrorCallback = pCallback; - break; - case HAL_SAI_MSPINIT_CB_ID : - hsai->MspInitCallback = pCallback; - break; - case HAL_SAI_MSPDEINIT_CB_ID : - hsai->MspDeInitCallback = pCallback; - break; - default : - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SAI_STATE_RESET == hsai->State) - { - switch (CallbackID) - { - case HAL_SAI_MSPINIT_CB_ID : - hsai->MspInitCallback = pCallback; - break; - case HAL_SAI_MSPDEINIT_CB_ID : - hsai->MspDeInitCallback = pCallback; - break; - default : - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - } - return status; -} - -/** - * @brief Unregister a user SAI callback. - * SAI callback is redirected to the weak predefined callback. - * @param hsai SAI handle. - * @param CallbackID ID of the callback to be unregistered. - * This parameter can be one of the following values: - * @arg @ref HAL_SAI_RX_COMPLETE_CB_ID receive complete callback ID. - * @arg @ref HAL_SAI_RX_HALFCOMPLETE_CB_ID receive half complete callback ID. - * @arg @ref HAL_SAI_TX_COMPLETE_CB_ID transmit complete callback ID. - * @arg @ref HAL_SAI_TX_HALFCOMPLETE_CB_ID transmit half complete callback ID. - * @arg @ref HAL_SAI_ERROR_CB_ID error callback ID. - * @arg @ref HAL_SAI_MSPINIT_CB_ID MSP init callback ID. - * @arg @ref HAL_SAI_MSPDEINIT_CB_ID MSP de-init callback ID. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_SAI_UnRegisterCallback(SAI_HandleTypeDef *hsai, - HAL_SAI_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_SAI_STATE_READY == hsai->State) - { - switch (CallbackID) - { - case HAL_SAI_RX_COMPLETE_CB_ID : - hsai->RxCpltCallback = HAL_SAI_RxCpltCallback; - break; - case HAL_SAI_RX_HALFCOMPLETE_CB_ID : - hsai->RxHalfCpltCallback = HAL_SAI_RxHalfCpltCallback; - break; - case HAL_SAI_TX_COMPLETE_CB_ID : - hsai->TxCpltCallback = HAL_SAI_TxCpltCallback; - break; - case HAL_SAI_TX_HALFCOMPLETE_CB_ID : - hsai->TxHalfCpltCallback = HAL_SAI_TxHalfCpltCallback; - break; - case HAL_SAI_ERROR_CB_ID : - hsai->ErrorCallback = HAL_SAI_ErrorCallback; - break; - case HAL_SAI_MSPINIT_CB_ID : - hsai->MspInitCallback = HAL_SAI_MspInit; - break; - case HAL_SAI_MSPDEINIT_CB_ID : - hsai->MspDeInitCallback = HAL_SAI_MspDeInit; - break; - default : - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SAI_STATE_RESET == hsai->State) - { - switch (CallbackID) - { - case HAL_SAI_MSPINIT_CB_ID : - hsai->MspInitCallback = HAL_SAI_MspInit; - break; - case HAL_SAI_MSPDEINIT_CB_ID : - hsai->MspDeInitCallback = HAL_SAI_MspDeInit; - break; - default : - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update the error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - return status; -} -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup SAI_Exported_Functions_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 are two modes 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() - - (+) Non Blocking mode functions with Interrupt are : - (++) HAL_SAI_Transmit_IT() - (++) HAL_SAI_Receive_IT() - - (+) Non Blocking mode functions with DMA are : - (++) HAL_SAI_Transmit_DMA() - (++) HAL_SAI_Receive_DMA() - - (+) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (++) HAL_SAI_TxCpltCallback() - (++) HAL_SAI_RxCpltCallback() - (++) HAL_SAI_ErrorCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Transmit an amount of data in blocking mode. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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, uint8_t *pData, uint16_t Size, uint32_t Timeout) -{ - uint32_t tickstart = HAL_GetTick(); - uint32_t temp; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hsai->State == HAL_SAI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsai); - - hsai->XferSize = Size; - hsai->XferCount = Size; - hsai->pBuffPtr = pData; - hsai->State = HAL_SAI_STATE_BUSY_TX; - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - - /* Check if the SAI is already enabled */ - if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) - { - /* fill the fifo with data before to enabled the SAI */ - SAI_FillFifo(hsai); - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - - while (hsai->XferCount > 0U) - { - /* Write data if the FIFO is not full */ - if ((hsai->Instance->SR & SAI_xSR_FLVL) != SAI_FIFOSTATUS_FULL) - { - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - hsai->Instance->DR = *hsai->pBuffPtr; - hsai->pBuffPtr++; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - temp = (uint32_t)(*hsai->pBuffPtr); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); - hsai->pBuffPtr++; - hsai->Instance->DR = temp; - } - else - { - temp = (uint32_t)(*hsai->pBuffPtr); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 16); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 24); - hsai->pBuffPtr++; - hsai->Instance->DR = temp; - } - hsai->XferCount--; - } - else - { - /* Check for the Timeout */ - if ((((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) && (Timeout != HAL_MAX_DELAY)) - { - /* Update error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; - - /* Clear all the flags */ - hsai->Instance->CLRFR = 0xFFFFFFFFU; - - /* Disable SAI peripheral */ - /* No need to check return value because state update, unlock and error return will be performed later */ - (void) SAI_Disable(hsai); - - /* Flush the fifo */ - SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); - - /* Change the SAI state */ - hsai->State = HAL_SAI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_ERROR; - } - } - } - - hsai->State = HAL_SAI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in blocking mode. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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, uint8_t *pData, uint16_t Size, uint32_t Timeout) -{ - uint32_t tickstart = HAL_GetTick(); - uint32_t temp; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hsai->State == HAL_SAI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsai); - - hsai->pBuffPtr = pData; - hsai->XferSize = Size; - hsai->XferCount = Size; - hsai->State = HAL_SAI_STATE_BUSY_RX; - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - - /* Check if the SAI is already enabled */ - if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) - { - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - - /* Receive data */ - while (hsai->XferCount > 0U) - { - if ((hsai->Instance->SR & SAI_xSR_FLVL) != SAI_FIFOSTATUS_EMPTY) - { - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - *hsai->pBuffPtr = (uint8_t)hsai->Instance->DR; - hsai->pBuffPtr++; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - temp = hsai->Instance->DR; - *hsai->pBuffPtr = (uint8_t)temp; - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 8); - hsai->pBuffPtr++; - } - else - { - temp = hsai->Instance->DR; - *hsai->pBuffPtr = (uint8_t)temp; - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 8); - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 16); - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 24); - hsai->pBuffPtr++; - } - hsai->XferCount--; - } - else - { - /* Check for the Timeout */ - if ((((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) && (Timeout != HAL_MAX_DELAY)) - { - /* Update error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; - - /* Clear all the flags */ - hsai->Instance->CLRFR = 0xFFFFFFFFU; - - /* Disable SAI peripheral */ - /* No need to check return value because state update, unlock and error return will be performed later */ - (void) SAI_Disable(hsai); - - /* Flush the fifo */ - SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); - - /* Change the SAI state */ - hsai->State = HAL_SAI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_ERROR; - } - } - } - - hsai->State = HAL_SAI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Transmit an amount of data in non-blocking mode with Interrupt. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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, uint8_t *pData, uint16_t Size) -{ - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hsai->State == HAL_SAI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsai); - - hsai->pBuffPtr = pData; - hsai->XferSize = Size; - hsai->XferCount = Size; - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - hsai->State = HAL_SAI_STATE_BUSY_TX; - - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - hsai->InterruptServiceRoutine = SAI_Transmit_IT8Bit; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - hsai->InterruptServiceRoutine = SAI_Transmit_IT16Bit; - } - else - { - hsai->InterruptServiceRoutine = SAI_Transmit_IT32Bit; - } - - /* Fill the fifo before starting the communication */ - SAI_FillFifo(hsai); - - /* Enable FRQ and OVRUDR interrupts */ - __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - - /* Check if the SAI is already enabled */ - if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) - { - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in non-blocking mode with Interrupt. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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, uint8_t *pData, uint16_t Size) -{ - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hsai->State == HAL_SAI_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsai); - - hsai->pBuffPtr = pData; - hsai->XferSize = Size; - hsai->XferCount = Size; - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - hsai->State = HAL_SAI_STATE_BUSY_RX; - - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - hsai->InterruptServiceRoutine = SAI_Receive_IT8Bit; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - hsai->InterruptServiceRoutine = SAI_Receive_IT16Bit; - } - else - { - hsai->InterruptServiceRoutine = SAI_Receive_IT32Bit; - } - - /* Enable TXE and OVRUDR interrupts */ - __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - - /* Check if the SAI is already enabled */ - if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) - { - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Pause the audio stream playing from the Media. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -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 Resume the audio stream playing from the Media. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -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) == 0U) - { - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; -} - -/** - * @brief Stop the audio stream playing from the Media. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_DMAStop(SAI_HandleTypeDef *hsai) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process Locked */ - __HAL_LOCK(hsai); - - /* Disable SAI peripheral */ - if (SAI_Disable(hsai) != HAL_OK) - { - status = HAL_ERROR; - } - - /* Disable the SAI DMA request */ - hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; - - /* Abort the SAI Tx DMA Stream */ - if ((hsai->State == HAL_SAI_STATE_BUSY_TX) && (hsai->hdmatx != NULL)) - { - if (HAL_DMA_Abort(hsai->hdmatx) != HAL_OK) - { - /* If the DMA Tx errorCode is different from DMA No Transfer then return Error */ - if (hsai->hdmatx->ErrorCode != HAL_DMA_ERROR_NO_XFER) - { - status = HAL_ERROR; - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - } - } - } - - /* Abort the SAI Rx DMA Stream */ - if ((hsai->State == HAL_SAI_STATE_BUSY_RX) && (hsai->hdmarx != NULL)) - { - if (HAL_DMA_Abort(hsai->hdmarx) != HAL_OK) - { - /* If the DMA Rx errorCode is different from DMA No Transfer then return Error */ - if (hsai->hdmarx->ErrorCode != HAL_DMA_ERROR_NO_XFER) - { - status = HAL_ERROR; - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - } - } - } - - /* Flush the fifo */ - SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); - - /* Set hsai state to ready */ - hsai->State = HAL_SAI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return status; -} - -/** - * @brief Abort the current transfer and disable the SAI. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_Abort(SAI_HandleTypeDef *hsai) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process Locked */ - __HAL_LOCK(hsai); - - /* Disable SAI peripheral */ - if (SAI_Disable(hsai) != HAL_OK) - { - status = HAL_ERROR; - } - - /* Check SAI DMA is enabled or not */ - if ((hsai->Instance->CR1 & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) - { - /* Disable the SAI DMA request */ - hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; - - /* Abort the SAI Tx DMA Stream */ - if ((hsai->State == HAL_SAI_STATE_BUSY_TX) && (hsai->hdmatx != NULL)) - { - if (HAL_DMA_Abort(hsai->hdmatx) != HAL_OK) - { - /* If the DMA Tx errorCode is different from DMA No Transfer then return Error */ - if (hsai->hdmatx->ErrorCode != HAL_DMA_ERROR_NO_XFER) - { - status = HAL_ERROR; - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - } - } - } - - /* Abort the SAI Rx DMA Stream */ - if ((hsai->State == HAL_SAI_STATE_BUSY_RX) && (hsai->hdmarx != NULL)) - { - if (HAL_DMA_Abort(hsai->hdmarx) != HAL_OK) - { - /* If the DMA Rx errorCode is different from DMA No Transfer then return Error */ - if (hsai->hdmarx->ErrorCode != HAL_DMA_ERROR_NO_XFER) - { - status = HAL_ERROR; - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - } - } - } - } - - /* Disabled All interrupt and clear all the flag */ - hsai->Instance->IMR = 0; - hsai->Instance->CLRFR = 0xFFFFFFFFU; - - /* Flush the fifo */ - SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); - - /* Set hsai state to ready */ - hsai->State = HAL_SAI_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return status; -} - -/** - * @brief Transmit an amount of data in non-blocking mode with DMA. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hsai->State == HAL_SAI_STATE_READY) - { - uint32_t dmaSrcSize; - - /* Process Locked */ - __HAL_LOCK(hsai); - - hsai->pBuffPtr = pData; - hsai->XferSize = Size; - hsai->XferCount = Size; - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - hsai->State = HAL_SAI_STATE_BUSY_TX; - - /* Set the SAI Tx DMA Half transfer 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; - - /* Set the DMA Tx abort callback */ - hsai->hdmatx->XferAbortCallback = NULL; - - /* For transmission, the DMA source is data buffer. - We have to compute DMA size of a source block transfer in bytes according SAI data size. */ - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - dmaSrcSize = (uint32_t) Size; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - dmaSrcSize = 2U * (uint32_t) Size; - } - else - { - dmaSrcSize = 4U * (uint32_t) Size; - } - - /* Enable the Tx DMA Stream */ - if ((hsai->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hsai->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hsai->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = dmaSrcSize; - - /* Set DMA source address */ - hsai->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hsai->pBuffPtr; - - /* Set DMA destination address */ - hsai->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hsai->Instance->DR; - - status = HAL_DMAEx_List_Start_IT(hsai->hdmatx); - } - else - { - __HAL_UNLOCK(hsai); - return HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hsai->hdmatx, (uint32_t)hsai->pBuffPtr, (uint32_t)&hsai->Instance->DR, dmaSrcSize); - } - - if (status != HAL_OK) - { - __HAL_UNLOCK(hsai); - return HAL_ERROR; - } - - /* Enable the interrupts for error handling */ - __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); - - /* Enable SAI Tx DMA Request */ - hsai->Instance->CR1 |= SAI_xCR1_DMAEN; - - /* Wait until FIFO is not empty */ - while ((hsai->Instance->SR & SAI_xSR_FLVL) == SAI_FIFOSTATUS_EMPTY) - { - /* Check for the Timeout */ - if ((HAL_GetTick() - tickstart) > SAI_LONG_TIMEOUT) - { - /* Update error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_TIMEOUT; - } - } - - /* Check if the SAI is already enabled */ - if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) - { - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in non-blocking mode with DMA. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @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, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hsai->State == HAL_SAI_STATE_READY) - { - uint32_t dmaSrcSize; - - /* Process Locked */ - __HAL_LOCK(hsai); - - hsai->pBuffPtr = pData; - hsai->XferSize = Size; - hsai->XferCount = Size; - hsai->ErrorCode = HAL_SAI_ERROR_NONE; - hsai->State = HAL_SAI_STATE_BUSY_RX; - - /* Set the SAI Rx DMA Half transfer complete callback */ - hsai->hdmarx->XferHalfCpltCallback = SAI_DMARxHalfCplt; - - /* Set the SAI Rx DMA transfer complete callback */ - hsai->hdmarx->XferCpltCallback = SAI_DMARxCplt; - - /* Set the DMA error callback */ - hsai->hdmarx->XferErrorCallback = SAI_DMAError; - - /* Set the DMA Rx abort callback */ - hsai->hdmarx->XferAbortCallback = NULL; - - /* For reception, the DMA source is SAI DR register. - We have to compute DMA size of a source block transfer in bytes according SAI data size. */ - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - dmaSrcSize = (uint32_t) Size; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - dmaSrcSize = 2U * (uint32_t) Size; - } - else - { - dmaSrcSize = 4U * (uint32_t) Size; - } - - /* Enable the Rx DMA Stream */ - if ((hsai->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hsai->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hsai->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = dmaSrcSize; - - /* Set DMA source address */ - hsai->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hsai->Instance->DR; - - /* Set DMA destination address */ - hsai->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hsai->pBuffPtr; - - status = HAL_DMAEx_List_Start_IT(hsai->hdmarx); - } - else - { - __HAL_UNLOCK(hsai); - return HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hsai->hdmarx, (uint32_t)&hsai->Instance->DR, (uint32_t)hsai->pBuffPtr, dmaSrcSize); - } - - if (status != HAL_OK) - { - __HAL_UNLOCK(hsai); - return HAL_ERROR; - } - - /* Enable the interrupts for error handling */ - __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); - - /* Enable SAI Rx DMA Request */ - hsai->Instance->CR1 |= SAI_xCR1_DMAEN; - - /* Check if the SAI is already enabled */ - if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) - { - /* Enable SAI peripheral */ - __HAL_SAI_ENABLE(hsai); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsai); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Enable the Tx mute mode. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @param val value sent during the mute @ref SAI_Block_Mute_Value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_EnableTxMuteMode(SAI_HandleTypeDef *hsai, uint16_t val) -{ - assert_param(IS_SAI_BLOCK_MUTE_VALUE(val)); - - if (hsai->State != HAL_SAI_STATE_RESET) - { - CLEAR_BIT(hsai->Instance->CR2, SAI_xCR2_MUTEVAL | SAI_xCR2_MUTE); - SET_BIT(hsai->Instance->CR2, SAI_xCR2_MUTE | (uint32_t)val); - return HAL_OK; - } - return HAL_ERROR; -} - -/** - * @brief Disable the Tx mute mode. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_DisableTxMuteMode(SAI_HandleTypeDef *hsai) -{ - if (hsai->State != HAL_SAI_STATE_RESET) - { - CLEAR_BIT(hsai->Instance->CR2, SAI_xCR2_MUTEVAL | SAI_xCR2_MUTE); - return HAL_OK; - } - return HAL_ERROR; -} - -/** - * @brief Enable the Rx mute detection. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @param callback function called when the mute is detected. - * @param counter number a data before mute detection max 63. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_EnableRxMuteMode(SAI_HandleTypeDef *hsai, SAIcallback callback, uint16_t counter) -{ - assert_param(IS_SAI_BLOCK_MUTE_COUNTER(counter)); - - if (hsai->State != HAL_SAI_STATE_RESET) - { - /* set the mute counter */ - CLEAR_BIT(hsai->Instance->CR2, SAI_xCR2_MUTECNT); - SET_BIT(hsai->Instance->CR2, (uint32_t)((uint32_t)counter << SAI_xCR2_MUTECNT_Pos)); - hsai->mutecallback = callback; - /* enable the IT interrupt */ - __HAL_SAI_ENABLE_IT(hsai, SAI_IT_MUTEDET); - return HAL_OK; - } - return HAL_ERROR; -} - -/** - * @brief Disable the Rx mute detection. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAI_DisableRxMuteMode(SAI_HandleTypeDef *hsai) -{ - if (hsai->State != HAL_SAI_STATE_RESET) - { - /* set the mutecallback to NULL */ - hsai->mutecallback = NULL; - /* enable the IT interrupt */ - __HAL_SAI_DISABLE_IT(hsai, SAI_IT_MUTEDET); - return HAL_OK; - } - return HAL_ERROR; -} - -/** - * @brief Handle SAI interrupt request. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -void HAL_SAI_IRQHandler(SAI_HandleTypeDef *hsai) -{ - if (hsai->State != HAL_SAI_STATE_RESET) - { - uint32_t itflags = hsai->Instance->SR; - uint32_t itsources = hsai->Instance->IMR; - uint32_t cr1config = hsai->Instance->CR1; - uint32_t tmperror; - - /* SAI Fifo request interrupt occurred -----------------------------------*/ - if (((itflags & SAI_xSR_FREQ) == SAI_xSR_FREQ) && ((itsources & SAI_IT_FREQ) == SAI_IT_FREQ)) - { - hsai->InterruptServiceRoutine(hsai); - } - /* SAI Overrun error interrupt occurred ----------------------------------*/ - else if (((itflags & SAI_FLAG_OVRUDR) == SAI_FLAG_OVRUDR) && ((itsources & SAI_IT_OVRUDR) == SAI_IT_OVRUDR)) - { - /* Clear the SAI Overrun flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); - /* Get the SAI error code */ - tmperror = ((hsai->State == HAL_SAI_STATE_BUSY_RX) ? HAL_SAI_ERROR_OVR : HAL_SAI_ERROR_UDR); - /* Change the SAI error code */ - hsai->ErrorCode |= tmperror; - /* the transfer is not stopped, we will forward the information to the user and we let - the user decide what needs to be done */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - /* SAI mutedet interrupt occurred ----------------------------------*/ - else if (((itflags & SAI_FLAG_MUTEDET) == SAI_FLAG_MUTEDET) && ((itsources & SAI_IT_MUTEDET) == SAI_IT_MUTEDET)) - { - /* Clear the SAI mutedet flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_MUTEDET); - /* call the call back function */ - if (hsai->mutecallback != NULL) - { - /* inform the user that an RX mute event has been detected */ - hsai->mutecallback(); - } - } - /* SAI AFSDET interrupt occurred ----------------------------------*/ - else if (((itflags & SAI_FLAG_AFSDET) == SAI_FLAG_AFSDET) && ((itsources & SAI_IT_AFSDET) == SAI_IT_AFSDET)) - { - /* Clear the SAI AFSDET flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_AFSDET); - - /* Change the SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_AFSDET; - - /* Check SAI DMA is enabled or not */ - if ((cr1config & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) - { - /* Abort the SAI DMA Streams */ - if (hsai->hdmatx != NULL) - { - /* Set the DMA Tx abort callback */ - hsai->hdmatx->XferAbortCallback = SAI_DMAAbort; - - /* Abort DMA in IT mode */ - if (HAL_DMA_Abort_IT(hsai->hdmatx) != HAL_OK) - { - /* Update SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Call SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - if (hsai->hdmarx != NULL) - { - /* Set the DMA Rx abort callback */ - hsai->hdmarx->XferAbortCallback = SAI_DMAAbort; - - /* Abort DMA in IT mode */ - if (HAL_DMA_Abort_IT(hsai->hdmarx) != HAL_OK) - { - /* Update SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Call SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - } - else - { - /* Abort SAI */ - /* No need to check return value because HAL_SAI_ErrorCallback will be called later */ - (void) HAL_SAI_Abort(hsai); - - /* Set error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - /* SAI LFSDET interrupt occurred ----------------------------------*/ - else if (((itflags & SAI_FLAG_LFSDET) == SAI_FLAG_LFSDET) && ((itsources & SAI_IT_LFSDET) == SAI_IT_LFSDET)) - { - /* Clear the SAI LFSDET flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_LFSDET); - - /* Change the SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_LFSDET; - - /* Check SAI DMA is enabled or not */ - if ((cr1config & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) - { - /* Abort the SAI DMA Streams */ - if (hsai->hdmatx != NULL) - { - /* Set the DMA Tx abort callback */ - hsai->hdmatx->XferAbortCallback = SAI_DMAAbort; - - /* Abort DMA in IT mode */ - if (HAL_DMA_Abort_IT(hsai->hdmatx) != HAL_OK) - { - /* Update SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Call SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - if (hsai->hdmarx != NULL) - { - /* Set the DMA Rx abort callback */ - hsai->hdmarx->XferAbortCallback = SAI_DMAAbort; - - /* Abort DMA in IT mode */ - if (HAL_DMA_Abort_IT(hsai->hdmarx) != HAL_OK) - { - /* Update SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Call SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - } - else - { - /* Abort SAI */ - /* No need to check return value because HAL_SAI_ErrorCallback will be called later */ - (void) HAL_SAI_Abort(hsai); - - /* Set error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - /* SAI WCKCFG interrupt occurred ----------------------------------*/ - else if (((itflags & SAI_FLAG_WCKCFG) == SAI_FLAG_WCKCFG) && ((itsources & SAI_IT_WCKCFG) == SAI_IT_WCKCFG)) - { - /* Clear the SAI WCKCFG flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_WCKCFG); - - /* Change the SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_WCKCFG; - - /* Check SAI DMA is enabled or not */ - if ((cr1config & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) - { - /* Abort the SAI DMA Streams */ - if (hsai->hdmatx != NULL) - { - /* Set the DMA Tx abort callback */ - hsai->hdmatx->XferAbortCallback = SAI_DMAAbort; - - /* Abort DMA in IT mode */ - if (HAL_DMA_Abort_IT(hsai->hdmatx) != HAL_OK) - { - /* Update SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Call SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - if (hsai->hdmarx != NULL) - { - /* Set the DMA Rx abort callback */ - hsai->hdmarx->XferAbortCallback = SAI_DMAAbort; - - /* Abort DMA in IT mode */ - if (HAL_DMA_Abort_IT(hsai->hdmarx) != HAL_OK) - { - /* Update SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Call SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - } - else - { - /* If WCKCFG occurs, SAI audio block is automatically disabled */ - /* Disable all interrupts and clear all flags */ - hsai->Instance->IMR = 0U; - hsai->Instance->CLRFR = 0xFFFFFFFFU; - /* Set the SAI state to ready to be able to start again the process */ - hsai->State = HAL_SAI_STATE_READY; - - /* Initialize XferCount */ - hsai->XferCount = 0U; - - /* SAI error callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - } - /* SAI CNRDY interrupt occurred ----------------------------------*/ - else if (((itflags & SAI_FLAG_CNRDY) == SAI_FLAG_CNRDY) && ((itsources & SAI_IT_CNRDY) == SAI_IT_CNRDY)) - { - /* Clear the SAI CNRDY flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_CNRDY); - /* Change the SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_CNREADY; - /* the transfer is not stopped, we will forward the information to the user and we let - the user decide what needs to be done */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } -} - -/** - * @brief Tx Transfer completed callback. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_TxCpltCallback(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 callback. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_TxHalfCpltCallback(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsai); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SAI_TxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 callback. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsai); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SAI_RxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief SAI error callback. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -__weak void HAL_SAI_ErrorCallback(SAI_HandleTypeDef *hsai) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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_Exported_Functions_Group3 Peripheral State functions - * @brief Peripheral State functions - * -@verbatim - =============================================================================== - ##### Peripheral State and Errors functions ##### - =============================================================================== - [..] - This subsection permits to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the SAI handle state. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval HAL state - */ -HAL_SAI_StateTypeDef HAL_SAI_GetState(const 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(const SAI_HandleTypeDef *hsai) -{ - return hsai->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup SAI_Private_Functions - * @brief Private functions - * @{ - */ - -/** - * @brief Initialize the SAI I2S protocol according to the specified parameters - * in the SAI_InitTypeDef and create the associated handle. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @param protocol one of the supported protocol. - * @param datasize one of the supported datasize @ref SAI_Protocol_DataSize. - * @param nbslot number of slot minimum value is 2 and max is 16. - * the value must be a multiple of 2. - * @retval HAL status - */ -static HAL_StatusTypeDef SAI_InitI2S(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot) -{ - HAL_StatusTypeDef status = HAL_OK; - - hsai->Init.Protocol = SAI_FREE_PROTOCOL; - hsai->Init.FirstBit = SAI_FIRSTBIT_MSB; - /* Compute ClockStrobing according AudioMode */ - if ((hsai->Init.AudioMode == SAI_MODEMASTER_TX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) - { - /* Transmit */ - hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_FALLINGEDGE; - } - else - { - /* Receive */ - hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_RISINGEDGE; - } - hsai->FrameInit.FSDefinition = SAI_FS_CHANNEL_IDENTIFICATION; - hsai->SlotInit.SlotActive = SAI_SLOTACTIVE_ALL; - hsai->SlotInit.FirstBitOffset = 0; - hsai->SlotInit.SlotNumber = nbslot; - - /* in IS2 the number of slot must be even */ - if ((nbslot & 0x1U) != 0U) - { - return HAL_ERROR; - } - - if (protocol == SAI_I2S_STANDARD) - { - hsai->FrameInit.FSPolarity = SAI_FS_ACTIVE_LOW; - hsai->FrameInit.FSOffset = SAI_FS_BEFOREFIRSTBIT; - } - else - { - /* SAI_I2S_MSBJUSTIFIED or SAI_I2S_LSBJUSTIFIED */ - hsai->FrameInit.FSPolarity = SAI_FS_ACTIVE_HIGH; - hsai->FrameInit.FSOffset = SAI_FS_FIRSTBIT; - } - - /* Frame definition */ - switch (datasize) - { - case SAI_PROTOCOL_DATASIZE_16BIT: - hsai->Init.DataSize = SAI_DATASIZE_16; - hsai->FrameInit.FrameLength = 32U * (nbslot / 2U); - hsai->FrameInit.ActiveFrameLength = 16U * (nbslot / 2U); - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_16B; - break; - case SAI_PROTOCOL_DATASIZE_16BITEXTENDED : - hsai->Init.DataSize = SAI_DATASIZE_16; - hsai->FrameInit.FrameLength = 64U * (nbslot / 2U); - hsai->FrameInit.ActiveFrameLength = 32U * (nbslot / 2U); - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; - break; - case SAI_PROTOCOL_DATASIZE_24BIT: - hsai->Init.DataSize = SAI_DATASIZE_24; - hsai->FrameInit.FrameLength = 64U * (nbslot / 2U); - hsai->FrameInit.ActiveFrameLength = 32U * (nbslot / 2U); - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; - break; - case SAI_PROTOCOL_DATASIZE_32BIT: - hsai->Init.DataSize = SAI_DATASIZE_32; - hsai->FrameInit.FrameLength = 64U * (nbslot / 2U); - hsai->FrameInit.ActiveFrameLength = 32U * (nbslot / 2U); - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; - break; - default : - status = HAL_ERROR; - break; - } - if (protocol == SAI_I2S_LSBJUSTIFIED) - { - if (datasize == SAI_PROTOCOL_DATASIZE_16BITEXTENDED) - { - hsai->SlotInit.FirstBitOffset = 16; - } - if (datasize == SAI_PROTOCOL_DATASIZE_24BIT) - { - hsai->SlotInit.FirstBitOffset = 8; - } - } - return status; -} - -/** - * @brief Initialize the SAI PCM protocol according to the specified parameters - * in the SAI_InitTypeDef and create the associated handle. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @param protocol one of the supported protocol - * @param datasize one of the supported datasize @ref SAI_Protocol_DataSize - * @param nbslot number of slot minimum value is 1 and the max is 16. - * @retval HAL status - */ -static HAL_StatusTypeDef SAI_InitPCM(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot) -{ - HAL_StatusTypeDef status = HAL_OK; - - hsai->Init.Protocol = SAI_FREE_PROTOCOL; - hsai->Init.FirstBit = SAI_FIRSTBIT_MSB; - /* Compute ClockStrobing according AudioMode */ - if ((hsai->Init.AudioMode == SAI_MODEMASTER_TX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) - { - /* Transmit */ - hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_RISINGEDGE; - } - else - { - /* Receive */ - hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_FALLINGEDGE; - } - hsai->FrameInit.FSDefinition = SAI_FS_STARTFRAME; - hsai->FrameInit.FSPolarity = SAI_FS_ACTIVE_HIGH; - hsai->FrameInit.FSOffset = SAI_FS_BEFOREFIRSTBIT; - hsai->SlotInit.FirstBitOffset = 0; - hsai->SlotInit.SlotNumber = nbslot; - hsai->SlotInit.SlotActive = SAI_SLOTACTIVE_ALL; - - if (protocol == SAI_PCM_SHORT) - { - hsai->FrameInit.ActiveFrameLength = 1; - } - else - { - /* SAI_PCM_LONG */ - hsai->FrameInit.ActiveFrameLength = 13; - } - - switch (datasize) - { - case SAI_PROTOCOL_DATASIZE_16BIT: - hsai->Init.DataSize = SAI_DATASIZE_16; - hsai->FrameInit.FrameLength = 16U * nbslot; - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_16B; - break; - case SAI_PROTOCOL_DATASIZE_16BITEXTENDED : - hsai->Init.DataSize = SAI_DATASIZE_16; - hsai->FrameInit.FrameLength = 32U * nbslot; - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; - break; - case SAI_PROTOCOL_DATASIZE_24BIT : - hsai->Init.DataSize = SAI_DATASIZE_24; - hsai->FrameInit.FrameLength = 32U * nbslot; - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; - break; - case SAI_PROTOCOL_DATASIZE_32BIT: - hsai->Init.DataSize = SAI_DATASIZE_32; - hsai->FrameInit.FrameLength = 32U * nbslot; - hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; - break; - default : - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @brief Fill the fifo. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_FillFifo(SAI_HandleTypeDef *hsai) -{ - uint32_t temp; - - /* fill the fifo with data before to enabled the SAI */ - while (((hsai->Instance->SR & SAI_xSR_FLVL) != SAI_FIFOSTATUS_FULL) && (hsai->XferCount > 0U)) - { - if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) - { - hsai->Instance->DR = *hsai->pBuffPtr; - hsai->pBuffPtr++; - } - else if (hsai->Init.DataSize <= SAI_DATASIZE_16) - { - temp = (uint32_t)(*hsai->pBuffPtr); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); - hsai->pBuffPtr++; - hsai->Instance->DR = temp; - } - else - { - temp = (uint32_t)(*hsai->pBuffPtr); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 16); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 24); - hsai->pBuffPtr++; - hsai->Instance->DR = temp; - } - hsai->XferCount--; - } -} - -/** - * @brief Return the interrupt flag to set according the SAI setup. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @param mode SAI_MODE_DMA or SAI_MODE_IT - * @retval the list of the IT flag to enable - */ -static uint32_t SAI_InterruptFlag(const SAI_HandleTypeDef *hsai, SAI_ModeTypedef mode) -{ - uint32_t tmpIT = SAI_IT_OVRUDR; - - if (mode == SAI_MODE_IT) - { - tmpIT |= SAI_IT_FREQ; - } - - if ((hsai->Init.Protocol == SAI_AC97_PROTOCOL) && - ((hsai->Init.AudioMode == SAI_MODESLAVE_RX) || (hsai->Init.AudioMode == SAI_MODEMASTER_RX))) - { - tmpIT |= SAI_IT_CNRDY; - } - - if ((hsai->Init.AudioMode == SAI_MODESLAVE_RX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) - { - tmpIT |= SAI_IT_AFSDET | SAI_IT_LFSDET; - } - else - { - /* hsai has been configured in master mode */ - tmpIT |= SAI_IT_WCKCFG; - } - return tmpIT; -} - -/** - * @brief Disable the SAI and wait for the disabling. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static HAL_StatusTypeDef SAI_Disable(SAI_HandleTypeDef *hsai) -{ - uint32_t count = SAI_DEFAULT_TIMEOUT * (SystemCoreClock / 7U / 1000U); - HAL_StatusTypeDef status = HAL_OK; - - /* Disable the SAI instance */ - __HAL_SAI_DISABLE(hsai); - - do - { - /* Check for the Timeout */ - if (count == 0U) - { - /* Update error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; - status = HAL_TIMEOUT; - break; - } - count--; - } while ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != 0U); - - return status; -} - -/** - * @brief Tx Handler for Transmit in Interrupt mode 8-Bit transfer. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_Transmit_IT8Bit(SAI_HandleTypeDef *hsai) -{ - if (hsai->XferCount == 0U) - { - /* Handle the end of the transmission */ - /* Disable FREQ and OVRUDR interrupts */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - hsai->State = HAL_SAI_STATE_READY; -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->TxCpltCallback(hsai); -#else - HAL_SAI_TxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - else - { - /* Write data on DR register */ - hsai->Instance->DR = *hsai->pBuffPtr; - hsai->pBuffPtr++; - hsai->XferCount--; - } -} - -/** - * @brief Tx Handler for Transmit in Interrupt mode for 16-Bit transfer. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_Transmit_IT16Bit(SAI_HandleTypeDef *hsai) -{ - if (hsai->XferCount == 0U) - { - /* Handle the end of the transmission */ - /* Disable FREQ and OVRUDR interrupts */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - hsai->State = HAL_SAI_STATE_READY; -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->TxCpltCallback(hsai); -#else - HAL_SAI_TxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - else - { - /* Write data on DR register */ - uint32_t temp; - temp = (uint32_t)(*hsai->pBuffPtr); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); - hsai->pBuffPtr++; - hsai->Instance->DR = temp; - hsai->XferCount--; - } -} - -/** - * @brief Tx Handler for Transmit in Interrupt mode for 32-Bit transfer. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_Transmit_IT32Bit(SAI_HandleTypeDef *hsai) -{ - if (hsai->XferCount == 0U) - { - /* Handle the end of the transmission */ - /* Disable FREQ and OVRUDR interrupts */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - hsai->State = HAL_SAI_STATE_READY; -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->TxCpltCallback(hsai); -#else - HAL_SAI_TxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } - else - { - /* Write data on DR register */ - uint32_t temp; - temp = (uint32_t)(*hsai->pBuffPtr); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 16); - hsai->pBuffPtr++; - temp |= ((uint32_t)(*hsai->pBuffPtr) << 24); - hsai->pBuffPtr++; - hsai->Instance->DR = temp; - hsai->XferCount--; - } -} - -/** - * @brief Rx Handler for Receive in Interrupt mode 8-Bit transfer. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_Receive_IT8Bit(SAI_HandleTypeDef *hsai) -{ - /* Receive data */ - *hsai->pBuffPtr = (uint8_t)hsai->Instance->DR; - hsai->pBuffPtr++; - hsai->XferCount--; - - /* Check end of the transfer */ - if (hsai->XferCount == 0U) - { - /* Disable TXE and OVRUDR interrupts */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - - /* Clear the SAI Overrun flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); - - hsai->State = HAL_SAI_STATE_READY; -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->RxCpltCallback(hsai); -#else - HAL_SAI_RxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Rx Handler for Receive in Interrupt mode for 16-Bit transfer. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_Receive_IT16Bit(SAI_HandleTypeDef *hsai) -{ - uint32_t temp; - - /* Receive data */ - temp = hsai->Instance->DR; - *hsai->pBuffPtr = (uint8_t)temp; - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 8); - hsai->pBuffPtr++; - hsai->XferCount--; - - /* Check end of the transfer */ - if (hsai->XferCount == 0U) - { - /* Disable TXE and OVRUDR interrupts */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - - /* Clear the SAI Overrun flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); - - hsai->State = HAL_SAI_STATE_READY; -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->RxCpltCallback(hsai); -#else - HAL_SAI_RxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Rx Handler for Receive in Interrupt mode for 32-Bit transfer. - * @param hsai pointer to a SAI_HandleTypeDef structure that contains - * the configuration information for SAI module. - * @retval None - */ -static void SAI_Receive_IT32Bit(SAI_HandleTypeDef *hsai) -{ - uint32_t temp; - - /* Receive data */ - temp = hsai->Instance->DR; - *hsai->pBuffPtr = (uint8_t)temp; - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 8); - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 16); - hsai->pBuffPtr++; - *hsai->pBuffPtr = (uint8_t)(temp >> 24); - hsai->pBuffPtr++; - hsai->XferCount--; - - /* Check end of the transfer */ - if (hsai->XferCount == 0U) - { - /* Disable TXE and OVRUDR interrupts */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); - - /* Clear the SAI Overrun flag */ - __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); - - hsai->State = HAL_SAI_STATE_READY; -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->RxCpltCallback(hsai); -#else - HAL_SAI_RxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DMA SAI transmit process complete callback. - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SAI_DMATxCplt(DMA_HandleTypeDef *hdma) -{ - SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Check if DMA in circular mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - hsai->XferCount = 0; - - /* Disable SAI Tx DMA Request */ - hsai->Instance->CR1 &= (uint32_t)(~SAI_xCR1_DMAEN); - - /* Stop the interrupts error handling */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); - - hsai->State = HAL_SAI_STATE_READY; - } - -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->TxCpltCallback(hsai); -#else - HAL_SAI_TxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SAI transmit process half complete callback. - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SAI_DMATxHalfCplt(DMA_HandleTypeDef *hdma) -{ - SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->TxHalfCpltCallback(hsai); -#else - HAL_SAI_TxHalfCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SAI receive process complete callback. - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SAI_DMARxCplt(DMA_HandleTypeDef *hdma) -{ - SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Check if DMA in circular mode*/ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - /* Disable Rx DMA Request */ - hsai->Instance->CR1 &= (uint32_t)(~SAI_xCR1_DMAEN); - hsai->XferCount = 0; - - /* Stop the interrupts error handling */ - __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); - - hsai->State = HAL_SAI_STATE_READY; - } - -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->RxCpltCallback(hsai); -#else - HAL_SAI_RxCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SAI receive process half complete callback - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SAI_DMARxHalfCplt(DMA_HandleTypeDef *hdma) -{ - SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->RxHalfCpltCallback(hsai); -#else - HAL_SAI_RxHalfCpltCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SAI communication error callback. - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SAI_DMAError(DMA_HandleTypeDef *hdma) -{ - SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Set SAI error code */ - hsai->ErrorCode |= HAL_SAI_ERROR_DMA; - - /* Disable the SAI DMA request */ - hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; - - /* Disable SAI peripheral */ - /* No need to check return value because state will be updated and HAL_SAI_ErrorCallback will be called later */ - (void) SAI_Disable(hsai); - - /* Set the SAI state ready to be able to start again the process */ - hsai->State = HAL_SAI_STATE_READY; - - /* Initialize XferCount */ - hsai->XferCount = 0U; - - /* SAI error Callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SAI Abort callback. - * @param hdma pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SAI_DMAAbort(DMA_HandleTypeDef *hdma) -{ - SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable DMA request */ - hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; - - /* Disable all interrupts and clear all flags */ - hsai->Instance->IMR = 0U; - hsai->Instance->CLRFR = 0xFFFFFFFFU; - - if (hsai->ErrorCode != HAL_SAI_ERROR_WCKCFG) - { - /* Disable SAI peripheral */ - /* No need to check return value because state will be updated and HAL_SAI_ErrorCallback will be called later */ - (void) SAI_Disable(hsai); - - /* Flush the fifo */ - SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); - } - /* Set the SAI state to ready to be able to start again the process */ - hsai->State = HAL_SAI_STATE_READY; - - /* Initialize XferCount */ - hsai->XferCount = 0U; - - /* SAI error Callback */ -#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) - hsai->ErrorCallback(hsai); -#else - HAL_SAI_ErrorCallback(hsai); -#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ -} - -/** - * @} - */ - -#endif /* HAL_SAI_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_sai.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + + [..] + The SAI HAL driver can be used as follows: + + (#) Declare a SAI_HandleTypeDef handle structure (eg. SAI_HandleTypeDef hsai). + (#) Initialize the SAI low level resources by implementing 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. + + (#) The initialization can be done by two ways + (##) Expert mode : Initialize the structures Init, FrameInit and SlotInit and call HAL_SAI_Init(). + (##) Simplified mode : Initialize the high part of Init Structure and call HAL_SAI_InitProtocol(). + + [..] + (@) The specific SAI interrupts (FIFO request and Overrun underrun interrupt) + will be managed using the macros __HAL_SAI_ENABLE_IT() and __HAL_SAI_DISABLE_IT() + inside the transmit and receive process. + [..] + (@) Make sure that either: + (+@) PLLSAI1CLK output is configured or + (+@) PLLSAI2CLK output is configured or + (+@) PLLSAI3CLK output is configured or + (+@) External clock source is configured after setting correctly + the define constant EXTERNAL_SAI1_CLOCK_VALUE or EXTERNAL_SAI2_CLOCK_VALUE + in the stm32h7rsxx_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. + + [..] + (@) PDM interface can be activated through HAL_SAI_Init function. + Please note that PDM interface is only available for SAI1 sub-block A. + PDM microphone delays can be tuned with HAL_SAIEx_ConfigPdmMicDelay function. + + [..] + Three operation modes 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 flag 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 flag 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 additional function list *** + =============================================== + [..] + Below the list the others API available SAI HAL driver : + + (+) HAL_SAI_EnableTxMuteMode(): Enable the mute in tx mode + (+) HAL_SAI_DisableTxMuteMode(): Disable the mute in tx mode + (+) HAL_SAI_EnableRxMuteMode(): Enable the mute in Rx mode + (+) HAL_SAI_DisableRxMuteMode(): Disable the mute in Rx mode + (+) HAL_SAI_FlushRxFifo(): Flush the rx fifo. + (+) HAL_SAI_Abort(): Abort the current transfer + + *** SAI HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SAI 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 + + *** Callback registration *** + ============================= + [..] + The compilation define USE_HAL_SAI_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use functions HAL_SAI_RegisterCallback() to register a user callback. + + [..] + Function HAL_SAI_RegisterCallback() allows to register following callbacks: + (+) RxCpltCallback : SAI receive complete. + (+) RxHalfCpltCallback : SAI receive half complete. + (+) TxCpltCallback : SAI transmit complete. + (+) TxHalfCpltCallback : SAI transmit half complete. + (+) ErrorCallback : SAI error. + (+) MspInitCallback : SAI MspInit. + (+) MspDeInitCallback : SAI MspDeInit. + [..] + This function takes as parameters the HAL peripheral handle, the callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_SAI_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_SAI_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the callback ID. + [..] + This function allows to reset following callbacks: + (+) RxCpltCallback : SAI receive complete. + (+) RxHalfCpltCallback : SAI receive half complete. + (+) TxCpltCallback : SAI transmit complete. + (+) TxHalfCpltCallback : SAI transmit half complete. + (+) ErrorCallback : SAI error. + (+) MspInitCallback : SAI MspInit. + (+) MspDeInitCallback : SAI MspDeInit. + + [..] + By default, after the HAL_SAI_Init and if the state is HAL_SAI_STATE_RESET + all callbacks are reset to the corresponding legacy weak functions: + examples HAL_SAI_RxCpltCallback(), HAL_SAI_ErrorCallback(). + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak functions in the HAL_SAI_Init + and HAL_SAI_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_SAI_Init and HAL_SAI_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SAI_RegisterCallback before calling HAL_SAI_DeInit + or HAL_SAI_Init function. + + [..] + When the compilation define USE_HAL_SAI_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak callbacks are used. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SAI SAI + * @brief SAI HAL module driver + * @{ + */ + +#ifdef HAL_SAI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/** @defgroup SAI_Private_Typedefs SAI Private Typedefs + * @{ + */ +typedef enum +{ + SAI_MODE_DMA, + SAI_MODE_IT +} SAI_ModeTypedef; +/** + * @} + */ + +/* Private define ------------------------------------------------------------*/ +/** @defgroup SAI_Private_Constants SAI Private Constants + * @{ + */ +#define SAI_DEFAULT_TIMEOUT 4U +#define SAI_LONG_TIMEOUT 1000U +#define SAI_SPDIF_FRAME_LENGTH 64U +#define SAI_AC97_FRAME_LENGTH 256U +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup SAI_Private_Functions SAI Private Functions + * @{ + */ +static void SAI_FillFifo(SAI_HandleTypeDef *hsai); +static uint32_t SAI_InterruptFlag(const SAI_HandleTypeDef *hsai, SAI_ModeTypedef mode); +static HAL_StatusTypeDef SAI_InitI2S(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot); +static HAL_StatusTypeDef SAI_InitPCM(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot); + +static HAL_StatusTypeDef SAI_Disable(SAI_HandleTypeDef *hsai); +static void SAI_Transmit_IT8Bit(SAI_HandleTypeDef *hsai); +static void SAI_Transmit_IT16Bit(SAI_HandleTypeDef *hsai); +static void SAI_Transmit_IT32Bit(SAI_HandleTypeDef *hsai); +static void SAI_Receive_IT8Bit(SAI_HandleTypeDef *hsai); +static void SAI_Receive_IT16Bit(SAI_HandleTypeDef *hsai); +static void SAI_Receive_IT32Bit(SAI_HandleTypeDef *hsai); + +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); +static void SAI_DMAAbort(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ +/** @defgroup SAI_Exported_Functions SAI Exported Functions + * @{ + */ + +/** @defgroup SAI_Exported_Functions_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 + (++) PDM Config + + (+) Call the function HAL_SAI_DeInit() to restore the default configuration + of the selected SAI peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the structure FrameInit, SlotInit and the low part of + * Init according to the specified parameters and call the function + * HAL_SAI_Init to initialize the SAI block. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @param protocol one of the supported protocol @ref SAI_Protocol + * @param datasize one of the supported datasize @ref SAI_Protocol_DataSize + * the configuration information for SAI module. + * @param nbslot Number of slot. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_InitProtocol(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot) +{ + HAL_StatusTypeDef status; + + /* Check the parameters */ + assert_param(IS_SAI_SUPPORTED_PROTOCOL(protocol)); + assert_param(IS_SAI_PROTOCOL_DATASIZE(datasize)); + + switch (protocol) + { + case SAI_I2S_STANDARD : + case SAI_I2S_MSBJUSTIFIED : + case SAI_I2S_LSBJUSTIFIED : + status = SAI_InitI2S(hsai, protocol, datasize, nbslot); + break; + case SAI_PCM_LONG : + case SAI_PCM_SHORT : + status = SAI_InitPCM(hsai, protocol, datasize, nbslot); + break; + default : + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + status = HAL_SAI_Init(hsai); + } + + return status; +} + +/** + * @brief Initialize the SAI according to the specified parameters. + * in the SAI_InitTypeDef structure and initialize the associated handle. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_Init(SAI_HandleTypeDef *hsai) +{ + uint32_t tmpregisterGCR; + uint32_t ckstr_bits; + uint32_t syncen_bits; + + /* Check the SAI handle allocation */ + if (hsai == NULL) + { + return HAL_ERROR; + } + + /* check the instance */ + assert_param(IS_SAI_ALL_INSTANCE(hsai->Instance)); + + /* Check the SAI Block parameters */ + assert_param(IS_SAI_AUDIO_FREQUENCY(hsai->Init.AudioFrequency)); + 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_MCK_OUTPUT(hsai->Init.MckOutput)); + 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_MONO_STEREO_MODE(hsai->Init.MonoStereoMode)); + assert_param(IS_SAI_BLOCK_COMPANDING_MODE(hsai->Init.CompandingMode)); + assert_param(IS_SAI_BLOCK_TRISTATE_MANAGEMENT(hsai->Init.TriState)); + assert_param(IS_SAI_BLOCK_SYNCEXT(hsai->Init.SynchroExt)); + assert_param(IS_SAI_BLOCK_MCK_OVERSAMPLING(hsai->Init.MckOverSampling)); + + /* 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)); + + /* Check the SAI PDM parameters */ + assert_param(IS_FUNCTIONAL_STATE(hsai->Init.PdmInit.Activation)); + if (hsai->Init.PdmInit.Activation == ENABLE) + { + assert_param(IS_SAI_PDM_MIC_PAIRS_NUMBER(hsai->Init.PdmInit.MicPairsNbr)); + assert_param(IS_SAI_PDM_CLOCK_ENABLE(hsai->Init.PdmInit.ClockEnable)); + /* Check that SAI sub-block is SAI1 sub-block A, in master RX mode with free protocol */ + if ((hsai->Instance != SAI1_Block_A) || + (hsai->Init.AudioMode != SAI_MODEMASTER_RX) || + (hsai->Init.Protocol != SAI_FREE_PROTOCOL)) + { + return HAL_ERROR; + } + } + + if (hsai->State == HAL_SAI_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsai->Lock = HAL_UNLOCKED; + +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + /* Reset callback pointers to the weak predefined callbacks */ + hsai->RxCpltCallback = HAL_SAI_RxCpltCallback; + hsai->RxHalfCpltCallback = HAL_SAI_RxHalfCpltCallback; + hsai->TxCpltCallback = HAL_SAI_TxCpltCallback; + hsai->TxHalfCpltCallback = HAL_SAI_TxHalfCpltCallback; + hsai->ErrorCallback = HAL_SAI_ErrorCallback; + + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + if (hsai->MspInitCallback == NULL) + { + hsai->MspInitCallback = HAL_SAI_MspInit; + } + hsai->MspInitCallback(hsai); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_SAI_MspInit(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + + /* Disable the selected SAI peripheral */ + if (SAI_Disable(hsai) != HAL_OK) + { + return HAL_ERROR; + } + + hsai->State = HAL_SAI_STATE_BUSY; + + /* SAI Block Synchro Configuration -----------------------------------------*/ + /* This setting must be done with both audio block (A & B) disabled */ + switch (hsai->Init.SynchroExt) + { + case SAI_SYNCEXT_DISABLE : + tmpregisterGCR = 0; + break; + case SAI_SYNCEXT_OUTBLOCKA_ENABLE : + tmpregisterGCR = SAI_GCR_SYNCOUT_0; + break; + case SAI_SYNCEXT_OUTBLOCKB_ENABLE : + tmpregisterGCR = SAI_GCR_SYNCOUT_1; + break; + default : + tmpregisterGCR = 0; + break; + } + + switch (hsai->Init.Synchro) + { + case SAI_ASYNCHRONOUS : + syncen_bits = 0; + break; + case SAI_SYNCHRONOUS : + syncen_bits = SAI_xCR1_SYNCEN_0; + break; + case SAI_SYNCHRONOUS_EXT_SAI1 : + syncen_bits = SAI_xCR1_SYNCEN_1; + break; + case SAI_SYNCHRONOUS_EXT_SAI2 : + syncen_bits = SAI_xCR1_SYNCEN_1; + tmpregisterGCR |= SAI_GCR_SYNCIN_0; + break; + default : + syncen_bits = 0; + break; + } + + if ((hsai->Instance == SAI1_Block_A) || (hsai->Instance == SAI1_Block_B)) + { + SAI1->GCR = tmpregisterGCR; + } + else + { + SAI2->GCR = tmpregisterGCR; + } + + if (hsai->Init.AudioFrequency != SAI_AUDIO_FREQUENCY_MCKDIV) + { + uint32_t freq = 0; + uint32_t tmpval; + + /* In this case, the MCKDIV value is calculated to get AudioFrequency */ + if ((hsai->Instance == SAI1_Block_A) || (hsai->Instance == SAI1_Block_B)) + { + freq = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SAI1); + } + if ((hsai->Instance == SAI2_Block_A) || (hsai->Instance == SAI2_Block_B)) + { + freq = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SAI2); + } + + /* Configure Master Clock Divider using the following formula : + - If NODIV = 1 : + MCKDIV[5:0] = SAI_CK_x / (FS * (FRL + 1)) + - If NODIV = 0 : + MCKDIV[5:0] = SAI_CK_x / (FS * (OSR + 1) * 256) */ + if (hsai->Init.NoDivider == SAI_MASTERDIVIDER_DISABLE) + { + /* NODIV = 1 */ + uint32_t tmpframelength; + + if (hsai->Init.Protocol == SAI_SPDIF_PROTOCOL) + { + /* For SPDIF protocol, frame length is set by hardware to 64 */ + tmpframelength = SAI_SPDIF_FRAME_LENGTH; + } + else if (hsai->Init.Protocol == SAI_AC97_PROTOCOL) + { + /* For AC97 protocol, frame length is set by hardware to 256 */ + tmpframelength = SAI_AC97_FRAME_LENGTH; + } + else + { + /* For free protocol, frame length is set by user */ + tmpframelength = hsai->FrameInit.FrameLength; + } + + /* (freq x 10) to keep Significant digits */ + tmpval = (freq * 10U) / (hsai->Init.AudioFrequency * tmpframelength); + } + else + { + /* NODIV = 0 */ + uint32_t tmposr; + tmposr = (hsai->Init.MckOverSampling == SAI_MCK_OVERSAMPLING_ENABLE) ? 2U : 1U; + /* (freq x 10) to keep Significant digits */ + tmpval = (freq * 10U) / (hsai->Init.AudioFrequency * tmposr * 256U); + } + hsai->Init.Mckdiv = tmpval / 10U; + + /* Round result to the nearest integer */ + if ((tmpval % 10U) > 8U) + { + hsai->Init.Mckdiv += 1U; + } + + /* For SPDIF protocol, SAI shall provide a bit clock twice faster the symbol-rate */ + if (hsai->Init.Protocol == SAI_SPDIF_PROTOCOL) + { + hsai->Init.Mckdiv = hsai->Init.Mckdiv >> 1; + } + } + + /* Check the SAI Block master clock divider parameter */ + assert_param(IS_SAI_BLOCK_MASTER_DIVIDER(hsai->Init.Mckdiv)); + + /* Compute CKSTR bits of SAI CR1 according ClockStrobing and AudioMode */ + if ((hsai->Init.AudioMode == SAI_MODEMASTER_TX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) + { + /* Transmit */ + ckstr_bits = (hsai->Init.ClockStrobing == SAI_CLOCKSTROBING_RISINGEDGE) ? 0U : SAI_xCR1_CKSTR; + } + else + { + /* Receive */ + ckstr_bits = (hsai->Init.ClockStrobing == SAI_CLOCKSTROBING_RISINGEDGE) ? SAI_xCR1_CKSTR : 0U; + } + + /* SAI Block Configuration -------------------------------------------------*/ + /* SAI CR1 Configuration */ + hsai->Instance->CR1 &= ~(SAI_xCR1_MODE | SAI_xCR1_PRTCFG | SAI_xCR1_DS | \ + SAI_xCR1_LSBFIRST | SAI_xCR1_CKSTR | SAI_xCR1_SYNCEN | \ + SAI_xCR1_MONO | SAI_xCR1_OUTDRIV | SAI_xCR1_DMAEN | \ + SAI_xCR1_NODIV | SAI_xCR1_MCKDIV | SAI_xCR1_OSR | \ + SAI_xCR1_MCKEN); + + hsai->Instance->CR1 |= (hsai->Init.AudioMode | hsai->Init.Protocol | \ + hsai->Init.DataSize | hsai->Init.FirstBit | \ + ckstr_bits | syncen_bits | \ + hsai->Init.MonoStereoMode | hsai->Init.OutputDrive | \ + hsai->Init.NoDivider | (hsai->Init.Mckdiv << 20) | \ + hsai->Init.MckOverSampling | hsai->Init.MckOutput); + + /* SAI CR2 Configuration */ + hsai->Instance->CR2 &= ~(SAI_xCR2_FTH | SAI_xCR2_FFLUSH | SAI_xCR2_COMP | SAI_xCR2_CPL); + hsai->Instance->CR2 |= (hsai->Init.FIFOThreshold | hsai->Init.CompandingMode | hsai->Init.TriState); + + /* SAI Frame Configuration -----------------------------------------*/ + hsai->Instance->FRCR &= (~(SAI_xFRCR_FRL | SAI_xFRCR_FSALL | SAI_xFRCR_FSDEF | \ + SAI_xFRCR_FSPOL | SAI_xFRCR_FSOFF)); + hsai->Instance->FRCR |= ((hsai->FrameInit.FrameLength - 1U) | + hsai->FrameInit.FSOffset | + hsai->FrameInit.FSDefinition | + hsai->FrameInit.FSPolarity | + ((hsai->FrameInit.ActiveFrameLength - 1U) << 8)); + + /* SAI Block_x SLOT Configuration ------------------------------------------*/ + /* This register has no meaning in AC 97 and SPDIF audio protocol */ + hsai->Instance->SLOTR &= (~(SAI_xSLOTR_FBOFF | SAI_xSLOTR_SLOTSZ | \ + SAI_xSLOTR_NBSLOT | SAI_xSLOTR_SLOTEN)); + + hsai->Instance->SLOTR |= hsai->SlotInit.FirstBitOffset | hsai->SlotInit.SlotSize | \ + (hsai->SlotInit.SlotActive << 16) | ((hsai->SlotInit.SlotNumber - 1U) << 8); + + /* SAI PDM Configuration ---------------------------------------------------*/ + if (hsai->Instance == SAI1_Block_A) + { + /* Disable PDM interface */ + SAI1->PDMCR &= ~(SAI_PDMCR_PDMEN); + if (hsai->Init.PdmInit.Activation == ENABLE) + { + /* Configure and enable PDM interface */ + SAI1->PDMCR = (hsai->Init.PdmInit.ClockEnable | + ((hsai->Init.PdmInit.MicPairsNbr - 1U) << SAI_PDMCR_MICNBR_Pos)); + SAI1->PDMCR |= SAI_PDMCR_PDMEN; + } + } + + /* Initialize the error code */ + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + + /* Initialize the SAI state */ + hsai->State = HAL_SAI_STATE_READY; + + /* Release Lock */ + __HAL_UNLOCK(hsai); + + return HAL_OK; +} + +/** + * @brief DeInitialize the SAI peripheral. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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; + + /* Disabled All interrupt and clear all the flag */ + hsai->Instance->IMR = 0; + hsai->Instance->CLRFR = 0xFFFFFFFFU; + + /* Disable the SAI */ + if (SAI_Disable(hsai) != HAL_OK) + { + /* Reset SAI state to ready */ + hsai->State = HAL_SAI_STATE_READY; + + /* Release Lock */ + __HAL_UNLOCK(hsai); + + return HAL_ERROR; + } + + /* Flush the fifo */ + SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); + + /* Disable SAI PDM interface */ + if (hsai->Instance == SAI1_Block_A) + { + /* Reset PDM delays */ + SAI1->PDMDLY = 0U; + + /* Disable PDM interface */ + SAI1->PDMCR &= ~(SAI_PDMCR_PDMEN); + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + if (hsai->MspDeInitCallback == NULL) + { + hsai->MspDeInitCallback = HAL_SAI_MspDeInit; + } + hsai->MspDeInitCallback(hsai); +#else + HAL_SAI_MspDeInit(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + + /* 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 Initialize the SAI MSP. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_MspInit(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 DeInitialize the SAI MSP. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_MspDeInit(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsai); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SAI_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) +/** + * @brief Register a user SAI callback + * to be used instead of the weak predefined callback. + * @param hsai SAI handle. + * @param CallbackID ID of the callback to be registered. + * This parameter can be one of the following values: + * @arg @ref HAL_SAI_RX_COMPLETE_CB_ID receive complete callback ID. + * @arg @ref HAL_SAI_RX_HALFCOMPLETE_CB_ID receive half complete callback ID. + * @arg @ref HAL_SAI_TX_COMPLETE_CB_ID transmit complete callback ID. + * @arg @ref HAL_SAI_TX_HALFCOMPLETE_CB_ID transmit half complete callback ID. + * @arg @ref HAL_SAI_ERROR_CB_ID error callback ID. + * @arg @ref HAL_SAI_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_SAI_MSPDEINIT_CB_ID MSP de-init callback ID. + * @param pCallback pointer to the callback function. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_SAI_RegisterCallback(SAI_HandleTypeDef *hsai, + HAL_SAI_CallbackIDTypeDef CallbackID, + pSAI_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + else + { + if (HAL_SAI_STATE_READY == hsai->State) + { + switch (CallbackID) + { + case HAL_SAI_RX_COMPLETE_CB_ID : + hsai->RxCpltCallback = pCallback; + break; + case HAL_SAI_RX_HALFCOMPLETE_CB_ID : + hsai->RxHalfCpltCallback = pCallback; + break; + case HAL_SAI_TX_COMPLETE_CB_ID : + hsai->TxCpltCallback = pCallback; + break; + case HAL_SAI_TX_HALFCOMPLETE_CB_ID : + hsai->TxHalfCpltCallback = pCallback; + break; + case HAL_SAI_ERROR_CB_ID : + hsai->ErrorCallback = pCallback; + break; + case HAL_SAI_MSPINIT_CB_ID : + hsai->MspInitCallback = pCallback; + break; + case HAL_SAI_MSPDEINIT_CB_ID : + hsai->MspDeInitCallback = pCallback; + break; + default : + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SAI_STATE_RESET == hsai->State) + { + switch (CallbackID) + { + case HAL_SAI_MSPINIT_CB_ID : + hsai->MspInitCallback = pCallback; + break; + case HAL_SAI_MSPDEINIT_CB_ID : + hsai->MspDeInitCallback = pCallback; + break; + default : + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + } + return status; +} + +/** + * @brief Unregister a user SAI callback. + * SAI callback is redirected to the weak predefined callback. + * @param hsai SAI handle. + * @param CallbackID ID of the callback to be unregistered. + * This parameter can be one of the following values: + * @arg @ref HAL_SAI_RX_COMPLETE_CB_ID receive complete callback ID. + * @arg @ref HAL_SAI_RX_HALFCOMPLETE_CB_ID receive half complete callback ID. + * @arg @ref HAL_SAI_TX_COMPLETE_CB_ID transmit complete callback ID. + * @arg @ref HAL_SAI_TX_HALFCOMPLETE_CB_ID transmit half complete callback ID. + * @arg @ref HAL_SAI_ERROR_CB_ID error callback ID. + * @arg @ref HAL_SAI_MSPINIT_CB_ID MSP init callback ID. + * @arg @ref HAL_SAI_MSPDEINIT_CB_ID MSP de-init callback ID. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_SAI_UnRegisterCallback(SAI_HandleTypeDef *hsai, + HAL_SAI_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_SAI_STATE_READY == hsai->State) + { + switch (CallbackID) + { + case HAL_SAI_RX_COMPLETE_CB_ID : + hsai->RxCpltCallback = HAL_SAI_RxCpltCallback; + break; + case HAL_SAI_RX_HALFCOMPLETE_CB_ID : + hsai->RxHalfCpltCallback = HAL_SAI_RxHalfCpltCallback; + break; + case HAL_SAI_TX_COMPLETE_CB_ID : + hsai->TxCpltCallback = HAL_SAI_TxCpltCallback; + break; + case HAL_SAI_TX_HALFCOMPLETE_CB_ID : + hsai->TxHalfCpltCallback = HAL_SAI_TxHalfCpltCallback; + break; + case HAL_SAI_ERROR_CB_ID : + hsai->ErrorCallback = HAL_SAI_ErrorCallback; + break; + case HAL_SAI_MSPINIT_CB_ID : + hsai->MspInitCallback = HAL_SAI_MspInit; + break; + case HAL_SAI_MSPDEINIT_CB_ID : + hsai->MspDeInitCallback = HAL_SAI_MspDeInit; + break; + default : + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SAI_STATE_RESET == hsai->State) + { + switch (CallbackID) + { + case HAL_SAI_MSPINIT_CB_ID : + hsai->MspInitCallback = HAL_SAI_MspInit; + break; + case HAL_SAI_MSPDEINIT_CB_ID : + hsai->MspDeInitCallback = HAL_SAI_MspDeInit; + break; + default : + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update the error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + return status; +} +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SAI_Exported_Functions_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 are two modes 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() + + (+) Non Blocking mode functions with Interrupt are : + (++) HAL_SAI_Transmit_IT() + (++) HAL_SAI_Receive_IT() + + (+) Non Blocking mode functions with DMA are : + (++) HAL_SAI_Transmit_DMA() + (++) HAL_SAI_Receive_DMA() + + (+) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (++) HAL_SAI_TxCpltCallback() + (++) HAL_SAI_RxCpltCallback() + (++) HAL_SAI_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + uint32_t temp; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hsai->State == HAL_SAI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsai); + + hsai->XferSize = Size; + hsai->XferCount = Size; + hsai->pBuffPtr = pData; + hsai->State = HAL_SAI_STATE_BUSY_TX; + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + + /* Check if the SAI is already enabled */ + if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) + { + /* fill the fifo with data before to enabled the SAI */ + SAI_FillFifo(hsai); + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + + while (hsai->XferCount > 0U) + { + /* Write data if the FIFO is not full */ + if ((hsai->Instance->SR & SAI_xSR_FLVL) != SAI_FIFOSTATUS_FULL) + { + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + hsai->Instance->DR = *hsai->pBuffPtr; + hsai->pBuffPtr++; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + temp = (uint32_t)(*hsai->pBuffPtr); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); + hsai->pBuffPtr++; + hsai->Instance->DR = temp; + } + else + { + temp = (uint32_t)(*hsai->pBuffPtr); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 16); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 24); + hsai->pBuffPtr++; + hsai->Instance->DR = temp; + } + hsai->XferCount--; + } + else + { + /* Check for the Timeout */ + if ((((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) && (Timeout != HAL_MAX_DELAY)) + { + /* Update error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; + + /* Clear all the flags */ + hsai->Instance->CLRFR = 0xFFFFFFFFU; + + /* Disable SAI peripheral */ + /* No need to check return value because state update, unlock and error return will be performed later */ + (void) SAI_Disable(hsai); + + /* Flush the fifo */ + SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); + + /* Change the SAI state */ + hsai->State = HAL_SAI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_ERROR; + } + } + } + + hsai->State = HAL_SAI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + uint32_t temp; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hsai->State == HAL_SAI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsai); + + hsai->pBuffPtr = pData; + hsai->XferSize = Size; + hsai->XferCount = Size; + hsai->State = HAL_SAI_STATE_BUSY_RX; + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + + /* Check if the SAI is already enabled */ + if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) + { + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + + /* Receive data */ + while (hsai->XferCount > 0U) + { + if ((hsai->Instance->SR & SAI_xSR_FLVL) != SAI_FIFOSTATUS_EMPTY) + { + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + *hsai->pBuffPtr = (uint8_t)hsai->Instance->DR; + hsai->pBuffPtr++; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + temp = hsai->Instance->DR; + *hsai->pBuffPtr = (uint8_t)temp; + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 8); + hsai->pBuffPtr++; + } + else + { + temp = hsai->Instance->DR; + *hsai->pBuffPtr = (uint8_t)temp; + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 8); + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 16); + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 24); + hsai->pBuffPtr++; + } + hsai->XferCount--; + } + else + { + /* Check for the Timeout */ + if ((((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) && (Timeout != HAL_MAX_DELAY)) + { + /* Update error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; + + /* Clear all the flags */ + hsai->Instance->CLRFR = 0xFFFFFFFFU; + + /* Disable SAI peripheral */ + /* No need to check return value because state update, unlock and error return will be performed later */ + (void) SAI_Disable(hsai); + + /* Flush the fifo */ + SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); + + /* Change the SAI state */ + hsai->State = HAL_SAI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_ERROR; + } + } + } + + hsai->State = HAL_SAI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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, uint8_t *pData, uint16_t Size) +{ + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hsai->State == HAL_SAI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsai); + + hsai->pBuffPtr = pData; + hsai->XferSize = Size; + hsai->XferCount = Size; + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + hsai->State = HAL_SAI_STATE_BUSY_TX; + + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + hsai->InterruptServiceRoutine = SAI_Transmit_IT8Bit; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + hsai->InterruptServiceRoutine = SAI_Transmit_IT16Bit; + } + else + { + hsai->InterruptServiceRoutine = SAI_Transmit_IT32Bit; + } + + /* Fill the fifo before starting the communication */ + SAI_FillFifo(hsai); + + /* Enable FRQ and OVRUDR interrupts */ + __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + + /* Check if the SAI is already enabled */ + if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) + { + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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, uint8_t *pData, uint16_t Size) +{ + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hsai->State == HAL_SAI_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsai); + + hsai->pBuffPtr = pData; + hsai->XferSize = Size; + hsai->XferCount = Size; + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + hsai->State = HAL_SAI_STATE_BUSY_RX; + + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + hsai->InterruptServiceRoutine = SAI_Receive_IT8Bit; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + hsai->InterruptServiceRoutine = SAI_Receive_IT16Bit; + } + else + { + hsai->InterruptServiceRoutine = SAI_Receive_IT32Bit; + } + + /* Enable TXE and OVRUDR interrupts */ + __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + + /* Check if the SAI is already enabled */ + if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) + { + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pause the audio stream playing from the Media. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +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 Resume the audio stream playing from the Media. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +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) == 0U) + { + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; +} + +/** + * @brief Stop the audio stream playing from the Media. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_DMAStop(SAI_HandleTypeDef *hsai) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(hsai); + + /* Disable SAI peripheral */ + if (SAI_Disable(hsai) != HAL_OK) + { + status = HAL_ERROR; + } + + /* Disable the SAI DMA request */ + hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; + + /* Abort the SAI Tx DMA Stream */ + if ((hsai->State == HAL_SAI_STATE_BUSY_TX) && (hsai->hdmatx != NULL)) + { + if (HAL_DMA_Abort(hsai->hdmatx) != HAL_OK) + { + /* If the DMA Tx errorCode is different from DMA No Transfer then return Error */ + if (hsai->hdmatx->ErrorCode != HAL_DMA_ERROR_NO_XFER) + { + status = HAL_ERROR; + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + } + } + } + + /* Abort the SAI Rx DMA Stream */ + if ((hsai->State == HAL_SAI_STATE_BUSY_RX) && (hsai->hdmarx != NULL)) + { + if (HAL_DMA_Abort(hsai->hdmarx) != HAL_OK) + { + /* If the DMA Rx errorCode is different from DMA No Transfer then return Error */ + if (hsai->hdmarx->ErrorCode != HAL_DMA_ERROR_NO_XFER) + { + status = HAL_ERROR; + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + } + } + } + + /* Flush the fifo */ + SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); + + /* Set hsai state to ready */ + hsai->State = HAL_SAI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return status; +} + +/** + * @brief Abort the current transfer and disable the SAI. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_Abort(SAI_HandleTypeDef *hsai) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(hsai); + + /* Disable SAI peripheral */ + if (SAI_Disable(hsai) != HAL_OK) + { + status = HAL_ERROR; + } + + /* Check SAI DMA is enabled or not */ + if ((hsai->Instance->CR1 & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) + { + /* Disable the SAI DMA request */ + hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; + + /* Abort the SAI Tx DMA Stream */ + if ((hsai->State == HAL_SAI_STATE_BUSY_TX) && (hsai->hdmatx != NULL)) + { + if (HAL_DMA_Abort(hsai->hdmatx) != HAL_OK) + { + /* If the DMA Tx errorCode is different from DMA No Transfer then return Error */ + if (hsai->hdmatx->ErrorCode != HAL_DMA_ERROR_NO_XFER) + { + status = HAL_ERROR; + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + } + } + } + + /* Abort the SAI Rx DMA Stream */ + if ((hsai->State == HAL_SAI_STATE_BUSY_RX) && (hsai->hdmarx != NULL)) + { + if (HAL_DMA_Abort(hsai->hdmarx) != HAL_OK) + { + /* If the DMA Rx errorCode is different from DMA No Transfer then return Error */ + if (hsai->hdmarx->ErrorCode != HAL_DMA_ERROR_NO_XFER) + { + status = HAL_ERROR; + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + } + } + } + } + + /* Disabled All interrupt and clear all the flag */ + hsai->Instance->IMR = 0; + hsai->Instance->CLRFR = 0xFFFFFFFFU; + + /* Flush the fifo */ + SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); + + /* Set hsai state to ready */ + hsai->State = HAL_SAI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return status; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hsai->State == HAL_SAI_STATE_READY) + { + uint32_t dmaSrcSize; + + /* Process Locked */ + __HAL_LOCK(hsai); + + hsai->pBuffPtr = pData; + hsai->XferSize = Size; + hsai->XferCount = Size; + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + hsai->State = HAL_SAI_STATE_BUSY_TX; + + /* Set the SAI Tx DMA Half transfer 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; + + /* Set the DMA Tx abort callback */ + hsai->hdmatx->XferAbortCallback = NULL; + + /* For transmission, the DMA source is data buffer. + We have to compute DMA size of a source block transfer in bytes according SAI data size. */ + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + dmaSrcSize = (uint32_t) Size; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + dmaSrcSize = 2U * (uint32_t) Size; + } + else + { + dmaSrcSize = 4U * (uint32_t) Size; + } + + /* Enable the Tx DMA Stream */ + if ((hsai->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hsai->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hsai->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = dmaSrcSize; + + /* Set DMA source address */ + hsai->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hsai->pBuffPtr; + + /* Set DMA destination address */ + hsai->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hsai->Instance->DR; + + status = HAL_DMAEx_List_Start_IT(hsai->hdmatx); + } + else + { + __HAL_UNLOCK(hsai); + return HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hsai->hdmatx, (uint32_t)hsai->pBuffPtr, (uint32_t)&hsai->Instance->DR, dmaSrcSize); + } + + if (status != HAL_OK) + { + __HAL_UNLOCK(hsai); + return HAL_ERROR; + } + + /* Enable the interrupts for error handling */ + __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); + + /* Enable SAI Tx DMA Request */ + hsai->Instance->CR1 |= SAI_xCR1_DMAEN; + + /* Wait until FIFO is not empty */ + while ((hsai->Instance->SR & SAI_xSR_FLVL) == SAI_FIFOSTATUS_EMPTY) + { + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > SAI_LONG_TIMEOUT) + { + /* Update error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_TIMEOUT; + } + } + + /* Check if the SAI is already enabled */ + if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) + { + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @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, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hsai->State == HAL_SAI_STATE_READY) + { + uint32_t dmaSrcSize; + + /* Process Locked */ + __HAL_LOCK(hsai); + + hsai->pBuffPtr = pData; + hsai->XferSize = Size; + hsai->XferCount = Size; + hsai->ErrorCode = HAL_SAI_ERROR_NONE; + hsai->State = HAL_SAI_STATE_BUSY_RX; + + /* Set the SAI Rx DMA Half transfer complete callback */ + hsai->hdmarx->XferHalfCpltCallback = SAI_DMARxHalfCplt; + + /* Set the SAI Rx DMA transfer complete callback */ + hsai->hdmarx->XferCpltCallback = SAI_DMARxCplt; + + /* Set the DMA error callback */ + hsai->hdmarx->XferErrorCallback = SAI_DMAError; + + /* Set the DMA Rx abort callback */ + hsai->hdmarx->XferAbortCallback = NULL; + + /* For reception, the DMA source is SAI DR register. + We have to compute DMA size of a source block transfer in bytes according SAI data size. */ + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + dmaSrcSize = (uint32_t) Size; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + dmaSrcSize = 2U * (uint32_t) Size; + } + else + { + dmaSrcSize = 4U * (uint32_t) Size; + } + + /* Enable the Rx DMA Stream */ + if ((hsai->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hsai->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hsai->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = dmaSrcSize; + + /* Set DMA source address */ + hsai->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hsai->Instance->DR; + + /* Set DMA destination address */ + hsai->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hsai->pBuffPtr; + + status = HAL_DMAEx_List_Start_IT(hsai->hdmarx); + } + else + { + __HAL_UNLOCK(hsai); + return HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hsai->hdmarx, (uint32_t)&hsai->Instance->DR, (uint32_t)hsai->pBuffPtr, dmaSrcSize); + } + + if (status != HAL_OK) + { + __HAL_UNLOCK(hsai); + return HAL_ERROR; + } + + /* Enable the interrupts for error handling */ + __HAL_SAI_ENABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); + + /* Enable SAI Rx DMA Request */ + hsai->Instance->CR1 |= SAI_xCR1_DMAEN; + + /* Check if the SAI is already enabled */ + if ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) == 0U) + { + /* Enable SAI peripheral */ + __HAL_SAI_ENABLE(hsai); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsai); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Enable the Tx mute mode. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @param val value sent during the mute @ref SAI_Block_Mute_Value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_EnableTxMuteMode(SAI_HandleTypeDef *hsai, uint16_t val) +{ + assert_param(IS_SAI_BLOCK_MUTE_VALUE(val)); + + if (hsai->State != HAL_SAI_STATE_RESET) + { + CLEAR_BIT(hsai->Instance->CR2, SAI_xCR2_MUTEVAL | SAI_xCR2_MUTE); + SET_BIT(hsai->Instance->CR2, SAI_xCR2_MUTE | (uint32_t)val); + return HAL_OK; + } + return HAL_ERROR; +} + +/** + * @brief Disable the Tx mute mode. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_DisableTxMuteMode(SAI_HandleTypeDef *hsai) +{ + if (hsai->State != HAL_SAI_STATE_RESET) + { + CLEAR_BIT(hsai->Instance->CR2, SAI_xCR2_MUTEVAL | SAI_xCR2_MUTE); + return HAL_OK; + } + return HAL_ERROR; +} + +/** + * @brief Enable the Rx mute detection. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @param callback function called when the mute is detected. + * @param counter number a data before mute detection max 63. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_EnableRxMuteMode(SAI_HandleTypeDef *hsai, SAIcallback callback, uint16_t counter) +{ + assert_param(IS_SAI_BLOCK_MUTE_COUNTER(counter)); + + if (hsai->State != HAL_SAI_STATE_RESET) + { + /* set the mute counter */ + CLEAR_BIT(hsai->Instance->CR2, SAI_xCR2_MUTECNT); + SET_BIT(hsai->Instance->CR2, (uint32_t)((uint32_t)counter << SAI_xCR2_MUTECNT_Pos)); + hsai->mutecallback = callback; + /* enable the IT interrupt */ + __HAL_SAI_ENABLE_IT(hsai, SAI_IT_MUTEDET); + return HAL_OK; + } + return HAL_ERROR; +} + +/** + * @brief Disable the Rx mute detection. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAI_DisableRxMuteMode(SAI_HandleTypeDef *hsai) +{ + if (hsai->State != HAL_SAI_STATE_RESET) + { + /* set the mutecallback to NULL */ + hsai->mutecallback = NULL; + /* enable the IT interrupt */ + __HAL_SAI_DISABLE_IT(hsai, SAI_IT_MUTEDET); + return HAL_OK; + } + return HAL_ERROR; +} + +/** + * @brief Handle SAI interrupt request. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +void HAL_SAI_IRQHandler(SAI_HandleTypeDef *hsai) +{ + if (hsai->State != HAL_SAI_STATE_RESET) + { + uint32_t itflags = hsai->Instance->SR; + uint32_t itsources = hsai->Instance->IMR; + uint32_t cr1config = hsai->Instance->CR1; + uint32_t tmperror; + + /* SAI Fifo request interrupt occurred -----------------------------------*/ + if (((itflags & SAI_xSR_FREQ) == SAI_xSR_FREQ) && ((itsources & SAI_IT_FREQ) == SAI_IT_FREQ)) + { + hsai->InterruptServiceRoutine(hsai); + } + /* SAI Overrun error interrupt occurred ----------------------------------*/ + else if (((itflags & SAI_FLAG_OVRUDR) == SAI_FLAG_OVRUDR) && ((itsources & SAI_IT_OVRUDR) == SAI_IT_OVRUDR)) + { + /* Clear the SAI Overrun flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); + /* Get the SAI error code */ + tmperror = ((hsai->State == HAL_SAI_STATE_BUSY_RX) ? HAL_SAI_ERROR_OVR : HAL_SAI_ERROR_UDR); + /* Change the SAI error code */ + hsai->ErrorCode |= tmperror; + /* the transfer is not stopped, we will forward the information to the user and we let + the user decide what needs to be done */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + /* SAI mutedet interrupt occurred ----------------------------------*/ + else if (((itflags & SAI_FLAG_MUTEDET) == SAI_FLAG_MUTEDET) && ((itsources & SAI_IT_MUTEDET) == SAI_IT_MUTEDET)) + { + /* Clear the SAI mutedet flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_MUTEDET); + /* call the call back function */ + if (hsai->mutecallback != NULL) + { + /* inform the user that an RX mute event has been detected */ + hsai->mutecallback(); + } + } + /* SAI AFSDET interrupt occurred ----------------------------------*/ + else if (((itflags & SAI_FLAG_AFSDET) == SAI_FLAG_AFSDET) && ((itsources & SAI_IT_AFSDET) == SAI_IT_AFSDET)) + { + /* Clear the SAI AFSDET flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_AFSDET); + + /* Change the SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_AFSDET; + + /* Check SAI DMA is enabled or not */ + if ((cr1config & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) + { + /* Abort the SAI DMA Streams */ + if (hsai->hdmatx != NULL) + { + /* Set the DMA Tx abort callback */ + hsai->hdmatx->XferAbortCallback = SAI_DMAAbort; + + /* Abort DMA in IT mode */ + if (HAL_DMA_Abort_IT(hsai->hdmatx) != HAL_OK) + { + /* Update SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Call SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + if (hsai->hdmarx != NULL) + { + /* Set the DMA Rx abort callback */ + hsai->hdmarx->XferAbortCallback = SAI_DMAAbort; + + /* Abort DMA in IT mode */ + if (HAL_DMA_Abort_IT(hsai->hdmarx) != HAL_OK) + { + /* Update SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Call SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + } + else + { + /* Abort SAI */ + /* No need to check return value because HAL_SAI_ErrorCallback will be called later */ + (void) HAL_SAI_Abort(hsai); + + /* Set error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + /* SAI LFSDET interrupt occurred ----------------------------------*/ + else if (((itflags & SAI_FLAG_LFSDET) == SAI_FLAG_LFSDET) && ((itsources & SAI_IT_LFSDET) == SAI_IT_LFSDET)) + { + /* Clear the SAI LFSDET flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_LFSDET); + + /* Change the SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_LFSDET; + + /* Check SAI DMA is enabled or not */ + if ((cr1config & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) + { + /* Abort the SAI DMA Streams */ + if (hsai->hdmatx != NULL) + { + /* Set the DMA Tx abort callback */ + hsai->hdmatx->XferAbortCallback = SAI_DMAAbort; + + /* Abort DMA in IT mode */ + if (HAL_DMA_Abort_IT(hsai->hdmatx) != HAL_OK) + { + /* Update SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Call SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + if (hsai->hdmarx != NULL) + { + /* Set the DMA Rx abort callback */ + hsai->hdmarx->XferAbortCallback = SAI_DMAAbort; + + /* Abort DMA in IT mode */ + if (HAL_DMA_Abort_IT(hsai->hdmarx) != HAL_OK) + { + /* Update SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Call SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + } + else + { + /* Abort SAI */ + /* No need to check return value because HAL_SAI_ErrorCallback will be called later */ + (void) HAL_SAI_Abort(hsai); + + /* Set error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + /* SAI WCKCFG interrupt occurred ----------------------------------*/ + else if (((itflags & SAI_FLAG_WCKCFG) == SAI_FLAG_WCKCFG) && ((itsources & SAI_IT_WCKCFG) == SAI_IT_WCKCFG)) + { + /* Clear the SAI WCKCFG flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_WCKCFG); + + /* Change the SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_WCKCFG; + + /* Check SAI DMA is enabled or not */ + if ((cr1config & SAI_xCR1_DMAEN) == SAI_xCR1_DMAEN) + { + /* Abort the SAI DMA Streams */ + if (hsai->hdmatx != NULL) + { + /* Set the DMA Tx abort callback */ + hsai->hdmatx->XferAbortCallback = SAI_DMAAbort; + + /* Abort DMA in IT mode */ + if (HAL_DMA_Abort_IT(hsai->hdmatx) != HAL_OK) + { + /* Update SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Call SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + if (hsai->hdmarx != NULL) + { + /* Set the DMA Rx abort callback */ + hsai->hdmarx->XferAbortCallback = SAI_DMAAbort; + + /* Abort DMA in IT mode */ + if (HAL_DMA_Abort_IT(hsai->hdmarx) != HAL_OK) + { + /* Update SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Call SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + } + else + { + /* If WCKCFG occurs, SAI audio block is automatically disabled */ + /* Disable all interrupts and clear all flags */ + hsai->Instance->IMR = 0U; + hsai->Instance->CLRFR = 0xFFFFFFFFU; + /* Set the SAI state to ready to be able to start again the process */ + hsai->State = HAL_SAI_STATE_READY; + + /* Initialize XferCount */ + hsai->XferCount = 0U; + + /* SAI error callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + } + /* SAI CNRDY interrupt occurred ----------------------------------*/ + else if (((itflags & SAI_FLAG_CNRDY) == SAI_FLAG_CNRDY) && ((itsources & SAI_IT_CNRDY) == SAI_IT_CNRDY)) + { + /* Clear the SAI CNRDY flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_CNRDY); + /* Change the SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_CNREADY; + /* the transfer is not stopped, we will forward the information to the user and we let + the user decide what needs to be done */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } +} + +/** + * @brief Tx Transfer completed callback. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_TxCpltCallback(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 callback. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_TxHalfCpltCallback(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsai); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SAI_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 callback. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsai); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SAI_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SAI error callback. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +__weak void HAL_SAI_ErrorCallback(SAI_HandleTypeDef *hsai) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the SAI handle state. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval HAL state + */ +HAL_SAI_StateTypeDef HAL_SAI_GetState(const 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(const SAI_HandleTypeDef *hsai) +{ + return hsai->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SAI_Private_Functions + * @brief Private functions + * @{ + */ + +/** + * @brief Initialize the SAI I2S protocol according to the specified parameters + * in the SAI_InitTypeDef and create the associated handle. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @param protocol one of the supported protocol. + * @param datasize one of the supported datasize @ref SAI_Protocol_DataSize. + * @param nbslot number of slot minimum value is 2 and max is 16. + * the value must be a multiple of 2. + * @retval HAL status + */ +static HAL_StatusTypeDef SAI_InitI2S(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot) +{ + HAL_StatusTypeDef status = HAL_OK; + + hsai->Init.Protocol = SAI_FREE_PROTOCOL; + hsai->Init.FirstBit = SAI_FIRSTBIT_MSB; + /* Compute ClockStrobing according AudioMode */ + if ((hsai->Init.AudioMode == SAI_MODEMASTER_TX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) + { + /* Transmit */ + hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_FALLINGEDGE; + } + else + { + /* Receive */ + hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_RISINGEDGE; + } + hsai->FrameInit.FSDefinition = SAI_FS_CHANNEL_IDENTIFICATION; + hsai->SlotInit.SlotActive = SAI_SLOTACTIVE_ALL; + hsai->SlotInit.FirstBitOffset = 0; + hsai->SlotInit.SlotNumber = nbslot; + + /* in IS2 the number of slot must be even */ + if ((nbslot & 0x1U) != 0U) + { + return HAL_ERROR; + } + + if (protocol == SAI_I2S_STANDARD) + { + hsai->FrameInit.FSPolarity = SAI_FS_ACTIVE_LOW; + hsai->FrameInit.FSOffset = SAI_FS_BEFOREFIRSTBIT; + } + else + { + /* SAI_I2S_MSBJUSTIFIED or SAI_I2S_LSBJUSTIFIED */ + hsai->FrameInit.FSPolarity = SAI_FS_ACTIVE_HIGH; + hsai->FrameInit.FSOffset = SAI_FS_FIRSTBIT; + } + + /* Frame definition */ + switch (datasize) + { + case SAI_PROTOCOL_DATASIZE_16BIT: + hsai->Init.DataSize = SAI_DATASIZE_16; + hsai->FrameInit.FrameLength = 32U * (nbslot / 2U); + hsai->FrameInit.ActiveFrameLength = 16U * (nbslot / 2U); + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_16B; + break; + case SAI_PROTOCOL_DATASIZE_16BITEXTENDED : + hsai->Init.DataSize = SAI_DATASIZE_16; + hsai->FrameInit.FrameLength = 64U * (nbslot / 2U); + hsai->FrameInit.ActiveFrameLength = 32U * (nbslot / 2U); + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; + break; + case SAI_PROTOCOL_DATASIZE_24BIT: + hsai->Init.DataSize = SAI_DATASIZE_24; + hsai->FrameInit.FrameLength = 64U * (nbslot / 2U); + hsai->FrameInit.ActiveFrameLength = 32U * (nbslot / 2U); + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; + break; + case SAI_PROTOCOL_DATASIZE_32BIT: + hsai->Init.DataSize = SAI_DATASIZE_32; + hsai->FrameInit.FrameLength = 64U * (nbslot / 2U); + hsai->FrameInit.ActiveFrameLength = 32U * (nbslot / 2U); + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; + break; + default : + status = HAL_ERROR; + break; + } + if (protocol == SAI_I2S_LSBJUSTIFIED) + { + if (datasize == SAI_PROTOCOL_DATASIZE_16BITEXTENDED) + { + hsai->SlotInit.FirstBitOffset = 16; + } + if (datasize == SAI_PROTOCOL_DATASIZE_24BIT) + { + hsai->SlotInit.FirstBitOffset = 8; + } + } + return status; +} + +/** + * @brief Initialize the SAI PCM protocol according to the specified parameters + * in the SAI_InitTypeDef and create the associated handle. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @param protocol one of the supported protocol + * @param datasize one of the supported datasize @ref SAI_Protocol_DataSize + * @param nbslot number of slot minimum value is 1 and the max is 16. + * @retval HAL status + */ +static HAL_StatusTypeDef SAI_InitPCM(SAI_HandleTypeDef *hsai, uint32_t protocol, uint32_t datasize, uint32_t nbslot) +{ + HAL_StatusTypeDef status = HAL_OK; + + hsai->Init.Protocol = SAI_FREE_PROTOCOL; + hsai->Init.FirstBit = SAI_FIRSTBIT_MSB; + /* Compute ClockStrobing according AudioMode */ + if ((hsai->Init.AudioMode == SAI_MODEMASTER_TX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) + { + /* Transmit */ + hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_RISINGEDGE; + } + else + { + /* Receive */ + hsai->Init.ClockStrobing = SAI_CLOCKSTROBING_FALLINGEDGE; + } + hsai->FrameInit.FSDefinition = SAI_FS_STARTFRAME; + hsai->FrameInit.FSPolarity = SAI_FS_ACTIVE_HIGH; + hsai->FrameInit.FSOffset = SAI_FS_BEFOREFIRSTBIT; + hsai->SlotInit.FirstBitOffset = 0; + hsai->SlotInit.SlotNumber = nbslot; + hsai->SlotInit.SlotActive = SAI_SLOTACTIVE_ALL; + + if (protocol == SAI_PCM_SHORT) + { + hsai->FrameInit.ActiveFrameLength = 1; + } + else + { + /* SAI_PCM_LONG */ + hsai->FrameInit.ActiveFrameLength = 13; + } + + switch (datasize) + { + case SAI_PROTOCOL_DATASIZE_16BIT: + hsai->Init.DataSize = SAI_DATASIZE_16; + hsai->FrameInit.FrameLength = 16U * nbslot; + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_16B; + break; + case SAI_PROTOCOL_DATASIZE_16BITEXTENDED : + hsai->Init.DataSize = SAI_DATASIZE_16; + hsai->FrameInit.FrameLength = 32U * nbslot; + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; + break; + case SAI_PROTOCOL_DATASIZE_24BIT : + hsai->Init.DataSize = SAI_DATASIZE_24; + hsai->FrameInit.FrameLength = 32U * nbslot; + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; + break; + case SAI_PROTOCOL_DATASIZE_32BIT: + hsai->Init.DataSize = SAI_DATASIZE_32; + hsai->FrameInit.FrameLength = 32U * nbslot; + hsai->SlotInit.SlotSize = SAI_SLOTSIZE_32B; + break; + default : + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Fill the fifo. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_FillFifo(SAI_HandleTypeDef *hsai) +{ + uint32_t temp; + + /* fill the fifo with data before to enabled the SAI */ + while (((hsai->Instance->SR & SAI_xSR_FLVL) != SAI_FIFOSTATUS_FULL) && (hsai->XferCount > 0U)) + { + if ((hsai->Init.DataSize == SAI_DATASIZE_8) && (hsai->Init.CompandingMode == SAI_NOCOMPANDING)) + { + hsai->Instance->DR = *hsai->pBuffPtr; + hsai->pBuffPtr++; + } + else if (hsai->Init.DataSize <= SAI_DATASIZE_16) + { + temp = (uint32_t)(*hsai->pBuffPtr); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); + hsai->pBuffPtr++; + hsai->Instance->DR = temp; + } + else + { + temp = (uint32_t)(*hsai->pBuffPtr); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 16); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 24); + hsai->pBuffPtr++; + hsai->Instance->DR = temp; + } + hsai->XferCount--; + } +} + +/** + * @brief Return the interrupt flag to set according the SAI setup. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @param mode SAI_MODE_DMA or SAI_MODE_IT + * @retval the list of the IT flag to enable + */ +static uint32_t SAI_InterruptFlag(const SAI_HandleTypeDef *hsai, SAI_ModeTypedef mode) +{ + uint32_t tmpIT = SAI_IT_OVRUDR; + + if (mode == SAI_MODE_IT) + { + tmpIT |= SAI_IT_FREQ; + } + + if ((hsai->Init.Protocol == SAI_AC97_PROTOCOL) && + ((hsai->Init.AudioMode == SAI_MODESLAVE_RX) || (hsai->Init.AudioMode == SAI_MODEMASTER_RX))) + { + tmpIT |= SAI_IT_CNRDY; + } + + if ((hsai->Init.AudioMode == SAI_MODESLAVE_RX) || (hsai->Init.AudioMode == SAI_MODESLAVE_TX)) + { + tmpIT |= SAI_IT_AFSDET | SAI_IT_LFSDET; + } + else + { + /* hsai has been configured in master mode */ + tmpIT |= SAI_IT_WCKCFG; + } + return tmpIT; +} + +/** + * @brief Disable the SAI and wait for the disabling. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static HAL_StatusTypeDef SAI_Disable(SAI_HandleTypeDef *hsai) +{ + uint32_t count = SAI_DEFAULT_TIMEOUT * (SystemCoreClock / 7U / 1000U); + HAL_StatusTypeDef status = HAL_OK; + + /* Disable the SAI instance */ + __HAL_SAI_DISABLE(hsai); + + do + { + /* Check for the Timeout */ + if (count == 0U) + { + /* Update error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_TIMEOUT; + status = HAL_TIMEOUT; + break; + } + count--; + } while ((hsai->Instance->CR1 & SAI_xCR1_SAIEN) != 0U); + + return status; +} + +/** + * @brief Tx Handler for Transmit in Interrupt mode 8-Bit transfer. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_Transmit_IT8Bit(SAI_HandleTypeDef *hsai) +{ + if (hsai->XferCount == 0U) + { + /* Handle the end of the transmission */ + /* Disable FREQ and OVRUDR interrupts */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + hsai->State = HAL_SAI_STATE_READY; +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->TxCpltCallback(hsai); +#else + HAL_SAI_TxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + else + { + /* Write data on DR register */ + hsai->Instance->DR = *hsai->pBuffPtr; + hsai->pBuffPtr++; + hsai->XferCount--; + } +} + +/** + * @brief Tx Handler for Transmit in Interrupt mode for 16-Bit transfer. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_Transmit_IT16Bit(SAI_HandleTypeDef *hsai) +{ + if (hsai->XferCount == 0U) + { + /* Handle the end of the transmission */ + /* Disable FREQ and OVRUDR interrupts */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + hsai->State = HAL_SAI_STATE_READY; +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->TxCpltCallback(hsai); +#else + HAL_SAI_TxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + else + { + /* Write data on DR register */ + uint32_t temp; + temp = (uint32_t)(*hsai->pBuffPtr); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); + hsai->pBuffPtr++; + hsai->Instance->DR = temp; + hsai->XferCount--; + } +} + +/** + * @brief Tx Handler for Transmit in Interrupt mode for 32-Bit transfer. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_Transmit_IT32Bit(SAI_HandleTypeDef *hsai) +{ + if (hsai->XferCount == 0U) + { + /* Handle the end of the transmission */ + /* Disable FREQ and OVRUDR interrupts */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + hsai->State = HAL_SAI_STATE_READY; +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->TxCpltCallback(hsai); +#else + HAL_SAI_TxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } + else + { + /* Write data on DR register */ + uint32_t temp; + temp = (uint32_t)(*hsai->pBuffPtr); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 8); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 16); + hsai->pBuffPtr++; + temp |= ((uint32_t)(*hsai->pBuffPtr) << 24); + hsai->pBuffPtr++; + hsai->Instance->DR = temp; + hsai->XferCount--; + } +} + +/** + * @brief Rx Handler for Receive in Interrupt mode 8-Bit transfer. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_Receive_IT8Bit(SAI_HandleTypeDef *hsai) +{ + /* Receive data */ + *hsai->pBuffPtr = (uint8_t)hsai->Instance->DR; + hsai->pBuffPtr++; + hsai->XferCount--; + + /* Check end of the transfer */ + if (hsai->XferCount == 0U) + { + /* Disable TXE and OVRUDR interrupts */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + + /* Clear the SAI Overrun flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); + + hsai->State = HAL_SAI_STATE_READY; +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->RxCpltCallback(hsai); +#else + HAL_SAI_RxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Rx Handler for Receive in Interrupt mode for 16-Bit transfer. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_Receive_IT16Bit(SAI_HandleTypeDef *hsai) +{ + uint32_t temp; + + /* Receive data */ + temp = hsai->Instance->DR; + *hsai->pBuffPtr = (uint8_t)temp; + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 8); + hsai->pBuffPtr++; + hsai->XferCount--; + + /* Check end of the transfer */ + if (hsai->XferCount == 0U) + { + /* Disable TXE and OVRUDR interrupts */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + + /* Clear the SAI Overrun flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); + + hsai->State = HAL_SAI_STATE_READY; +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->RxCpltCallback(hsai); +#else + HAL_SAI_RxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Rx Handler for Receive in Interrupt mode for 32-Bit transfer. + * @param hsai pointer to a SAI_HandleTypeDef structure that contains + * the configuration information for SAI module. + * @retval None + */ +static void SAI_Receive_IT32Bit(SAI_HandleTypeDef *hsai) +{ + uint32_t temp; + + /* Receive data */ + temp = hsai->Instance->DR; + *hsai->pBuffPtr = (uint8_t)temp; + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 8); + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 16); + hsai->pBuffPtr++; + *hsai->pBuffPtr = (uint8_t)(temp >> 24); + hsai->pBuffPtr++; + hsai->XferCount--; + + /* Check end of the transfer */ + if (hsai->XferCount == 0U) + { + /* Disable TXE and OVRUDR interrupts */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_IT)); + + /* Clear the SAI Overrun flag */ + __HAL_SAI_CLEAR_FLAG(hsai, SAI_FLAG_OVRUDR); + + hsai->State = HAL_SAI_STATE_READY; +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->RxCpltCallback(hsai); +#else + HAL_SAI_RxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA SAI transmit process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SAI_DMATxCplt(DMA_HandleTypeDef *hdma) +{ + SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Check if DMA in circular mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + hsai->XferCount = 0; + + /* Disable SAI Tx DMA Request */ + hsai->Instance->CR1 &= (uint32_t)(~SAI_xCR1_DMAEN); + + /* Stop the interrupts error handling */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); + + hsai->State = HAL_SAI_STATE_READY; + } + +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->TxCpltCallback(hsai); +#else + HAL_SAI_TxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SAI transmit process half complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SAI_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->TxHalfCpltCallback(hsai); +#else + HAL_SAI_TxHalfCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SAI receive process complete callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SAI_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Check if DMA in circular mode*/ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + /* Disable Rx DMA Request */ + hsai->Instance->CR1 &= (uint32_t)(~SAI_xCR1_DMAEN); + hsai->XferCount = 0; + + /* Stop the interrupts error handling */ + __HAL_SAI_DISABLE_IT(hsai, SAI_InterruptFlag(hsai, SAI_MODE_DMA)); + + hsai->State = HAL_SAI_STATE_READY; + } + +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->RxCpltCallback(hsai); +#else + HAL_SAI_RxCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SAI receive process half complete callback + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SAI_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->RxHalfCpltCallback(hsai); +#else + HAL_SAI_RxHalfCpltCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SAI communication error callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SAI_DMAError(DMA_HandleTypeDef *hdma) +{ + SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Set SAI error code */ + hsai->ErrorCode |= HAL_SAI_ERROR_DMA; + + /* Disable the SAI DMA request */ + hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; + + /* Disable SAI peripheral */ + /* No need to check return value because state will be updated and HAL_SAI_ErrorCallback will be called later */ + (void) SAI_Disable(hsai); + + /* Set the SAI state ready to be able to start again the process */ + hsai->State = HAL_SAI_STATE_READY; + + /* Initialize XferCount */ + hsai->XferCount = 0U; + + /* SAI error Callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SAI Abort callback. + * @param hdma pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SAI_DMAAbort(DMA_HandleTypeDef *hdma) +{ + SAI_HandleTypeDef *hsai = (SAI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable DMA request */ + hsai->Instance->CR1 &= ~SAI_xCR1_DMAEN; + + /* Disable all interrupts and clear all flags */ + hsai->Instance->IMR = 0U; + hsai->Instance->CLRFR = 0xFFFFFFFFU; + + if (hsai->ErrorCode != HAL_SAI_ERROR_WCKCFG) + { + /* Disable SAI peripheral */ + /* No need to check return value because state will be updated and HAL_SAI_ErrorCallback will be called later */ + (void) SAI_Disable(hsai); + + /* Flush the fifo */ + SET_BIT(hsai->Instance->CR2, SAI_xCR2_FFLUSH); + } + /* Set the SAI state to ready to be able to start again the process */ + hsai->State = HAL_SAI_STATE_READY; + + /* Initialize XferCount */ + hsai->XferCount = 0U; + + /* SAI error Callback */ +#if (USE_HAL_SAI_REGISTER_CALLBACKS == 1) + hsai->ErrorCallback(hsai); +#else + HAL_SAI_ErrorCallback(hsai); +#endif /* USE_HAL_SAI_REGISTER_CALLBACKS */ +} + +/** + * @} + */ + +#endif /* HAL_SAI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai_ex.c index e1bbaec65..57de5db8b 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sai_ex.c @@ -1,129 +1,129 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_sai_ex.c - * @author MCD Application Team - * @brief SAI Extended HAL module driver. - * This file provides firmware functions to manage the following - * functionality of the SAI Peripheral Controller: - * + Modify PDM microphone delays. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ -#ifdef HAL_SAI_MODULE_ENABLED - -/** @defgroup SAIEx SAIEx - * @brief SAI Extended HAL module driver - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup SAIEx_Private_Defines SAIEx Extended Private Defines - * @{ - */ -#define SAI_PDM_DELAY_MASK 0x77U -#define SAI_PDM_DELAY_OFFSET 8U -#define SAI_PDM_RIGHT_DELAY_OFFSET 4U -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @defgroup SAIEx_Exported_Functions SAIEx Extended Exported Functions - * @{ - */ - -/** @defgroup SAIEx_Exported_Functions_Group1 Peripheral Control functions - * @brief SAIEx control functions - * -@verbatim - =============================================================================== - ##### Extended features functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Modify PDM microphone delays - -@endverbatim - * @{ - */ - -/** - * @brief Configure PDM microphone delays. - * @param hsai SAI handle. - * @param pdmMicDelay Microphone delays configuration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SAIEx_ConfigPdmMicDelay(const SAI_HandleTypeDef *hsai, - const SAIEx_PdmMicDelayParamTypeDef *pdmMicDelay) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t offset; - - /* Check that SAI sub-block is SAI1 sub-block A */ - if (hsai->Instance != SAI1_Block_A) - { - status = HAL_ERROR; - } - else - { - /* Check microphone delay parameters */ - assert_param(IS_SAI_PDM_MIC_PAIRS_NUMBER(pdmMicDelay->MicPair)); - assert_param(IS_SAI_PDM_MIC_DELAY(pdmMicDelay->LeftDelay)); - assert_param(IS_SAI_PDM_MIC_DELAY(pdmMicDelay->RightDelay)); - - /* Compute offset on PDMDLY register according mic pair number */ - offset = SAI_PDM_DELAY_OFFSET * (pdmMicDelay->MicPair - 1U); - - /* Check SAI state and offset */ - if ((hsai->State != HAL_SAI_STATE_RESET) && (offset <= 24U)) - { - /* Reset current delays for specified microphone */ - SAI1->PDMDLY &= ~(SAI_PDM_DELAY_MASK << offset); - - /* Apply new microphone delays */ - SAI1->PDMDLY |= (((pdmMicDelay->RightDelay << SAI_PDM_RIGHT_DELAY_OFFSET) | pdmMicDelay->LeftDelay) << offset); - } - else - { - status = HAL_ERROR; - } - } - return status; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_SAI_MODULE_ENABLED */ -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_sai_ex.c + * @author MCD Application Team + * @brief SAI Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionality of the SAI Peripheral Controller: + * + Modify PDM microphone delays. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ +#ifdef HAL_SAI_MODULE_ENABLED + +/** @defgroup SAIEx SAIEx + * @brief SAI Extended HAL module driver + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SAIEx_Private_Defines SAIEx Extended Private Defines + * @{ + */ +#define SAI_PDM_DELAY_MASK 0x77U +#define SAI_PDM_DELAY_OFFSET 8U +#define SAI_PDM_RIGHT_DELAY_OFFSET 4U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SAIEx_Exported_Functions SAIEx Extended Exported Functions + * @{ + */ + +/** @defgroup SAIEx_Exported_Functions_Group1 Peripheral Control functions + * @brief SAIEx control functions + * +@verbatim + =============================================================================== + ##### Extended features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Modify PDM microphone delays + +@endverbatim + * @{ + */ + +/** + * @brief Configure PDM microphone delays. + * @param hsai SAI handle. + * @param pdmMicDelay Microphone delays configuration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SAIEx_ConfigPdmMicDelay(const SAI_HandleTypeDef *hsai, + const SAIEx_PdmMicDelayParamTypeDef *pdmMicDelay) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t offset; + + /* Check that SAI sub-block is SAI1 sub-block A */ + if (hsai->Instance != SAI1_Block_A) + { + status = HAL_ERROR; + } + else + { + /* Check microphone delay parameters */ + assert_param(IS_SAI_PDM_MIC_PAIRS_NUMBER(pdmMicDelay->MicPair)); + assert_param(IS_SAI_PDM_MIC_DELAY(pdmMicDelay->LeftDelay)); + assert_param(IS_SAI_PDM_MIC_DELAY(pdmMicDelay->RightDelay)); + + /* Compute offset on PDMDLY register according mic pair number */ + offset = SAI_PDM_DELAY_OFFSET * (pdmMicDelay->MicPair - 1U); + + /* Check SAI state and offset */ + if ((hsai->State != HAL_SAI_STATE_RESET) && (offset <= 24U)) + { + /* Reset current delays for specified microphone */ + SAI1->PDMDLY &= ~(SAI_PDM_DELAY_MASK << offset); + + /* Apply new microphone delays */ + SAI1->PDMDLY |= (((pdmMicDelay->RightDelay << SAI_PDM_RIGHT_DELAY_OFFSET) | pdmMicDelay->LeftDelay) << offset); + } + else + { + status = HAL_ERROR; + } + } + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SAI_MODULE_ENABLED */ +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd.c index 761af23d2..61049c8a6 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd.c @@ -1,4070 +1,4070 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_sd.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 (SDMMC 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 SDMMC memories which uses the HAL - SDMMC driver functions to interface with SD and uSD cards devices. - It is used as follows: - - (#)Initialize the SDMMC low level resources by implementing the HAL_SD_MspInit() API: - (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE(); - (##) SDMMC pins configuration for SD card - (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE(); - (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init() - and according to your pin assignment; - (##) NVIC configuration if you need to use interrupt process (HAL_SD_ReadBlocks_IT() - and HAL_SD_WriteBlocks_IT() APIs). - (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority(); - (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ() - (+++) SDMMC interrupts are managed using the macros __HAL_SD_ENABLE_IT() - and __HAL_SD_DISABLE_IT() inside the communication process. - (+++) SDMMC interrupts pending bits are managed using the macros __HAL_SD_GET_IT() - and __HAL_SD_CLEAR_IT() - (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used. - - (#) 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 - SDMMC Peripheral(STM32 side) and 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 (SDMMC_CK) is computed as follows: - - SDMMC_CK = SDMMCCLK / (2 * ClockDiv) - - In initialization mode and according to the SD Card standard, - make sure that the SDMMC_CK frequency doesn't exceed 400KHz. - - This phase of initialization is done through SDMMC_Init() and - SDMMC_PowerState_ON() SDMMC low level APIs. - - (#) Initialize the SD card. The API used is HAL_SD_InitCard(). - This phase allows the card initialization and identification - and check the SD Card type (Standard Capacity or High Capacity) - The initialization flow is compatible with SD standard. - - This API (HAL_SD_InitCard()) could be used also to reinitialize the card in case - of plug-off plug-in. - - (#) Configure the SD Card Data transfer frequency. You can change or adapt this - frequency by adjusting the "ClockDiv" field. - In transfer mode and according to the SD Card standard, make sure that the - SDMMC_CK frequency doesn't exceed 25MHz and 100MHz in High-speed mode switch. - - (#) 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-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - - (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the DMA transfer process through the SD Rx interrupt event. - - (+) You can read from SD card in Interrupt mode by using function HAL_SD_ReadBlocks_IT(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the IT transfer process through the SD Rx interrupt event. - - *** SD Card Write operation *** - =============================== - [..] - (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - - (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the DMA transfer process through the SD Tx interrupt event. - - (+) You can write to SD card in Interrupt mode by using function HAL_SD_WriteBlocks_IT(). - This function support only 512-bytes block length (the block size should be - chosen as 512 bytes). - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the IT transfer process through the SD Tx interrupt event. - - *** SD card status *** - ====================== - [..] - (+) The SD Status contains status bits that are related to the SD Memory - Card proprietary features. To get SD card status use the HAL_SD_GetCardStatus(). - - *** SD card information *** - =========================== - [..] - (+) To get SD card information, you can use the function HAL_SD_GetCardInfo(). - It returns useful information about the SD card such as block size, card type, - block number ... - - *** SD card CSD register *** - ============================ - (+) The HAL_SD_GetCardCSD() API allows to get the parameters of the CSD register. - Some of the CSD parameters are useful for card initialization and identification. - - *** SD card CID register *** - ============================ - (+) The HAL_SD_GetCardCID() API allows to get the parameters of the CID register. - Some of the CSD parameters are useful for card initialization and identification. - - *** SD HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in SD HAL driver. - - (+) __HAL_SD_ENABLE_IT: Enable the SD device interrupt - (+) __HAL_SD_DISABLE_IT: Disable the SD device interrupt - (+) __HAL_SD_GET_FLAG:Check whether the specified SD flag is set or not - (+) __HAL_SD_CLEAR_FLAG: Clear the SD's pending flags - - (@) You can refer to the SD HAL driver header file for more useful macros - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_SD_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - Use Functions HAL_SD_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) TxCpltCallback : callback when a transmission transfer is completed. - (+) RxCpltCallback : callback when a reception transfer is completed. - (+) ErrorCallback : callback when error occurs. - (+) AbortCpltCallback : callback when abort is completed. - (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed. - (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed. - (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed. - (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed. - (+) MspInitCallback : SD MspInit. - (+) MspDeInitCallback : SD MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - For specific callbacks TransceiverCallback use dedicated register callbacks: - respectively HAL_SD_RegisterTransceiverCallback(). - - Use function HAL_SD_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) TxCpltCallback : callback when a transmission transfer is completed. - (+) RxCpltCallback : callback when a reception transfer is completed. - (+) ErrorCallback : callback when error occurs. - (+) AbortCpltCallback : callback when abort is completed. - (+) Read_DMALnkLstBufCpltCallback : callback when the DMA reception of linked list node buffer is completed. - (+) Write_DMALnkLstBufCpltCallback : callback when the DMA transmission of linked list node buffer is completed. - (+) MspInitCallback : SD MspInit. - (+) MspDeInitCallback : SD MspDeInit. - This function) takes as parameters the HAL peripheral handle and the Callback ID. - For specific callbacks TransceiverCallback use dedicated unregister callbacks: - respectively HAL_SD_UnRegisterTransceiverCallback(). - - By default, after the HAL_SD_Init and if the state is HAL_SD_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_SD_Init - and HAL_SD_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_SD_Init and HAL_SD_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_SD_RegisterCallback before calling HAL_SD_DeInit - or HAL_SD_Init function. - - When The compilation define USE_HAL_SD_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @addtogroup SD - * @{ - */ - -#if defined (SDMMC1) || defined (SDMMC2) -#ifdef HAL_SD_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup SD_Private_Defines - * @{ - */ -/* Frequencies used in the driver for clock divider calculation */ -#define SD_INIT_FREQ 400000U /* Initialization phase : 400 kHz max */ -#define SD_NORMAL_SPEED_FREQ 25000000U /* Normal speed phase : 25 MHz max */ -#define SD_HIGH_SPEED_FREQ 50000000U /* High speed phase : 50 MHz max */ -/* Private macro -------------------------------------------------------------*/ -#if defined (DLYB_SDMMC1) && defined (DLYB_SDMMC2) -#define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) (((SDMMC_INSTANCE) == SDMMC1)? \ - DLYB_SDMMC1 : DLYB_SDMMC2 ) -#elif defined (DLYB_SDMMC1) -#define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) ( DLYB_SDMMC1 ) -#endif /* (DLYB_SDMMC1) && defined (DLYB_SDMMC2) */ - -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup SD_Private_Functions SD Private Functions - * @{ - */ -static uint32_t SD_InitCard(SD_HandleTypeDef *hsd); -static uint32_t SD_PowerON(SD_HandleTypeDef *hsd); -static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); -static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus); -static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd); -static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd); -static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR); -static void SD_PowerOFF(SD_HandleTypeDef *hsd); -static void SD_Write_IT(SD_HandleTypeDef *hsd); -static void SD_Read_IT(SD_HandleTypeDef *hsd); -static uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode); -#if (USE_SD_TRANSCEIVER != 0U) -static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode); -static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd); -#endif /* USE_SD_TRANSCEIVER */ -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup SD_Exported_Functions - * @{ - */ - -/** @addtogroup SD_Exported_Functions_Group1 - * @brief Initialization and de-initialization 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 according to the specified parameters in the - SD_HandleTypeDef and create the associated handle. - * @param hsd: Pointer to the SD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd) -{ - HAL_SD_CardStatusTypeDef CardStatus; - uint32_t speedgrade; - uint32_t unitsize; - uint32_t tickstart; - - /* Check the SD handle allocation */ - if (hsd == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance)); - assert_param(IS_SDMMC_CLOCK_EDGE(hsd->Init.ClockEdge)); - assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave)); - assert_param(IS_SDMMC_BUS_WIDE(hsd->Init.BusWide)); - assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl)); - assert_param(IS_SDMMC_CLKDIV(hsd->Init.ClockDiv)); - - if (hsd->State == HAL_SD_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hsd->Lock = HAL_UNLOCKED; - -#if (USE_SD_TRANSCEIVER != 0U) - /* Force SDMMC_TRANSCEIVER_PRESENT for Legacy usage */ - if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_UNKNOWN) - { - hsd->Init.TranceiverPresent = SDMMC_TRANSCEIVER_PRESENT; - } -#endif /*USE_SD_TRANSCEIVER */ -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - /* Reset Callback pointers in HAL_SD_STATE_RESET only */ - hsd->TxCpltCallback = HAL_SD_TxCpltCallback; - hsd->RxCpltCallback = HAL_SD_RxCpltCallback; - hsd->ErrorCallback = HAL_SD_ErrorCallback; - hsd->AbortCpltCallback = HAL_SD_AbortCallback; - hsd->Read_DMALnkLstBufCpltCallback = HAL_SDEx_Read_DMALnkLstBufCpltCallback; - hsd->Write_DMALnkLstBufCpltCallback = HAL_SDEx_Write_DMALnkLstBufCpltCallback; -#if (USE_SD_TRANSCEIVER != 0U) - if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) - { - hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback; - } -#endif /* USE_SD_TRANSCEIVER */ - - if (hsd->MspInitCallback == NULL) - { - hsd->MspInitCallback = HAL_SD_MspInit; - } - - /* Init the low level hardware */ - hsd->MspInitCallback(hsd); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_SD_MspInit(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - - hsd->State = HAL_SD_STATE_PROGRAMMING; - - /* Initialize the Card parameters */ - if (HAL_SD_InitCard(hsd) != HAL_OK) - { - return HAL_ERROR; - } - - if (HAL_SD_GetCardStatus(hsd, &CardStatus) != HAL_OK) - { - return HAL_ERROR; - } - /* Get Initial Card Speed from Card Status*/ - speedgrade = CardStatus.UhsSpeedGrade; - unitsize = CardStatus.UhsAllocationUnitSize; - if ((hsd->SdCard.CardType == CARD_SDHC_SDXC) && ((speedgrade != 0U) || (unitsize != 0U))) - { - hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED; - } - else - { - if (hsd->SdCard.CardType == CARD_SDHC_SDXC) - { - hsd->SdCard.CardSpeed = CARD_HIGH_SPEED; - } - else - { - hsd->SdCard.CardSpeed = CARD_NORMAL_SPEED; - } - - } - /* Configure the bus wide */ - if (HAL_SD_ConfigWideBusOperation(hsd, hsd->Init.BusWide) != HAL_OK) - { - return HAL_ERROR; - } - - /* Verify that SD card is ready to use after Initialization */ - tickstart = HAL_GetTick(); - while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Initialize the error code */ - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - /* Initialize the SD operation */ - hsd->Context = SD_CONTEXT_NONE; - - /* Initialize the SD state */ - hsd->State = HAL_SD_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Initializes the SD Card. - * @param hsd: Pointer to SD handle - * @note This function initializes the SD card. It could be used when a card - re-initialization is needed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) -{ - uint32_t errorstate; - SD_InitTypeDef Init; - uint32_t sdmmc_clk; - - /* Default SDMMC peripheral configuration for SD card initialization */ - Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; - Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; - Init.BusWide = SDMMC_BUS_WIDE_1B; - Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE; - - /* Init Clock should be less or equal to 400Khz*/ - sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); - if (sdmmc_clk == 0U) - { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER; - return HAL_ERROR; - } - Init.ClockDiv = sdmmc_clk / (2U * SD_INIT_FREQ); - -#if (USE_SD_TRANSCEIVER != 0U) - Init.TranceiverPresent = hsd->Init.TranceiverPresent; - - if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) - { - /* Set Transceiver polarity */ - hsd->Instance->POWER |= SDMMC_POWER_DIRPOL; - } -#elif defined (USE_SD_DIRPOL) - /* Set Transceiver polarity */ - hsd->Instance->POWER |= SDMMC_POWER_DIRPOL; -#endif /* USE_SD_TRANSCEIVER */ - - /* Initialize SDMMC peripheral interface with default configuration */ - (void)SDMMC_Init(hsd->Instance, Init); - - /* Set Power State to ON */ - (void)SDMMC_PowerState_ON(hsd->Instance); - - /* wait 74 Cycles: required power up waiting time before starting - the SD initialization sequence */ - if (Init.ClockDiv != 0U) - { - sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv); - } - - if (sdmmc_clk != 0U) - { - HAL_Delay(1U + (74U * 1000U / (sdmmc_clk))); - } - - /* Identify card operating voltage */ - errorstate = SD_PowerON(hsd); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode |= errorstate; - return HAL_ERROR; - } - - /* Card initialization */ - errorstate = SD_InitCard(hsd); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode |= errorstate; - return HAL_ERROR; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief De-Initializes the SD card. - * @param hsd: Pointer to SD handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd) -{ - /* Check the SD handle allocation */ - if (hsd == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance)); - - hsd->State = HAL_SD_STATE_BUSY; - -#if (USE_SD_TRANSCEIVER != 0U) - /* Deactivate the 1.8V Mode */ - if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - if (hsd->DriveTransceiver_1_8V_Callback == NULL) - { - hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback; - } - hsd->DriveTransceiver_1_8V_Callback(RESET); -#else - HAL_SD_DriveTransceiver_1_8V_Callback(RESET); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } -#endif /* USE_SD_TRANSCEIVER */ - - /* Set SD power state to off */ - SD_PowerOFF(hsd); - -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - if (hsd->MspDeInitCallback == NULL) - { - hsd->MspDeInitCallback = HAL_SD_MspDeInit; - } - - /* DeInit the low level hardware */ - hsd->MspDeInitCallback(hsd); -#else - /* De-Initialize the MSP layer */ - HAL_SD_MspDeInit(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - - hsd->ErrorCode = HAL_SD_ERROR_NONE; - hsd->State = HAL_SD_STATE_RESET; - - return HAL_OK; -} - -/** - * @brief Initializes the SD MSP. - * @param hsd: Pointer to SD handle - * @retval None - */ -__weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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: Pointer to SD handle - * @retval None - */ -__weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @addtogroup SD_Exported_Functions_Group2 - * @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. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @param hsd: Pointer to SD handle - * @param pData: pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of SD blocks to read - * @param Timeout: Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, - uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t data; - uint32_t dataremaining; - uint32_t add = BlockAdd; - uint8_t *tempbuff = pData; - - if (NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= BLOCKSIZE; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - /* Read block(s) in polling mode */ - if (NumberOfBlocks > 1U) - { - hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); - } - else - { - hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK; - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); - } - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - - /* Poll on SDMMC flags */ - dataremaining = config.DataLength; - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hsd->Instance); - *tempbuff = (uint8_t)(data & 0xFFU); - tempbuff++; - *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); - tempbuff++; - *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); - tempbuff++; - *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); - tempbuff++; - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hsd->Instance); - - /* Send stop transmission command in case of multiblock read */ - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - if (hsd->SdCard.CardType != CARD_SECURED) - { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - } - } - - /* Get error state */ - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - hsd->State = HAL_SD_STATE_READY; - - return HAL_OK; - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Allows to write block(s) to a specified address in a card. The Data - * transfer is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @param hsd: Pointer to SD handle - * @param pData: pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of SD blocks to write - * @param Timeout: Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks, uint32_t Timeout) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t data; - uint32_t dataremaining; - uint32_t add = BlockAdd; - const uint8_t *tempbuff = pData; - - if (NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= BLOCKSIZE; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * BLOCKSIZE; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - /* Write Blocks in Polling mode */ - if (NumberOfBlocks > 1U) - { - hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); - } - else - { - hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK; - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); - } - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - - /* Write block(s) in polling mode */ - dataremaining = config.DataLength; - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | - SDMMC_FLAG_DATAEND)) - { - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) - { - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*tempbuff); - tempbuff++; - data |= ((uint32_t)(*tempbuff) << 8U); - tempbuff++; - data |= ((uint32_t)(*tempbuff) << 16U); - tempbuff++; - data |= ((uint32_t)(*tempbuff) << 24U); - tempbuff++; - (void)SDMMC_WriteFIFO(hsd->Instance, &data); - } - dataremaining -= SDMMC_FIFO_SIZE; - } - - if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_TIMEOUT; - } - } - __SDMMC_CMDTRANS_DISABLE(hsd->Instance); - - /* Send stop transmission command in case of multiblock write */ - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - if (hsd->SdCard.CardType != CARD_SECURED) - { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - } - } - - /* Get error state */ - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - hsd->State = HAL_SD_STATE_READY; - - return HAL_OK; - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the IT transfer process through the SD Rx - * interrupt event. - * @param hsd: Pointer to SD handle - * @param pData: Pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of blocks to read. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - hsd->pRxBuffPtr = pData; - hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= BLOCKSIZE; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - /* Read Blocks in IT mode */ - if (NumberOfBlocks > 1U) - { - hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); - } - else - { - hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); - } - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - - __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | - SDMMC_FLAG_RXFIFOHF)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Writes block(s) to a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the IT transfer process through the SD Tx - * interrupt event. - * @param hsd: Pointer to SD handle - * @param pData: Pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of blocks to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - hsd->pTxBuffPtr = pData; - hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= BLOCKSIZE; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - /* Write Blocks in Polling mode */ - if (NumberOfBlocks > 1U) - { - hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_IT); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); - } - else - { - hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT); - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); - } - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - - /* Enable transfer interrupts */ - __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | - SDMMC_FLAG_TXFIFOHE)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @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 a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the DMA transfer process through the SD Rx - * interrupt event. - * @param hsd: Pointer SD handle - * @param pData: Pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of blocks to read. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - hsd->pRxBuffPtr = pData; - hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= BLOCKSIZE; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - hsd->Instance->IDMABASER = (uint32_t) pData ; - hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; - - /* Read Blocks in DMA mode */ - if (NumberOfBlocks > 1U) - { - hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); - } - else - { - hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); - } - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - - /* Enable transfer interrupts */ - __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @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 a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the DMA transfer process through the SD Tx - * interrupt event. - * @param hsd: Pointer to SD handle - * @param pData: Pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of blocks to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd, - uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t add = BlockAdd; - - if (NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - hsd->pTxBuffPtr = pData; - hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= BLOCKSIZE; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - hsd->Instance->IDMABASER = (uint32_t) pData ; - hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; - - /* Write Blocks in Polling mode */ - if (NumberOfBlocks > 1U) - { - hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); - } - else - { - hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA); - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); - } - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - return HAL_ERROR; - } - - /* Enable transfer interrupts */ - __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Erases the specified memory area of the given SD card. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @param hsd: Pointer to SD handle - * @param BlockStartAdd: Start Block address - * @param BlockEndAdd: End Block address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd) -{ - uint32_t errorstate; - uint32_t start_add = BlockStartAdd; - uint32_t end_add = BlockEndAdd; - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - if (end_add < start_add) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } - - if (end_add > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Check if the card command class supports erase command */ - if (((hsd->SdCard.Class) & SDMMC_CCCC_ERASE) == 0U) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_LOCK_UNLOCK_FAILED; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - /* Get start and end block for high capacity cards */ - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - start_add *= BLOCKSIZE; - end_add *= BLOCKSIZE; - } - - /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ - if (hsd->SdCard.CardType != CARD_SECURED) - { - /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ - errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, start_add); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ - errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, end_add); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - } - - /* Send CMD38 ERASE */ - errorstate = SDMMC_CmdErase(hsd->Instance, 0UL); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief This function handles SD card interrupt request. - * @param hsd: Pointer to SD handle - * @retval None - */ -void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd) -{ - uint32_t errorstate; - uint32_t context = hsd->Context; - - /* Check for SDMMC interrupt flags */ - if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) != RESET) && ((context & SD_CONTEXT_IT) != 0U)) - { - SD_Read_IT(hsd); - } - - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) != RESET) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DATAEND); - - __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR | SDMMC_IT_TXFIFOHE | \ - SDMMC_IT_RXFIFOHF); - - __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC); - __SDMMC_CMDTRANS_DISABLE(hsd->Instance); - - if ((context & SD_CONTEXT_IT) != 0U) - { - if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) - { - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= errorstate; -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->ErrorCallback(hsd); -#else - HAL_SD_ErrorCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - } - - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->RxCpltCallback(hsd); -#else - HAL_SD_RxCpltCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - else - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->TxCpltCallback(hsd); -#else - HAL_SD_TxCpltCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - } - else if ((context & SD_CONTEXT_DMA) != 0U) - { - hsd->Instance->DLEN = 0; - hsd->Instance->DCTRL = 0; - hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - /* Stop Transfer for Write Multi blocks or Read Multi blocks */ - if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) - { - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= errorstate; -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->ErrorCallback(hsd); -#else - HAL_SD_ErrorCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - } - - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; - if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->TxCpltCallback(hsd); -#else - HAL_SD_TxCpltCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->RxCpltCallback(hsd); -#else - HAL_SD_RxCpltCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } - } - - else if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) != RESET) && ((context & SD_CONTEXT_IT) != 0U)) - { - SD_Write_IT(hsd); - } - - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR | - SDMMC_FLAG_TXUNDERR) != RESET) - { - /* Set Error code */ - if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DCRCFAIL) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; - } - if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DTIMEOUT) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - } - if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_RXOVERR) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN; - } - if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_TXUNDERR) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN; - } - - /* Clear All flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - /* Disable all interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); - - __SDMMC_CMDTRANS_DISABLE(hsd->Instance); - hsd->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; - hsd->Instance->CMD |= SDMMC_CMD_CMDSTOP; - hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); - hsd->Instance->CMD &= ~(SDMMC_CMD_CMDSTOP); - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DABORT); - - if ((context & SD_CONTEXT_IT) != 0U) - { - /* Set the SD state to ready to be able to start again the process */ - hsd->State = HAL_SD_STATE_READY; - hsd->Context = SD_CONTEXT_NONE; -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->ErrorCallback(hsd); -#else - HAL_SD_ErrorCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - else if ((context & SD_CONTEXT_DMA) != 0U) - { - if (hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - /* Disable Internal DMA */ - __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC); - hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - /* Set the SD state to ready to be able to start again the process */ - hsd->State = HAL_SD_STATE_READY; -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->ErrorCallback(hsd); -#else - HAL_SD_ErrorCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } - } - - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_IDMABTC) != RESET) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_IDMABTC); - - if ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U) - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->Write_DMALnkLstBufCpltCallback(hsd); -#else - HAL_SDEx_Write_DMALnkLstBufCpltCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - else /* SD_CONTEXT_READ_MULTIPLE_BLOCK */ - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->Read_DMALnkLstBufCpltCallback(hsd); -#else - HAL_SDEx_Read_DMALnkLstBufCpltCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } -} - -/** - * @brief return the SD state - * @param hsd: Pointer to sd handle - * @retval HAL state - */ -HAL_SD_StateTypeDef HAL_SD_GetState(const SD_HandleTypeDef *hsd) -{ - return hsd->State; -} - -/** - * @brief Return the SD error code - * @param hsd : Pointer to a SD_HandleTypeDef structure that contains - * the configuration information. - * @retval SD Error Code - */ -uint32_t HAL_SD_GetError(const SD_HandleTypeDef *hsd) -{ - return hsd->ErrorCode; -} - -/** - * @brief Tx Transfer completed callbacks - * @param hsd: Pointer to SD handle - * @retval None - */ -__weak void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_TxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hsd: Pointer SD handle - * @retval None - */ -__weak void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_RxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief SD error callbacks - * @param hsd: Pointer SD handle - * @retval None - */ -__weak void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_ErrorCallback can be implemented in the user file - */ -} - -/** - * @brief SD Abort callbacks - * @param hsd: Pointer SD handle - * @retval None - */ -__weak void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_AbortCallback can be implemented in the user file - */ -} - -#if (USE_SD_TRANSCEIVER != 0U) -/** - * @brief Enable/Disable the SD Transceiver 1.8V Mode Callback. - * @param status: Voltage Switch State - * @retval None - */ -__weak void HAL_SD_DriveTransceiver_1_8V_Callback(FlagStatus status) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(status); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_EnableTransceiver could be implemented in the user file - */ -} -#endif /* USE_SD_TRANSCEIVER */ - -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a User SD Callback - * To be used instead of the weak (overridden) predefined callback - * @note The HAL_SD_RegisterCallback() may be called before HAL_SD_Init() in - * HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID - * and HAL_SD_MSP_DEINIT_CB_ID. - * @param hsd : SD handle - * @param CallbackID : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SD_TX_CPLT_CB_ID SD Tx Complete Callback ID - * @arg @ref HAL_SD_RX_CPLT_CB_ID SD Rx Complete Callback ID - * @arg @ref HAL_SD_ERROR_CB_ID SD Error Callback ID - * @arg @ref HAL_SD_ABORT_CB_ID SD Abort Callback ID - * @arg @ref HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Rx Linked List Node buffer Callback ID - * @arg @ref HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Tx Linked List Node buffer Callback ID - * @arg @ref HAL_SD_MSP_INIT_CB_ID SD MspInit Callback ID - * @arg @ref HAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_SD_RegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID, - pSD_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hsd->State == HAL_SD_STATE_READY) - { - switch (CallbackID) - { - case HAL_SD_TX_CPLT_CB_ID : - hsd->TxCpltCallback = pCallback; - break; - case HAL_SD_RX_CPLT_CB_ID : - hsd->RxCpltCallback = pCallback; - break; - case HAL_SD_ERROR_CB_ID : - hsd->ErrorCallback = pCallback; - break; - case HAL_SD_ABORT_CB_ID : - hsd->AbortCpltCallback = pCallback; - break; - case HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID : - hsd->Read_DMALnkLstBufCpltCallback = pCallback; - break; - case HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : - hsd->Write_DMALnkLstBufCpltCallback = pCallback; - break; - case HAL_SD_MSP_INIT_CB_ID : - hsd->MspInitCallback = pCallback; - break; - case HAL_SD_MSP_DEINIT_CB_ID : - hsd->MspDeInitCallback = pCallback; - break; - default : - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hsd->State == HAL_SD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_SD_MSP_INIT_CB_ID : - hsd->MspInitCallback = pCallback; - break; - case HAL_SD_MSP_DEINIT_CB_ID : - hsd->MspDeInitCallback = pCallback; - break; - default : - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User SD Callback - * SD Callback is redirected to the weak (overridden) predefined callback - * @note The HAL_SD_UnRegisterCallback() may be called before HAL_SD_Init() in - * HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID - * and HAL_SD_MSP_DEINIT_CB_ID. - * @param hsd : SD handle - * @param CallbackID : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_SD_TX_CPLT_CB_ID SD Tx Complete Callback ID - * @arg @ref HAL_SD_RX_CPLT_CB_ID SD Rx Complete Callback ID - * @arg @ref HAL_SD_ERROR_CB_ID SD Error Callback ID - * @arg @ref HAL_SD_ABORT_CB_ID SD Abort Callback ID - * @arg @ref HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Rx Linked List Node buffer Callback ID - * @arg @ref HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Tx Linked List Node buffer Callback ID - * @arg @ref HAL_SD_MSP_INIT_CB_ID SD MspInit Callback ID - * @arg @ref HAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hsd->State == HAL_SD_STATE_READY) - { - switch (CallbackID) - { - case HAL_SD_TX_CPLT_CB_ID : - hsd->TxCpltCallback = HAL_SD_TxCpltCallback; - break; - case HAL_SD_RX_CPLT_CB_ID : - hsd->RxCpltCallback = HAL_SD_RxCpltCallback; - break; - case HAL_SD_ERROR_CB_ID : - hsd->ErrorCallback = HAL_SD_ErrorCallback; - break; - case HAL_SD_ABORT_CB_ID : - hsd->AbortCpltCallback = HAL_SD_AbortCallback; - break; - case HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID : - hsd->Read_DMALnkLstBufCpltCallback = HAL_SDEx_Read_DMALnkLstBufCpltCallback; - break; - case HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : - hsd->Write_DMALnkLstBufCpltCallback = HAL_SDEx_Write_DMALnkLstBufCpltCallback; - break; - case HAL_SD_MSP_INIT_CB_ID : - hsd->MspInitCallback = HAL_SD_MspInit; - break; - case HAL_SD_MSP_DEINIT_CB_ID : - hsd->MspDeInitCallback = HAL_SD_MspDeInit; - break; - default : - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hsd->State == HAL_SD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_SD_MSP_INIT_CB_ID : - hsd->MspInitCallback = HAL_SD_MspInit; - break; - case HAL_SD_MSP_DEINIT_CB_ID : - hsd->MspDeInitCallback = HAL_SD_MspDeInit; - break; - default : - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -#if (USE_SD_TRANSCEIVER != 0U) -/** - * @brief Register a User SD Transceiver Callback - * To be used instead of the weak (overridden) predefined callback - * @param hsd : SD handle - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_SD_RegisterTransceiverCallback(SD_HandleTypeDef *hsd, pSD_TransceiverCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hsd); - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->DriveTransceiver_1_8V_Callback = pCallback; - } - else - { - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hsd); - return status; -} - -/** - * @brief Unregister a User SD Transceiver Callback - * SD Callback is redirected to the weak (overridden) predefined callback - * @param hsd : SD handle - * @retval status - */ -HAL_StatusTypeDef HAL_SD_UnRegisterTransceiverCallback(SD_HandleTypeDef *hsd) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hsd); - - if (hsd->State == HAL_SD_STATE_READY) - { - hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback; - } - else - { - /* Update the error code */ - hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hsd); - return status; -} -#endif /* USE_SD_TRANSCEIVER */ -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @addtogroup SD_Exported_Functions_Group3 - * @brief management functions - * -@verbatim - ============================================================================== - ##### Peripheral Control functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to control the SD card - operations and get the related information - -@endverbatim - * @{ - */ - -/** - * @brief Returns information the information of the card which are stored on - * the CID register. - * @param hsd: Pointer to SD handle - * @param pCID: Pointer to a HAL_SD_CardCIDTypeDef structure that - * contains all CID register parameters - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID) -{ - pCID->ManufacturerID = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24U); - - pCID->OEM_AppliID = (uint16_t)((hsd->CID[0] & 0x00FFFF00U) >> 8U); - - pCID->ProdName1 = (((hsd->CID[0] & 0x000000FFU) << 24U) | ((hsd->CID[1] & 0xFFFFFF00U) >> 8U)); - - pCID->ProdName2 = (uint8_t)(hsd->CID[1] & 0x000000FFU); - - pCID->ProdRev = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24U); - - pCID->ProdSN = (((hsd->CID[2] & 0x00FFFFFFU) << 8U) | ((hsd->CID[3] & 0xFF000000U) >> 24U)); - - pCID->Reserved1 = (uint8_t)((hsd->CID[3] & 0x00F00000U) >> 20U); - - pCID->ManufactDate = (uint16_t)((hsd->CID[3] & 0x000FFF00U) >> 8U); - - pCID->CID_CRC = (uint8_t)((hsd->CID[3] & 0x000000FEU) >> 1U); - - pCID->Reserved2 = 1U; - - return HAL_OK; -} - -/** - * @brief Returns information the information of the card which are stored on - * the CSD register. - * @param hsd: Pointer to SD handle - * @param pCSD: Pointer to a HAL_SD_CardCSDTypeDef structure that - * contains all CSD register parameters - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD) -{ - pCSD->CSDStruct = (uint8_t)((hsd->CSD[0] & 0xC0000000U) >> 30U); - - pCSD->SysSpecVersion = (uint8_t)((hsd->CSD[0] & 0x3C000000U) >> 26U); - - pCSD->Reserved1 = (uint8_t)((hsd->CSD[0] & 0x03000000U) >> 24U); - - pCSD->TAAC = (uint8_t)((hsd->CSD[0] & 0x00FF0000U) >> 16U); - - pCSD->NSAC = (uint8_t)((hsd->CSD[0] & 0x0000FF00U) >> 8U); - - pCSD->MaxBusClkFrec = (uint8_t)(hsd->CSD[0] & 0x000000FFU); - - pCSD->CardComdClasses = (uint16_t)((hsd->CSD[1] & 0xFFF00000U) >> 20U); - - pCSD->RdBlockLen = (uint8_t)((hsd->CSD[1] & 0x000F0000U) >> 16U); - - pCSD->PartBlockRead = (uint8_t)((hsd->CSD[1] & 0x00008000U) >> 15U); - - pCSD->WrBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00004000U) >> 14U); - - pCSD->RdBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00002000U) >> 13U); - - pCSD->DSRImpl = (uint8_t)((hsd->CSD[1] & 0x00001000U) >> 12U); - - pCSD->Reserved2 = 0U; /*!< Reserved */ - - if (hsd->SdCard.CardType == CARD_SDSC) - { - pCSD->DeviceSize = (((hsd->CSD[1] & 0x000003FFU) << 2U) | ((hsd->CSD[2] & 0xC0000000U) >> 30U)); - - pCSD->MaxRdCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x38000000U) >> 27U); - - pCSD->MaxRdCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x07000000U) >> 24U); - - pCSD->MaxWrCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x00E00000U) >> 21U); - - pCSD->MaxWrCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x001C0000U) >> 18U); - - pCSD->DeviceSizeMul = (uint8_t)((hsd->CSD[2] & 0x00038000U) >> 15U); - - hsd->SdCard.BlockNbr = (pCSD->DeviceSize + 1U) ; - hsd->SdCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U)); - hsd->SdCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU)); - - hsd->SdCard.LogBlockNbr = (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / BLOCKSIZE); - hsd->SdCard.LogBlockSize = BLOCKSIZE; - } - else if (hsd->SdCard.CardType == CARD_SDHC_SDXC) - { - /* Byte 7 */ - pCSD->DeviceSize = (((hsd->CSD[1] & 0x0000003FU) << 16U) | ((hsd->CSD[2] & 0xFFFF0000U) >> 16U)); - - hsd->SdCard.BlockNbr = ((pCSD->DeviceSize + 1U) * 1024U); - hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr; - hsd->SdCard.BlockSize = BLOCKSIZE; - hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize; - } - else - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - pCSD->EraseGrSize = (uint8_t)((hsd->CSD[2] & 0x00004000U) >> 14U); - - pCSD->EraseGrMul = (uint8_t)((hsd->CSD[2] & 0x00003F80U) >> 7U); - - pCSD->WrProtectGrSize = (uint8_t)(hsd->CSD[2] & 0x0000007FU); - - pCSD->WrProtectGrEnable = (uint8_t)((hsd->CSD[3] & 0x80000000U) >> 31U); - - pCSD->ManDeflECC = (uint8_t)((hsd->CSD[3] & 0x60000000U) >> 29U); - - pCSD->WrSpeedFact = (uint8_t)((hsd->CSD[3] & 0x1C000000U) >> 26U); - - pCSD->MaxWrBlockLen = (uint8_t)((hsd->CSD[3] & 0x03C00000U) >> 22U); - - pCSD->WriteBlockPaPartial = (uint8_t)((hsd->CSD[3] & 0x00200000U) >> 21U); - - pCSD->Reserved3 = 0; - - pCSD->ContentProtectAppli = (uint8_t)((hsd->CSD[3] & 0x00010000U) >> 16U); - - pCSD->FileFormatGroup = (uint8_t)((hsd->CSD[3] & 0x00008000U) >> 15U); - - pCSD->CopyFlag = (uint8_t)((hsd->CSD[3] & 0x00004000U) >> 14U); - - pCSD->PermWrProtect = (uint8_t)((hsd->CSD[3] & 0x00002000U) >> 13U); - - pCSD->TempWrProtect = (uint8_t)((hsd->CSD[3] & 0x00001000U) >> 12U); - - pCSD->FileFormat = (uint8_t)((hsd->CSD[3] & 0x00000C00U) >> 10U); - - pCSD->ECC = (uint8_t)((hsd->CSD[3] & 0x00000300U) >> 8U); - - pCSD->CSD_CRC = (uint8_t)((hsd->CSD[3] & 0x000000FEU) >> 1U); - - pCSD->Reserved4 = 1; - - return HAL_OK; -} - -/** - * @brief Gets the SD status info.( shall be called if there is no SD transaction ongoing ) - * @param hsd: Pointer to SD handle - * @param pStatus: Pointer to the HAL_SD_CardStatusTypeDef structure that - * will contain the SD card status information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus) -{ - uint32_t sd_status[16]; - uint32_t errorstate; - HAL_StatusTypeDef status = HAL_OK; - - if (hsd->State == HAL_SD_STATE_BUSY) - { - return HAL_ERROR; - } - - errorstate = SD_SendSDStatus(hsd, sd_status); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - status = HAL_ERROR; - } - else - { - pStatus->DataBusWidth = (uint8_t)((sd_status[0] & 0xC0U) >> 6U); - - pStatus->SecuredMode = (uint8_t)((sd_status[0] & 0x20U) >> 5U); - - pStatus->CardType = (uint16_t)(((sd_status[0] & 0x00FF0000U) >> 8U) | ((sd_status[0] & 0xFF000000U) >> 24U)); - - pStatus->ProtectedAreaSize = (((sd_status[1] & 0xFFU) << 24U) | ((sd_status[1] & 0xFF00U) << 8U) | - ((sd_status[1] & 0xFF0000U) >> 8U) | ((sd_status[1] & 0xFF000000U) >> 24U)); - - pStatus->SpeedClass = (uint8_t)(sd_status[2] & 0xFFU); - - pStatus->PerformanceMove = (uint8_t)((sd_status[2] & 0xFF00U) >> 8U); - - pStatus->AllocationUnitSize = (uint8_t)((sd_status[2] & 0xF00000U) >> 20U); - - pStatus->EraseSize = (uint16_t)(((sd_status[2] & 0xFF000000U) >> 16U) | (sd_status[3] & 0xFFU)); - - pStatus->EraseTimeout = (uint8_t)((sd_status[3] & 0xFC00U) >> 10U); - - pStatus->EraseOffset = (uint8_t)((sd_status[3] & 0x0300U) >> 8U); - - pStatus->UhsSpeedGrade = (uint8_t)((sd_status[3] & 0x00F0U) >> 4U); - pStatus->UhsAllocationUnitSize = (uint8_t)(sd_status[3] & 0x000FU) ; - pStatus->VideoSpeedClass = (uint8_t)((sd_status[4] & 0xFF000000U) >> 24U); - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode = errorstate; - hsd->State = HAL_SD_STATE_READY; - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Gets the SD card info. - * @param hsd: Pointer to SD handle - * @param pCardInfo: Pointer to the HAL_SD_CardInfoTypeDef structure that - * will contain the SD card status information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo) -{ - pCardInfo->CardType = (uint32_t)(hsd->SdCard.CardType); - pCardInfo->CardVersion = (uint32_t)(hsd->SdCard.CardVersion); - pCardInfo->Class = (uint32_t)(hsd->SdCard.Class); - pCardInfo->RelCardAdd = (uint32_t)(hsd->SdCard.RelCardAdd); - pCardInfo->BlockNbr = (uint32_t)(hsd->SdCard.BlockNbr); - pCardInfo->BlockSize = (uint32_t)(hsd->SdCard.BlockSize); - pCardInfo->LogBlockNbr = (uint32_t)(hsd->SdCard.LogBlockNbr); - pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize); - - return HAL_OK; -} - -/** - * @brief Enables wide bus operation for the requested card if supported by - * card. - * @param hsd: Pointer to SD handle - * @param WideMode: Specifies the SD card wide bus mode - * This parameter can be one of the following values: - * @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer - * @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer - * @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode) -{ - SDMMC_InitTypeDef Init; - uint32_t errorstate; - uint32_t sdmmc_clk; - - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_SDMMC_BUS_WIDE(WideMode)); - - /* Change State */ - hsd->State = HAL_SD_STATE_BUSY; - - if (hsd->SdCard.CardType != CARD_SECURED) - { - if (WideMode == SDMMC_BUS_WIDE_8B) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - else if (WideMode == SDMMC_BUS_WIDE_4B) - { - errorstate = SD_WideBus_Enable(hsd); - - hsd->ErrorCode |= errorstate; - } - else if (WideMode == SDMMC_BUS_WIDE_1B) - { - errorstate = SD_WideBus_Disable(hsd); - - hsd->ErrorCode |= errorstate; - } - else - { - /* WideMode is not a valid argument*/ - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - } - } - else - { - /* SD Card does not support this feature */ - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - - if (hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - status = HAL_ERROR; - } - else - { - sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); - if (sdmmc_clk != 0U) - { - /* Configure the SDMMC peripheral */ - Init.ClockEdge = hsd->Init.ClockEdge; - Init.ClockPowerSave = hsd->Init.ClockPowerSave; - Init.BusWide = WideMode; - Init.HardwareFlowControl = hsd->Init.HardwareFlowControl; - - /* Check if user Clock div < Normal speed 25Mhz, no change in Clockdiv */ - if (hsd->Init.ClockDiv >= (sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ))) - { - Init.ClockDiv = hsd->Init.ClockDiv; - } - else if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) - { - /* UltraHigh speed SD card,user Clock div */ - Init.ClockDiv = hsd->Init.ClockDiv; - } - else if (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) - { - /* High speed SD card, Max Frequency = 50Mhz */ - if (hsd->Init.ClockDiv == 0U) - { - if (sdmmc_clk > SD_HIGH_SPEED_FREQ) - { - Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ); - } - else - { - Init.ClockDiv = hsd->Init.ClockDiv; - } - } - else - { - if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_HIGH_SPEED_FREQ) - { - Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ); - } - else - { - Init.ClockDiv = hsd->Init.ClockDiv; - } - } - } - else - { - /* No High speed SD card, Max Frequency = 25Mhz */ - if (hsd->Init.ClockDiv == 0U) - { - if (sdmmc_clk > SD_NORMAL_SPEED_FREQ) - { - Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ); - } - else - { - Init.ClockDiv = hsd->Init.ClockDiv; - } - } - else - { - if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_NORMAL_SPEED_FREQ) - { - Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ); - } - else - { - Init.ClockDiv = hsd->Init.ClockDiv; - } - } - } - -#if (USE_SD_TRANSCEIVER != 0U) - Init.TranceiverPresent = hsd->Init.TranceiverPresent; -#endif /* USE_SD_TRANSCEIVER */ - - (void)SDMMC_Init(hsd->Instance, Init); - } - else - { - hsd->ErrorCode |= SDMMC_ERROR_INVALID_PARAMETER; - status = HAL_ERROR; - } - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - status = HAL_ERROR; - } - - /* Change State */ - hsd->State = HAL_SD_STATE_READY; - - return status; -} - -/** - * @brief Configure the speed bus mode - * @param hsd: Pointer to the SD handle - * @param SpeedMode: Specifies the SD card speed bus mode - * This parameter can be one of the following values: - * @arg SDMMC_SPEED_MODE_AUTO: Max speed mode supported by the card - * @arg SDMMC_SPEED_MODE_DEFAULT: Default Speed/SDR12 mode - * @arg SDMMC_SPEED_MODE_HIGH: High Speed/SDR25 mode - * @arg SDMMC_SPEED_MODE_ULTRA: Ultra high speed mode - * @retval HAL status - */ - -HAL_StatusTypeDef HAL_SD_ConfigSpeedBusOperation(SD_HandleTypeDef *hsd, uint32_t SpeedMode) -{ - uint32_t tickstart; - uint32_t errorstate; - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_SDMMC_SPEED_MODE(SpeedMode)); - /* Change State */ - hsd->State = HAL_SD_STATE_BUSY; - -#if (USE_SD_TRANSCEIVER != 0U) - if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) - { - switch (SpeedMode) - { - case SDMMC_SPEED_MODE_AUTO: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED; - /* Enable Ultra High Speed */ - if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - } - else if (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) - { - /* Enable High Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - else - { - /*Nothing to do, Use defaultSpeed */ - } - break; - } - case SDMMC_SPEED_MODE_ULTRA_SDR104: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable UltraHigh Speed */ - if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED; - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_ULTRA_SDR50: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable UltraHigh Speed */ - if (SD_UltraHighSpeed(hsd, SDMMC_SDR50_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED; - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_DDR: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable DDR Mode*/ - if (SD_DDR_Mode(hsd) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED | SDMMC_CLKCR_DDR; - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_HIGH: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable High Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_DEFAULT: - { - /* Switch to default Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - - break; - } - default: - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - status = HAL_ERROR; - break; - } - } - else - { - switch (SpeedMode) - { - case SDMMC_SPEED_MODE_AUTO: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable High Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - else - { - /*Nothing to do, Use defaultSpeed */ - } - break; - } - case SDMMC_SPEED_MODE_HIGH: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable High Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_DEFAULT: - { - /* Switch to default Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - - break; - } - case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/ - default: - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - status = HAL_ERROR; - break; - } - } -#else - switch (SpeedMode) - { - case SDMMC_SPEED_MODE_AUTO: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable High Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - else - { - /*Nothing to do, Use defaultSpeed */ - } - break; - } - case SDMMC_SPEED_MODE_HIGH: - { - if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || - (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || - (hsd->SdCard.CardType == CARD_SDHC_SDXC)) - { - /* Enable High Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - } - else - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - break; - } - case SDMMC_SPEED_MODE_DEFAULT: - { - /* Switch to default Speed */ - if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - status = HAL_ERROR; - } - - break; - } - case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/ - default: - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - status = HAL_ERROR; - break; - } -#endif /* USE_SD_TRANSCEIVER */ - - /* Verify that SD card is ready to use after Speed mode switch*/ - tickstart = HAL_GetTick(); - while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if (errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - status = HAL_ERROR; - } - - /* Change State */ - hsd->State = HAL_SD_STATE_READY; - return status; -} - -/** - * @brief Gets the current sd card data state. - * @param hsd: pointer to SD handle - * @retval Card state - */ -HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd) -{ - uint32_t cardstate; - uint32_t errorstate; - uint32_t resp1 = 0; - - errorstate = SD_SendStatus(hsd, &resp1); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= errorstate; - } - - cardstate = ((resp1 >> 9U) & 0x0FU); - - return (HAL_SD_CardStateTypeDef)cardstate; -} - -/** - * @brief Abort the current transfer and disable the SD. - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information for SD module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd) -{ - uint32_t error_code; - uint32_t tickstart; - - if (hsd->State == HAL_SD_STATE_BUSY) - { - /* DIsable All interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); - __SDMMC_CMDTRANS_DISABLE(hsd->Instance); - - /*we will send the CMD12 in all cases in order to stop the data transfers*/ - /*In case the data transfer just finished , the external memory will not respond - and will return HAL_SD_ERROR_CMD_RSP_TIMEOUT*/ - /*In case the data transfer aborted , the external memory will respond and will return HAL_SD_ERROR_NONE*/ - /*Other scenario will return HAL_ERROR*/ - - hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); - error_code = hsd->ErrorCode; - if ((error_code != HAL_SD_ERROR_NONE) && (error_code != HAL_SD_ERROR_CMD_RSP_TIMEOUT)) - { - return HAL_ERROR; - } - - tickstart = HAL_GetTick(); - if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_CARD) - { - if (hsd->ErrorCode == HAL_SD_ERROR_NONE) - { - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_BUSYD0END)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_TIMEOUT; - } - } - } - - if (hsd->ErrorCode == HAL_SD_ERROR_CMD_RSP_TIMEOUT) - { - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - else if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_SDMMC) - { - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_DATAEND)) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_TIMEOUT; - } - } - } - else - { - /* Nothing to do*/ - } - - /*The reason of all these while conditions previously is that we need to wait the SDMMC and clear - the appropriate flags that will be set depending of the abort/non abort of the memory */ - /*Not waiting the SDMMC flags will cause the next SDMMC_DISABLE_IDMA to not get cleared - and will result in next SDMMC read/write operation to fail */ - - /*SDMMC ready for clear data flags*/ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_BUSYD0END); - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - /* If IDMA Context, disable Internal DMA */ - hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - hsd->State = HAL_SD_STATE_READY; - - /* Initialize the SD operation */ - hsd->Context = SD_CONTEXT_NONE; - } - return HAL_OK; -} - -/** - * @brief Abort the current transfer and disable the SD (IT mode). - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information for SD module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd) -{ - HAL_SD_CardStateTypeDef CardState; - - /* Disable All interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ - SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); - - /* If IDMA Context, disable Internal DMA */ - hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; - - /* Clear All flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - CardState = HAL_SD_GetCardState(hsd); - hsd->State = HAL_SD_STATE_READY; - - if ((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) - { - hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); - } - - if (hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - return HAL_ERROR; - } - else - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->AbortCpltCallback(hsd); -#else - HAL_SD_AbortCallback(hsd); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -/* Private function ----------------------------------------------------------*/ -/** @addtogroup SD_Private_Functions - * @{ - */ - -/** - * @brief Initializes the sd card. - * @param hsd: Pointer to SD handle - * @retval SD Card error state - */ -static uint32_t SD_InitCard(SD_HandleTypeDef *hsd) -{ - HAL_SD_CardCSDTypeDef CSD; - uint32_t errorstate; - uint16_t sd_rca = 0U; - uint32_t tickstart = HAL_GetTick(); - - /* Check the power State */ - if (SDMMC_GetPowerState(hsd->Instance) == 0U) - { - /* Power off */ - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - } - - if (hsd->SdCard.CardType != CARD_SECURED) - { - /* Send CMD2 ALL_SEND_CID */ - errorstate = SDMMC_CmdSendCID(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card identification number data */ - hsd->CID[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); - hsd->CID[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2); - hsd->CID[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3); - hsd->CID[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4); - } - } - - if (hsd->SdCard.CardType != CARD_SECURED) - { - /* Send CMD3 SET_REL_ADDR with argument 0 */ - /* SD Card publishes its RCA. */ - while (sd_rca == 0U) - { - errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - if ((HAL_GetTick() - tickstart) >= SDMMC_CMDTIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } - } - } - if (hsd->SdCard.CardType != CARD_SECURED) - { - /* Get the SD card RCA */ - hsd->SdCard.RelCardAdd = sd_rca; - - /* Send CMD9 SEND_CSD with argument as card's RCA */ - errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card Specific Data */ - hsd->CSD[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); - hsd->CSD[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2); - hsd->CSD[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3); - hsd->CSD[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4); - } - } - - /* Get the Card Class */ - hsd->SdCard.Class = (SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2) >> 20U); - - /* Get CSD parameters */ - if (HAL_SD_GetCardCSD(hsd, &CSD) != HAL_OK) - { - return HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - - /* Select the Card */ - errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* All cards are initialized */ - return HAL_SD_ERROR_NONE; -} - -/** - * @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: Pointer to SD handle - * @retval error state - */ -static uint32_t SD_PowerON(SD_HandleTypeDef *hsd) -{ - __IO uint32_t count = 0U; - uint32_t response = 0U; - uint32_t validvoltage = 0U; - uint32_t errorstate; -#if (USE_SD_TRANSCEIVER != 0U) - uint32_t tickstart = HAL_GetTick(); -#endif /* USE_SD_TRANSCEIVER */ - - /* CMD0: GO_IDLE_STATE */ - errorstate = SDMMC_CmdGoIdleState(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */ - errorstate = SDMMC_CmdOperCond(hsd->Instance); - if (errorstate == SDMMC_ERROR_TIMEOUT) /* No response to CMD8 */ - { - hsd->SdCard.CardVersion = CARD_V1_X; - /* CMD0: GO_IDLE_STATE */ - errorstate = SDMMC_CmdGoIdleState(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - } - else - { - hsd->SdCard.CardVersion = CARD_V2_X; - } - - if (hsd->SdCard.CardVersion == CARD_V2_X) - { - /* SEND CMD55 APP_CMD with RCA as 0 */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0); - if (errorstate != HAL_SD_ERROR_NONE) - { - return HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - } - /* SD CARD */ - /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ - while ((count < SDMMC_MAX_VOLT_TRIAL) && (validvoltage == 0U)) - { - /* SEND CMD55 APP_CMD with RCA as 0 */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Send CMD41 */ - errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_VOLTAGE_WINDOW_SD | SDMMC_HIGH_CAPACITY | - SD_SWITCH_1_8V_CAPACITY); - if (errorstate != HAL_SD_ERROR_NONE) - { - return HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - - /* Get command response */ - response = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); - - /* Get operating voltage*/ - validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); - - count++; - } - - if (count >= SDMMC_MAX_VOLT_TRIAL) - { - return HAL_SD_ERROR_INVALID_VOLTRANGE; - } - - /* Set default card type */ - hsd->SdCard.CardType = CARD_SDSC; - - if ((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY) - { - hsd->SdCard.CardType = CARD_SDHC_SDXC; -#if (USE_SD_TRANSCEIVER != 0U) - if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) - { - if ((response & SD_SWITCH_1_8V_CAPACITY) == SD_SWITCH_1_8V_CAPACITY) - { - hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED; - - /* Start switching procedue */ - hsd->Instance->POWER |= SDMMC_POWER_VSWITCHEN; - - /* Send CMD11 to switch 1.8V mode */ - errorstate = SDMMC_CmdVoltageSwitch(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Check to CKSTOP */ - while ((hsd->Instance->STA & SDMMC_FLAG_CKSTOP) != SDMMC_FLAG_CKSTOP) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } - } - - /* Clear CKSTOP Flag */ - hsd->Instance->ICR = SDMMC_FLAG_CKSTOP; - - /* Check to BusyD0 */ - if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) != SDMMC_FLAG_BUSYD0) - { - /* Error when activate Voltage Switch in SDMMC Peripheral */ - return SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { - /* Enable Transceiver Switch PIN */ -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->DriveTransceiver_1_8V_Callback(SET); -#else - HAL_SD_DriveTransceiver_1_8V_Callback(SET); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ - - /* Switch ready */ - hsd->Instance->POWER |= SDMMC_POWER_VSWITCH; - - /* Check VSWEND Flag */ - while ((hsd->Instance->STA & SDMMC_FLAG_VSWEND) != SDMMC_FLAG_VSWEND) - { - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } - } - - /* Clear VSWEND Flag */ - hsd->Instance->ICR = SDMMC_FLAG_VSWEND; - - /* Check BusyD0 status */ - if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) == SDMMC_FLAG_BUSYD0) - { - /* Error when enabling 1.8V mode */ - return HAL_SD_ERROR_INVALID_VOLTRANGE; - } - /* Switch to 1.8V OK */ - - /* Disable VSWITCH FLAG from SDMMC Peripheral */ - hsd->Instance->POWER = 0x13U; - - /* Clean Status flags */ - hsd->Instance->ICR = 0xFFFFFFFFU; - } - } - } -#endif /* USE_SD_TRANSCEIVER */ - } - - return HAL_SD_ERROR_NONE; -} - -/** - * @brief Turns the SDMMC output signals off. - * @param hsd: Pointer to SD handle - * @retval None - */ -static void SD_PowerOFF(SD_HandleTypeDef *hsd) -{ - /* Set Power State to OFF */ - (void)SDMMC_PowerState_OFF(hsd->Instance); -} - -/** - * @brief Send Status info command. - * @param hsd: pointer to SD handle - * @param pSDstatus: Pointer to the buffer that will contain the SD card status - * SD Status register) - * @retval error state - */ -static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t count; - uint32_t *pData = pSDstatus; - - /* Check SD response */ - if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; - } - - /* Set block size for card if it is not equal to current block size for card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_NONE; - return errorstate; - } - - /* Send CMD55 */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_NONE; - return errorstate; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = 64U; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_ENABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - /* Send ACMD13 (SD_APP_STAUS) with argument as card's RCA */ - errorstate = SDMMC_CmdStatusRegister(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= HAL_SD_ERROR_NONE; - return errorstate; - } - - /* Get status data */ - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) - { - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) - { - for (count = 0U; count < 8U; count++) - { - *pData = SDMMC_ReadFIFO(hsd->Instance); - pData++; - } - } - - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } - } - - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - return HAL_SD_ERROR_DATA_TIMEOUT; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - return HAL_SD_ERROR_DATA_CRC_FAIL; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) - { - return HAL_SD_ERROR_RX_OVERRUN; - } - else - { - /* Nothing to do */ - } - - while ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DPSMACT))) - { - *pData = SDMMC_ReadFIFO(hsd->Instance); - pData++; - - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } - } - - /* Clear all the static status flags*/ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - return HAL_SD_ERROR_NONE; -} - -/** - * @brief Returns the current card's status. - * @param hsd: Pointer to SD handle - * @param pCardStatus: pointer to the buffer that will contain the SD card - * status (Card Status register) - * @retval error state - */ -static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus) -{ - uint32_t errorstate; - - if (pCardStatus == NULL) - { - return HAL_SD_ERROR_PARAM; - } - - /* Send Status command */ - errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Get SD card status */ - *pCardStatus = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); - - return HAL_SD_ERROR_NONE; -} - -/** - * @brief Enables the SDMMC wide bus mode. - * @param hsd: pointer to SD handle - * @retval error state - */ -static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd) -{ - uint32_t scr[2U] = {0UL, 0UL}; - uint32_t errorstate; - - if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; - } - - /* Get SCR Register */ - errorstate = SD_FindSCR(hsd, scr); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* If requested card supports wide bus operation */ - if ((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO) - { - /* Send CMD55 APP_CMD with argument as card's RCA.*/ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */ - errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - return HAL_SD_ERROR_NONE; - } - else - { - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - } -} - -/** - * @brief Disables the SDMMC wide bus mode. - * @param hsd: Pointer to SD handle - * @retval error state - */ -static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd) -{ - uint32_t scr[2U] = {0UL, 0UL}; - uint32_t errorstate; - - if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; - } - - /* Get SCR Register */ - errorstate = SD_FindSCR(hsd, scr); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* If requested card supports 1 bit mode operation */ - if ((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO) - { - /* Send CMD55 APP_CMD with argument as card's RCA */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */ - errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - return HAL_SD_ERROR_NONE; - } - else - { - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - } -} - -/** - * @brief Finds the SD card SCR register value. - * @param hsd: Pointer to SD handle - * @param pSCR: pointer to the buffer that will contain the SCR value - * @retval error state - */ -static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t tickstart = HAL_GetTick(); - uint32_t index = 0U; - uint32_t tempscr[2U] = {0UL, 0UL}; - uint32_t *scr = pSCR; - - /* Set Block Size To 8 Bytes */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Send CMD55 APP_CMD with argument as card's RCA */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U)); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = 8U; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_8B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_ENABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */ - errorstate = SDMMC_CmdSendSCR(hsd->Instance); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | - SDMMC_FLAG_DATAEND)) - { - if ((!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOE)) && (index == 0U)) - { - tempscr[0] = SDMMC_ReadFIFO(hsd->Instance); - tempscr[1] = SDMMC_ReadFIFO(hsd->Instance); - index++; - } - - if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } - } - - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); - - return HAL_SD_ERROR_DATA_TIMEOUT; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); - - return HAL_SD_ERROR_DATA_CRC_FAIL; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); - - return HAL_SD_ERROR_RX_OVERRUN; - } - else - { - /* No error flag set */ - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - *scr = (((tempscr[1] & SDMMC_0TO7BITS) << 24U) | ((tempscr[1] & SDMMC_8TO15BITS) << 8U) | \ - ((tempscr[1] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24U)); - scr++; - *scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24U) | ((tempscr[0] & SDMMC_8TO15BITS) << 8U) | \ - ((tempscr[0] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24U)); - - } - - return HAL_SD_ERROR_NONE; -} - -/** - * @brief Wrap up reading in non-blocking mode. - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information. - * @retval None - */ -static void SD_Read_IT(SD_HandleTypeDef *hsd) -{ - uint32_t count; - uint32_t data; - uint8_t *tmp; - - tmp = hsd->pRxBuffPtr; - - if (hsd->RxXferSize >= SDMMC_FIFO_SIZE) - { - /* Read data from SDMMC Rx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = SDMMC_ReadFIFO(hsd->Instance); - *tmp = (uint8_t)(data & 0xFFU); - tmp++; - *tmp = (uint8_t)((data >> 8U) & 0xFFU); - tmp++; - *tmp = (uint8_t)((data >> 16U) & 0xFFU); - tmp++; - *tmp = (uint8_t)((data >> 24U) & 0xFFU); - tmp++; - } - - hsd->pRxBuffPtr = tmp; - hsd->RxXferSize -= SDMMC_FIFO_SIZE; - } -} - -/** - * @brief Wrap up writing in non-blocking mode. - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information. - * @retval None - */ -static void SD_Write_IT(SD_HandleTypeDef *hsd) -{ - uint32_t count; - uint32_t data; - const uint8_t *tmp; - - tmp = hsd->pTxBuffPtr; - - if (hsd->TxXferSize >= SDMMC_FIFO_SIZE) - { - /* Write data to SDMMC Tx FIFO */ - for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) - { - data = (uint32_t)(*tmp); - tmp++; - data |= ((uint32_t)(*tmp) << 8U); - tmp++; - data |= ((uint32_t)(*tmp) << 16U); - tmp++; - data |= ((uint32_t)(*tmp) << 24U); - tmp++; - (void)SDMMC_WriteFIFO(hsd->Instance, &data); - } - - hsd->pTxBuffPtr = tmp; - hsd->TxXferSize -= SDMMC_FIFO_SIZE; - } -} - -/** - * @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 SDMMCCK clock between 25 and 50 MHz - * @param hsd: SD handle - * @param SwitchSpeedMode: SD speed mode( SDMMC_SDR12_SWITCH_PATTERN, SDMMC_SDR25_SWITCH_PATTERN) - * @retval SD Card error state - */ -uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode) -{ - uint32_t errorstate = HAL_SD_ERROR_NONE; - SDMMC_DataInitTypeDef sdmmc_datainitstructure; - uint32_t SD_hs[16] = {0}; - uint32_t count; - uint32_t loop = 0 ; - uint32_t Timeout = HAL_GetTick(); - - if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED) - { - /* Standard Speed Card <= 12.5Mhz */ - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - } - - if (hsd->SdCard.CardSpeed >= CARD_HIGH_SPEED) - { - /* Initialize the Data control register */ - hsd->Instance->DCTRL = 0; - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); - - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - sdmmc_datainitstructure.DataTimeOut = SDMMC_DATATIMEOUT; - sdmmc_datainitstructure.DataLength = 64U; - sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ; - sdmmc_datainitstructure.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - sdmmc_datainitstructure.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - sdmmc_datainitstructure.DPSM = SDMMC_DPSM_ENABLE; - - (void)SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure); - - errorstate = SDMMC_CmdSwitch(hsd->Instance, SwitchSpeedMode); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | - SDMMC_FLAG_DATAEND)) - { - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) - { - for (count = 0U; count < 8U; count++) - { - SD_hs[(8U * loop) + count] = SDMMC_ReadFIFO(hsd->Instance); - } - loop ++; - } - if ((HAL_GetTick() - Timeout) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_SD_ERROR_TIMEOUT; - } - } - - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); - - return errorstate; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); - - errorstate = SDMMC_ERROR_DATA_CRC_FAIL; - - return errorstate; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); - - errorstate = SDMMC_ERROR_RX_OVERRUN; - - return errorstate; - } - else - { - /* No error flag set */ - } - - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - /* Test if the switch mode HS is ok */ - if ((((uint8_t *)SD_hs)[13] & 2U) != 2U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - - } - - return errorstate; -} - -#if (USE_SD_TRANSCEIVER != 0U) -/** - * @brief Switches the SD card to Ultra High Speed mode. - * This API must be used after "Transfer State" - * @note This operation should be followed by the configuration - * of PLL to have SDMMCCK clock between 50 and 120 MHz - * @param hsd: SD handle - * @param UltraHighSpeedMode: SD speed mode( SDMMC_SDR50_SWITCH_PATTERN, SDMMC_SDR104_SWITCH_PATTERN) - * @retval SD Card error state - */ -static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode) -{ - uint32_t errorstate = HAL_SD_ERROR_NONE; - SDMMC_DataInitTypeDef sdmmc_datainitstructure; - uint32_t SD_hs[16] = {0}; - uint32_t count; - uint32_t loop = 0 ; - uint32_t Timeout = HAL_GetTick(); - - if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED) - { - /* Standard Speed Card <= 12.5Mhz */ - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - } - - if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) - { - /* Initialize the Data control register */ - hsd->Instance->DCTRL = 0; - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); - - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - sdmmc_datainitstructure.DataTimeOut = SDMMC_DATATIMEOUT; - sdmmc_datainitstructure.DataLength = 64U; - sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ; - sdmmc_datainitstructure.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - sdmmc_datainitstructure.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - sdmmc_datainitstructure.DPSM = SDMMC_DPSM_ENABLE; - - if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK) - { - return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR); - } - - errorstate = SDMMC_CmdSwitch(hsd->Instance, UltraHighSpeedMode); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | - SDMMC_FLAG_DATAEND)) - { - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) - { - for (count = 0U; count < 8U; count++) - { - SD_hs[(8U * loop) + count] = SDMMC_ReadFIFO(hsd->Instance); - } - loop ++; - } - - if ((HAL_GetTick() - Timeout) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_SD_ERROR_TIMEOUT; - } - } - - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); - - return errorstate; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); - - errorstate = SDMMC_ERROR_DATA_CRC_FAIL; - - return errorstate; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); - - errorstate = SDMMC_ERROR_RX_OVERRUN; - - return errorstate; - } - else - { - /* No error flag set */ - } - - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - /* Test if the switch mode HS is ok */ - if ((((uint8_t *)SD_hs)[13] & 2U) != 2U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->DriveTransceiver_1_8V_Callback(SET); -#else - HAL_SD_DriveTransceiver_1_8V_Callback(SET); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ -#if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2) - /* Enable DelayBlock Peripheral */ - /* SDMMC_FB_CLK tuned feedback clock selected as receive clock, for SDR104 */ - MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_1); - LL_DLYB_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance)); -#endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */ - } - } - - return errorstate; -} - -/** - * @brief Switches the SD card to Double Data Rate (DDR) mode. - * This API must be used after "Transfer State" - * @note This operation should be followed by the configuration - * of PLL to have SDMMCCK clock less than 50MHz - * @param hsd: SD handle - * @retval SD Card error state - */ -static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd) -{ - uint32_t errorstate = HAL_SD_ERROR_NONE; - SDMMC_DataInitTypeDef sdmmc_datainitstructure; - uint32_t SD_hs[16] = {0}; - uint32_t count; - uint32_t loop = 0 ; - uint32_t Timeout = HAL_GetTick(); - - if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED) - { - /* Standard Speed Card <= 12.5Mhz */ - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - } - - if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) - { - /* Initialize the Data control register */ - hsd->Instance->DCTRL = 0; - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); - - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - sdmmc_datainitstructure.DataTimeOut = SDMMC_DATATIMEOUT; - sdmmc_datainitstructure.DataLength = 64U; - sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ; - sdmmc_datainitstructure.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - sdmmc_datainitstructure.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - sdmmc_datainitstructure.DPSM = SDMMC_DPSM_ENABLE; - - if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK) - { - return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR); - } - - errorstate = SDMMC_CmdSwitch(hsd->Instance, SDMMC_DDR50_SWITCH_PATTERN); - if (errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | - SDMMC_FLAG_DATAEND)) - { - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) - { - for (count = 0U; count < 8U; count++) - { - SD_hs[(8U * loop) + count] = SDMMC_ReadFIFO(hsd->Instance); - } - loop ++; - } - - if ((HAL_GetTick() - Timeout) >= SDMMC_SWDATATIMEOUT) - { - hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_SD_ERROR_TIMEOUT; - } - } - - if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); - - return errorstate; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); - - errorstate = SDMMC_ERROR_DATA_CRC_FAIL; - - return errorstate; - } - else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) - { - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); - - errorstate = SDMMC_ERROR_RX_OVERRUN; - - return errorstate; - } - else - { - /* No error flag set */ - } - - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - /* Test if the switch mode is ok */ - if ((((uint8_t *)SD_hs)[13] & 2U) != 2U) - { - errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; - } - else - { -#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) - hsd->DriveTransceiver_1_8V_Callback(SET); -#else - HAL_SD_DriveTransceiver_1_8V_Callback(SET); -#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ -#if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2) - /* Enable DelayBlock Peripheral */ - /* SDMMC_CKin feedback clock selected as receive clock, for DDR50 */ - MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_0); - LL_DLYB_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance)); -#endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */ - } - } - - return errorstate; -} - -#endif /* USE_SD_TRANSCEIVER */ - -/** - * @brief Read DMA Linked list node Transfer completed callbacks - * @param hsd: SD handle - * @retval None - */ -__weak void HAL_SDEx_Read_DMALnkLstBufCpltCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SDEx_Read_DMALnkLstBufCpltCallback can be implemented in the user file - */ -} -/** - * @brief Read DMA Linked list node Transfer completed callbacks - * @param hsd: SD handle - * @retval None - */ -__weak void HAL_SDEx_Write_DMALnkLstBufCpltCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SDEx_Write_DMALnkLstBufCpltCallback can be implemented in the user file - */ -} - -/** - * @} - */ - -#endif /* HAL_SD_MODULE_ENABLED */ -#endif /* SDMMC1 || SDMMC2 */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_sd.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 (SDMMC 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 SDMMC memories which uses the HAL + SDMMC driver functions to interface with SD and uSD cards devices. + It is used as follows: + + (#)Initialize the SDMMC low level resources by implementing the HAL_SD_MspInit() API: + (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE(); + (##) SDMMC pins configuration for SD card + (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE(); + (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init() + and according to your pin assignment; + (##) NVIC configuration if you need to use interrupt process (HAL_SD_ReadBlocks_IT() + and HAL_SD_WriteBlocks_IT() APIs). + (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority(); + (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ() + (+++) SDMMC interrupts are managed using the macros __HAL_SD_ENABLE_IT() + and __HAL_SD_DISABLE_IT() inside the communication process. + (+++) SDMMC interrupts pending bits are managed using the macros __HAL_SD_GET_IT() + and __HAL_SD_CLEAR_IT() + (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used. + + (#) 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 + SDMMC Peripheral(STM32 side) and 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 (SDMMC_CK) is computed as follows: + + SDMMC_CK = SDMMCCLK / (2 * ClockDiv) + + In initialization mode and according to the SD Card standard, + make sure that the SDMMC_CK frequency doesn't exceed 400KHz. + + This phase of initialization is done through SDMMC_Init() and + SDMMC_PowerState_ON() SDMMC low level APIs. + + (#) Initialize the SD card. The API used is HAL_SD_InitCard(). + This phase allows the card initialization and identification + and check the SD Card type (Standard Capacity or High Capacity) + The initialization flow is compatible with SD standard. + + This API (HAL_SD_InitCard()) could be used also to reinitialize the card in case + of plug-off plug-in. + + (#) Configure the SD Card Data transfer frequency. You can change or adapt this + frequency by adjusting the "ClockDiv" field. + In transfer mode and according to the SD Card standard, make sure that the + SDMMC_CK frequency doesn't exceed 25MHz and 100MHz in High-speed mode switch. + + (#) 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-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_SD_GetCardState() function for SD card state. + + (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_SD_GetCardState() function for SD card state. + You could also check the DMA transfer process through the SD Rx interrupt event. + + (+) You can read from SD card in Interrupt mode by using function HAL_SD_ReadBlocks_IT(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_SD_GetCardState() function for SD card state. + You could also check the IT transfer process through the SD Rx interrupt event. + + *** SD Card Write operation *** + =============================== + [..] + (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_SD_GetCardState() function for SD card state. + + (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_SD_GetCardState() function for SD card state. + You could also check the DMA transfer process through the SD Tx interrupt event. + + (+) You can write to SD card in Interrupt mode by using function HAL_SD_WriteBlocks_IT(). + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). + You can choose either one block read operation or multiple block read operation + by adjusting the "NumberOfBlocks" parameter. + After this, you have to ensure that the transfer is done correctly. The check is done + through HAL_SD_GetCardState() function for SD card state. + You could also check the IT transfer process through the SD Tx interrupt event. + + *** SD card status *** + ====================== + [..] + (+) The SD Status contains status bits that are related to the SD Memory + Card proprietary features. To get SD card status use the HAL_SD_GetCardStatus(). + + *** SD card information *** + =========================== + [..] + (+) To get SD card information, you can use the function HAL_SD_GetCardInfo(). + It returns useful information about the SD card such as block size, card type, + block number ... + + *** SD card CSD register *** + ============================ + (+) The HAL_SD_GetCardCSD() API allows to get the parameters of the CSD register. + Some of the CSD parameters are useful for card initialization and identification. + + *** SD card CID register *** + ============================ + (+) The HAL_SD_GetCardCID() API allows to get the parameters of the CID register. + Some of the CSD parameters are useful for card initialization and identification. + + *** SD HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SD HAL driver. + + (+) __HAL_SD_ENABLE_IT: Enable the SD device interrupt + (+) __HAL_SD_DISABLE_IT: Disable the SD device interrupt + (+) __HAL_SD_GET_FLAG:Check whether the specified SD flag is set or not + (+) __HAL_SD_CLEAR_FLAG: Clear the SD's pending flags + + (@) You can refer to the SD HAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_SD_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_SD_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed. + (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed. + (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed. + (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed. + (+) MspInitCallback : SD MspInit. + (+) MspDeInitCallback : SD MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + For specific callbacks TransceiverCallback use dedicated register callbacks: + respectively HAL_SD_RegisterTransceiverCallback(). + + Use function HAL_SD_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) Read_DMALnkLstBufCpltCallback : callback when the DMA reception of linked list node buffer is completed. + (+) Write_DMALnkLstBufCpltCallback : callback when the DMA transmission of linked list node buffer is completed. + (+) MspInitCallback : SD MspInit. + (+) MspDeInitCallback : SD MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + For specific callbacks TransceiverCallback use dedicated unregister callbacks: + respectively HAL_SD_UnRegisterTransceiverCallback(). + + By default, after the HAL_SD_Init and if the state is HAL_SD_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_SD_Init + and HAL_SD_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_SD_Init and HAL_SD_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SD_RegisterCallback before calling HAL_SD_DeInit + or HAL_SD_Init function. + + When The compilation define USE_HAL_SD_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @addtogroup SD + * @{ + */ + +#if defined (SDMMC1) || defined (SDMMC2) +#ifdef HAL_SD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @addtogroup SD_Private_Defines + * @{ + */ +/* Frequencies used in the driver for clock divider calculation */ +#define SD_INIT_FREQ 400000U /* Initialization phase : 400 kHz max */ +#define SD_NORMAL_SPEED_FREQ 25000000U /* Normal speed phase : 25 MHz max */ +#define SD_HIGH_SPEED_FREQ 50000000U /* High speed phase : 50 MHz max */ +/* Private macro -------------------------------------------------------------*/ +#if defined (DLYB_SDMMC1) && defined (DLYB_SDMMC2) +#define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) (((SDMMC_INSTANCE) == SDMMC1)? \ + DLYB_SDMMC1 : DLYB_SDMMC2 ) +#elif defined (DLYB_SDMMC1) +#define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) ( DLYB_SDMMC1 ) +#endif /* (DLYB_SDMMC1) && defined (DLYB_SDMMC2) */ + +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup SD_Private_Functions SD Private Functions + * @{ + */ +static uint32_t SD_InitCard(SD_HandleTypeDef *hsd); +static uint32_t SD_PowerON(SD_HandleTypeDef *hsd); +static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); +static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus); +static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd); +static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd); +static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR); +static void SD_PowerOFF(SD_HandleTypeDef *hsd); +static void SD_Write_IT(SD_HandleTypeDef *hsd); +static void SD_Read_IT(SD_HandleTypeDef *hsd); +static uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode); +#if (USE_SD_TRANSCEIVER != 0U) +static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode); +static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd); +#endif /* USE_SD_TRANSCEIVER */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SD_Exported_Functions + * @{ + */ + +/** @addtogroup SD_Exported_Functions_Group1 + * @brief Initialization and de-initialization 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 according to the specified parameters in the + SD_HandleTypeDef and create the associated handle. + * @param hsd: Pointer to the SD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd) +{ + HAL_SD_CardStatusTypeDef CardStatus; + uint32_t speedgrade; + uint32_t unitsize; + uint32_t tickstart; + + /* Check the SD handle allocation */ + if (hsd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance)); + assert_param(IS_SDMMC_CLOCK_EDGE(hsd->Init.ClockEdge)); + assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave)); + assert_param(IS_SDMMC_BUS_WIDE(hsd->Init.BusWide)); + assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl)); + assert_param(IS_SDMMC_CLKDIV(hsd->Init.ClockDiv)); + + if (hsd->State == HAL_SD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsd->Lock = HAL_UNLOCKED; + +#if (USE_SD_TRANSCEIVER != 0U) + /* Force SDMMC_TRANSCEIVER_PRESENT for Legacy usage */ + if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_UNKNOWN) + { + hsd->Init.TranceiverPresent = SDMMC_TRANSCEIVER_PRESENT; + } +#endif /*USE_SD_TRANSCEIVER */ +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + /* Reset Callback pointers in HAL_SD_STATE_RESET only */ + hsd->TxCpltCallback = HAL_SD_TxCpltCallback; + hsd->RxCpltCallback = HAL_SD_RxCpltCallback; + hsd->ErrorCallback = HAL_SD_ErrorCallback; + hsd->AbortCpltCallback = HAL_SD_AbortCallback; + hsd->Read_DMALnkLstBufCpltCallback = HAL_SDEx_Read_DMALnkLstBufCpltCallback; + hsd->Write_DMALnkLstBufCpltCallback = HAL_SDEx_Write_DMALnkLstBufCpltCallback; +#if (USE_SD_TRANSCEIVER != 0U) + if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) + { + hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback; + } +#endif /* USE_SD_TRANSCEIVER */ + + if (hsd->MspInitCallback == NULL) + { + hsd->MspInitCallback = HAL_SD_MspInit; + } + + /* Init the low level hardware */ + hsd->MspInitCallback(hsd); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_SD_MspInit(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + + hsd->State = HAL_SD_STATE_PROGRAMMING; + + /* Initialize the Card parameters */ + if (HAL_SD_InitCard(hsd) != HAL_OK) + { + return HAL_ERROR; + } + + if (HAL_SD_GetCardStatus(hsd, &CardStatus) != HAL_OK) + { + return HAL_ERROR; + } + /* Get Initial Card Speed from Card Status*/ + speedgrade = CardStatus.UhsSpeedGrade; + unitsize = CardStatus.UhsAllocationUnitSize; + if ((hsd->SdCard.CardType == CARD_SDHC_SDXC) && ((speedgrade != 0U) || (unitsize != 0U))) + { + hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED; + } + else + { + if (hsd->SdCard.CardType == CARD_SDHC_SDXC) + { + hsd->SdCard.CardSpeed = CARD_HIGH_SPEED; + } + else + { + hsd->SdCard.CardSpeed = CARD_NORMAL_SPEED; + } + + } + /* Configure the bus wide */ + if (HAL_SD_ConfigWideBusOperation(hsd, hsd->Init.BusWide) != HAL_OK) + { + return HAL_ERROR; + } + + /* Verify that SD card is ready to use after Initialization */ + tickstart = HAL_GetTick(); + while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_TIMEOUT; + } + } + + /* Initialize the error code */ + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + /* Initialize the SD operation */ + hsd->Context = SD_CONTEXT_NONE; + + /* Initialize the SD state */ + hsd->State = HAL_SD_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the SD Card. + * @param hsd: Pointer to SD handle + * @note This function initializes the SD card. It could be used when a card + re-initialization is needed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) +{ + uint32_t errorstate; + SD_InitTypeDef Init; + uint32_t sdmmc_clk; + + /* Default SDMMC peripheral configuration for SD card initialization */ + Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; + Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; + Init.BusWide = SDMMC_BUS_WIDE_1B; + Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE; + + /* Init Clock should be less or equal to 400Khz*/ + sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); + if (sdmmc_clk == 0U) + { + hsd->State = HAL_SD_STATE_READY; + hsd->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER; + return HAL_ERROR; + } + Init.ClockDiv = sdmmc_clk / (2U * SD_INIT_FREQ); + +#if (USE_SD_TRANSCEIVER != 0U) + Init.TranceiverPresent = hsd->Init.TranceiverPresent; + + if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) + { + /* Set Transceiver polarity */ + hsd->Instance->POWER |= SDMMC_POWER_DIRPOL; + } +#elif defined (USE_SD_DIRPOL) + /* Set Transceiver polarity */ + hsd->Instance->POWER |= SDMMC_POWER_DIRPOL; +#endif /* USE_SD_TRANSCEIVER */ + + /* Initialize SDMMC peripheral interface with default configuration */ + (void)SDMMC_Init(hsd->Instance, Init); + + /* Set Power State to ON */ + (void)SDMMC_PowerState_ON(hsd->Instance); + + /* wait 74 Cycles: required power up waiting time before starting + the SD initialization sequence */ + if (Init.ClockDiv != 0U) + { + sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv); + } + + if (sdmmc_clk != 0U) + { + HAL_Delay(1U + (74U * 1000U / (sdmmc_clk))); + } + + /* Identify card operating voltage */ + errorstate = SD_PowerON(hsd); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->State = HAL_SD_STATE_READY; + hsd->ErrorCode |= errorstate; + return HAL_ERROR; + } + + /* Card initialization */ + errorstate = SD_InitCard(hsd); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->State = HAL_SD_STATE_READY; + hsd->ErrorCode |= errorstate; + return HAL_ERROR; + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief De-Initializes the SD card. + * @param hsd: Pointer to SD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd) +{ + /* Check the SD handle allocation */ + if (hsd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance)); + + hsd->State = HAL_SD_STATE_BUSY; + +#if (USE_SD_TRANSCEIVER != 0U) + /* Deactivate the 1.8V Mode */ + if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + if (hsd->DriveTransceiver_1_8V_Callback == NULL) + { + hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback; + } + hsd->DriveTransceiver_1_8V_Callback(RESET); +#else + HAL_SD_DriveTransceiver_1_8V_Callback(RESET); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } +#endif /* USE_SD_TRANSCEIVER */ + + /* Set SD power state to off */ + SD_PowerOFF(hsd); + +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + if (hsd->MspDeInitCallback == NULL) + { + hsd->MspDeInitCallback = HAL_SD_MspDeInit; + } + + /* DeInit the low level hardware */ + hsd->MspDeInitCallback(hsd); +#else + /* De-Initialize the MSP layer */ + HAL_SD_MspDeInit(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + + hsd->ErrorCode = HAL_SD_ERROR_NONE; + hsd->State = HAL_SD_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initializes the SD MSP. + * @param hsd: Pointer to SD handle + * @retval None + */ +__weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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: Pointer to SD handle + * @retval None + */ +__weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SD_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @addtogroup SD_Exported_Functions_Group2 + * @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. + * @note This API should be followed by a check on the card state through + * HAL_SD_GetCardState(). + * @param hsd: Pointer to SD handle + * @param pData: pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of SD blocks to read + * @param Timeout: Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, + uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t data; + uint32_t dataremaining; + uint32_t add = BlockAdd; + uint8_t *tempbuff = pData; + + if (NULL == pData) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= BLOCKSIZE; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + /* Read block(s) in polling mode */ + if (NumberOfBlocks > 1U) + { + hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK; + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK; + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); + } + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + + /* Poll on SDMMC flags */ + dataremaining = config.DataLength; + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hsd->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hsd->Instance); + + /* Send stop transmission command in case of multiblock read */ + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + if (hsd->SdCard.CardType != CARD_SECURED) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + } + } + + /* Get error state */ + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + hsd->State = HAL_SD_STATE_READY; + + return HAL_OK; + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Allows to write block(s) to a specified address in a card. The Data + * transfer is managed by polling mode. + * @note This API should be followed by a check on the card state through + * HAL_SD_GetCardState(). + * @param hsd: Pointer to SD handle + * @param pData: pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of SD blocks to write + * @param Timeout: Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks, uint32_t Timeout) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t data; + uint32_t dataremaining; + uint32_t add = BlockAdd; + const uint8_t *tempbuff = pData; + + if (NULL == pData) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= BLOCKSIZE; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = NumberOfBlocks * BLOCKSIZE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + /* Write Blocks in Polling mode */ + if (NumberOfBlocks > 1U) + { + hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK; + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK; + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); + } + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | + SDMMC_FLAG_DATAEND)) + { + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE)) + { + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*tempbuff); + tempbuff++; + data |= ((uint32_t)(*tempbuff) << 8U); + tempbuff++; + data |= ((uint32_t)(*tempbuff) << 16U); + tempbuff++; + data |= ((uint32_t)(*tempbuff) << 24U); + tempbuff++; + (void)SDMMC_WriteFIFO(hsd->Instance, &data); + } + dataremaining -= SDMMC_FIFO_SIZE; + } + + if (((HAL_GetTick() - tickstart) >= Timeout) || (Timeout == 0U)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hsd->Instance); + + /* Send stop transmission command in case of multiblock write */ + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U)) + { + if (hsd->SdCard.CardType != CARD_SECURED) + { + /* Send stop transmission command */ + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + } + } + + /* Get error state */ + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + hsd->State = HAL_SD_STATE_READY; + + return HAL_OK; + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_BUSY; + return HAL_ERROR; + } +} + +/** + * @brief Reads block(s) from a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * HAL_SD_GetCardState(). + * @note You could also check the IT transfer process through the SD Rx + * interrupt event. + * @param hsd: Pointer to SD handle + * @param pData: Pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of blocks to read. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + hsd->pRxBuffPtr = pData; + hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= BLOCKSIZE; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + /* Read Blocks in IT mode */ + if (NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); + } + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + + __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | + SDMMC_FLAG_RXFIFOHF)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Writes block(s) to a specified address in a card. The Data transfer + * is managed in interrupt mode. + * @note This API should be followed by a check on the card state through + * HAL_SD_GetCardState(). + * @note You could also check the IT transfer process through the SD Tx + * interrupt event. + * @param hsd: Pointer to SD handle + * @param pData: Pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of blocks to write + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + hsd->pTxBuffPtr = pData; + hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= BLOCKSIZE; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + /* Write Blocks in Polling mode */ + if (NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_IT); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); + } + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + + /* Enable transfer interrupts */ + __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | + SDMMC_FLAG_TXFIFOHE)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @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 a check on the card state through + * HAL_SD_GetCardState(). + * @note You could also check the DMA transfer process through the SD Rx + * interrupt event. + * @param hsd: Pointer SD handle + * @param pData: Pointer to the buffer that will contain the received data + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Number of blocks to read. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + hsd->pRxBuffPtr = pData; + hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= BLOCKSIZE; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + hsd->Instance->IDMABASER = (uint32_t) pData ; + hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; + + /* Read Blocks in DMA mode */ + if (NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA); + + /* Read Single Block command */ + errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add); + } + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + + /* Enable transfer interrupts */ + __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @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 a check on the card state through + * HAL_SD_GetCardState(). + * @note You could also check the DMA transfer process through the SD Tx + * interrupt event. + * @param hsd: Pointer to SD handle + * @param pData: Pointer to the buffer that will contain the data to transmit + * @param BlockAdd: Block Address where data will be written + * @param NumberOfBlocks: Number of blocks to write + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd, + uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t add = BlockAdd; + + if (NULL == pData) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0U; + + hsd->pTxBuffPtr = pData; + hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= BLOCKSIZE; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + hsd->Instance->IDMABASER = (uint32_t) pData ; + hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; + + /* Write Blocks in Polling mode */ + if (NumberOfBlocks > 1U) + { + hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + } + else + { + hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA); + + /* Write Single Block command */ + errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add); + } + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + return HAL_ERROR; + } + + /* Enable transfer interrupts */ + __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Erases the specified memory area of the given SD card. + * @note This API should be followed by a check on the card state through + * HAL_SD_GetCardState(). + * @param hsd: Pointer to SD handle + * @param BlockStartAdd: Start Block address + * @param BlockEndAdd: End Block address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd) +{ + uint32_t errorstate; + uint32_t start_add = BlockStartAdd; + uint32_t end_add = BlockEndAdd; + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + if (end_add < start_add) + { + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + return HAL_ERROR; + } + + if (end_add > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_BUSY; + + /* Check if the card command class supports erase command */ + if (((hsd->SdCard.Class) & SDMMC_CCCC_ERASE) == 0U) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + + if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_LOCK_UNLOCK_FAILED; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + + /* Get start and end block for high capacity cards */ + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + start_add *= BLOCKSIZE; + end_add *= BLOCKSIZE; + } + + /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ + if (hsd->SdCard.CardType != CARD_SECURED) + { + /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ + errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, start_add); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + + /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ + errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, end_add); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + } + + /* Send CMD38 ERASE */ + errorstate = SDMMC_CmdErase(hsd->Instance, 0UL); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + + hsd->State = HAL_SD_STATE_READY; + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles SD card interrupt request. + * @param hsd: Pointer to SD handle + * @retval None + */ +void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd) +{ + uint32_t errorstate; + uint32_t context = hsd->Context; + + /* Check for SDMMC interrupt flags */ + if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) != RESET) && ((context & SD_CONTEXT_IT) != 0U)) + { + SD_Read_IT(hsd); + } + + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) != RESET) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DATAEND); + + __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR | SDMMC_IT_TXFIFOHE | \ + SDMMC_IT_RXFIFOHF); + + __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC); + __SDMMC_CMDTRANS_DISABLE(hsd->Instance); + + if ((context & SD_CONTEXT_IT) != 0U) + { + if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + HAL_SD_ErrorCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + } + + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->RxCpltCallback(hsd); +#else + HAL_SD_RxCpltCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + else + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->TxCpltCallback(hsd); +#else + HAL_SD_TxCpltCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + } + else if ((context & SD_CONTEXT_DMA) != 0U) + { + hsd->Instance->DLEN = 0; + hsd->Instance->DCTRL = 0; + hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + /* Stop Transfer for Write Multi blocks or Read Multi blocks */ + if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { + errorstate = SDMMC_CmdStopTransfer(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + HAL_SD_ErrorCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + } + + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; + if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->TxCpltCallback(hsd); +#else + HAL_SD_TxCpltCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->RxCpltCallback(hsd); +#else + HAL_SD_RxCpltCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + } + + else if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) != RESET) && ((context & SD_CONTEXT_IT) != 0U)) + { + SD_Write_IT(hsd); + } + + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR | + SDMMC_FLAG_TXUNDERR) != RESET) + { + /* Set Error code */ + if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DCRCFAIL) != RESET) + { + hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; + } + if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DTIMEOUT) != RESET) + { + hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; + } + if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_RXOVERR) != RESET) + { + hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN; + } + if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_TXUNDERR) != RESET) + { + hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN; + } + + /* Clear All flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + /* Disable all interrupts */ + __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); + + __SDMMC_CMDTRANS_DISABLE(hsd->Instance); + hsd->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; + hsd->Instance->CMD |= SDMMC_CMD_CMDSTOP; + hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); + hsd->Instance->CMD &= ~(SDMMC_CMD_CMDSTOP); + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DABORT); + + if ((context & SD_CONTEXT_IT) != 0U) + { + /* Set the SD state to ready to be able to start again the process */ + hsd->State = HAL_SD_STATE_READY; + hsd->Context = SD_CONTEXT_NONE; +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + HAL_SD_ErrorCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + else if ((context & SD_CONTEXT_DMA) != 0U) + { + if (hsd->ErrorCode != HAL_SD_ERROR_NONE) + { + /* Disable Internal DMA */ + __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC); + hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + /* Set the SD state to ready to be able to start again the process */ + hsd->State = HAL_SD_STATE_READY; +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->ErrorCallback(hsd); +#else + HAL_SD_ErrorCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + } + + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_IDMABTC) != RESET) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_IDMABTC); + + if ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U) + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->Write_DMALnkLstBufCpltCallback(hsd); +#else + HAL_SDEx_Write_DMALnkLstBufCpltCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + else /* SD_CONTEXT_READ_MULTIPLE_BLOCK */ + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->Read_DMALnkLstBufCpltCallback(hsd); +#else + HAL_SDEx_Read_DMALnkLstBufCpltCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief return the SD state + * @param hsd: Pointer to sd handle + * @retval HAL state + */ +HAL_SD_StateTypeDef HAL_SD_GetState(const SD_HandleTypeDef *hsd) +{ + return hsd->State; +} + +/** + * @brief Return the SD error code + * @param hsd : Pointer to a SD_HandleTypeDef structure that contains + * the configuration information. + * @retval SD Error Code + */ +uint32_t HAL_SD_GetError(const SD_HandleTypeDef *hsd) +{ + return hsd->ErrorCode; +} + +/** + * @brief Tx Transfer completed callbacks + * @param hsd: Pointer to SD handle + * @retval None + */ +__weak void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SD_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hsd: Pointer SD handle + * @retval None + */ +__weak void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SD_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief SD error callbacks + * @param hsd: Pointer SD handle + * @retval None + */ +__weak void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SD_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief SD Abort callbacks + * @param hsd: Pointer SD handle + * @retval None + */ +__weak void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SD_AbortCallback can be implemented in the user file + */ +} + +#if (USE_SD_TRANSCEIVER != 0U) +/** + * @brief Enable/Disable the SD Transceiver 1.8V Mode Callback. + * @param status: Voltage Switch State + * @retval None + */ +__weak void HAL_SD_DriveTransceiver_1_8V_Callback(FlagStatus status) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(status); + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SD_EnableTransceiver could be implemented in the user file + */ +} +#endif /* USE_SD_TRANSCEIVER */ + +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User SD Callback + * To be used instead of the weak (overridden) predefined callback + * @note The HAL_SD_RegisterCallback() may be called before HAL_SD_Init() in + * HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID + * and HAL_SD_MSP_DEINIT_CB_ID. + * @param hsd : SD handle + * @param CallbackID : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SD_TX_CPLT_CB_ID SD Tx Complete Callback ID + * @arg @ref HAL_SD_RX_CPLT_CB_ID SD Rx Complete Callback ID + * @arg @ref HAL_SD_ERROR_CB_ID SD Error Callback ID + * @arg @ref HAL_SD_ABORT_CB_ID SD Abort Callback ID + * @arg @ref HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Rx Linked List Node buffer Callback ID + * @arg @ref HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Tx Linked List Node buffer Callback ID + * @arg @ref HAL_SD_MSP_INIT_CB_ID SD MspInit Callback ID + * @arg @ref HAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SD_RegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID, + pSD_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hsd->State == HAL_SD_STATE_READY) + { + switch (CallbackID) + { + case HAL_SD_TX_CPLT_CB_ID : + hsd->TxCpltCallback = pCallback; + break; + case HAL_SD_RX_CPLT_CB_ID : + hsd->RxCpltCallback = pCallback; + break; + case HAL_SD_ERROR_CB_ID : + hsd->ErrorCallback = pCallback; + break; + case HAL_SD_ABORT_CB_ID : + hsd->AbortCpltCallback = pCallback; + break; + case HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID : + hsd->Read_DMALnkLstBufCpltCallback = pCallback; + break; + case HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : + hsd->Write_DMALnkLstBufCpltCallback = pCallback; + break; + case HAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = pCallback; + break; + case HAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hsd->State == HAL_SD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = pCallback; + break; + case HAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User SD Callback + * SD Callback is redirected to the weak (overridden) predefined callback + * @note The HAL_SD_UnRegisterCallback() may be called before HAL_SD_Init() in + * HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID + * and HAL_SD_MSP_DEINIT_CB_ID. + * @param hsd : SD handle + * @param CallbackID : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_SD_TX_CPLT_CB_ID SD Tx Complete Callback ID + * @arg @ref HAL_SD_RX_CPLT_CB_ID SD Rx Complete Callback ID + * @arg @ref HAL_SD_ERROR_CB_ID SD Error Callback ID + * @arg @ref HAL_SD_ABORT_CB_ID SD Abort Callback ID + * @arg @ref HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Rx Linked List Node buffer Callback ID + * @arg @ref HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Tx Linked List Node buffer Callback ID + * @arg @ref HAL_SD_MSP_INIT_CB_ID SD MspInit Callback ID + * @arg @ref HAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hsd->State == HAL_SD_STATE_READY) + { + switch (CallbackID) + { + case HAL_SD_TX_CPLT_CB_ID : + hsd->TxCpltCallback = HAL_SD_TxCpltCallback; + break; + case HAL_SD_RX_CPLT_CB_ID : + hsd->RxCpltCallback = HAL_SD_RxCpltCallback; + break; + case HAL_SD_ERROR_CB_ID : + hsd->ErrorCallback = HAL_SD_ErrorCallback; + break; + case HAL_SD_ABORT_CB_ID : + hsd->AbortCpltCallback = HAL_SD_AbortCallback; + break; + case HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID : + hsd->Read_DMALnkLstBufCpltCallback = HAL_SDEx_Read_DMALnkLstBufCpltCallback; + break; + case HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID : + hsd->Write_DMALnkLstBufCpltCallback = HAL_SDEx_Write_DMALnkLstBufCpltCallback; + break; + case HAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = HAL_SD_MspInit; + break; + case HAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = HAL_SD_MspDeInit; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hsd->State == HAL_SD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_SD_MSP_INIT_CB_ID : + hsd->MspInitCallback = HAL_SD_MspInit; + break; + case HAL_SD_MSP_DEINIT_CB_ID : + hsd->MspDeInitCallback = HAL_SD_MspDeInit; + break; + default : + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +#if (USE_SD_TRANSCEIVER != 0U) +/** + * @brief Register a User SD Transceiver Callback + * To be used instead of the weak (overridden) predefined callback + * @param hsd : SD handle + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SD_RegisterTransceiverCallback(SD_HandleTypeDef *hsd, pSD_TransceiverCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hsd); + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->DriveTransceiver_1_8V_Callback = pCallback; + } + else + { + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hsd); + return status; +} + +/** + * @brief Unregister a User SD Transceiver Callback + * SD Callback is redirected to the weak (overridden) predefined callback + * @param hsd : SD handle + * @retval status + */ +HAL_StatusTypeDef HAL_SD_UnRegisterTransceiverCallback(SD_HandleTypeDef *hsd) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hsd); + + if (hsd->State == HAL_SD_STATE_READY) + { + hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback; + } + else + { + /* Update the error code */ + hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hsd); + return status; +} +#endif /* USE_SD_TRANSCEIVER */ +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @addtogroup SD_Exported_Functions_Group3 + * @brief management functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the SD card + operations and get the related information + +@endverbatim + * @{ + */ + +/** + * @brief Returns information the information of the card which are stored on + * the CID register. + * @param hsd: Pointer to SD handle + * @param pCID: Pointer to a HAL_SD_CardCIDTypeDef structure that + * contains all CID register parameters + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID) +{ + pCID->ManufacturerID = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24U); + + pCID->OEM_AppliID = (uint16_t)((hsd->CID[0] & 0x00FFFF00U) >> 8U); + + pCID->ProdName1 = (((hsd->CID[0] & 0x000000FFU) << 24U) | ((hsd->CID[1] & 0xFFFFFF00U) >> 8U)); + + pCID->ProdName2 = (uint8_t)(hsd->CID[1] & 0x000000FFU); + + pCID->ProdRev = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24U); + + pCID->ProdSN = (((hsd->CID[2] & 0x00FFFFFFU) << 8U) | ((hsd->CID[3] & 0xFF000000U) >> 24U)); + + pCID->Reserved1 = (uint8_t)((hsd->CID[3] & 0x00F00000U) >> 20U); + + pCID->ManufactDate = (uint16_t)((hsd->CID[3] & 0x000FFF00U) >> 8U); + + pCID->CID_CRC = (uint8_t)((hsd->CID[3] & 0x000000FEU) >> 1U); + + pCID->Reserved2 = 1U; + + return HAL_OK; +} + +/** + * @brief Returns information the information of the card which are stored on + * the CSD register. + * @param hsd: Pointer to SD handle + * @param pCSD: Pointer to a HAL_SD_CardCSDTypeDef structure that + * contains all CSD register parameters + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD) +{ + pCSD->CSDStruct = (uint8_t)((hsd->CSD[0] & 0xC0000000U) >> 30U); + + pCSD->SysSpecVersion = (uint8_t)((hsd->CSD[0] & 0x3C000000U) >> 26U); + + pCSD->Reserved1 = (uint8_t)((hsd->CSD[0] & 0x03000000U) >> 24U); + + pCSD->TAAC = (uint8_t)((hsd->CSD[0] & 0x00FF0000U) >> 16U); + + pCSD->NSAC = (uint8_t)((hsd->CSD[0] & 0x0000FF00U) >> 8U); + + pCSD->MaxBusClkFrec = (uint8_t)(hsd->CSD[0] & 0x000000FFU); + + pCSD->CardComdClasses = (uint16_t)((hsd->CSD[1] & 0xFFF00000U) >> 20U); + + pCSD->RdBlockLen = (uint8_t)((hsd->CSD[1] & 0x000F0000U) >> 16U); + + pCSD->PartBlockRead = (uint8_t)((hsd->CSD[1] & 0x00008000U) >> 15U); + + pCSD->WrBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00004000U) >> 14U); + + pCSD->RdBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00002000U) >> 13U); + + pCSD->DSRImpl = (uint8_t)((hsd->CSD[1] & 0x00001000U) >> 12U); + + pCSD->Reserved2 = 0U; /*!< Reserved */ + + if (hsd->SdCard.CardType == CARD_SDSC) + { + pCSD->DeviceSize = (((hsd->CSD[1] & 0x000003FFU) << 2U) | ((hsd->CSD[2] & 0xC0000000U) >> 30U)); + + pCSD->MaxRdCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x38000000U) >> 27U); + + pCSD->MaxRdCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x07000000U) >> 24U); + + pCSD->MaxWrCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x00E00000U) >> 21U); + + pCSD->MaxWrCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x001C0000U) >> 18U); + + pCSD->DeviceSizeMul = (uint8_t)((hsd->CSD[2] & 0x00038000U) >> 15U); + + hsd->SdCard.BlockNbr = (pCSD->DeviceSize + 1U) ; + hsd->SdCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U)); + hsd->SdCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU)); + + hsd->SdCard.LogBlockNbr = (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / BLOCKSIZE); + hsd->SdCard.LogBlockSize = BLOCKSIZE; + } + else if (hsd->SdCard.CardType == CARD_SDHC_SDXC) + { + /* Byte 7 */ + pCSD->DeviceSize = (((hsd->CSD[1] & 0x0000003FU) << 16U) | ((hsd->CSD[2] & 0xFFFF0000U) >> 16U)); + + hsd->SdCard.BlockNbr = ((pCSD->DeviceSize + 1U) * 1024U); + hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr; + hsd->SdCard.BlockSize = BLOCKSIZE; + hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize; + } + else + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + hsd->State = HAL_SD_STATE_READY; + return HAL_ERROR; + } + + pCSD->EraseGrSize = (uint8_t)((hsd->CSD[2] & 0x00004000U) >> 14U); + + pCSD->EraseGrMul = (uint8_t)((hsd->CSD[2] & 0x00003F80U) >> 7U); + + pCSD->WrProtectGrSize = (uint8_t)(hsd->CSD[2] & 0x0000007FU); + + pCSD->WrProtectGrEnable = (uint8_t)((hsd->CSD[3] & 0x80000000U) >> 31U); + + pCSD->ManDeflECC = (uint8_t)((hsd->CSD[3] & 0x60000000U) >> 29U); + + pCSD->WrSpeedFact = (uint8_t)((hsd->CSD[3] & 0x1C000000U) >> 26U); + + pCSD->MaxWrBlockLen = (uint8_t)((hsd->CSD[3] & 0x03C00000U) >> 22U); + + pCSD->WriteBlockPaPartial = (uint8_t)((hsd->CSD[3] & 0x00200000U) >> 21U); + + pCSD->Reserved3 = 0; + + pCSD->ContentProtectAppli = (uint8_t)((hsd->CSD[3] & 0x00010000U) >> 16U); + + pCSD->FileFormatGroup = (uint8_t)((hsd->CSD[3] & 0x00008000U) >> 15U); + + pCSD->CopyFlag = (uint8_t)((hsd->CSD[3] & 0x00004000U) >> 14U); + + pCSD->PermWrProtect = (uint8_t)((hsd->CSD[3] & 0x00002000U) >> 13U); + + pCSD->TempWrProtect = (uint8_t)((hsd->CSD[3] & 0x00001000U) >> 12U); + + pCSD->FileFormat = (uint8_t)((hsd->CSD[3] & 0x00000C00U) >> 10U); + + pCSD->ECC = (uint8_t)((hsd->CSD[3] & 0x00000300U) >> 8U); + + pCSD->CSD_CRC = (uint8_t)((hsd->CSD[3] & 0x000000FEU) >> 1U); + + pCSD->Reserved4 = 1; + + return HAL_OK; +} + +/** + * @brief Gets the SD status info.( shall be called if there is no SD transaction ongoing ) + * @param hsd: Pointer to SD handle + * @param pStatus: Pointer to the HAL_SD_CardStatusTypeDef structure that + * will contain the SD card status information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus) +{ + uint32_t sd_status[16]; + uint32_t errorstate; + HAL_StatusTypeDef status = HAL_OK; + + if (hsd->State == HAL_SD_STATE_BUSY) + { + return HAL_ERROR; + } + + errorstate = SD_SendSDStatus(hsd, sd_status); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + hsd->State = HAL_SD_STATE_READY; + status = HAL_ERROR; + } + else + { + pStatus->DataBusWidth = (uint8_t)((sd_status[0] & 0xC0U) >> 6U); + + pStatus->SecuredMode = (uint8_t)((sd_status[0] & 0x20U) >> 5U); + + pStatus->CardType = (uint16_t)(((sd_status[0] & 0x00FF0000U) >> 8U) | ((sd_status[0] & 0xFF000000U) >> 24U)); + + pStatus->ProtectedAreaSize = (((sd_status[1] & 0xFFU) << 24U) | ((sd_status[1] & 0xFF00U) << 8U) | + ((sd_status[1] & 0xFF0000U) >> 8U) | ((sd_status[1] & 0xFF000000U) >> 24U)); + + pStatus->SpeedClass = (uint8_t)(sd_status[2] & 0xFFU); + + pStatus->PerformanceMove = (uint8_t)((sd_status[2] & 0xFF00U) >> 8U); + + pStatus->AllocationUnitSize = (uint8_t)((sd_status[2] & 0xF00000U) >> 20U); + + pStatus->EraseSize = (uint16_t)(((sd_status[2] & 0xFF000000U) >> 16U) | (sd_status[3] & 0xFFU)); + + pStatus->EraseTimeout = (uint8_t)((sd_status[3] & 0xFC00U) >> 10U); + + pStatus->EraseOffset = (uint8_t)((sd_status[3] & 0x0300U) >> 8U); + + pStatus->UhsSpeedGrade = (uint8_t)((sd_status[3] & 0x00F0U) >> 4U); + pStatus->UhsAllocationUnitSize = (uint8_t)(sd_status[3] & 0x000FU) ; + pStatus->VideoSpeedClass = (uint8_t)((sd_status[4] & 0xFF000000U) >> 24U); + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode = errorstate; + hsd->State = HAL_SD_STATE_READY; + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Gets the SD card info. + * @param hsd: Pointer to SD handle + * @param pCardInfo: Pointer to the HAL_SD_CardInfoTypeDef structure that + * will contain the SD card status information + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo) +{ + pCardInfo->CardType = (uint32_t)(hsd->SdCard.CardType); + pCardInfo->CardVersion = (uint32_t)(hsd->SdCard.CardVersion); + pCardInfo->Class = (uint32_t)(hsd->SdCard.Class); + pCardInfo->RelCardAdd = (uint32_t)(hsd->SdCard.RelCardAdd); + pCardInfo->BlockNbr = (uint32_t)(hsd->SdCard.BlockNbr); + pCardInfo->BlockSize = (uint32_t)(hsd->SdCard.BlockSize); + pCardInfo->LogBlockNbr = (uint32_t)(hsd->SdCard.LogBlockNbr); + pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize); + + return HAL_OK; +} + +/** + * @brief Enables wide bus operation for the requested card if supported by + * card. + * @param hsd: Pointer to SD handle + * @param WideMode: Specifies the SD card wide bus mode + * This parameter can be one of the following values: + * @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer + * @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer + * @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode) +{ + SDMMC_InitTypeDef Init; + uint32_t errorstate; + uint32_t sdmmc_clk; + + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_SDMMC_BUS_WIDE(WideMode)); + + /* Change State */ + hsd->State = HAL_SD_STATE_BUSY; + + if (hsd->SdCard.CardType != CARD_SECURED) + { + if (WideMode == SDMMC_BUS_WIDE_8B) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + else if (WideMode == SDMMC_BUS_WIDE_4B) + { + errorstate = SD_WideBus_Enable(hsd); + + hsd->ErrorCode |= errorstate; + } + else if (WideMode == SDMMC_BUS_WIDE_1B) + { + errorstate = SD_WideBus_Disable(hsd); + + hsd->ErrorCode |= errorstate; + } + else + { + /* WideMode is not a valid argument*/ + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + } + } + else + { + /* SD Card does not support this feature */ + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + + if (hsd->ErrorCode != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + status = HAL_ERROR; + } + else + { + sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12); + if (sdmmc_clk != 0U) + { + /* Configure the SDMMC peripheral */ + Init.ClockEdge = hsd->Init.ClockEdge; + Init.ClockPowerSave = hsd->Init.ClockPowerSave; + Init.BusWide = WideMode; + Init.HardwareFlowControl = hsd->Init.HardwareFlowControl; + + /* Check if user Clock div < Normal speed 25Mhz, no change in Clockdiv */ + if (hsd->Init.ClockDiv >= (sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ))) + { + Init.ClockDiv = hsd->Init.ClockDiv; + } + else if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) + { + /* UltraHigh speed SD card,user Clock div */ + Init.ClockDiv = hsd->Init.ClockDiv; + } + else if (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) + { + /* High speed SD card, Max Frequency = 50Mhz */ + if (hsd->Init.ClockDiv == 0U) + { + if (sdmmc_clk > SD_HIGH_SPEED_FREQ) + { + Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ); + } + else + { + Init.ClockDiv = hsd->Init.ClockDiv; + } + } + else + { + if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_HIGH_SPEED_FREQ) + { + Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ); + } + else + { + Init.ClockDiv = hsd->Init.ClockDiv; + } + } + } + else + { + /* No High speed SD card, Max Frequency = 25Mhz */ + if (hsd->Init.ClockDiv == 0U) + { + if (sdmmc_clk > SD_NORMAL_SPEED_FREQ) + { + Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ); + } + else + { + Init.ClockDiv = hsd->Init.ClockDiv; + } + } + else + { + if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_NORMAL_SPEED_FREQ) + { + Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ); + } + else + { + Init.ClockDiv = hsd->Init.ClockDiv; + } + } + } + +#if (USE_SD_TRANSCEIVER != 0U) + Init.TranceiverPresent = hsd->Init.TranceiverPresent; +#endif /* USE_SD_TRANSCEIVER */ + + (void)SDMMC_Init(hsd->Instance, Init); + } + else + { + hsd->ErrorCode |= SDMMC_ERROR_INVALID_PARAMETER; + status = HAL_ERROR; + } + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + status = HAL_ERROR; + } + + /* Change State */ + hsd->State = HAL_SD_STATE_READY; + + return status; +} + +/** + * @brief Configure the speed bus mode + * @param hsd: Pointer to the SD handle + * @param SpeedMode: Specifies the SD card speed bus mode + * This parameter can be one of the following values: + * @arg SDMMC_SPEED_MODE_AUTO: Max speed mode supported by the card + * @arg SDMMC_SPEED_MODE_DEFAULT: Default Speed/SDR12 mode + * @arg SDMMC_SPEED_MODE_HIGH: High Speed/SDR25 mode + * @arg SDMMC_SPEED_MODE_ULTRA: Ultra high speed mode + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_SD_ConfigSpeedBusOperation(SD_HandleTypeDef *hsd, uint32_t SpeedMode) +{ + uint32_t tickstart; + uint32_t errorstate; + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_SDMMC_SPEED_MODE(SpeedMode)); + /* Change State */ + hsd->State = HAL_SD_STATE_BUSY; + +#if (USE_SD_TRANSCEIVER != 0U) + if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) + { + switch (SpeedMode) + { + case SDMMC_SPEED_MODE_AUTO: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED; + /* Enable Ultra High Speed */ + if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + } + else if (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) + { + /* Enable High Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + else + { + /*Nothing to do, Use defaultSpeed */ + } + break; + } + case SDMMC_SPEED_MODE_ULTRA_SDR104: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable UltraHigh Speed */ + if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED; + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_ULTRA_SDR50: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable UltraHigh Speed */ + if (SD_UltraHighSpeed(hsd, SDMMC_SDR50_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED; + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_DDR: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable DDR Mode*/ + if (SD_DDR_Mode(hsd) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED | SDMMC_CLKCR_DDR; + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_HIGH: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable High Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_DEFAULT: + { + /* Switch to default Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + + break; + } + default: + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + status = HAL_ERROR; + break; + } + } + else + { + switch (SpeedMode) + { + case SDMMC_SPEED_MODE_AUTO: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable High Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + else + { + /*Nothing to do, Use defaultSpeed */ + } + break; + } + case SDMMC_SPEED_MODE_HIGH: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable High Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_DEFAULT: + { + /* Switch to default Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + + break; + } + case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/ + default: + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + status = HAL_ERROR; + break; + } + } +#else + switch (SpeedMode) + { + case SDMMC_SPEED_MODE_AUTO: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable High Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + else + { + /*Nothing to do, Use defaultSpeed */ + } + break; + } + case SDMMC_SPEED_MODE_HIGH: + { + if ((hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) || + (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED) || + (hsd->SdCard.CardType == CARD_SDHC_SDXC)) + { + /* Enable High Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + } + else + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + break; + } + case SDMMC_SPEED_MODE_DEFAULT: + { + /* Switch to default Speed */ + if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; + status = HAL_ERROR; + } + + break; + } + case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/ + default: + hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + status = HAL_ERROR; + break; + } +#endif /* USE_SD_TRANSCEIVER */ + + /* Verify that SD card is ready to use after Speed mode switch*/ + tickstart = HAL_GetTick(); + while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_TIMEOUT; + } + } + + /* Set Block Size for Card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); + if (errorstate != HAL_SD_ERROR_NONE) + { + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS); + hsd->ErrorCode |= errorstate; + status = HAL_ERROR; + } + + /* Change State */ + hsd->State = HAL_SD_STATE_READY; + return status; +} + +/** + * @brief Gets the current sd card data state. + * @param hsd: pointer to SD handle + * @retval Card state + */ +HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd) +{ + uint32_t cardstate; + uint32_t errorstate; + uint32_t resp1 = 0; + + errorstate = SD_SendStatus(hsd, &resp1); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= errorstate; + } + + cardstate = ((resp1 >> 9U) & 0x0FU); + + return (HAL_SD_CardStateTypeDef)cardstate; +} + +/** + * @brief Abort the current transfer and disable the SD. + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information for SD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd) +{ + uint32_t error_code; + uint32_t tickstart; + + if (hsd->State == HAL_SD_STATE_BUSY) + { + /* DIsable All interrupts */ + __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); + __SDMMC_CMDTRANS_DISABLE(hsd->Instance); + + /*we will send the CMD12 in all cases in order to stop the data transfers*/ + /*In case the data transfer just finished , the external memory will not respond + and will return HAL_SD_ERROR_CMD_RSP_TIMEOUT*/ + /*In case the data transfer aborted , the external memory will respond and will return HAL_SD_ERROR_NONE*/ + /*Other scenario will return HAL_ERROR*/ + + hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); + error_code = hsd->ErrorCode; + if ((error_code != HAL_SD_ERROR_NONE) && (error_code != HAL_SD_ERROR_CMD_RSP_TIMEOUT)) + { + return HAL_ERROR; + } + + tickstart = HAL_GetTick(); + if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_CARD) + { + if (hsd->ErrorCode == HAL_SD_ERROR_NONE) + { + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_BUSYD0END)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_TIMEOUT; + } + } + } + + if (hsd->ErrorCode == HAL_SD_ERROR_CMD_RSP_TIMEOUT) + { + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + else if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_SDMMC) + { + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_DATAEND)) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_TIMEOUT; + } + } + } + else + { + /* Nothing to do*/ + } + + /*The reason of all these while conditions previously is that we need to wait the SDMMC and clear + the appropriate flags that will be set depending of the abort/non abort of the memory */ + /*Not waiting the SDMMC flags will cause the next SDMMC_DISABLE_IDMA to not get cleared + and will result in next SDMMC read/write operation to fail */ + + /*SDMMC ready for clear data flags*/ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_BUSYD0END); + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + /* If IDMA Context, disable Internal DMA */ + hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + hsd->State = HAL_SD_STATE_READY; + + /* Initialize the SD operation */ + hsd->Context = SD_CONTEXT_NONE; + } + return HAL_OK; +} + +/** + * @brief Abort the current transfer and disable the SD (IT mode). + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information for SD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd) +{ + HAL_SD_CardStateTypeDef CardState; + + /* Disable All interrupts */ + __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \ + SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR); + + /* If IDMA Context, disable Internal DMA */ + hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + + /* Clear All flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + CardState = HAL_SD_GetCardState(hsd); + hsd->State = HAL_SD_STATE_READY; + + if ((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) + { + hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); + } + + if (hsd->ErrorCode != HAL_SD_ERROR_NONE) + { + return HAL_ERROR; + } + else + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->AbortCpltCallback(hsd); +#else + HAL_SD_AbortCallback(hsd); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/* Private function ----------------------------------------------------------*/ +/** @addtogroup SD_Private_Functions + * @{ + */ + +/** + * @brief Initializes the sd card. + * @param hsd: Pointer to SD handle + * @retval SD Card error state + */ +static uint32_t SD_InitCard(SD_HandleTypeDef *hsd) +{ + HAL_SD_CardCSDTypeDef CSD; + uint32_t errorstate; + uint16_t sd_rca = 0U; + uint32_t tickstart = HAL_GetTick(); + + /* Check the power State */ + if (SDMMC_GetPowerState(hsd->Instance) == 0U) + { + /* Power off */ + return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } + + if (hsd->SdCard.CardType != CARD_SECURED) + { + /* Send CMD2 ALL_SEND_CID */ + errorstate = SDMMC_CmdSendCID(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card identification number data */ + hsd->CID[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); + hsd->CID[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2); + hsd->CID[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3); + hsd->CID[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4); + } + } + + if (hsd->SdCard.CardType != CARD_SECURED) + { + /* Send CMD3 SET_REL_ADDR with argument 0 */ + /* SD Card publishes its RCA. */ + while (sd_rca == 0U) + { + errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + if ((HAL_GetTick() - tickstart) >= SDMMC_CMDTIMEOUT) + { + return HAL_SD_ERROR_TIMEOUT; + } + } + } + if (hsd->SdCard.CardType != CARD_SECURED) + { + /* Get the SD card RCA */ + hsd->SdCard.RelCardAdd = sd_rca; + + /* Send CMD9 SEND_CSD with argument as card's RCA */ + errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + else + { + /* Get Card Specific Data */ + hsd->CSD[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); + hsd->CSD[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2); + hsd->CSD[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3); + hsd->CSD[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4); + } + } + + /* Get the Card Class */ + hsd->SdCard.Class = (SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2) >> 20U); + + /* Get CSD parameters */ + if (HAL_SD_GetCardCSD(hsd, &CSD) != HAL_OK) + { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + + /* Select the Card */ + errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* All cards are initialized */ + return HAL_SD_ERROR_NONE; +} + +/** + * @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: Pointer to SD handle + * @retval error state + */ +static uint32_t SD_PowerON(SD_HandleTypeDef *hsd) +{ + __IO uint32_t count = 0U; + uint32_t response = 0U; + uint32_t validvoltage = 0U; + uint32_t errorstate; +#if (USE_SD_TRANSCEIVER != 0U) + uint32_t tickstart = HAL_GetTick(); +#endif /* USE_SD_TRANSCEIVER */ + + /* CMD0: GO_IDLE_STATE */ + errorstate = SDMMC_CmdGoIdleState(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */ + errorstate = SDMMC_CmdOperCond(hsd->Instance); + if (errorstate == SDMMC_ERROR_TIMEOUT) /* No response to CMD8 */ + { + hsd->SdCard.CardVersion = CARD_V1_X; + /* CMD0: GO_IDLE_STATE */ + errorstate = SDMMC_CmdGoIdleState(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + } + else + { + hsd->SdCard.CardVersion = CARD_V2_X; + } + + if (hsd->SdCard.CardVersion == CARD_V2_X) + { + /* SEND CMD55 APP_CMD with RCA as 0 */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0); + if (errorstate != HAL_SD_ERROR_NONE) + { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + } + /* SD CARD */ + /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ + while ((count < SDMMC_MAX_VOLT_TRIAL) && (validvoltage == 0U)) + { + /* SEND CMD55 APP_CMD with RCA as 0 */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send CMD41 */ + errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_VOLTAGE_WINDOW_SD | SDMMC_HIGH_CAPACITY | + SD_SWITCH_1_8V_CAPACITY); + if (errorstate != HAL_SD_ERROR_NONE) + { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + + /* Get command response */ + response = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); + + /* Get operating voltage*/ + validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); + + count++; + } + + if (count >= SDMMC_MAX_VOLT_TRIAL) + { + return HAL_SD_ERROR_INVALID_VOLTRANGE; + } + + /* Set default card type */ + hsd->SdCard.CardType = CARD_SDSC; + + if ((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY) + { + hsd->SdCard.CardType = CARD_SDHC_SDXC; +#if (USE_SD_TRANSCEIVER != 0U) + if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) + { + if ((response & SD_SWITCH_1_8V_CAPACITY) == SD_SWITCH_1_8V_CAPACITY) + { + hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED; + + /* Start switching procedue */ + hsd->Instance->POWER |= SDMMC_POWER_VSWITCHEN; + + /* Send CMD11 to switch 1.8V mode */ + errorstate = SDMMC_CmdVoltageSwitch(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Check to CKSTOP */ + while ((hsd->Instance->STA & SDMMC_FLAG_CKSTOP) != SDMMC_FLAG_CKSTOP) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + return HAL_SD_ERROR_TIMEOUT; + } + } + + /* Clear CKSTOP Flag */ + hsd->Instance->ICR = SDMMC_FLAG_CKSTOP; + + /* Check to BusyD0 */ + if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) != SDMMC_FLAG_BUSYD0) + { + /* Error when activate Voltage Switch in SDMMC Peripheral */ + return SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { + /* Enable Transceiver Switch PIN */ +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->DriveTransceiver_1_8V_Callback(SET); +#else + HAL_SD_DriveTransceiver_1_8V_Callback(SET); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ + + /* Switch ready */ + hsd->Instance->POWER |= SDMMC_POWER_VSWITCH; + + /* Check VSWEND Flag */ + while ((hsd->Instance->STA & SDMMC_FLAG_VSWEND) != SDMMC_FLAG_VSWEND) + { + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + return HAL_SD_ERROR_TIMEOUT; + } + } + + /* Clear VSWEND Flag */ + hsd->Instance->ICR = SDMMC_FLAG_VSWEND; + + /* Check BusyD0 status */ + if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) == SDMMC_FLAG_BUSYD0) + { + /* Error when enabling 1.8V mode */ + return HAL_SD_ERROR_INVALID_VOLTRANGE; + } + /* Switch to 1.8V OK */ + + /* Disable VSWITCH FLAG from SDMMC Peripheral */ + hsd->Instance->POWER = 0x13U; + + /* Clean Status flags */ + hsd->Instance->ICR = 0xFFFFFFFFU; + } + } + } +#endif /* USE_SD_TRANSCEIVER */ + } + + return HAL_SD_ERROR_NONE; +} + +/** + * @brief Turns the SDMMC output signals off. + * @param hsd: Pointer to SD handle + * @retval None + */ +static void SD_PowerOFF(SD_HandleTypeDef *hsd) +{ + /* Set Power State to OFF */ + (void)SDMMC_PowerState_OFF(hsd->Instance); +} + +/** + * @brief Send Status info command. + * @param hsd: pointer to SD handle + * @param pSDstatus: Pointer to the buffer that will contain the SD card status + * SD Status register) + * @retval error state + */ +static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t count; + uint32_t *pData = pSDstatus; + + /* Check SD response */ + if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; + } + + /* Set block size for card if it is not equal to current block size for card */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_NONE; + return errorstate; + } + + /* Send CMD55 */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_NONE; + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = 64U; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_ENABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + /* Send ACMD13 (SD_APP_STAUS) with argument as card's RCA */ + errorstate = SDMMC_CmdStatusRegister(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->ErrorCode |= HAL_SD_ERROR_NONE; + return errorstate; + } + + /* Get status data */ + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) + { + for (count = 0U; count < 8U; count++) + { + *pData = SDMMC_ReadFIFO(hsd->Instance); + pData++; + } + } + + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + return HAL_SD_ERROR_TIMEOUT; + } + } + + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + return HAL_SD_ERROR_DATA_TIMEOUT; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + return HAL_SD_ERROR_DATA_CRC_FAIL; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) + { + return HAL_SD_ERROR_RX_OVERRUN; + } + else + { + /* Nothing to do */ + } + + while ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DPSMACT))) + { + *pData = SDMMC_ReadFIFO(hsd->Instance); + pData++; + + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + return HAL_SD_ERROR_TIMEOUT; + } + } + + /* Clear all the static status flags*/ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + return HAL_SD_ERROR_NONE; +} + +/** + * @brief Returns the current card's status. + * @param hsd: Pointer to SD handle + * @param pCardStatus: pointer to the buffer that will contain the SD card + * status (Card Status register) + * @retval error state + */ +static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus) +{ + uint32_t errorstate; + + if (pCardStatus == NULL) + { + return HAL_SD_ERROR_PARAM; + } + + /* Send Status command */ + errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Get SD card status */ + *pCardStatus = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1); + + return HAL_SD_ERROR_NONE; +} + +/** + * @brief Enables the SDMMC wide bus mode. + * @param hsd: pointer to SD handle + * @retval error state + */ +static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd) +{ + uint32_t scr[2U] = {0UL, 0UL}; + uint32_t errorstate; + + if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; + } + + /* Get SCR Register */ + errorstate = SD_FindSCR(hsd, scr); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* If requested card supports wide bus operation */ + if ((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO) + { + /* Send CMD55 APP_CMD with argument as card's RCA.*/ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */ + errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + return HAL_SD_ERROR_NONE; + } + else + { + return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } +} + +/** + * @brief Disables the SDMMC wide bus mode. + * @param hsd: Pointer to SD handle + * @retval error state + */ +static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd) +{ + uint32_t scr[2U] = {0UL, 0UL}; + uint32_t errorstate; + + if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + { + return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; + } + + /* Get SCR Register */ + errorstate = SD_FindSCR(hsd, scr); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* If requested card supports 1 bit mode operation */ + if ((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO) + { + /* Send CMD55 APP_CMD with argument as card's RCA */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */ + errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + return HAL_SD_ERROR_NONE; + } + else + { + return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } +} + +/** + * @brief Finds the SD card SCR register value. + * @param hsd: Pointer to SD handle + * @param pSCR: pointer to the buffer that will contain the SCR value + * @retval error state + */ +static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t index = 0U; + uint32_t tempscr[2U] = {0UL, 0UL}; + uint32_t *scr = pSCR; + + /* Set Block Size To 8 Bytes */ + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Send CMD55 APP_CMD with argument as card's RCA */ + errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U)); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = 8U; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_8B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_ENABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */ + errorstate = SDMMC_CmdSendSCR(hsd->Instance); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | + SDMMC_FLAG_DATAEND)) + { + if ((!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOE)) && (index == 0U)) + { + tempscr[0] = SDMMC_ReadFIFO(hsd->Instance); + tempscr[1] = SDMMC_ReadFIFO(hsd->Instance); + index++; + } + + if ((HAL_GetTick() - tickstart) >= SDMMC_SWDATATIMEOUT) + { + return HAL_SD_ERROR_TIMEOUT; + } + } + + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); + + return HAL_SD_ERROR_DATA_TIMEOUT; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); + + return HAL_SD_ERROR_DATA_CRC_FAIL; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); + + return HAL_SD_ERROR_RX_OVERRUN; + } + else + { + /* No error flag set */ + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + *scr = (((tempscr[1] & SDMMC_0TO7BITS) << 24U) | ((tempscr[1] & SDMMC_8TO15BITS) << 8U) | \ + ((tempscr[1] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24U)); + scr++; + *scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24U) | ((tempscr[0] & SDMMC_8TO15BITS) << 8U) | \ + ((tempscr[0] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24U)); + + } + + return HAL_SD_ERROR_NONE; +} + +/** + * @brief Wrap up reading in non-blocking mode. + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void SD_Read_IT(SD_HandleTypeDef *hsd) +{ + uint32_t count; + uint32_t data; + uint8_t *tmp; + + tmp = hsd->pRxBuffPtr; + + if (hsd->RxXferSize >= SDMMC_FIFO_SIZE) + { + /* Read data from SDMMC Rx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = SDMMC_ReadFIFO(hsd->Instance); + *tmp = (uint8_t)(data & 0xFFU); + tmp++; + *tmp = (uint8_t)((data >> 8U) & 0xFFU); + tmp++; + *tmp = (uint8_t)((data >> 16U) & 0xFFU); + tmp++; + *tmp = (uint8_t)((data >> 24U) & 0xFFU); + tmp++; + } + + hsd->pRxBuffPtr = tmp; + hsd->RxXferSize -= SDMMC_FIFO_SIZE; + } +} + +/** + * @brief Wrap up writing in non-blocking mode. + * @param hsd: pointer to a SD_HandleTypeDef structure that contains + * the configuration information. + * @retval None + */ +static void SD_Write_IT(SD_HandleTypeDef *hsd) +{ + uint32_t count; + uint32_t data; + const uint8_t *tmp; + + tmp = hsd->pTxBuffPtr; + + if (hsd->TxXferSize >= SDMMC_FIFO_SIZE) + { + /* Write data to SDMMC Tx FIFO */ + for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++) + { + data = (uint32_t)(*tmp); + tmp++; + data |= ((uint32_t)(*tmp) << 8U); + tmp++; + data |= ((uint32_t)(*tmp) << 16U); + tmp++; + data |= ((uint32_t)(*tmp) << 24U); + tmp++; + (void)SDMMC_WriteFIFO(hsd->Instance, &data); + } + + hsd->pTxBuffPtr = tmp; + hsd->TxXferSize -= SDMMC_FIFO_SIZE; + } +} + +/** + * @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 SDMMCCK clock between 25 and 50 MHz + * @param hsd: SD handle + * @param SwitchSpeedMode: SD speed mode( SDMMC_SDR12_SWITCH_PATTERN, SDMMC_SDR25_SWITCH_PATTERN) + * @retval SD Card error state + */ +uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode) +{ + uint32_t errorstate = HAL_SD_ERROR_NONE; + SDMMC_DataInitTypeDef sdmmc_datainitstructure; + uint32_t SD_hs[16] = {0}; + uint32_t count; + uint32_t loop = 0 ; + uint32_t Timeout = HAL_GetTick(); + + if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED) + { + /* Standard Speed Card <= 12.5Mhz */ + return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } + + if (hsd->SdCard.CardSpeed >= CARD_HIGH_SPEED) + { + /* Initialize the Data control register */ + hsd->Instance->DCTRL = 0; + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); + + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdmmc_datainitstructure.DataTimeOut = SDMMC_DATATIMEOUT; + sdmmc_datainitstructure.DataLength = 64U; + sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ; + sdmmc_datainitstructure.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + sdmmc_datainitstructure.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + sdmmc_datainitstructure.DPSM = SDMMC_DPSM_ENABLE; + + (void)SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure); + + errorstate = SDMMC_CmdSwitch(hsd->Instance, SwitchSpeedMode); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | + SDMMC_FLAG_DATAEND)) + { + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) + { + for (count = 0U; count < 8U; count++) + { + SD_hs[(8U * loop) + count] = SDMMC_ReadFIFO(hsd->Instance); + } + loop ++; + } + if ((HAL_GetTick() - Timeout) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_SD_ERROR_TIMEOUT; + } + } + + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); + + return errorstate; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); + + errorstate = SDMMC_ERROR_DATA_CRC_FAIL; + + return errorstate; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); + + errorstate = SDMMC_ERROR_RX_OVERRUN; + + return errorstate; + } + else + { + /* No error flag set */ + } + + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + /* Test if the switch mode HS is ok */ + if ((((uint8_t *)SD_hs)[13] & 2U) != 2U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + + } + + return errorstate; +} + +#if (USE_SD_TRANSCEIVER != 0U) +/** + * @brief Switches the SD card to Ultra High Speed mode. + * This API must be used after "Transfer State" + * @note This operation should be followed by the configuration + * of PLL to have SDMMCCK clock between 50 and 120 MHz + * @param hsd: SD handle + * @param UltraHighSpeedMode: SD speed mode( SDMMC_SDR50_SWITCH_PATTERN, SDMMC_SDR104_SWITCH_PATTERN) + * @retval SD Card error state + */ +static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode) +{ + uint32_t errorstate = HAL_SD_ERROR_NONE; + SDMMC_DataInitTypeDef sdmmc_datainitstructure; + uint32_t SD_hs[16] = {0}; + uint32_t count; + uint32_t loop = 0 ; + uint32_t Timeout = HAL_GetTick(); + + if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED) + { + /* Standard Speed Card <= 12.5Mhz */ + return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } + + if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) + { + /* Initialize the Data control register */ + hsd->Instance->DCTRL = 0; + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); + + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdmmc_datainitstructure.DataTimeOut = SDMMC_DATATIMEOUT; + sdmmc_datainitstructure.DataLength = 64U; + sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ; + sdmmc_datainitstructure.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + sdmmc_datainitstructure.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + sdmmc_datainitstructure.DPSM = SDMMC_DPSM_ENABLE; + + if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK) + { + return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR); + } + + errorstate = SDMMC_CmdSwitch(hsd->Instance, UltraHighSpeedMode); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | + SDMMC_FLAG_DATAEND)) + { + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) + { + for (count = 0U; count < 8U; count++) + { + SD_hs[(8U * loop) + count] = SDMMC_ReadFIFO(hsd->Instance); + } + loop ++; + } + + if ((HAL_GetTick() - Timeout) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_SD_ERROR_TIMEOUT; + } + } + + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); + + return errorstate; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); + + errorstate = SDMMC_ERROR_DATA_CRC_FAIL; + + return errorstate; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); + + errorstate = SDMMC_ERROR_RX_OVERRUN; + + return errorstate; + } + else + { + /* No error flag set */ + } + + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + /* Test if the switch mode HS is ok */ + if ((((uint8_t *)SD_hs)[13] & 2U) != 2U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->DriveTransceiver_1_8V_Callback(SET); +#else + HAL_SD_DriveTransceiver_1_8V_Callback(SET); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ +#if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2) + /* Enable DelayBlock Peripheral */ + /* SDMMC_FB_CLK tuned feedback clock selected as receive clock, for SDR104 */ + MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_1); + LL_DLYB_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance)); +#endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */ + } + } + + return errorstate; +} + +/** + * @brief Switches the SD card to Double Data Rate (DDR) mode. + * This API must be used after "Transfer State" + * @note This operation should be followed by the configuration + * of PLL to have SDMMCCK clock less than 50MHz + * @param hsd: SD handle + * @retval SD Card error state + */ +static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd) +{ + uint32_t errorstate = HAL_SD_ERROR_NONE; + SDMMC_DataInitTypeDef sdmmc_datainitstructure; + uint32_t SD_hs[16] = {0}; + uint32_t count; + uint32_t loop = 0 ; + uint32_t Timeout = HAL_GetTick(); + + if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED) + { + /* Standard Speed Card <= 12.5Mhz */ + return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + } + + if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED) + { + /* Initialize the Data control register */ + hsd->Instance->DCTRL = 0; + errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); + + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdmmc_datainitstructure.DataTimeOut = SDMMC_DATATIMEOUT; + sdmmc_datainitstructure.DataLength = 64U; + sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ; + sdmmc_datainitstructure.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + sdmmc_datainitstructure.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + sdmmc_datainitstructure.DPSM = SDMMC_DPSM_ENABLE; + + if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK) + { + return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR); + } + + errorstate = SDMMC_CmdSwitch(hsd->Instance, SDMMC_DDR50_SWITCH_PATTERN); + if (errorstate != HAL_SD_ERROR_NONE) + { + return errorstate; + } + + while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND | + SDMMC_FLAG_DATAEND)) + { + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF)) + { + for (count = 0U; count < 8U; count++) + { + SD_hs[(8U * loop) + count] = SDMMC_ReadFIFO(hsd->Instance); + } + loop ++; + } + + if ((HAL_GetTick() - Timeout) >= SDMMC_SWDATATIMEOUT) + { + hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT; + hsd->State = HAL_SD_STATE_READY; + return HAL_SD_ERROR_TIMEOUT; + } + } + + if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT); + + return errorstate; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL); + + errorstate = SDMMC_ERROR_DATA_CRC_FAIL; + + return errorstate; + } + else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR)) + { + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR); + + errorstate = SDMMC_ERROR_RX_OVERRUN; + + return errorstate; + } + else + { + /* No error flag set */ + } + + /* Clear all the static flags */ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + /* Test if the switch mode is ok */ + if ((((uint8_t *)SD_hs)[13] & 2U) != 2U) + { + errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE; + } + else + { +#if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U) + hsd->DriveTransceiver_1_8V_Callback(SET); +#else + HAL_SD_DriveTransceiver_1_8V_Callback(SET); +#endif /* USE_HAL_SD_REGISTER_CALLBACKS */ +#if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2) + /* Enable DelayBlock Peripheral */ + /* SDMMC_CKin feedback clock selected as receive clock, for DDR50 */ + MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_0); + LL_DLYB_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance)); +#endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */ + } + } + + return errorstate; +} + +#endif /* USE_SD_TRANSCEIVER */ + +/** + * @brief Read DMA Linked list node Transfer completed callbacks + * @param hsd: SD handle + * @retval None + */ +__weak void HAL_SDEx_Read_DMALnkLstBufCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDEx_Read_DMALnkLstBufCpltCallback can be implemented in the user file + */ +} +/** + * @brief Read DMA Linked list node Transfer completed callbacks + * @param hsd: SD handle + * @retval None + */ +__weak void HAL_SDEx_Write_DMALnkLstBufCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDEx_Write_DMALnkLstBufCpltCallback can be implemented in the user file + */ +} + +/** + * @} + */ + +#endif /* HAL_SD_MODULE_ENABLED */ +#endif /* SDMMC1 || SDMMC2 */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd_ex.c index ec9375d7d..c788096e6 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sd_ex.c @@ -1,393 +1,393 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_sd_ex.c - * @author MCD Application Team - * @brief SD card Extended HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Secure Digital (SD) peripheral: - * + Extended features functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The SD Extension HAL driver can be used as follows: - (+) Configure Buffer0 and Buffer1 start address and Buffer size using HAL_SDEx_ConfigDMAMultiBuffer() function. - (+) Start Read and Write for multibuffer mode using HAL_SDEx_ReadBlocksDMAMultiBuffer() - and HAL_SDEx_WriteBlocksDMAMultiBuffer() functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SDEx SDEx - * @brief SD Extended HAL module driver - * @{ - */ - -#if defined (SDMMC1) || defined (SDMMC2) -#ifdef HAL_SD_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup SDEx_Exported_Functions - * @{ - */ - - -/** @addtogroup SDEx_Exported_Functions_Group1 - * @brief Linked List management functions - * -@verbatim - =============================================================================== - ##### Linked List management functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the needed functions. - -@endverbatim - * @{ - */ - -/** - * @brief Build Linked List node. - * @param pNode: Pointer to new node to add. - * @param pNodeConf: Pointer to configuration parameters for new node to add. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_BuildNode(SD_DMALinkNodeTypeDef *pNode, SD_DMALinkNodeConfTypeDef *pNodeConf) -{ - - (void)SDMMC_DMALinkedList_BuildNode(pNode, pNodeConf); - - return (HAL_OK); - -} - -/** - * @brief Insert new Linked List node. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @param pPrevNode: Pointer to previous node. - * @param pNewNode: Pointer to new node to insert. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_InsertNode(SD_DMALinkedListTypeDef *pLinkedList, - SD_DMALinkNodeTypeDef *pPrevNode, SD_DMALinkNodeTypeDef *pNewNode) -{ - - (void)SDMMC_DMALinkedList_InsertNode(pLinkedList, pPrevNode, pNewNode); - - return (HAL_OK); - -} -/** - * @brief Remove Linked List node. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @param pNode: Pointer to node to remove. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_RemoveNode(SD_DMALinkedListTypeDef *pLinkedList, SD_DMALinkNodeTypeDef *pNode) -{ - - if (SDMMC_DMALinkedList_RemoveNode(pLinkedList, pNode) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} - -/** - * @brief Lock Linked List node. - * @param pNode: Pointer to node to remove. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_LockNode(SD_DMALinkNodeTypeDef *pNode) -{ - - if (SDMMC_DMALinkedList_LockNode(pNode) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} - -/** - * @brief Unlock Linked List node. - * @param pNode: Pointer to node to remove. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_UnlockNode(SD_DMALinkNodeTypeDef *pNode) -{ - - if (SDMMC_DMALinkedList_UnlockNode(pNode) != SDMMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - return HAL_OK; - } -} - -/** - * @brief Enable Circular mode for DMA Linked List. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_EnableCircularMode(SD_DMALinkedListTypeDef *pLinkedList) -{ - - (void)SDMMC_DMALinkedList_EnableCircularMode(pLinkedList); - - return HAL_OK; - -} -/** - * @brief Disable Circular mode for DMA Linked List. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_DisableCircularMode(SD_DMALinkedListTypeDef *pLinkedList) -{ - - (void)SDMMC_DMALinkedList_DisableCircularMode(pLinkedList); - - return HAL_OK; - -} - - -/** - * @brief Reads block(s) from a specified address in a card. The received Data will be stored in linked list buffers. - * linked list should be prepared before call this function . - * @param hsd: SD handle - * @param pLinkedList: pointer to first linked list node - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Total number of blocks to read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_ReadBlocks(SD_HandleTypeDef *hsd, SDMMC_DMALinkedListTypeDef *pLinkedList, - uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t DmaBase0_reg; - uint32_t DmaBase1_reg; - uint32_t add = BlockAdd; - - if (hsd->State == HAL_SD_STATE_READY) - { - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; - hsd->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; - - hsd->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; - hsd->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | - sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ - - DmaBase0_reg = hsd->Instance->IDMABASER; - DmaBase1_reg = hsd->Instance->IDMABAR; - - if ((hsd->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) - { - hsd->ErrorCode = HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0; - /* Clear old Flags*/ - __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); - - hsd->ErrorCode = HAL_SD_ERROR_NONE; - hsd->State = HAL_SD_STATE_BUSY; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= 512U; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - hsd->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; - - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; - - /* Read Blocks in DMA mode */ - hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode |= errorstate; - return HAL_ERROR; - } - - __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | - SDMMC_IT_IDMABTC)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } - -} - -/** - * @brief Write block(s) to a specified address in a card. The transferred Data are stored linked list nodes buffers . - * linked list should be prepared before call this function . - * @param hsd: SD handle - * @param pLinkedList: pointer to first linked list node - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Total number of blocks to read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDEx_DMALinkedList_WriteBlocks(SD_HandleTypeDef *hsd, SDMMC_DMALinkedListTypeDef *pLinkedList, - uint32_t BlockAdd, uint32_t NumberOfBlocks) - -{ - SDMMC_DataInitTypeDef config; - uint32_t errorstate; - uint32_t DmaBase0_reg; - uint32_t DmaBase1_reg; - uint32_t add = BlockAdd; - - if (hsd->State == HAL_SD_STATE_READY) - { - if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; - hsd->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; - - hsd->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; - hsd->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | - sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ - - DmaBase0_reg = hsd->Instance->IDMABASER; - DmaBase1_reg = hsd->Instance->IDMABAR; - - if ((hsd->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) - { - hsd->ErrorCode = HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0; - - hsd->ErrorCode = HAL_SD_ERROR_NONE; - - hsd->State = HAL_SD_STATE_BUSY; - - if (hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - add *= 512U; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; - config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; - config.DPSM = SDMMC_DPSM_DISABLE; - (void)SDMMC_ConfigData(hsd->Instance, &config); - - __SDMMC_CMDTRANS_ENABLE(hsd->Instance); - - hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; - - /* Write Blocks in DMA mode */ - hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); - if (errorstate != HAL_SD_ERROR_NONE) - { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode |= errorstate; - return HAL_ERROR; - } - - __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | - SDMMC_IT_IDMABTC)); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_SD_MODULE_ENABLED */ -#endif /* SDMMC1 || SDMMC2 */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_sd_ex.c + * @author MCD Application Team + * @brief SD card Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Secure Digital (SD) peripheral: + * + Extended features functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SD Extension HAL driver can be used as follows: + (+) Configure Buffer0 and Buffer1 start address and Buffer size using HAL_SDEx_ConfigDMAMultiBuffer() function. + (+) Start Read and Write for multibuffer mode using HAL_SDEx_ReadBlocksDMAMultiBuffer() + and HAL_SDEx_WriteBlocksDMAMultiBuffer() functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SDEx SDEx + * @brief SD Extended HAL module driver + * @{ + */ + +#if defined (SDMMC1) || defined (SDMMC2) +#ifdef HAL_SD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SDEx_Exported_Functions + * @{ + */ + + +/** @addtogroup SDEx_Exported_Functions_Group1 + * @brief Linked List management functions + * +@verbatim + =============================================================================== + ##### Linked List management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed functions. + +@endverbatim + * @{ + */ + +/** + * @brief Build Linked List node. + * @param pNode: Pointer to new node to add. + * @param pNodeConf: Pointer to configuration parameters for new node to add. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_BuildNode(SD_DMALinkNodeTypeDef *pNode, SD_DMALinkNodeConfTypeDef *pNodeConf) +{ + + (void)SDMMC_DMALinkedList_BuildNode(pNode, pNodeConf); + + return (HAL_OK); + +} + +/** + * @brief Insert new Linked List node. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @param pPrevNode: Pointer to previous node. + * @param pNewNode: Pointer to new node to insert. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_InsertNode(SD_DMALinkedListTypeDef *pLinkedList, + SD_DMALinkNodeTypeDef *pPrevNode, SD_DMALinkNodeTypeDef *pNewNode) +{ + + (void)SDMMC_DMALinkedList_InsertNode(pLinkedList, pPrevNode, pNewNode); + + return (HAL_OK); + +} +/** + * @brief Remove Linked List node. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @param pNode: Pointer to node to remove. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_RemoveNode(SD_DMALinkedListTypeDef *pLinkedList, SD_DMALinkNodeTypeDef *pNode) +{ + + if (SDMMC_DMALinkedList_RemoveNode(pLinkedList, pNode) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Lock Linked List node. + * @param pNode: Pointer to node to remove. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_LockNode(SD_DMALinkNodeTypeDef *pNode) +{ + + if (SDMMC_DMALinkedList_LockNode(pNode) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Unlock Linked List node. + * @param pNode: Pointer to node to remove. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_UnlockNode(SD_DMALinkNodeTypeDef *pNode) +{ + + if (SDMMC_DMALinkedList_UnlockNode(pNode) != SDMMC_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Enable Circular mode for DMA Linked List. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_EnableCircularMode(SD_DMALinkedListTypeDef *pLinkedList) +{ + + (void)SDMMC_DMALinkedList_EnableCircularMode(pLinkedList); + + return HAL_OK; + +} +/** + * @brief Disable Circular mode for DMA Linked List. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_DisableCircularMode(SD_DMALinkedListTypeDef *pLinkedList) +{ + + (void)SDMMC_DMALinkedList_DisableCircularMode(pLinkedList); + + return HAL_OK; + +} + + +/** + * @brief Reads block(s) from a specified address in a card. The received Data will be stored in linked list buffers. + * linked list should be prepared before call this function . + * @param hsd: SD handle + * @param pLinkedList: pointer to first linked list node + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Total number of blocks to read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_ReadBlocks(SD_HandleTypeDef *hsd, SDMMC_DMALinkedListTypeDef *pLinkedList, + uint32_t BlockAdd, uint32_t NumberOfBlocks) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t DmaBase0_reg; + uint32_t DmaBase1_reg; + uint32_t add = BlockAdd; + + if (hsd->State == HAL_SD_STATE_READY) + { + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; + hsd->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; + + hsd->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; + hsd->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | + sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ + + DmaBase0_reg = hsd->Instance->IDMABASER; + DmaBase1_reg = hsd->Instance->IDMABAR; + + if ((hsd->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) + { + hsd->ErrorCode = HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0; + /* Clear old Flags*/ + __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS); + + hsd->ErrorCode = HAL_SD_ERROR_NONE; + hsd->State = HAL_SD_STATE_BUSY; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + hsd->Instance->DCTRL |= SDMMC_DCTRL_FIFORST; + + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; + + /* Read Blocks in DMA mode */ + hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + + /* Read Multi Block command */ + errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->State = HAL_SD_STATE_READY; + hsd->ErrorCode |= errorstate; + return HAL_ERROR; + } + + __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND | + SDMMC_IT_IDMABTC)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } + +} + +/** + * @brief Write block(s) to a specified address in a card. The transferred Data are stored linked list nodes buffers . + * linked list should be prepared before call this function . + * @param hsd: SD handle + * @param pLinkedList: pointer to first linked list node + * @param BlockAdd: Block Address from where data is to be read + * @param NumberOfBlocks: Total number of blocks to read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDEx_DMALinkedList_WriteBlocks(SD_HandleTypeDef *hsd, SDMMC_DMALinkedListTypeDef *pLinkedList, + uint32_t BlockAdd, uint32_t NumberOfBlocks) + +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t DmaBase0_reg; + uint32_t DmaBase1_reg; + uint32_t add = BlockAdd; + + if (hsd->State == HAL_SD_STATE_READY) + { + if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + { + hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + hsd->Instance->IDMABASER = (uint32_t) pLinkedList->pHeadNode->IDMABASER; + hsd->Instance->IDMABSIZE = (uint32_t) pLinkedList->pHeadNode->IDMABSIZE; + + hsd->Instance->IDMABAR = (uint32_t) pLinkedList->pHeadNode; + hsd->Instance->IDMALAR = (uint32_t) SDMMC_IDMALAR_ABR | SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ULA | + sizeof(SDMMC_DMALinkNodeTypeDef) ; /* Initial configuration */ + + DmaBase0_reg = hsd->Instance->IDMABASER; + DmaBase1_reg = hsd->Instance->IDMABAR; + + if ((hsd->Instance->IDMABSIZE == 0U) || (DmaBase0_reg == 0U) || (DmaBase1_reg == 0U)) + { + hsd->ErrorCode = HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return HAL_ERROR; + } + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0; + + hsd->ErrorCode = HAL_SD_ERROR_NONE; + + hsd->State = HAL_SD_STATE_BUSY; + + if (hsd->SdCard.CardType != CARD_SDHC_SDXC) + { + add *= 512U; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + config.DataLength = BLOCKSIZE * NumberOfBlocks; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B; + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = SDMMC_TRANSFER_MODE_BLOCK; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsd->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hsd->Instance); + + hsd->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_DOUBLE_BUFF0; + + /* Write Blocks in DMA mode */ + hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + + /* Write Multi Block command */ + errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add); + if (errorstate != HAL_SD_ERROR_NONE) + { + hsd->State = HAL_SD_STATE_READY; + hsd->ErrorCode |= errorstate; + return HAL_ERROR; + } + + __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND | + SDMMC_IT_IDMABTC)); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SD_MODULE_ENABLED */ +#endif /* SDMMC1 || SDMMC2 */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sdram.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sdram.c index 217ad74c1..a3687090b 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sdram.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sdram.c @@ -1,1429 +1,1431 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_sdram.c - * @author MCD Application Team - * @brief SDRAM HAL module driver. - * This file provides a generic firmware to drive SDRAM memories mounted - * as external device. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 hsdram - - (++) 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() - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_SDRAM_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - Use Functions HAL_SDRAM_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) MspInitCallback : SDRAM MspInit. - (+) MspDeInitCallback : SDRAM MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function HAL_SDRAM_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) MspInitCallback : SDRAM MspInit. - (+) MspDeInitCallback : SDRAM MspDeInit. - This function) takes as parameters the HAL peripheral handle and the Callback ID. - - By default, after the HAL_SDRAM_Init and if the state is HAL_SDRAM_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_SDRAM_Init - and HAL_SDRAM_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_SDRAM_Init and HAL_SDRAM_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_SDRAM_RegisterCallback before calling HAL_SDRAM_DeInit - or HAL_SDRAM_Init function. - - When The compilation define USE_HAL_SDRAM_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_SDRAM_MODULE_ENABLED - -/** @defgroup SDRAM SDRAM - * @brief SDRAM driver modules - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SDRAM_Private_Functions SDRAM Private Functions - * @{ - */ -static void SDRAM_DMACplt(DMA_HandleTypeDef *hdma); -static void SDRAM_DMACpltProt(DMA_HandleTypeDef *hdma); -static void SDRAM_DMAError(DMA_HandleTypeDef *hdma); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup SDRAM_Exported_Functions SDRAM Exported Functions - * @{ - */ - -/** @defgroup SDRAM_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) - { - /* Allocate lock resource and initialize it */ - hsdram->Lock = HAL_UNLOCKED; -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) - if (hsdram->MspInitCallback == NULL) - { - hsdram->MspInitCallback = HAL_SDRAM_MspInit; - } - hsdram->RefreshErrorCallback = HAL_SDRAM_RefreshErrorCallback; - hsdram->DmaXferCpltCallback = HAL_SDRAM_DMA_XferCpltCallback; - hsdram->DmaXferErrorCallback = HAL_SDRAM_DMA_XferErrorCallback; - - /* Init the low level hardware */ - hsdram->MspInitCallback(hsdram); -#else - /* Initialize the low level hardware (MSP) */ - HAL_SDRAM_MspInit(hsdram); -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ - } - - /* Initialize the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Initialize SDRAM control Interface */ - (void)FMC_SDRAM_Init(hsdram->Instance, &(hsdram->Init)); - - /* Initialize SDRAM timing Interface */ - (void)FMC_SDRAM_Timing_Init(hsdram->Instance, Timing, hsdram->Init.SDBank); - - /* Enable FMC Peripheral */ - __FMC_ENABLE(); - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Perform the SDRAM device initialization sequence. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram) -{ -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) - if (hsdram->MspDeInitCallback == NULL) - { - hsdram->MspDeInitCallback = HAL_SDRAM_MspDeInit; - } - - /* DeInit the low level hardware */ - hsdram->MspDeInitCallback(hsdram); -#else - /* Initialize the low level hardware (MSP) */ - HAL_SDRAM_MspDeInit(hsdram); -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ - - /* Configure the SDRAM registers with their reset values */ - (void)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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @retval None - */ -__weak void HAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @retval None - */ -__weak void HAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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 */ -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) - hsdram->RefreshErrorCallback(hsdram); -#else - HAL_SDRAM_RefreshErrorCallback(hsdram); -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ - - /* 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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @retval None - */ -__weak void HAL_SDRAM_RefreshErrorCallback(SDRAM_HandleTypeDef *hsdram) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -__weak void HAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - uint32_t size; - __IO uint8_t *pSdramAddress = (uint8_t *)pAddress; - uint8_t *pdestbuff = pDstBuffer; - HAL_SDRAM_StateTypeDef state = hsdram->State; - - /* Check the SDRAM controller state */ - if (state == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Read data from source */ - for (size = BufferSize; size != 0U; size--) - { - *pdestbuff = *(__IO uint8_t *)pSdramAddress; - pdestbuff++; - pSdramAddress++; - } - - /* Update the SDRAM controller state */ - hsdram->State = state; - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Writes 8-bit data buffer to SDRAM memory. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - uint32_t size; - __IO uint8_t *pSdramAddress = (uint8_t *)pAddress; - uint8_t *psrcbuff = pSrcBuffer; - - /* Check the SDRAM controller state */ - if (hsdram->State == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Write data to memory */ - for (size = BufferSize; size != 0U; size--) - { - *(__IO uint8_t *)pSdramAddress = *psrcbuff; - psrcbuff++; - pSdramAddress++; - } - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Reads 16-bit data buffer from the SDRAM memory. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *pSdramAddress = pAddress; - uint16_t *pdestbuff = pDstBuffer; - HAL_SDRAM_StateTypeDef state = hsdram->State; - - /* Check the SDRAM controller state */ - if (state == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Read data from memory */ - for (size = BufferSize; size >= 2U ; size -= 2U) - { - *pdestbuff = (uint16_t)((*pSdramAddress) & 0x0000FFFFU); - pdestbuff++; - *pdestbuff = (uint16_t)(((*pSdramAddress) & 0xFFFF0000U) >> 16U); - pdestbuff++; - pSdramAddress++; - } - - /* Read last 16-bits if size is not 32-bits multiple */ - if ((BufferSize % 2U) != 0U) - { - *pdestbuff = (uint16_t)((*pSdramAddress) & 0x0000FFFFU); - } - - /* Update the SDRAM controller state */ - hsdram->State = state; - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Writes 16-bit data buffer to SDRAM memory. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *psdramaddress = pAddress; - uint16_t *psrcbuff = pSrcBuffer; - - /* Check the SDRAM controller state */ - if (hsdram->State == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Write data to memory */ - for (size = BufferSize; size >= 2U ; size -= 2U) - { - *psdramaddress = (uint32_t)(*psrcbuff); - psrcbuff++; - *psdramaddress |= ((uint32_t)(*psrcbuff) << 16U); - psrcbuff++; - psdramaddress++; - } - - /* Write last 16-bits if size is not 32-bits multiple */ - if ((BufferSize % 2U) != 0U) - { - *psdramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psdramaddress) & 0xFFFF0000U); - } - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Reads 32-bit data buffer from the SDRAM memory. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *pSdramAddress = (uint32_t *)pAddress; - uint32_t *pdestbuff = pDstBuffer; - HAL_SDRAM_StateTypeDef state = hsdram->State; - - /* Check the SDRAM controller state */ - if (state == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Read data from source */ - for (size = BufferSize; size != 0U; size--) - { - *pdestbuff = *(__IO uint32_t *)pSdramAddress; - pdestbuff++; - pSdramAddress++; - } - - /* Update the SDRAM controller state */ - hsdram->State = state; - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Writes 32-bit data buffer to SDRAM memory. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *pSdramAddress = pAddress; - uint32_t *psrcbuff = pSrcBuffer; - - /* Check the SDRAM controller state */ - if (hsdram->State == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Write data to memory */ - for (size = BufferSize; size != 0U; size--) - { - *pSdramAddress = *psrcbuff; - psrcbuff++; - pSdramAddress++; - } - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Reads a Words data from the SDRAM memory using DMA transfer. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - HAL_StatusTypeDef status; - HAL_SDRAM_StateTypeDef state = hsdram->State; - uint32_t size; - uint32_t data_width; - - /* Check the SDRAM controller state */ - if (state == HAL_SDRAM_STATE_BUSY) - { - status = HAL_BUSY; - } - else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Configure DMA user callbacks */ - if (state == HAL_SDRAM_STATE_READY) - { - hsdram->hdma->XferCpltCallback = SDRAM_DMACplt; - } - else - { - hsdram->hdma->XferCpltCallback = SDRAM_DMACpltProt; - } - hsdram->hdma->XferErrorCallback = SDRAM_DMAError; - - if ((hsdram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hsdram->hdma->LinkedListQueue != 0U) && (hsdram->hdma->LinkedListQueue->Head != 0U)) - { - /* Check destination data width and set the size to be transferred */ - data_width = hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - /* Set Source , destination , buffer size */ - /* Set DMA data size */ - hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; - /* Set DMA source address */ - hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pAddress; - /* Set DMA destination address */ - hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pDstBuffer; - - /* Enable the DMA Stream */ - status = HAL_DMAEx_List_Start_IT(hsdram->hdma); - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - - status = HAL_ERROR; - } - } - else - { - /* Check destination data width and set the size to be transferred */ - data_width = hsdram->hdma->Init.DestDataWidth; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - - /* Enable the DMA Stream */ - status = HAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, size); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Writes a Words data buffer to SDRAM memory using DMA transfer. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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) -{ - HAL_StatusTypeDef status; - uint32_t size; - uint32_t data_width; - - /* Check the SDRAM controller state */ - if (hsdram->State == HAL_SDRAM_STATE_BUSY) - { - status = HAL_BUSY; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsdram); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Configure DMA user callbacks */ - hsdram->hdma->XferCpltCallback = SDRAM_DMACplt; - hsdram->hdma->XferErrorCallback = SDRAM_DMAError; - - if ((hsdram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hsdram->hdma->LinkedListQueue != 0U) && (hsdram->hdma->LinkedListQueue->Head != 0U)) - { - /* Check destination data width and set the size to be transferred */ - data_width = hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - /* Set Source , destination , buffer size */ - /* Set DMA data size */ - hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; - /* Set DMA source address */ - hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pSrcBuffer; - /* Set DMA destination address */ - hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pAddress; - - /* Enable the DMA Stream */ - status = HAL_DMAEx_List_Start_IT(hsdram->hdma); - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - - status = HAL_ERROR; - } - } - else - { - /* Check destination data width and set the size to be transferred */ - data_width = hsdram->hdma->Init.DestDataWidth; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - - /* Enable the DMA Stream */ - status = HAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, size); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsdram); - } - else - { - status = HAL_ERROR; - } - - return status; -} - -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User SDRAM Callback - * To be used to override the weak predefined callback - * @param hsdram : SDRAM handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SDRAM_MSP_INIT_CB_ID SDRAM MspInit callback ID - * @arg @ref HAL_SDRAM_MSP_DEINIT_CB_ID SDRAM MspDeInit callback ID - * @arg @ref HAL_SDRAM_REFRESH_ERR_CB_ID SDRAM Refresh Error callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_SDRAM_RegisterCallback(SDRAM_HandleTypeDef *hsdram, HAL_SDRAM_CallbackIDTypeDef CallbackId, - pSDRAM_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_SDRAM_StateTypeDef state; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - state = hsdram->State; - if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_SDRAM_MSP_INIT_CB_ID : - hsdram->MspInitCallback = pCallback; - break; - case HAL_SDRAM_MSP_DEINIT_CB_ID : - hsdram->MspDeInitCallback = pCallback; - break; - case HAL_SDRAM_REFRESH_ERR_CB_ID : - hsdram->RefreshErrorCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hsdram->State == HAL_SDRAM_STATE_RESET) - { - switch (CallbackId) - { - case HAL_SDRAM_MSP_INIT_CB_ID : - hsdram->MspInitCallback = pCallback; - break; - case HAL_SDRAM_MSP_DEINIT_CB_ID : - hsdram->MspDeInitCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User SDRAM Callback - * SDRAM Callback is redirected to the weak predefined callback - * @param hsdram : SDRAM handle - * @param CallbackId : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_SDRAM_MSP_INIT_CB_ID SDRAM MspInit callback ID - * @arg @ref HAL_SDRAM_MSP_DEINIT_CB_ID SDRAM MspDeInit callback ID - * @arg @ref HAL_SDRAM_REFRESH_ERR_CB_ID SDRAM Refresh Error callback ID - * @arg @ref HAL_SDRAM_DMA_XFER_CPLT_CB_ID SDRAM DMA Xfer Complete callback ID - * @arg @ref HAL_SDRAM_DMA_XFER_ERR_CB_ID SDRAM DMA Xfer Error callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_SDRAM_UnRegisterCallback(SDRAM_HandleTypeDef *hsdram, HAL_SDRAM_CallbackIDTypeDef CallbackId) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_SDRAM_StateTypeDef state; - - state = hsdram->State; - if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_SDRAM_MSP_INIT_CB_ID : - hsdram->MspInitCallback = HAL_SDRAM_MspInit; - break; - case HAL_SDRAM_MSP_DEINIT_CB_ID : - hsdram->MspDeInitCallback = HAL_SDRAM_MspDeInit; - break; - case HAL_SDRAM_REFRESH_ERR_CB_ID : - hsdram->RefreshErrorCallback = HAL_SDRAM_RefreshErrorCallback; - break; - case HAL_SDRAM_DMA_XFER_CPLT_CB_ID : - hsdram->DmaXferCpltCallback = HAL_SDRAM_DMA_XferCpltCallback; - break; - case HAL_SDRAM_DMA_XFER_ERR_CB_ID : - hsdram->DmaXferErrorCallback = HAL_SDRAM_DMA_XferErrorCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hsdram->State == HAL_SDRAM_STATE_RESET) - { - switch (CallbackId) - { - case HAL_SDRAM_MSP_INIT_CB_ID : - hsdram->MspInitCallback = HAL_SDRAM_MspInit; - break; - case HAL_SDRAM_MSP_DEINIT_CB_ID : - hsdram->MspDeInitCallback = HAL_SDRAM_MspDeInit; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register a User SDRAM Callback for DMA transfers - * To be used to override the weak predefined callback - * @param hsdram : SDRAM handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SDRAM_DMA_XFER_CPLT_CB_ID SDRAM DMA Xfer Complete callback ID - * @arg @ref HAL_SDRAM_DMA_XFER_ERR_CB_ID SDRAM DMA Xfer Error callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_SDRAM_RegisterDmaCallback(SDRAM_HandleTypeDef *hsdram, HAL_SDRAM_CallbackIDTypeDef CallbackId, - pSDRAM_DmaCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_SDRAM_StateTypeDef state; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hsdram); - - state = hsdram->State; - if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_SDRAM_DMA_XFER_CPLT_CB_ID : - hsdram->DmaXferCpltCallback = pCallback; - break; - case HAL_SDRAM_DMA_XFER_ERR_CB_ID : - hsdram->DmaXferErrorCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hsdram); - return status; -} -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup SDRAM_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Enable write protection */ - (void)FMC_SDRAM_WriteProtection_Enable(hsdram->Instance, hsdram->Init.SDBank); - - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_WRITE_PROTECTED; - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Disables dynamically SDRAM write protection. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Disable(SDRAM_HandleTypeDef *hsdram) -{ - HAL_SDRAM_StateTypeDef state = hsdram->State; - - /* Check the SDRAM controller state */ - if (state == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if (state == HAL_SDRAM_STATE_WRITE_PROTECTED) - { - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Disable write protection */ - (void)FMC_SDRAM_WriteProtection_Disable(hsdram->Instance, hsdram->Init.SDBank); - - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_READY; - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Sends Command to the SDRAM bank. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @param Command SDRAM command structure - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SDRAM_SendCommand(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command, - uint32_t Timeout) -{ - HAL_SDRAM_StateTypeDef state = hsdram->State; - - /* Check the SDRAM controller state */ - if (state == HAL_SDRAM_STATE_BUSY) - { - return HAL_BUSY; - } - else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_PRECHARGED)) - { - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Send SDRAM command */ - (void)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; - } - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Programs the SDRAM Memory Refresh rate. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @param RefreshRate The SDRAM refresh rate value - * @retval HAL status - */ -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; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Program the refresh rate */ - (void)FMC_SDRAM_ProgramRefreshRate(hsdram->Instance, RefreshRate); - - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_READY; - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Sets the Number of consecutive SDRAM Memory auto Refresh commands. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @param AutoRefreshNumber The SDRAM auto Refresh number - * @retval HAL status - */ -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; - } - else if (hsdram->State == HAL_SDRAM_STATE_READY) - { - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_BUSY; - - /* Set the Auto-Refresh number */ - (void)FMC_SDRAM_SetAutoRefreshNumber(hsdram->Instance, AutoRefreshNumber); - - /* Update the SDRAM state */ - hsdram->State = HAL_SDRAM_STATE_READY; - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Returns the SDRAM memory current mode. - * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @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_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains - * the configuration information for SDRAM module. - * @retval HAL state - */ -HAL_SDRAM_StateTypeDef HAL_SDRAM_GetState(const SDRAM_HandleTypeDef *hsdram) -{ - return hsdram->State; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup SDRAM_Private_Functions SDRAM Private Functions - * @{ - */ -/** - * @brief DMA SDRAM process complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void SDRAM_DMACplt(DMA_HandleTypeDef *hdma) -{ - SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_READY; - -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) - hsdram->DmaXferCpltCallback(hdma); -#else - HAL_SDRAM_DMA_XferCpltCallback(hdma); -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SRAM process complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void SDRAM_DMACpltProt(DMA_HandleTypeDef *hdma) -{ - SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_WRITE_PROTECTED; - -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) - hsdram->DmaXferCpltCallback(hdma); -#else - HAL_SDRAM_DMA_XferCpltCallback(hdma); -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SDRAM error callback. - * @param hdma : DMA handle - * @retval None - */ -static void SDRAM_DMAError(DMA_HandleTypeDef *hdma) -{ - SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Update the SDRAM controller state */ - hsdram->State = HAL_SDRAM_STATE_ERROR; - -#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) - hsdram->DmaXferErrorCallback(hdma); -#else - HAL_SDRAM_DMA_XferErrorCallback(hdma); -#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ -} - -/** - * @} - */ -/** - * @} - */ - -#endif /* HAL_SDRAM_MODULE_ENABLED */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_sdram.c + * @author MCD Application Team + * @brief SDRAM HAL module driver. + * This file provides a generic firmware to drive SDRAM memories mounted + * as external device. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 hsdram + + (++) 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() + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_SDRAM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_SDRAM_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : SDRAM MspInit. + (+) MspDeInitCallback : SDRAM MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function HAL_SDRAM_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) MspInitCallback : SDRAM MspInit. + (+) MspDeInitCallback : SDRAM MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + + By default, after the HAL_SDRAM_Init and if the state is HAL_SDRAM_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_SDRAM_Init + and HAL_SDRAM_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_SDRAM_Init and HAL_SDRAM_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SDRAM_RegisterCallback before calling HAL_SDRAM_DeInit + or HAL_SDRAM_Init function. + + When The compilation define USE_HAL_SDRAM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_SDRAM_MODULE_ENABLED + +/** @defgroup SDRAM SDRAM + * @brief SDRAM driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup SDRAM_Private_Functions SDRAM Private Functions + * @{ + */ +static void SDRAM_DMACplt(DMA_HandleTypeDef *hdma); +static void SDRAM_DMACpltProt(DMA_HandleTypeDef *hdma); +static void SDRAM_DMAError(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SDRAM_Exported_Functions SDRAM Exported Functions + * @{ + */ + +/** @defgroup SDRAM_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) + { + /* Allocate lock resource and initialize it */ + hsdram->Lock = HAL_UNLOCKED; +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) + if (hsdram->MspInitCallback == NULL) + { + hsdram->MspInitCallback = HAL_SDRAM_MspInit; + } + hsdram->RefreshErrorCallback = HAL_SDRAM_RefreshErrorCallback; + hsdram->DmaXferCpltCallback = HAL_SDRAM_DMA_XferCpltCallback; + hsdram->DmaXferErrorCallback = HAL_SDRAM_DMA_XferErrorCallback; + + /* Init the low level hardware */ + hsdram->MspInitCallback(hsdram); +#else + /* Initialize the low level hardware (MSP) */ + HAL_SDRAM_MspInit(hsdram); +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ + } + + /* Initialize the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Initialize SDRAM control Interface */ + (void)FMC_SDRAM_Init(hsdram->Instance, &(hsdram->Init)); + + /* Initialize SDRAM timing Interface */ + (void)FMC_SDRAM_Timing_Init(hsdram->Instance, Timing, hsdram->Init.SDBank); + + /* Enable FMC Peripheral */ + __FMC_ENABLE(); + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Perform the SDRAM device initialization sequence. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDRAM_DeInit(SDRAM_HandleTypeDef *hsdram) +{ +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) + if (hsdram->MspDeInitCallback == NULL) + { + hsdram->MspDeInitCallback = HAL_SDRAM_MspDeInit; + } + + /* DeInit the low level hardware */ + hsdram->MspDeInitCallback(hsdram); +#else + /* Initialize the low level hardware (MSP) */ + HAL_SDRAM_MspDeInit(hsdram); +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ + + /* Configure the SDRAM registers with their reset values */ + (void)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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval None + */ +__weak void HAL_SDRAM_MspInit(SDRAM_HandleTypeDef *hsdram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval None + */ +__weak void HAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef *hsdram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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 */ +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->RefreshErrorCallback(hsdram); +#else + HAL_SDRAM_RefreshErrorCallback(hsdram); +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ + + /* 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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval None + */ +__weak void HAL_SDRAM_RefreshErrorCallback(SDRAM_HandleTypeDef *hsdram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +__weak void HAL_SDRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + uint32_t size; + __IO uint8_t *pSdramAddress = (uint8_t *)pAddress; + uint8_t *pdestbuff = pDstBuffer; + HAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Read data from source */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *(__IO uint8_t *)pSdramAddress; + pdestbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = state; + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Writes 8-bit data buffer to SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + uint32_t size; + __IO uint8_t *pSdramAddress = (uint8_t *)pAddress; + uint8_t *psrcbuff = pSrcBuffer; + + /* Check the SDRAM controller state */ + if (hsdram->State == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *(__IO uint8_t *)pSdramAddress = *psrcbuff; + psrcbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Reads 16-bit data buffer from the SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *pSdramAddress = pAddress; + uint16_t *pdestbuff = pDstBuffer; + HAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Read data from memory */ + for (size = BufferSize; size >= 2U ; size -= 2U) + { + *pdestbuff = (uint16_t)((*pSdramAddress) & 0x0000FFFFU); + pdestbuff++; + *pdestbuff = (uint16_t)(((*pSdramAddress) & 0xFFFF0000U) >> 16U); + pdestbuff++; + pSdramAddress++; + } + + /* Read last 16-bits if size is not 32-bits multiple */ + if ((BufferSize % 2U) != 0U) + { + *pdestbuff = (uint16_t)((*pSdramAddress) & 0x0000FFFFU); + } + + /* Update the SDRAM controller state */ + hsdram->State = state; + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Writes 16-bit data buffer to SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *psdramaddress = pAddress; + uint16_t *psrcbuff = pSrcBuffer; + + /* Check the SDRAM controller state */ + if (hsdram->State == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size >= 2U ; size -= 2U) + { + *psdramaddress = (uint32_t)(*psrcbuff); + psrcbuff++; + *psdramaddress |= ((uint32_t)(*psrcbuff) << 16U); + psrcbuff++; + psdramaddress++; + } + + /* Write last 16-bits if size is not 32-bits multiple */ + if ((BufferSize % 2U) != 0U) + { + *psdramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psdramaddress) & 0xFFFF0000U); + } + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Reads 32-bit data buffer from the SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *pSdramAddress = (uint32_t *)pAddress; + uint32_t *pdestbuff = pDstBuffer; + HAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Read data from source */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *(__IO uint32_t *)pSdramAddress; + pdestbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = state; + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Writes 32-bit data buffer to SDRAM memory. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *pSdramAddress = pAddress; + uint32_t *psrcbuff = pSrcBuffer; + + /* Check the SDRAM controller state */ + if (hsdram->State == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *pSdramAddress = *psrcbuff; + psrcbuff++; + pSdramAddress++; + } + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Reads a Words data from the SDRAM memory using DMA transfer. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + HAL_StatusTypeDef status; + HAL_SDRAM_StateTypeDef state = hsdram->State; + uint32_t size; + uint32_t data_width; + + /* Check the SDRAM controller state */ + if (state == HAL_SDRAM_STATE_BUSY) + { + status = HAL_BUSY; + } + else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + if (state == HAL_SDRAM_STATE_READY) + { + hsdram->hdma->XferCpltCallback = SDRAM_DMACplt; + } + else + { + hsdram->hdma->XferCpltCallback = SDRAM_DMACpltProt; + } + hsdram->hdma->XferErrorCallback = SDRAM_DMAError; + + if ((hsdram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hsdram->hdma->LinkedListQueue != 0U) && (hsdram->hdma->LinkedListQueue->Head != 0U)) + { + /* Check destination data width and set the size to be transferred */ + data_width = hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + /* Set Source , destination , buffer size */ + /* Set DMA data size */ + hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; + /* Set DMA source address */ + hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pAddress; + /* Set DMA destination address */ + hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pDstBuffer; + + /* Enable the DMA Stream */ + status = HAL_DMAEx_List_Start_IT(hsdram->hdma); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + + status = HAL_ERROR; + } + } + else + { + /* Check destination data width and set the size to be transferred */ + data_width = hsdram->hdma->Init.DestDataWidth; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + + /* Enable the DMA Stream */ + status = HAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, size); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Writes a Words data buffer to SDRAM memory using DMA transfer. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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) +{ + HAL_StatusTypeDef status; + uint32_t size; + uint32_t data_width; + + /* Check the SDRAM controller state */ + if (hsdram->State == HAL_SDRAM_STATE_BUSY) + { + status = HAL_BUSY; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsdram); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + hsdram->hdma->XferCpltCallback = SDRAM_DMACplt; + hsdram->hdma->XferErrorCallback = SDRAM_DMAError; + + if ((hsdram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hsdram->hdma->LinkedListQueue != 0U) && (hsdram->hdma->LinkedListQueue->Head != 0U)) + { + /* Check destination data width and set the size to be transferred */ + data_width = hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + /* Set Source , destination , buffer size */ + /* Set DMA data size */ + hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; + /* Set DMA source address */ + hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pSrcBuffer; + /* Set DMA destination address */ + hsdram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pAddress; + + /* Enable the DMA Stream */ + status = HAL_DMAEx_List_Start_IT(hsdram->hdma); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + + status = HAL_ERROR; + } + } + else + { + /* Check destination data width and set the size to be transferred */ + data_width = hsdram->hdma->Init.DestDataWidth; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + + /* Enable the DMA Stream */ + status = HAL_DMA_Start_IT(hsdram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, size); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsdram); + } + else + { + status = HAL_ERROR; + } + + return status; +} + +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SDRAM Callback + * To be used to override the weak predefined callback + * @param hsdram : SDRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SDRAM_MSP_INIT_CB_ID SDRAM MspInit callback ID + * @arg @ref HAL_SDRAM_MSP_DEINIT_CB_ID SDRAM MspDeInit callback ID + * @arg @ref HAL_SDRAM_REFRESH_ERR_CB_ID SDRAM Refresh Error callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SDRAM_RegisterCallback(SDRAM_HandleTypeDef *hsdram, HAL_SDRAM_CallbackIDTypeDef CallbackId, + pSDRAM_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_SDRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + state = hsdram->State; + if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = pCallback; + break; + case HAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = pCallback; + break; + case HAL_SDRAM_REFRESH_ERR_CB_ID : + hsdram->RefreshErrorCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hsdram->State == HAL_SDRAM_STATE_RESET) + { + switch (CallbackId) + { + case HAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = pCallback; + break; + case HAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User SDRAM Callback + * SDRAM Callback is redirected to the weak predefined callback + * @param hsdram : SDRAM handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_SDRAM_MSP_INIT_CB_ID SDRAM MspInit callback ID + * @arg @ref HAL_SDRAM_MSP_DEINIT_CB_ID SDRAM MspDeInit callback ID + * @arg @ref HAL_SDRAM_REFRESH_ERR_CB_ID SDRAM Refresh Error callback ID + * @arg @ref HAL_SDRAM_DMA_XFER_CPLT_CB_ID SDRAM DMA Xfer Complete callback ID + * @arg @ref HAL_SDRAM_DMA_XFER_ERR_CB_ID SDRAM DMA Xfer Error callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_SDRAM_UnRegisterCallback(SDRAM_HandleTypeDef *hsdram, HAL_SDRAM_CallbackIDTypeDef CallbackId) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_SDRAM_StateTypeDef state; + + state = hsdram->State; + if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = HAL_SDRAM_MspInit; + break; + case HAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = HAL_SDRAM_MspDeInit; + break; + case HAL_SDRAM_REFRESH_ERR_CB_ID : + hsdram->RefreshErrorCallback = HAL_SDRAM_RefreshErrorCallback; + break; + case HAL_SDRAM_DMA_XFER_CPLT_CB_ID : + hsdram->DmaXferCpltCallback = HAL_SDRAM_DMA_XferCpltCallback; + break; + case HAL_SDRAM_DMA_XFER_ERR_CB_ID : + hsdram->DmaXferErrorCallback = HAL_SDRAM_DMA_XferErrorCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hsdram->State == HAL_SDRAM_STATE_RESET) + { + switch (CallbackId) + { + case HAL_SDRAM_MSP_INIT_CB_ID : + hsdram->MspInitCallback = HAL_SDRAM_MspInit; + break; + case HAL_SDRAM_MSP_DEINIT_CB_ID : + hsdram->MspDeInitCallback = HAL_SDRAM_MspDeInit; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register a User SDRAM Callback for DMA transfers + * To be used to override the weak predefined callback + * @param hsdram : SDRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SDRAM_DMA_XFER_CPLT_CB_ID SDRAM DMA Xfer Complete callback ID + * @arg @ref HAL_SDRAM_DMA_XFER_ERR_CB_ID SDRAM DMA Xfer Error callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SDRAM_RegisterDmaCallback(SDRAM_HandleTypeDef *hsdram, HAL_SDRAM_CallbackIDTypeDef CallbackId, + pSDRAM_DmaCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_SDRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hsdram); + + state = hsdram->State; + if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_WRITE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_SDRAM_DMA_XFER_CPLT_CB_ID : + hsdram->DmaXferCpltCallback = pCallback; + break; + case HAL_SDRAM_DMA_XFER_ERR_CB_ID : + hsdram->DmaXferErrorCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hsdram); + return status; +} +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SDRAM_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Enable write protection */ + (void)FMC_SDRAM_WriteProtection_Enable(hsdram->Instance, hsdram->Init.SDBank); + + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_WRITE_PROTECTED; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Disables dynamically SDRAM write protection. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDRAM_WriteProtection_Disable(SDRAM_HandleTypeDef *hsdram) +{ + HAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if (state == HAL_SDRAM_STATE_WRITE_PROTECTED) + { + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Disable write protection */ + (void)FMC_SDRAM_WriteProtection_Disable(hsdram->Instance, hsdram->Init.SDBank); + + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_READY; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Sends Command to the SDRAM bank. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param Command SDRAM command structure + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDRAM_SendCommand(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command, + uint32_t Timeout) +{ + HAL_SDRAM_StateTypeDef state = hsdram->State; + + /* Check the SDRAM controller state */ + if (state == HAL_SDRAM_STATE_BUSY) + { + return HAL_BUSY; + } + else if ((state == HAL_SDRAM_STATE_READY) || (state == HAL_SDRAM_STATE_PRECHARGED)) + { + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Send SDRAM command */ + (void)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; + } + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Programs the SDRAM Memory Refresh rate. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param RefreshRate The SDRAM refresh rate value + * @retval HAL status + */ +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; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Program the refresh rate */ + (void)FMC_SDRAM_ProgramRefreshRate(hsdram->Instance, RefreshRate); + + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_READY; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Sets the Number of consecutive SDRAM Memory auto Refresh commands. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @param AutoRefreshNumber The SDRAM auto Refresh number + * @retval HAL status + */ +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; + } + else if (hsdram->State == HAL_SDRAM_STATE_READY) + { + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_BUSY; + + /* Set the Auto-Refresh number */ + (void)FMC_SDRAM_SetAutoRefreshNumber(hsdram->Instance, AutoRefreshNumber); + + /* Update the SDRAM state */ + hsdram->State = HAL_SDRAM_STATE_READY; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Returns the SDRAM memory current mode. + * @param hsdram pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @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_Exported_Functions_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 pointer to a SDRAM_HandleTypeDef structure that contains + * the configuration information for SDRAM module. + * @retval HAL state + */ +HAL_SDRAM_StateTypeDef HAL_SDRAM_GetState(const SDRAM_HandleTypeDef *hsdram) +{ + return hsdram->State; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SDRAM_Private_Functions SDRAM Private Functions + * @{ + */ +/** + * @brief DMA SDRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SDRAM_DMACplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_READY; + +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->DmaXferCpltCallback(hdma); +#else + HAL_SDRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SDRAM_DMACpltProt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_WRITE_PROTECTED; + +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->DmaXferCpltCallback(hdma); +#else + HAL_SDRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SDRAM error callback. + * @param hdma : DMA handle + * @retval None + */ +static void SDRAM_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + SDRAM_HandleTypeDef *hsdram = (SDRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Update the SDRAM controller state */ + hsdram->State = HAL_SDRAM_STATE_ERROR; + +#if (USE_HAL_SDRAM_REGISTER_CALLBACKS == 1) + hsdram->DmaXferErrorCallback(hdma); +#else + HAL_SDRAM_DMA_XferErrorCallback(hdma); +#endif /* USE_HAL_SDRAM_REGISTER_CALLBACKS */ +} + +/** + * @} + */ +/** + * @} + */ + +#endif /* HAL_SDRAM_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard.c index 00f8d575f..31f31b7a4 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard.c @@ -1,3286 +1,3285 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_smartcard.c - * @author MCD Application Team - * @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 Control functions - * + Peripheral State and Error functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The SMARTCARD HAL driver can be used as follows: - - (#) Declare a SMARTCARD_HandleTypeDef handle structure (eg. SMARTCARD_HandleTypeDef hsmartcard). - (#) Associate a USART to the SMARTCARD handle hsmartcard. - (#) Initialize the SMARTCARD low level resources by implementing the HAL_SMARTCARD_MspInit() API: - (++) Enable the USARTx interface clock. - (++) USART pins configuration: - (+++) Enable the clock for the USART GPIOs. - (+++) Configure the USART pins (TX as alternate function pull-up, RX as alternate function Input). - (++) 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. - (++) 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 channel. - (+++) Enable the DMAx interface clock. - (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. - (+++) Configure the DMA Tx/Rx channel. - (+++) Associate the initialized 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 channel. - - (#) Program the Baud Rate, Parity, Mode(Receiver/Transmitter), clock enabling/disabling and accordingly, - the clock parameters (parity, phase, last bit), prescaler value, guard time and NACK on transmission - error enabling or disabling in the hsmartcard handle Init structure. - - (#) If required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, auto-retry counter,...) - in the hsmartcard handle AdvancedInit structure. - - (#) Initialize the SMARTCARD registers by calling the HAL_SMARTCARD_Init() API: - (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_SMARTCARD_MspInit() API. - [..] - (@) The specific SMARTCARD interrupts (Transmission complete interrupt, - RXNE interrupt and Error Interrupts) will be managed using the macros - __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. - - [..] - [..] Three operation modes 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_GET_FLAG : Check whether or not the specified SMARTCARD flag is set - (+) __HAL_SMARTCARD_CLEAR_FLAG : Clear the specified SMARTCARD pending flag - (+) __HAL_SMARTCARD_ENABLE_IT: Enable the specified SMARTCARD interrupt - (+) __HAL_SMARTCARD_DISABLE_IT: Disable the specified SMARTCARD interrupt - (+) __HAL_SMARTCARD_GET_IT_SOURCE: Check whether or not the specified SMARTCARD interrupt is enabled - - [..] - (@) You can refer to the SMARTCARD HAL driver header file for more useful macros - - ##### Callback registration ##### - ================================== - - [..] - The compilation define USE_HAL_SMARTCARD_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - [..] - Use Function HAL_SMARTCARD_RegisterCallback() to register a user callback. - Function HAL_SMARTCARD_RegisterCallback() allows to register following callbacks: - (+) TxCpltCallback : Tx Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. - (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. - (+) RxFifoFullCallback : Rx Fifo Full Callback. - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) MspInitCallback : SMARTCARD MspInit. - (+) MspDeInitCallback : SMARTCARD MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_SMARTCARD_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_SMARTCARD_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxCpltCallback : Tx Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. - (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. - (+) RxFifoFullCallback : Rx Fifo Full Callback. - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) MspInitCallback : SMARTCARD MspInit. - (+) MspDeInitCallback : SMARTCARD MspDeInit. - - [..] - By default, after the HAL_SMARTCARD_Init() and when the state is HAL_SMARTCARD_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are respectively - reset to the legacy weak functions in the HAL_SMARTCARD_Init() - and HAL_SMARTCARD_DeInit() only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_SMARTCARD_Init() and HAL_SMARTCARD_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in HAL_SMARTCARD_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_SMARTCARD_STATE_READY or HAL_SMARTCARD_STATE_RESET state, thus registered (user) - MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_SMARTCARD_RegisterCallback() before calling HAL_SMARTCARD_DeInit() - or HAL_SMARTCARD_Init() function. - - [..] - When The compilation define USE_HAL_SMARTCARD_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available - and weak callbacks are used. - - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SMARTCARD SMARTCARD - * @brief HAL SMARTCARD module driver - * @{ - */ - -#ifdef HAL_SMARTCARD_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants - * @{ - */ -#define SMARTCARD_TEACK_REACK_TIMEOUT 1000U /*!< SMARTCARD TX or RX enable acknowledge time-out value */ - -#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \ - USART_CR1_RE | USART_CR1_OVER8| \ - USART_CR1_FIFOEN)) /*!< USART CR1 fields of parameters set by SMARTCARD_SetConfig API */ - -#define USART_CR2_CLK_FIELDS ((uint32_t)(USART_CR2_CLKEN | USART_CR2_CPOL | \ - USART_CR2_CPHA | USART_CR2_LBCL)) /*!< SMARTCARD clock-related USART CR2 fields of parameters */ - -#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_RTOEN | USART_CR2_CLK_FIELDS | \ - USART_CR2_STOP)) /*!< USART CR2 fields of parameters set by SMARTCARD_SetConfig API */ - -#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_ONEBIT | USART_CR3_NACK | USART_CR3_SCARCNT | \ - USART_CR3_TXFTCFG | USART_CR3_RXFTCFG )) /*!< USART CR3 fields of parameters set by SMARTCARD_SetConfig API */ - -#define USART_BRR_MIN 0x10U /*!< USART BRR minimum authorized value */ - -#define USART_BRR_MAX 0x0000FFFFU /*!< USART BRR maximum authorized value */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SMARTCARD_Private_Functions - * @{ - */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) -void SMARTCARD_InitCallbacksToDefault(SMARTCARD_HandleTypeDef *hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ -static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard); -static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard); -static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard); -static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, - FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); -static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsmartcard); -static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsmartcard); -#if defined(HAL_DMA_MODULE_ENABLED) -static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -#endif /* HAL_DMA_MODULE_ENABLED */ -static void SMARTCARD_TxISR(SMARTCARD_HandleTypeDef *hsmartcard); -static void SMARTCARD_TxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard); -static void SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard); -static void SMARTCARD_RxISR(SMARTCARD_HandleTypeDef *hsmartcard); -static void SMARTCARD_RxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions - * @{ - */ - -/** @defgroup SMARTCARD_Exported_Functions_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 - associated to the SmartCard. - (+) These parameters can be configured: - (++) Baud Rate - (++) Parity: parity should be enabled, frame Length is fixed to 8 bits plus parity - (++) Receiver/transmitter modes - (++) Synchronous mode (and if enabled, phase, polarity and last bit parameters) - (++) Prescaler value - (++) Guard bit time - (++) NACK enabling or disabling on transmission error - - (+) The following advanced features can be configured as well: - (++) TX and/or RX pin level inversion - (++) data logical level inversion - (++) RX and TX pins swap - (++) RX overrun detection disabling - (++) DMA disabling on RX error - (++) MSB first on communication line - (++) Time out enabling (and if activated, timeout value) - (++) Block length - (++) Auto-retry counter - [..] - The HAL_SMARTCARD_Init() API follows the USART synchronous configuration procedures - (details for the procedures are available in reference manual). - -@endverbatim - - The USART frame format is given in the following table: - - Table 1. USART frame format. - +---------------------------------------------------------------+ - | M1M0 bits | PCE bit | USART frame | - |-----------------------|---------------------------------------| - | 01 | 1 | | SB | 8 bit data | PB | STB | | - +---------------------------------------------------------------+ - - - * @{ - */ - -/** - * @brief Initialize the SMARTCARD mode according to the specified - * parameters in the SMARTCARD_HandleTypeDef and initialize the associated handle. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Check the SMARTCARD handle allocation */ - if (hsmartcard == NULL) - { - return HAL_ERROR; - } - - /* Check the USART associated to the SMARTCARD handle */ - assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); - - if (hsmartcard->gState == HAL_SMARTCARD_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hsmartcard->Lock = HAL_UNLOCKED; - -#if USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1 - SMARTCARD_InitCallbacksToDefault(hsmartcard); - - if (hsmartcard->MspInitCallback == NULL) - { - hsmartcard->MspInitCallback = HAL_SMARTCARD_MspInit; - } - - /* Init the low level hardware */ - hsmartcard->MspInitCallback(hsmartcard); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_SMARTCARD_MspInit(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ - } - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Disable the Peripheral to set smartcard mode */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* In SmartCard mode, the following bits must be kept cleared: - - LINEN in the USART_CR2 register, - - HDSEL and IREN bits in the USART_CR3 register.*/ - CLEAR_BIT(hsmartcard->Instance->CR2, USART_CR2_LINEN); - CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_HDSEL | USART_CR3_IREN)); - - /* set the USART in SMARTCARD mode */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_SCEN); - - /* Set the SMARTCARD Communication parameters */ - if (SMARTCARD_SetConfig(hsmartcard) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* Set the SMARTCARD transmission completion indication */ - SMARTCARD_TRANSMISSION_COMPLETION_SETTING(hsmartcard); - - if (hsmartcard->AdvancedInit.AdvFeatureInit != SMARTCARD_ADVFEATURE_NO_INIT) - { - SMARTCARD_AdvFeatureConfig(hsmartcard); - } - - /* Enable the Peripheral */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* TEACK and/or REACK to check before moving hsmartcard->gState and hsmartcard->RxState to Ready */ - return (SMARTCARD_CheckIdleState(hsmartcard)); -} - -/** - * @brief DeInitialize the SMARTCARD peripheral. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Check the SMARTCARD handle allocation */ - if (hsmartcard == NULL) - { - return HAL_ERROR; - } - - /* Check the USART/UART associated to the SMARTCARD handle */ - assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Disable the Peripheral */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - WRITE_REG(hsmartcard->Instance->CR1, 0x0U); - WRITE_REG(hsmartcard->Instance->CR2, 0x0U); - WRITE_REG(hsmartcard->Instance->CR3, 0x0U); - WRITE_REG(hsmartcard->Instance->RTOR, 0x0U); - WRITE_REG(hsmartcard->Instance->GTPR, 0x0U); - - /* DeInit the low level hardware */ -#if USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1 - if (hsmartcard->MspDeInitCallback == NULL) - { - hsmartcard->MspDeInitCallback = HAL_SMARTCARD_MspDeInit; - } - /* DeInit the low level hardware */ - hsmartcard->MspDeInitCallback(hsmartcard); -#else - HAL_SMARTCARD_MspDeInit(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->gState = HAL_SMARTCARD_STATE_RESET; - hsmartcard->RxState = HAL_SMARTCARD_STATE_RESET; - - /* Process Unlock */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; -} - -/** - * @brief Initialize the SMARTCARD MSP. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_MspInit can be implemented in the user file - */ -} - -/** - * @brief DeInitialize the SMARTCARD MSP. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User SMARTCARD Callback - * To be used to override the weak predefined callback - * @note The HAL_SMARTCARD_RegisterCallback() may be called before HAL_SMARTCARD_Init() - * in HAL_SMARTCARD_STATE_RESET to register callbacks for HAL_SMARTCARD_MSPINIT_CB_ID - * and HAL_SMARTCARD_MSPDEINIT_CB_ID - * @param hsmartcard smartcard handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SMARTCARD_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_SMARTCARD_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_SMARTCARD_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_SMARTCARD_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID - * @arg @ref HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID - * @arg @ref HAL_SMARTCARD_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID - * @arg @ref HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID - * @arg @ref HAL_SMARTCARD_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_SMARTCARD_MSPDEINIT_CB_ID MspDeInit Callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_RegisterCallback(SMARTCARD_HandleTypeDef *hsmartcard, - HAL_SMARTCARD_CallbackIDTypeDef CallbackID, - pSMARTCARD_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - switch (CallbackID) - { - - case HAL_SMARTCARD_TX_COMPLETE_CB_ID : - hsmartcard->TxCpltCallback = pCallback; - break; - - case HAL_SMARTCARD_RX_COMPLETE_CB_ID : - hsmartcard->RxCpltCallback = pCallback; - break; - - case HAL_SMARTCARD_ERROR_CB_ID : - hsmartcard->ErrorCallback = pCallback; - break; - - case HAL_SMARTCARD_ABORT_COMPLETE_CB_ID : - hsmartcard->AbortCpltCallback = pCallback; - break; - - case HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID : - hsmartcard->AbortTransmitCpltCallback = pCallback; - break; - - case HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID : - hsmartcard->AbortReceiveCpltCallback = pCallback; - break; - - case HAL_SMARTCARD_RX_FIFO_FULL_CB_ID : - hsmartcard->RxFifoFullCallback = pCallback; - break; - - case HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID : - hsmartcard->TxFifoEmptyCallback = pCallback; - break; - - case HAL_SMARTCARD_MSPINIT_CB_ID : - hsmartcard->MspInitCallback = pCallback; - break; - - case HAL_SMARTCARD_MSPDEINIT_CB_ID : - hsmartcard->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (hsmartcard->gState == HAL_SMARTCARD_STATE_RESET) - { - switch (CallbackID) - { - case HAL_SMARTCARD_MSPINIT_CB_ID : - hsmartcard->MspInitCallback = pCallback; - break; - - case HAL_SMARTCARD_MSPDEINIT_CB_ID : - hsmartcard->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an SMARTCARD callback - * SMARTCARD callback is redirected to the weak predefined callback - * @note The HAL_SMARTCARD_UnRegisterCallback() may be called before HAL_SMARTCARD_Init() - * in HAL_SMARTCARD_STATE_RESET to un-register callbacks for HAL_SMARTCARD_MSPINIT_CB_ID - * and HAL_SMARTCARD_MSPDEINIT_CB_ID - * @param hsmartcard smartcard handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_SMARTCARD_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_SMARTCARD_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_SMARTCARD_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_SMARTCARD_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID - * @arg @ref HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID - * @arg @ref HAL_SMARTCARD_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID - * @arg @ref HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID - * @arg @ref HAL_SMARTCARD_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_SMARTCARD_MSPDEINIT_CB_ID MspDeInit Callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_UnRegisterCallback(SMARTCARD_HandleTypeDef *hsmartcard, - HAL_SMARTCARD_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_SMARTCARD_STATE_READY == hsmartcard->gState) - { - switch (CallbackID) - { - case HAL_SMARTCARD_TX_COMPLETE_CB_ID : - hsmartcard->TxCpltCallback = HAL_SMARTCARD_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_SMARTCARD_RX_COMPLETE_CB_ID : - hsmartcard->RxCpltCallback = HAL_SMARTCARD_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_SMARTCARD_ERROR_CB_ID : - hsmartcard->ErrorCallback = HAL_SMARTCARD_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_SMARTCARD_ABORT_COMPLETE_CB_ID : - hsmartcard->AbortCpltCallback = HAL_SMARTCARD_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID : - hsmartcard->AbortTransmitCpltCallback = HAL_SMARTCARD_AbortTransmitCpltCallback; /* Legacy weak - AbortTransmitCpltCallback*/ - break; - - case HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID : - hsmartcard->AbortReceiveCpltCallback = HAL_SMARTCARD_AbortReceiveCpltCallback; /* Legacy weak - AbortReceiveCpltCallback */ - break; - - case HAL_SMARTCARD_RX_FIFO_FULL_CB_ID : - hsmartcard->RxFifoFullCallback = HAL_SMARTCARDEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ - break; - - case HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID : - hsmartcard->TxFifoEmptyCallback = HAL_SMARTCARDEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ - break; - - case HAL_SMARTCARD_MSPINIT_CB_ID : - hsmartcard->MspInitCallback = HAL_SMARTCARD_MspInit; /* Legacy weak MspInitCallback */ - break; - - case HAL_SMARTCARD_MSPDEINIT_CB_ID : - hsmartcard->MspDeInitCallback = HAL_SMARTCARD_MspDeInit; /* Legacy weak MspDeInitCallback */ - break; - - default : - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SMARTCARD_STATE_RESET == hsmartcard->gState) - { - switch (CallbackID) - { - case HAL_SMARTCARD_MSPINIT_CB_ID : - hsmartcard->MspInitCallback = HAL_SMARTCARD_MspInit; - break; - - case HAL_SMARTCARD_MSPDEINIT_CB_ID : - hsmartcard->MspDeInitCallback = HAL_SMARTCARD_MspDeInit; - break; - - default : - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup SMARTCARD_Exported_Functions_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. - - [..] - Smartcard is a single wire half duplex communication protocol. - The Smartcard interface is designed to support asynchronous protocol Smartcards as - defined in the ISO 7816-3 standard. The USART should be configured as: - (+) 8 bits plus parity: where M=1 and PCE=1 in the USART_CR1 register - (+) 1.5 stop bits when transmitting and receiving: where STOP=11 in the USART_CR2 register. - - [..] - (#) 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, the relevant 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 respectively 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 APIs are : - (##) HAL_SMARTCARD_Transmit() - (##) HAL_SMARTCARD_Receive() - - (#) Non Blocking mode APIs with Interrupt are : - (##) HAL_SMARTCARD_Transmit_IT() - (##) HAL_SMARTCARD_Receive_IT() - (##) HAL_SMARTCARD_IRQHandler() - - (#) Non Blocking mode functions with DMA are : - (##) HAL_SMARTCARD_Transmit_DMA() - (##) HAL_SMARTCARD_Receive_DMA() - - (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (##) HAL_SMARTCARD_TxCpltCallback() - (##) HAL_SMARTCARD_RxCpltCallback() - (##) HAL_SMARTCARD_ErrorCallback() - - [..] - (#) Non-Blocking mode transfers could be aborted using Abort API's : - (##) HAL_SMARTCARD_Abort() - (##) HAL_SMARTCARD_AbortTransmit() - (##) HAL_SMARTCARD_AbortReceive() - (##) HAL_SMARTCARD_Abort_IT() - (##) HAL_SMARTCARD_AbortTransmit_IT() - (##) HAL_SMARTCARD_AbortReceive_IT() - - (#) For Abort services based on interrupts (HAL_SMARTCARD_Abortxxx_IT), - a set of Abort Complete Callbacks are provided: - (##) HAL_SMARTCARD_AbortCpltCallback() - (##) HAL_SMARTCARD_AbortTransmitCpltCallback() - (##) HAL_SMARTCARD_AbortReceiveCpltCallback() - - (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. - Errors are handled as follows : - (##) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is - to be evaluated by user : this concerns Frame Error, - Parity Error or Noise Error in Interrupt mode reception . - Received character is then retrieved and stored in Rx buffer, - Error code is set to allow user to identify error type, - and HAL_SMARTCARD_ErrorCallback() user callback is executed. Transfer is kept ongoing on SMARTCARD side. - If user wants to abort it, Abort services should be called by user. - (##) Error is considered as Blocking : Transfer could not be completed properly and is aborted. - This concerns Frame Error in Interrupt mode transmission, Overrun Error in Interrupt - mode reception and all errors in DMA mode. - Error code is set to allow user to identify error type, - and HAL_SMARTCARD_ErrorCallback() user callback is executed. - -@endverbatim - * @{ - */ - -/** - * @brief Send an amount of data in blocking mode. - * @note When FIFO mode is enabled, writing a data in the TDR register adds one - * data to the TXFIFO. Write operations to the TDR register are performed - * when TXFNF flag is set. From hardware perspective, TXFNF flag and - * TXE are mapped on the same bit-field. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @param pData pointer to data buffer. - * @param Size amount of data to be sent. - * @param Timeout Timeout duration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsmartcard, const uint8_t *pData, uint16_t Size, - uint32_t Timeout) -{ - uint32_t tickstart; - const uint8_t *ptmpdata = pData; - - /* Check that a Tx process is not already ongoing */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - if ((ptmpdata == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY_TX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Disable the Peripheral first to update mode for TX master */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* In case of TX only mode, if NACK is enabled, the USART must be able to monitor - the bidirectional line to detect a NACK signal in case of parity error. - Therefore, the receiver block must be enabled as well (RE bit must be set). */ - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) - && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); - } - /* Enable Tx */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TE); - - /* Enable the Peripheral */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* Perform a TX/RX FIFO Flush */ - __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->TxXferSize = Size; - hsmartcard->TxXferCount = Size; - - while (hsmartcard->TxXferCount > 0U) - { - hsmartcard->TxXferCount--; - if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - hsmartcard->Instance->TDR = (uint8_t)(*ptmpdata & 0xFFU); - ptmpdata++; - } - if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_TRANSMISSION_COMPLETION_FLAG(hsmartcard), RESET, - tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Disable the Peripheral first to update mode */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) - && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - /* In case of TX only mode, if NACK is enabled, receiver block has been enabled - for Transmit phase. Disable this receiver block. */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); - } - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX_RX) - || (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - /* Perform a TX FIFO Flush at end of Tx phase, as all sent bytes are appearing in Rx Data register */ - __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); - } - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* At end of Tx process, restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in blocking mode. - * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO - * is not empty. Read operations from the RDR register are performed when - * RXFNE flag is set. From hardware perspective, RXFNE flag and - * RXNE are mapped on the same bit-field. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @param pData pointer to data buffer. - * @param Size amount of data to be received. - * @param Timeout Timeout duration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, - uint32_t Timeout) -{ - uint32_t tickstart; - uint8_t *ptmpdata = pData; - - /* Check that a Rx process is not already ongoing */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) - { - if ((ptmpdata == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->RxState = HAL_SMARTCARD_STATE_BUSY_RX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - hsmartcard->RxXferSize = Size; - hsmartcard->RxXferCount = Size; - - /* Check the remain data to be received */ - while (hsmartcard->RxXferCount > 0U) - { - hsmartcard->RxXferCount--; - - if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - *ptmpdata = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0x00FF); - ptmpdata++; - } - - /* At end of Rx process, restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Send an amount of data in interrupt mode. - * @note When FIFO mode is disabled, USART interrupt is generated whenever - * USART_TDR register is empty, i.e one interrupt per data to transmit. - * @note When FIFO mode is enabled, USART interrupt is generated whenever - * TXFIFO threshold reached. In that case the interrupt rate depends on - * TXFIFO threshold configuration. - * @note This function sets the hsmartcard->TxIsr function pointer according to - * the FIFO mode (data transmission processing depends on FIFO mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @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 *hsmartcard, const uint8_t *pData, uint16_t Size) -{ - /* Check that a Tx process is not already ongoing */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY_TX; - - hsmartcard->pTxBuffPtr = pData; - hsmartcard->TxXferSize = Size; - hsmartcard->TxXferCount = Size; - hsmartcard->TxISR = NULL; - - /* Disable the Peripheral first to update mode for TX master */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* In case of TX only mode, if NACK is enabled, the USART must be able to monitor - the bidirectional line to detect a NACK signal in case of parity error. - Therefore, the receiver block must be enabled as well (RE bit must be set). */ - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) - && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); - } - /* Enable Tx */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TE); - - /* Enable the Peripheral */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* Perform a TX/RX FIFO Flush */ - __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); - - /* Configure Tx interrupt processing */ - if (hsmartcard->FifoMode == SMARTCARD_FIFOMODE_ENABLE) - { - /* Set the Tx ISR function pointer */ - hsmartcard->TxISR = SMARTCARD_TxISR_FIFOEN; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Enable the SMARTCARD Error Interrupt: (Frame error) */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* Enable the TX FIFO threshold interrupt */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTIE); - } - else - { - /* Set the Tx ISR function pointer */ - hsmartcard->TxISR = SMARTCARD_TxISR; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Enable the SMARTCARD Error Interrupt: (Frame error) */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* Enable the SMARTCARD Transmit Data Register Empty Interrupt */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in interrupt mode. - * @note When FIFO mode is disabled, USART interrupt is generated whenever - * USART_RDR register can be read, i.e one interrupt per data to receive. - * @note When FIFO mode is enabled, USART interrupt is generated whenever - * RXFIFO threshold reached. In that case the interrupt rate depends on - * RXFIFO threshold configuration. - * @note This function sets the hsmartcard->RxIsr function pointer according to - * the FIFO mode (data reception processing depends on FIFO mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @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 *hsmartcard, uint8_t *pData, uint16_t Size) -{ - /* Check that a Rx process is not already ongoing */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->RxState = HAL_SMARTCARD_STATE_BUSY_RX; - - hsmartcard->pRxBuffPtr = pData; - hsmartcard->RxXferSize = Size; - hsmartcard->RxXferCount = Size; - - /* Configure Rx interrupt processing */ - if ((hsmartcard->FifoMode == SMARTCARD_FIFOMODE_ENABLE) && (Size >= hsmartcard->NbRxDataToProcess)) - { - /* Set the Rx ISR function pointer */ - hsmartcard->RxISR = SMARTCARD_RxISR_FIFOEN; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Enable the SMARTCART Parity Error interrupt and RX FIFO Threshold interrupt */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_RXFTIE); - } - else - { - /* Set the Rx ISR function pointer */ - hsmartcard->RxISR = SMARTCARD_RxISR; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Enable the SMARTCARD Parity Error and Data Register not empty Interrupts */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); - } - - /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Send an amount of data in DMA mode. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @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 *hsmartcard, const uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - - /* Check that a Tx process is not already ongoing */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY_TX; - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->pTxBuffPtr = pData; - hsmartcard->TxXferSize = Size; - hsmartcard->TxXferCount = Size; - - /* Disable the Peripheral first to update mode for TX master */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* In case of TX only mode, if NACK is enabled, the USART must be able to monitor - the bidirectional line to detect a NACK signal in case of parity error. - Therefore, the receiver block must be enabled as well (RE bit must be set). */ - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) - && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); - } - /* Enable Tx */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TE); - - /* Enable the Peripheral */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* Perform a TX/RX FIFO Flush */ - __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); - - /* Set the SMARTCARD DMA transfer complete callback */ - hsmartcard->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt; - - /* Set the SMARTCARD error callback */ - hsmartcard->hdmatx->XferErrorCallback = SMARTCARD_DMAError; - - /* Set the DMA abort callback */ - hsmartcard->hdmatx->XferAbortCallback = NULL; - - /* Check linked list mode */ - if ((hsmartcard->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hsmartcard->hdmatx->LinkedListQueue != NULL) && (hsmartcard->hdmatx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - hsmartcard->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = Size; - - /* Set DMA source address */ - hsmartcard->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)hsmartcard->pTxBuffPtr; - - /* Set DMA destination address */ - hsmartcard->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&hsmartcard->Instance->TDR; - - /* Enable the SMARTCARD transmit DMA channel */ - status = HAL_DMAEx_List_Start_IT(hsmartcard->hdmatx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the SMARTCARD transmit DMA channel */ - status = HAL_DMA_Start_IT(hsmartcard->hdmatx, (uint32_t)hsmartcard->pTxBuffPtr, - (uint32_t)&hsmartcard->Instance->TDR, Size); - } - - if (status == HAL_OK) - { - /* Clear the TC flag in the ICR register */ - CLEAR_BIT(hsmartcard->Instance->ICR, USART_ICR_TCCF); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Enable the UART Error Interrupt: (Frame error) */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the SMARTCARD associated USART CR3 register */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - return HAL_OK; - } - else - { - /* Set error code to DMA */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Restore hsmartcard->State to ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in DMA mode. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @param pData pointer to data buffer. - * @param Size amount of data to be received. - * @note The SMARTCARD-associated USART parity is enabled (PCE = 1), - * the received data contain the parity bit (MSB position). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - - /* Check that a Rx process is not already ongoing */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsmartcard->RxState = HAL_SMARTCARD_STATE_BUSY_RX; - - hsmartcard->pRxBuffPtr = pData; - hsmartcard->RxXferSize = Size; - - /* Set the SMARTCARD DMA transfer complete callback */ - hsmartcard->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt; - - /* Set the SMARTCARD DMA error callback */ - hsmartcard->hdmarx->XferErrorCallback = SMARTCARD_DMAError; - - /* Set the DMA abort callback */ - hsmartcard->hdmarx->XferAbortCallback = NULL; - - /* Check linked list mode */ - if ((hsmartcard->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hsmartcard->hdmarx->LinkedListQueue != NULL) && (hsmartcard->hdmarx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - hsmartcard->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = Size; - - /* Set DMA source address */ - hsmartcard->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)&hsmartcard->Instance->RDR; - - /* Set DMA destination address */ - hsmartcard->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)hsmartcard->pRxBuffPtr; - - /* Enable the SMARTCARD receive DMA channel */ - status = HAL_DMAEx_List_Start_IT(hsmartcard->hdmarx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the DMA channel */ - status = HAL_DMA_Start_IT(hsmartcard->hdmarx, (uint32_t)&hsmartcard->Instance->RDR, - (uint32_t)hsmartcard->pRxBuffPtr, Size); - } - - if (status == HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Enable the SMARTCARD Parity Error Interrupt */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); - - /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the SMARTCARD associated USART CR3 register */ - SET_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - return HAL_OK; - } - else - { - /* Set error code to DMA */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - /* Restore hsmartcard->State to ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Abort ongoing transfers (blocking mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SMARTCARD Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable RTOIE, EOBIE, TXEIE, TCIE, RXNE, PE, RXFT, TXFT and - ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, - (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE | USART_CR1_RTOIE | - USART_CR1_EOBIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (hsmartcard->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsmartcard->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hsmartcard->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hsmartcard->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - - /* Disable the SMARTCARD DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (hsmartcard->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsmartcard->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hsmartcard->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hsmartcard->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx and Rx transfer counters */ - hsmartcard->TxXferCount = 0U; - hsmartcard->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | - SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* Reset Handle ErrorCode to No Error */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (blocking mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SMARTCARD Interrupts (Tx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable TCIE, TXEIE and TXFTIE interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTIE); - - /* Check if a receive process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (hsmartcard->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsmartcard->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hsmartcard->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hsmartcard->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx transfer counter */ - hsmartcard->TxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, SMARTCARD_CLEAR_FEF); - - /* Restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (blocking mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SMARTCARD Interrupts (Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable RTOIE, EOBIE, RXNE, PE, RXFT, TXFT and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE | - USART_CR1_EOBIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Check if a Transmit process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (hsmartcard->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsmartcard->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(hsmartcard->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hsmartcard->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Rx transfer counter */ - hsmartcard->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | - SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (Interrupt mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SMARTCARD Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint32_t abortcplt = 1U; - - /* Disable RTOIE, EOBIE, TXEIE, TCIE, RXNE, PE, RXFT, TXFT and - ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, - (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE | USART_CR1_RTOIE | - USART_CR1_EOBIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* If DMA Tx and/or DMA Rx Handles are associated to SMARTCARD Handle, - DMA Abort complete callbacks should be initialised before any call - to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if (hsmartcard->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if SMARTCARD DMA Tx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - hsmartcard->hdmatx->XferAbortCallback = SMARTCARD_DMATxAbortCallback; - } - else - { - hsmartcard->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if (hsmartcard->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if SMARTCARD DMA Rx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - hsmartcard->hdmarx->XferAbortCallback = SMARTCARD_DMARxAbortCallback; - } - else - { - hsmartcard->hdmarx->XferAbortCallback = NULL; - } - } - - /* Disable the SMARTCARD DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at UART level */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (hsmartcard->hdmatx != NULL) - { - /* SMARTCARD Tx DMA Abort callback has already been initialised : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hsmartcard->hdmatx) != HAL_OK) - { - hsmartcard->hdmatx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } - } - } - - /* Disable the SMARTCARD DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (hsmartcard->hdmarx != NULL) - { - /* SMARTCARD Rx DMA Abort callback has already been initialised : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hsmartcard->hdmarx) != HAL_OK) - { - hsmartcard->hdmarx->XferAbortCallback = NULL; - abortcplt = 1U; - } - else - { - abortcplt = 0U; - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if (abortcplt == 1U) - { - /* Reset Tx and Rx transfer counters */ - hsmartcard->TxXferCount = 0U; - hsmartcard->RxXferCount = 0U; - - /* Clear ISR function pointers */ - hsmartcard->RxISR = NULL; - hsmartcard->TxISR = NULL; - - /* Reset errorCode */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | - SMARTCARD_CLEAR_FEF | SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - hsmartcard->AbortCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort complete callback */ - HAL_SMARTCARD_AbortCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (Interrupt mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SMARTCARD Interrupts (Tx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable TCIE, TXEIE and TXFTIE interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTIE); - - /* Check if a receive process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (hsmartcard->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - hsmartcard->hdmatx->XferAbortCallback = SMARTCARD_DMATxOnlyAbortCallback; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hsmartcard->hdmatx) != HAL_OK) - { - /* Call Directly hsmartcard->hdmatx->XferAbortCallback function in case of error */ - hsmartcard->hdmatx->XferAbortCallback(hsmartcard->hdmatx); - } - } - else - { - /* Reset Tx transfer counter */ - hsmartcard->TxXferCount = 0U; - - /* Clear TxISR function pointers */ - hsmartcard->TxISR = NULL; - - /* Restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - hsmartcard->AbortTransmitCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_SMARTCARD_AbortTransmitCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Reset Tx transfer counter */ - hsmartcard->TxXferCount = 0U; - - /* Clear TxISR function pointers */ - hsmartcard->TxISR = NULL; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, SMARTCARD_CLEAR_FEF); - - /* Restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - hsmartcard->AbortTransmitCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_SMARTCARD_AbortTransmitCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (Interrupt mode). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SMARTCARD Interrupts (Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable RTOIE, EOBIE, RXNE, PE, RXFT and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE | - USART_CR1_EOBIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Check if a Transmit process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (hsmartcard->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - hsmartcard->hdmarx->XferAbortCallback = SMARTCARD_DMARxOnlyAbortCallback; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hsmartcard->hdmarx) != HAL_OK) - { - /* Call Directly hsmartcard->hdmarx->XferAbortCallback function in case of error */ - hsmartcard->hdmarx->XferAbortCallback(hsmartcard->hdmarx); - } - } - else - { - /* Reset Rx transfer counter */ - hsmartcard->RxXferCount = 0U; - - /* Clear RxISR function pointer */ - hsmartcard->RxISR = NULL; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | - SMARTCARD_CLEAR_FEF | SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - hsmartcard->AbortReceiveCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_SMARTCARD_AbortReceiveCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Reset Rx transfer counter */ - hsmartcard->RxXferCount = 0U; - - /* Clear RxISR function pointer */ - hsmartcard->RxISR = NULL; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | - SMARTCARD_CLEAR_FEF | SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - hsmartcard->AbortReceiveCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_SMARTCARD_AbortReceiveCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - - return HAL_OK; -} - -/** - * @brief Handle SMARTCARD interrupt requests. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint32_t isrflags = READ_REG(hsmartcard->Instance->ISR); - uint32_t cr1its = READ_REG(hsmartcard->Instance->CR1); - uint32_t cr3its = READ_REG(hsmartcard->Instance->CR3); - uint32_t errorflags; - uint32_t errorcode; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF)); - if (errorflags == 0U) - { - /* SMARTCARD in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U))) - { - if (hsmartcard->RxISR != NULL) - { - hsmartcard->RxISR(hsmartcard); - } - return; - } - } - - /* If some errors occur */ - if ((errorflags != 0U) - && ((((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) - || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U)))) - { - /* SMARTCARD parity error interrupt occurred -------------------------------------*/ - if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) - { - __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_PEF); - - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_PE; - } - - /* SMARTCARD frame error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_FEF); - - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_FE; - } - - /* SMARTCARD noise error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_NEF); - - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_NE; - } - - /* SMARTCARD Over-Run interrupt occurred -----------------------------------------*/ - if (((isrflags & USART_ISR_ORE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U) - || ((cr3its & USART_CR3_EIE) != 0U))) - { - __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_OREF); - - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; - } - - /* SMARTCARD receiver timeout interrupt occurred -----------------------------------------*/ - if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) - { - __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_RTOF); - - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_RTO; - } - - /* Call SMARTCARD Error Call back function if need be --------------------------*/ - if (hsmartcard->ErrorCode != HAL_SMARTCARD_ERROR_NONE) - { - /* SMARTCARD in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U))) - { - if (hsmartcard->RxISR != NULL) - { - hsmartcard->RxISR(hsmartcard); - } - } - - /* If Error is to be considered as blocking : - - Receiver Timeout error in Reception - - Overrun error in Reception - - any error occurs in DMA mode reception - */ - errorcode = hsmartcard->ErrorCode; - if ((HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - || ((errorcode & (HAL_SMARTCARD_ERROR_RTO | HAL_SMARTCARD_ERROR_ORE)) != 0U)) - { - /* Blocking error : transfer is aborted - Set the SMARTCARD state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - SMARTCARD_EndRxTransfer(hsmartcard); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel */ - if (hsmartcard->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_ErrorCallback() at end of DMA abort procedure */ - hsmartcard->hdmarx->XferAbortCallback = SMARTCARD_DMAAbortOnError; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hsmartcard->hdmarx) != HAL_OK) - { - /* Call Directly hsmartcard->hdmarx->XferAbortCallback function in case of error */ - hsmartcard->hdmarx->XferAbortCallback(hsmartcard->hdmarx); - } - } - else - { -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - /* other error type to be considered as blocking : - - Frame error in Transmission - */ - else if ((hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) - && ((errorcode & HAL_SMARTCARD_ERROR_FE) != 0U)) - { - /* Blocking error : transfer is aborted - Set the SMARTCARD state ready to be able to start again the process, - Disable Tx Interrupts, and disable Tx DMA request, if ongoing */ - SMARTCARD_EndTxTransfer(hsmartcard); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Disable the SMARTCARD DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel */ - if (hsmartcard->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_ErrorCallback() at end of DMA abort procedure */ - hsmartcard->hdmatx->XferAbortCallback = SMARTCARD_DMAAbortOnError; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hsmartcard->hdmatx) != HAL_OK) - { - /* Call Directly hsmartcard->hdmatx->XferAbortCallback function in case of error */ - hsmartcard->hdmatx->XferAbortCallback(hsmartcard->hdmatx); - } - } - else - { -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - } - } - return; - - } /* End if some error occurs */ - - /* SMARTCARD in mode Receiver, end of block interruption ------------------------*/ - if (((isrflags & USART_ISR_EOBF) != 0U) && ((cr1its & USART_CR1_EOBIE) != 0U)) - { - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - __HAL_UNLOCK(hsmartcard); -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Rx complete callback */ - hsmartcard->RxCpltCallback(hsmartcard); -#else - /* Call legacy weak Rx complete callback */ - HAL_SMARTCARD_RxCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - /* Clear EOBF interrupt after HAL_SMARTCARD_RxCpltCallback() call for the End of Block information - to be available during HAL_SMARTCARD_RxCpltCallback() processing */ - __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_EOBF); - return; - } - - /* SMARTCARD in mode Transmitter ------------------------------------------------*/ - if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) - && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) - || ((cr3its & USART_CR3_TXFTIE) != 0U))) - { - if (hsmartcard->TxISR != NULL) - { - hsmartcard->TxISR(hsmartcard); - } - return; - } - - /* SMARTCARD in mode Transmitter (transmission end) ------------------------*/ - if (__HAL_SMARTCARD_GET_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication) != RESET) - { - if (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication) != RESET) - { - SMARTCARD_EndTransmit_IT(hsmartcard); - return; - } - } - - /* SMARTCARD TX Fifo Empty occurred ----------------------------------------------*/ - if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) - { -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Tx Fifo Empty Callback */ - hsmartcard->TxFifoEmptyCallback(hsmartcard); -#else - /* Call legacy weak Tx Fifo Empty Callback */ - HAL_SMARTCARDEx_TxFifoEmptyCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - return; - } - - /* SMARTCARD RX Fifo Full occurred ----------------------------------------------*/ - if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) - { -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Rx Fifo Full Callback */ - hsmartcard->RxFifoFullCallback(hsmartcard); -#else - /* Call legacy weak Rx Fifo Full Callback */ - HAL_SMARTCARDEx_RxFifoFullCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - return; - } -} - -/** - * @brief Tx Transfer completed callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_RxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD error callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_ErrorCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD Abort Complete callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_AbortCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD Abort Complete callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_AbortTransmitCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_AbortTransmitCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD Abort Receive Complete callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_AbortReceiveCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_AbortReceiveCpltCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup SMARTCARD_Exported_Functions_Group4 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 return the State of SmartCard - handle and also return Peripheral Errors occurred during communication process - (+) HAL_SMARTCARD_GetState() API can be helpful to check in run-time the state - of the SMARTCARD peripheral. - (+) HAL_SMARTCARD_GetError() checks in run-time errors that could occur during - communication. - -@endverbatim - * @{ - */ - -/** - * @brief Return the SMARTCARD handle state. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval SMARTCARD handle state - */ -HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(const SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Return SMARTCARD handle state */ - uint32_t temp1; - uint32_t temp2; - temp1 = (uint32_t)hsmartcard->gState; - temp2 = (uint32_t)hsmartcard->RxState; - - return (HAL_SMARTCARD_StateTypeDef)(temp1 | temp2); -} - -/** - * @brief Return the SMARTCARD handle error code. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval SMARTCARD handle Error Code - */ -uint32_t HAL_SMARTCARD_GetError(const SMARTCARD_HandleTypeDef *hsmartcard) -{ - return hsmartcard->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions - * @{ - */ - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) -/** - * @brief Initialize the callbacks to their default values. - * @param hsmartcard SMARTCARD handle. - * @retval none - */ -void SMARTCARD_InitCallbacksToDefault(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Init the SMARTCARD Callback settings */ - hsmartcard->TxCpltCallback = HAL_SMARTCARD_TxCpltCallback; /* Legacy weak TxCpltCallback */ - hsmartcard->RxCpltCallback = HAL_SMARTCARD_RxCpltCallback; /* Legacy weak RxCpltCallback */ - hsmartcard->ErrorCallback = HAL_SMARTCARD_ErrorCallback; /* Legacy weak ErrorCallback */ - hsmartcard->AbortCpltCallback = HAL_SMARTCARD_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - hsmartcard->AbortTransmitCpltCallback = HAL_SMARTCARD_AbortTransmitCpltCallback; /* Legacy weak - AbortTransmitCpltCallback */ - hsmartcard->AbortReceiveCpltCallback = HAL_SMARTCARD_AbortReceiveCpltCallback; /* Legacy weak - AbortReceiveCpltCallback */ - hsmartcard->RxFifoFullCallback = HAL_SMARTCARDEx_RxFifoFullCallback; /* Legacy weak - RxFifoFullCallback */ - hsmartcard->TxFifoEmptyCallback = HAL_SMARTCARDEx_TxFifoEmptyCallback; /* Legacy weak - TxFifoEmptyCallback */ - -} -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ - -/** - * @brief Configure the SMARTCARD associated USART peripheral. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval HAL status - */ -static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint32_t tmpreg; - SMARTCARD_ClockSourceTypeDef clocksource; - HAL_StatusTypeDef ret = HAL_OK; - static const uint16_t SMARTCARDPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; - uint32_t pclk; - - /* Check the parameters */ - assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); - assert_param(IS_SMARTCARD_BAUDRATE(hsmartcard->Init.BaudRate)); - assert_param(IS_SMARTCARD_WORD_LENGTH(hsmartcard->Init.WordLength)); - assert_param(IS_SMARTCARD_STOPBITS(hsmartcard->Init.StopBits)); - assert_param(IS_SMARTCARD_PARITY(hsmartcard->Init.Parity)); - assert_param(IS_SMARTCARD_MODE(hsmartcard->Init.Mode)); - assert_param(IS_SMARTCARD_POLARITY(hsmartcard->Init.CLKPolarity)); - assert_param(IS_SMARTCARD_PHASE(hsmartcard->Init.CLKPhase)); - assert_param(IS_SMARTCARD_LASTBIT(hsmartcard->Init.CLKLastBit)); - assert_param(IS_SMARTCARD_ONE_BIT_SAMPLE(hsmartcard->Init.OneBitSampling)); - assert_param(IS_SMARTCARD_NACK(hsmartcard->Init.NACKEnable)); - assert_param(IS_SMARTCARD_TIMEOUT(hsmartcard->Init.TimeOutEnable)); - assert_param(IS_SMARTCARD_AUTORETRY_COUNT(hsmartcard->Init.AutoRetryCount)); - assert_param(IS_SMARTCARD_CLOCKPRESCALER(hsmartcard->Init.ClockPrescaler)); - - /*-------------------------- USART CR1 Configuration -----------------------*/ - /* In SmartCard mode, M and PCE are forced to 1 (8 bits + parity). - * Oversampling is forced to 16 (OVER8 = 0). - * Configure the Parity and Mode: - * set PS bit according to hsmartcard->Init.Parity value - * set TE and RE bits according to hsmartcard->Init.Mode value */ - tmpreg = (((uint32_t)hsmartcard->Init.Parity) | ((uint32_t)hsmartcard->Init.Mode) | - ((uint32_t)hsmartcard->Init.WordLength)); - MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_FIELDS, tmpreg); - - /*-------------------------- USART CR2 Configuration -----------------------*/ - tmpreg = hsmartcard->Init.StopBits; - /* Synchronous mode is activated by default */ - tmpreg |= (uint32_t) USART_CR2_CLKEN | hsmartcard->Init.CLKPolarity; - tmpreg |= (uint32_t) hsmartcard->Init.CLKPhase | hsmartcard->Init.CLKLastBit; - tmpreg |= (uint32_t) hsmartcard->Init.TimeOutEnable; - MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_FIELDS, tmpreg); - - /*-------------------------- USART CR3 Configuration -----------------------*/ - /* Configure - * - one-bit sampling method versus three samples' majority rule - * according to hsmartcard->Init.OneBitSampling - * - NACK transmission in case of parity error according - * to hsmartcard->Init.NACKEnable - * - autoretry counter according to hsmartcard->Init.AutoRetryCount */ - - tmpreg = (uint32_t) hsmartcard->Init.OneBitSampling | hsmartcard->Init.NACKEnable; - tmpreg |= ((uint32_t)hsmartcard->Init.AutoRetryCount << USART_CR3_SCARCNT_Pos); - MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_FIELDS, tmpreg); - - /*--------------------- SMARTCARD clock PRESC Configuration ----------------*/ - /* Configure - * - SMARTCARD Clock Prescaler: set PRESCALER according to hsmartcard->Init.ClockPrescaler value */ - MODIFY_REG(hsmartcard->Instance->PRESC, USART_PRESC_PRESCALER, hsmartcard->Init.ClockPrescaler); - - /*-------------------------- USART GTPR Configuration ----------------------*/ - tmpreg = (hsmartcard->Init.Prescaler | ((uint32_t)hsmartcard->Init.GuardTime << USART_GTPR_GT_Pos)); - MODIFY_REG(hsmartcard->Instance->GTPR, (uint16_t)(USART_GTPR_GT | USART_GTPR_PSC), (uint16_t)tmpreg); - - /*-------------------------- USART RTOR Configuration ----------------------*/ - tmpreg = ((uint32_t)hsmartcard->Init.BlockLength << USART_RTOR_BLEN_Pos); - if (hsmartcard->Init.TimeOutEnable == SMARTCARD_TIMEOUT_ENABLE) - { - assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); - tmpreg |= (uint32_t) hsmartcard->Init.TimeOutValue; - } - WRITE_REG(hsmartcard->Instance->RTOR, tmpreg); - - /*-------------------------- USART BRR Configuration -----------------------*/ - SMARTCARD_GETCLOCKSOURCE(hsmartcard, clocksource); - tmpreg = 0U; - switch (clocksource) - { - case SMARTCARD_CLOCKSOURCE_PCLK1: - pclk = HAL_RCC_GetPCLK1Freq(); - tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - break; - case SMARTCARD_CLOCKSOURCE_PCLK2: - pclk = HAL_RCC_GetPCLK2Freq(); - tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - break; - case SMARTCARD_CLOCKSOURCE_PLL2Q: - pclk = HAL_RCC_GetPLL2QFreq(); - tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - break; - case SMARTCARD_CLOCKSOURCE_PLL3Q: - pclk = HAL_RCC_GetPLL3QFreq(); - tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - break; - case SMARTCARD_CLOCKSOURCE_HSI: - if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) - { - tmpreg = (uint32_t)((((HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)) / - SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - } - else - { - tmpreg = (uint32_t)(((HSI_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - } - break; - case SMARTCARD_CLOCKSOURCE_CSI: - tmpreg = (uint32_t)(((CSI_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - break; - case SMARTCARD_CLOCKSOURCE_LSE: - tmpreg = (uint32_t)(((uint16_t)(LSE_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + - (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); - break; - default: - ret = HAL_ERROR; - break; - } - - /* USARTDIV must be greater than or equal to 0d16 */ - if ((tmpreg >= USART_BRR_MIN) && (tmpreg <= USART_BRR_MAX)) - { - hsmartcard->Instance->BRR = (uint16_t)tmpreg; - } - else - { - ret = HAL_ERROR; - } - - /* Initialize the number of data to process during RX/TX ISR execution */ - hsmartcard->NbTxDataToProcess = 1U; - hsmartcard->NbRxDataToProcess = 1U; - - /* Clear ISR function pointers */ - hsmartcard->RxISR = NULL; - hsmartcard->TxISR = NULL; - - return ret; -} - - -/** - * @brief Configure the SMARTCARD associated USART peripheral advanced features. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Check whether the set of advanced features to configure is properly set */ - assert_param(IS_SMARTCARD_ADVFEATURE_INIT(hsmartcard->AdvancedInit.AdvFeatureInit)); - - /* if required, configure TX pin active level inversion */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_TXINVERT_INIT)) - { - assert_param(IS_SMARTCARD_ADVFEATURE_TXINV(hsmartcard->AdvancedInit.TxPinLevelInvert)); - MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_TXINV, hsmartcard->AdvancedInit.TxPinLevelInvert); - } - - /* if required, configure RX pin active level inversion */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXINVERT_INIT)) - { - assert_param(IS_SMARTCARD_ADVFEATURE_RXINV(hsmartcard->AdvancedInit.RxPinLevelInvert)); - MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_RXINV, hsmartcard->AdvancedInit.RxPinLevelInvert); - } - - /* if required, configure data inversion */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DATAINVERT_INIT)) - { - assert_param(IS_SMARTCARD_ADVFEATURE_DATAINV(hsmartcard->AdvancedInit.DataInvert)); - MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_DATAINV, hsmartcard->AdvancedInit.DataInvert); - } - - /* if required, configure RX/TX pins swap */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_SWAP_INIT)) - { - assert_param(IS_SMARTCARD_ADVFEATURE_SWAP(hsmartcard->AdvancedInit.Swap)); - MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_SWAP, hsmartcard->AdvancedInit.Swap); - } - - /* if required, configure RX overrun detection disabling */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT)) - { - assert_param(IS_SMARTCARD_OVERRUN(hsmartcard->AdvancedInit.OverrunDisable)); - MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_OVRDIS, hsmartcard->AdvancedInit.OverrunDisable); - } - - /* if required, configure DMA disabling on reception error */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT)) - { - assert_param(IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(hsmartcard->AdvancedInit.DMADisableonRxError)); - MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_DDRE, hsmartcard->AdvancedInit.DMADisableonRxError); - } - - /* if required, configure MSB first on communication line */ - if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) - { - assert_param(IS_SMARTCARD_ADVFEATURE_MSBFIRST(hsmartcard->AdvancedInit.MSBFirst)); - MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_MSBFIRST, hsmartcard->AdvancedInit.MSBFirst); - } - -} - -/** - * @brief Check the SMARTCARD Idle State. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval HAL status - */ -static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint32_t tickstart; - - /* Initialize the SMARTCARD ErrorCode */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check if the Transmitter is enabled */ - if ((hsmartcard->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) - { - /* Wait until TEACK flag is set */ - if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_TEACK, RESET, tickstart, - SMARTCARD_TEACK_REACK_TIMEOUT) != HAL_OK) - { - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - /* Check if the Receiver is enabled */ - if ((hsmartcard->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) - { - /* Wait until REACK flag is set */ - if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_REACK, RESET, tickstart, - SMARTCARD_TEACK_REACK_TIMEOUT) != HAL_OK) - { - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - - /* Initialize the SMARTCARD states */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; -} - -/** - * @brief Handle SMARTCARD Communication Timeout. It waits - * until a flag is no longer in the specified status. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @param Flag Specifies the SMARTCARD flag to check. - * @param Status The actual Flag status (SET or RESET). - * @param Tickstart Tick start value - * @param Timeout Timeout duration. - * @retval HAL status - */ -static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, - FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is set */ - while ((__HAL_SMARTCARD_GET_FLAG(hsmartcard, Flag) ? SET : RESET) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) - interrupts for the interrupt process */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - - -/** - * @brief End ongoing Tx transfer on SMARTCARD peripheral (following error detection or Transmit completion). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable TXEIE, TCIE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* At end of Tx process, restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; -} - - -/** - * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* At end of Rx process, restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; -} - - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief DMA SMARTCARD transmit process complete callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - hsmartcard->TxXferCount = 0U; - - /* Disable the DMA transfer for transmit request by resetting the DMAT bit - in the SMARTCARD associated USART CR3 register */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); - - /* Enable the SMARTCARD Transmit Complete Interrupt */ - __HAL_SMARTCARD_ENABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); -} - -/** - * @brief DMA SMARTCARD receive process complete callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - hsmartcard->RxXferCount = 0U; - - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* Disable the DMA transfer for the receiver request by resetting the DMAR bit - in the SMARTCARD associated USART CR3 register */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); - - /* At end of Rx process, restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Rx complete callback */ - hsmartcard->RxCpltCallback(hsmartcard); -#else - /* Call legacy weak Rx complete callback */ - HAL_SMARTCARD_RxCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - -/** - * @brief DMA SMARTCARD communication error callback. - * @param hdma Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - - /* Stop SMARTCARD DMA Tx request if ongoing */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) - { - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) - { - hsmartcard->TxXferCount = 0U; - SMARTCARD_EndTxTransfer(hsmartcard); - } - } - - /* Stop SMARTCARD DMA Rx request if ongoing */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_BUSY_RX) - { - if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) - { - hsmartcard->RxXferCount = 0U; - SMARTCARD_EndRxTransfer(hsmartcard); - } - } - - hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_DMA; -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - -/** - * @brief DMA SMARTCARD communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - hsmartcard->RxXferCount = 0U; - hsmartcard->TxXferCount = 0U; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered user error callback */ - hsmartcard->ErrorCallback(hsmartcard); -#else - /* Call legacy weak user error callback */ - HAL_SMARTCARD_ErrorCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - -/** - * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - - hsmartcard->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (hsmartcard->hdmarx != NULL) - { - if (hsmartcard->hdmarx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hsmartcard->TxXferCount = 0U; - hsmartcard->RxXferCount = 0U; - - /* Reset errorCode */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | - SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - hsmartcard->AbortCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort complete callback */ - HAL_SMARTCARD_AbortCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - - -/** - * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - - hsmartcard->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (hsmartcard->hdmatx != NULL) - { - if (hsmartcard->hdmatx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hsmartcard->TxXferCount = 0U; - hsmartcard->RxXferCount = 0U; - - /* Reset errorCode */ - hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | - SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - hsmartcard->AbortCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort complete callback */ - HAL_SMARTCARD_AbortCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - - -/** - * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user by a call to - * HAL_SMARTCARD_AbortTransmit_IT API (Abort only Tx transfer) - * (This callback is executed at end of DMA Tx Abort procedure following user abort request, - * and leads to user Tx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - - hsmartcard->TxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, SMARTCARD_CLEAR_FEF); - - /* Restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - hsmartcard->AbortTransmitCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_SMARTCARD_AbortTransmitCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - -/** - * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user by a call to - * HAL_SMARTCARD_AbortReceive_IT API (Abort only Rx transfer) - * (This callback is executed at end of DMA Rx Abort procedure following user abort request, - * and leads to user Rx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); - - hsmartcard->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, - SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | - SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); - - /* Restore hsmartcard->RxState to Ready */ - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - hsmartcard->AbortReceiveCpltCallback(hsmartcard); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_SMARTCARD_AbortReceiveCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Send an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() - * and when the FIFO mode is disabled. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_TxISR(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Check that a Tx process is ongoing */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) - { - if (hsmartcard->TxXferCount == 0U) - { - /* Disable the SMARTCARD Transmit Data Register Empty Interrupt */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - - /* Enable the SMARTCARD Transmit Complete Interrupt */ - __HAL_SMARTCARD_ENABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); - } - else - { - hsmartcard->Instance->TDR = (uint8_t)(*hsmartcard->pTxBuffPtr & 0xFFU); - hsmartcard->pTxBuffPtr++; - hsmartcard->TxXferCount--; - } - } -} - -/** - * @brief Send an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() - * and when the FIFO mode is enabled. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_TxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint16_t nb_tx_data; - - /* Check that a Tx process is ongoing */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) - { - for (nb_tx_data = hsmartcard->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) - { - if (hsmartcard->TxXferCount == 0U) - { - /* Disable the SMARTCARD Transmit Data Register Empty Interrupt */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - - /* Enable the SMARTCARD Transmit Complete Interrupt */ - __HAL_SMARTCARD_ENABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); - } - else if (READ_BIT(hsmartcard->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) - { - hsmartcard->Instance->TDR = (uint8_t)(*hsmartcard->pTxBuffPtr & 0xFFU); - hsmartcard->pTxBuffPtr++; - hsmartcard->TxXferCount--; - } - else - { - /* Nothing to do */ - } - } - } -} - -/** - * @brief Wrap up transmission in non-blocking mode. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Disable the SMARTCARD Transmit Complete Interrupt */ - __HAL_SMARTCARD_DISABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); - - /* Check if a receive process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - - /* Disable the Peripheral first to update mode */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) - && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - /* In case of TX only mode, if NACK is enabled, receiver block has been enabled - for Transmit phase. Disable this receiver block. */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); - } - if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX_RX) - || (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) - { - /* Perform a TX FIFO Flush at end of Tx phase, as all sent bytes are appearing in Rx Data register */ - __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); - } - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); - - /* Tx process is ended, restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Clear TxISR function pointer */ - hsmartcard->TxISR = NULL; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Tx complete callback */ - hsmartcard->TxCpltCallback(hsmartcard); -#else - /* Call legacy weak Tx complete callback */ - HAL_SMARTCARD_TxCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ -} - -/** - * @brief Receive an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_SMARTCARD_Receive_IT() - * and when the FIFO mode is disabled. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_RxISR(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Check that a Rx process is ongoing */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_BUSY_RX) - { - *hsmartcard->pRxBuffPtr = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0xFF); - hsmartcard->pRxBuffPtr++; - - hsmartcard->RxXferCount--; - if (hsmartcard->RxXferCount == 0U) - { - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - - /* Check if a transmit process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - - /* Disable the SMARTCARD Parity Error Interrupt */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); - - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* Clear RxISR function pointer */ - hsmartcard->RxISR = NULL; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Rx complete callback */ - hsmartcard->RxCpltCallback(hsmartcard); -#else - /* Call legacy weak Rx complete callback */ - HAL_SMARTCARD_RxCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_SMARTCARD_SEND_REQ(hsmartcard, SMARTCARD_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @brief Receive an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_SMARTCARD_Receive_IT() - * and when the FIFO mode is enabled. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -static void SMARTCARD_RxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint16_t nb_rx_data; - uint16_t rxdatacount; - - /* Check that a Rx process is ongoing */ - if (hsmartcard->RxState == HAL_SMARTCARD_STATE_BUSY_RX) - { - for (nb_rx_data = hsmartcard->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) - { - *hsmartcard->pRxBuffPtr = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0xFF); - hsmartcard->pRxBuffPtr++; - - hsmartcard->RxXferCount--; - if (hsmartcard->RxXferCount == 0U) - { - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - - /* Check if a transmit process is ongoing or not. If not disable ERR IT */ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - } - - /* Disable the SMARTCARD Parity Error Interrupt */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); - - hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; - - /* Clear RxISR function pointer */ - hsmartcard->RxISR = NULL; - -#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) - /* Call registered Rx complete callback */ - hsmartcard->RxCpltCallback(hsmartcard); -#else - /* Call legacy weak Rx complete callback */ - HAL_SMARTCARD_RxCpltCallback(hsmartcard); -#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ - } - } - - /* When remaining number of bytes to receive is less than the RX FIFO - threshold, next incoming frames are processed as if FIFO mode was - disabled (i.e. one interrupt per received frame). - */ - rxdatacount = hsmartcard->RxXferCount; - if (((rxdatacount != 0U)) && (rxdatacount < hsmartcard->NbRxDataToProcess)) - { - /* Disable the UART RXFT interrupt*/ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_RXFTIE); - - /* Update the RxISR function pointer */ - hsmartcard->RxISR = SMARTCARD_RxISR; - - /* Enable the UART Data Register Not Empty interrupt */ - SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_SMARTCARD_SEND_REQ(hsmartcard, SMARTCARD_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @} - */ - -#endif /* HAL_SMARTCARD_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_smartcard.c + * @author MCD Application Team + * @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 Control functions + * + Peripheral State and Error functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SMARTCARD HAL driver can be used as follows: + + (#) Declare a SMARTCARD_HandleTypeDef handle structure (eg. SMARTCARD_HandleTypeDef hsmartcard). + (#) Associate a USART to the SMARTCARD handle hsmartcard. + (#) Initialize the SMARTCARD low level resources by implementing the HAL_SMARTCARD_MspInit() API: + (++) Enable the USARTx interface clock. + (++) USART pins configuration: + (+++) Enable the clock for the USART GPIOs. + (+++) Configure the USART pins (TX as alternate function pull-up, RX as alternate function Input). + (++) 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. + (++) 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 channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx channel. + (+++) Associate the initialized 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 channel. + + (#) Program the Baud Rate, Parity, Mode(Receiver/Transmitter), clock enabling/disabling and accordingly, + the clock parameters (parity, phase, last bit), prescaler value, guard time and NACK on transmission + error enabling or disabling in the hsmartcard handle Init structure. + + (#) If required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, auto-retry counter,...) + in the hsmartcard handle AdvancedInit structure. + + (#) Initialize the SMARTCARD registers by calling the HAL_SMARTCARD_Init() API: + (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized HAL_SMARTCARD_MspInit() API. + [..] + (@) The specific SMARTCARD interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. + + [..] + [..] Three operation modes 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_GET_FLAG : Check whether or not the specified SMARTCARD flag is set + (+) __HAL_SMARTCARD_CLEAR_FLAG : Clear the specified SMARTCARD pending flag + (+) __HAL_SMARTCARD_ENABLE_IT: Enable the specified SMARTCARD interrupt + (+) __HAL_SMARTCARD_DISABLE_IT: Disable the specified SMARTCARD interrupt + (+) __HAL_SMARTCARD_GET_IT_SOURCE: Check whether or not the specified SMARTCARD interrupt is enabled + + [..] + (@) You can refer to the SMARTCARD HAL driver header file for more useful macros + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_HAL_SMARTCARD_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function HAL_SMARTCARD_RegisterCallback() to register a user callback. + Function HAL_SMARTCARD_RegisterCallback() allows to register following callbacks: + (+) TxCpltCallback : Tx Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) RxFifoFullCallback : Rx Fifo Full Callback. + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) MspInitCallback : SMARTCARD MspInit. + (+) MspDeInitCallback : SMARTCARD MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_SMARTCARD_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_SMARTCARD_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxCpltCallback : Tx Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) RxFifoFullCallback : Rx Fifo Full Callback. + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) MspInitCallback : SMARTCARD MspInit. + (+) MspDeInitCallback : SMARTCARD MspDeInit. + + [..] + By default, after the HAL_SMARTCARD_Init() and when the state is HAL_SMARTCARD_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak functions in the HAL_SMARTCARD_Init() + and HAL_SMARTCARD_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_SMARTCARD_Init() and HAL_SMARTCARD_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in HAL_SMARTCARD_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_SMARTCARD_STATE_READY or HAL_SMARTCARD_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SMARTCARD_RegisterCallback() before calling HAL_SMARTCARD_DeInit() + or HAL_SMARTCARD_Init() function. + + [..] + When The compilation define USE_HAL_SMARTCARD_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak callbacks are used. + + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARD SMARTCARD + * @brief HAL SMARTCARD module driver + * @{ + */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants + * @{ + */ +#define SMARTCARD_TEACK_REACK_TIMEOUT 1000U /*!< SMARTCARD TX or RX enable acknowledge time-out value */ + +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \ + USART_CR1_RE | USART_CR1_OVER8| \ + USART_CR1_FIFOEN)) /*!< USART CR1 fields of parameters set by SMARTCARD_SetConfig API */ + +#define USART_CR2_CLK_FIELDS ((uint32_t)(USART_CR2_CLKEN | USART_CR2_CPOL | \ + USART_CR2_CPHA | USART_CR2_LBCL)) /*!< SMARTCARD clock-related USART CR2 fields of parameters */ + +#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_RTOEN | USART_CR2_CLK_FIELDS | \ + USART_CR2_STOP)) /*!< USART CR2 fields of parameters set by SMARTCARD_SetConfig API */ + +#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_ONEBIT | USART_CR3_NACK | USART_CR3_SCARCNT | \ + USART_CR3_TXFTCFG | USART_CR3_RXFTCFG )) /*!< USART CR3 fields of parameters set by SMARTCARD_SetConfig API */ + +#define USART_BRR_MIN 0x10U /*!< USART BRR minimum authorized value */ + +#define USART_BRR_MAX 0x0000FFFFU /*!< USART BRR maximum authorized value */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup SMARTCARD_Private_Functions + * @{ + */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) +void SMARTCARD_InitCallbacksToDefault(SMARTCARD_HandleTypeDef *hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ +static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard); +static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard); +static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard); +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, + FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); +static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsmartcard); +static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsmartcard); +#if defined(HAL_DMA_MODULE_ENABLED) +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +#endif /* HAL_DMA_MODULE_ENABLED */ +static void SMARTCARD_TxISR(SMARTCARD_HandleTypeDef *hsmartcard); +static void SMARTCARD_TxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard); +static void SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard); +static void SMARTCARD_RxISR(SMARTCARD_HandleTypeDef *hsmartcard); +static void SMARTCARD_RxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions + * @{ + */ + +/** @defgroup SMARTCARD_Exported_Functions_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 + associated to the SmartCard. + (+) These parameters can be configured: + (++) Baud Rate + (++) Parity: parity should be enabled, frame Length is fixed to 8 bits plus parity + (++) Receiver/transmitter modes + (++) Synchronous mode (and if enabled, phase, polarity and last bit parameters) + (++) Prescaler value + (++) Guard bit time + (++) NACK enabling or disabling on transmission error + + (+) The following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) Time out enabling (and if activated, timeout value) + (++) Block length + (++) Auto-retry counter + [..] + The HAL_SMARTCARD_Init() API follows the USART synchronous configuration procedures + (details for the procedures are available in reference manual). + +@endverbatim + + The USART frame format is given in the following table: + + Table 1. USART frame format. + +---------------------------------------------------------------+ + | M1M0 bits | PCE bit | USART frame | + |-----------------------|---------------------------------------| + | 01 | 1 | | SB | 8 bit data | PB | STB | | + +---------------------------------------------------------------+ + + + * @{ + */ + +/** + * @brief Initialize the SMARTCARD mode according to the specified + * parameters in the SMARTCARD_HandleTypeDef and initialize the associated handle. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check the SMARTCARD handle allocation */ + if (hsmartcard == NULL) + { + return HAL_ERROR; + } + + /* Check the USART associated to the SMARTCARD handle */ + assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); + + if (hsmartcard->gState == HAL_SMARTCARD_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsmartcard->Lock = HAL_UNLOCKED; + +#if USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1 + SMARTCARD_InitCallbacksToDefault(hsmartcard); + + if (hsmartcard->MspInitCallback == NULL) + { + hsmartcard->MspInitCallback = HAL_SMARTCARD_MspInit; + } + + /* Init the low level hardware */ + hsmartcard->MspInitCallback(hsmartcard); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_SMARTCARD_MspInit(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ + } + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Disable the Peripheral to set smartcard mode */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* In SmartCard mode, the following bits must be kept cleared: + - LINEN in the USART_CR2 register, + - HDSEL and IREN bits in the USART_CR3 register.*/ + CLEAR_BIT(hsmartcard->Instance->CR2, USART_CR2_LINEN); + CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_HDSEL | USART_CR3_IREN)); + + /* set the USART in SMARTCARD mode */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_SCEN); + + /* Set the SMARTCARD Communication parameters */ + if (SMARTCARD_SetConfig(hsmartcard) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* Set the SMARTCARD transmission completion indication */ + SMARTCARD_TRANSMISSION_COMPLETION_SETTING(hsmartcard); + + if (hsmartcard->AdvancedInit.AdvFeatureInit != SMARTCARD_ADVFEATURE_NO_INIT) + { + SMARTCARD_AdvFeatureConfig(hsmartcard); + } + + /* Enable the Peripheral */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* TEACK and/or REACK to check before moving hsmartcard->gState and hsmartcard->RxState to Ready */ + return (SMARTCARD_CheckIdleState(hsmartcard)); +} + +/** + * @brief DeInitialize the SMARTCARD peripheral. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check the SMARTCARD handle allocation */ + if (hsmartcard == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the SMARTCARD handle */ + assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Disable the Peripheral */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + WRITE_REG(hsmartcard->Instance->CR1, 0x0U); + WRITE_REG(hsmartcard->Instance->CR2, 0x0U); + WRITE_REG(hsmartcard->Instance->CR3, 0x0U); + WRITE_REG(hsmartcard->Instance->RTOR, 0x0U); + WRITE_REG(hsmartcard->Instance->GTPR, 0x0U); + + /* DeInit the low level hardware */ +#if USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1 + if (hsmartcard->MspDeInitCallback == NULL) + { + hsmartcard->MspDeInitCallback = HAL_SMARTCARD_MspDeInit; + } + /* DeInit the low level hardware */ + hsmartcard->MspDeInitCallback(hsmartcard); +#else + HAL_SMARTCARD_MspDeInit(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->gState = HAL_SMARTCARD_STATE_RESET; + hsmartcard->RxState = HAL_SMARTCARD_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief Initialize the SMARTCARD MSP. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitialize the SMARTCARD MSP. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_MspDeInit can be implemented in the user file + */ +} + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SMARTCARD Callback + * To be used to override the weak predefined callback + * @note The HAL_SMARTCARD_RegisterCallback() may be called before HAL_SMARTCARD_Init() + * in HAL_SMARTCARD_STATE_RESET to register callbacks for HAL_SMARTCARD_MSPINIT_CB_ID + * and HAL_SMARTCARD_MSPDEINIT_CB_ID + * @param hsmartcard smartcard handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SMARTCARD_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_SMARTCARD_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_SMARTCARD_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_SMARTCARD_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref HAL_SMARTCARD_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID + * @arg @ref HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID + * @arg @ref HAL_SMARTCARD_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_SMARTCARD_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_RegisterCallback(SMARTCARD_HandleTypeDef *hsmartcard, + HAL_SMARTCARD_CallbackIDTypeDef CallbackID, + pSMARTCARD_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + switch (CallbackID) + { + + case HAL_SMARTCARD_TX_COMPLETE_CB_ID : + hsmartcard->TxCpltCallback = pCallback; + break; + + case HAL_SMARTCARD_RX_COMPLETE_CB_ID : + hsmartcard->RxCpltCallback = pCallback; + break; + + case HAL_SMARTCARD_ERROR_CB_ID : + hsmartcard->ErrorCallback = pCallback; + break; + + case HAL_SMARTCARD_ABORT_COMPLETE_CB_ID : + hsmartcard->AbortCpltCallback = pCallback; + break; + + case HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID : + hsmartcard->AbortTransmitCpltCallback = pCallback; + break; + + case HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID : + hsmartcard->AbortReceiveCpltCallback = pCallback; + break; + + case HAL_SMARTCARD_RX_FIFO_FULL_CB_ID : + hsmartcard->RxFifoFullCallback = pCallback; + break; + + case HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID : + hsmartcard->TxFifoEmptyCallback = pCallback; + break; + + case HAL_SMARTCARD_MSPINIT_CB_ID : + hsmartcard->MspInitCallback = pCallback; + break; + + case HAL_SMARTCARD_MSPDEINIT_CB_ID : + hsmartcard->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (hsmartcard->gState == HAL_SMARTCARD_STATE_RESET) + { + switch (CallbackID) + { + case HAL_SMARTCARD_MSPINIT_CB_ID : + hsmartcard->MspInitCallback = pCallback; + break; + + case HAL_SMARTCARD_MSPDEINIT_CB_ID : + hsmartcard->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an SMARTCARD callback + * SMARTCARD callback is redirected to the weak predefined callback + * @note The HAL_SMARTCARD_UnRegisterCallback() may be called before HAL_SMARTCARD_Init() + * in HAL_SMARTCARD_STATE_RESET to un-register callbacks for HAL_SMARTCARD_MSPINIT_CB_ID + * and HAL_SMARTCARD_MSPDEINIT_CB_ID + * @param hsmartcard smartcard handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_SMARTCARD_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_SMARTCARD_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_SMARTCARD_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_SMARTCARD_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref HAL_SMARTCARD_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID + * @arg @ref HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID + * @arg @ref HAL_SMARTCARD_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_SMARTCARD_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_UnRegisterCallback(SMARTCARD_HandleTypeDef *hsmartcard, + HAL_SMARTCARD_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_SMARTCARD_STATE_READY == hsmartcard->gState) + { + switch (CallbackID) + { + case HAL_SMARTCARD_TX_COMPLETE_CB_ID : + hsmartcard->TxCpltCallback = HAL_SMARTCARD_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_SMARTCARD_RX_COMPLETE_CB_ID : + hsmartcard->RxCpltCallback = HAL_SMARTCARD_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_SMARTCARD_ERROR_CB_ID : + hsmartcard->ErrorCallback = HAL_SMARTCARD_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_SMARTCARD_ABORT_COMPLETE_CB_ID : + hsmartcard->AbortCpltCallback = HAL_SMARTCARD_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_SMARTCARD_ABORT_TRANSMIT_COMPLETE_CB_ID : + hsmartcard->AbortTransmitCpltCallback = HAL_SMARTCARD_AbortTransmitCpltCallback; /* Legacy weak + AbortTransmitCpltCallback*/ + break; + + case HAL_SMARTCARD_ABORT_RECEIVE_COMPLETE_CB_ID : + hsmartcard->AbortReceiveCpltCallback = HAL_SMARTCARD_AbortReceiveCpltCallback; /* Legacy weak + AbortReceiveCpltCallback */ + break; + + case HAL_SMARTCARD_RX_FIFO_FULL_CB_ID : + hsmartcard->RxFifoFullCallback = HAL_SMARTCARDEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ + break; + + case HAL_SMARTCARD_TX_FIFO_EMPTY_CB_ID : + hsmartcard->TxFifoEmptyCallback = HAL_SMARTCARDEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ + break; + + case HAL_SMARTCARD_MSPINIT_CB_ID : + hsmartcard->MspInitCallback = HAL_SMARTCARD_MspInit; /* Legacy weak MspInitCallback */ + break; + + case HAL_SMARTCARD_MSPDEINIT_CB_ID : + hsmartcard->MspDeInitCallback = HAL_SMARTCARD_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SMARTCARD_STATE_RESET == hsmartcard->gState) + { + switch (CallbackID) + { + case HAL_SMARTCARD_MSPINIT_CB_ID : + hsmartcard->MspInitCallback = HAL_SMARTCARD_MspInit; + break; + + case HAL_SMARTCARD_MSPDEINIT_CB_ID : + hsmartcard->MspDeInitCallback = HAL_SMARTCARD_MspDeInit; + break; + + default : + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SMARTCARD_Exported_Functions_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. + + [..] + Smartcard is a single wire half duplex communication protocol. + The Smartcard interface is designed to support asynchronous protocol Smartcards as + defined in the ISO 7816-3 standard. The USART should be configured as: + (+) 8 bits plus parity: where M=1 and PCE=1 in the USART_CR1 register + (+) 1.5 stop bits when transmitting and receiving: where STOP=11 in the USART_CR2 register. + + [..] + (#) 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, the relevant 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 respectively 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 APIs are : + (##) HAL_SMARTCARD_Transmit() + (##) HAL_SMARTCARD_Receive() + + (#) Non Blocking mode APIs with Interrupt are : + (##) HAL_SMARTCARD_Transmit_IT() + (##) HAL_SMARTCARD_Receive_IT() + (##) HAL_SMARTCARD_IRQHandler() + + (#) Non Blocking mode functions with DMA are : + (##) HAL_SMARTCARD_Transmit_DMA() + (##) HAL_SMARTCARD_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: + (##) HAL_SMARTCARD_TxCpltCallback() + (##) HAL_SMARTCARD_RxCpltCallback() + (##) HAL_SMARTCARD_ErrorCallback() + + [..] + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (##) HAL_SMARTCARD_Abort() + (##) HAL_SMARTCARD_AbortTransmit() + (##) HAL_SMARTCARD_AbortReceive() + (##) HAL_SMARTCARD_Abort_IT() + (##) HAL_SMARTCARD_AbortTransmit_IT() + (##) HAL_SMARTCARD_AbortReceive_IT() + + (#) For Abort services based on interrupts (HAL_SMARTCARD_Abortxxx_IT), + a set of Abort Complete Callbacks are provided: + (##) HAL_SMARTCARD_AbortCpltCallback() + (##) HAL_SMARTCARD_AbortTransmitCpltCallback() + (##) HAL_SMARTCARD_AbortReceiveCpltCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (##) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, + Parity Error or Noise Error in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, + Error code is set to allow user to identify error type, + and HAL_SMARTCARD_ErrorCallback() user callback is executed. Transfer is kept ongoing on SMARTCARD side. + If user wants to abort it, Abort services should be called by user. + (##) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Frame Error in Interrupt mode transmission, Overrun Error in Interrupt + mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, + and HAL_SMARTCARD_ErrorCallback() user callback is executed. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode. + * @note When FIFO mode is enabled, writing a data in the TDR register adds one + * data to the TXFIFO. Write operations to the TDR register are performed + * when TXFNF flag is set. From hardware perspective, TXFNF flag and + * TXE are mapped on the same bit-field. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData pointer to data buffer. + * @param Size amount of data to be sent. + * @param Timeout Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsmartcard, const uint8_t *pData, uint16_t Size, + uint32_t Timeout) +{ + uint32_t tickstart; + const uint8_t *ptmpdata = pData; + + /* Check that a Tx process is not already ongoing */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + if ((ptmpdata == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Disable the Peripheral first to update mode for TX master */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* In case of TX only mode, if NACK is enabled, the USART must be able to monitor + the bidirectional line to detect a NACK signal in case of parity error. + Therefore, the receiver block must be enabled as well (RE bit must be set). */ + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) + && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); + } + /* Enable Tx */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TE); + + /* Enable the Peripheral */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* Perform a TX/RX FIFO Flush */ + __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->TxXferSize = Size; + hsmartcard->TxXferCount = Size; + + while (hsmartcard->TxXferCount > 0U) + { + hsmartcard->TxXferCount--; + if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hsmartcard->Instance->TDR = (uint8_t)(*ptmpdata & 0xFFU); + ptmpdata++; + } + if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_TRANSMISSION_COMPLETION_FLAG(hsmartcard), RESET, + tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Disable the Peripheral first to update mode */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) + && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + /* In case of TX only mode, if NACK is enabled, receiver block has been enabled + for Transmit phase. Disable this receiver block. */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); + } + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX_RX) + || (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + /* Perform a TX FIFO Flush at end of Tx phase, as all sent bytes are appearing in Rx Data register */ + __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); + } + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* At end of Tx process, restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode. + * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO + * is not empty. Read operations from the RDR register are performed when + * RXFNE flag is set. From hardware perspective, RXFNE flag and + * RXNE are mapped on the same bit-field. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData pointer to data buffer. + * @param Size amount of data to be received. + * @param Timeout Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, + uint32_t Timeout) +{ + uint32_t tickstart; + uint8_t *ptmpdata = pData; + + /* Check that a Rx process is not already ongoing */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) + { + if ((ptmpdata == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->RxState = HAL_SMARTCARD_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + hsmartcard->RxXferSize = Size; + hsmartcard->RxXferCount = Size; + + /* Check the remain data to be received */ + while (hsmartcard->RxXferCount > 0U) + { + hsmartcard->RxXferCount--; + + if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + *ptmpdata = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0x00FF); + ptmpdata++; + } + + /* At end of Rx process, restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode. + * @note When FIFO mode is disabled, USART interrupt is generated whenever + * USART_TDR register is empty, i.e one interrupt per data to transmit. + * @note When FIFO mode is enabled, USART interrupt is generated whenever + * TXFIFO threshold reached. In that case the interrupt rate depends on + * TXFIFO threshold configuration. + * @note This function sets the hsmartcard->TxIsr function pointer according to + * the FIFO mode (data transmission processing depends on FIFO mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @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 *hsmartcard, const uint8_t *pData, uint16_t Size) +{ + /* Check that a Tx process is not already ongoing */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY_TX; + + hsmartcard->pTxBuffPtr = pData; + hsmartcard->TxXferSize = Size; + hsmartcard->TxXferCount = Size; + hsmartcard->TxISR = NULL; + + /* Disable the Peripheral first to update mode for TX master */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* In case of TX only mode, if NACK is enabled, the USART must be able to monitor + the bidirectional line to detect a NACK signal in case of parity error. + Therefore, the receiver block must be enabled as well (RE bit must be set). */ + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) + && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); + } + /* Enable Tx */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TE); + + /* Enable the Peripheral */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* Perform a TX/RX FIFO Flush */ + __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); + + /* Configure Tx interrupt processing */ + if (hsmartcard->FifoMode == SMARTCARD_FIFOMODE_ENABLE) + { + /* Set the Tx ISR function pointer */ + hsmartcard->TxISR = SMARTCARD_TxISR_FIFOEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCARD Error Interrupt: (Frame error) */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* Enable the TX FIFO threshold interrupt */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTIE); + } + else + { + /* Set the Tx ISR function pointer */ + hsmartcard->TxISR = SMARTCARD_TxISR; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCARD Error Interrupt: (Frame error) */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* Enable the SMARTCARD Transmit Data Register Empty Interrupt */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode. + * @note When FIFO mode is disabled, USART interrupt is generated whenever + * USART_RDR register can be read, i.e one interrupt per data to receive. + * @note When FIFO mode is enabled, USART interrupt is generated whenever + * RXFIFO threshold reached. In that case the interrupt rate depends on + * RXFIFO threshold configuration. + * @note This function sets the hsmartcard->RxIsr function pointer according to + * the FIFO mode (data reception processing depends on FIFO mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @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 *hsmartcard, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->RxState = HAL_SMARTCARD_STATE_BUSY_RX; + + hsmartcard->pRxBuffPtr = pData; + hsmartcard->RxXferSize = Size; + hsmartcard->RxXferCount = Size; + + /* Configure Rx interrupt processing */ + if ((hsmartcard->FifoMode == SMARTCARD_FIFOMODE_ENABLE) && (Size >= hsmartcard->NbRxDataToProcess)) + { + /* Set the Rx ISR function pointer */ + hsmartcard->RxISR = SMARTCARD_RxISR_FIFOEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCART Parity Error interrupt and RX FIFO Threshold interrupt */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_RXFTIE); + } + else + { + /* Set the Rx ISR function pointer */ + hsmartcard->RxISR = SMARTCARD_RxISR; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCARD Parity Error and Data Register not empty Interrupts */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); + } + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Send an amount of data in DMA mode. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @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 *hsmartcard, const uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + + /* Check that a Tx process is not already ongoing */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY_TX; + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->pTxBuffPtr = pData; + hsmartcard->TxXferSize = Size; + hsmartcard->TxXferCount = Size; + + /* Disable the Peripheral first to update mode for TX master */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* In case of TX only mode, if NACK is enabled, the USART must be able to monitor + the bidirectional line to detect a NACK signal in case of parity error. + Therefore, the receiver block must be enabled as well (RE bit must be set). */ + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) + && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); + } + /* Enable Tx */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_TE); + + /* Enable the Peripheral */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* Perform a TX/RX FIFO Flush */ + __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); + + /* Set the SMARTCARD DMA transfer complete callback */ + hsmartcard->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt; + + /* Set the SMARTCARD error callback */ + hsmartcard->hdmatx->XferErrorCallback = SMARTCARD_DMAError; + + /* Set the DMA abort callback */ + hsmartcard->hdmatx->XferAbortCallback = NULL; + + /* Check linked list mode */ + if ((hsmartcard->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hsmartcard->hdmatx->LinkedListQueue != NULL) && (hsmartcard->hdmatx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + hsmartcard->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = Size; + + /* Set DMA source address */ + hsmartcard->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)hsmartcard->pTxBuffPtr; + + /* Set DMA destination address */ + hsmartcard->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&hsmartcard->Instance->TDR; + + /* Enable the SMARTCARD transmit DMA channel */ + status = HAL_DMAEx_List_Start_IT(hsmartcard->hdmatx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the SMARTCARD transmit DMA channel */ + status = HAL_DMA_Start_IT(hsmartcard->hdmatx, (uint32_t)hsmartcard->pTxBuffPtr, + (uint32_t)&hsmartcard->Instance->TDR, Size); + } + + if (status == HAL_OK) + { + /* Clear the TC flag in the ICR register */ + CLEAR_BIT(hsmartcard->Instance->ICR, USART_ICR_TCCF); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the UART Error Interrupt: (Frame error) */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD associated USART CR3 register */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + return HAL_OK; + } + else + { + /* Set error code to DMA */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Restore hsmartcard->State to ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData pointer to data buffer. + * @param Size amount of data to be received. + * @note The SMARTCARD-associated USART parity is enabled (PCE = 1), + * the received data contain the parity bit (MSB position). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + + /* Check that a Rx process is not already ongoing */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->RxState = HAL_SMARTCARD_STATE_BUSY_RX; + + hsmartcard->pRxBuffPtr = pData; + hsmartcard->RxXferSize = Size; + + /* Set the SMARTCARD DMA transfer complete callback */ + hsmartcard->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt; + + /* Set the SMARTCARD DMA error callback */ + hsmartcard->hdmarx->XferErrorCallback = SMARTCARD_DMAError; + + /* Set the DMA abort callback */ + hsmartcard->hdmarx->XferAbortCallback = NULL; + + /* Check linked list mode */ + if ((hsmartcard->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hsmartcard->hdmarx->LinkedListQueue != NULL) && (hsmartcard->hdmarx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + hsmartcard->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = Size; + + /* Set DMA source address */ + hsmartcard->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)&hsmartcard->Instance->RDR; + + /* Set DMA destination address */ + hsmartcard->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)hsmartcard->pRxBuffPtr; + + /* Enable the SMARTCARD receive DMA channel */ + status = HAL_DMAEx_List_Start_IT(hsmartcard->hdmarx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the DMA channel */ + status = HAL_DMA_Start_IT(hsmartcard->hdmarx, (uint32_t)&hsmartcard->Instance->RDR, + (uint32_t)hsmartcard->pRxBuffPtr, Size); + } + + if (status == HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCARD Parity Error Interrupt */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD associated USART CR3 register */ + SET_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + return HAL_OK; + } + else + { + /* Set error code to DMA */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Restore hsmartcard->State to ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable RTOIE, EOBIE, TXEIE, TCIE, RXNE, PE, RXFT, TXFT and + ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, + (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE | USART_CR1_RTOIE | + USART_CR1_EOBIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (hsmartcard->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsmartcard->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hsmartcard->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hsmartcard->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + + /* Disable the SMARTCARD DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (hsmartcard->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsmartcard->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hsmartcard->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hsmartcard->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx and Rx transfer counters */ + hsmartcard->TxXferCount = 0U; + hsmartcard->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | + SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* Reset Handle ErrorCode to No Error */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + return HAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (blocking mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable TCIE, TXEIE and TXFTIE interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTIE); + + /* Check if a receive process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (hsmartcard->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsmartcard->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hsmartcard->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hsmartcard->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx transfer counter */ + hsmartcard->TxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, SMARTCARD_CLEAR_FEF); + + /* Restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (blocking mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable RTOIE, EOBIE, RXNE, PE, RXFT, TXFT and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE | + USART_CR1_EOBIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Check if a Transmit process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (hsmartcard->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + hsmartcard->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(hsmartcard->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hsmartcard->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Rx transfer counter */ + hsmartcard->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | + SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t abortcplt = 1U; + + /* Disable RTOIE, EOBIE, TXEIE, TCIE, RXNE, PE, RXFT, TXFT and + ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, + (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE | USART_CR1_RTOIE | + USART_CR1_EOBIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* If DMA Tx and/or DMA Rx Handles are associated to SMARTCARD Handle, + DMA Abort complete callbacks should be initialised before any call + to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (hsmartcard->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if SMARTCARD DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + hsmartcard->hdmatx->XferAbortCallback = SMARTCARD_DMATxAbortCallback; + } + else + { + hsmartcard->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (hsmartcard->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if SMARTCARD DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + hsmartcard->hdmarx->XferAbortCallback = SMARTCARD_DMARxAbortCallback; + } + else + { + hsmartcard->hdmarx->XferAbortCallback = NULL; + } + } + + /* Disable the SMARTCARD DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable DMA Tx at UART level */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + /* Abort the SMARTCARD DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (hsmartcard->hdmatx != NULL) + { + /* SMARTCARD Tx DMA Abort callback has already been initialised : + will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hsmartcard->hdmatx) != HAL_OK) + { + hsmartcard->hdmatx->XferAbortCallback = NULL; + } + else + { + abortcplt = 0U; + } + } + } + + /* Disable the SMARTCARD DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + /* Abort the SMARTCARD DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (hsmartcard->hdmarx != NULL) + { + /* SMARTCARD Rx DMA Abort callback has already been initialised : + will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hsmartcard->hdmarx) != HAL_OK) + { + hsmartcard->hdmarx->XferAbortCallback = NULL; + abortcplt = 1U; + } + else + { + abortcplt = 0U; + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (abortcplt == 1U) + { + /* Reset Tx and Rx transfer counters */ + hsmartcard->TxXferCount = 0U; + hsmartcard->RxXferCount = 0U; + + /* Clear ISR function pointers */ + hsmartcard->RxISR = NULL; + hsmartcard->TxISR = NULL; + + /* Reset errorCode */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | + SMARTCARD_CLEAR_FEF | SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hsmartcard->AbortCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort complete callback */ + HAL_SMARTCARD_AbortCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + + return HAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (Interrupt mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable TCIE, TXEIE and TXFTIE interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTIE); + + /* Check if a receive process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + /* Abort the SMARTCARD DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (hsmartcard->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + hsmartcard->hdmatx->XferAbortCallback = SMARTCARD_DMATxOnlyAbortCallback; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hsmartcard->hdmatx) != HAL_OK) + { + /* Call Directly hsmartcard->hdmatx->XferAbortCallback function in case of error */ + hsmartcard->hdmatx->XferAbortCallback(hsmartcard->hdmatx); + } + } + else + { + /* Reset Tx transfer counter */ + hsmartcard->TxXferCount = 0U; + + /* Clear TxISR function pointers */ + hsmartcard->TxISR = NULL; + + /* Restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hsmartcard->AbortTransmitCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_SMARTCARD_AbortTransmitCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Reset Tx transfer counter */ + hsmartcard->TxXferCount = 0U; + + /* Clear TxISR function pointers */ + hsmartcard->TxISR = NULL; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, SMARTCARD_CLEAR_FEF); + + /* Restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hsmartcard->AbortTransmitCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_SMARTCARD_AbortTransmitCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + + return HAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (Interrupt mode). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable SMARTCARD Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable RTOIE, EOBIE, RXNE, PE, RXFT and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE | + USART_CR1_EOBIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Check if a Transmit process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + /* Abort the SMARTCARD DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (hsmartcard->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ + hsmartcard->hdmarx->XferAbortCallback = SMARTCARD_DMARxOnlyAbortCallback; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hsmartcard->hdmarx) != HAL_OK) + { + /* Call Directly hsmartcard->hdmarx->XferAbortCallback function in case of error */ + hsmartcard->hdmarx->XferAbortCallback(hsmartcard->hdmarx); + } + } + else + { + /* Reset Rx transfer counter */ + hsmartcard->RxXferCount = 0U; + + /* Clear RxISR function pointer */ + hsmartcard->RxISR = NULL; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | + SMARTCARD_CLEAR_FEF | SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hsmartcard->AbortReceiveCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_SMARTCARD_AbortReceiveCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Reset Rx transfer counter */ + hsmartcard->RxXferCount = 0U; + + /* Clear RxISR function pointer */ + hsmartcard->RxISR = NULL; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | + SMARTCARD_CLEAR_FEF | SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hsmartcard->AbortReceiveCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_SMARTCARD_AbortReceiveCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + + return HAL_OK; +} + +/** + * @brief Handle SMARTCARD interrupt requests. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t isrflags = READ_REG(hsmartcard->Instance->ISR); + uint32_t cr1its = READ_REG(hsmartcard->Instance->CR1); + uint32_t cr3its = READ_REG(hsmartcard->Instance->CR3); + uint32_t errorflags; + uint32_t errorcode; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF)); + if (errorflags == 0U) + { + /* SMARTCARD in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U))) + { + if (hsmartcard->RxISR != NULL) + { + hsmartcard->RxISR(hsmartcard); + } + return; + } + } + + /* If some errors occur */ + if ((errorflags != 0U) + && ((((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) + || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U)))) + { + /* SMARTCARD parity error interrupt occurred -------------------------------------*/ + if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_PEF); + + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_PE; + } + + /* SMARTCARD frame error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_FEF); + + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_FE; + } + + /* SMARTCARD noise error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_NEF); + + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_NE; + } + + /* SMARTCARD Over-Run interrupt occurred -----------------------------------------*/ + if (((isrflags & USART_ISR_ORE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U) + || ((cr3its & USART_CR3_EIE) != 0U))) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_OREF); + + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; + } + + /* SMARTCARD receiver timeout interrupt occurred -----------------------------------------*/ + if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_RTOF); + + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_RTO; + } + + /* Call SMARTCARD Error Call back function if need be --------------------------*/ + if (hsmartcard->ErrorCode != HAL_SMARTCARD_ERROR_NONE) + { + /* SMARTCARD in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U))) + { + if (hsmartcard->RxISR != NULL) + { + hsmartcard->RxISR(hsmartcard); + } + } + + /* If Error is to be considered as blocking : + - Receiver Timeout error in Reception + - Overrun error in Reception + - any error occurs in DMA mode reception + */ + errorcode = hsmartcard->ErrorCode; + if ((HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + || ((errorcode & (HAL_SMARTCARD_ERROR_RTO | HAL_SMARTCARD_ERROR_ORE)) != 0U)) + { + /* Blocking error : transfer is aborted + Set the SMARTCARD state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + SMARTCARD_EndRxTransfer(hsmartcard); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + /* Abort the SMARTCARD DMA Rx channel */ + if (hsmartcard->hdmarx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call HAL_SMARTCARD_ErrorCallback() at end of DMA abort procedure */ + hsmartcard->hdmarx->XferAbortCallback = SMARTCARD_DMAAbortOnError; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(hsmartcard->hdmarx) != HAL_OK) + { + /* Call Directly hsmartcard->hdmarx->XferAbortCallback function in case of error */ + hsmartcard->hdmarx->XferAbortCallback(hsmartcard->hdmarx); + } + } + else + { +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + /* other error type to be considered as blocking : + - Frame error in Transmission + */ + else if ((hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) + && ((errorcode & HAL_SMARTCARD_ERROR_FE) != 0U)) + { + /* Blocking error : transfer is aborted + Set the SMARTCARD state ready to be able to start again the process, + Disable Tx Interrupts, and disable Tx DMA request, if ongoing */ + SMARTCARD_EndTxTransfer(hsmartcard); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Disable the SMARTCARD DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + /* Abort the SMARTCARD DMA Tx channel */ + if (hsmartcard->hdmatx != NULL) + { + /* Set the SMARTCARD DMA Abort callback : + will lead to call HAL_SMARTCARD_ErrorCallback() at end of DMA abort procedure */ + hsmartcard->hdmatx->XferAbortCallback = SMARTCARD_DMAAbortOnError; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(hsmartcard->hdmatx) != HAL_OK) + { + /* Call Directly hsmartcard->hdmatx->XferAbortCallback function in case of error */ + hsmartcard->hdmatx->XferAbortCallback(hsmartcard->hdmatx); + } + } + else + { +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + } + } + return; + + } /* End if some error occurs */ + + /* SMARTCARD in mode Receiver, end of block interruption ------------------------*/ + if (((isrflags & USART_ISR_EOBF) != 0U) && ((cr1its & USART_CR1_EOBIE) != 0U)) + { + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + __HAL_UNLOCK(hsmartcard); +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hsmartcard->RxCpltCallback(hsmartcard); +#else + /* Call legacy weak Rx complete callback */ + HAL_SMARTCARD_RxCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + /* Clear EOBF interrupt after HAL_SMARTCARD_RxCpltCallback() call for the End of Block information + to be available during HAL_SMARTCARD_RxCpltCallback() processing */ + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_EOBF); + return; + } + + /* SMARTCARD in mode Transmitter ------------------------------------------------*/ + if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) + && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) + || ((cr3its & USART_CR3_TXFTIE) != 0U))) + { + if (hsmartcard->TxISR != NULL) + { + hsmartcard->TxISR(hsmartcard); + } + return; + } + + /* SMARTCARD in mode Transmitter (transmission end) ------------------------*/ + if (__HAL_SMARTCARD_GET_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication) != RESET) + { + if (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication) != RESET) + { + SMARTCARD_EndTransmit_IT(hsmartcard); + return; + } + } + + /* SMARTCARD TX Fifo Empty occurred ----------------------------------------------*/ + if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) + { +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Tx Fifo Empty Callback */ + hsmartcard->TxFifoEmptyCallback(hsmartcard); +#else + /* Call legacy weak Tx Fifo Empty Callback */ + HAL_SMARTCARDEx_TxFifoEmptyCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + return; + } + + /* SMARTCARD RX Fifo Full occurred ----------------------------------------------*/ + if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) + { +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx Fifo Full Callback */ + hsmartcard->RxFifoFullCallback(hsmartcard); +#else + /* Call legacy weak Rx Fifo Full Callback */ + HAL_SMARTCARDEx_RxFifoFullCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + return; + } +} + +/** + * @brief Tx Transfer completed callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_RxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD error callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD Abort Complete callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_AbortCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD Abort Complete callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_AbortTransmitCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_AbortTransmitCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD Abort Receive Complete callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_AbortReceiveCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_AbortReceiveCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup SMARTCARD_Exported_Functions_Group4 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 return the State of SmartCard + handle and also return Peripheral Errors occurred during communication process + (+) HAL_SMARTCARD_GetState() API can be helpful to check in run-time the state + of the SMARTCARD peripheral. + (+) HAL_SMARTCARD_GetError() checks in run-time errors that could occur during + communication. + +@endverbatim + * @{ + */ + +/** + * @brief Return the SMARTCARD handle state. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval SMARTCARD handle state + */ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(const SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Return SMARTCARD handle state */ + uint32_t temp1; + uint32_t temp2; + temp1 = (uint32_t)hsmartcard->gState; + temp2 = (uint32_t)hsmartcard->RxState; + + return (HAL_SMARTCARD_StateTypeDef)(temp1 | temp2); +} + +/** + * @brief Return the SMARTCARD handle error code. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval SMARTCARD handle Error Code + */ +uint32_t HAL_SMARTCARD_GetError(const SMARTCARD_HandleTypeDef *hsmartcard) +{ + return hsmartcard->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions + * @{ + */ + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) +/** + * @brief Initialize the callbacks to their default values. + * @param hsmartcard SMARTCARD handle. + * @retval none + */ +void SMARTCARD_InitCallbacksToDefault(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Init the SMARTCARD Callback settings */ + hsmartcard->TxCpltCallback = HAL_SMARTCARD_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hsmartcard->RxCpltCallback = HAL_SMARTCARD_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hsmartcard->ErrorCallback = HAL_SMARTCARD_ErrorCallback; /* Legacy weak ErrorCallback */ + hsmartcard->AbortCpltCallback = HAL_SMARTCARD_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hsmartcard->AbortTransmitCpltCallback = HAL_SMARTCARD_AbortTransmitCpltCallback; /* Legacy weak + AbortTransmitCpltCallback */ + hsmartcard->AbortReceiveCpltCallback = HAL_SMARTCARD_AbortReceiveCpltCallback; /* Legacy weak + AbortReceiveCpltCallback */ + hsmartcard->RxFifoFullCallback = HAL_SMARTCARDEx_RxFifoFullCallback; /* Legacy weak + RxFifoFullCallback */ + hsmartcard->TxFifoEmptyCallback = HAL_SMARTCARDEx_TxFifoEmptyCallback; /* Legacy weak + TxFifoEmptyCallback */ + +} +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACKS */ + +/** + * @brief Configure the SMARTCARD associated USART peripheral. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t tmpreg; + SMARTCARD_ClockSourceTypeDef clocksource; + HAL_StatusTypeDef ret = HAL_OK; + static const uint16_t SMARTCARDPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; + uint32_t pclk; + + /* Check the parameters */ + assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); + assert_param(IS_SMARTCARD_BAUDRATE(hsmartcard->Init.BaudRate)); + assert_param(IS_SMARTCARD_WORD_LENGTH(hsmartcard->Init.WordLength)); + assert_param(IS_SMARTCARD_STOPBITS(hsmartcard->Init.StopBits)); + assert_param(IS_SMARTCARD_PARITY(hsmartcard->Init.Parity)); + assert_param(IS_SMARTCARD_MODE(hsmartcard->Init.Mode)); + assert_param(IS_SMARTCARD_POLARITY(hsmartcard->Init.CLKPolarity)); + assert_param(IS_SMARTCARD_PHASE(hsmartcard->Init.CLKPhase)); + assert_param(IS_SMARTCARD_LASTBIT(hsmartcard->Init.CLKLastBit)); + assert_param(IS_SMARTCARD_ONE_BIT_SAMPLE(hsmartcard->Init.OneBitSampling)); + assert_param(IS_SMARTCARD_NACK(hsmartcard->Init.NACKEnable)); + assert_param(IS_SMARTCARD_TIMEOUT(hsmartcard->Init.TimeOutEnable)); + assert_param(IS_SMARTCARD_AUTORETRY_COUNT(hsmartcard->Init.AutoRetryCount)); + assert_param(IS_SMARTCARD_CLOCKPRESCALER(hsmartcard->Init.ClockPrescaler)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* In SmartCard mode, M and PCE are forced to 1 (8 bits + parity). + * Oversampling is forced to 16 (OVER8 = 0). + * Configure the Parity and Mode: + * set PS bit according to hsmartcard->Init.Parity value + * set TE and RE bits according to hsmartcard->Init.Mode value */ + tmpreg = (((uint32_t)hsmartcard->Init.Parity) | ((uint32_t)hsmartcard->Init.Mode) | + ((uint32_t)hsmartcard->Init.WordLength)); + MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR2 Configuration -----------------------*/ + tmpreg = hsmartcard->Init.StopBits; + /* Synchronous mode is activated by default */ + tmpreg |= (uint32_t) USART_CR2_CLKEN | hsmartcard->Init.CLKPolarity; + tmpreg |= (uint32_t) hsmartcard->Init.CLKPhase | hsmartcard->Init.CLKLastBit; + tmpreg |= (uint32_t) hsmartcard->Init.TimeOutEnable; + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* Configure + * - one-bit sampling method versus three samples' majority rule + * according to hsmartcard->Init.OneBitSampling + * - NACK transmission in case of parity error according + * to hsmartcard->Init.NACKEnable + * - autoretry counter according to hsmartcard->Init.AutoRetryCount */ + + tmpreg = (uint32_t) hsmartcard->Init.OneBitSampling | hsmartcard->Init.NACKEnable; + tmpreg |= ((uint32_t)hsmartcard->Init.AutoRetryCount << USART_CR3_SCARCNT_Pos); + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_FIELDS, tmpreg); + + /*--------------------- SMARTCARD clock PRESC Configuration ----------------*/ + /* Configure + * - SMARTCARD Clock Prescaler: set PRESCALER according to hsmartcard->Init.ClockPrescaler value */ + MODIFY_REG(hsmartcard->Instance->PRESC, USART_PRESC_PRESCALER, hsmartcard->Init.ClockPrescaler); + + /*-------------------------- USART GTPR Configuration ----------------------*/ + tmpreg = (hsmartcard->Init.Prescaler | ((uint32_t)hsmartcard->Init.GuardTime << USART_GTPR_GT_Pos)); + MODIFY_REG(hsmartcard->Instance->GTPR, (uint16_t)(USART_GTPR_GT | USART_GTPR_PSC), (uint16_t)tmpreg); + + /*-------------------------- USART RTOR Configuration ----------------------*/ + tmpreg = ((uint32_t)hsmartcard->Init.BlockLength << USART_RTOR_BLEN_Pos); + if (hsmartcard->Init.TimeOutEnable == SMARTCARD_TIMEOUT_ENABLE) + { + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); + tmpreg |= (uint32_t) hsmartcard->Init.TimeOutValue; + } + WRITE_REG(hsmartcard->Instance->RTOR, tmpreg); + + /*-------------------------- USART BRR Configuration -----------------------*/ + SMARTCARD_GETCLOCKSOURCE(hsmartcard, clocksource); + tmpreg = 0U; + switch (clocksource) + { + case SMARTCARD_CLOCKSOURCE_PCLK1: + pclk = HAL_RCC_GetPCLK1Freq(); + tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_PCLK2: + pclk = HAL_RCC_GetPCLK2Freq(); + tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_PLL2Q: + pclk = HAL_RCC_GetPLL2QFreq(); + tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_PLL3Q: + pclk = HAL_RCC_GetPLL3QFreq(); + tmpreg = (uint32_t)(((pclk / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_HSI: + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) + { + tmpreg = (uint32_t)((((HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)) / + SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + } + else + { + tmpreg = (uint32_t)(((HSI_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + } + break; + case SMARTCARD_CLOCKSOURCE_CSI: + tmpreg = (uint32_t)(((CSI_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_LSE: + tmpreg = (uint32_t)(((uint16_t)(LSE_VALUE / SMARTCARDPrescTable[hsmartcard->Init.ClockPrescaler]) + + (hsmartcard->Init.BaudRate / 2U)) / hsmartcard->Init.BaudRate); + break; + default: + ret = HAL_ERROR; + break; + } + + /* USARTDIV must be greater than or equal to 0d16 */ + if ((tmpreg >= USART_BRR_MIN) && (tmpreg <= USART_BRR_MAX)) + { + hsmartcard->Instance->BRR = (uint16_t)tmpreg; + } + else + { + ret = HAL_ERROR; + } + + /* Initialize the number of data to process during RX/TX ISR execution */ + hsmartcard->NbTxDataToProcess = 1U; + hsmartcard->NbRxDataToProcess = 1U; + + /* Clear ISR function pointers */ + hsmartcard->RxISR = NULL; + hsmartcard->TxISR = NULL; + + return ret; +} + + +/** + * @brief Configure the SMARTCARD associated USART peripheral advanced features. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check whether the set of advanced features to configure is properly set */ + assert_param(IS_SMARTCARD_ADVFEATURE_INIT(hsmartcard->AdvancedInit.AdvFeatureInit)); + + /* if required, configure TX pin active level inversion */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_TXINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_TXINV(hsmartcard->AdvancedInit.TxPinLevelInvert)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_TXINV, hsmartcard->AdvancedInit.TxPinLevelInvert); + } + + /* if required, configure RX pin active level inversion */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_RXINV(hsmartcard->AdvancedInit.RxPinLevelInvert)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_RXINV, hsmartcard->AdvancedInit.RxPinLevelInvert); + } + + /* if required, configure data inversion */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DATAINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_DATAINV(hsmartcard->AdvancedInit.DataInvert)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_DATAINV, hsmartcard->AdvancedInit.DataInvert); + } + + /* if required, configure RX/TX pins swap */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_SWAP_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_SWAP(hsmartcard->AdvancedInit.Swap)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_SWAP, hsmartcard->AdvancedInit.Swap); + } + + /* if required, configure RX overrun detection disabling */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT)) + { + assert_param(IS_SMARTCARD_OVERRUN(hsmartcard->AdvancedInit.OverrunDisable)); + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_OVRDIS, hsmartcard->AdvancedInit.OverrunDisable); + } + + /* if required, configure DMA disabling on reception error */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(hsmartcard->AdvancedInit.DMADisableonRxError)); + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_DDRE, hsmartcard->AdvancedInit.DMADisableonRxError); + } + + /* if required, configure MSB first on communication line */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_MSBFIRST(hsmartcard->AdvancedInit.MSBFirst)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_MSBFIRST, hsmartcard->AdvancedInit.MSBFirst); + } + +} + +/** + * @brief Check the SMARTCARD Idle State. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t tickstart; + + /* Initialize the SMARTCARD ErrorCode */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check if the Transmitter is enabled */ + if ((hsmartcard->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_TEACK, RESET, tickstart, + SMARTCARD_TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if ((hsmartcard->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if (SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_REACK, RESET, tickstart, + SMARTCARD_TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + + /* Initialize the SMARTCARD states */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief Handle SMARTCARD Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param Flag Specifies the SMARTCARD flag to check. + * @param Status The actual Flag status (SET or RESET). + * @param Tickstart Tick start value + * @param Timeout Timeout duration. + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, + FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__HAL_SMARTCARD_GET_FLAG(hsmartcard, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) + interrupts for the interrupt process */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + + +/** + * @brief End ongoing Tx transfer on SMARTCARD peripheral (following error detection or Transmit completion). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable TXEIE, TCIE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* At end of Tx process, restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; +} + + +/** + * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* At end of Rx process, restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; +} + + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief DMA SMARTCARD transmit process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + hsmartcard->TxXferCount = 0U; + + /* Disable the DMA transfer for transmit request by resetting the DMAT bit + in the SMARTCARD associated USART CR3 register */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAT); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); +} + +/** + * @brief DMA SMARTCARD receive process complete callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + hsmartcard->RxXferCount = 0U; + + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + + /* Disable the DMA transfer for the receiver request by resetting the DMAR bit + in the SMARTCARD associated USART CR3 register */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_DMAR); + + /* At end of Rx process, restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hsmartcard->RxCpltCallback(hsmartcard); +#else + /* Call legacy weak Rx complete callback */ + HAL_SMARTCARD_RxCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD communication error callback. + * @param hdma Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + + /* Stop SMARTCARD DMA Tx request if ongoing */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) + { + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAT)) + { + hsmartcard->TxXferCount = 0U; + SMARTCARD_EndTxTransfer(hsmartcard); + } + } + + /* Stop SMARTCARD DMA Rx request if ongoing */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_BUSY_RX) + { + if (HAL_IS_BIT_SET(hsmartcard->Instance->CR3, USART_CR3_DMAR)) + { + hsmartcard->RxXferCount = 0U; + SMARTCARD_EndRxTransfer(hsmartcard); + } + } + + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_DMA; +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD communication abort callback, when initiated by HAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + hsmartcard->RxXferCount = 0U; + hsmartcard->TxXferCount = 0U; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered user error callback */ + hsmartcard->ErrorCallback(hsmartcard); +#else + /* Call legacy weak user error callback */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + + hsmartcard->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hsmartcard->hdmarx != NULL) + { + if (hsmartcard->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hsmartcard->TxXferCount = 0U; + hsmartcard->RxXferCount = 0U; + + /* Reset errorCode */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | + SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hsmartcard->AbortCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort complete callback */ + HAL_SMARTCARD_AbortCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + + +/** + * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + + hsmartcard->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hsmartcard->hdmatx != NULL) + { + if (hsmartcard->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + hsmartcard->TxXferCount = 0U; + hsmartcard->RxXferCount = 0U; + + /* Reset errorCode */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | + SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->gState and hsmartcard->RxState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + hsmartcard->AbortCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort complete callback */ + HAL_SMARTCARD_AbortCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + + +/** + * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user by a call to + * HAL_SMARTCARD_AbortTransmit_IT API (Abort only Tx transfer) + * (This callback is executed at end of DMA Tx Abort procedure following user abort request, + * and leads to user Tx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + + hsmartcard->TxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, SMARTCARD_CLEAR_FEF); + + /* Restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + hsmartcard->AbortTransmitCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_SMARTCARD_AbortTransmitCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user by a call to + * HAL_SMARTCARD_AbortReceive_IT API (Abort only Rx transfer) + * (This callback is executed at end of DMA Rx Abort procedure following user abort request, + * and leads to user Rx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef *hsmartcard = (SMARTCARD_HandleTypeDef *)(hdma->Parent); + + hsmartcard->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_SMARTCARD_CLEAR_FLAG(hsmartcard, + SMARTCARD_CLEAR_OREF | SMARTCARD_CLEAR_NEF | SMARTCARD_CLEAR_PEF | SMARTCARD_CLEAR_FEF | + SMARTCARD_CLEAR_RTOF | SMARTCARD_CLEAR_EOBF); + + /* Restore hsmartcard->RxState to Ready */ + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + hsmartcard->AbortReceiveCpltCallback(hsmartcard); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_SMARTCARD_AbortReceiveCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Send an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() + * and when the FIFO mode is disabled. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_TxISR(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check that a Tx process is ongoing */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) + { + if (hsmartcard->TxXferCount == 0U) + { + /* Disable the SMARTCARD Transmit Data Register Empty Interrupt */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); + } + else + { + hsmartcard->Instance->TDR = (uint8_t)(*hsmartcard->pTxBuffPtr & 0xFFU); + hsmartcard->pTxBuffPtr++; + hsmartcard->TxXferCount--; + } + } +} + +/** + * @brief Send an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() + * and when the FIFO mode is enabled. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_TxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint16_t nb_tx_data; + + /* Check that a Tx process is ongoing */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_BUSY_TX) + { + for (nb_tx_data = hsmartcard->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) + { + if (hsmartcard->TxXferCount == 0U) + { + /* Disable the SMARTCARD Transmit Data Register Empty Interrupt */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); + } + else if (READ_BIT(hsmartcard->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) + { + hsmartcard->Instance->TDR = (uint8_t)(*hsmartcard->pTxBuffPtr & 0xFFU); + hsmartcard->pTxBuffPtr++; + hsmartcard->TxXferCount--; + } + else + { + /* Nothing to do */ + } + } + } +} + +/** + * @brief Wrap up transmission in non-blocking mode. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Disable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, hsmartcard->AdvancedInit.TxCompletionIndication); + + /* Check if a receive process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + + /* Disable the Peripheral first to update mode */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) + && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + /* In case of TX only mode, if NACK is enabled, receiver block has been enabled + for Transmit phase. Disable this receiver block. */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RE); + } + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX_RX) + || (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLE)) + { + /* Perform a TX FIFO Flush at end of Tx phase, as all sent bytes are appearing in Rx Data register */ + __HAL_SMARTCARD_FLUSH_DRREGISTER(hsmartcard); + } + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_UE); + + /* Tx process is ended, restore hsmartcard->gState to Ready */ + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Clear TxISR function pointer */ + hsmartcard->TxISR = NULL; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Tx complete callback */ + hsmartcard->TxCpltCallback(hsmartcard); +#else + /* Call legacy weak Tx complete callback */ + HAL_SMARTCARD_TxCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ +} + +/** + * @brief Receive an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Receive_IT() + * and when the FIFO mode is disabled. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_RxISR(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check that a Rx process is ongoing */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_BUSY_RX) + { + *hsmartcard->pRxBuffPtr = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0xFF); + hsmartcard->pRxBuffPtr++; + + hsmartcard->RxXferCount--; + if (hsmartcard->RxXferCount == 0U) + { + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + + /* Check if a transmit process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + + /* Disable the SMARTCARD Parity Error Interrupt */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); + + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* Clear RxISR function pointer */ + hsmartcard->RxISR = NULL; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hsmartcard->RxCpltCallback(hsmartcard); +#else + /* Call legacy weak Rx complete callback */ + HAL_SMARTCARD_RxCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_SMARTCARD_SEND_REQ(hsmartcard, SMARTCARD_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @brief Receive an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Receive_IT() + * and when the FIFO mode is enabled. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +static void SMARTCARD_RxISR_FIFOEN(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint16_t nb_rx_data; + uint16_t rxdatacount; + + /* Check that a Rx process is ongoing */ + if (hsmartcard->RxState == HAL_SMARTCARD_STATE_BUSY_RX) + { + for (nb_rx_data = hsmartcard->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) + { + *hsmartcard->pRxBuffPtr = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0xFF); + hsmartcard->pRxBuffPtr++; + + hsmartcard->RxXferCount--; + if (hsmartcard->RxXferCount == 0U) + { + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + + /* Check if a transmit process is ongoing or not. If not disable ERR IT */ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); + } + + /* Disable the SMARTCARD Parity Error Interrupt */ + CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_PEIE); + + hsmartcard->RxState = HAL_SMARTCARD_STATE_READY; + + /* Clear RxISR function pointer */ + hsmartcard->RxISR = NULL; + +#if (USE_HAL_SMARTCARD_REGISTER_CALLBACKS == 1) + /* Call registered Rx complete callback */ + hsmartcard->RxCpltCallback(hsmartcard); +#else + /* Call legacy weak Rx complete callback */ + HAL_SMARTCARD_RxCpltCallback(hsmartcard); +#endif /* USE_HAL_SMARTCARD_REGISTER_CALLBACK */ + } + } + + /* When remaining number of bytes to receive is less than the RX FIFO + threshold, next incoming frames are processed as if FIFO mode was + disabled (i.e. one interrupt per received frame). + */ + rxdatacount = hsmartcard->RxXferCount; + if (((rxdatacount != 0U)) && (rxdatacount < hsmartcard->NbRxDataToProcess)) + { + /* Disable the UART RXFT interrupt*/ + CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_RXFTIE); + + /* Update the RxISR function pointer */ + hsmartcard->RxISR = SMARTCARD_RxISR; + + /* Enable the UART Data Register Not Empty interrupt */ + SET_BIT(hsmartcard->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_SMARTCARD_SEND_REQ(hsmartcard, SMARTCARD_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @} + */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard_ex.c index 2cdc8b016..f9225fc00 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smartcard_ex.c @@ -1,495 +1,494 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_smartcard_ex.c - * @author MCD Application Team - * @brief SMARTCARD HAL module driver. - * This file provides extended firmware functions to manage the following - * functionalities of the SmartCard. - * + Initialization and de-initialization functions - * + Peripheral Control functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================= - ##### SMARTCARD peripheral extended features ##### - ============================================================================= - [..] - The Extended SMARTCARD HAL driver can be used as follows: - - (#) After having configured the SMARTCARD basic features with HAL_SMARTCARD_Init(), - then program SMARTCARD advanced features if required (TX/RX pins swap, TimeOut, - auto-retry counter,...) in the hsmartcard AdvancedInit structure. - - (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. - - -@- When SMARTCARD operates in FIFO mode, FIFO mode must be enabled prior - starting RX/TX transfers. Also RX/TX FIFO thresholds must be - configured prior starting RX/TX transfers. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SMARTCARDEx SMARTCARDEx - * @brief SMARTCARD Extended HAL module driver - * @{ - */ -#ifdef HAL_SMARTCARD_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup SMARTCARDEx_Private_Constants SMARTCARD Extended Private Constants - * @{ - */ -/* UART RX FIFO depth */ -#define RX_FIFO_DEPTH 16U - -/* UART TX FIFO depth */ -#define TX_FIFO_DEPTH 16U -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -static void SMARTCARDEx_SetNbDataToProcess(SMARTCARD_HandleTypeDef *hsmartcard); - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup SMARTCARDEx_Exported_Functions SMARTCARD Extended Exported Functions - * @{ - */ - -/** @defgroup SMARTCARDEx_Exported_Functions_Group1 Extended Peripheral Control functions - * @brief Extended control functions - * -@verbatim - =============================================================================== - ##### Peripheral Control functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to initialize the SMARTCARD. - (+) HAL_SMARTCARDEx_BlockLength_Config() API allows to configure the Block Length on the fly - (+) HAL_SMARTCARDEx_TimeOut_Config() API allows to configure the receiver timeout value on the fly - (+) HAL_SMARTCARDEx_EnableReceiverTimeOut() API enables the receiver timeout feature - (+) HAL_SMARTCARDEx_DisableReceiverTimeOut() API disables the receiver timeout feature - -@endverbatim - * @{ - */ - -/** @brief Update on the fly the SMARTCARD block length in RTOR register. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @param BlockLength SMARTCARD block length (8-bit long at most) - * @retval None - */ -void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t BlockLength) -{ - MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_BLEN, ((uint32_t)BlockLength << USART_RTOR_BLEN_Pos)); -} - -/** @brief Update on the fly the receiver timeout value in RTOR register. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @param TimeOutValue receiver timeout value in number of baud blocks. The timeout - * value must be less or equal to 0x0FFFFFFFF. - * @retval None - */ -void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t TimeOutValue) -{ - assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); - MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_RTO, TimeOutValue); -} - -/** @brief Enable the SMARTCARD receiver timeout feature. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) -{ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Set the USART RTOEN bit */ - SET_BIT(hsmartcard->Instance->CR2, USART_CR2_RTOEN); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** @brief Disable the SMARTCARD receiver timeout feature. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) -{ - if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Clear the USART RTOEN bit */ - CLEAR_BIT(hsmartcard->Instance->CR2, USART_CR2_RTOEN); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @} - */ - -/** @defgroup SMARTCARDEx_Exported_Functions_Group2 Extended Peripheral IO operation functions - * @brief SMARTCARD Transmit and Receive functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of FIFO mode related callback functions. - - (#) TX/RX Fifos Callbacks: - (++) HAL_SMARTCARDEx_RxFifoFullCallback() - (++) HAL_SMARTCARDEx_TxFifoEmptyCallback() - -@endverbatim - * @{ - */ - -/** - * @brief SMARTCARD RX Fifo full callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARDEx_RxFifoFullCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARDEx_RxFifoFullCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD TX Fifo empty callback. - * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARDEx_TxFifoEmptyCallback(SMARTCARD_HandleTypeDef *hsmartcard) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmartcard); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARDEx_TxFifoEmptyCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup SMARTCARDEx_Exported_Functions_Group3 Extended Peripheral FIFO Control functions - * @brief SMARTCARD control functions - * -@verbatim - =============================================================================== - ##### Peripheral FIFO Control functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to control the SMARTCARD - FIFO feature. - (+) HAL_SMARTCARDEx_EnableFifoMode() API enables the FIFO mode - (+) HAL_SMARTCARDEx_DisableFifoMode() API disables the FIFO mode - (+) HAL_SMARTCARDEx_SetTxFifoThreshold() API sets the TX FIFO threshold - (+) HAL_SMARTCARDEx_SetRxFifoThreshold() API sets the RX FIFO threshold -@endverbatim - * @{ - */ - -/** - * @brief Enable the FIFO mode. - * @param hsmartcard SMARTCARD handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARDEx_EnableFifoMode(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Save actual SMARTCARD configuration */ - tmpcr1 = READ_REG(hsmartcard->Instance->CR1); - - /* Disable SMARTCARD */ - __HAL_SMARTCARD_DISABLE(hsmartcard); - - /* Enable FIFO mode */ - SET_BIT(tmpcr1, USART_CR1_FIFOEN); - hsmartcard->FifoMode = SMARTCARD_FIFOMODE_ENABLE; - - /* Restore SMARTCARD configuration */ - WRITE_REG(hsmartcard->Instance->CR1, tmpcr1); - - /* Determine the number of data to process during RX/TX ISR execution */ - SMARTCARDEx_SetNbDataToProcess(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; -} - -/** - * @brief Disable the FIFO mode. - * @param hsmartcard SMARTCARD handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARDEx_DisableFifoMode(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Save actual SMARTCARD configuration */ - tmpcr1 = READ_REG(hsmartcard->Instance->CR1); - - /* Disable SMARTCARD */ - __HAL_SMARTCARD_DISABLE(hsmartcard); - - /* Enable FIFO mode */ - CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); - hsmartcard->FifoMode = SMARTCARD_FIFOMODE_DISABLE; - - /* Restore SMARTCARD configuration */ - WRITE_REG(hsmartcard->Instance->CR1, tmpcr1); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; -} - -/** - * @brief Set the TXFIFO threshold. - * @param hsmartcard SMARTCARD handle. - * @param Threshold TX FIFO threshold value - * This parameter can be one of the following values: - * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_1_8 - * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_1_4 - * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_1_2 - * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_3_4 - * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_7_8 - * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_8_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARDEx_SetTxFifoThreshold(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Threshold) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); - assert_param(IS_SMARTCARD_TXFIFO_THRESHOLD(Threshold)); - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Save actual SMARTCARD configuration */ - tmpcr1 = READ_REG(hsmartcard->Instance->CR1); - - /* Disable SMARTCARD */ - __HAL_SMARTCARD_DISABLE(hsmartcard); - - /* Update TX threshold configuration */ - MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_TXFTCFG, Threshold); - - /* Determine the number of data to process during RX/TX ISR execution */ - SMARTCARDEx_SetNbDataToProcess(hsmartcard); - - /* Restore SMARTCARD configuration */ - MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_UE, tmpcr1); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; -} - -/** - * @brief Set the RXFIFO threshold. - * @param hsmartcard SMARTCARD handle. - * @param Threshold RX FIFO threshold value - * This parameter can be one of the following values: - * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_1_8 - * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_1_4 - * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_1_2 - * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_3_4 - * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_7_8 - * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_8_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMARTCARDEx_SetRxFifoThreshold(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Threshold) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); - assert_param(IS_SMARTCARD_RXFIFO_THRESHOLD(Threshold)); - - /* Process Locked */ - __HAL_LOCK(hsmartcard); - - hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; - - /* Save actual SMARTCARD configuration */ - tmpcr1 = READ_REG(hsmartcard->Instance->CR1); - - /* Disable SMARTCARD */ - __HAL_SMARTCARD_DISABLE(hsmartcard); - - /* Update RX threshold configuration */ - MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_RXFTCFG, Threshold); - - /* Determine the number of data to process during RX/TX ISR execution */ - SMARTCARDEx_SetNbDataToProcess(hsmartcard); - - /* Restore SMARTCARD configuration */ - MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_UE, tmpcr1); - - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmartcard); - - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup SMARTCARDEx_Private_Functions SMARTCARD Extended Private Functions - * @{ - */ - -/** - * @brief Calculate the number of data to process in RX/TX ISR. - * @note The RX FIFO depth and the TX FIFO depth is extracted from - * the USART configuration registers. - * @param hsmartcard SMARTCARD handle. - * @retval None - */ -static void SMARTCARDEx_SetNbDataToProcess(SMARTCARD_HandleTypeDef *hsmartcard) -{ - uint8_t rx_fifo_depth; - uint8_t tx_fifo_depth; - uint8_t rx_fifo_threshold; - uint8_t tx_fifo_threshold; - /* 2 0U/1U added for MISRAC2012-Rule-18.1_b and MISRAC2012-Rule-18.1_d */ - static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; - static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; - - if (hsmartcard->FifoMode == SMARTCARD_FIFOMODE_DISABLE) - { - hsmartcard->NbTxDataToProcess = 1U; - hsmartcard->NbRxDataToProcess = 1U; - } - else - { - rx_fifo_depth = RX_FIFO_DEPTH; - tx_fifo_depth = TX_FIFO_DEPTH; - rx_fifo_threshold = (uint8_t)(READ_BIT(hsmartcard->Instance->CR3, USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos); - tx_fifo_threshold = (uint8_t)(READ_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos); - hsmartcard->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / \ - (uint16_t)denominator[tx_fifo_threshold]; - hsmartcard->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / \ - (uint16_t)denominator[rx_fifo_threshold]; - } -} - -/** - * @} - */ - -#endif /* HAL_SMARTCARD_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_smartcard_ex.c + * @author MCD Application Team + * @brief SMARTCARD HAL module driver. + * This file provides extended firmware functions to manage the following + * functionalities of the SmartCard. + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================= + ##### SMARTCARD peripheral extended features ##### + ============================================================================= + [..] + The Extended SMARTCARD HAL driver can be used as follows: + + (#) After having configured the SMARTCARD basic features with HAL_SMARTCARD_Init(), + then program SMARTCARD advanced features if required (TX/RX pins swap, TimeOut, + auto-retry counter,...) in the hsmartcard AdvancedInit structure. + + (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. + + -@- When SMARTCARD operates in FIFO mode, FIFO mode must be enabled prior + starting RX/TX transfers. Also RX/TX FIFO thresholds must be + configured prior starting RX/TX transfers. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARDEx SMARTCARDEx + * @brief SMARTCARD Extended HAL module driver + * @{ + */ +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup SMARTCARDEx_Private_Constants SMARTCARD Extended Private Constants + * @{ + */ +/* UART RX FIFO depth */ +#define RX_FIFO_DEPTH 16U + +/* UART TX FIFO depth */ +#define TX_FIFO_DEPTH 16U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SMARTCARDEx_SetNbDataToProcess(SMARTCARD_HandleTypeDef *hsmartcard); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SMARTCARDEx_Exported_Functions SMARTCARD Extended Exported Functions + * @{ + */ + +/** @defgroup SMARTCARDEx_Exported_Functions_Group1 Extended Peripheral Control functions + * @brief Extended control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the SMARTCARD. + (+) HAL_SMARTCARDEx_BlockLength_Config() API allows to configure the Block Length on the fly + (+) HAL_SMARTCARDEx_TimeOut_Config() API allows to configure the receiver timeout value on the fly + (+) HAL_SMARTCARDEx_EnableReceiverTimeOut() API enables the receiver timeout feature + (+) HAL_SMARTCARDEx_DisableReceiverTimeOut() API disables the receiver timeout feature + +@endverbatim + * @{ + */ + +/** @brief Update on the fly the SMARTCARD block length in RTOR register. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param BlockLength SMARTCARD block length (8-bit long at most) + * @retval None + */ +void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t BlockLength) +{ + MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_BLEN, ((uint32_t)BlockLength << USART_RTOR_BLEN_Pos)); +} + +/** @brief Update on the fly the receiver timeout value in RTOR register. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param TimeOutValue receiver timeout value in number of baud blocks. The timeout + * value must be less or equal to 0x0FFFFFFFF. + * @retval None + */ +void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t TimeOutValue) +{ + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); + MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_RTO, TimeOutValue); +} + +/** @brief Enable the SMARTCARD receiver timeout feature. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) +{ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Set the USART RTOEN bit */ + SET_BIT(hsmartcard->Instance->CR2, USART_CR2_RTOEN); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** @brief Disable the SMARTCARD receiver timeout feature. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) +{ + if (hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Clear the USART RTOEN bit */ + CLEAR_BIT(hsmartcard->Instance->CR2, USART_CR2_RTOEN); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup SMARTCARDEx_Exported_Functions_Group2 Extended Peripheral IO operation functions + * @brief SMARTCARD Transmit and Receive functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of FIFO mode related callback functions. + + (#) TX/RX Fifos Callbacks: + (++) HAL_SMARTCARDEx_RxFifoFullCallback() + (++) HAL_SMARTCARDEx_TxFifoEmptyCallback() + +@endverbatim + * @{ + */ + +/** + * @brief SMARTCARD RX Fifo full callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARDEx_RxFifoFullCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARDEx_RxFifoFullCallback can be implemented in the user file. + */ +} + +/** + * @brief SMARTCARD TX Fifo empty callback. + * @param hsmartcard Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARDEx_TxFifoEmptyCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmartcard); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARDEx_TxFifoEmptyCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup SMARTCARDEx_Exported_Functions_Group3 Extended Peripheral FIFO Control functions + * @brief SMARTCARD control functions + * +@verbatim + =============================================================================== + ##### Peripheral FIFO Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SMARTCARD + FIFO feature. + (+) HAL_SMARTCARDEx_EnableFifoMode() API enables the FIFO mode + (+) HAL_SMARTCARDEx_DisableFifoMode() API disables the FIFO mode + (+) HAL_SMARTCARDEx_SetTxFifoThreshold() API sets the TX FIFO threshold + (+) HAL_SMARTCARDEx_SetRxFifoThreshold() API sets the RX FIFO threshold +@endverbatim + * @{ + */ + +/** + * @brief Enable the FIFO mode. + * @param hsmartcard SMARTCARD handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableFifoMode(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Save actual SMARTCARD configuration */ + tmpcr1 = READ_REG(hsmartcard->Instance->CR1); + + /* Disable SMARTCARD */ + __HAL_SMARTCARD_DISABLE(hsmartcard); + + /* Enable FIFO mode */ + SET_BIT(tmpcr1, USART_CR1_FIFOEN); + hsmartcard->FifoMode = SMARTCARD_FIFOMODE_ENABLE; + + /* Restore SMARTCARD configuration */ + WRITE_REG(hsmartcard->Instance->CR1, tmpcr1); + + /* Determine the number of data to process during RX/TX ISR execution */ + SMARTCARDEx_SetNbDataToProcess(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief Disable the FIFO mode. + * @param hsmartcard SMARTCARD handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableFifoMode(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Save actual SMARTCARD configuration */ + tmpcr1 = READ_REG(hsmartcard->Instance->CR1); + + /* Disable SMARTCARD */ + __HAL_SMARTCARD_DISABLE(hsmartcard); + + /* Enable FIFO mode */ + CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); + hsmartcard->FifoMode = SMARTCARD_FIFOMODE_DISABLE; + + /* Restore SMARTCARD configuration */ + WRITE_REG(hsmartcard->Instance->CR1, tmpcr1); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief Set the TXFIFO threshold. + * @param hsmartcard SMARTCARD handle. + * @param Threshold TX FIFO threshold value + * This parameter can be one of the following values: + * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_1_8 + * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_1_4 + * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_1_2 + * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_3_4 + * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_7_8 + * @arg @ref SMARTCARD_TXFIFO_THRESHOLD_8_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_SetTxFifoThreshold(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Threshold) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); + assert_param(IS_SMARTCARD_TXFIFO_THRESHOLD(Threshold)); + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Save actual SMARTCARD configuration */ + tmpcr1 = READ_REG(hsmartcard->Instance->CR1); + + /* Disable SMARTCARD */ + __HAL_SMARTCARD_DISABLE(hsmartcard); + + /* Update TX threshold configuration */ + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_TXFTCFG, Threshold); + + /* Determine the number of data to process during RX/TX ISR execution */ + SMARTCARDEx_SetNbDataToProcess(hsmartcard); + + /* Restore SMARTCARD configuration */ + MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_UE, tmpcr1); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief Set the RXFIFO threshold. + * @param hsmartcard SMARTCARD handle. + * @param Threshold RX FIFO threshold value + * This parameter can be one of the following values: + * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_1_8 + * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_1_4 + * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_1_2 + * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_3_4 + * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_7_8 + * @arg @ref SMARTCARD_RXFIFO_THRESHOLD_8_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_SetRxFifoThreshold(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Threshold) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(hsmartcard->Instance)); + assert_param(IS_SMARTCARD_RXFIFO_THRESHOLD(Threshold)); + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Save actual SMARTCARD configuration */ + tmpcr1 = READ_REG(hsmartcard->Instance->CR1); + + /* Disable SMARTCARD */ + __HAL_SMARTCARD_DISABLE(hsmartcard); + + /* Update RX threshold configuration */ + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_RXFTCFG, Threshold); + + /* Determine the number of data to process during RX/TX ISR execution */ + SMARTCARDEx_SetNbDataToProcess(hsmartcard); + + /* Restore SMARTCARD configuration */ + MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_UE, tmpcr1); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup SMARTCARDEx_Private_Functions SMARTCARD Extended Private Functions + * @{ + */ + +/** + * @brief Calculate the number of data to process in RX/TX ISR. + * @note The RX FIFO depth and the TX FIFO depth is extracted from + * the USART configuration registers. + * @param hsmartcard SMARTCARD handle. + * @retval None + */ +static void SMARTCARDEx_SetNbDataToProcess(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint8_t rx_fifo_depth; + uint8_t tx_fifo_depth; + uint8_t rx_fifo_threshold; + uint8_t tx_fifo_threshold; + /* 2 0U/1U added for MISRAC2012-Rule-18.1_b and MISRAC2012-Rule-18.1_d */ + static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; + static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; + + if (hsmartcard->FifoMode == SMARTCARD_FIFOMODE_DISABLE) + { + hsmartcard->NbTxDataToProcess = 1U; + hsmartcard->NbRxDataToProcess = 1U; + } + else + { + rx_fifo_depth = RX_FIFO_DEPTH; + tx_fifo_depth = TX_FIFO_DEPTH; + rx_fifo_threshold = (uint8_t)(READ_BIT(hsmartcard->Instance->CR3, USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos); + tx_fifo_threshold = (uint8_t)(READ_BIT(hsmartcard->Instance->CR3, USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos); + hsmartcard->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / \ + (uint16_t)denominator[tx_fifo_threshold]; + hsmartcard->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / \ + (uint16_t)denominator[rx_fifo_threshold]; + } +} + +/** + * @} + */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus.c index 30c94955e..38f5e4ba4 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus.c @@ -1,2776 +1,2776 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_smbus.c - * @author MCD Application Team - * @brief SMBUS HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the System Management Bus (SMBus) peripheral, - * based on I2C principles of operation : - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State and Errors functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The SMBUS HAL driver can be used as follows: - - (#) Declare a SMBUS_HandleTypeDef handle structure, for example: - SMBUS_HandleTypeDef hsmbus; - - (#)Initialize the SMBUS low level resources by implementing the HAL_SMBUS_MspInit() API: - (##) Enable the SMBUSx interface clock - (##) SMBUS pins configuration - (+++) Enable the clock for the SMBUS GPIOs - (+++) Configure SMBUS pins as alternate function open-drain - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the SMBUSx interrupt priority - (+++) Enable the NVIC SMBUS IRQ Channel - - (#) Configure the Communication Clock Timing, Bus Timeout, Own Address1, Master Addressing mode, - Dual Addressing mode, Own Address2, Own Address2 Mask, General call, Nostretch mode, - Peripheral mode and Packet Error Check mode in the hsmbus Init structure. - - (#) Initialize the SMBUS registers by calling the HAL_SMBUS_Init() API: - (++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_SMBUS_MspInit(&hsmbus) API. - - (#) To check if target device is ready for communication, use the function HAL_SMBUS_IsDeviceReady() - - (#) For SMBUS IO operations, only one mode of operations is available within this driver - - *** Interrupt mode IO operation *** - =================================== - [..] - (+) Transmit in master/host SMBUS mode an amount of data in non-blocking mode - using HAL_SMBUS_Master_Transmit_IT() - (++) At transmission end of transfer HAL_SMBUS_MasterTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_SMBUS_MasterTxCpltCallback() - (+) Receive in master/host SMBUS mode an amount of data in non-blocking mode - using HAL_SMBUS_Master_Receive_IT() - (++) At reception end of transfer HAL_SMBUS_MasterRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_SMBUS_MasterRxCpltCallback() - (+) Abort a master/host SMBUS process communication with Interrupt using HAL_SMBUS_Master_Abort_IT() - (++) The associated previous transfer callback is called at the end of abort process - (++) mean HAL_SMBUS_MasterTxCpltCallback() in case of previous state was master transmit - (++) mean HAL_SMBUS_MasterRxCpltCallback() in case of previous state was master receive - (+) Enable/disable the Address listen mode in slave/device or host/slave SMBUS mode - using HAL_SMBUS_EnableListen_IT() HAL_SMBUS_DisableListen_IT() - (++) When address slave/device SMBUS match, HAL_SMBUS_AddrCallback() is executed and users can - add their own code to check the Address Match Code and the transmission direction - request by master/host (Write/Read). - (++) At Listen mode end HAL_SMBUS_ListenCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_SMBUS_ListenCpltCallback() - (+) Transmit in slave/device SMBUS mode an amount of data in non-blocking mode - using HAL_SMBUS_Slave_Transmit_IT() - (++) At transmission end of transfer HAL_SMBUS_SlaveTxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_SMBUS_SlaveTxCpltCallback() - (+) Receive in slave/device SMBUS mode an amount of data in non-blocking mode - using HAL_SMBUS_Slave_Receive_IT() - (++) At reception end of transfer HAL_SMBUS_SlaveRxCpltCallback() is executed and users can - add their own code by customization of function pointer HAL_SMBUS_SlaveRxCpltCallback() - (+) Enable/Disable the SMBUS alert mode using - HAL_SMBUS_EnableAlert_IT() or HAL_SMBUS_DisableAlert_IT() - (++) When SMBUS Alert is generated HAL_SMBUS_ErrorCallback() is executed and users can - add their own code by customization of function pointer HAL_SMBUS_ErrorCallback() - to check the Alert Error Code using function HAL_SMBUS_GetError() - (+) Get HAL state machine or error values using HAL_SMBUS_GetState() or HAL_SMBUS_GetError() - (+) In case of transfer Error, HAL_SMBUS_ErrorCallback() function is executed and users can - add their own code by customization of function pointer HAL_SMBUS_ErrorCallback() - to check the Error Code using function HAL_SMBUS_GetError() - - *** SMBUS HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in SMBUS HAL driver. - - (+) __HAL_SMBUS_ENABLE: Enable the SMBUS peripheral - (+) __HAL_SMBUS_DISABLE: Disable the SMBUS peripheral - (+) __HAL_SMBUS_GET_FLAG: Check whether the specified SMBUS flag is set or not - (+) __HAL_SMBUS_CLEAR_FLAG: Clear the specified SMBUS pending flag - (+) __HAL_SMBUS_ENABLE_IT: Enable the specified SMBUS interrupt - (+) __HAL_SMBUS_DISABLE_IT: Disable the specified SMBUS interrupt - - *** Callback registration *** - ============================================= - [..] - The compilation flag USE_HAL_SMBUS_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_SMBUS_RegisterCallback() or HAL_SMBUS_RegisterAddrCallback() - to register an interrupt callback. - [..] - Function HAL_SMBUS_RegisterCallback() allows to register following callbacks: - (+) MasterTxCpltCallback : callback for Master transmission end of transfer. - (+) MasterRxCpltCallback : callback for Master reception end of transfer. - (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. - (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. - (+) ListenCpltCallback : callback for end of listen mode. - (+) ErrorCallback : callback for error detection. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - [..] - For specific callback AddrCallback use dedicated register callbacks : HAL_SMBUS_RegisterAddrCallback. - [..] - Use function HAL_SMBUS_UnRegisterCallback to reset a callback to the default - weak function. - HAL_SMBUS_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) MasterTxCpltCallback : callback for Master transmission end of transfer. - (+) MasterRxCpltCallback : callback for Master reception end of transfer. - (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. - (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. - (+) ListenCpltCallback : callback for end of listen mode. - (+) ErrorCallback : callback for error detection. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - [..] - For callback AddrCallback use dedicated register callbacks : HAL_SMBUS_UnRegisterAddrCallback. - [..] - By default, after the HAL_SMBUS_Init() and when the state is HAL_I2C_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_SMBUS_MasterTxCpltCallback(), HAL_SMBUS_MasterRxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the HAL_SMBUS_Init()/ HAL_SMBUS_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the HAL_SMBUS_Init()/ HAL_SMBUS_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - [..] - Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using HAL_SMBUS_RegisterCallback() before calling HAL_SMBUS_DeInit() - or HAL_SMBUS_Init() function. - [..] - When the compilation flag USE_HAL_SMBUS_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - [..] - (@) You can refer to the SMBUS HAL driver header file for more useful macros - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SMBUS SMBUS - * @brief SMBUS HAL module driver - * @{ - */ - -#ifdef HAL_SMBUS_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup SMBUS_Private_Define SMBUS Private Constants - * @{ - */ -#define TIMING_CLEAR_MASK (0xF0FFFFFFUL) /*!< SMBUS TIMING clear register Mask */ -#define HAL_TIMEOUT_ADDR (10000U) /*!< 10 s */ -#define HAL_TIMEOUT_BUSY (25U) /*!< 25 ms */ -#define HAL_TIMEOUT_DIR (25U) /*!< 25 ms */ -#define HAL_TIMEOUT_RXNE (25U) /*!< 25 ms */ -#define HAL_TIMEOUT_STOPF (25U) /*!< 25 ms */ -#define HAL_TIMEOUT_TC (25U) /*!< 25 ms */ -#define HAL_TIMEOUT_TCR (25U) /*!< 25 ms */ -#define HAL_TIMEOUT_TXIS (25U) /*!< 25 ms */ -#define MAX_NBYTE_SIZE 255U -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SMBUS_Private_Functions SMBUS Private Functions - * @{ - */ -/* Private functions to handle flags during polling transfer */ -static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, - FlagStatus Status, uint32_t Timeout); - -/* Private functions for SMBUS transfer IRQ handler */ -static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags); -static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags); -static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus); - -/* Private functions to centralize the enable/disable of Interrupts */ -static void SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest); -static void SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest); - -/* Private function to flush TXDR register */ -static void SMBUS_Flush_TXDR(SMBUS_HandleTypeDef *hsmbus); - -/* Private function to handle start, restart or stop a transfer */ -static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, - uint32_t Mode, uint32_t Request); - -/* Private function to Convert Specific options */ -static void SMBUS_ConvertOtherXferOptions(SMBUS_HandleTypeDef *hsmbus); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup SMBUS_Exported_Functions SMBUS Exported Functions - * @{ - */ - -/** @defgroup SMBUS_Exported_Functions_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 - deinitialize the SMBUSx peripheral: - - (+) User must Implement HAL_SMBUS_MspInit() function in which he configures - all related peripherals resources (CLOCK, GPIO, IT and NVIC ). - - (+) Call the function HAL_SMBUS_Init() to configure the selected device with - the selected configuration: - (++) Clock Timing - (++) Bus Timeout - (++) Analog Filer mode - (++) Own Address 1 - (++) Addressing mode (Master, Slave) - (++) Dual Addressing mode - (++) Own Address 2 - (++) Own Address 2 Mask - (++) General call mode - (++) Nostretch mode - (++) Packet Error Check mode - (++) Peripheral mode - - - (+) Call the function HAL_SMBUS_DeInit() to restore the default configuration - of the selected SMBUSx peripheral. - - (+) Enable/Disable Analog/Digital filters with HAL_SMBUS_ConfigAnalogFilter() and - HAL_SMBUS_ConfigDigitalFilter(). - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the SMBUS according to the specified parameters - * in the SMBUS_InitTypeDef and initialize the associated handle. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus) -{ - /* Check the SMBUS handle allocation */ - if (hsmbus == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); - assert_param(IS_SMBUS_ANALOG_FILTER(hsmbus->Init.AnalogFilter)); - assert_param(IS_SMBUS_OWN_ADDRESS1(hsmbus->Init.OwnAddress1)); - assert_param(IS_SMBUS_ADDRESSING_MODE(hsmbus->Init.AddressingMode)); - assert_param(IS_SMBUS_DUAL_ADDRESS(hsmbus->Init.DualAddressMode)); - assert_param(IS_SMBUS_OWN_ADDRESS2(hsmbus->Init.OwnAddress2)); - assert_param(IS_SMBUS_OWN_ADDRESS2_MASK(hsmbus->Init.OwnAddress2Masks)); - assert_param(IS_SMBUS_GENERAL_CALL(hsmbus->Init.GeneralCallMode)); - assert_param(IS_SMBUS_NO_STRETCH(hsmbus->Init.NoStretchMode)); - assert_param(IS_SMBUS_PEC(hsmbus->Init.PacketErrorCheckMode)); - assert_param(IS_SMBUS_PERIPHERAL_MODE(hsmbus->Init.PeripheralMode)); - - if (hsmbus->State == HAL_SMBUS_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hsmbus->Lock = HAL_UNLOCKED; - -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterTxCpltCallback = HAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ - hsmbus->MasterRxCpltCallback = HAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ - hsmbus->SlaveTxCpltCallback = HAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ - hsmbus->SlaveRxCpltCallback = HAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ - hsmbus->ListenCpltCallback = HAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ - hsmbus->ErrorCallback = HAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ - hsmbus->AddrCallback = HAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ - - if (hsmbus->MspInitCallback == NULL) - { - hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - hsmbus->MspInitCallback(hsmbus); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - HAL_SMBUS_MspInit(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - /*---------------------------- SMBUSx TIMINGR Configuration ------------------------*/ - /* Configure SMBUSx: Frequency range */ - hsmbus->Instance->TIMINGR = hsmbus->Init.Timing & TIMING_CLEAR_MASK; - - /*---------------------------- SMBUSx TIMEOUTR Configuration ------------------------*/ - /* Configure SMBUSx: Bus Timeout */ - hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TIMOUTEN; - hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TEXTEN; - hsmbus->Instance->TIMEOUTR = hsmbus->Init.SMBusTimeout; - - /*---------------------------- SMBUSx OAR1 Configuration -----------------------*/ - /* Configure SMBUSx: Own Address1 and ack own address1 mode */ - hsmbus->Instance->OAR1 &= ~I2C_OAR1_OA1EN; - - if (hsmbus->Init.OwnAddress1 != 0UL) - { - if (hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_7BIT) - { - hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | hsmbus->Init.OwnAddress1); - } - } - - /*---------------------------- SMBUSx CR2 Configuration ------------------------*/ - /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process) */ - /* AUTOEND and NACK bit will be manage during Transfer process */ - hsmbus->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); - - /*---------------------------- SMBUSx OAR2 Configuration -----------------------*/ - /* Configure SMBUSx: Dual mode and Own Address2 */ - hsmbus->Instance->OAR2 = (hsmbus->Init.DualAddressMode | hsmbus->Init.OwnAddress2 | \ - (hsmbus->Init.OwnAddress2Masks << 8U)); - - /*---------------------------- SMBUSx CR1 Configuration ------------------------*/ - /* Configure SMBUSx: Generalcall and NoStretch mode */ - hsmbus->Instance->CR1 = (hsmbus->Init.GeneralCallMode | hsmbus->Init.NoStretchMode | \ - hsmbus->Init.PacketErrorCheckMode | hsmbus->Init.PeripheralMode | \ - hsmbus->Init.AnalogFilter); - - /* Enable Slave Byte Control only in case of Packet Error Check is enabled - and SMBUS Peripheral is set in Slave mode */ - if ((hsmbus->Init.PacketErrorCheckMode == SMBUS_PEC_ENABLE) && \ - ((hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ - (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP))) - { - hsmbus->Instance->CR1 |= I2C_CR1_SBC; - } - - /* Enable the selected SMBUS peripheral */ - __HAL_SMBUS_ENABLE(hsmbus); - - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - hsmbus->PreviousState = HAL_SMBUS_STATE_READY; - hsmbus->State = HAL_SMBUS_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitialize the SMBUS peripheral. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus) -{ - /* Check the SMBUS handle allocation */ - if (hsmbus == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the SMBUS Peripheral Clock */ - __HAL_SMBUS_DISABLE(hsmbus); - -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - if (hsmbus->MspDeInitCallback == NULL) - { - hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - hsmbus->MspDeInitCallback(hsmbus); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_SMBUS_MspDeInit(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - hsmbus->PreviousState = HAL_SMBUS_STATE_RESET; - hsmbus->State = HAL_SMBUS_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; -} - -/** - * @brief Initialize the SMBUS MSP. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitialize the SMBUS MSP. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_MspDeInit could be implemented in the user file - */ -} - -/** - * @brief Configure Analog noise filter. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param AnalogFilter This parameter can be one of the following values: - * @arg @ref SMBUS_ANALOGFILTER_ENABLE - * @arg @ref SMBUS_ANALOGFILTER_DISABLE - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_ConfigAnalogFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t AnalogFilter) -{ - /* Check the parameters */ - assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); - assert_param(IS_SMBUS_ANALOG_FILTER(AnalogFilter)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - /* Reset ANOFF bit */ - hsmbus->Instance->CR1 &= ~(I2C_CR1_ANFOFF); - - /* Set analog filter bit*/ - hsmbus->Instance->CR1 |= AnalogFilter; - - __HAL_SMBUS_ENABLE(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Configure Digital noise filter. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param DigitalFilter Coefficient of digital noise filter between Min_Data=0x00 and Max_Data=0x0F. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_ConfigDigitalFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t DigitalFilter) -{ - uint32_t tmpreg; - - /* Check the parameters */ - assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); - assert_param(IS_SMBUS_DIGITAL_FILTER(DigitalFilter)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - /* Get the old register value */ - tmpreg = hsmbus->Instance->CR1; - - /* Reset I2C DNF bits [11:8] */ - tmpreg &= ~(I2C_CR1_DNF); - - /* Set I2Cx DNF coefficient */ - tmpreg |= DigitalFilter << I2C_CR1_DNF_Pos; - - /* Store the new register value */ - hsmbus->Instance->CR1 = tmpreg; - - __HAL_SMBUS_ENABLE(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User SMBUS Callback - * To be used instead of the weak predefined callback - * @note The HAL_SMBUS_RegisterCallback() may be called before HAL_SMBUS_Init() in - * HAL_SMBUS_STATE_RESET to register callbacks for HAL_SMBUS_MSPINIT_CB_ID and - * HAL_SMBUS_MSPDEINIT_CB_ID. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID - * @arg @ref HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID - * @arg @ref HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID - * @arg @ref HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID - * @arg @ref HAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID - * @arg @ref HAL_SMBUS_ERROR_CB_ID Error callback ID - * @arg @ref HAL_SMBUS_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_RegisterCallback(SMBUS_HandleTypeDef *hsmbus, - HAL_SMBUS_CallbackIDTypeDef CallbackID, - pSMBUS_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (HAL_SMBUS_STATE_READY == hsmbus->State) - { - switch (CallbackID) - { - case HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : - hsmbus->MasterTxCpltCallback = pCallback; - break; - - case HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : - hsmbus->MasterRxCpltCallback = pCallback; - break; - - case HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : - hsmbus->SlaveTxCpltCallback = pCallback; - break; - - case HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : - hsmbus->SlaveRxCpltCallback = pCallback; - break; - - case HAL_SMBUS_LISTEN_COMPLETE_CB_ID : - hsmbus->ListenCpltCallback = pCallback; - break; - - case HAL_SMBUS_ERROR_CB_ID : - hsmbus->ErrorCallback = pCallback; - break; - - case HAL_SMBUS_MSPINIT_CB_ID : - hsmbus->MspInitCallback = pCallback; - break; - - case HAL_SMBUS_MSPDEINIT_CB_ID : - hsmbus->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SMBUS_STATE_RESET == hsmbus->State) - { - switch (CallbackID) - { - case HAL_SMBUS_MSPINIT_CB_ID : - hsmbus->MspInitCallback = pCallback; - break; - - case HAL_SMBUS_MSPDEINIT_CB_ID : - hsmbus->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an SMBUS Callback - * SMBUS callback is redirected to the weak predefined callback - * @note The HAL_SMBUS_UnRegisterCallback() may be called before HAL_SMBUS_Init() in - * HAL_SMBUS_STATE_RESET to un-register callbacks for HAL_SMBUS_MSPINIT_CB_ID and - * HAL_SMBUS_MSPDEINIT_CB_ID - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * This parameter can be one of the following values: - * @arg @ref HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID - * @arg @ref HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID - * @arg @ref HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID - * @arg @ref HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID - * @arg @ref HAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID - * @arg @ref HAL_SMBUS_ERROR_CB_ID Error callback ID - * @arg @ref HAL_SMBUS_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_UnRegisterCallback(SMBUS_HandleTypeDef *hsmbus, - HAL_SMBUS_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_SMBUS_STATE_READY == hsmbus->State) - { - switch (CallbackID) - { - case HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : - hsmbus->MasterTxCpltCallback = HAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ - break; - - case HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : - hsmbus->MasterRxCpltCallback = HAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ - break; - - case HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : - hsmbus->SlaveTxCpltCallback = HAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ - break; - - case HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : - hsmbus->SlaveRxCpltCallback = HAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ - break; - - case HAL_SMBUS_LISTEN_COMPLETE_CB_ID : - hsmbus->ListenCpltCallback = HAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ - break; - - case HAL_SMBUS_ERROR_CB_ID : - hsmbus->ErrorCallback = HAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_SMBUS_MSPINIT_CB_ID : - hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_SMBUS_MSPDEINIT_CB_ID : - hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SMBUS_STATE_RESET == hsmbus->State) - { - switch (CallbackID) - { - case HAL_SMBUS_MSPINIT_CB_ID : - hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_SMBUS_MSPDEINIT_CB_ID : - hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register the Slave Address Match SMBUS Callback - * To be used instead of the weak HAL_SMBUS_AddrCallback() predefined callback - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param pCallback pointer to the Address Match Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_RegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus, - pSMBUS_AddrCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (HAL_SMBUS_STATE_READY == hsmbus->State) - { - hsmbus->AddrCallback = pCallback; - } - else - { - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the Slave Address Match SMBUS Callback - * Info Ready SMBUS Callback is redirected to the weak HAL_SMBUS_AddrCallback() predefined callback - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_UnRegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_SMBUS_STATE_READY == hsmbus->State) - { - hsmbus->AddrCallback = HAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ - } - else - { - /* Update the error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup SMBUS_Exported_Functions_Group2 Input and Output operation functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the SMBUS data - transfers. - - (#) Blocking mode function to check if device is ready for usage is : - (++) HAL_SMBUS_IsDeviceReady() - - (#) There is only one mode of transfer: - (++) Non-Blocking mode : The communication is performed using Interrupts. - These functions return the status of the transfer startup. - The end of the data processing will be indicated through the - dedicated SMBUS IRQ when using Interrupt mode. - - (#) Non-Blocking mode functions with Interrupt are : - (++) HAL_SMBUS_Master_Transmit_IT() - (++) HAL_SMBUS_Master_Receive_IT() - (++) HAL_SMBUS_Slave_Transmit_IT() - (++) HAL_SMBUS_Slave_Receive_IT() - (++) HAL_SMBUS_EnableListen_IT() or alias HAL_SMBUS_EnableListen_IT() - (++) HAL_SMBUS_DisableListen_IT() - (++) HAL_SMBUS_EnableAlert_IT() - (++) HAL_SMBUS_DisableAlert_IT() - - (#) A set of Transfer Complete Callbacks are provided in non-Blocking mode: - (++) HAL_SMBUS_MasterTxCpltCallback() - (++) HAL_SMBUS_MasterRxCpltCallback() - (++) HAL_SMBUS_SlaveTxCpltCallback() - (++) HAL_SMBUS_SlaveRxCpltCallback() - (++) HAL_SMBUS_AddrCallback() - (++) HAL_SMBUS_ListenCpltCallback() - (++) HAL_SMBUS_ErrorCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Transmit in master/host SMBUS mode an amount of data in non-blocking mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, - uint8_t *pData, uint16_t Size, uint32_t XferOptions) -{ - uint32_t tmp; - - /* Check the parameters */ - assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - /* Prepare transfer parameters */ - hsmbus->pBuffPtr = pData; - hsmbus->XferCount = Size; - hsmbus->XferOptions = XferOptions; - - /* In case of Quick command, remove autoend mode */ - /* Manage the stop generation by software */ - if (hsmbus->pBuffPtr == NULL) - { - hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; - } - - if (Size > MAX_NBYTE_SIZE) - { - hsmbus->XferSize = MAX_NBYTE_SIZE; - } - else - { - hsmbus->XferSize = Size; - } - - /* Send Slave Address */ - /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ - if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) - { - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, - SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), - SMBUS_GENERATE_START_WRITE); - } - else - { - /* If transfer direction not change, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - - /* Store current volatile XferOptions, misra rule */ - tmp = hsmbus->XferOptions; - - if ((hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) && \ - (IS_SMBUS_TRANSFER_OTHER_OPTIONS_REQUEST(tmp) == 0)) - { - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, - SMBUS_NO_STARTSTOP); - } - /* Else transfer direction change, so generate Restart with new transfer direction */ - else - { - /* Convert OTHER_xxx XferOptions if any */ - SMBUS_ConvertOtherXferOptions(hsmbus); - - /* Handle Transfer */ - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, - hsmbus->XferOptions, - SMBUS_GENERATE_START_WRITE); - } - - /* If PEC mode is enable, size to transmit manage by SW part should be Size-1 byte, corresponding to PEC byte */ - /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ - if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) - { - if (hsmbus->XferSize > 0U) - { - hsmbus->XferSize--; - hsmbus->XferCount--; - } - else - { - return HAL_ERROR; - } - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Note : The SMBUS interrupts must be enabled after unlocking current process - to avoid the risk of SMBUS interrupt handle execution before current - process unlock */ - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master/host SMBUS mode an amount of data in non-blocking mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, - uint16_t Size, uint32_t XferOptions) -{ - uint32_t tmp; - - /* Check the parameters */ - assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - - /* Prepare transfer parameters */ - hsmbus->pBuffPtr = pData; - hsmbus->XferCount = Size; - hsmbus->XferOptions = XferOptions; - - /* In case of Quick command, remove autoend mode */ - /* Manage the stop generation by software */ - if (hsmbus->pBuffPtr == NULL) - { - hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; - } - - if (Size > MAX_NBYTE_SIZE) - { - hsmbus->XferSize = MAX_NBYTE_SIZE; - } - else - { - hsmbus->XferSize = Size; - } - - /* Send Slave Address */ - /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ - if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) - { - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, - SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), - SMBUS_GENERATE_START_READ); - } - else - { - /* If transfer direction not change, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - - /* Store current volatile XferOptions, Misra rule */ - tmp = hsmbus->XferOptions; - - if ((hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) && \ - (IS_SMBUS_TRANSFER_OTHER_OPTIONS_REQUEST(tmp) == 0)) - { - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, - SMBUS_NO_STARTSTOP); - } - /* Else transfer direction change, so generate Restart with new transfer direction */ - else - { - /* Convert OTHER_xxx XferOptions if any */ - SMBUS_ConvertOtherXferOptions(hsmbus); - - /* Handle Transfer */ - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, - hsmbus->XferOptions, - SMBUS_GENERATE_START_READ); - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Note : The SMBUS interrupts must be enabled after unlocking current process - to avoid the risk of SMBUS interrupt handle execution before current - process unlock */ - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Abort a master/host SMBUS process communication with Interrupt. - * @note This abort can be called only if state is ready - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress) -{ - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - /* Keep the same state as previous */ - /* to perform as well the call of the corresponding end of transfer callback */ - if (hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) - { - hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; - } - else if (hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) - { - hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; - } - else - { - /* Wrong usage of abort function */ - /* This function should be used only in case of abort monitored by master device */ - return HAL_ERROR; - } - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - - /* Set NBYTES to 1 to generate a dummy read on SMBUS peripheral */ - /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ - SMBUS_TransferConfig(hsmbus, DevAddress, 1, SMBUS_AUTOEND_MODE, SMBUS_NO_STARTSTOP); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Note : The SMBUS interrupts must be enabled after unlocking current process - to avoid the risk of SMBUS interrupt handle execution before current - process unlock */ - if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) - { - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); - } - else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) - { - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); - } - else - { - /* Nothing to do */ - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in slave/device SMBUS mode an amount of data in non-blocking mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, - uint32_t XferOptions) -{ - /* Check the parameters */ - assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) - { - if ((pData == NULL) || (Size == 0UL)) - { - hsmbus->ErrorCode = HAL_SMBUS_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_TX); - - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = (HAL_SMBUS_STATE_SLAVE_BUSY_TX | HAL_SMBUS_STATE_LISTEN); - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - - /* Set SBC bit to manage Acknowledge at each bit */ - hsmbus->Instance->CR1 |= I2C_CR1_SBC; - - /* Enable Address Acknowledge */ - hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hsmbus->pBuffPtr = pData; - hsmbus->XferCount = Size; - hsmbus->XferOptions = XferOptions; - - /* Convert OTHER_xxx XferOptions if any */ - SMBUS_ConvertOtherXferOptions(hsmbus); - - if (Size > MAX_NBYTE_SIZE) - { - hsmbus->XferSize = MAX_NBYTE_SIZE; - } - else - { - hsmbus->XferSize = Size; - } - - /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ - if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) - { - SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, - SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), - SMBUS_NO_STARTSTOP); - } - else - { - /* Set NBYTE to transmit */ - SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, - SMBUS_NO_STARTSTOP); - - /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ - /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ - if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) - { - hsmbus->XferSize--; - hsmbus->XferCount--; - } - } - - /* Clear ADDR flag after prepare the transfer parameters */ - /* This action will generate an acknowledge to the HOST */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Note : The SMBUS interrupts must be enabled after unlocking current process - to avoid the risk of SMBUS interrupt handle execution before current - process unlock */ - /* REnable ADDR interrupt */ - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX | SMBUS_IT_ADDR); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave/device SMBUS mode an amount of data in non-blocking mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, - uint32_t XferOptions) -{ - /* Check the parameters */ - assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) - { - if ((pData == NULL) || (Size == 0UL)) - { - hsmbus->ErrorCode = HAL_SMBUS_ERROR_INVALID_PARAM; - return HAL_ERROR; - } - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_RX); - - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = (HAL_SMBUS_STATE_SLAVE_BUSY_RX | HAL_SMBUS_STATE_LISTEN); - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - - /* Set SBC bit to manage Acknowledge at each bit */ - hsmbus->Instance->CR1 |= I2C_CR1_SBC; - - /* Enable Address Acknowledge */ - hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; - - /* Prepare transfer parameters */ - hsmbus->pBuffPtr = pData; - hsmbus->XferSize = Size; - hsmbus->XferCount = Size; - hsmbus->XferOptions = XferOptions; - - /* Convert OTHER_xxx XferOptions if any */ - SMBUS_ConvertOtherXferOptions(hsmbus); - - /* Set NBYTE to receive */ - /* If XferSize equal "1", or XferSize equal "2" with PEC requested (mean 1 data byte + 1 PEC byte */ - /* no need to set RELOAD bit mode, a ACK will be automatically generated in that case */ - /* else need to set RELOAD bit mode to generate an automatic ACK at each byte Received */ - /* This RELOAD bit will be reset for last BYTE to be receive in SMBUS_Slave_ISR */ - if (((SMBUS_GET_PEC_MODE(hsmbus) != 0UL) && (hsmbus->XferSize == 2U)) || (hsmbus->XferSize == 1U)) - { - SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, - SMBUS_NO_STARTSTOP); - } - else - { - SMBUS_TransferConfig(hsmbus, 0, 1, hsmbus->XferOptions | SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); - } - - /* Clear ADDR flag after prepare the transfer parameters */ - /* This action will generate an acknowledge to the HOST */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Note : The SMBUS interrupts must be enabled after unlocking current process - to avoid the risk of SMBUS interrupt handle execution before current - process unlock */ - /* REnable ADDR interrupt */ - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_ADDR); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Enable the Address listen mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_EnableListen_IT(SMBUS_HandleTypeDef *hsmbus) -{ - hsmbus->State = HAL_SMBUS_STATE_LISTEN; - - /* Enable the Address Match interrupt */ - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ADDR); - - return HAL_OK; -} - -/** - * @brief Disable the Address listen mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus) -{ - /* Disable Address listen mode only if a transfer is not ongoing */ - if (hsmbus->State == HAL_SMBUS_STATE_LISTEN) - { - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Disable the Address Match interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Enable the SMBUS alert mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUSx peripheral. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus) -{ - /* Enable SMBus alert */ - hsmbus->Instance->CR1 |= I2C_CR1_ALERTEN; - - /* Clear ALERT flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); - - /* Enable Alert Interrupt */ - SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ALERT); - - return HAL_OK; -} -/** - * @brief Disable the SMBUS alert mode with Interrupt. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUSx peripheral. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus) -{ - /* Enable SMBus alert */ - hsmbus->Instance->CR1 &= ~I2C_CR1_ALERTEN; - - /* Disable Alert Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ALERT); - - return HAL_OK; -} - -/** - * @brief Check if target device is ready for communication. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Trials Number of trials - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, - uint32_t Timeout) -{ - uint32_t tickstart; - - __IO uint32_t SMBUS_Trials = 0UL; - - FlagStatus tmp1; - FlagStatus tmp2; - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET) - { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; - - do - { - /* Generate Start */ - hsmbus->Instance->CR2 = SMBUS_GENERATE_START(hsmbus->Init.AddressingMode, DevAddress); - - /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ - /* Wait until STOPF flag is set or a NACK flag is set*/ - tickstart = HAL_GetTick(); - - tmp1 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF); - tmp2 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); - - while ((tmp1 == RESET) && (tmp2 == RESET)) - { - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) - { - /* Device is ready */ - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Update SMBUS error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - return HAL_ERROR; - } - } - - tmp1 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF); - tmp2 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); - } - - /* Check if the NACKF flag has not been set */ - if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) - { - /* Wait until STOPF flag is reset */ - if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); - - /* Device is ready */ - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; - } - else - { - /* Wait until STOPF flag is reset */ - if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear NACK Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); - - /* Clear STOP Flag, auto generated with autoend*/ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); - } - - /* Check if the maximum allowed number of trials has been reached */ - if (SMBUS_Trials == Trials) - { - /* Generate Stop */ - hsmbus->Instance->CR2 |= I2C_CR2_STOP; - - /* Wait until STOPF flag is reset */ - if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) - { - return HAL_ERROR; - } - - /* Clear STOP Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); - } - - /* Increment Trials */ - SMBUS_Trials++; - } while (SMBUS_Trials < Trials); - - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Update SMBUS error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_ERROR; - } - else - { - return HAL_BUSY; - } -} -/** - * @} - */ - -/** @defgroup SMBUS_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks - * @{ - */ - -/** - * @brief Handle SMBUS event interrupt request. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus) -{ - /* Use a local variable to store the current ISR flags */ - /* This action will avoid a wrong treatment due to ISR flags change during interrupt handler */ - uint32_t tmpisrvalue = READ_REG(hsmbus->Instance->ISR); - uint32_t tmpcr1value = READ_REG(hsmbus->Instance->CR1); - - /* SMBUS in mode Transmitter ---------------------------------------------------*/ - if ((SMBUS_CHECK_IT_SOURCE(tmpcr1value, (SMBUS_IT_TCI | SMBUS_IT_STOPI | - SMBUS_IT_NACKI | SMBUS_IT_TXI)) != RESET) && - ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TXIS) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) - { - /* Slave mode selected */ - if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) - { - (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); - } - /* Master mode selected */ - else if ((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_TX) == HAL_SMBUS_STATE_MASTER_BUSY_TX) - { - (void)SMBUS_Master_ISR(hsmbus, tmpisrvalue); - } - else - { - /* Nothing to do */ - } - } - - /* SMBUS in mode Receiver ----------------------------------------------------*/ - if ((SMBUS_CHECK_IT_SOURCE(tmpcr1value, (SMBUS_IT_TCI | SMBUS_IT_STOPI | - SMBUS_IT_NACKI | SMBUS_IT_RXI)) != RESET) && - ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_RXNE) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) - { - /* Slave mode selected */ - if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) - { - (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); - } - /* Master mode selected */ - else if ((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_RX) == HAL_SMBUS_STATE_MASTER_BUSY_RX) - { - (void)SMBUS_Master_ISR(hsmbus, tmpisrvalue); - } - else - { - /* Nothing to do */ - } - } - - /* SMBUS in mode Listener Only --------------------------------------------------*/ - if (((SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_ADDRI) != RESET) || - (SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_STOPI) != RESET) || - (SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_NACKI) != RESET)) && - ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_ADDR) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || - (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) - { - if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) - { - (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); - } - } -} - -/** - * @brief Handle SMBUS error interrupt request. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus) -{ - SMBUS_ITErrorHandler(hsmbus); -} - -/** - * @brief Master Tx Transfer completed callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_MasterTxCpltCallback() could be implemented in the user file - */ -} - -/** - * @brief Master Rx Transfer completed callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_MasterRxCpltCallback() could be implemented in the user file - */ -} - -/** @brief Slave Tx Transfer completed callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_SlaveTxCpltCallback() could be implemented in the user file - */ -} - -/** - * @brief Slave Rx Transfer completed callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_SlaveRxCpltCallback() could be implemented in the user file - */ -} - -/** - * @brief Slave Address Match callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param TransferDirection Master request Transfer Direction (Write/Read) - * @param AddrMatchCode Address Match Code - * @retval None - */ -__weak void HAL_SMBUS_AddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, - uint16_t AddrMatchCode) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - UNUSED(TransferDirection); - UNUSED(AddrMatchCode); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_AddrCallback() could be implemented in the user file - */ -} - -/** - * @brief Listen Complete callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_ListenCpltCallback(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_ListenCpltCallback() could be implemented in the user file - */ -} - -/** - * @brief SMBUS error callback. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval None - */ -__weak void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsmbus); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMBUS_ErrorCallback() could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup SMBUS_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief Peripheral State and Errors functions - * -@verbatim - =============================================================================== - ##### Peripheral State and Errors functions ##### - =============================================================================== - [..] - This subsection permits to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the SMBUS handle state. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval HAL state - */ -uint32_t HAL_SMBUS_GetState(const SMBUS_HandleTypeDef *hsmbus) -{ - /* Return SMBUS handle state */ - return hsmbus->State; -} - -/** - * @brief Return the SMBUS error code. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @retval SMBUS Error Code - */ -uint32_t HAL_SMBUS_GetError(const SMBUS_HandleTypeDef *hsmbus) -{ - return hsmbus->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup SMBUS_Private_Functions SMBUS Private Functions - * @brief Data transfers Private functions - * @{ - */ - -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param StatusFlags Value of Interrupt Flags. - * @retval HAL status - */ -static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags) -{ - uint16_t DevAddress; - - /* Process Locked */ - __HAL_LOCK(hsmbus); - - if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_AF) != RESET) - { - /* Clear NACK Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); - - /* Set corresponding Error Code */ - /* No need to generate STOP, it is automatically done */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; - - /* Flush TX register */ - SMBUS_Flush_TXDR(hsmbus); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the Error callback to inform upper layer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->ErrorCallback(hsmbus); -#else - HAL_SMBUS_ErrorCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_STOPF) != RESET) - { - /* Check and treat errors if errors occurs during STOP process */ - SMBUS_ITErrorHandler(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) - { - /* Disable Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); - - /* Clear STOP Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - SMBUS_RESET_CR2(hsmbus); - - /* Flush remaining data in Fifo register in case of error occurs before TXEmpty */ - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - hsmbus->PreviousState = HAL_SMBUS_STATE_READY; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Re-enable the selected SMBUS peripheral */ - __HAL_SMBUS_ENABLE(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterTxCpltCallback(hsmbus); -#else - HAL_SMBUS_MasterTxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) - { - /* Store Last receive data if any */ - if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) - { - /* Read data from RXDR */ - *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); - - /* Increment Buffer pointer */ - hsmbus->pBuffPtr++; - - if ((hsmbus->XferSize > 0U)) - { - hsmbus->XferSize--; - hsmbus->XferCount--; - } - } - - /* Disable Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); - - /* Clear STOP Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); - - /* Clear Configuration Register 2 */ - SMBUS_RESET_CR2(hsmbus); - - hsmbus->PreviousState = HAL_SMBUS_STATE_READY; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterRxCpltCallback(hsmbus); -#else - HAL_SMBUS_MasterRxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) - { - /* Read data from RXDR */ - *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); - - /* Increment Buffer pointer */ - hsmbus->pBuffPtr++; - - /* Increment Size counter */ - hsmbus->XferSize--; - hsmbus->XferCount--; - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TXIS) != RESET) - { - /* Write data to TXDR */ - hsmbus->Instance->TXDR = *hsmbus->pBuffPtr; - - /* Increment Buffer pointer */ - hsmbus->pBuffPtr++; - - /* Increment Size counter */ - hsmbus->XferSize--; - hsmbus->XferCount--; - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TCR) != RESET) - { - if ((hsmbus->XferCount != 0U) && (hsmbus->XferSize == 0U)) - { - DevAddress = (uint16_t)(hsmbus->Instance->CR2 & I2C_CR2_SADD); - - if (hsmbus->XferCount > MAX_NBYTE_SIZE) - { - SMBUS_TransferConfig(hsmbus, DevAddress, MAX_NBYTE_SIZE, - (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), - SMBUS_NO_STARTSTOP); - hsmbus->XferSize = MAX_NBYTE_SIZE; - } - else - { - hsmbus->XferSize = hsmbus->XferCount; - SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, - SMBUS_NO_STARTSTOP); - /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ - /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ - if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) - { - hsmbus->XferSize--; - hsmbus->XferCount--; - } - } - } - else if ((hsmbus->XferCount == 0U) && (hsmbus->XferSize == 0U)) - { - /* Call TxCpltCallback() if no stop mode is set */ - if (SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) - { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) - { - /* Disable Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); - hsmbus->PreviousState = hsmbus->State; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterTxCpltCallback(hsmbus); -#else - HAL_SMBUS_MasterTxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) - { - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); - hsmbus->PreviousState = hsmbus->State; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterRxCpltCallback(hsmbus); -#else - HAL_SMBUS_MasterRxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - } - else - { - /* Nothing to do */ - } - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TC) != RESET) - { - if (hsmbus->XferCount == 0U) - { - /* Specific use case for Quick command */ - if (hsmbus->pBuffPtr == NULL) - { - /* Generate a Stop command */ - hsmbus->Instance->CR2 |= I2C_CR2_STOP; - } - /* Call TxCpltCallback() if no stop mode is set */ - else if (SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) - { - /* No Generate Stop, to permit restart mode */ - /* The stop will be done at the end of transfer, when SMBUS_AUTOEND_MODE enable */ - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) - { - /* Disable Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); - hsmbus->PreviousState = hsmbus->State; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterTxCpltCallback(hsmbus); -#else - HAL_SMBUS_MasterTxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) - { - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); - hsmbus->PreviousState = hsmbus->State; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->MasterRxCpltCallback(hsmbus); -#else - HAL_SMBUS_MasterRxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - else - { - /* Nothing to do */ - } - } - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; -} -/** - * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param StatusFlags Value of Interrupt Flags. - * @retval HAL status - */ -static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags) -{ - uint8_t TransferDirection; - uint16_t SlaveAddrCode; - - /* Process Locked */ - __HAL_LOCK(hsmbus); - - if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_AF) != RESET) - { - /* Check that SMBUS transfer finished */ - /* if yes, normal usecase, a NACK is sent by the HOST when Transfer is finished */ - /* Mean XferCount == 0*/ - /* So clear Flag NACKF only */ - if (hsmbus->XferCount == 0U) - { - /* Clear NACK Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); - - /* Flush TX register */ - SMBUS_Flush_TXDR(hsmbus); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - } - else - { - /* if no, error usecase, a Non-Acknowledge of last Data is generated by the HOST*/ - /* Clear NACK Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); - - /* Set HAL State to "Idle" State, mean to LISTEN state */ - /* So reset Slave Busy state */ - hsmbus->PreviousState = hsmbus->State; - hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); - hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); - - /* Disable RX/TX Interrupts, keep only ADDR Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); - - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; - - /* Flush TX register */ - SMBUS_Flush_TXDR(hsmbus); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the Error callback to inform upper layer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->ErrorCallback(hsmbus); -#else - HAL_SMBUS_ErrorCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_ADDR) != RESET) - { - TransferDirection = (uint8_t)(SMBUS_GET_DIR(hsmbus)); - SlaveAddrCode = (uint16_t)(SMBUS_GET_ADDR_MATCH(hsmbus)); - - /* Disable ADDR interrupt to prevent multiple ADDRInterrupt*/ - /* Other ADDRInterrupt will be treat in next Listen usecase */ - __HAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_ADDRI); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call Slave Addr callback */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); -#else - HAL_SMBUS_AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else if ((SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) || - (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TCR) != RESET)) - { - if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) - { - /* Read data from RXDR */ - *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); - - /* Increment Buffer pointer */ - hsmbus->pBuffPtr++; - - hsmbus->XferSize--; - hsmbus->XferCount--; - - if (hsmbus->XferCount == 1U) - { - /* Receive last Byte, can be PEC byte in case of PEC BYTE enabled */ - /* or only the last Byte of Transfer */ - /* So reset the RELOAD bit mode */ - hsmbus->XferOptions &= ~SMBUS_RELOAD_MODE; - SMBUS_TransferConfig(hsmbus, 0, 1, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); - } - else if (hsmbus->XferCount == 0U) - { - /* Last Byte is received, disable Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); - - /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_RX, keep only HAL_SMBUS_STATE_LISTEN */ - hsmbus->PreviousState = hsmbus->State; - hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->SlaveRxCpltCallback(hsmbus); -#else - HAL_SMBUS_SlaveRxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - else - { - /* Set Reload for next Bytes */ - SMBUS_TransferConfig(hsmbus, 0, 1, - SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), - SMBUS_NO_STARTSTOP); - - /* Ack last Byte Read */ - hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; - } - } - else if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) - { - if ((hsmbus->XferCount != 0U) && (hsmbus->XferSize == 0U)) - { - if (hsmbus->XferCount > MAX_NBYTE_SIZE) - { - SMBUS_TransferConfig(hsmbus, 0, MAX_NBYTE_SIZE, - (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), - SMBUS_NO_STARTSTOP); - hsmbus->XferSize = MAX_NBYTE_SIZE; - } - else - { - hsmbus->XferSize = hsmbus->XferCount; - SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, - SMBUS_NO_STARTSTOP); - /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ - /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ - if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) - { - hsmbus->XferSize--; - hsmbus->XferCount--; - } - } - } - } - else - { - /* Nothing to do */ - } - } - else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TXIS) != RESET) - { - /* Write data to TXDR only if XferCount not reach "0" */ - /* A TXIS flag can be set, during STOP treatment */ - /* Check if all Data have already been sent */ - /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ - if (hsmbus->XferCount > 0U) - { - /* Write data to TXDR */ - hsmbus->Instance->TXDR = *hsmbus->pBuffPtr; - - /* Increment Buffer pointer */ - hsmbus->pBuffPtr++; - - hsmbus->XferCount--; - hsmbus->XferSize--; - } - - if (hsmbus->XferCount == 0U) - { - /* Last Byte is Transmitted */ - /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_TX, keep only HAL_SMBUS_STATE_LISTEN */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); - hsmbus->PreviousState = hsmbus->State; - hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->SlaveTxCpltCallback(hsmbus); -#else - HAL_SMBUS_SlaveTxCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - } - else - { - /* Nothing to do */ - } - - /* Check if STOPF is set */ - if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_STOPF) != RESET) - { - if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) - { - /* Store Last receive data if any */ - if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) - { - /* Read data from RXDR */ - *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); - - /* Increment Buffer pointer */ - hsmbus->pBuffPtr++; - - if ((hsmbus->XferSize > 0U)) - { - hsmbus->XferSize--; - hsmbus->XferCount--; - } - } - - /* Disable RX and TX Interrupts */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); - - /* Disable ADDR Interrupt */ - SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); - - /* Disable Address Acknowledge */ - hsmbus->Instance->CR2 |= I2C_CR2_NACK; - - /* Clear Configuration Register 2 */ - SMBUS_RESET_CR2(hsmbus); - - /* Clear STOP Flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); - - /* Clear ADDR flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); - - hsmbus->XferOptions = 0; - hsmbus->PreviousState = hsmbus->State; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->ListenCpltCallback(hsmbus); -#else - HAL_SMBUS_ListenCpltCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; -} -/** - * @brief Manage the enabling of Interrupts. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param InterruptRequest Value of @ref SMBUS_Interrupt_configuration_definition. - * @retval HAL status - */ -static void SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest) -{ - uint32_t tmpisr = 0UL; - - if ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) - { - /* Enable ERR interrupt */ - tmpisr |= SMBUS_IT_ERRI; - } - - if ((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) - { - /* Enable ADDR, STOP interrupt */ - tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_ERRI; - } - - if ((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) - { - /* Enable ERR, TC, STOP, NACK, RXI interrupt */ - tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI; - } - - if ((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) - { - /* Enable ERR, TC, STOP, NACK, TXI interrupt */ - tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_RXI; - } - - /* Enable interrupts only at the end */ - /* to avoid the risk of SMBUS interrupt handle execution before */ - /* all interrupts requested done */ - __HAL_SMBUS_ENABLE_IT(hsmbus, tmpisr); -} -/** - * @brief Manage the disabling of Interrupts. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param InterruptRequest Value of @ref SMBUS_Interrupt_configuration_definition. - * @retval HAL status - */ -static void SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest) -{ - uint32_t tmpisr = 0UL; - uint32_t tmpstate = hsmbus->State; - - if ((tmpstate == HAL_SMBUS_STATE_READY) && ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT)) - { - /* Disable ERR interrupt */ - tmpisr |= SMBUS_IT_ERRI; - } - - if ((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) - { - /* Disable TC, STOP, NACK and TXI interrupt */ - tmpisr |= SMBUS_IT_TCI | SMBUS_IT_TXI; - - if ((SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) - && ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) - { - /* Disable ERR interrupt */ - tmpisr |= SMBUS_IT_ERRI; - } - - if ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) - { - /* Disable STOP and NACK interrupt */ - tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; - } - } - - if ((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) - { - /* Disable TC, STOP, NACK and RXI interrupt */ - tmpisr |= SMBUS_IT_TCI | SMBUS_IT_RXI; - - if ((SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) - && ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) - { - /* Disable ERR interrupt */ - tmpisr |= SMBUS_IT_ERRI; - } - - if ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) - { - /* Disable STOP and NACK interrupt */ - tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; - } - } - - if ((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) - { - /* Disable ADDR, STOP and NACK interrupt */ - tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI; - - if (SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) - { - /* Disable ERR interrupt */ - tmpisr |= SMBUS_IT_ERRI; - } - } - - /* Disable interrupts only at the end */ - /* to avoid a breaking situation like at "t" time */ - /* all disable interrupts request are not done */ - __HAL_SMBUS_DISABLE_IT(hsmbus, tmpisr); -} - -/** - * @brief SMBUS interrupts error handler. - * @param hsmbus SMBUS handle. - * @retval None - */ -static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus) -{ - uint32_t itflags = READ_REG(hsmbus->Instance->ISR); - uint32_t itsources = READ_REG(hsmbus->Instance->CR1); - uint32_t tmpstate; - uint32_t tmperror; - - /* SMBUS Bus error interrupt occurred ------------------------------------*/ - if (((itflags & SMBUS_FLAG_BERR) == SMBUS_FLAG_BERR) && \ - ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) - { - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BERR; - - /* Clear BERR flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_BERR); - } - - /* SMBUS Over-Run/Under-Run interrupt occurred ----------------------------------------*/ - if (((itflags & SMBUS_FLAG_OVR) == SMBUS_FLAG_OVR) && \ - ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) - { - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_OVR; - - /* Clear OVR flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_OVR); - } - - /* SMBUS Arbitration Loss error interrupt occurred ------------------------------------*/ - if (((itflags & SMBUS_FLAG_ARLO) == SMBUS_FLAG_ARLO) && \ - ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) - { - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ARLO; - - /* Clear ARLO flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ARLO); - } - - /* SMBUS Timeout error interrupt occurred ---------------------------------------------*/ - if (((itflags & SMBUS_FLAG_TIMEOUT) == SMBUS_FLAG_TIMEOUT) && \ - ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) - { - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BUSTIMEOUT; - - /* Clear TIMEOUT flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT); - } - - /* SMBUS Alert error interrupt occurred -----------------------------------------------*/ - if (((itflags & SMBUS_FLAG_ALERT) == SMBUS_FLAG_ALERT) && \ - ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) - { - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ALERT; - - /* Clear ALERT flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); - } - - /* SMBUS Packet Error Check error interrupt occurred ----------------------------------*/ - if (((itflags & SMBUS_FLAG_PECERR) == SMBUS_FLAG_PECERR) && \ - ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) - { - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_PECERR; - - /* Clear PEC error flag */ - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); - } - - if (hsmbus->ErrorCode != HAL_SMBUS_ERROR_NONE) - { - /* Flush TX register */ - SMBUS_Flush_TXDR(hsmbus); - } - - /* Store current volatile hsmbus->ErrorCode, misra rule */ - tmperror = hsmbus->ErrorCode; - - /* Call the Error Callback in case of Error detected */ - if ((tmperror != HAL_SMBUS_ERROR_NONE) && (tmperror != HAL_SMBUS_ERROR_ACKF)) - { - /* Do not Reset the HAL state in case of ALERT error */ - if ((tmperror & HAL_SMBUS_ERROR_ALERT) != HAL_SMBUS_ERROR_ALERT) - { - /* Store current volatile hsmbus->State, misra rule */ - tmpstate = hsmbus->State; - - if (((tmpstate & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) - || ((tmpstate & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX)) - { - /* Reset only HAL_SMBUS_STATE_SLAVE_BUSY_XX */ - /* keep HAL_SMBUS_STATE_LISTEN if set */ - hsmbus->PreviousState = HAL_SMBUS_STATE_READY; - hsmbus->State = HAL_SMBUS_STATE_LISTEN; - } - } - - /* Call the Error callback to inform upper layer */ -#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) - hsmbus->ErrorCallback(hsmbus); -#else - HAL_SMBUS_ErrorCallback(hsmbus); -#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Handle SMBUS Communication Timeout. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUS. - * @param Flag Specifies the SMBUS flag to check. - * @param Status The new Flag status (SET or RESET). - * @param Timeout Timeout duration - * @retval HAL status - */ -static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, - FlagStatus Status, uint32_t Timeout) -{ - uint32_t tickstart = HAL_GetTick(); - - /* Wait until flag is set */ - while ((FlagStatus)(__HAL_SMBUS_GET_FLAG(hsmbus, Flag)) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) - { - hsmbus->PreviousState = hsmbus->State; - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Update SMBUS error code */ - hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_ERROR; - } - } - } - - return HAL_OK; -} - -/** - * @brief SMBUS Tx data register flush process. - * @param hsmbus SMBUS handle. - * @retval None - */ -static void SMBUS_Flush_TXDR(SMBUS_HandleTypeDef *hsmbus) -{ - /* If a pending TXIS flag is set */ - /* Write a dummy data in TXDR to clear it */ - if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) - { - hsmbus->Instance->TXDR = 0x00U; - } - - /* Flush TX register if not empty */ - if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXE) == RESET) - { - __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TXE); - } -} - -/** - * @brief Handle SMBUSx communication when starting transfer or during transfer (TC or TCR flag are set). - * @param hsmbus SMBUS handle. - * @param DevAddress specifies the slave address to be programmed. - * @param Size specifies the number of bytes to be programmed. - * This parameter must be a value between 0 and 255. - * @param Mode New state of the SMBUS START condition generation. - * This parameter can be one or a combination of the following values: - * @arg @ref SMBUS_RELOAD_MODE Enable Reload mode. - * @arg @ref SMBUS_AUTOEND_MODE Enable Automatic end mode. - * @arg @ref SMBUS_SOFTEND_MODE Enable Software end mode and Reload mode. - * @arg @ref SMBUS_SENDPEC_MODE Enable Packet Error Calculation mode. - * @param Request New state of the SMBUS START condition generation. - * This parameter can be one of the following values: - * @arg @ref SMBUS_NO_STARTSTOP Don't Generate stop and start condition. - * @arg @ref SMBUS_GENERATE_STOP Generate stop condition (Size should be set to 0). - * @arg @ref SMBUS_GENERATE_START_READ Generate Restart for read request. - * @arg @ref SMBUS_GENERATE_START_WRITE Generate Restart for write request. - * @retval None - */ -static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, - uint32_t Mode, uint32_t Request) -{ - /* Check the parameters */ - assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); - assert_param(IS_SMBUS_TRANSFER_MODE(Mode)); - assert_param(IS_SMBUS_TRANSFER_REQUEST(Request)); - - /* update CR2 register */ - MODIFY_REG(hsmbus->Instance->CR2, - ((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \ - (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31UL - I2C_CR2_RD_WRN_Pos))) | \ - I2C_CR2_START | I2C_CR2_STOP | I2C_CR2_PECBYTE)), \ - (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \ - (((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \ - (uint32_t)Mode | (uint32_t)Request)); -} - -/** - * @brief Convert SMBUSx OTHER_xxx XferOptions to functional XferOptions. - * @param hsmbus SMBUS handle. - * @retval None - */ -static void SMBUS_ConvertOtherXferOptions(SMBUS_HandleTypeDef *hsmbus) -{ - /* if user set XferOptions to SMBUS_OTHER_FRAME_NO_PEC */ - /* it request implicitly to generate a restart condition */ - /* set XferOptions to SMBUS_FIRST_FRAME */ - if (hsmbus->XferOptions == SMBUS_OTHER_FRAME_NO_PEC) - { - hsmbus->XferOptions = SMBUS_FIRST_FRAME; - } - /* else if user set XferOptions to SMBUS_OTHER_FRAME_WITH_PEC */ - /* it request implicitly to generate a restart condition */ - /* set XferOptions to SMBUS_FIRST_FRAME | SMBUS_SENDPEC_MODE */ - else if (hsmbus->XferOptions == SMBUS_OTHER_FRAME_WITH_PEC) - { - hsmbus->XferOptions = SMBUS_FIRST_FRAME | SMBUS_SENDPEC_MODE; - } - /* else if user set XferOptions to SMBUS_OTHER_AND_LAST_FRAME_NO_PEC */ - /* it request implicitly to generate a restart condition */ - /* then generate a stop condition at the end of transfer */ - /* set XferOptions to SMBUS_FIRST_AND_LAST_FRAME_NO_PEC */ - else if (hsmbus->XferOptions == SMBUS_OTHER_AND_LAST_FRAME_NO_PEC) - { - hsmbus->XferOptions = SMBUS_FIRST_AND_LAST_FRAME_NO_PEC; - } - /* else if user set XferOptions to SMBUS_OTHER_AND_LAST_FRAME_WITH_PEC */ - /* it request implicitly to generate a restart condition */ - /* then generate a stop condition at the end of transfer */ - /* set XferOptions to SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC */ - else if (hsmbus->XferOptions == SMBUS_OTHER_AND_LAST_FRAME_WITH_PEC) - { - hsmbus->XferOptions = SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC; - } - else - { - /* Nothing to do */ - } -} -/** - * @} - */ - -#endif /* HAL_SMBUS_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_smbus.c + * @author MCD Application Team + * @brief SMBUS HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the System Management Bus (SMBus) peripheral, + * based on I2C principles of operation : + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SMBUS HAL driver can be used as follows: + + (#) Declare a SMBUS_HandleTypeDef handle structure, for example: + SMBUS_HandleTypeDef hsmbus; + + (#)Initialize the SMBUS low level resources by implementing the HAL_SMBUS_MspInit() API: + (##) Enable the SMBUSx interface clock + (##) SMBUS pins configuration + (+++) Enable the clock for the SMBUS GPIOs + (+++) Configure SMBUS pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the SMBUSx interrupt priority + (+++) Enable the NVIC SMBUS IRQ Channel + + (#) Configure the Communication Clock Timing, Bus Timeout, Own Address1, Master Addressing mode, + Dual Addressing mode, Own Address2, Own Address2 Mask, General call, Nostretch mode, + Peripheral mode and Packet Error Check mode in the hsmbus Init structure. + + (#) Initialize the SMBUS registers by calling the HAL_SMBUS_Init() API: + (++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized HAL_SMBUS_MspInit(&hsmbus) API. + + (#) To check if target device is ready for communication, use the function HAL_SMBUS_IsDeviceReady() + + (#) For SMBUS IO operations, only one mode of operations is available within this driver + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in master/host SMBUS mode an amount of data in non-blocking mode + using HAL_SMBUS_Master_Transmit_IT() + (++) At transmission end of transfer HAL_SMBUS_MasterTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_SMBUS_MasterTxCpltCallback() + (+) Receive in master/host SMBUS mode an amount of data in non-blocking mode + using HAL_SMBUS_Master_Receive_IT() + (++) At reception end of transfer HAL_SMBUS_MasterRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_SMBUS_MasterRxCpltCallback() + (+) Abort a master/host SMBUS process communication with Interrupt using HAL_SMBUS_Master_Abort_IT() + (++) The associated previous transfer callback is called at the end of abort process + (++) mean HAL_SMBUS_MasterTxCpltCallback() in case of previous state was master transmit + (++) mean HAL_SMBUS_MasterRxCpltCallback() in case of previous state was master receive + (+) Enable/disable the Address listen mode in slave/device or host/slave SMBUS mode + using HAL_SMBUS_EnableListen_IT() HAL_SMBUS_DisableListen_IT() + (++) When address slave/device SMBUS match, HAL_SMBUS_AddrCallback() is executed and users can + add their own code to check the Address Match Code and the transmission direction + request by master/host (Write/Read). + (++) At Listen mode end HAL_SMBUS_ListenCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_SMBUS_ListenCpltCallback() + (+) Transmit in slave/device SMBUS mode an amount of data in non-blocking mode + using HAL_SMBUS_Slave_Transmit_IT() + (++) At transmission end of transfer HAL_SMBUS_SlaveTxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_SMBUS_SlaveTxCpltCallback() + (+) Receive in slave/device SMBUS mode an amount of data in non-blocking mode + using HAL_SMBUS_Slave_Receive_IT() + (++) At reception end of transfer HAL_SMBUS_SlaveRxCpltCallback() is executed and users can + add their own code by customization of function pointer HAL_SMBUS_SlaveRxCpltCallback() + (+) Enable/Disable the SMBUS alert mode using + HAL_SMBUS_EnableAlert_IT() or HAL_SMBUS_DisableAlert_IT() + (++) When SMBUS Alert is generated HAL_SMBUS_ErrorCallback() is executed and users can + add their own code by customization of function pointer HAL_SMBUS_ErrorCallback() + to check the Alert Error Code using function HAL_SMBUS_GetError() + (+) Get HAL state machine or error values using HAL_SMBUS_GetState() or HAL_SMBUS_GetError() + (+) In case of transfer Error, HAL_SMBUS_ErrorCallback() function is executed and users can + add their own code by customization of function pointer HAL_SMBUS_ErrorCallback() + to check the Error Code using function HAL_SMBUS_GetError() + + *** SMBUS HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SMBUS HAL driver. + + (+) __HAL_SMBUS_ENABLE: Enable the SMBUS peripheral + (+) __HAL_SMBUS_DISABLE: Disable the SMBUS peripheral + (+) __HAL_SMBUS_GET_FLAG: Check whether the specified SMBUS flag is set or not + (+) __HAL_SMBUS_CLEAR_FLAG: Clear the specified SMBUS pending flag + (+) __HAL_SMBUS_ENABLE_IT: Enable the specified SMBUS interrupt + (+) __HAL_SMBUS_DISABLE_IT: Disable the specified SMBUS interrupt + + *** Callback registration *** + ============================================= + [..] + The compilation flag USE_HAL_SMBUS_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_SMBUS_RegisterCallback() or HAL_SMBUS_RegisterAddrCallback() + to register an interrupt callback. + [..] + Function HAL_SMBUS_RegisterCallback() allows to register following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + [..] + For specific callback AddrCallback use dedicated register callbacks : HAL_SMBUS_RegisterAddrCallback. + [..] + Use function HAL_SMBUS_UnRegisterCallback to reset a callback to the default + weak function. + HAL_SMBUS_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) MasterTxCpltCallback : callback for Master transmission end of transfer. + (+) MasterRxCpltCallback : callback for Master reception end of transfer. + (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. + (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. + (+) ListenCpltCallback : callback for end of listen mode. + (+) ErrorCallback : callback for error detection. + (+) MspInitCallback : callback for Msp Init. + (+) MspDeInitCallback : callback for Msp DeInit. + [..] + For callback AddrCallback use dedicated register callbacks : HAL_SMBUS_UnRegisterAddrCallback. + [..] + By default, after the HAL_SMBUS_Init() and when the state is HAL_I2C_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_SMBUS_MasterTxCpltCallback(), HAL_SMBUS_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the HAL_SMBUS_Init()/ HAL_SMBUS_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the HAL_SMBUS_Init()/ HAL_SMBUS_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + [..] + Callbacks can be registered/unregistered in HAL_I2C_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in HAL_I2C_STATE_READY or HAL_I2C_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using HAL_SMBUS_RegisterCallback() before calling HAL_SMBUS_DeInit() + or HAL_SMBUS_Init() function. + [..] + When the compilation flag USE_HAL_SMBUS_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + [..] + (@) You can refer to the SMBUS HAL driver header file for more useful macros + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SMBUS SMBUS + * @brief SMBUS HAL module driver + * @{ + */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SMBUS_Private_Define SMBUS Private Constants + * @{ + */ +#define TIMING_CLEAR_MASK (0xF0FFFFFFUL) /*!< SMBUS TIMING clear register Mask */ +#define HAL_TIMEOUT_ADDR (10000U) /*!< 10 s */ +#define HAL_TIMEOUT_BUSY (25U) /*!< 25 ms */ +#define HAL_TIMEOUT_DIR (25U) /*!< 25 ms */ +#define HAL_TIMEOUT_RXNE (25U) /*!< 25 ms */ +#define HAL_TIMEOUT_STOPF (25U) /*!< 25 ms */ +#define HAL_TIMEOUT_TC (25U) /*!< 25 ms */ +#define HAL_TIMEOUT_TCR (25U) /*!< 25 ms */ +#define HAL_TIMEOUT_TXIS (25U) /*!< 25 ms */ +#define MAX_NBYTE_SIZE 255U +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup SMBUS_Private_Functions SMBUS Private Functions + * @{ + */ +/* Private functions to handle flags during polling transfer */ +static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, + FlagStatus Status, uint32_t Timeout); + +/* Private functions for SMBUS transfer IRQ handler */ +static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags); +static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags); +static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus); + +/* Private functions to centralize the enable/disable of Interrupts */ +static void SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest); +static void SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest); + +/* Private function to flush TXDR register */ +static void SMBUS_Flush_TXDR(SMBUS_HandleTypeDef *hsmbus); + +/* Private function to handle start, restart or stop a transfer */ +static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, + uint32_t Mode, uint32_t Request); + +/* Private function to Convert Specific options */ +static void SMBUS_ConvertOtherXferOptions(SMBUS_HandleTypeDef *hsmbus); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SMBUS_Exported_Functions SMBUS Exported Functions + * @{ + */ + +/** @defgroup SMBUS_Exported_Functions_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 + deinitialize the SMBUSx peripheral: + + (+) User must Implement HAL_SMBUS_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, IT and NVIC ). + + (+) Call the function HAL_SMBUS_Init() to configure the selected device with + the selected configuration: + (++) Clock Timing + (++) Bus Timeout + (++) Analog Filer mode + (++) Own Address 1 + (++) Addressing mode (Master, Slave) + (++) Dual Addressing mode + (++) Own Address 2 + (++) Own Address 2 Mask + (++) General call mode + (++) Nostretch mode + (++) Packet Error Check mode + (++) Peripheral mode + + + (+) Call the function HAL_SMBUS_DeInit() to restore the default configuration + of the selected SMBUSx peripheral. + + (+) Enable/Disable Analog/Digital filters with HAL_SMBUS_ConfigAnalogFilter() and + HAL_SMBUS_ConfigDigitalFilter(). + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the SMBUS according to the specified parameters + * in the SMBUS_InitTypeDef and initialize the associated handle. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if (hsmbus == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_ANALOG_FILTER(hsmbus->Init.AnalogFilter)); + assert_param(IS_SMBUS_OWN_ADDRESS1(hsmbus->Init.OwnAddress1)); + assert_param(IS_SMBUS_ADDRESSING_MODE(hsmbus->Init.AddressingMode)); + assert_param(IS_SMBUS_DUAL_ADDRESS(hsmbus->Init.DualAddressMode)); + assert_param(IS_SMBUS_OWN_ADDRESS2(hsmbus->Init.OwnAddress2)); + assert_param(IS_SMBUS_OWN_ADDRESS2_MASK(hsmbus->Init.OwnAddress2Masks)); + assert_param(IS_SMBUS_GENERAL_CALL(hsmbus->Init.GeneralCallMode)); + assert_param(IS_SMBUS_NO_STRETCH(hsmbus->Init.NoStretchMode)); + assert_param(IS_SMBUS_PEC(hsmbus->Init.PacketErrorCheckMode)); + assert_param(IS_SMBUS_PERIPHERAL_MODE(hsmbus->Init.PeripheralMode)); + + if (hsmbus->State == HAL_SMBUS_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hsmbus->Lock = HAL_UNLOCKED; + +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback = HAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + hsmbus->MasterRxCpltCallback = HAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + hsmbus->SlaveTxCpltCallback = HAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + hsmbus->SlaveRxCpltCallback = HAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + hsmbus->ListenCpltCallback = HAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + hsmbus->ErrorCallback = HAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ + hsmbus->AddrCallback = HAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ + + if (hsmbus->MspInitCallback == NULL) + { + hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + hsmbus->MspInitCallback(hsmbus); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_SMBUS_MspInit(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /*---------------------------- SMBUSx TIMINGR Configuration ------------------------*/ + /* Configure SMBUSx: Frequency range */ + hsmbus->Instance->TIMINGR = hsmbus->Init.Timing & TIMING_CLEAR_MASK; + + /*---------------------------- SMBUSx TIMEOUTR Configuration ------------------------*/ + /* Configure SMBUSx: Bus Timeout */ + hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TIMOUTEN; + hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TEXTEN; + hsmbus->Instance->TIMEOUTR = hsmbus->Init.SMBusTimeout; + + /*---------------------------- SMBUSx OAR1 Configuration -----------------------*/ + /* Configure SMBUSx: Own Address1 and ack own address1 mode */ + hsmbus->Instance->OAR1 &= ~I2C_OAR1_OA1EN; + + if (hsmbus->Init.OwnAddress1 != 0UL) + { + if (hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_7BIT) + { + hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | hsmbus->Init.OwnAddress1); + } + } + + /*---------------------------- SMBUSx CR2 Configuration ------------------------*/ + /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process) */ + /* AUTOEND and NACK bit will be manage during Transfer process */ + hsmbus->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); + + /*---------------------------- SMBUSx OAR2 Configuration -----------------------*/ + /* Configure SMBUSx: Dual mode and Own Address2 */ + hsmbus->Instance->OAR2 = (hsmbus->Init.DualAddressMode | hsmbus->Init.OwnAddress2 | \ + (hsmbus->Init.OwnAddress2Masks << 8U)); + + /*---------------------------- SMBUSx CR1 Configuration ------------------------*/ + /* Configure SMBUSx: Generalcall and NoStretch mode */ + hsmbus->Instance->CR1 = (hsmbus->Init.GeneralCallMode | hsmbus->Init.NoStretchMode | \ + hsmbus->Init.PacketErrorCheckMode | hsmbus->Init.PeripheralMode | \ + hsmbus->Init.AnalogFilter); + + /* Enable Slave Byte Control only in case of Packet Error Check is enabled + and SMBUS Peripheral is set in Slave mode */ + if ((hsmbus->Init.PacketErrorCheckMode == SMBUS_PEC_ENABLE) && \ + ((hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ + (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP))) + { + hsmbus->Instance->CR1 |= I2C_CR1_SBC; + } + + /* Enable the selected SMBUS peripheral */ + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitialize the SMBUS peripheral. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if (hsmbus == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the SMBUS Peripheral Clock */ + __HAL_SMBUS_DISABLE(hsmbus); + +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + if (hsmbus->MspDeInitCallback == NULL) + { + hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + hsmbus->MspDeInitCallback(hsmbus); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_SMBUS_MspDeInit(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + hsmbus->PreviousState = HAL_SMBUS_STATE_RESET; + hsmbus->State = HAL_SMBUS_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} + +/** + * @brief Initialize the SMBUS MSP. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitialize the SMBUS MSP. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Configure Analog noise filter. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param AnalogFilter This parameter can be one of the following values: + * @arg @ref SMBUS_ANALOGFILTER_ENABLE + * @arg @ref SMBUS_ANALOGFILTER_DISABLE + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_ConfigAnalogFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t AnalogFilter) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_ANALOG_FILTER(AnalogFilter)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /* Reset ANOFF bit */ + hsmbus->Instance->CR1 &= ~(I2C_CR1_ANFOFF); + + /* Set analog filter bit*/ + hsmbus->Instance->CR1 |= AnalogFilter; + + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Configure Digital noise filter. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DigitalFilter Coefficient of digital noise filter between Min_Data=0x00 and Max_Data=0x0F. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_ConfigDigitalFilter(SMBUS_HandleTypeDef *hsmbus, uint32_t DigitalFilter) +{ + uint32_t tmpreg; + + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_DIGITAL_FILTER(DigitalFilter)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /* Get the old register value */ + tmpreg = hsmbus->Instance->CR1; + + /* Reset I2C DNF bits [11:8] */ + tmpreg &= ~(I2C_CR1_DNF); + + /* Set I2Cx DNF coefficient */ + tmpreg |= DigitalFilter << I2C_CR1_DNF_Pos; + + /* Store the new register value */ + hsmbus->Instance->CR1 = tmpreg; + + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SMBUS Callback + * To be used instead of the weak predefined callback + * @note The HAL_SMBUS_RegisterCallback() may be called before HAL_SMBUS_Init() in + * HAL_SMBUS_STATE_RESET to register callbacks for HAL_SMBUS_MSPINIT_CB_ID and + * HAL_SMBUS_MSPDEINIT_CB_ID. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref HAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref HAL_SMBUS_ERROR_CB_ID Error callback ID + * @arg @ref HAL_SMBUS_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_RegisterCallback(SMBUS_HandleTypeDef *hsmbus, + HAL_SMBUS_CallbackIDTypeDef CallbackID, + pSMBUS_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (HAL_SMBUS_STATE_READY == hsmbus->State) + { + switch (CallbackID) + { + case HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : + hsmbus->MasterTxCpltCallback = pCallback; + break; + + case HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : + hsmbus->MasterRxCpltCallback = pCallback; + break; + + case HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : + hsmbus->SlaveTxCpltCallback = pCallback; + break; + + case HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : + hsmbus->SlaveRxCpltCallback = pCallback; + break; + + case HAL_SMBUS_LISTEN_COMPLETE_CB_ID : + hsmbus->ListenCpltCallback = pCallback; + break; + + case HAL_SMBUS_ERROR_CB_ID : + hsmbus->ErrorCallback = pCallback; + break; + + case HAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = pCallback; + break; + + case HAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SMBUS_STATE_RESET == hsmbus->State) + { + switch (CallbackID) + { + case HAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = pCallback; + break; + + case HAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an SMBUS Callback + * SMBUS callback is redirected to the weak predefined callback + * @note The HAL_SMBUS_UnRegisterCallback() may be called before HAL_SMBUS_Init() in + * HAL_SMBUS_STATE_RESET to un-register callbacks for HAL_SMBUS_MSPINIT_CB_ID and + * HAL_SMBUS_MSPDEINIT_CB_ID + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * This parameter can be one of the following values: + * @arg @ref HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID + * @arg @ref HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID + * @arg @ref HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID + * @arg @ref HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID + * @arg @ref HAL_SMBUS_LISTEN_COMPLETE_CB_ID Listen Complete callback ID + * @arg @ref HAL_SMBUS_ERROR_CB_ID Error callback ID + * @arg @ref HAL_SMBUS_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_SMBUS_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_UnRegisterCallback(SMBUS_HandleTypeDef *hsmbus, + HAL_SMBUS_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_SMBUS_STATE_READY == hsmbus->State) + { + switch (CallbackID) + { + case HAL_SMBUS_MASTER_TX_COMPLETE_CB_ID : + hsmbus->MasterTxCpltCallback = HAL_SMBUS_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ + break; + + case HAL_SMBUS_MASTER_RX_COMPLETE_CB_ID : + hsmbus->MasterRxCpltCallback = HAL_SMBUS_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ + break; + + case HAL_SMBUS_SLAVE_TX_COMPLETE_CB_ID : + hsmbus->SlaveTxCpltCallback = HAL_SMBUS_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ + break; + + case HAL_SMBUS_SLAVE_RX_COMPLETE_CB_ID : + hsmbus->SlaveRxCpltCallback = HAL_SMBUS_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ + break; + + case HAL_SMBUS_LISTEN_COMPLETE_CB_ID : + hsmbus->ListenCpltCallback = HAL_SMBUS_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ + break; + + case HAL_SMBUS_ERROR_CB_ID : + hsmbus->ErrorCallback = HAL_SMBUS_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SMBUS_STATE_RESET == hsmbus->State) + { + switch (CallbackID) + { + case HAL_SMBUS_MSPINIT_CB_ID : + hsmbus->MspInitCallback = HAL_SMBUS_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_SMBUS_MSPDEINIT_CB_ID : + hsmbus->MspDeInitCallback = HAL_SMBUS_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register the Slave Address Match SMBUS Callback + * To be used instead of the weak HAL_SMBUS_AddrCallback() predefined callback + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pCallback pointer to the Address Match Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_RegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus, + pSMBUS_AddrCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (HAL_SMBUS_STATE_READY == hsmbus->State) + { + hsmbus->AddrCallback = pCallback; + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the Slave Address Match SMBUS Callback + * Info Ready SMBUS Callback is redirected to the weak HAL_SMBUS_AddrCallback() predefined callback + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_UnRegisterAddrCallback(SMBUS_HandleTypeDef *hsmbus) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_SMBUS_STATE_READY == hsmbus->State) + { + hsmbus->AddrCallback = HAL_SMBUS_AddrCallback; /* Legacy weak AddrCallback */ + } + else + { + /* Update the error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SMBUS_Exported_Functions_Group2 Input and Output operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SMBUS data + transfers. + + (#) Blocking mode function to check if device is ready for usage is : + (++) HAL_SMBUS_IsDeviceReady() + + (#) There is only one mode of transfer: + (++) Non-Blocking mode : The communication is performed using Interrupts. + These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated SMBUS IRQ when using Interrupt mode. + + (#) Non-Blocking mode functions with Interrupt are : + (++) HAL_SMBUS_Master_Transmit_IT() + (++) HAL_SMBUS_Master_Receive_IT() + (++) HAL_SMBUS_Slave_Transmit_IT() + (++) HAL_SMBUS_Slave_Receive_IT() + (++) HAL_SMBUS_EnableListen_IT() or alias HAL_SMBUS_EnableListen_IT() + (++) HAL_SMBUS_DisableListen_IT() + (++) HAL_SMBUS_EnableAlert_IT() + (++) HAL_SMBUS_DisableAlert_IT() + + (#) A set of Transfer Complete Callbacks are provided in non-Blocking mode: + (++) HAL_SMBUS_MasterTxCpltCallback() + (++) HAL_SMBUS_MasterRxCpltCallback() + (++) HAL_SMBUS_SlaveTxCpltCallback() + (++) HAL_SMBUS_SlaveRxCpltCallback() + (++) HAL_SMBUS_AddrCallback() + (++) HAL_SMBUS_ListenCpltCallback() + (++) HAL_SMBUS_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit in master/host SMBUS mode an amount of data in non-blocking mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, + uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + uint32_t tmp; + + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* In case of Quick command, remove autoend mode */ + /* Manage the stop generation by software */ + if (hsmbus->pBuffPtr == NULL) + { + hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; + } + + if (Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) + { + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, + SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), + SMBUS_GENERATE_START_WRITE); + } + else + { + /* If transfer direction not change, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + + /* Store current volatile XferOptions, misra rule */ + tmp = hsmbus->XferOptions; + + if ((hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) && \ + (IS_SMBUS_TRANSFER_OTHER_OPTIONS_REQUEST(tmp) == 0)) + { + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, + SMBUS_NO_STARTSTOP); + } + /* Else transfer direction change, so generate Restart with new transfer direction */ + else + { + /* Convert OTHER_xxx XferOptions if any */ + SMBUS_ConvertOtherXferOptions(hsmbus); + + /* Handle Transfer */ + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, + hsmbus->XferOptions, + SMBUS_GENERATE_START_WRITE); + } + + /* If PEC mode is enable, size to transmit manage by SW part should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) + { + if (hsmbus->XferSize > 0U) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else + { + return HAL_ERROR; + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master/host SMBUS mode an amount of data in non-blocking mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, + uint16_t Size, uint32_t XferOptions) +{ + uint32_t tmp; + + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* In case of Quick command, remove autoend mode */ + /* Manage the stop generation by software */ + if (hsmbus->pBuffPtr == NULL) + { + hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; + } + + if (Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) + { + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, + SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), + SMBUS_GENERATE_START_READ); + } + else + { + /* If transfer direction not change, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + + /* Store current volatile XferOptions, Misra rule */ + tmp = hsmbus->XferOptions; + + if ((hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) && \ + (IS_SMBUS_TRANSFER_OTHER_OPTIONS_REQUEST(tmp) == 0)) + { + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, + SMBUS_NO_STARTSTOP); + } + /* Else transfer direction change, so generate Restart with new transfer direction */ + else + { + /* Convert OTHER_xxx XferOptions if any */ + SMBUS_ConvertOtherXferOptions(hsmbus); + + /* Handle Transfer */ + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, + hsmbus->XferOptions, + SMBUS_GENERATE_START_READ); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Abort a master/host SMBUS process communication with Interrupt. + * @note This abort can be called only if state is ready + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress) +{ + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + /* Keep the same state as previous */ + /* to perform as well the call of the corresponding end of transfer callback */ + if (hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; + } + else if (hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; + } + else + { + /* Wrong usage of abort function */ + /* This function should be used only in case of abort monitored by master device */ + return HAL_ERROR; + } + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Set NBYTES to 1 to generate a dummy read on SMBUS peripheral */ + /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ + SMBUS_TransferConfig(hsmbus, DevAddress, 1, SMBUS_AUTOEND_MODE, SMBUS_NO_STARTSTOP); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); + } + else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); + } + else + { + /* Nothing to do */ + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave/device SMBUS mode an amount of data in non-blocking mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, + uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0UL)) + { + hsmbus->ErrorCode = HAL_SMBUS_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_TX); + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = (HAL_SMBUS_STATE_SLAVE_BUSY_TX | HAL_SMBUS_STATE_LISTEN); + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Set SBC bit to manage Acknowledge at each bit */ + hsmbus->Instance->CR1 |= I2C_CR1_SBC; + + /* Enable Address Acknowledge */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* Convert OTHER_xxx XferOptions if any */ + SMBUS_ConvertOtherXferOptions(hsmbus); + + if (Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if ((hsmbus->XferSize < hsmbus->XferCount) && (hsmbus->XferSize == MAX_NBYTE_SIZE)) + { + SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, + SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), + SMBUS_NO_STARTSTOP); + } + else + { + /* Set NBYTE to transmit */ + SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, + SMBUS_NO_STARTSTOP); + + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX | SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave/device SMBUS mode an amount of data in non-blocking mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData Pointer to data buffer + * @param Size Amount of data to be sent + * @param XferOptions Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, + uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) + { + if ((pData == NULL) || (Size == 0UL)) + { + hsmbus->ErrorCode = HAL_SMBUS_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_RX); + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = (HAL_SMBUS_STATE_SLAVE_BUSY_RX | HAL_SMBUS_STATE_LISTEN); + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Set SBC bit to manage Acknowledge at each bit */ + hsmbus->Instance->CR1 |= I2C_CR1_SBC; + + /* Enable Address Acknowledge */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferSize = Size; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* Convert OTHER_xxx XferOptions if any */ + SMBUS_ConvertOtherXferOptions(hsmbus); + + /* Set NBYTE to receive */ + /* If XferSize equal "1", or XferSize equal "2" with PEC requested (mean 1 data byte + 1 PEC byte */ + /* no need to set RELOAD bit mode, a ACK will be automatically generated in that case */ + /* else need to set RELOAD bit mode to generate an automatic ACK at each byte Received */ + /* This RELOAD bit will be reset for last BYTE to be receive in SMBUS_Slave_ISR */ + if (((SMBUS_GET_PEC_MODE(hsmbus) != 0UL) && (hsmbus->XferSize == 2U)) || (hsmbus->XferSize == 1U)) + { + SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, + SMBUS_NO_STARTSTOP); + } + else + { + SMBUS_TransferConfig(hsmbus, 0, 1, hsmbus->XferOptions | SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); + } + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Enable the Address listen mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_EnableListen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + hsmbus->State = HAL_SMBUS_STATE_LISTEN; + + /* Enable the Address Match interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ADDR); + + return HAL_OK; +} + +/** + * @brief Disable the Address listen mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Disable Address listen mode only if a transfer is not ongoing */ + if (hsmbus->State == HAL_SMBUS_STATE_LISTEN) + { + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Disable the Address Match interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Enable the SMBUS alert mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + hsmbus->Instance->CR1 |= I2C_CR1_ALERTEN; + + /* Clear ALERT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); + + /* Enable Alert Interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ALERT); + + return HAL_OK; +} +/** + * @brief Disable the SMBUS alert mode with Interrupt. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + hsmbus->Instance->CR1 &= ~I2C_CR1_ALERTEN; + + /* Disable Alert Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ALERT); + + return HAL_OK; +} + +/** + * @brief Check if target device is ready for communication. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress Target device address: The device 7 bits address value + * in datasheet must be shifted to the left before calling the interface + * @param Trials Number of trials + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, + uint32_t Timeout) +{ + uint32_t tickstart; + + __IO uint32_t SMBUS_Trials = 0UL; + + FlagStatus tmp1; + FlagStatus tmp2; + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + do + { + /* Generate Start */ + hsmbus->Instance->CR2 = SMBUS_GENERATE_START(hsmbus->Init.AddressingMode, DevAddress); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set or a NACK flag is set*/ + tickstart = HAL_GetTick(); + + tmp1 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF); + tmp2 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); + + while ((tmp1 == RESET) && (tmp2 == RESET)) + { + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) + { + /* Device is ready */ + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Update SMBUS error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + return HAL_ERROR; + } + } + + tmp1 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF); + tmp2 = __HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF); + } + + /* Check if the NACKF flag has not been set */ + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) + { + /* Wait until STOPF flag is reset */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Device is ready */ + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + /* Wait until STOPF flag is reset */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Clear STOP Flag, auto generated with autoend*/ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + } + + /* Check if the maximum allowed number of trials has been reached */ + if (SMBUS_Trials == Trials) + { + /* Generate Stop */ + hsmbus->Instance->CR2 |= I2C_CR2_STOP; + + /* Wait until STOPF flag is reset */ + if (SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_ERROR; + } + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + } + + /* Increment Trials */ + SMBUS_Trials++; + } while (SMBUS_Trials < Trials); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Update SMBUS error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_ERROR; + } + else + { + return HAL_BUSY; + } +} +/** + * @} + */ + +/** @defgroup SMBUS_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks + * @{ + */ + +/** + * @brief Handle SMBUS event interrupt request. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + /* Use a local variable to store the current ISR flags */ + /* This action will avoid a wrong treatment due to ISR flags change during interrupt handler */ + uint32_t tmpisrvalue = READ_REG(hsmbus->Instance->ISR); + uint32_t tmpcr1value = READ_REG(hsmbus->Instance->CR1); + + /* SMBUS in mode Transmitter ---------------------------------------------------*/ + if ((SMBUS_CHECK_IT_SOURCE(tmpcr1value, (SMBUS_IT_TCI | SMBUS_IT_STOPI | + SMBUS_IT_NACKI | SMBUS_IT_TXI)) != RESET) && + ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TXIS) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) + { + /* Slave mode selected */ + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) + { + (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); + } + /* Master mode selected */ + else if ((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_TX) == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + (void)SMBUS_Master_ISR(hsmbus, tmpisrvalue); + } + else + { + /* Nothing to do */ + } + } + + /* SMBUS in mode Receiver ----------------------------------------------------*/ + if ((SMBUS_CHECK_IT_SOURCE(tmpcr1value, (SMBUS_IT_TCI | SMBUS_IT_STOPI | + SMBUS_IT_NACKI | SMBUS_IT_RXI)) != RESET) && + ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_RXNE) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) + { + /* Slave mode selected */ + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) + { + (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); + } + /* Master mode selected */ + else if ((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_RX) == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + (void)SMBUS_Master_ISR(hsmbus, tmpisrvalue); + } + else + { + /* Nothing to do */ + } + } + + /* SMBUS in mode Listener Only --------------------------------------------------*/ + if (((SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_ADDRI) != RESET) || + (SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_STOPI) != RESET) || + (SMBUS_CHECK_IT_SOURCE(tmpcr1value, SMBUS_IT_NACKI) != RESET)) && + ((SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_ADDR) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || + (SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET))) + { + if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) + { + (void)SMBUS_Slave_ISR(hsmbus, tmpisrvalue); + } + } +} + +/** + * @brief Handle SMBUS error interrupt request. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + SMBUS_ITErrorHandler(hsmbus); +} + +/** + * @brief Master Tx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_MasterTxCpltCallback() could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_MasterRxCpltCallback() could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_SlaveTxCpltCallback() could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_SlaveRxCpltCallback() could be implemented in the user file + */ +} + +/** + * @brief Slave Address Match callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param TransferDirection Master request Transfer Direction (Write/Read) + * @param AddrMatchCode Address Match Code + * @retval None + */ +__weak void HAL_SMBUS_AddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, + uint16_t AddrMatchCode) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + UNUSED(TransferDirection); + UNUSED(AddrMatchCode); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_AddrCallback() could be implemented in the user file + */ +} + +/** + * @brief Listen Complete callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_ListenCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_ListenCpltCallback() could be implemented in the user file + */ +} + +/** + * @brief SMBUS error callback. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsmbus); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMBUS_ErrorCallback() could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SMBUS_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the SMBUS handle state. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL state + */ +uint32_t HAL_SMBUS_GetState(const SMBUS_HandleTypeDef *hsmbus) +{ + /* Return SMBUS handle state */ + return hsmbus->State; +} + +/** + * @brief Return the SMBUS error code. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval SMBUS Error Code + */ +uint32_t HAL_SMBUS_GetError(const SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SMBUS_Private_Functions SMBUS Private Functions + * @brief Data transfers Private functions + * @{ + */ + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param StatusFlags Value of Interrupt Flags. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_AF) != RESET) + { + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Set corresponding Error Code */ + /* No need to generate STOP, it is automatically done */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; + + /* Flush TX register */ + SMBUS_Flush_TXDR(hsmbus); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Error callback to inform upper layer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ErrorCallback(hsmbus); +#else + HAL_SMBUS_ErrorCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_STOPF) != RESET) + { + /* Check and treat errors if errors occurs during STOP process */ + SMBUS_ITErrorHandler(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + SMBUS_RESET_CR2(hsmbus); + + /* Flush remaining data in Fifo register in case of error occurs before TXEmpty */ + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Re-enable the selected SMBUS peripheral */ + __HAL_SMBUS_ENABLE(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + HAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + /* Store Last receive data if any */ + if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) + { + /* Read data from RXDR */ + *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); + + /* Increment Buffer pointer */ + hsmbus->pBuffPtr++; + + if ((hsmbus->XferSize > 0U)) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + SMBUS_RESET_CR2(hsmbus); + + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterRxCpltCallback(hsmbus); +#else + HAL_SMBUS_MasterRxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) + { + /* Read data from RXDR */ + *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); + + /* Increment Buffer pointer */ + hsmbus->pBuffPtr++; + + /* Increment Size counter */ + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TXIS) != RESET) + { + /* Write data to TXDR */ + hsmbus->Instance->TXDR = *hsmbus->pBuffPtr; + + /* Increment Buffer pointer */ + hsmbus->pBuffPtr++; + + /* Increment Size counter */ + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TCR) != RESET) + { + if ((hsmbus->XferCount != 0U) && (hsmbus->XferSize == 0U)) + { + DevAddress = (uint16_t)(hsmbus->Instance->CR2 & I2C_CR2_SADD); + + if (hsmbus->XferCount > MAX_NBYTE_SIZE) + { + SMBUS_TransferConfig(hsmbus, DevAddress, MAX_NBYTE_SIZE, + (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), + SMBUS_NO_STARTSTOP); + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = hsmbus->XferCount; + SMBUS_TransferConfig(hsmbus, DevAddress, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, + SMBUS_NO_STARTSTOP); + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + } + else if ((hsmbus->XferCount == 0U) && (hsmbus->XferSize == 0U)) + { + /* Call TxCpltCallback() if no stop mode is set */ + if (SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + HAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterRxCpltCallback(hsmbus); +#else + HAL_SMBUS_MasterRxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + } + else + { + /* Nothing to do */ + } + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TC) != RESET) + { + if (hsmbus->XferCount == 0U) + { + /* Specific use case for Quick command */ + if (hsmbus->pBuffPtr == NULL) + { + /* Generate a Stop command */ + hsmbus->Instance->CR2 |= I2C_CR2_STOP; + } + /* Call TxCpltCallback() if no stop mode is set */ + else if (SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) + { + /* No Generate Stop, to permit restart mode */ + /* The stop will be done at the end of transfer, when SMBUS_AUTOEND_MODE enable */ + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterTxCpltCallback(hsmbus); +#else + HAL_SMBUS_MasterTxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else if (hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->MasterRxCpltCallback(hsmbus); +#else + HAL_SMBUS_MasterRxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + else + { + /* Nothing to do */ + } + } + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param StatusFlags Value of Interrupt Flags. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus, uint32_t StatusFlags) +{ + uint8_t TransferDirection; + uint16_t SlaveAddrCode; + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_AF) != RESET) + { + /* Check that SMBUS transfer finished */ + /* if yes, normal usecase, a NACK is sent by the HOST when Transfer is finished */ + /* Mean XferCount == 0*/ + /* So clear Flag NACKF only */ + if (hsmbus->XferCount == 0U) + { + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Flush TX register */ + SMBUS_Flush_TXDR(hsmbus); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + } + else + { + /* if no, error usecase, a Non-Acknowledge of last Data is generated by the HOST*/ + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Set HAL State to "Idle" State, mean to LISTEN state */ + /* So reset Slave Busy state */ + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); + + /* Disable RX/TX Interrupts, keep only ADDR Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; + + /* Flush TX register */ + SMBUS_Flush_TXDR(hsmbus); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Error callback to inform upper layer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ErrorCallback(hsmbus); +#else + HAL_SMBUS_ErrorCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_ADDR) != RESET) + { + TransferDirection = (uint8_t)(SMBUS_GET_DIR(hsmbus)); + SlaveAddrCode = (uint16_t)(SMBUS_GET_ADDR_MATCH(hsmbus)); + + /* Disable ADDR interrupt to prevent multiple ADDRInterrupt*/ + /* Other ADDRInterrupt will be treat in next Listen usecase */ + __HAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_ADDRI); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call Slave Addr callback */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); +#else + HAL_SMBUS_AddrCallback(hsmbus, TransferDirection, SlaveAddrCode); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else if ((SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_RXNE) != RESET) || + (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TCR) != RESET)) + { + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) + { + /* Read data from RXDR */ + *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); + + /* Increment Buffer pointer */ + hsmbus->pBuffPtr++; + + hsmbus->XferSize--; + hsmbus->XferCount--; + + if (hsmbus->XferCount == 1U) + { + /* Receive last Byte, can be PEC byte in case of PEC BYTE enabled */ + /* or only the last Byte of Transfer */ + /* So reset the RELOAD bit mode */ + hsmbus->XferOptions &= ~SMBUS_RELOAD_MODE; + SMBUS_TransferConfig(hsmbus, 0, 1, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + else if (hsmbus->XferCount == 0U) + { + /* Last Byte is received, disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + + /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_RX, keep only HAL_SMBUS_STATE_LISTEN */ + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->SlaveRxCpltCallback(hsmbus); +#else + HAL_SMBUS_SlaveRxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + else + { + /* Set Reload for next Bytes */ + SMBUS_TransferConfig(hsmbus, 0, 1, + SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), + SMBUS_NO_STARTSTOP); + + /* Ack last Byte Read */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + } + } + else if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) + { + if ((hsmbus->XferCount != 0U) && (hsmbus->XferSize == 0U)) + { + if (hsmbus->XferCount > MAX_NBYTE_SIZE) + { + SMBUS_TransferConfig(hsmbus, 0, MAX_NBYTE_SIZE, + (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), + SMBUS_NO_STARTSTOP); + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = hsmbus->XferCount; + SMBUS_TransferConfig(hsmbus, 0, (uint8_t)hsmbus->XferSize, hsmbus->XferOptions, + SMBUS_NO_STARTSTOP); + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if (SMBUS_GET_PEC_MODE(hsmbus) != 0UL) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + } + } + else + { + /* Nothing to do */ + } + } + else if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_TXIS) != RESET) + { + /* Write data to TXDR only if XferCount not reach "0" */ + /* A TXIS flag can be set, during STOP treatment */ + /* Check if all Data have already been sent */ + /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ + if (hsmbus->XferCount > 0U) + { + /* Write data to TXDR */ + hsmbus->Instance->TXDR = *hsmbus->pBuffPtr; + + /* Increment Buffer pointer */ + hsmbus->pBuffPtr++; + + hsmbus->XferCount--; + hsmbus->XferSize--; + } + + if (hsmbus->XferCount == 0U) + { + /* Last Byte is Transmitted */ + /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_TX, keep only HAL_SMBUS_STATE_LISTEN */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the corresponding callback to inform upper layer of End of Transfer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->SlaveTxCpltCallback(hsmbus); +#else + HAL_SMBUS_SlaveTxCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + } + else + { + /* Nothing to do */ + } + + /* Check if STOPF is set */ + if (SMBUS_CHECK_FLAG(StatusFlags, SMBUS_FLAG_STOPF) != RESET) + { + if ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) + { + /* Store Last receive data if any */ + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) + { + /* Read data from RXDR */ + *hsmbus->pBuffPtr = (uint8_t)(hsmbus->Instance->RXDR); + + /* Increment Buffer pointer */ + hsmbus->pBuffPtr++; + + if ((hsmbus->XferSize > 0U)) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Disable RX and TX Interrupts */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); + + /* Disable ADDR Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); + + /* Disable Address Acknowledge */ + hsmbus->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear Configuration Register 2 */ + SMBUS_RESET_CR2(hsmbus); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear ADDR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ADDR); + + hsmbus->XferOptions = 0; + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ListenCpltCallback(hsmbus); +#else + HAL_SMBUS_ListenCpltCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} +/** + * @brief Manage the enabling of Interrupts. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param InterruptRequest Value of @ref SMBUS_Interrupt_configuration_definition. + * @retval HAL status + */ +static void SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest) +{ + uint32_t tmpisr = 0UL; + + if ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) + { + /* Enable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if ((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) + { + /* Enable ADDR, STOP interrupt */ + tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_ERRI; + } + + if ((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) + { + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI; + } + + if ((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) + { + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_RXI; + } + + /* Enable interrupts only at the end */ + /* to avoid the risk of SMBUS interrupt handle execution before */ + /* all interrupts requested done */ + __HAL_SMBUS_ENABLE_IT(hsmbus, tmpisr); +} +/** + * @brief Manage the disabling of Interrupts. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param InterruptRequest Value of @ref SMBUS_Interrupt_configuration_definition. + * @retval HAL status + */ +static void SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint32_t InterruptRequest) +{ + uint32_t tmpisr = 0UL; + uint32_t tmpstate = hsmbus->State; + + if ((tmpstate == HAL_SMBUS_STATE_READY) && ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if ((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) + { + /* Disable TC, STOP, NACK and TXI interrupt */ + tmpisr |= SMBUS_IT_TCI | SMBUS_IT_TXI; + + if ((SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) + && ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) + { + /* Disable STOP and NACK interrupt */ + tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; + } + } + + if ((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) + { + /* Disable TC, STOP, NACK and RXI interrupt */ + tmpisr |= SMBUS_IT_TCI | SMBUS_IT_RXI; + + if ((SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) + && ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if ((tmpstate & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) + { + /* Disable STOP and NACK interrupt */ + tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; + } + } + + if ((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) + { + /* Disable ADDR, STOP and NACK interrupt */ + tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI; + + if (SMBUS_GET_ALERT_ENABLED(hsmbus) == 0UL) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + } + + /* Disable interrupts only at the end */ + /* to avoid a breaking situation like at "t" time */ + /* all disable interrupts request are not done */ + __HAL_SMBUS_DISABLE_IT(hsmbus, tmpisr); +} + +/** + * @brief SMBUS interrupts error handler. + * @param hsmbus SMBUS handle. + * @retval None + */ +static void SMBUS_ITErrorHandler(SMBUS_HandleTypeDef *hsmbus) +{ + uint32_t itflags = READ_REG(hsmbus->Instance->ISR); + uint32_t itsources = READ_REG(hsmbus->Instance->CR1); + uint32_t tmpstate; + uint32_t tmperror; + + /* SMBUS Bus error interrupt occurred ------------------------------------*/ + if (((itflags & SMBUS_FLAG_BERR) == SMBUS_FLAG_BERR) && \ + ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_BERR); + } + + /* SMBUS Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if (((itflags & SMBUS_FLAG_OVR) == SMBUS_FLAG_OVR) && \ + ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_OVR); + } + + /* SMBUS Arbitration Loss error interrupt occurred ------------------------------------*/ + if (((itflags & SMBUS_FLAG_ARLO) == SMBUS_FLAG_ARLO) && \ + ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ARLO); + } + + /* SMBUS Timeout error interrupt occurred ---------------------------------------------*/ + if (((itflags & SMBUS_FLAG_TIMEOUT) == SMBUS_FLAG_TIMEOUT) && \ + ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BUSTIMEOUT; + + /* Clear TIMEOUT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT); + } + + /* SMBUS Alert error interrupt occurred -----------------------------------------------*/ + if (((itflags & SMBUS_FLAG_ALERT) == SMBUS_FLAG_ALERT) && \ + ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ALERT; + + /* Clear ALERT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); + } + + /* SMBUS Packet Error Check error interrupt occurred ----------------------------------*/ + if (((itflags & SMBUS_FLAG_PECERR) == SMBUS_FLAG_PECERR) && \ + ((itsources & SMBUS_IT_ERRI) == SMBUS_IT_ERRI)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_PECERR; + + /* Clear PEC error flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); + } + + if (hsmbus->ErrorCode != HAL_SMBUS_ERROR_NONE) + { + /* Flush TX register */ + SMBUS_Flush_TXDR(hsmbus); + } + + /* Store current volatile hsmbus->ErrorCode, misra rule */ + tmperror = hsmbus->ErrorCode; + + /* Call the Error Callback in case of Error detected */ + if ((tmperror != HAL_SMBUS_ERROR_NONE) && (tmperror != HAL_SMBUS_ERROR_ACKF)) + { + /* Do not Reset the HAL state in case of ALERT error */ + if ((tmperror & HAL_SMBUS_ERROR_ALERT) != HAL_SMBUS_ERROR_ALERT) + { + /* Store current volatile hsmbus->State, misra rule */ + tmpstate = hsmbus->State; + + if (((tmpstate & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) + || ((tmpstate & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX)) + { + /* Reset only HAL_SMBUS_STATE_SLAVE_BUSY_XX */ + /* keep HAL_SMBUS_STATE_LISTEN if set */ + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_LISTEN; + } + } + + /* Call the Error callback to inform upper layer */ +#if (USE_HAL_SMBUS_REGISTER_CALLBACKS == 1) + hsmbus->ErrorCallback(hsmbus); +#else + HAL_SMBUS_ErrorCallback(hsmbus); +#endif /* USE_HAL_SMBUS_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Handle SMBUS Communication Timeout. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param Flag Specifies the SMBUS flag to check. + * @param Status The new Flag status (SET or RESET). + * @param Timeout Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, + FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + while ((FlagStatus)(__HAL_SMBUS_GET_FLAG(hsmbus, Flag)) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) + { + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Update SMBUS error code */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_HALTIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_ERROR; + } + } + } + + return HAL_OK; +} + +/** + * @brief SMBUS Tx data register flush process. + * @param hsmbus SMBUS handle. + * @retval None + */ +static void SMBUS_Flush_TXDR(SMBUS_HandleTypeDef *hsmbus) +{ + /* If a pending TXIS flag is set */ + /* Write a dummy data in TXDR to clear it */ + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) + { + hsmbus->Instance->TXDR = 0x00U; + } + + /* Flush TX register if not empty */ + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXE) == RESET) + { + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TXE); + } +} + +/** + * @brief Handle SMBUSx communication when starting transfer or during transfer (TC or TCR flag are set). + * @param hsmbus SMBUS handle. + * @param DevAddress specifies the slave address to be programmed. + * @param Size specifies the number of bytes to be programmed. + * This parameter must be a value between 0 and 255. + * @param Mode New state of the SMBUS START condition generation. + * This parameter can be one or a combination of the following values: + * @arg @ref SMBUS_RELOAD_MODE Enable Reload mode. + * @arg @ref SMBUS_AUTOEND_MODE Enable Automatic end mode. + * @arg @ref SMBUS_SOFTEND_MODE Enable Software end mode and Reload mode. + * @arg @ref SMBUS_SENDPEC_MODE Enable Packet Error Calculation mode. + * @param Request New state of the SMBUS START condition generation. + * This parameter can be one of the following values: + * @arg @ref SMBUS_NO_STARTSTOP Don't Generate stop and start condition. + * @arg @ref SMBUS_GENERATE_STOP Generate stop condition (Size should be set to 0). + * @arg @ref SMBUS_GENERATE_START_READ Generate Restart for read request. + * @arg @ref SMBUS_GENERATE_START_WRITE Generate Restart for write request. + * @retval None + */ +static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, + uint32_t Mode, uint32_t Request) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_TRANSFER_MODE(Mode)); + assert_param(IS_SMBUS_TRANSFER_REQUEST(Request)); + + /* update CR2 register */ + MODIFY_REG(hsmbus->Instance->CR2, + ((I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | \ + (I2C_CR2_RD_WRN & (uint32_t)(Request >> (31UL - I2C_CR2_RD_WRN_Pos))) | \ + I2C_CR2_START | I2C_CR2_STOP | I2C_CR2_PECBYTE)), \ + (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | \ + (((uint32_t)Size << I2C_CR2_NBYTES_Pos) & I2C_CR2_NBYTES) | \ + (uint32_t)Mode | (uint32_t)Request)); +} + +/** + * @brief Convert SMBUSx OTHER_xxx XferOptions to functional XferOptions. + * @param hsmbus SMBUS handle. + * @retval None + */ +static void SMBUS_ConvertOtherXferOptions(SMBUS_HandleTypeDef *hsmbus) +{ + /* if user set XferOptions to SMBUS_OTHER_FRAME_NO_PEC */ + /* it request implicitly to generate a restart condition */ + /* set XferOptions to SMBUS_FIRST_FRAME */ + if (hsmbus->XferOptions == SMBUS_OTHER_FRAME_NO_PEC) + { + hsmbus->XferOptions = SMBUS_FIRST_FRAME; + } + /* else if user set XferOptions to SMBUS_OTHER_FRAME_WITH_PEC */ + /* it request implicitly to generate a restart condition */ + /* set XferOptions to SMBUS_FIRST_FRAME | SMBUS_SENDPEC_MODE */ + else if (hsmbus->XferOptions == SMBUS_OTHER_FRAME_WITH_PEC) + { + hsmbus->XferOptions = SMBUS_FIRST_FRAME | SMBUS_SENDPEC_MODE; + } + /* else if user set XferOptions to SMBUS_OTHER_AND_LAST_FRAME_NO_PEC */ + /* it request implicitly to generate a restart condition */ + /* then generate a stop condition at the end of transfer */ + /* set XferOptions to SMBUS_FIRST_AND_LAST_FRAME_NO_PEC */ + else if (hsmbus->XferOptions == SMBUS_OTHER_AND_LAST_FRAME_NO_PEC) + { + hsmbus->XferOptions = SMBUS_FIRST_AND_LAST_FRAME_NO_PEC; + } + /* else if user set XferOptions to SMBUS_OTHER_AND_LAST_FRAME_WITH_PEC */ + /* it request implicitly to generate a restart condition */ + /* then generate a stop condition at the end of transfer */ + /* set XferOptions to SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC */ + else if (hsmbus->XferOptions == SMBUS_OTHER_AND_LAST_FRAME_WITH_PEC) + { + hsmbus->XferOptions = SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC; + } + else + { + /* Nothing to do */ + } +} +/** + * @} + */ + +#endif /* HAL_SMBUS_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus_ex.c index 646af16a2..a158cb3a1 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_smbus_ex.c @@ -1,245 +1,245 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_smbus_ex.c - * @author MCD Application Team - * @brief SMBUS Extended HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of SMBUS Extended peripheral: - * + Extended features functions - * + WakeUp Mode Functions - * + FastModePlus Functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### SMBUS peripheral Extended features ##### - ============================================================================== - - [..] Comparing to other previous devices, the SMBUS interface for STM32H7RSxx - devices contains the following additional features - - (+) Disable or enable wakeup from Stop mode(s) - - ##### How to use this driver ##### - ============================================================================== - (#) Configure the enable or disable of SMBUS Wake Up Mode using the functions : - (++) HAL_SMBUSEx_EnableWakeUp() - (++) HAL_SMBUSEx_DisableWakeUp() - (#) Configure the enable or disable of fast mode plus driving capability using the functions : - (++) HAL_SMBUSEx_ConfigFastModePlus() - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SMBUSEx SMBUSEx - * @brief SMBUS Extended HAL module driver - * @{ - */ - -#ifdef HAL_SMBUS_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ - -/** @defgroup SMBUSEx_Exported_Functions SMBUS Extended Exported Functions - * @{ - */ - -/** @defgroup SMBUSEx_Exported_Functions_Group2 WakeUp Mode Functions - * @brief WakeUp Mode Functions - * -@verbatim - =============================================================================== - ##### WakeUp Mode Functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure Wake Up Feature - -@endverbatim - * @{ - */ - -/** - * @brief Enable SMBUS wakeup from Stop mode(s). - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUSx peripheral. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUSEx_EnableWakeUp(SMBUS_HandleTypeDef *hsmbus) -{ - /* Check the parameters */ - assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hsmbus->Instance)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - /* Enable wakeup from stop mode */ - hsmbus->Instance->CR1 |= I2C_CR1_WUPEN; - - __HAL_SMBUS_ENABLE(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Disable SMBUS wakeup from Stop mode(s). - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUSx peripheral. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUSEx_DisableWakeUp(SMBUS_HandleTypeDef *hsmbus) -{ - /* Check the parameters */ - assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hsmbus->Instance)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - /* Disable wakeup from stop mode */ - hsmbus->Instance->CR1 &= ~(I2C_CR1_WUPEN); - - __HAL_SMBUS_ENABLE(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} -/** - * @} - */ - -/** @defgroup SMBUSEx_Exported_Functions_Group3 Fast Mode Plus Functions - * @brief Fast Mode Plus Functions - * -@verbatim - =============================================================================== - ##### Fast Mode Plus Functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Configure Fast Mode Plus - -@endverbatim - * @{ - */ - -/** - * @brief Configure SMBUS Fast Mode Plus. - * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains - * the configuration information for the specified SMBUSx peripheral. - * @param FastModePlus New state of the Fast Mode Plus. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SMBUSEx_ConfigFastModePlus(SMBUS_HandleTypeDef *hsmbus, uint32_t FastModePlus) -{ - /* Check the parameters */ - assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); - assert_param(IS_SMBUS_FASTMODEPLUS(FastModePlus)); - - if (hsmbus->State == HAL_SMBUS_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_BUSY; - - /* Disable the selected SMBUS peripheral */ - __HAL_SMBUS_DISABLE(hsmbus); - - if (FastModePlus == SMBUS_FASTMODEPLUS_ENABLE) - { - /* Set SMBUSx FMP bit */ - hsmbus->Instance->CR1 |= (I2C_CR1_FMP); - } - else - { - /* Reset SMBUSx FMP bit */ - hsmbus->Instance->CR1 &= ~(I2C_CR1_FMP); - } - - __HAL_SMBUS_ENABLE(hsmbus); - - hsmbus->State = HAL_SMBUS_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsmbus); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_SMBUS_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_smbus_ex.c + * @author MCD Application Team + * @brief SMBUS Extended HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of SMBUS Extended peripheral: + * + Extended features functions + * + WakeUp Mode Functions + * + FastModePlus Functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### SMBUS peripheral Extended features ##### + ============================================================================== + + [..] Comparing to other previous devices, the SMBUS interface for STM32H7RSxx + devices contains the following additional features + + (+) Disable or enable wakeup from Stop mode(s) + + ##### How to use this driver ##### + ============================================================================== + (#) Configure the enable or disable of SMBUS Wake Up Mode using the functions : + (++) HAL_SMBUSEx_EnableWakeUp() + (++) HAL_SMBUSEx_DisableWakeUp() + (#) Configure the enable or disable of fast mode plus driving capability using the functions : + (++) HAL_SMBUSEx_ConfigFastModePlus() + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SMBUSEx SMBUSEx + * @brief SMBUS Extended HAL module driver + * @{ + */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMBUSEx_Exported_Functions SMBUS Extended Exported Functions + * @{ + */ + +/** @defgroup SMBUSEx_Exported_Functions_Group2 WakeUp Mode Functions + * @brief WakeUp Mode Functions + * +@verbatim + =============================================================================== + ##### WakeUp Mode Functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Wake Up Feature + +@endverbatim + * @{ + */ + +/** + * @brief Enable SMBUS wakeup from Stop mode(s). + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUSEx_EnableWakeUp(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the parameters */ + assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hsmbus->Instance)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /* Enable wakeup from stop mode */ + hsmbus->Instance->CR1 |= I2C_CR1_WUPEN; + + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Disable SMBUS wakeup from Stop mode(s). + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUSEx_DisableWakeUp(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the parameters */ + assert_param(IS_I2C_WAKEUP_FROMSTOP_INSTANCE(hsmbus->Instance)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /* Disable wakeup from stop mode */ + hsmbus->Instance->CR1 &= ~(I2C_CR1_WUPEN); + + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @} + */ + +/** @defgroup SMBUSEx_Exported_Functions_Group3 Fast Mode Plus Functions + * @brief Fast Mode Plus Functions + * +@verbatim + =============================================================================== + ##### Fast Mode Plus Functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Fast Mode Plus + +@endverbatim + * @{ + */ + +/** + * @brief Configure SMBUS Fast Mode Plus. + * @param hsmbus Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @param FastModePlus New state of the Fast Mode Plus. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUSEx_ConfigFastModePlus(SMBUS_HandleTypeDef *hsmbus, uint32_t FastModePlus) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_FASTMODEPLUS(FastModePlus)); + + if (hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + if (FastModePlus == SMBUS_FASTMODEPLUS_ENABLE) + { + /* Set SMBUSx FMP bit */ + hsmbus->Instance->CR1 |= (I2C_CR1_FMP); + } + else + { + /* Reset SMBUSx FMP bit */ + hsmbus->Instance->CR1 &= ~(I2C_CR1_FMP); + } + + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SMBUS_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spdifrx.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spdifrx.c index 8edd76f1c..7d670b724 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spdifrx.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spdifrx.c @@ -1,1741 +1,1741 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_spdifrx.c - * @author MCD Application Team - * @brief This file provides firmware functions to manage the following - * functionalities of the SPDIFRX audio interface: - * + Initialization and Configuration - * + Data transfers functions - * + DMA transfers management - * + Interrupts and flags management - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - =============================================================================== - ##### How to use this driver ##### - =============================================================================== - [..] - The SPDIFRX HAL driver can be used as follow: - - (#) Declare SPDIFRX_HandleTypeDef handle structure. - (#) Initialize the SPDIFRX low level resources by implement the HAL_SPDIFRX_MspInit() API: - (##) Enable the SPDIFRX interface clock. - (##) SPDIFRX pins configuration: - (+++) Enable the clock for the SPDIFRX GPIOs. - (+++) Configure these SPDIFRX pins as alternate function pull-up. - (##) NVIC configuration if you need to use interrupt process (HAL_SPDIFRX_ReceiveCtrlFlow_IT() and - HAL_SPDIFRX_ReceiveDataFlow_IT() API's). - (+++) Configure the SPDIFRX interrupt priority. - (+++) Enable the NVIC SPDIFRX IRQ handle. - (##) DMA Configuration if you need to use DMA process (HAL_SPDIFRX_ReceiveDataFlow_DMA() and - HAL_SPDIFRX_ReceiveCtrlFlow_DMA() API's). - (+++) Declare a DMA handle structure for the reception of the Data Flow channel. - (+++) Declare a DMA handle structure for the reception of the Control Flow channel. - (+++) Enable the DMAx interface clock. - (+++) Configure the declared DMA handle structure CtrlRx/DataRx with the required parameters. - (+++) Configure the DMA Channel. - (+++) Associate the initialized DMA handle to the SPDIFRX DMA CtrlRx/DataRx handle. - (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the - DMA CtrlRx/DataRx channel. - - (#) Program the input selection, re-tries number, wait for activity, channel status selection, data format, - stereo mode and masking of user bits using HAL_SPDIFRX_Init() function. - - -@- The specific SPDIFRX interrupts (RXNE/CSRNE and Error Interrupts) will be managed using the macros - __SPDIFRX_ENABLE_IT() and __SPDIFRX_DISABLE_IT() inside the receive process. - -@- Make sure that ck_spdif clock is configured. - - (#) Three operation modes are available within this driver : - - *** Polling mode for reception operation (for debug purpose) *** - ================================================================ - [..] - (+) Receive data flow in blocking mode using HAL_SPDIFRX_ReceiveDataFlow() - (+) Receive control flow of data in blocking mode using HAL_SPDIFRX_ReceiveCtrlFlow() - - *** Interrupt mode for reception operation *** - ========================================= - [..] - (+) Receive an amount of data (Data Flow) in non blocking mode using HAL_SPDIFRX_ReceiveDataFlow_IT() - (+) Receive an amount of data (Control Flow) in non blocking mode using HAL_SPDIFRX_ReceiveCtrlFlow_IT() - (+) At reception end of half transfer HAL_SPDIFRX_RxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SPDIFRX_RxHalfCpltCallback - (+) At reception end of transfer HAL_SPDIFRX_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SPDIFRX_RxCpltCallback - (+) In case of transfer Error, HAL_SPDIFRX_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_SPDIFRX_ErrorCallback - - *** DMA mode for reception operation *** - ======================================== - [..] - (+) Receive an amount of data (Data Flow) in non blocking mode (DMA) using HAL_SPDIFRX_ReceiveDataFlow_DMA() - (+) Receive an amount of data (Control Flow) in non blocking mode (DMA) using HAL_SPDIFRX_ReceiveCtrlFlow_DMA() - (+) At reception end of half transfer HAL_SPDIFRX_RxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SPDIFRX_RxHalfCpltCallback - (+) At reception end of transfer HAL_SPDIFRX_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SPDIFRX_RxCpltCallback - (+) In case of transfer Error, HAL_SPDIFRX_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_SPDIFRX_ErrorCallback - (+) Stop the DMA Transfer using HAL_SPDIFRX_DMAStop() - - *** SPDIFRX HAL driver macros list *** - ============================================= - [..] - Below the list of most used macros in SPDIFRX HAL driver. - (+) __HAL_SPDIFRX_IDLE: Disable the specified SPDIFRX peripheral (IDLE State) - (+) __HAL_SPDIFRX_SYNC: Enable the synchronization state of the specified SPDIFRX peripheral (SYNC State) - (+) __HAL_SPDIFRX_RCV: Enable the receive state of the specified SPDIFRX peripheral (RCV State) - (+) __HAL_SPDIFRX_ENABLE_IT : Enable the specified SPDIFRX interrupts - (+) __HAL_SPDIFRX_DISABLE_IT : Disable the specified SPDIFRX interrupts - (+) __HAL_SPDIFRX_GET_FLAG: Check whether the specified SPDIFRX flag is set or not. - - [..] - (@) You can refer to the SPDIFRX HAL driver header file for more useful macros - - *** Callback registration *** - ============================================= - - The compilation define USE_HAL_SPDIFRX_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use HAL_SPDIFRX_RegisterCallback() function to register an interrupt callback. - - The HAL_SPDIFRX_RegisterCallback() function allows to register the following callbacks: - (+) RxHalfCpltCallback : SPDIFRX Data flow half completed callback. - (+) RxCpltCallback : SPDIFRX Data flow completed callback. - (+) CxHalfCpltCallback : SPDIFRX Control flow half completed callback. - (+) CxCpltCallback : SPDIFRX Control flow completed callback. - (+) ErrorCallback : SPDIFRX error callback. - (+) MspInitCallback : SPDIFRX MspInit. - (+) MspDeInitCallback : SPDIFRX MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use HAL_SPDIFRX_UnRegisterCallback() function to reset a callback to the default - weak function. - The HAL_SPDIFRX_UnRegisterCallback() function takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset the following callbacks: - (+) RxHalfCpltCallback : SPDIFRX Data flow half completed callback. - (+) RxCpltCallback : SPDIFRX Data flow completed callback. - (+) CxHalfCpltCallback : SPDIFRX Control flow half completed callback. - (+) CxCpltCallback : SPDIFRX Control flow completed callback. - (+) ErrorCallback : SPDIFRX error callback. - (+) MspInitCallback : SPDIFRX MspInit. - (+) MspDeInitCallback : SPDIFRX MspDeInit. - - By default, after the HAL_SPDIFRX_Init() and when the state is HAL_SPDIFRX_STATE_RESET - all callbacks are set to the corresponding weak functions : - HAL_SPDIFRX_RxHalfCpltCallback() , HAL_SPDIFRX_RxCpltCallback(), HAL_SPDIFRX_CxHalfCpltCallback(), - HAL_SPDIFRX_CxCpltCallback() and HAL_SPDIFRX_ErrorCallback() - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak function in the HAL_SPDIFRX_Init()/ HAL_SPDIFRX_DeInit() only when - these callbacks pointers are NULL (not registered beforehand). - If not, MspInit or MspDeInit callbacks pointers are not null, the HAL_SPDIFRX_Init() / HAL_SPDIFRX_DeInit() - keep and use the user MspInit/MspDeInit functions (registered beforehand) - - Callbacks can be registered/unregistered in HAL_SPDIFRX_STATE_READY state only. - Exception done MspInit/MspDeInit callbacks that can be registered/unregistered - in HAL_SPDIFRX_STATE_READY or HAL_SPDIFRX_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_SPDIFRX_RegisterCallback() before calling HAL_SPDIFRX_DeInit() - or HAL_SPDIFRX_Init() function. - - When The compilation define USE_HAL_SPDIFRX_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SPDIFRX SPDIFRX - * @brief SPDIFRX HAL module driver - * @{ - */ - -#ifdef HAL_SPDIFRX_MODULE_ENABLED -#if defined (SPDIFRX) - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup SPDIFRX_Private_Defines SPDIFRX Private Defines - * @{ - */ -#define SPDIFRX_TIMEOUT_VALUE 10U -/** - * @} - */ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SPDIFRX_Private_Functions - * @{ - */ -static void SPDIFRX_DMARxCplt(DMA_HandleTypeDef *hdma); -static void SPDIFRX_DMARxHalfCplt(DMA_HandleTypeDef *hdma); -static void SPDIFRX_DMACxCplt(DMA_HandleTypeDef *hdma); -static void SPDIFRX_DMACxHalfCplt(DMA_HandleTypeDef *hdma); -static void SPDIFRX_DMAError(DMA_HandleTypeDef *hdma); -static void SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif); -static void SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif); -static HAL_StatusTypeDef SPDIFRX_WaitOnFlagUntilTimeout(SPDIFRX_HandleTypeDef *hspdif, uint32_t Flag, - FlagStatus Status, uint32_t Timeout, uint32_t tickstart); -/** - * @} - */ -/* Exported functions ---------------------------------------------------------*/ - -/** @defgroup SPDIFRX_Exported_Functions SPDIFRX Exported Functions - * @{ - */ - -/** @defgroup SPDIFRX_Exported_Functions_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 SPDIFRX peripheral: - - (+) User must Implement HAL_SPDIFRX_MspInit() function in which he configures - all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). - - (+) Call the function HAL_SPDIFRX_Init() to configure the SPDIFRX peripheral with - the selected configuration: - (++) Input Selection (IN0, IN1,...) - (++) Maximum allowed re-tries during synchronization phase - (++) Wait for activity on SPDIF selected input - (++) Channel status selection (from channel A or B) - (++) Data format (LSB, MSB, ...) - (++) Stereo mode - (++) User bits masking (PT,C,U,V,...) - - (+) Call the function HAL_SPDIFRX_DeInit() to restore the default configuration - of the selected SPDIFRXx peripheral. - @endverbatim - * @{ - */ - -/** - * @brief Initializes the SPDIFRX according to the specified parameters - * in the SPDIFRX_InitTypeDef and create the associated handle. - * @param hspdif SPDIFRX handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_Init(SPDIFRX_HandleTypeDef *hspdif) -{ - uint32_t tmpreg; - - /* Check the SPDIFRX handle allocation */ - if (hspdif == NULL) - { - return HAL_ERROR; - } - - /* Check the SPDIFRX parameters */ - assert_param(IS_STEREO_MODE(hspdif->Init.StereoMode)); - assert_param(IS_SPDIFRX_INPUT_SELECT(hspdif->Init.InputSelection)); - assert_param(IS_SPDIFRX_MAX_RETRIES(hspdif->Init.Retries)); - assert_param(IS_SPDIFRX_WAIT_FOR_ACTIVITY(hspdif->Init.WaitForActivity)); - assert_param(IS_SPDIFRX_CHANNEL(hspdif->Init.ChannelSelection)); - assert_param(IS_SPDIFRX_DATA_FORMAT(hspdif->Init.DataFormat)); - assert_param(IS_PREAMBLE_TYPE_MASK(hspdif->Init.PreambleTypeMask)); - assert_param(IS_CHANNEL_STATUS_MASK(hspdif->Init.ChannelStatusMask)); - assert_param(IS_VALIDITY_MASK(hspdif->Init.ValidityBitMask)); - assert_param(IS_PARITY_ERROR_MASK(hspdif->Init.ParityErrorMask)); - assert_param(IS_SYMBOL_CLOCK_GEN(hspdif->Init.SymbolClockGen)); - assert_param(IS_SYMBOL_CLOCK_GEN(hspdif->Init.BackupSymbolClockGen)); - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - if (hspdif->State == HAL_SPDIFRX_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hspdif->Lock = HAL_UNLOCKED; - - hspdif->RxHalfCpltCallback = HAL_SPDIFRX_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - hspdif->RxCpltCallback = HAL_SPDIFRX_RxCpltCallback; /* Legacy weak RxCpltCallback */ - hspdif->CxHalfCpltCallback = HAL_SPDIFRX_CxHalfCpltCallback; /* Legacy weak CxHalfCpltCallback */ - hspdif->CxCpltCallback = HAL_SPDIFRX_CxCpltCallback; /* Legacy weak CxCpltCallback */ - hspdif->ErrorCallback = HAL_SPDIFRX_ErrorCallback; /* Legacy weak ErrorCallback */ - - if (hspdif->MspInitCallback == NULL) - { - hspdif->MspInitCallback = HAL_SPDIFRX_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware */ - hspdif->MspInitCallback(hspdif); - } -#else - if (hspdif->State == HAL_SPDIFRX_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hspdif->Lock = HAL_UNLOCKED; - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_SPDIFRX_MspInit(hspdif); - } -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ - - /* SPDIFRX peripheral state is BUSY */ - hspdif->State = HAL_SPDIFRX_STATE_BUSY; - - /* Disable SPDIFRX interface (IDLE State) */ - __HAL_SPDIFRX_IDLE(hspdif); - - /* Reset the old SPDIFRX CR configuration */ - tmpreg = hspdif->Instance->CR; - - tmpreg &= ~(SPDIFRX_CR_RXSTEO | SPDIFRX_CR_DRFMT | SPDIFRX_CR_PMSK | - SPDIFRX_CR_VMSK | SPDIFRX_CR_CUMSK | SPDIFRX_CR_PTMSK | - SPDIFRX_CR_CHSEL | SPDIFRX_CR_NBTR | SPDIFRX_CR_WFA | - SPDIFRX_CR_CKSEN | SPDIFRX_CR_CKSBKPEN | - SPDIFRX_CR_INSEL); - - /* Sets the new configuration of the SPDIFRX peripheral */ - tmpreg |= (hspdif->Init.StereoMode | - hspdif->Init.InputSelection | - hspdif->Init.Retries | - hspdif->Init.WaitForActivity | - hspdif->Init.ChannelSelection | - hspdif->Init.DataFormat | - hspdif->Init.PreambleTypeMask | - hspdif->Init.ChannelStatusMask | - hspdif->Init.ValidityBitMask | - hspdif->Init.ParityErrorMask - ); - - if (hspdif->Init.SymbolClockGen == ENABLE) - { - tmpreg |= SPDIFRX_CR_CKSEN; - } - - if (hspdif->Init.BackupSymbolClockGen == ENABLE) - { - tmpreg |= SPDIFRX_CR_CKSBKPEN; - } - - hspdif->Instance->CR = tmpreg; - - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; - - /* SPDIFRX peripheral state is READY*/ - hspdif->State = HAL_SPDIFRX_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitializes the SPDIFRX peripheral - * @param hspdif SPDIFRX handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_DeInit(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Check the SPDIFRX handle allocation */ - if (hspdif == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SPDIFRX_ALL_INSTANCE(hspdif->Instance)); - - hspdif->State = HAL_SPDIFRX_STATE_BUSY; - - /* Disable SPDIFRX interface (IDLE state) */ - __HAL_SPDIFRX_IDLE(hspdif); - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - if (hspdif->MspDeInitCallback == NULL) - { - hspdif->MspDeInitCallback = HAL_SPDIFRX_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware */ - hspdif->MspDeInitCallback(hspdif); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ - HAL_SPDIFRX_MspDeInit(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ - - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; - - /* SPDIFRX peripheral state is RESET*/ - hspdif->State = HAL_SPDIFRX_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; -} - -/** - * @brief SPDIFRX MSP Init - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_MspInit(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_MspInit could be implemented in the user file - */ -} - -/** - * @brief SPDIFRX MSP DeInit - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_MspDeInit(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User SPDIFRX Callback - * To be used instead of the weak predefined callback - * @param hspdif SPDIFRX handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SPDIFRX_RX_HALF_CB_ID SPDIFRX Data flow half completed callback ID - * @arg @ref HAL_SPDIFRX_RX_CPLT_CB_ID SPDIFRX Data flow completed callback ID - * @arg @ref HAL_SPDIFRX_CX_HALF_CB_ID SPDIFRX Control flow half completed callback ID - * @arg @ref HAL_SPDIFRX_CX_CPLT_CB_ID SPDIFRX Control flow completed callback ID - * @arg @ref HAL_SPDIFRX_ERROR_CB_ID SPDIFRX error callback ID - * @arg @ref HAL_SPDIFRX_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_SPDIFRX_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_RegisterCallback(SPDIFRX_HandleTypeDef *hspdif, HAL_SPDIFRX_CallbackIDTypeDef CallbackID, - pSPDIFRX_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hspdif); - - if (HAL_SPDIFRX_STATE_READY == hspdif->State) - { - switch (CallbackID) - { - case HAL_SPDIFRX_RX_HALF_CB_ID : - hspdif->RxHalfCpltCallback = pCallback; - break; - - case HAL_SPDIFRX_RX_CPLT_CB_ID : - hspdif->RxCpltCallback = pCallback; - break; - - case HAL_SPDIFRX_CX_HALF_CB_ID : - hspdif->CxHalfCpltCallback = pCallback; - break; - - case HAL_SPDIFRX_CX_CPLT_CB_ID : - hspdif->CxCpltCallback = pCallback; - break; - - case HAL_SPDIFRX_ERROR_CB_ID : - hspdif->ErrorCallback = pCallback; - break; - - case HAL_SPDIFRX_MSPINIT_CB_ID : - hspdif->MspInitCallback = pCallback; - break; - - case HAL_SPDIFRX_MSPDEINIT_CB_ID : - hspdif->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SPDIFRX_STATE_RESET == hspdif->State) - { - switch (CallbackID) - { - case HAL_SPDIFRX_MSPINIT_CB_ID : - hspdif->MspInitCallback = pCallback; - break; - - case HAL_SPDIFRX_MSPDEINIT_CB_ID : - hspdif->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hspdif); - return status; -} - -/** - * @brief Unregister a SPDIFRX Callback - * SPDIFRX callback is redirected to the weak predefined callback - * @param hspdif SPDIFRX handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_SPDIFRX_RX_HALF_CB_ID SPDIFRX Data flow half completed callback ID - * @arg @ref HAL_SPDIFRX_RX_CPLT_CB_ID SPDIFRX Data flow completed callback ID - * @arg @ref HAL_SPDIFRX_CX_HALF_CB_ID SPDIFRX Control flow half completed callback ID - * @arg @ref HAL_SPDIFRX_CX_CPLT_CB_ID SPDIFRX Control flow completed callback ID - * @arg @ref HAL_SPDIFRX_ERROR_CB_ID SPDIFRX error callback ID - * @arg @ref HAL_SPDIFRX_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_SPDIFRX_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_UnRegisterCallback(SPDIFRX_HandleTypeDef *hspdif, - HAL_SPDIFRX_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hspdif); - - if (HAL_SPDIFRX_STATE_READY == hspdif->State) - { - switch (CallbackID) - { - case HAL_SPDIFRX_RX_HALF_CB_ID : - hspdif->RxHalfCpltCallback = HAL_SPDIFRX_RxHalfCpltCallback; - break; - - case HAL_SPDIFRX_RX_CPLT_CB_ID : - hspdif->RxCpltCallback = HAL_SPDIFRX_RxCpltCallback; - break; - - case HAL_SPDIFRX_CX_HALF_CB_ID : - hspdif->CxHalfCpltCallback = HAL_SPDIFRX_CxHalfCpltCallback; - break; - - case HAL_SPDIFRX_CX_CPLT_CB_ID : - hspdif->CxCpltCallback = HAL_SPDIFRX_CxCpltCallback; - break; - - case HAL_SPDIFRX_ERROR_CB_ID : - hspdif->ErrorCallback = HAL_SPDIFRX_ErrorCallback; - break; - - default : - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SPDIFRX_STATE_RESET == hspdif->State) - { - switch (CallbackID) - { - case HAL_SPDIFRX_MSPINIT_CB_ID : - hspdif->MspInitCallback = HAL_SPDIFRX_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_SPDIFRX_MSPDEINIT_CB_ID : - hspdif->MspDeInitCallback = HAL_SPDIFRX_MspDeInit; /* Legacy weak MspInit */ - break; - - default : - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hspdif); - return status; -} - -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ - -/** - * @brief Set the SPDIFRX data format according to the specified parameters in the SPDIFRX_InitTypeDef. - * @param hspdif SPDIFRX handle - * @param sDataFormat SPDIFRX data format - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_SetDataFormat(SPDIFRX_HandleTypeDef *hspdif, SPDIFRX_SetDataFormatTypeDef sDataFormat) -{ - uint32_t tmpreg; - - /* Check the SPDIFRX handle allocation */ - if (hspdif == NULL) - { - return HAL_ERROR; - } - - /* Check the SPDIFRX parameters */ - assert_param(IS_STEREO_MODE(sDataFormat.StereoMode)); - assert_param(IS_SPDIFRX_DATA_FORMAT(sDataFormat.DataFormat)); - assert_param(IS_PREAMBLE_TYPE_MASK(sDataFormat.PreambleTypeMask)); - assert_param(IS_CHANNEL_STATUS_MASK(sDataFormat.ChannelStatusMask)); - assert_param(IS_VALIDITY_MASK(sDataFormat.ValidityBitMask)); - assert_param(IS_PARITY_ERROR_MASK(sDataFormat.ParityErrorMask)); - - /* Reset the old SPDIFRX CR configuration */ - tmpreg = hspdif->Instance->CR; - - if (((tmpreg & SPDIFRX_STATE_RCV) == SPDIFRX_STATE_RCV) && - (((tmpreg & SPDIFRX_CR_DRFMT) != sDataFormat.DataFormat) || - ((tmpreg & SPDIFRX_CR_RXSTEO) != sDataFormat.StereoMode))) - { - return HAL_ERROR; - } - - tmpreg &= ~(SPDIFRX_CR_RXSTEO | SPDIFRX_CR_DRFMT | SPDIFRX_CR_PMSK | - SPDIFRX_CR_VMSK | SPDIFRX_CR_CUMSK | SPDIFRX_CR_PTMSK); - - /* Configure the new data format */ - tmpreg |= (sDataFormat.StereoMode | - sDataFormat.DataFormat | - sDataFormat.PreambleTypeMask | - sDataFormat.ChannelStatusMask | - sDataFormat.ValidityBitMask | - sDataFormat.ParityErrorMask); - - hspdif->Instance->CR = tmpreg; - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup SPDIFRX_Exported_Functions_Group2 IO operation functions - * @brief Data transfers functions - * -@verbatim -=============================================================================== - ##### IO operation functions ##### -=============================================================================== - [..] - This subsection provides a set of functions allowing to manage the SPDIFRX 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 start-up. - The end of the data processing will be indicated through the - dedicated SPDIFRX IRQ when using Interrupt mode or the DMA IRQ when - using DMA mode. - - (#) Blocking mode functions are : - (++) HAL_SPDIFRX_ReceiveDataFlow() - (++) HAL_SPDIFRX_ReceiveCtrlFlow() - (+@) Do not use blocking mode to receive both control and data flow at the same time. - - (#) No-Blocking mode functions with Interrupt are : - (++) HAL_SPDIFRX_ReceiveCtrlFlow_IT() - (++) HAL_SPDIFRX_ReceiveDataFlow_IT() - - (#) No-Blocking mode functions with DMA are : - (++) HAL_SPDIFRX_ReceiveCtrlFlow_DMA() - (++) HAL_SPDIFRX_ReceiveDataFlow_DMA() - - (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: - (++) HAL_SPDIFRX_RxCpltCallback() - (++) HAL_SPDIFRX_CxCpltCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Receives an amount of data (Data Flow) in blocking mode. - * @param hspdif pointer to SPDIFRX_HandleTypeDef structure that contains - * the configuration information for SPDIFRX module. - * @param pData Pointer to data buffer - * @param Size Amount of data to be received - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, - uint32_t Timeout) -{ - uint32_t tickstart; - uint16_t sizeCounter = Size; - uint32_t *pTmpBuf = pData; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hspdif->State == HAL_SPDIFRX_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hspdif); - - hspdif->State = HAL_SPDIFRX_STATE_BUSY; - - /* Start synchronisation */ - __HAL_SPDIFRX_SYNC(hspdif); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until SYNCD flag is set */ - if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Start reception */ - __HAL_SPDIFRX_RCV(hspdif); - - /* Receive data flow */ - while (sizeCounter > 0U) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until RXNE flag is set */ - if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_TIMEOUT; - } - - (*pTmpBuf) = hspdif->Instance->DR; - pTmpBuf++; - sizeCounter--; - } - - /* SPDIFRX ready */ - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receives an amount of data (Control Flow) in blocking mode. - * @param hspdif pointer to a SPDIFRX_HandleTypeDef structure that contains - * the configuration information for SPDIFRX module. - * @param pData Pointer to data buffer - * @param Size Amount of data to be received - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_ReceiveCtrlFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, - uint32_t Timeout) -{ - uint32_t tickstart; - uint16_t sizeCounter = Size; - uint32_t *pTmpBuf = pData; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if (hspdif->State == HAL_SPDIFRX_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hspdif); - - hspdif->State = HAL_SPDIFRX_STATE_BUSY; - - /* Start synchronization */ - __HAL_SPDIFRX_SYNC(hspdif); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until SYNCD flag is set */ - if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Start reception */ - __HAL_SPDIFRX_RCV(hspdif); - - /* Receive control flow */ - while (sizeCounter > 0U) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until CSRNE flag is set */ - if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_CSRNE, RESET, Timeout, tickstart) != HAL_OK) - { - return HAL_TIMEOUT; - } - - (*pTmpBuf) = hspdif->Instance->CSR; - pTmpBuf++; - sizeCounter--; - } - - /* SPDIFRX ready */ - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data (Data Flow) in non-blocking mode with Interrupt - * @param hspdif SPDIFRX handle - * @param pData a 32-bit pointer to the Receive data buffer. - * @param Size number of data sample to be received . - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) -{ - uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); - - const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; - - if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_CX)) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hspdif); - - hspdif->pRxBuffPtr = pData; - hspdif->RxXferSize = Size; - hspdif->RxXferCount = Size; - - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; - - /* Check if a receive process is ongoing or not */ - hspdif->State = HAL_SPDIFRX_STATE_BUSY_RX; - - /* Enable the SPDIFRX PE Error Interrupt */ - __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - - /* Enable the SPDIFRX OVR Error Interrupt */ - __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - - /* Enable the SPDIFRX RXNE interrupt */ - __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_RXNE); - - if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) - { - /* Start synchronization */ - __HAL_SPDIFRX_SYNC(hspdif); - - /* Wait until SYNCD flag is set */ - do - { - if (count == 0U) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt - process */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_TIMEOUT; - } - count--; - } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); - - /* Start reception */ - __HAL_SPDIFRX_RCV(hspdif); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data (Control Flow) with Interrupt - * @param hspdif SPDIFRX handle - * @param pData a 32-bit pointer to the Receive data buffer. - * @param Size number of data sample (Control Flow) to be received - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_ReceiveCtrlFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) -{ - uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); - - const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; - - if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_RX)) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hspdif); - - hspdif->pCsBuffPtr = pData; - hspdif->CsXferSize = Size; - hspdif->CsXferCount = Size; - - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; - - /* Check if a receive process is ongoing or not */ - hspdif->State = HAL_SPDIFRX_STATE_BUSY_CX; - - /* Enable the SPDIFRX PE Error Interrupt */ - __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - - /* Enable the SPDIFRX OVR Error Interrupt */ - __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - - /* Enable the SPDIFRX CSRNE interrupt */ - __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - - if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) - { - /* Start synchronization */ - __HAL_SPDIFRX_SYNC(hspdif); - - /* Wait until SYNCD flag is set */ - do - { - if (count == 0U) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt - process */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_TIMEOUT; - } - count--; - } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); - - /* Start reception */ - __HAL_SPDIFRX_RCV(hspdif); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data (Data Flow) mode with DMA - * @param hspdif SPDIFRX handle - * @param pData a 32-bit pointer to the Receive data buffer. - * @param Size number of data sample to be received - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) -{ - uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); - - const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_CX)) - { - /* Process Locked */ - __HAL_LOCK(hspdif); - - hspdif->pRxBuffPtr = pData; - hspdif->RxXferSize = Size; - hspdif->RxXferCount = Size; - - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; - hspdif->State = HAL_SPDIFRX_STATE_BUSY_RX; - - /* Set the SPDIFRX Rx DMA Half transfer complete callback */ - hspdif->hdmaDrRx->XferHalfCpltCallback = SPDIFRX_DMARxHalfCplt; - - /* Set the SPDIFRX Rx DMA transfer complete callback */ - hspdif->hdmaDrRx->XferCpltCallback = SPDIFRX_DMARxCplt; - - /* Set the DMA error callback */ - hspdif->hdmaDrRx->XferErrorCallback = SPDIFRX_DMAError; - - /* Enable the DMA request */ - if ((hspdif->hdmaDrRx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hspdif->hdmaDrRx->LinkedListQueue != NULL) - { - hspdif->hdmaDrRx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (uint32_t) Size * 4U; - hspdif->hdmaDrRx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t) &hspdif->Instance->DR; - hspdif->hdmaDrRx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t) hspdif->pRxBuffPtr; - - if (HAL_DMAEx_List_Start_IT(hspdif->hdmaDrRx) != HAL_OK) - { - /* Set SPDIFRX error */ - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; - - /* Set SPDIFRX state */ - hspdif->State = HAL_SPDIFRX_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_ERROR; - } - } - else - { - /* Set SPDIFRX error */ - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; - - /* Set SPDIFRX state */ - hspdif->State = HAL_SPDIFRX_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_ERROR; - } - } - else - { - if (HAL_DMA_Start_IT(hspdif->hdmaDrRx, (uint32_t)&hspdif->Instance->DR, (uint32_t)hspdif->pRxBuffPtr, - (uint32_t) Size * 4U) != HAL_OK) - { - /* Set SPDIFRX error */ - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; - - /* Set SPDIFRX state */ - hspdif->State = HAL_SPDIFRX_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_ERROR; - } - } - - /* Enable RXDMAEN bit in SPDIFRX CR register for data flow reception*/ - hspdif->Instance->CR |= SPDIFRX_CR_RXDMAEN; - - if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) - { - /* Start synchronization */ - __HAL_SPDIFRX_SYNC(hspdif); - - /* Wait until SYNCD flag is set */ - do - { - if (count == 0U) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt - process */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_TIMEOUT; - } - count--; - } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); - - /* Start reception */ - __HAL_SPDIFRX_RCV(hspdif); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data (Control Flow) with DMA - * @param hspdif SPDIFRX handle - * @param pData a 32-bit pointer to the Receive data buffer. - * @param Size number of data (Control Flow) sample to be received - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPDIFRX_ReceiveCtrlFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) -{ - uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); - - const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; - - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_RX)) - { - hspdif->pCsBuffPtr = pData; - hspdif->CsXferSize = Size; - hspdif->CsXferCount = Size; - - /* Process Locked */ - __HAL_LOCK(hspdif); - - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; - hspdif->State = HAL_SPDIFRX_STATE_BUSY_CX; - - /* Set the SPDIFRX Rx DMA Half transfer complete callback */ - hspdif->hdmaCsRx->XferHalfCpltCallback = SPDIFRX_DMACxHalfCplt; - - /* Set the SPDIFRX Rx DMA transfer complete callback */ - hspdif->hdmaCsRx->XferCpltCallback = SPDIFRX_DMACxCplt; - - /* Set the DMA error callback */ - hspdif->hdmaCsRx->XferErrorCallback = SPDIFRX_DMAError; - - /* Enable the DMA request */ - if ((hspdif->hdmaCsRx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hspdif->hdmaCsRx->LinkedListQueue != NULL) - { - hspdif->hdmaCsRx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (uint32_t) Size * 4U; - hspdif->hdmaCsRx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t) &hspdif->Instance->CSR; - hspdif->hdmaCsRx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t) hspdif->pCsBuffPtr; - - if (HAL_DMAEx_List_Start_IT(hspdif->hdmaCsRx) != HAL_OK) - { - /* Set SPDIFRX error */ - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; - - /* Set SPDIFRX state */ - hspdif->State = HAL_SPDIFRX_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_ERROR; - } - } - else - { - /* Set SPDIFRX error */ - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; - - /* Set SPDIFRX state */ - hspdif->State = HAL_SPDIFRX_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_ERROR; - } - } - else - { - if (HAL_DMA_Start_IT(hspdif->hdmaCsRx, (uint32_t)&hspdif->Instance->CSR, (uint32_t)hspdif->pCsBuffPtr, - (uint32_t) Size * 4U) != HAL_OK) - { - /* Set SPDIFRX error */ - hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; - - /* Set SPDIFRX state */ - hspdif->State = HAL_SPDIFRX_STATE_ERROR; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_ERROR; - } - } - - /* Enable CBDMAEN bit in SPDIFRX CR register for control flow reception*/ - hspdif->Instance->CR |= SPDIFRX_CR_CBDMAEN; - - if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) - { - /* Start synchronization */ - __HAL_SPDIFRX_SYNC(hspdif); - - /* Wait until SYNCD flag is set */ - do - { - if (count == 0U) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt - process */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_TIMEOUT; - } - count--; - } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); - - /* Start reception */ - __HAL_SPDIFRX_RCV(hspdif); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief stop the audio stream receive from the Media. - * @param hspdif SPDIFRX handle - * @retval None - */ -HAL_StatusTypeDef HAL_SPDIFRX_DMAStop(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Process Locked */ - __HAL_LOCK(hspdif); - - /* Disable the SPDIFRX DMA requests */ - hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_RXDMAEN); - hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_CBDMAEN); - - /* Disable the SPDIFRX DMA channel */ - if (hspdif->hdmaDrRx != NULL) - { - __HAL_DMA_DISABLE(hspdif->hdmaDrRx); - } - if (hspdif->hdmaCsRx != NULL) - { - __HAL_DMA_DISABLE(hspdif->hdmaCsRx); - } - - /* Disable SPDIFRX peripheral */ - __HAL_SPDIFRX_IDLE(hspdif); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_OK; -} - -/** - * @brief This function handles SPDIFRX interrupt request. - * @param hspdif SPDIFRX handle - * @retval HAL status - */ -void HAL_SPDIFRX_IRQHandler(SPDIFRX_HandleTypeDef *hspdif) -{ - uint32_t itFlag = hspdif->Instance->SR; - uint32_t itSource = hspdif->Instance->IMR; - - /* SPDIFRX in mode Data Flow Reception */ - if (((itFlag & SPDIFRX_FLAG_RXNE) == SPDIFRX_FLAG_RXNE) && ((itSource & SPDIFRX_IT_RXNE) == SPDIFRX_IT_RXNE)) - { - __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_RXNE); - SPDIFRX_ReceiveDataFlow_IT(hspdif); - } - - /* SPDIFRX in mode Control Flow Reception */ - if (((itFlag & SPDIFRX_FLAG_CSRNE) == SPDIFRX_FLAG_CSRNE) && ((itSource & SPDIFRX_IT_CSRNE) == SPDIFRX_IT_CSRNE)) - { - __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_CSRNE); - SPDIFRX_ReceiveControlFlow_IT(hspdif); - } - - /* SPDIFRX Overrun error interrupt occurred */ - if (((itFlag & SPDIFRX_FLAG_OVR) == SPDIFRX_FLAG_OVR) && ((itSource & SPDIFRX_IT_OVRIE) == SPDIFRX_IT_OVRIE)) - { - __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_OVRIE); - - /* Change the SPDIFRX error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_OVR; - - /* the transfer is not stopped */ - HAL_SPDIFRX_ErrorCallback(hspdif); - } - - /* SPDIFRX Parity error interrupt occurred */ - if (((itFlag & SPDIFRX_FLAG_PERR) == SPDIFRX_FLAG_PERR) && ((itSource & SPDIFRX_IT_PERRIE) == SPDIFRX_IT_PERRIE)) - { - __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_PERRIE); - - /* Change the SPDIFRX error code */ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_PE; - - /* the transfer is not stopped */ - HAL_SPDIFRX_ErrorCallback(hspdif); - } -} - -/** - * @brief Rx Transfer (Data flow) half completed callbacks - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_RxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer (Data flow) completed callbacks - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_RxCpltCallback(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx (Control flow) Transfer half completed callbacks - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_CxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer (Control flow) completed callbacks - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_CxCpltCallback(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief SPDIFRX error callbacks - * @param hspdif SPDIFRX handle - * @retval None - */ -__weak void HAL_SPDIFRX_ErrorCallback(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspdif); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SPDIFRX_ErrorCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup SPDIFRX_Exported_Functions_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 SPDIFRX state - * @param hspdif SPDIFRX handle - * @retval HAL state - */ -HAL_SPDIFRX_StateTypeDef HAL_SPDIFRX_GetState(SPDIFRX_HandleTypeDef const *const hspdif) -{ - return hspdif->State; -} - -/** - * @brief Return the SPDIFRX error code - * @param hspdif SPDIFRX handle - * @retval SPDIFRX Error Code - */ -uint32_t HAL_SPDIFRX_GetError(SPDIFRX_HandleTypeDef const *const hspdif) -{ - return hspdif->ErrorCode; -} - -/** - * @} - */ - -/** - * @brief DMA SPDIFRX receive process (Data flow) complete callback - * @param hdma DMA handle - * @retval None - */ -static void SPDIFRX_DMARxCplt(DMA_HandleTypeDef *hdma) -{ - SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable Rx DMA Request */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_RXDMAEN); - hspdif->RxXferCount = 0; - hspdif->State = HAL_SPDIFRX_STATE_READY; - } -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - hspdif->RxCpltCallback(hspdif); -#else - HAL_SPDIFRX_RxCpltCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPDIFRX receive process (Data flow) half complete callback - * @param hdma DMA handle - * @retval None - */ -static void SPDIFRX_DMARxHalfCplt(DMA_HandleTypeDef *hdma) -{ - SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - hspdif->RxHalfCpltCallback(hspdif); -#else - HAL_SPDIFRX_RxHalfCpltCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ -} - - -/** - * @brief DMA SPDIFRX receive process (Control flow) complete callback - * @param hdma DMA handle - * @retval None - */ -static void SPDIFRX_DMACxCplt(DMA_HandleTypeDef *hdma) -{ - SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable Cb DMA Request */ - hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_CBDMAEN); - hspdif->CsXferCount = 0; - - hspdif->State = HAL_SPDIFRX_STATE_READY; -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - hspdif->CxCpltCallback(hspdif); -#else - HAL_SPDIFRX_CxCpltCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPDIFRX receive process (Control flow) half complete callback - * @param hdma DMA handle - * @retval None - */ -static void SPDIFRX_DMACxHalfCplt(DMA_HandleTypeDef *hdma) -{ - SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - hspdif->CxHalfCpltCallback(hspdif); -#else - HAL_SPDIFRX_CxHalfCpltCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPDIFRX communication error callback - * @param hdma DMA handle - * @retval None - */ -static void SPDIFRX_DMAError(DMA_HandleTypeDef *hdma) -{ - SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable Rx and Cb DMA Request */ - hspdif->Instance->CR &= (uint16_t)(~(SPDIFRX_CR_RXDMAEN | SPDIFRX_CR_CBDMAEN)); - hspdif->RxXferCount = 0; - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Set the error code and execute error callback*/ - hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_DMA; - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - /* The transfer is not stopped */ - hspdif->ErrorCallback(hspdif); -#else - /* The transfer is not stopped */ - HAL_SPDIFRX_ErrorCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ -} - -/** - * @brief Receive an amount of data (Data Flow) with Interrupt - * @param hspdif SPDIFRX handle - * @retval None - */ -static void SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Receive data */ - (*hspdif->pRxBuffPtr) = hspdif->Instance->DR; - hspdif->pRxBuffPtr++; - hspdif->RxXferCount--; - - if (hspdif->RxXferCount == 0U) - { - /* Disable RXNE/PE and OVR interrupts */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE | SPDIFRX_IT_PERRIE | SPDIFRX_IT_RXNE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - hspdif->RxCpltCallback(hspdif); -#else - HAL_SPDIFRX_RxCpltCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ - } -} - -/** - * @brief Receive an amount of data (Control Flow) with Interrupt - * @param hspdif SPDIFRX handle - * @retval None - */ -static void SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif) -{ - /* Receive data */ - (*hspdif->pCsBuffPtr) = hspdif->Instance->CSR; - hspdif->pCsBuffPtr++; - hspdif->CsXferCount--; - - if (hspdif->CsXferCount == 0U) - { - /* Disable CSRNE interrupt */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - -#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) - hspdif->CxCpltCallback(hspdif); -#else - HAL_SPDIFRX_CxCpltCallback(hspdif); -#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ - } -} - -/** - * @brief This function handles SPDIFRX Communication Timeout. - * @param hspdif SPDIFRX handle - * @param Flag Flag checked - * @param Status Value of the flag expected - * @param Timeout Duration of the timeout - * @param tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef SPDIFRX_WaitOnFlagUntilTimeout(SPDIFRX_HandleTypeDef *hspdif, uint32_t Flag, - FlagStatus Status, uint32_t Timeout, uint32_t tickstart) -{ - /* Wait until flag is set */ - while (__HAL_SPDIFRX_GET_FLAG(hspdif, Flag) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt - process */ - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); - __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); - - hspdif->State = HAL_SPDIFRX_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hspdif); - - return HAL_TIMEOUT; - } - } - } - - return HAL_OK; -} - -/** - * @} - */ - - -#endif /* SPDIFRX */ -#endif /* HAL_SPDIFRX_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_spdifrx.c + * @author MCD Application Team + * @brief This file provides firmware functions to manage the following + * functionalities of the SPDIFRX audio interface: + * + Initialization and Configuration + * + Data transfers functions + * + DMA transfers management + * + Interrupts and flags management + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The SPDIFRX HAL driver can be used as follow: + + (#) Declare SPDIFRX_HandleTypeDef handle structure. + (#) Initialize the SPDIFRX low level resources by implement the HAL_SPDIFRX_MspInit() API: + (##) Enable the SPDIFRX interface clock. + (##) SPDIFRX pins configuration: + (+++) Enable the clock for the SPDIFRX GPIOs. + (+++) Configure these SPDIFRX pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_SPDIFRX_ReceiveCtrlFlow_IT() and + HAL_SPDIFRX_ReceiveDataFlow_IT() API's). + (+++) Configure the SPDIFRX interrupt priority. + (+++) Enable the NVIC SPDIFRX IRQ handle. + (##) DMA Configuration if you need to use DMA process (HAL_SPDIFRX_ReceiveDataFlow_DMA() and + HAL_SPDIFRX_ReceiveCtrlFlow_DMA() API's). + (+++) Declare a DMA handle structure for the reception of the Data Flow channel. + (+++) Declare a DMA handle structure for the reception of the Control Flow channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure CtrlRx/DataRx with the required parameters. + (+++) Configure the DMA Channel. + (+++) Associate the initialized DMA handle to the SPDIFRX DMA CtrlRx/DataRx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the + DMA CtrlRx/DataRx channel. + + (#) Program the input selection, re-tries number, wait for activity, channel status selection, data format, + stereo mode and masking of user bits using HAL_SPDIFRX_Init() function. + + -@- The specific SPDIFRX interrupts (RXNE/CSRNE and Error Interrupts) will be managed using the macros + __SPDIFRX_ENABLE_IT() and __SPDIFRX_DISABLE_IT() inside the receive process. + -@- Make sure that ck_spdif clock is configured. + + (#) Three operation modes are available within this driver : + + *** Polling mode for reception operation (for debug purpose) *** + ================================================================ + [..] + (+) Receive data flow in blocking mode using HAL_SPDIFRX_ReceiveDataFlow() + (+) Receive control flow of data in blocking mode using HAL_SPDIFRX_ReceiveCtrlFlow() + + *** Interrupt mode for reception operation *** + ========================================= + [..] + (+) Receive an amount of data (Data Flow) in non blocking mode using HAL_SPDIFRX_ReceiveDataFlow_IT() + (+) Receive an amount of data (Control Flow) in non blocking mode using HAL_SPDIFRX_ReceiveCtrlFlow_IT() + (+) At reception end of half transfer HAL_SPDIFRX_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SPDIFRX_RxHalfCpltCallback + (+) At reception end of transfer HAL_SPDIFRX_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SPDIFRX_RxCpltCallback + (+) In case of transfer Error, HAL_SPDIFRX_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_SPDIFRX_ErrorCallback + + *** DMA mode for reception operation *** + ======================================== + [..] + (+) Receive an amount of data (Data Flow) in non blocking mode (DMA) using HAL_SPDIFRX_ReceiveDataFlow_DMA() + (+) Receive an amount of data (Control Flow) in non blocking mode (DMA) using HAL_SPDIFRX_ReceiveCtrlFlow_DMA() + (+) At reception end of half transfer HAL_SPDIFRX_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SPDIFRX_RxHalfCpltCallback + (+) At reception end of transfer HAL_SPDIFRX_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SPDIFRX_RxCpltCallback + (+) In case of transfer Error, HAL_SPDIFRX_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_SPDIFRX_ErrorCallback + (+) Stop the DMA Transfer using HAL_SPDIFRX_DMAStop() + + *** SPDIFRX HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in SPDIFRX HAL driver. + (+) __HAL_SPDIFRX_IDLE: Disable the specified SPDIFRX peripheral (IDLE State) + (+) __HAL_SPDIFRX_SYNC: Enable the synchronization state of the specified SPDIFRX peripheral (SYNC State) + (+) __HAL_SPDIFRX_RCV: Enable the receive state of the specified SPDIFRX peripheral (RCV State) + (+) __HAL_SPDIFRX_ENABLE_IT : Enable the specified SPDIFRX interrupts + (+) __HAL_SPDIFRX_DISABLE_IT : Disable the specified SPDIFRX interrupts + (+) __HAL_SPDIFRX_GET_FLAG: Check whether the specified SPDIFRX flag is set or not. + + [..] + (@) You can refer to the SPDIFRX HAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + + The compilation define USE_HAL_SPDIFRX_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + Use HAL_SPDIFRX_RegisterCallback() function to register an interrupt callback. + + The HAL_SPDIFRX_RegisterCallback() function allows to register the following callbacks: + (+) RxHalfCpltCallback : SPDIFRX Data flow half completed callback. + (+) RxCpltCallback : SPDIFRX Data flow completed callback. + (+) CxHalfCpltCallback : SPDIFRX Control flow half completed callback. + (+) CxCpltCallback : SPDIFRX Control flow completed callback. + (+) ErrorCallback : SPDIFRX error callback. + (+) MspInitCallback : SPDIFRX MspInit. + (+) MspDeInitCallback : SPDIFRX MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use HAL_SPDIFRX_UnRegisterCallback() function to reset a callback to the default + weak function. + The HAL_SPDIFRX_UnRegisterCallback() function takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset the following callbacks: + (+) RxHalfCpltCallback : SPDIFRX Data flow half completed callback. + (+) RxCpltCallback : SPDIFRX Data flow completed callback. + (+) CxHalfCpltCallback : SPDIFRX Control flow half completed callback. + (+) CxCpltCallback : SPDIFRX Control flow completed callback. + (+) ErrorCallback : SPDIFRX error callback. + (+) MspInitCallback : SPDIFRX MspInit. + (+) MspDeInitCallback : SPDIFRX MspDeInit. + + By default, after the HAL_SPDIFRX_Init() and when the state is HAL_SPDIFRX_STATE_RESET + all callbacks are set to the corresponding weak functions : + HAL_SPDIFRX_RxHalfCpltCallback() , HAL_SPDIFRX_RxCpltCallback(), HAL_SPDIFRX_CxHalfCpltCallback(), + HAL_SPDIFRX_CxCpltCallback() and HAL_SPDIFRX_ErrorCallback() + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak function in the HAL_SPDIFRX_Init()/ HAL_SPDIFRX_DeInit() only when + these callbacks pointers are NULL (not registered beforehand). + If not, MspInit or MspDeInit callbacks pointers are not null, the HAL_SPDIFRX_Init() / HAL_SPDIFRX_DeInit() + keep and use the user MspInit/MspDeInit functions (registered beforehand) + + Callbacks can be registered/unregistered in HAL_SPDIFRX_STATE_READY state only. + Exception done MspInit/MspDeInit callbacks that can be registered/unregistered + in HAL_SPDIFRX_STATE_READY or HAL_SPDIFRX_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SPDIFRX_RegisterCallback() before calling HAL_SPDIFRX_DeInit() + or HAL_SPDIFRX_Init() function. + + When The compilation define USE_HAL_SPDIFRX_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SPDIFRX SPDIFRX + * @brief SPDIFRX HAL module driver + * @{ + */ + +#ifdef HAL_SPDIFRX_MODULE_ENABLED +#if defined (SPDIFRX) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup SPDIFRX_Private_Defines SPDIFRX Private Defines + * @{ + */ +#define SPDIFRX_TIMEOUT_VALUE 10U +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup SPDIFRX_Private_Functions + * @{ + */ +static void SPDIFRX_DMARxCplt(DMA_HandleTypeDef *hdma); +static void SPDIFRX_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void SPDIFRX_DMACxCplt(DMA_HandleTypeDef *hdma); +static void SPDIFRX_DMACxHalfCplt(DMA_HandleTypeDef *hdma); +static void SPDIFRX_DMAError(DMA_HandleTypeDef *hdma); +static void SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif); +static void SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif); +static HAL_StatusTypeDef SPDIFRX_WaitOnFlagUntilTimeout(SPDIFRX_HandleTypeDef *hspdif, uint32_t Flag, + FlagStatus Status, uint32_t Timeout, uint32_t tickstart); +/** + * @} + */ +/* Exported functions ---------------------------------------------------------*/ + +/** @defgroup SPDIFRX_Exported_Functions SPDIFRX Exported Functions + * @{ + */ + +/** @defgroup SPDIFRX_Exported_Functions_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 SPDIFRX peripheral: + + (+) User must Implement HAL_SPDIFRX_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function HAL_SPDIFRX_Init() to configure the SPDIFRX peripheral with + the selected configuration: + (++) Input Selection (IN0, IN1,...) + (++) Maximum allowed re-tries during synchronization phase + (++) Wait for activity on SPDIF selected input + (++) Channel status selection (from channel A or B) + (++) Data format (LSB, MSB, ...) + (++) Stereo mode + (++) User bits masking (PT,C,U,V,...) + + (+) Call the function HAL_SPDIFRX_DeInit() to restore the default configuration + of the selected SPDIFRXx peripheral. + @endverbatim + * @{ + */ + +/** + * @brief Initializes the SPDIFRX according to the specified parameters + * in the SPDIFRX_InitTypeDef and create the associated handle. + * @param hspdif SPDIFRX handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_Init(SPDIFRX_HandleTypeDef *hspdif) +{ + uint32_t tmpreg; + + /* Check the SPDIFRX handle allocation */ + if (hspdif == NULL) + { + return HAL_ERROR; + } + + /* Check the SPDIFRX parameters */ + assert_param(IS_STEREO_MODE(hspdif->Init.StereoMode)); + assert_param(IS_SPDIFRX_INPUT_SELECT(hspdif->Init.InputSelection)); + assert_param(IS_SPDIFRX_MAX_RETRIES(hspdif->Init.Retries)); + assert_param(IS_SPDIFRX_WAIT_FOR_ACTIVITY(hspdif->Init.WaitForActivity)); + assert_param(IS_SPDIFRX_CHANNEL(hspdif->Init.ChannelSelection)); + assert_param(IS_SPDIFRX_DATA_FORMAT(hspdif->Init.DataFormat)); + assert_param(IS_PREAMBLE_TYPE_MASK(hspdif->Init.PreambleTypeMask)); + assert_param(IS_CHANNEL_STATUS_MASK(hspdif->Init.ChannelStatusMask)); + assert_param(IS_VALIDITY_MASK(hspdif->Init.ValidityBitMask)); + assert_param(IS_PARITY_ERROR_MASK(hspdif->Init.ParityErrorMask)); + assert_param(IS_SYMBOL_CLOCK_GEN(hspdif->Init.SymbolClockGen)); + assert_param(IS_SYMBOL_CLOCK_GEN(hspdif->Init.BackupSymbolClockGen)); + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + if (hspdif->State == HAL_SPDIFRX_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hspdif->Lock = HAL_UNLOCKED; + + hspdif->RxHalfCpltCallback = HAL_SPDIFRX_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + hspdif->RxCpltCallback = HAL_SPDIFRX_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hspdif->CxHalfCpltCallback = HAL_SPDIFRX_CxHalfCpltCallback; /* Legacy weak CxHalfCpltCallback */ + hspdif->CxCpltCallback = HAL_SPDIFRX_CxCpltCallback; /* Legacy weak CxCpltCallback */ + hspdif->ErrorCallback = HAL_SPDIFRX_ErrorCallback; /* Legacy weak ErrorCallback */ + + if (hspdif->MspInitCallback == NULL) + { + hspdif->MspInitCallback = HAL_SPDIFRX_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware */ + hspdif->MspInitCallback(hspdif); + } +#else + if (hspdif->State == HAL_SPDIFRX_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hspdif->Lock = HAL_UNLOCKED; + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_SPDIFRX_MspInit(hspdif); + } +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ + + /* SPDIFRX peripheral state is BUSY */ + hspdif->State = HAL_SPDIFRX_STATE_BUSY; + + /* Disable SPDIFRX interface (IDLE State) */ + __HAL_SPDIFRX_IDLE(hspdif); + + /* Reset the old SPDIFRX CR configuration */ + tmpreg = hspdif->Instance->CR; + + tmpreg &= ~(SPDIFRX_CR_RXSTEO | SPDIFRX_CR_DRFMT | SPDIFRX_CR_PMSK | + SPDIFRX_CR_VMSK | SPDIFRX_CR_CUMSK | SPDIFRX_CR_PTMSK | + SPDIFRX_CR_CHSEL | SPDIFRX_CR_NBTR | SPDIFRX_CR_WFA | + SPDIFRX_CR_CKSEN | SPDIFRX_CR_CKSBKPEN | + SPDIFRX_CR_INSEL); + + /* Sets the new configuration of the SPDIFRX peripheral */ + tmpreg |= (hspdif->Init.StereoMode | + hspdif->Init.InputSelection | + hspdif->Init.Retries | + hspdif->Init.WaitForActivity | + hspdif->Init.ChannelSelection | + hspdif->Init.DataFormat | + hspdif->Init.PreambleTypeMask | + hspdif->Init.ChannelStatusMask | + hspdif->Init.ValidityBitMask | + hspdif->Init.ParityErrorMask + ); + + if (hspdif->Init.SymbolClockGen == ENABLE) + { + tmpreg |= SPDIFRX_CR_CKSEN; + } + + if (hspdif->Init.BackupSymbolClockGen == ENABLE) + { + tmpreg |= SPDIFRX_CR_CKSBKPEN; + } + + hspdif->Instance->CR = tmpreg; + + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; + + /* SPDIFRX peripheral state is READY*/ + hspdif->State = HAL_SPDIFRX_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the SPDIFRX peripheral + * @param hspdif SPDIFRX handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_DeInit(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Check the SPDIFRX handle allocation */ + if (hspdif == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPDIFRX_ALL_INSTANCE(hspdif->Instance)); + + hspdif->State = HAL_SPDIFRX_STATE_BUSY; + + /* Disable SPDIFRX interface (IDLE state) */ + __HAL_SPDIFRX_IDLE(hspdif); + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + if (hspdif->MspDeInitCallback == NULL) + { + hspdif->MspDeInitCallback = HAL_SPDIFRX_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware */ + hspdif->MspDeInitCallback(hspdif); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_SPDIFRX_MspDeInit(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ + + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; + + /* SPDIFRX peripheral state is RESET*/ + hspdif->State = HAL_SPDIFRX_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; +} + +/** + * @brief SPDIFRX MSP Init + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_MspInit(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_MspInit could be implemented in the user file + */ +} + +/** + * @brief SPDIFRX MSP DeInit + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_MspDeInit(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_MspDeInit could be implemented in the user file + */ +} + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SPDIFRX Callback + * To be used instead of the weak predefined callback + * @param hspdif SPDIFRX handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SPDIFRX_RX_HALF_CB_ID SPDIFRX Data flow half completed callback ID + * @arg @ref HAL_SPDIFRX_RX_CPLT_CB_ID SPDIFRX Data flow completed callback ID + * @arg @ref HAL_SPDIFRX_CX_HALF_CB_ID SPDIFRX Control flow half completed callback ID + * @arg @ref HAL_SPDIFRX_CX_CPLT_CB_ID SPDIFRX Control flow completed callback ID + * @arg @ref HAL_SPDIFRX_ERROR_CB_ID SPDIFRX error callback ID + * @arg @ref HAL_SPDIFRX_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_SPDIFRX_MSPDEINIT_CB_ID MspDeInit callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_RegisterCallback(SPDIFRX_HandleTypeDef *hspdif, HAL_SPDIFRX_CallbackIDTypeDef CallbackID, + pSPDIFRX_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + /* Process locked */ + __HAL_LOCK(hspdif); + + if (HAL_SPDIFRX_STATE_READY == hspdif->State) + { + switch (CallbackID) + { + case HAL_SPDIFRX_RX_HALF_CB_ID : + hspdif->RxHalfCpltCallback = pCallback; + break; + + case HAL_SPDIFRX_RX_CPLT_CB_ID : + hspdif->RxCpltCallback = pCallback; + break; + + case HAL_SPDIFRX_CX_HALF_CB_ID : + hspdif->CxHalfCpltCallback = pCallback; + break; + + case HAL_SPDIFRX_CX_CPLT_CB_ID : + hspdif->CxCpltCallback = pCallback; + break; + + case HAL_SPDIFRX_ERROR_CB_ID : + hspdif->ErrorCallback = pCallback; + break; + + case HAL_SPDIFRX_MSPINIT_CB_ID : + hspdif->MspInitCallback = pCallback; + break; + + case HAL_SPDIFRX_MSPDEINIT_CB_ID : + hspdif->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SPDIFRX_STATE_RESET == hspdif->State) + { + switch (CallbackID) + { + case HAL_SPDIFRX_MSPINIT_CB_ID : + hspdif->MspInitCallback = pCallback; + break; + + case HAL_SPDIFRX_MSPDEINIT_CB_ID : + hspdif->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hspdif); + return status; +} + +/** + * @brief Unregister a SPDIFRX Callback + * SPDIFRX callback is redirected to the weak predefined callback + * @param hspdif SPDIFRX handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_SPDIFRX_RX_HALF_CB_ID SPDIFRX Data flow half completed callback ID + * @arg @ref HAL_SPDIFRX_RX_CPLT_CB_ID SPDIFRX Data flow completed callback ID + * @arg @ref HAL_SPDIFRX_CX_HALF_CB_ID SPDIFRX Control flow half completed callback ID + * @arg @ref HAL_SPDIFRX_CX_CPLT_CB_ID SPDIFRX Control flow completed callback ID + * @arg @ref HAL_SPDIFRX_ERROR_CB_ID SPDIFRX error callback ID + * @arg @ref HAL_SPDIFRX_MSPINIT_CB_ID MspInit callback ID + * @arg @ref HAL_SPDIFRX_MSPDEINIT_CB_ID MspDeInit callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_UnRegisterCallback(SPDIFRX_HandleTypeDef *hspdif, + HAL_SPDIFRX_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hspdif); + + if (HAL_SPDIFRX_STATE_READY == hspdif->State) + { + switch (CallbackID) + { + case HAL_SPDIFRX_RX_HALF_CB_ID : + hspdif->RxHalfCpltCallback = HAL_SPDIFRX_RxHalfCpltCallback; + break; + + case HAL_SPDIFRX_RX_CPLT_CB_ID : + hspdif->RxCpltCallback = HAL_SPDIFRX_RxCpltCallback; + break; + + case HAL_SPDIFRX_CX_HALF_CB_ID : + hspdif->CxHalfCpltCallback = HAL_SPDIFRX_CxHalfCpltCallback; + break; + + case HAL_SPDIFRX_CX_CPLT_CB_ID : + hspdif->CxCpltCallback = HAL_SPDIFRX_CxCpltCallback; + break; + + case HAL_SPDIFRX_ERROR_CB_ID : + hspdif->ErrorCallback = HAL_SPDIFRX_ErrorCallback; + break; + + default : + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SPDIFRX_STATE_RESET == hspdif->State) + { + switch (CallbackID) + { + case HAL_SPDIFRX_MSPINIT_CB_ID : + hspdif->MspInitCallback = HAL_SPDIFRX_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_SPDIFRX_MSPDEINIT_CB_ID : + hspdif->MspDeInitCallback = HAL_SPDIFRX_MspDeInit; /* Legacy weak MspInit */ + break; + + default : + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_INVALID_CALLBACK; + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hspdif); + return status; +} + +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ + +/** + * @brief Set the SPDIFRX data format according to the specified parameters in the SPDIFRX_InitTypeDef. + * @param hspdif SPDIFRX handle + * @param sDataFormat SPDIFRX data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_SetDataFormat(SPDIFRX_HandleTypeDef *hspdif, SPDIFRX_SetDataFormatTypeDef sDataFormat) +{ + uint32_t tmpreg; + + /* Check the SPDIFRX handle allocation */ + if (hspdif == NULL) + { + return HAL_ERROR; + } + + /* Check the SPDIFRX parameters */ + assert_param(IS_STEREO_MODE(sDataFormat.StereoMode)); + assert_param(IS_SPDIFRX_DATA_FORMAT(sDataFormat.DataFormat)); + assert_param(IS_PREAMBLE_TYPE_MASK(sDataFormat.PreambleTypeMask)); + assert_param(IS_CHANNEL_STATUS_MASK(sDataFormat.ChannelStatusMask)); + assert_param(IS_VALIDITY_MASK(sDataFormat.ValidityBitMask)); + assert_param(IS_PARITY_ERROR_MASK(sDataFormat.ParityErrorMask)); + + /* Reset the old SPDIFRX CR configuration */ + tmpreg = hspdif->Instance->CR; + + if (((tmpreg & SPDIFRX_STATE_RCV) == SPDIFRX_STATE_RCV) && + (((tmpreg & SPDIFRX_CR_DRFMT) != sDataFormat.DataFormat) || + ((tmpreg & SPDIFRX_CR_RXSTEO) != sDataFormat.StereoMode))) + { + return HAL_ERROR; + } + + tmpreg &= ~(SPDIFRX_CR_RXSTEO | SPDIFRX_CR_DRFMT | SPDIFRX_CR_PMSK | + SPDIFRX_CR_VMSK | SPDIFRX_CR_CUMSK | SPDIFRX_CR_PTMSK); + + /* Configure the new data format */ + tmpreg |= (sDataFormat.StereoMode | + sDataFormat.DataFormat | + sDataFormat.PreambleTypeMask | + sDataFormat.ChannelStatusMask | + sDataFormat.ValidityBitMask | + sDataFormat.ParityErrorMask); + + hspdif->Instance->CR = tmpreg; + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup SPDIFRX_Exported_Functions_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim +=============================================================================== + ##### IO operation functions ##### +=============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SPDIFRX 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 start-up. + The end of the data processing will be indicated through the + dedicated SPDIFRX IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) HAL_SPDIFRX_ReceiveDataFlow() + (++) HAL_SPDIFRX_ReceiveCtrlFlow() + (+@) Do not use blocking mode to receive both control and data flow at the same time. + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_SPDIFRX_ReceiveCtrlFlow_IT() + (++) HAL_SPDIFRX_ReceiveDataFlow_IT() + + (#) No-Blocking mode functions with DMA are : + (++) HAL_SPDIFRX_ReceiveCtrlFlow_DMA() + (++) HAL_SPDIFRX_ReceiveDataFlow_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) HAL_SPDIFRX_RxCpltCallback() + (++) HAL_SPDIFRX_CxCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Receives an amount of data (Data Flow) in blocking mode. + * @param hspdif pointer to SPDIFRX_HandleTypeDef structure that contains + * the configuration information for SPDIFRX module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, + uint32_t Timeout) +{ + uint32_t tickstart; + uint16_t sizeCounter = Size; + uint32_t *pTmpBuf = pData; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hspdif->State == HAL_SPDIFRX_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hspdif); + + hspdif->State = HAL_SPDIFRX_STATE_BUSY; + + /* Start synchronisation */ + __HAL_SPDIFRX_SYNC(hspdif); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until SYNCD flag is set */ + if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Start reception */ + __HAL_SPDIFRX_RCV(hspdif); + + /* Receive data flow */ + while (sizeCounter > 0U) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until RXNE flag is set */ + if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*pTmpBuf) = hspdif->Instance->DR; + pTmpBuf++; + sizeCounter--; + } + + /* SPDIFRX ready */ + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receives an amount of data (Control Flow) in blocking mode. + * @param hspdif pointer to a SPDIFRX_HandleTypeDef structure that contains + * the configuration information for SPDIFRX module. + * @param pData Pointer to data buffer + * @param Size Amount of data to be received + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_ReceiveCtrlFlow(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size, + uint32_t Timeout) +{ + uint32_t tickstart; + uint16_t sizeCounter = Size; + uint32_t *pTmpBuf = pData; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if (hspdif->State == HAL_SPDIFRX_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hspdif); + + hspdif->State = HAL_SPDIFRX_STATE_BUSY; + + /* Start synchronization */ + __HAL_SPDIFRX_SYNC(hspdif); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until SYNCD flag is set */ + if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_SYNCD, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Start reception */ + __HAL_SPDIFRX_RCV(hspdif); + + /* Receive control flow */ + while (sizeCounter > 0U) + { + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until CSRNE flag is set */ + if (SPDIFRX_WaitOnFlagUntilTimeout(hspdif, SPDIFRX_FLAG_CSRNE, RESET, Timeout, tickstart) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*pTmpBuf) = hspdif->Instance->CSR; + pTmpBuf++; + sizeCounter--; + } + + /* SPDIFRX ready */ + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data (Data Flow) in non-blocking mode with Interrupt + * @param hspdif SPDIFRX handle + * @param pData a 32-bit pointer to the Receive data buffer. + * @param Size number of data sample to be received . + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) +{ + uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); + + const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; + + if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_CX)) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspdif); + + hspdif->pRxBuffPtr = pData; + hspdif->RxXferSize = Size; + hspdif->RxXferCount = Size; + + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; + + /* Check if a receive process is ongoing or not */ + hspdif->State = HAL_SPDIFRX_STATE_BUSY_RX; + + /* Enable the SPDIFRX PE Error Interrupt */ + __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + + /* Enable the SPDIFRX OVR Error Interrupt */ + __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + + /* Enable the SPDIFRX RXNE interrupt */ + __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_RXNE); + + if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) + { + /* Start synchronization */ + __HAL_SPDIFRX_SYNC(hspdif); + + /* Wait until SYNCD flag is set */ + do + { + if (count == 0U) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt + process */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_TIMEOUT; + } + count--; + } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); + + /* Start reception */ + __HAL_SPDIFRX_RCV(hspdif); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data (Control Flow) with Interrupt + * @param hspdif SPDIFRX handle + * @param pData a 32-bit pointer to the Receive data buffer. + * @param Size number of data sample (Control Flow) to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_ReceiveCtrlFlow_IT(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) +{ + uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); + + const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; + + if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_RX)) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspdif); + + hspdif->pCsBuffPtr = pData; + hspdif->CsXferSize = Size; + hspdif->CsXferCount = Size; + + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; + + /* Check if a receive process is ongoing or not */ + hspdif->State = HAL_SPDIFRX_STATE_BUSY_CX; + + /* Enable the SPDIFRX PE Error Interrupt */ + __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + + /* Enable the SPDIFRX OVR Error Interrupt */ + __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + + /* Enable the SPDIFRX CSRNE interrupt */ + __HAL_SPDIFRX_ENABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + + if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) + { + /* Start synchronization */ + __HAL_SPDIFRX_SYNC(hspdif); + + /* Wait until SYNCD flag is set */ + do + { + if (count == 0U) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt + process */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_TIMEOUT; + } + count--; + } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); + + /* Start reception */ + __HAL_SPDIFRX_RCV(hspdif); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data (Data Flow) mode with DMA + * @param hspdif SPDIFRX handle + * @param pData a 32-bit pointer to the Receive data buffer. + * @param Size number of data sample to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_ReceiveDataFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) +{ + uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); + + const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_CX)) + { + /* Process Locked */ + __HAL_LOCK(hspdif); + + hspdif->pRxBuffPtr = pData; + hspdif->RxXferSize = Size; + hspdif->RxXferCount = Size; + + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; + hspdif->State = HAL_SPDIFRX_STATE_BUSY_RX; + + /* Set the SPDIFRX Rx DMA Half transfer complete callback */ + hspdif->hdmaDrRx->XferHalfCpltCallback = SPDIFRX_DMARxHalfCplt; + + /* Set the SPDIFRX Rx DMA transfer complete callback */ + hspdif->hdmaDrRx->XferCpltCallback = SPDIFRX_DMARxCplt; + + /* Set the DMA error callback */ + hspdif->hdmaDrRx->XferErrorCallback = SPDIFRX_DMAError; + + /* Enable the DMA request */ + if ((hspdif->hdmaDrRx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hspdif->hdmaDrRx->LinkedListQueue != NULL) + { + hspdif->hdmaDrRx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (uint32_t) Size * 4U; + hspdif->hdmaDrRx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t) &hspdif->Instance->DR; + hspdif->hdmaDrRx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t) hspdif->pRxBuffPtr; + + if (HAL_DMAEx_List_Start_IT(hspdif->hdmaDrRx) != HAL_OK) + { + /* Set SPDIFRX error */ + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; + + /* Set SPDIFRX state */ + hspdif->State = HAL_SPDIFRX_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_ERROR; + } + } + else + { + /* Set SPDIFRX error */ + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; + + /* Set SPDIFRX state */ + hspdif->State = HAL_SPDIFRX_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_ERROR; + } + } + else + { + if (HAL_DMA_Start_IT(hspdif->hdmaDrRx, (uint32_t)&hspdif->Instance->DR, (uint32_t)hspdif->pRxBuffPtr, + (uint32_t) Size * 4U) != HAL_OK) + { + /* Set SPDIFRX error */ + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; + + /* Set SPDIFRX state */ + hspdif->State = HAL_SPDIFRX_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_ERROR; + } + } + + /* Enable RXDMAEN bit in SPDIFRX CR register for data flow reception*/ + hspdif->Instance->CR |= SPDIFRX_CR_RXDMAEN; + + if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) + { + /* Start synchronization */ + __HAL_SPDIFRX_SYNC(hspdif); + + /* Wait until SYNCD flag is set */ + do + { + if (count == 0U) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt + process */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_TIMEOUT; + } + count--; + } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); + + /* Start reception */ + __HAL_SPDIFRX_RCV(hspdif); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data (Control Flow) with DMA + * @param hspdif SPDIFRX handle + * @param pData a 32-bit pointer to the Receive data buffer. + * @param Size number of data (Control Flow) sample to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPDIFRX_ReceiveCtrlFlow_DMA(SPDIFRX_HandleTypeDef *hspdif, uint32_t *pData, uint16_t Size) +{ + uint32_t count = SPDIFRX_TIMEOUT_VALUE * (SystemCoreClock / 24U / 1000U); + + const HAL_SPDIFRX_StateTypeDef tempState = hspdif->State; + + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + if ((tempState == HAL_SPDIFRX_STATE_READY) || (tempState == HAL_SPDIFRX_STATE_BUSY_RX)) + { + hspdif->pCsBuffPtr = pData; + hspdif->CsXferSize = Size; + hspdif->CsXferCount = Size; + + /* Process Locked */ + __HAL_LOCK(hspdif); + + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_NONE; + hspdif->State = HAL_SPDIFRX_STATE_BUSY_CX; + + /* Set the SPDIFRX Rx DMA Half transfer complete callback */ + hspdif->hdmaCsRx->XferHalfCpltCallback = SPDIFRX_DMACxHalfCplt; + + /* Set the SPDIFRX Rx DMA transfer complete callback */ + hspdif->hdmaCsRx->XferCpltCallback = SPDIFRX_DMACxCplt; + + /* Set the DMA error callback */ + hspdif->hdmaCsRx->XferErrorCallback = SPDIFRX_DMAError; + + /* Enable the DMA request */ + if ((hspdif->hdmaCsRx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hspdif->hdmaCsRx->LinkedListQueue != NULL) + { + hspdif->hdmaCsRx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (uint32_t) Size * 4U; + hspdif->hdmaCsRx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t) &hspdif->Instance->CSR; + hspdif->hdmaCsRx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t) hspdif->pCsBuffPtr; + + if (HAL_DMAEx_List_Start_IT(hspdif->hdmaCsRx) != HAL_OK) + { + /* Set SPDIFRX error */ + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; + + /* Set SPDIFRX state */ + hspdif->State = HAL_SPDIFRX_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_ERROR; + } + } + else + { + /* Set SPDIFRX error */ + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; + + /* Set SPDIFRX state */ + hspdif->State = HAL_SPDIFRX_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_ERROR; + } + } + else + { + if (HAL_DMA_Start_IT(hspdif->hdmaCsRx, (uint32_t)&hspdif->Instance->CSR, (uint32_t)hspdif->pCsBuffPtr, + (uint32_t) Size * 4U) != HAL_OK) + { + /* Set SPDIFRX error */ + hspdif->ErrorCode = HAL_SPDIFRX_ERROR_DMA; + + /* Set SPDIFRX state */ + hspdif->State = HAL_SPDIFRX_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_ERROR; + } + } + + /* Enable CBDMAEN bit in SPDIFRX CR register for control flow reception*/ + hspdif->Instance->CR |= SPDIFRX_CR_CBDMAEN; + + if ((SPDIFRX->CR & SPDIFRX_CR_SPDIFRXEN) != SPDIFRX_STATE_RCV) + { + /* Start synchronization */ + __HAL_SPDIFRX_SYNC(hspdif); + + /* Wait until SYNCD flag is set */ + do + { + if (count == 0U) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt + process */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_TIMEOUT; + } + count--; + } while (__HAL_SPDIFRX_GET_FLAG(hspdif, SPDIFRX_FLAG_SYNCD) == RESET); + + /* Start reception */ + __HAL_SPDIFRX_RCV(hspdif); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief stop the audio stream receive from the Media. + * @param hspdif SPDIFRX handle + * @retval None + */ +HAL_StatusTypeDef HAL_SPDIFRX_DMAStop(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Process Locked */ + __HAL_LOCK(hspdif); + + /* Disable the SPDIFRX DMA requests */ + hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_RXDMAEN); + hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_CBDMAEN); + + /* Disable the SPDIFRX DMA channel */ + if (hspdif->hdmaDrRx != NULL) + { + __HAL_DMA_DISABLE(hspdif->hdmaDrRx); + } + if (hspdif->hdmaCsRx != NULL) + { + __HAL_DMA_DISABLE(hspdif->hdmaCsRx); + } + + /* Disable SPDIFRX peripheral */ + __HAL_SPDIFRX_IDLE(hspdif); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_OK; +} + +/** + * @brief This function handles SPDIFRX interrupt request. + * @param hspdif SPDIFRX handle + * @retval HAL status + */ +void HAL_SPDIFRX_IRQHandler(SPDIFRX_HandleTypeDef *hspdif) +{ + uint32_t itFlag = hspdif->Instance->SR; + uint32_t itSource = hspdif->Instance->IMR; + + /* SPDIFRX in mode Data Flow Reception */ + if (((itFlag & SPDIFRX_FLAG_RXNE) == SPDIFRX_FLAG_RXNE) && ((itSource & SPDIFRX_IT_RXNE) == SPDIFRX_IT_RXNE)) + { + __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_RXNE); + SPDIFRX_ReceiveDataFlow_IT(hspdif); + } + + /* SPDIFRX in mode Control Flow Reception */ + if (((itFlag & SPDIFRX_FLAG_CSRNE) == SPDIFRX_FLAG_CSRNE) && ((itSource & SPDIFRX_IT_CSRNE) == SPDIFRX_IT_CSRNE)) + { + __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_CSRNE); + SPDIFRX_ReceiveControlFlow_IT(hspdif); + } + + /* SPDIFRX Overrun error interrupt occurred */ + if (((itFlag & SPDIFRX_FLAG_OVR) == SPDIFRX_FLAG_OVR) && ((itSource & SPDIFRX_IT_OVRIE) == SPDIFRX_IT_OVRIE)) + { + __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_OVRIE); + + /* Change the SPDIFRX error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_OVR; + + /* the transfer is not stopped */ + HAL_SPDIFRX_ErrorCallback(hspdif); + } + + /* SPDIFRX Parity error interrupt occurred */ + if (((itFlag & SPDIFRX_FLAG_PERR) == SPDIFRX_FLAG_PERR) && ((itSource & SPDIFRX_IT_PERRIE) == SPDIFRX_IT_PERRIE)) + { + __HAL_SPDIFRX_CLEAR_IT(hspdif, SPDIFRX_IT_PERRIE); + + /* Change the SPDIFRX error code */ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_PE; + + /* the transfer is not stopped */ + HAL_SPDIFRX_ErrorCallback(hspdif); + } +} + +/** + * @brief Rx Transfer (Data flow) half completed callbacks + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_RxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer (Data flow) completed callbacks + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_RxCpltCallback(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx (Control flow) Transfer half completed callbacks + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_CxHalfCpltCallback(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer (Control flow) completed callbacks + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_CxCpltCallback(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SPDIFRX error callbacks + * @param hspdif SPDIFRX handle + * @retval None + */ +__weak void HAL_SPDIFRX_ErrorCallback(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspdif); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPDIFRX_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SPDIFRX_Exported_Functions_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 SPDIFRX state + * @param hspdif SPDIFRX handle + * @retval HAL state + */ +HAL_SPDIFRX_StateTypeDef HAL_SPDIFRX_GetState(SPDIFRX_HandleTypeDef const *const hspdif) +{ + return hspdif->State; +} + +/** + * @brief Return the SPDIFRX error code + * @param hspdif SPDIFRX handle + * @retval SPDIFRX Error Code + */ +uint32_t HAL_SPDIFRX_GetError(SPDIFRX_HandleTypeDef const *const hspdif) +{ + return hspdif->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief DMA SPDIFRX receive process (Data flow) complete callback + * @param hdma DMA handle + * @retval None + */ +static void SPDIFRX_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable Rx DMA Request */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_RXDMAEN); + hspdif->RxXferCount = 0; + hspdif->State = HAL_SPDIFRX_STATE_READY; + } +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + hspdif->RxCpltCallback(hspdif); +#else + HAL_SPDIFRX_RxCpltCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPDIFRX receive process (Data flow) half complete callback + * @param hdma DMA handle + * @retval None + */ +static void SPDIFRX_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + hspdif->RxHalfCpltCallback(hspdif); +#else + HAL_SPDIFRX_RxHalfCpltCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ +} + + +/** + * @brief DMA SPDIFRX receive process (Control flow) complete callback + * @param hdma DMA handle + * @retval None + */ +static void SPDIFRX_DMACxCplt(DMA_HandleTypeDef *hdma) +{ + SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable Cb DMA Request */ + hspdif->Instance->CR &= (uint16_t)(~SPDIFRX_CR_CBDMAEN); + hspdif->CsXferCount = 0; + + hspdif->State = HAL_SPDIFRX_STATE_READY; +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + hspdif->CxCpltCallback(hspdif); +#else + HAL_SPDIFRX_CxCpltCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPDIFRX receive process (Control flow) half complete callback + * @param hdma DMA handle + * @retval None + */ +static void SPDIFRX_DMACxHalfCplt(DMA_HandleTypeDef *hdma) +{ + SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + hspdif->CxHalfCpltCallback(hspdif); +#else + HAL_SPDIFRX_CxHalfCpltCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPDIFRX communication error callback + * @param hdma DMA handle + * @retval None + */ +static void SPDIFRX_DMAError(DMA_HandleTypeDef *hdma) +{ + SPDIFRX_HandleTypeDef *hspdif = (SPDIFRX_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Disable Rx and Cb DMA Request */ + hspdif->Instance->CR &= (uint16_t)(~(SPDIFRX_CR_RXDMAEN | SPDIFRX_CR_CBDMAEN)); + hspdif->RxXferCount = 0; + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Set the error code and execute error callback*/ + hspdif->ErrorCode |= HAL_SPDIFRX_ERROR_DMA; + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + /* The transfer is not stopped */ + hspdif->ErrorCallback(hspdif); +#else + /* The transfer is not stopped */ + HAL_SPDIFRX_ErrorCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ +} + +/** + * @brief Receive an amount of data (Data Flow) with Interrupt + * @param hspdif SPDIFRX handle + * @retval None + */ +static void SPDIFRX_ReceiveDataFlow_IT(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Receive data */ + (*hspdif->pRxBuffPtr) = hspdif->Instance->DR; + hspdif->pRxBuffPtr++; + hspdif->RxXferCount--; + + if (hspdif->RxXferCount == 0U) + { + /* Disable RXNE/PE and OVR interrupts */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE | SPDIFRX_IT_PERRIE | SPDIFRX_IT_RXNE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + hspdif->RxCpltCallback(hspdif); +#else + HAL_SPDIFRX_RxCpltCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Receive an amount of data (Control Flow) with Interrupt + * @param hspdif SPDIFRX handle + * @retval None + */ +static void SPDIFRX_ReceiveControlFlow_IT(SPDIFRX_HandleTypeDef *hspdif) +{ + /* Receive data */ + (*hspdif->pCsBuffPtr) = hspdif->Instance->CSR; + hspdif->pCsBuffPtr++; + hspdif->CsXferCount--; + + if (hspdif->CsXferCount == 0U) + { + /* Disable CSRNE interrupt */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + +#if (USE_HAL_SPDIFRX_REGISTER_CALLBACKS == 1) + hspdif->CxCpltCallback(hspdif); +#else + HAL_SPDIFRX_CxCpltCallback(hspdif); +#endif /* USE_HAL_SPDIFRX_REGISTER_CALLBACKS */ + } +} + +/** + * @brief This function handles SPDIFRX Communication Timeout. + * @param hspdif SPDIFRX handle + * @param Flag Flag checked + * @param Status Value of the flag expected + * @param Timeout Duration of the timeout + * @param tickstart Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef SPDIFRX_WaitOnFlagUntilTimeout(SPDIFRX_HandleTypeDef *hspdif, uint32_t Flag, + FlagStatus Status, uint32_t Timeout, uint32_t tickstart) +{ + /* Wait until flag is set */ + while (__HAL_SPDIFRX_GET_FLAG(hspdif, Flag) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt + process */ + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_RXNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_CSRNE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_PERRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_OVRIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SBLKIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_SYNCDIE); + __HAL_SPDIFRX_DISABLE_IT(hspdif, SPDIFRX_IT_IFEIE); + + hspdif->State = HAL_SPDIFRX_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspdif); + + return HAL_TIMEOUT; + } + } + } + + return HAL_OK; +} + +/** + * @} + */ + + +#endif /* SPDIFRX */ +#endif /* HAL_SPDIFRX_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi.c index ee04aea47..5c5f00c36 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi.c @@ -1,3796 +1,3796 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_spi.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 implementing 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 or DMA 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/Channel - (+++) Enable the DMAx clock - (+++) Configure the DMA handle parameters - (+++) Configure the DMA Tx or Rx Stream/Channel - (+++) Associate the initialized 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/Channel - - (#) Program the Mode, BidirectionalMode , 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 customized HAL_SPI_MspInit() API. - [..] - Callback registration: - - (#) The compilation flag USE_HAL_SPI_REGISTER_CALLBACKS when set to 1UL - allows the user to configure dynamically the driver callbacks. - Use Functions HAL_SPI_RegisterCallback() to register an interrupt callback. - - Function HAL_SPI_RegisterCallback() allows to register following callbacks: - (+) TxCpltCallback : SPI Tx Completed callback - (+) RxCpltCallback : SPI Rx Completed callback - (+) TxRxCpltCallback : SPI TxRx Completed callback - (+) TxHalfCpltCallback : SPI Tx Half Completed callback - (+) RxHalfCpltCallback : SPI Rx Half Completed callback - (+) TxRxHalfCpltCallback : SPI TxRx Half Completed callback - (+) ErrorCallback : SPI Error callback - (+) AbortCpltCallback : SPI Abort callback - (+) SuspendCallback : SPI Suspend callback - (+) MspInitCallback : SPI Msp Init callback - (+) MspDeInitCallback : SPI Msp DeInit callback - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - - (#) Use function HAL_SPI_UnRegisterCallback to reset a callback to the default - weak function. - HAL_SPI_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxCpltCallback : SPI Tx Completed callback - (+) RxCpltCallback : SPI Rx Completed callback - (+) TxRxCpltCallback : SPI TxRx Completed callback - (+) TxHalfCpltCallback : SPI Tx Half Completed callback - (+) RxHalfCpltCallback : SPI Rx Half Completed callback - (+) TxRxHalfCpltCallback : SPI TxRx Half Completed callback - (+) ErrorCallback : SPI Error callback - (+) AbortCpltCallback : SPI Abort callback - (+) SuspendCallback : SPI Suspend callback - (+) MspInitCallback : SPI Msp Init callback - (+) MspDeInitCallback : SPI Msp DeInit callback - - By default, after the HAL_SPI_Init() and when the state is HAL_SPI_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_SPI_MasterTxCpltCallback(), HAL_SPI_MasterRxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the HAL_SPI_Init()/ HAL_SPI_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the HAL_SPI_Init()/ HAL_SPI_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - - Callbacks can be registered/unregistered in HAL_SPI_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in HAL_SPI_STATE_READY or HAL_SPI_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using HAL_SPI_RegisterCallback() before calling HAL_SPI_DeInit() - or HAL_SPI_Init() function. - - When The compilation define USE_HAL_PPP_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (surcharged) callbacks are used. - - SuspendCallback restriction: - SuspendCallback is called only when MasterReceiverAutoSusp is enabled and - EOT interrupt is activated. SuspendCallback is used in relation with functions - HAL_SPI_Transmit_IT, HAL_SPI_Receive_IT and HAL_SPI_TransmitReceive_IT. - - [..] - Circular mode restriction: - (+) The DMA circular mode cannot be used when the SPI is configured in these modes: - (++) Master 2Lines RxOnly - (++) Master 1Line Rx - (+) The CRC feature is not managed when the DMA circular mode is enabled - (+) The functions HAL_SPI_DMAPause()/ HAL_SPI_DMAResume() are not supported. Return always - HAL_ERROR with ErrorCode set to HAL_SPI_ERROR_NOT_SUPPORTED. - Those functions are maintained for backward compatibility reasons. - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SPI SPI - * @brief SPI HAL module driver - * @{ - */ -#ifdef HAL_SPI_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private defines -----------------------------------------------------------*/ -/** @defgroup SPI_Private_Constants SPI Private Constants - * @{ - */ -#define SPI_DEFAULT_TIMEOUT 100UL -#define MAX_FIFO_LENGTH 16UL -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup SPI_Private_Functions SPI Private Functions - * @{ - */ -static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma); -static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma); -static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma); -static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma); -static void SPI_DMAError(DMA_HandleTypeDef *hdma); -static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(const SPI_HandleTypeDef *hspi, uint32_t Flag, - FlagStatus FlagStatus, uint32_t Timeout, uint32_t Tickstart); -static void SPI_TxISR_8BIT(SPI_HandleTypeDef *hspi); -static void SPI_TxISR_16BIT(SPI_HandleTypeDef *hspi); -static void SPI_TxISR_32BIT(SPI_HandleTypeDef *hspi); -static void SPI_RxISR_8BIT(SPI_HandleTypeDef *hspi); -static void SPI_RxISR_16BIT(SPI_HandleTypeDef *hspi); -static void SPI_RxISR_32BIT(SPI_HandleTypeDef *hspi); -static void SPI_AbortTransfer(SPI_HandleTypeDef *hspi); -static void SPI_CloseTransfer(SPI_HandleTypeDef *hspi); -static uint32_t SPI_GetPacketSize(const SPI_HandleTypeDef *hspi); - - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup SPI_Exported_Functions SPI Exported Functions - * @{ - */ - -/** @defgroup SPI_Exported_Functions_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 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 - (++) CRC Length, used only with Data8 and Data16 - (++) FIFO reception threshold - (++) FIFO transmission threshold - - (+) Call the function HAL_SPI_DeInit() to restore the default configuration - of the selected SPIx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the SPI according to the specified parameters - * in the SPI_InitTypeDef and initialize the associated handle. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) -{ - uint32_t crc_length; - uint32_t packet_length; - - /* Check the SPI handle allocation */ - if (hspi == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); - assert_param(IS_SPI_MODE(hspi->Init.Mode)); - assert_param(IS_SPI_DIRECTION(hspi->Init.Direction)); - if (IS_SPI_LIMITED_INSTANCE(hspi->Instance)) - { - assert_param(IS_SPI_LIMITED_DATASIZE(hspi->Init.DataSize)); - assert_param(IS_SPI_LIMITED_FIFOTHRESHOLD(hspi->Init.FifoThreshold)); - } - else - { - assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); - assert_param(IS_SPI_FIFOTHRESHOLD(hspi->Init.FifoThreshold)); - } - assert_param(IS_SPI_NSS(hspi->Init.NSS)); - assert_param(IS_SPI_NSSP(hspi->Init.NSSPMode)); - 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)); - if (hspi->Init.TIMode == SPI_TIMODE_DISABLE) - { - assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); - assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); - } -#if (USE_SPI_CRC != 0UL) - assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); - if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - if (IS_SPI_LIMITED_INSTANCE(hspi->Instance)) - { - assert_param(IS_SPI_LIMITED_CRC_LENGTH(hspi->Init.CRCLength)); - } - else - { - assert_param(IS_SPI_CRC_LENGTH(hspi->Init.CRCLength)); - } - assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); - assert_param(IS_SPI_CRC_INITIALIZATION_PATTERN(hspi->Init.TxCRCInitializationPattern)); - assert_param(IS_SPI_CRC_INITIALIZATION_PATTERN(hspi->Init.RxCRCInitializationPattern)); - } -#else - hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; -#endif /* USE_SPI_CRC */ - - assert_param(IS_SPI_RDY_MASTER_MANAGEMENT(hspi->Init.ReadyMasterManagement)); - assert_param(IS_SPI_RDY_POLARITY(hspi->Init.ReadyPolarity)); - assert_param(IS_SPI_MASTER_RX_AUTOSUSP(hspi->Init.MasterReceiverAutoSusp)); - - /* Verify that the SPI instance supports Data Size higher than 16bits */ - if ((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (hspi->Init.DataSize > SPI_DATASIZE_16BIT)) - { - return HAL_ERROR; - } - - /* Verify that the SPI instance supports requested data packing */ - packet_length = SPI_GetPacketSize(hspi); - if (((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (packet_length > SPI_LOWEND_FIFO_SIZE)) || - ((IS_SPI_FULL_INSTANCE(hspi->Instance)) && (packet_length > SPI_HIGHEND_FIFO_SIZE))) - { - return HAL_ERROR; - } -#if (USE_SPI_CRC != 0UL) - if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Verify that the SPI instance supports CRC Length higher than 16bits */ - if ((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (hspi->Init.CRCLength > SPI_CRC_LENGTH_16BIT)) - { - return HAL_ERROR; - } - - /* Align the CRC Length on the data size */ - if (hspi->Init.CRCLength == SPI_CRC_LENGTH_DATASIZE) - { - crc_length = (hspi->Init.DataSize >> SPI_CFG1_DSIZE_Pos) << SPI_CFG1_CRCSIZE_Pos; - } - else - { - crc_length = hspi->Init.CRCLength; - } - - /* Verify that the CRC Length is higher than DataSize */ - if ((hspi->Init.DataSize >> SPI_CFG1_DSIZE_Pos) > (crc_length >> SPI_CFG1_CRCSIZE_Pos)) - { - return HAL_ERROR; - } - } - else - { - crc_length = hspi->Init.DataSize << SPI_CFG1_CRCSIZE_Pos; - } -#endif /* USE_SPI_CRC */ - - if (hspi->State == HAL_SPI_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hspi->Lock = HAL_UNLOCKED; - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - /* Init the SPI Callback settings */ - hspi->TxCpltCallback = HAL_SPI_TxCpltCallback; /* Legacy weak TxCpltCallback */ - hspi->RxCpltCallback = HAL_SPI_RxCpltCallback; /* Legacy weak RxCpltCallback */ - hspi->TxRxCpltCallback = HAL_SPI_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ - hspi->TxHalfCpltCallback = HAL_SPI_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - hspi->RxHalfCpltCallback = HAL_SPI_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - hspi->TxRxHalfCpltCallback = HAL_SPI_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ - hspi->ErrorCallback = HAL_SPI_ErrorCallback; /* Legacy weak ErrorCallback */ - hspi->AbortCpltCallback = HAL_SPI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - hspi->SuspendCallback = HAL_SPI_SuspendCallback; /* Legacy weak SuspendCallback */ - - if (hspi->MspInitCallback == NULL) - { - hspi->MspInitCallback = HAL_SPI_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware : GPIO, CLOCK, NVIC... */ - hspi->MspInitCallback(hspi); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC... */ - HAL_SPI_MspInit(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } - - hspi->State = HAL_SPI_STATE_BUSY; - - /* Disable the selected SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - -#if (USE_SPI_CRC == 0) - /* Keep the default value of CRCSIZE in case of CRC is not used */ - crc_length = hspi->Instance->CFG1 & SPI_CFG1_CRCSIZE; -#endif /* USE_SPI_CRC */ - - /*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/ - /* Configure : SPI Mode, Communication Mode, Clock polarity and phase, NSS management, - Communication speed, First bit, CRC calculation state, CRC Length */ - - /* SPIx NSS Software Management Configuration */ - if ((hspi->Init.NSS == SPI_NSS_SOFT) && (((hspi->Init.Mode == SPI_MODE_MASTER) && \ - (hspi->Init.NSSPolarity == SPI_NSS_POLARITY_LOW)) || \ - ((hspi->Init.Mode == SPI_MODE_SLAVE) && \ - (hspi->Init.NSSPolarity == SPI_NSS_POLARITY_HIGH)))) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_SSI); - } - - /* SPIx Master Rx Auto Suspend Configuration */ - if (((hspi->Init.Mode & SPI_MODE_MASTER) == SPI_MODE_MASTER) && (hspi->Init.DataSize >= SPI_DATASIZE_8BIT)) - { - MODIFY_REG(hspi->Instance->CR1, SPI_CR1_MASRX, hspi->Init.MasterReceiverAutoSusp); - } - else - { - CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_MASRX); - } - - /* SPIx CFG1 Configuration */ - WRITE_REG(hspi->Instance->CFG1, (hspi->Init.BaudRatePrescaler | hspi->Init.CRCCalculation | crc_length | - hspi->Init.FifoThreshold | hspi->Init.DataSize)); - - /* SPIx CFG2 Configuration */ - WRITE_REG(hspi->Instance->CFG2, (hspi->Init.NSSPMode | hspi->Init.TIMode | - hspi->Init.NSSPolarity | hspi->Init.NSS | - hspi->Init.CLKPolarity | hspi->Init.CLKPhase | - hspi->Init.FirstBit | hspi->Init.Mode | - hspi->Init.MasterInterDataIdleness | hspi->Init.Direction | - hspi->Init.MasterSSIdleness | hspi->Init.IOSwap | - hspi->Init.ReadyMasterManagement | hspi->Init.ReadyPolarity)); - -#if (USE_SPI_CRC != 0UL) - /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ - /* Configure : CRC Polynomial */ - if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Initialize TXCRC Pattern Initial Value */ - if (hspi->Init.TxCRCInitializationPattern == SPI_CRC_INITIALIZATION_ALL_ONE_PATTERN) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_TCRCINI); - } - else - { - CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_TCRCINI); - } - - /* Initialize RXCRC Pattern Initial Value */ - if (hspi->Init.RxCRCInitializationPattern == SPI_CRC_INITIALIZATION_ALL_ONE_PATTERN) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_RCRCINI); - } - else - { - CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_RCRCINI); - } - - /* Enable 33/17 bits CRC computation */ - if (((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (crc_length == SPI_CRC_LENGTH_16BIT)) || - ((IS_SPI_FULL_INSTANCE(hspi->Instance)) && (crc_length == SPI_CRC_LENGTH_32BIT))) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRC33_17); - } - else - { - CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_CRC33_17); - } - - /* Write CRC polynomial in SPI Register */ - WRITE_REG(hspi->Instance->CRCPOLY, hspi->Init.CRCPolynomial); - } -#endif /* USE_SPI_CRC */ - - /* Insure that Underrun configuration is managed only by Salve */ - if (hspi->Init.Mode == SPI_MODE_SLAVE) - { -#if (USE_SPI_CRC != 0UL) - MODIFY_REG(hspi->Instance->CFG1, SPI_CFG1_UDRCFG, SPI_CFG1_UDRCFG); -#endif /* USE_SPI_CRC */ - } - -#if defined(SPI_I2SCFGR_I2SMOD) - /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ - CLEAR_BIT(hspi->Instance->I2SCFGR, SPI_I2SCFGR_I2SMOD); -#endif /* SPI_I2SCFGR_I2SMOD */ - - /* Insure that AFCNTR is managed only by Master */ - if ((hspi->Init.Mode & SPI_MODE_MASTER) == SPI_MODE_MASTER) - { - /* Alternate function GPIOs control */ - MODIFY_REG(hspi->Instance->CFG2, SPI_CFG2_AFCNTR, (hspi->Init.MasterKeepIOState)); - } - - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->State = HAL_SPI_STATE_READY; - - return HAL_OK; -} - -/** - * @brief De-Initialize the SPI peripheral. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) -{ - /* Check the SPI handle allocation */ - if (hspi == NULL) - { - return HAL_ERROR; - } - - /* Check SPI Instance parameter */ - assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); - - hspi->State = HAL_SPI_STATE_BUSY; - - /* Disable the SPI Peripheral Clock */ - __HAL_SPI_DISABLE(hspi); - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - if (hspi->MspDeInitCallback == NULL) - { - hspi->MspDeInitCallback = HAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ - hspi->MspDeInitCallback(hspi); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ - HAL_SPI_MspDeInit(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->State = HAL_SPI_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hspi); - - return HAL_OK; -} - -/** - * @brief Initialize the SPI MSP. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_MspInit should be implemented in the user file - */ -} - -/** - * @brief De-Initialize the SPI MSP. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_MspDeInit should be implemented in the user file - */ -} - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) -/** - * @brief Register a User SPI Callback - * To be used instead of the weak predefined callback - * @param hspi Pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI. - * @param CallbackID ID of the callback to be registered - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_RegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_CallbackIDTypeDef CallbackID, - pSPI_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hspi->ErrorCode |= HAL_SPI_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - /* Lock the process */ - __HAL_LOCK(hspi); - - if (HAL_SPI_STATE_READY == hspi->State) - { - switch (CallbackID) - { - case HAL_SPI_TX_COMPLETE_CB_ID : - hspi->TxCpltCallback = pCallback; - break; - - case HAL_SPI_RX_COMPLETE_CB_ID : - hspi->RxCpltCallback = pCallback; - break; - - case HAL_SPI_TX_RX_COMPLETE_CB_ID : - hspi->TxRxCpltCallback = pCallback; - break; - - case HAL_SPI_TX_HALF_COMPLETE_CB_ID : - hspi->TxHalfCpltCallback = pCallback; - break; - - case HAL_SPI_RX_HALF_COMPLETE_CB_ID : - hspi->RxHalfCpltCallback = pCallback; - break; - - case HAL_SPI_TX_RX_HALF_COMPLETE_CB_ID : - hspi->TxRxHalfCpltCallback = pCallback; - break; - - case HAL_SPI_ERROR_CB_ID : - hspi->ErrorCallback = pCallback; - break; - - case HAL_SPI_ABORT_CB_ID : - hspi->AbortCpltCallback = pCallback; - break; - - case HAL_SPI_SUSPEND_CB_ID : - hspi->SuspendCallback = pCallback; - break; - - case HAL_SPI_MSPINIT_CB_ID : - hspi->MspInitCallback = pCallback; - break; - - case HAL_SPI_MSPDEINIT_CB_ID : - hspi->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SPI_STATE_RESET == hspi->State) - { - switch (CallbackID) - { - case HAL_SPI_MSPINIT_CB_ID : - hspi->MspInitCallback = pCallback; - break; - - case HAL_SPI_MSPDEINIT_CB_ID : - hspi->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hspi); - return status; -} - -/** - * @brief Unregister an SPI Callback - * SPI callback is redirected to the weak predefined callback - * @param hspi Pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI. - * @param CallbackID ID of the callback to be unregistered - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Lock the process */ - __HAL_LOCK(hspi); - - if (HAL_SPI_STATE_READY == hspi->State) - { - switch (CallbackID) - { - case HAL_SPI_TX_COMPLETE_CB_ID : - hspi->TxCpltCallback = HAL_SPI_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_SPI_RX_COMPLETE_CB_ID : - hspi->RxCpltCallback = HAL_SPI_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_SPI_TX_RX_COMPLETE_CB_ID : - hspi->TxRxCpltCallback = HAL_SPI_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ - break; - - case HAL_SPI_TX_HALF_COMPLETE_CB_ID : - hspi->TxHalfCpltCallback = HAL_SPI_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - break; - - case HAL_SPI_RX_HALF_COMPLETE_CB_ID : - hspi->RxHalfCpltCallback = HAL_SPI_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - break; - - case HAL_SPI_TX_RX_HALF_COMPLETE_CB_ID : - hspi->TxRxHalfCpltCallback = HAL_SPI_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ - break; - - case HAL_SPI_ERROR_CB_ID : - hspi->ErrorCallback = HAL_SPI_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_SPI_ABORT_CB_ID : - hspi->AbortCpltCallback = HAL_SPI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_SPI_SUSPEND_CB_ID : - hspi->SuspendCallback = HAL_SPI_SuspendCallback; /* Legacy weak SuspendCallback */ - break; - - case HAL_SPI_MSPINIT_CB_ID : - hspi->MspInitCallback = HAL_SPI_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_SPI_MSPDEINIT_CB_ID : - hspi->MspDeInitCallback = HAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_SPI_STATE_RESET == hspi->State) - { - switch (CallbackID) - { - case HAL_SPI_MSPINIT_CB_ID : - hspi->MspInitCallback = HAL_SPI_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_SPI_MSPDEINIT_CB_ID : - hspi->MspDeInitCallback = HAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default : - /* Update the error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hspi); - return status; -} -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -/** - * @} - */ - -/** @defgroup SPI_Exported_Functions_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 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. - (##) No-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 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 respectively at the end of the transmit or Receive process - The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected - - (#) APIs provided for these 2 transfer modes (Blocking mode or Non blocking mode using either Interrupt or DMA) - exist for 1Line (simplex) and 2Lines (full duplex) modes. - -@endverbatim - * @{ - */ - -/** - * @brief Transmit an amount of data in blocking mode. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @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, const uint8_t *pData, uint16_t Size, uint32_t Timeout) -{ -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); -#endif /* __GNUC__ */ - - uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_TXONLY(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (const uint8_t *)pData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - - /*Init field not used in handle to zero */ - hspi->pRxBuffPtr = NULL; - hspi->RxXferSize = (uint16_t) 0UL; - hspi->RxXferCount = (uint16_t) 0UL; - hspi->TxISR = NULL; - hspi->RxISR = NULL; - - /* Configure communication direction : 1Line */ - if (hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_TX(hspi); - } - else - { - SPI_2LINES_TX(hspi); - } - - /* Set the number of data at current transfer */ - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Transmit data in 32 Bit mode */ - if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) - { - /* Transmit data in 32 Bit mode */ - while (hspi->TxXferCount > 0UL) - { - /* Wait until TXP flag is set to send data */ - if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) - { - *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint32_t); - hspi->TxXferCount--; - } - else - { - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - /* Transmit data in 16 Bit mode */ - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { - /* Transmit data in 16 Bit mode */ - while (hspi->TxXferCount > 0UL) - { - /* Wait until TXP flag is set to send data */ - if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) - { - if ((hspi->TxXferCount > 1UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_01DATA)) - { - *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint32_t); - hspi->TxXferCount -= (uint16_t)2UL; - } - else - { -#if defined (__GNUC__) - *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); -#else - *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); -#endif /* __GNUC__ */ - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount--; - } - } - else - { - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - /* Transmit data in 8 Bit mode */ - else - { - while (hspi->TxXferCount > 0UL) - { - /* Wait until TXP flag is set to send data */ - if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) - { - if ((hspi->TxXferCount > 3UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_03DATA)) - { - *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint32_t); - hspi->TxXferCount -= (uint16_t)4UL; - } - else if ((hspi->TxXferCount > 1UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_01DATA)) - { -#if defined (__GNUC__) - *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); -#else - *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); -#endif /* __GNUC__ */ - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount -= (uint16_t)2UL; - } - else - { - *((__IO uint8_t *)&hspi->Instance->TXDR) = *((const uint8_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint8_t); - hspi->TxXferCount--; - } - } - else - { - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - - /* Wait for Tx (and CRC) data to be sent */ - if (SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_EOT, RESET, Timeout, tickstart) != HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - } - - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - - if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - return HAL_ERROR; - } - return errorcode; -} - -/** - * @brief Receive an amount of data in blocking mode. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param pData : pointer to data buffer - * @param Size : amount of data to be received - * @param Timeout: Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) -{ - uint32_t tickstart; - HAL_StatusTypeDef errorcode = HAL_OK; -#if defined (__GNUC__) - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); -#endif /* __GNUC__ */ - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_RXONLY(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /*Init field not used in handle to zero */ - hspi->pTxBuffPtr = NULL; - hspi->TxXferSize = (uint16_t) 0UL; - hspi->TxXferCount = (uint16_t) 0UL; - hspi->RxISR = NULL; - hspi->TxISR = NULL; - - /* Configure communication direction: 1Line */ - if (hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_RX(hspi); - } - else - { - SPI_2LINES_RX(hspi); - } - - /* Set the number of data at current transfer */ - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Receive data in 32 Bit mode */ - if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) - { - /* Transfer loop */ - while (hspi->RxXferCount > 0UL) - { - /* Check the RXWNE/EOT flag */ - if ((hspi->Instance->SR & (SPI_FLAG_RXWNE | SPI_FLAG_EOT)) != 0UL) - { - *((uint32_t *)hspi->pRxBuffPtr) = *((__IO uint32_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint32_t); - hspi->RxXferCount--; - } - else - { - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - /* Receive data in 16 Bit mode */ - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { - /* Transfer loop */ - while (hspi->RxXferCount > 0UL) - { - /* Check the RXP flag */ - if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) - { -#if defined (__GNUC__) - *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hspi->pRxBuffPtr) = *((__IO uint16_t *)&hspi->Instance->RXDR); -#endif /* __GNUC__ */ - hspi->pRxBuffPtr += sizeof(uint16_t); - hspi->RxXferCount--; - } - else - { - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - /* Receive data in 8 Bit mode */ - else - { - /* Transfer loop */ - while (hspi->RxXferCount > 0UL) - { - /* Check the RXP flag */ - if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) - { - *((uint8_t *)hspi->pRxBuffPtr) = *((__IO uint8_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint8_t); - hspi->RxXferCount--; - } - else - { - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - } - -#if (USE_SPI_CRC != 0UL) - if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Wait for crc data to be received */ - if (SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_EOT, RESET, Timeout, tickstart) != HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - } - } -#endif /* USE_SPI_CRC */ - - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - - if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - return HAL_ERROR; - } - return errorcode; -} - -/** - * @brief Transmit and Receive an amount of data in blocking mode. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param pTxData: pointer to transmission data buffer - * @param pRxData: pointer to reception data buffer - * @param Size : amount of data to be sent and received - * @param Timeout: Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, - uint16_t Size, uint32_t Timeout) -{ - HAL_StatusTypeDef errorcode = HAL_OK; -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); -#endif /* __GNUC__ */ - - uint32_t tickstart; - uint16_t initial_TxXferCount; - uint16_t initial_RxXferCount; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - initial_TxXferCount = Size; - initial_RxXferCount = Size; - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pRxData; - hspi->RxXferCount = Size; - hspi->RxXferSize = Size; - hspi->pTxBuffPtr = (const uint8_t *)pTxData; - hspi->TxXferCount = Size; - hspi->TxXferSize = Size; - - /*Init field not used in handle to zero */ - hspi->RxISR = NULL; - hspi->TxISR = NULL; - - /* Set Full-Duplex mode */ - SPI_2LINES(hspi); - - /* Set the number of data at current transfer */ - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - - __HAL_SPI_ENABLE(hspi); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Transmit and Receive data in 32 Bit mode */ - if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) - { - while ((initial_TxXferCount > 0UL) || (initial_RxXferCount > 0UL)) - { - /* Check TXP flag */ - if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) && (initial_TxXferCount > 0UL)) - { - *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint32_t); - hspi->TxXferCount --; - initial_TxXferCount = hspi->TxXferCount; - } - - /* Check RXWNE/EOT flag */ - if (((hspi->Instance->SR & (SPI_FLAG_RXWNE | SPI_FLAG_EOT)) != 0UL) && (initial_RxXferCount > 0UL)) - { - *((uint32_t *)hspi->pRxBuffPtr) = *((__IO uint32_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint32_t); - hspi->RxXferCount --; - initial_RxXferCount = hspi->RxXferCount; - } - - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - /* Transmit and Receive data in 16 Bit mode */ - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { - while ((initial_TxXferCount > 0UL) || (initial_RxXferCount > 0UL)) - { - /* Check the TXP flag */ - if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP) && (initial_TxXferCount > 0UL)) - { -#if defined (__GNUC__) - *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); -#else - *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); -#endif /* __GNUC__ */ - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount--; - initial_TxXferCount = hspi->TxXferCount; - } - - /* Check the RXP flag */ - if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) && (initial_RxXferCount > 0UL)) - { -#if defined (__GNUC__) - *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hspi->pRxBuffPtr) = *((__IO uint16_t *)&hspi->Instance->RXDR); -#endif /* __GNUC__ */ - hspi->pRxBuffPtr += sizeof(uint16_t); - hspi->RxXferCount--; - initial_RxXferCount = hspi->RxXferCount; - } - - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - /* Transmit and Receive data in 8 Bit mode */ - else - { - while ((initial_TxXferCount > 0UL) || (initial_RxXferCount > 0UL)) - { - /* Check the TXP flag */ - if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) && (initial_TxXferCount > 0UL)) - { - *((__IO uint8_t *)&hspi->Instance->TXDR) = *((const uint8_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint8_t); - hspi->TxXferCount--; - initial_TxXferCount = hspi->TxXferCount; - } - - /* Check the RXP flag */ - if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) && (initial_RxXferCount > 0UL)) - { - *((uint8_t *)hspi->pRxBuffPtr) = *((__IO uint8_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint8_t); - hspi->RxXferCount--; - initial_RxXferCount = hspi->RxXferCount; - } - - /* Timeout management */ - if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); - hspi->State = HAL_SPI_STATE_READY; - return HAL_TIMEOUT; - } - } - } - - /* Wait for Tx/Rx (and CRC) data to be sent/received */ - if (SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_EOT, RESET, Timeout, tickstart) != HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - } - - /* Call standard close procedure with error check */ - SPI_CloseTransfer(hspi); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - - if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - return HAL_ERROR; - } - return errorcode; -} - -/** - * @brief Transmit an amount of data in non-blocking mode with Interrupt. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @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, const uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_TXONLY(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - if ((pData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (const uint8_t *)pData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->pRxBuffPtr = NULL; - hspi->RxXferSize = (uint16_t) 0UL; - hspi->RxXferCount = (uint16_t) 0UL; - hspi->RxISR = NULL; - - /* Set the function for IT treatment */ - if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) - { - hspi->TxISR = SPI_TxISR_32BIT; - } - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { - hspi->TxISR = SPI_TxISR_16BIT; - } - else - { - hspi->TxISR = SPI_TxISR_8BIT; - } - - /* Configure communication direction : 1Line */ - if (hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_TX(hspi); - } - else - { - SPI_2LINES_TX(hspi); - } - - /* Set the number of data at current transfer */ - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - /* Enable EOT, TXP, FRE, MODF and UDR interrupts */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_TXP | SPI_IT_UDR | SPI_IT_FRE | SPI_IT_MODF)); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Receive an amount of data in non-blocking mode with Interrupt. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @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) -{ - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_RXONLY(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->pTxBuffPtr = NULL; - hspi->TxXferSize = (uint16_t) 0UL; - hspi->TxXferCount = (uint16_t) 0UL; - hspi->TxISR = NULL; - - /* Set the function for IT treatment */ - if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) - { - hspi->RxISR = SPI_RxISR_32BIT; - } - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { - hspi->RxISR = SPI_RxISR_16BIT; - } - else - { - hspi->RxISR = SPI_RxISR_8BIT; - } - - /* Configure communication direction : 1Line */ - if (hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_RX(hspi); - } - else - { - SPI_2LINES_RX(hspi); - } - - /* Note : The SPI must be enabled after unlocking current process - to avoid the risk of SPI interrupt handle execution before current - process unlock */ - - /* Set the number of data at current transfer */ - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - /* Enable EOT, RXP, OVR, FRE and MODF interrupts */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_RXP | SPI_IT_OVR | SPI_IT_FRE | SPI_IT_MODF)); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Transmit and Receive an amount of data in non-blocking mode with Interrupt. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param pTxData: pointer to transmission data buffer - * @param pRxData: pointer to reception data buffer - * @param Size : amount of data to be sent and received - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, - uint16_t Size) -{ - HAL_StatusTypeDef errorcode = HAL_OK; - uint32_t tmp_TxXferCount; - -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); -#endif /* __GNUC__ */ - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (const uint8_t *)pTxData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - hspi->pRxBuffPtr = (uint8_t *)pRxData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - tmp_TxXferCount = hspi->TxXferCount; - - /* Set the function for IT treatment */ - if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) - { - hspi->TxISR = SPI_TxISR_32BIT; - hspi->RxISR = SPI_RxISR_32BIT; - } - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { - hspi->RxISR = SPI_RxISR_16BIT; - hspi->TxISR = SPI_TxISR_16BIT; - } - else - { - hspi->RxISR = SPI_RxISR_8BIT; - hspi->TxISR = SPI_TxISR_8BIT; - } - - /* Set Full-Duplex mode */ - SPI_2LINES(hspi); - - /* Set the number of data at current transfer */ - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - /* Fill in the TxFIFO */ - while ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) && (tmp_TxXferCount != 0UL)) - { - /* Transmit data in 32 Bit mode */ - if (hspi->Init.DataSize > SPI_DATASIZE_16BIT) - { - *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint32_t); - hspi->TxXferCount--; - tmp_TxXferCount = hspi->TxXferCount; - } - /* Transmit data in 16 Bit mode */ - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { -#if defined (__GNUC__) - *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); -#else - *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); -#endif /* __GNUC__ */ - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount--; - tmp_TxXferCount = hspi->TxXferCount; - } - /* Transmit data in 8 Bit mode */ - else - { - *((__IO uint8_t *)&hspi->Instance->TXDR) = *((const uint8_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint8_t); - hspi->TxXferCount--; - tmp_TxXferCount = hspi->TxXferCount; - } - } - - /* Enable EOT, DXP, UDR, OVR, FRE and MODF interrupts */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_DXP | SPI_IT_UDR | SPI_IT_OVR | SPI_IT_FRE | SPI_IT_MODF)); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Start Master transfer */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - return errorcode; -} - - - - -/** - * @brief Transmit an amount of data in non-blocking mode with DMA. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @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, const uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef errorcode; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_TXONLY(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (const uint8_t *)pData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->pRxBuffPtr = NULL; - hspi->TxISR = NULL; - hspi->RxISR = NULL; - hspi->RxXferSize = (uint16_t)0UL; - hspi->RxXferCount = (uint16_t)0UL; - - /* Configure communication direction : 1Line */ - if (hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_TX(hspi); - } - else - { - SPI_2LINES_TX(hspi); - } - - /* Packing mode management is enabled by the DMA settings */ - if (((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (hspi->hdmatx->Init.SrcDataWidth != DMA_SRC_DATAWIDTH_WORD) && \ - (IS_SPI_FULL_INSTANCE(hspi->Instance))) || \ - ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) && (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_BYTE))) - { - /* Restriction the DMA data received is not allowed in this mode */ - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Adjust XferCount according to DMA alignment / Data size */ - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_HALFWORD) - { - hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; - } - if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) - { - hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 3UL) >> 2UL; - } - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) - { - hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; - } - } - else - { - /* Adjustment done */ - } - - /* Set the SPI TxDMA Half transfer complete callback */ - hspi->hdmatx->XferHalfCpltCallback = SPI_DMAHalfTransmitCplt; - - /* Set the SPI TxDMA transfer complete callback */ - hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt; - - /* Set the DMA error callback */ - hspi->hdmatx->XferErrorCallback = SPI_DMAError; - - /* Set the DMA AbortCpltCallback */ - hspi->hdmatx->XferAbortCallback = NULL; - - /* Clear TXDMAEN bit*/ - CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN); - - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - hspi->TxXferCount = Size; - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - hspi->TxXferCount = Size * 2U; - } - else - { - hspi->TxXferCount = Size * 4U; - } - - /* Enable the Tx DMA Stream/Channel */ - if ((hspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hspi->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->TxXferCount; - - /* Set DMA source address */ - hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hspi->pTxBuffPtr; - - /* Set DMA destination address */ - hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->TXDR; - - errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmatx); - } - else - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->TXDR, - hspi->TxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - - /* Set the number of data at current transfer */ - if (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR) - { - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, 0UL); - } - else - { - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - } - - /* Enable Tx DMA Request */ - SET_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN); - - /* Enable the SPI Error Interrupt Bit */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_UDR | SPI_IT_FRE | SPI_IT_MODF)); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Receive an amount of data in non-blocking mode with DMA. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param pData: pointer to data buffer - * @param Size : amount of data to be sent - * @note When the CRC feature is enabled the pData Length must be Size + 1. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef errorcode; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_RXONLY(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /*Init field not used in handle to zero */ - hspi->RxISR = NULL; - hspi->TxISR = NULL; - hspi->TxXferSize = (uint16_t) 0UL; - hspi->TxXferCount = (uint16_t) 0UL; - - /* Configure communication direction : 1Line */ - if (hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_RX(hspi); - } - else - { - SPI_2LINES_RX(hspi); - } - - /* Packing mode management is enabled by the DMA settings */ - if (((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (hspi->hdmarx->Init.DestDataWidth != DMA_DEST_DATAWIDTH_WORD) && \ - (IS_SPI_FULL_INSTANCE(hspi->Instance))) || \ - ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) && (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_BYTE))) - { - /* Restriction the DMA data received is not allowed in this mode */ - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Clear RXDMAEN bit */ - CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN); - - /* Adjust XferCount according to DMA alignment / Data size */ - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_HALFWORD) - { - hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; - } - if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) - { - hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 3UL) >> 2UL; - } - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) - { - hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; - } - } - else - { - /* Adjustment done */ - } - - /* Set the SPI RxDMA Half transfer complete callback */ - hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; - - /* Set the SPI Rx DMA transfer complete callback */ - hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; - - /* Set the DMA error callback */ - hspi->hdmarx->XferErrorCallback = SPI_DMAError; - - /* Set the DMA AbortCpltCallback */ - hspi->hdmarx->XferAbortCallback = NULL; - - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - hspi->RxXferCount = Size; - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - hspi->RxXferCount = Size * 2U; - } - else - { - hspi->RxXferCount = Size * 4U; - } - - /* Enable the Rx DMA Stream/Channel */ - if ((hspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hspi->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->RxXferCount; - - /* Set DMA source address */ - hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->RXDR; - - /* Set DMA destination address */ - hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hspi->pRxBuffPtr; - - errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmarx); - } - else - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->RXDR, (uint32_t)hspi->pRxBuffPtr, - hspi->RxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - - /* Set the number of data at current transfer */ - if (hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) - { - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, 0UL); - } - else - { - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - } - - /* Enable Rx DMA Request */ - SET_BIT(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN); - - /* Enable the SPI Error Interrupt Bit */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_OVR | SPI_IT_FRE | SPI_IT_MODF)); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Transmit and Receive an amount of data in non-blocking mode with DMA. - * @param hspi : pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param pTxData: pointer to transmission data buffer - * @param pRxData: pointer to reception data buffer - * @param Size : amount of data to be sent - * @note When the CRC feature is enabled the pRxData Length must be Size + 1 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, - uint16_t Size) -{ - HAL_StatusTypeDef errorcode; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - - /* Lock the process */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - __HAL_UNLOCK(hspi); - return errorcode; - } - - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL)) - { - errorcode = HAL_ERROR; - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (const 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 = NULL; - hspi->TxISR = NULL; - - /* Set Full-Duplex mode */ - SPI_2LINES(hspi); - - /* Reset the Tx/Rx DMA bits */ - CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); - - /* Packing mode management is enabled by the DMA settings */ - if (((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (hspi->hdmarx->Init.DestDataWidth != DMA_DEST_DATAWIDTH_WORD) && \ - (IS_SPI_FULL_INSTANCE(hspi->Instance))) || \ - ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) && (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_BYTE))) - { - /* Restriction the DMA data received is not allowed in this mode */ - errorcode = HAL_ERROR; - /* Unlock the process */ - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Adjust XferCount according to DMA alignment / Data size */ - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_HALFWORD) - { - hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; - } - if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) - { - hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 3UL) >> 2UL; - } - if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_HALFWORD) - { - hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; - } - if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) - { - hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 3UL) >> 2UL; - } - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) - { - hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; - } - if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) - { - hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; - } - } - else - { - /* Adjustment done */ - } - - /* Set the SPI Tx/Rx DMA Half transfer complete callback */ - hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfTransmitReceiveCplt; - hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt; - - /* Set the DMA error callback */ - hspi->hdmarx->XferErrorCallback = SPI_DMAError; - - /* Set the DMA AbortCallback */ - hspi->hdmarx->XferAbortCallback = NULL; - - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - hspi->RxXferCount = Size; - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - hspi->RxXferCount = Size * 2U; - } - else - { - hspi->RxXferCount = Size * 4U; - } - /* Enable the Rx DMA Stream/Channel */ - if ((hspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hspi->hdmarx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->RxXferCount; - - /* Set DMA source address */ - hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->RXDR; - - /* Set DMA destination address */ - hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hspi->pRxBuffPtr; - - errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmarx); - } - else - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->RXDR, (uint32_t)hspi->pRxBuffPtr, - hspi->RxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - - /* Enable Rx DMA Request */ - SET_BIT(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN); - - /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing - is performed in DMA reception complete callback */ - hspi->hdmatx->XferHalfCpltCallback = NULL; - hspi->hdmatx->XferCpltCallback = NULL; - hspi->hdmatx->XferAbortCallback = NULL; - - /* Set the DMA error callback */ - hspi->hdmatx->XferErrorCallback = SPI_DMAError; - - if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) - { - hspi->TxXferCount = Size; - } - else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) - { - hspi->TxXferCount = Size * 2U; - } - else - { - hspi->TxXferCount = Size * 4U; - } - - /* Enable the Tx DMA Stream/Channel */ - if ((hspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hspi->hdmatx->LinkedListQueue != NULL) - { - /* Set DMA data size */ - hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->TxXferCount; - - /* Set DMA source address */ - hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hspi->pTxBuffPtr; - - /* Set DMA destination address */ - hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->TXDR; - - errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmatx); - } - else - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - } - else - { - errorcode = HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->TXDR, - hspi->TxXferCount); - } - - /* Check status */ - if (errorcode != HAL_OK) - { - /* Update SPI error code */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - hspi->State = HAL_SPI_STATE_READY; - errorcode = HAL_ERROR; - return errorcode; - } - - if ((hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) && (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR)) - { - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, 0UL); - } - else - { - MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); - } - - /* Enable Tx DMA Request */ - SET_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN); - - /* Enable the SPI Error Interrupt Bit */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_OVR | SPI_IT_UDR | SPI_IT_FRE | SPI_IT_MODF)); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - - if (hspi->Init.Mode == SPI_MODE_MASTER) - { - /* Master transfer start */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); - } - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Abort ongoing transfer (blocking mode). - * @param hspi SPI handle. - * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), - * started in Interrupt or DMA mode. - * @note This procedure performs following operations : - * + Disable SPI Interrupts (depending of transfer direction) - * + Disable the DMA transfer in the peripheral register (if enabled) - * + Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * + Set handle State to READY. - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_Abort(SPI_HandleTypeDef *hspi) -{ - HAL_StatusTypeDef errorcode; - - __IO uint32_t count; - - /* Lock the process */ - __HAL_LOCK(hspi); - - /* Set hspi->state to aborting to avoid any interaction */ - hspi->State = HAL_SPI_STATE_ABORT; - - /* Initialized local variable */ - errorcode = HAL_OK; - count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24UL / 1000UL); - - /* If master communication on going, make sure current frame is done before closing the connection */ - if (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)) - { - /* Disable EOT interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_EOT); - do - { - count--; - if (count == 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - break; - } - } - while (HAL_IS_BIT_SET(hspi->Instance->IER, SPI_IT_EOT)); - - /* Request a Suspend transfer */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSUSP); - do - { - count--; - if (count == 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - break; - } - } - while (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)); - - /* Clear SUSP flag */ - __HAL_SPI_CLEAR_SUSPFLAG(hspi); - do - { - count--; - if (count == 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - break; - } - } - while (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_SUSP)); - } - - /* Disable the SPI DMA Tx request if enabled */ - if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN)) - { - if (hspi->hdmatx != NULL) - { - /* Abort the SPI DMA Tx Stream/Channel : use blocking DMA Abort API (no callback) */ - hspi->hdmatx->XferAbortCallback = NULL; - - /* Abort DMA Tx Handle linked to SPI Peripheral */ - if (HAL_DMA_Abort(hspi->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hspi->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - hspi->ErrorCode = HAL_SPI_ERROR_ABORT; - } - } - } - } - - /* Disable the SPI DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN)) - { - if (hspi->hdmarx != NULL) - { - /* Abort the SPI DMA Rx Stream/Channel : use blocking DMA Abort API (no callback) */ - hspi->hdmarx->XferAbortCallback = NULL; - - /* Abort DMA Rx Handle linked to SPI Peripheral */ - if (HAL_DMA_Abort(hspi->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hspi->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - hspi->ErrorCode = HAL_SPI_ERROR_ABORT; - } - } - } - } - - /* Proceed with abort procedure */ - SPI_AbortTransfer(hspi); - - /* Check error during Abort procedure */ - if (HAL_IS_BIT_SET(hspi->ErrorCode, HAL_SPI_ERROR_ABORT)) - { - /* return HAL_Error in case of error during Abort procedure */ - errorcode = HAL_ERROR; - } - else - { - /* Reset errorCode */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - } - - /* Unlock the process */ - __HAL_UNLOCK(hspi); - - /* Restore hspi->state to ready */ - hspi->State = HAL_SPI_STATE_READY; - - return errorcode; -} - -/** - * @brief Abort ongoing transfer (Interrupt mode). - * @param hspi SPI handle. - * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), - * started in Interrupt or DMA mode. - * @note This procedure performs following operations : - * + Disable SPI Interrupts (depending of transfer direction) - * + Disable the DMA transfer in the peripheral register (if enabled) - * + Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * + Set handle State to READY - * + At abort completion, call user abort complete callback. - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPI_Abort_IT(SPI_HandleTypeDef *hspi) -{ - HAL_StatusTypeDef errorcode; - __IO uint32_t count; - uint32_t dma_tx_abort_done = 1UL; - uint32_t dma_rx_abort_done = 1UL; - - /* Set hspi->state to aborting to avoid any interaction */ - hspi->State = HAL_SPI_STATE_ABORT; - - /* Initialized local variable */ - errorcode = HAL_OK; - count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24UL / 1000UL); - - /* If master communication on going, make sure current frame is done before closing the connection */ - if (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)) - { - /* Disable EOT interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_EOT); - do - { - count--; - if (count == 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - break; - } - } - while (HAL_IS_BIT_SET(hspi->Instance->IER, SPI_IT_EOT)); - - /* Request a Suspend transfer */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CSUSP); - do - { - count--; - if (count == 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - break; - } - } - while (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)); - - /* Clear SUSP flag */ - __HAL_SPI_CLEAR_SUSPFLAG(hspi); - do - { - count--; - if (count == 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - break; - } - } - while (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_SUSP)); - } - - /* If DMA Tx and/or DMA Rx Handles are associated to SPI Handle, DMA Abort complete callbacks should be initialized - before any call to DMA Abort functions */ - - if (hspi->hdmatx != NULL) - { - if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN)) - { - /* Set DMA Abort Complete callback if SPI DMA Tx request if enabled */ - hspi->hdmatx->XferAbortCallback = SPI_DMATxAbortCallback; - - dma_tx_abort_done = 0UL; - - /* Abort DMA Tx Handle linked to SPI Peripheral */ - if (HAL_DMA_Abort_IT(hspi->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(hspi->hdmatx) == HAL_DMA_ERROR_NO_XFER) - { - dma_tx_abort_done = 1UL; - hspi->hdmatx->XferAbortCallback = NULL; - } - } - } - else - { - hspi->hdmatx->XferAbortCallback = NULL; - } - } - - if (hspi->hdmarx != NULL) - { - if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN)) - { - /* Set DMA Abort Complete callback if SPI DMA Rx request if enabled */ - hspi->hdmarx->XferAbortCallback = SPI_DMARxAbortCallback; - - dma_rx_abort_done = 0UL; - - /* Abort DMA Rx Handle linked to SPI Peripheral */ - if (HAL_DMA_Abort_IT(hspi->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(hspi->hdmarx) == HAL_DMA_ERROR_NO_XFER) - { - dma_rx_abort_done = 1UL; - hspi->hdmarx->XferAbortCallback = NULL; - } - } - } - else - { - hspi->hdmarx->XferAbortCallback = NULL; - } - } - - /* If no running DMA transfer, finish cleanup and call callbacks */ - if ((dma_tx_abort_done == 1UL) && (dma_rx_abort_done == 1UL)) - { - /* Proceed with abort procedure */ - SPI_AbortTransfer(hspi); - - /* Check error during Abort procedure */ - if (HAL_IS_BIT_SET(hspi->ErrorCode, HAL_SPI_ERROR_ABORT)) - { - /* return HAL_Error in case of error during Abort procedure */ - errorcode = HAL_ERROR; - } - else - { - /* Reset errorCode */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - } - - /* Restore hspi->state to ready */ - hspi->State = HAL_SPI_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->AbortCpltCallback(hspi); -#else - HAL_SPI_AbortCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } - - return errorcode; -} - -/** - * @brief Pause the DMA Transfer. - * This API is not supported, it is maintained for backward compatibility. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. - * @retval HAL_ERROR - */ -HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi) -{ - /* Set error code to not supported */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_NOT_SUPPORTED); - - return HAL_ERROR; -} - -/** - * @brief Resume the DMA Transfer. - * This API is not supported, it is maintained for backward compatibility. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. - * @retval HAL_ERROR - */ -HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi) -{ - /* Set error code to not supported */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_NOT_SUPPORTED); - - return HAL_ERROR; -} - -/** - * @brief Stop the DMA Transfer. - * This API is not supported, it is maintained for backward compatibility. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. - * @retval HAL_ERROR - */ -HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) -{ - /* Set error code to not supported */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_NOT_SUPPORTED); - - return HAL_ERROR; -} - -/** - * @brief Handle SPI interrupt request. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. - * @retval None - */ -void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) -{ - uint32_t itsource = hspi->Instance->IER; - uint32_t itflag = hspi->Instance->SR; - uint32_t trigger = itsource & itflag; - uint32_t cfg1 = hspi->Instance->CFG1; - uint32_t handled = 0UL; - - HAL_SPI_StateTypeDef State = hspi->State; -#if defined (__GNUC__) - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); -#endif /* __GNUC__ */ - - /* SPI in SUSPEND mode ----------------------------------------------------*/ - if (HAL_IS_BIT_SET(itflag, SPI_FLAG_SUSP) && HAL_IS_BIT_SET(itsource, SPI_FLAG_EOT)) - { - /* Clear the Suspend flag */ - __HAL_SPI_CLEAR_SUSPFLAG(hspi); - - /* Suspend on going, Call the Suspend callback */ -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->SuspendCallback(hspi); -#else - HAL_SPI_SuspendCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - return; - } - - /* SPI in mode Transmitter and Receiver ------------------------------------*/ - if (HAL_IS_BIT_CLR(trigger, SPI_FLAG_OVR) && HAL_IS_BIT_CLR(trigger, SPI_FLAG_UDR) && \ - HAL_IS_BIT_SET(trigger, SPI_FLAG_DXP)) - { - hspi->TxISR(hspi); - hspi->RxISR(hspi); - handled = 1UL; - } - - /* SPI in mode Receiver ----------------------------------------------------*/ - if (HAL_IS_BIT_CLR(trigger, SPI_FLAG_OVR) && HAL_IS_BIT_SET(trigger, SPI_FLAG_RXP) && \ - HAL_IS_BIT_CLR(trigger, SPI_FLAG_DXP)) - { - hspi->RxISR(hspi); - handled = 1UL; - } - - /* SPI in mode Transmitter -------------------------------------------------*/ - if (HAL_IS_BIT_CLR(trigger, SPI_FLAG_UDR) && HAL_IS_BIT_SET(trigger, SPI_FLAG_TXP) && \ - HAL_IS_BIT_CLR(trigger, SPI_FLAG_DXP)) - { - hspi->TxISR(hspi); - handled = 1UL; - } - - - if (handled != 0UL) - { - return; - } - - /* SPI End Of Transfer: DMA or IT based transfer */ - if (HAL_IS_BIT_SET(trigger, SPI_FLAG_EOT)) - { - /* Clear EOT/TXTF/SUSP flag */ - __HAL_SPI_CLEAR_EOTFLAG(hspi); - __HAL_SPI_CLEAR_TXTFFLAG(hspi); - __HAL_SPI_CLEAR_SUSPFLAG(hspi); - - /* Disable EOT interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_EOT); - - /* For the IT based receive extra polling maybe required for last packet */ - if (HAL_IS_BIT_CLR(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN)) - { - /* Pooling remaining data */ - while (hspi->RxXferCount != 0UL) - { - /* Receive data in 32 Bit mode */ - if (hspi->Init.DataSize > SPI_DATASIZE_16BIT) - { - *((uint32_t *)hspi->pRxBuffPtr) = *((__IO uint32_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint32_t); - } - /* Receive data in 16 Bit mode */ - else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) - { -#if defined (__GNUC__) - *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hspi->pRxBuffPtr) = *((__IO uint16_t *)&hspi->Instance->RXDR); -#endif /* __GNUC__ */ - hspi->pRxBuffPtr += sizeof(uint16_t); - } - /* Receive data in 8 Bit mode */ - else - { - *((uint8_t *)hspi->pRxBuffPtr) = *((__IO uint8_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint8_t); - } - - hspi->RxXferCount--; - } - } - - /* Call SPI Standard close procedure */ - SPI_CloseTransfer(hspi); - - hspi->State = HAL_SPI_STATE_READY; - if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->ErrorCallback(hspi); -#else - HAL_SPI_ErrorCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - return; - } - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - /* Call appropriate user callback */ - if (State == HAL_SPI_STATE_BUSY_TX_RX) - { - hspi->TxRxCpltCallback(hspi); - } - else if (State == HAL_SPI_STATE_BUSY_RX) - { - hspi->RxCpltCallback(hspi); - } - else if (State == HAL_SPI_STATE_BUSY_TX) - { - hspi->TxCpltCallback(hspi); - } -#else - /* Call appropriate user callback */ - if (State == HAL_SPI_STATE_BUSY_TX_RX) - { - HAL_SPI_TxRxCpltCallback(hspi); - } - else if (State == HAL_SPI_STATE_BUSY_RX) - { - HAL_SPI_RxCpltCallback(hspi); - } - else if (State == HAL_SPI_STATE_BUSY_TX) - { - HAL_SPI_TxCpltCallback(hspi); - } -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - else - { - /* End of the appropriate call */ - } - - return; - } - - /* SPI in Error Treatment --------------------------------------------------*/ - if ((trigger & (SPI_FLAG_MODF | SPI_FLAG_OVR | SPI_FLAG_FRE | SPI_FLAG_UDR)) != 0UL) - { - /* SPI Overrun error interrupt occurred ----------------------------------*/ - if ((trigger & SPI_FLAG_OVR) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR); - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } - - /* SPI Mode Fault error interrupt occurred -------------------------------*/ - if ((trigger & SPI_FLAG_MODF) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_MODF); - __HAL_SPI_CLEAR_MODFFLAG(hspi); - } - - /* SPI Frame error interrupt occurred ------------------------------------*/ - if ((trigger & SPI_FLAG_FRE) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FRE); - __HAL_SPI_CLEAR_FREFLAG(hspi); - } - - /* SPI Underrun error interrupt occurred ------------------------------------*/ - if ((trigger & SPI_FLAG_UDR) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_UDR); - __HAL_SPI_CLEAR_UDRFLAG(hspi); - } - - if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - - /* Disable all interrupts */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_RXP | SPI_IT_TXP | SPI_IT_MODF | - SPI_IT_OVR | SPI_IT_FRE | SPI_IT_UDR)); - - /* Disable the SPI DMA requests if enabled */ - if (HAL_IS_BIT_SET(cfg1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN)) - { - /* Disable the SPI DMA requests */ - CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); - - /* Abort the SPI DMA Rx channel */ - if (hspi->hdmarx != NULL) - { - /* Set the SPI DMA Abort callback : - will lead to call HAL_SPI_ErrorCallback() at end of DMA abort procedure */ - hspi->hdmarx->XferAbortCallback = SPI_DMAAbortOnError; - if (HAL_OK != HAL_DMA_Abort_IT(hspi->hdmarx)) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - } - } - /* Abort the SPI DMA Tx channel */ - if (hspi->hdmatx != NULL) - { - /* Set the SPI DMA Abort callback : - will lead to call HAL_SPI_ErrorCallback() at end of DMA abort procedure */ - hspi->hdmatx->XferAbortCallback = SPI_DMAAbortOnError; - if (HAL_OK != HAL_DMA_Abort_IT(hspi->hdmatx)) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); - } - } - } - else - { - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; - - /* Call user error callback */ -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->ErrorCallback(hspi); -#else - HAL_SPI_ErrorCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } - } - return; - } -} - -/** - * @brief Tx Transfer completed callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxCpltCallback should be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_RxCpltCallback should be implemented in the user file - */ -} - -/** - * @brief Tx and Rx Transfer completed callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxRxCpltCallback should be implemented in the user file - */ -} - -/** - * @brief Tx Half Transfer completed callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxHalfCpltCallback should be implemented in the user file - */ -} - -/** - * @brief Rx Half Transfer completed callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_RxHalfCpltCallback() should be implemented in the user file - */ -} - -/** - * @brief Tx and Rx Half Transfer callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxRxHalfCpltCallback() should be implemented in the user file - */ -} - -/** - * @brief SPI error callback. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -__weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_ErrorCallback should be implemented in the user file - */ - /* NOTE : 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 occurred - */ -} - -/** - * @brief SPI Abort Complete callback. - * @param hspi SPI handle. - * @retval None - */ -__weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief SPI Suspend callback. - * @param hspi SPI handle. - * @retval None - */ -__weak void HAL_SPI_SuspendCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_SuspendCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup SPI_Exported_Functions_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 handle state. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval SPI state - */ -HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi) -{ - /* Return SPI handle state */ - return hspi->State; -} - -/** - * @brief Return the SPI error code. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval SPI error code in bitmap format - */ -uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi) -{ - /* Return SPI ErrorCode */ - return hspi->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup SPI_Private_Functions - * @brief Private functions - * @{ - */ - -/** - * @brief DMA SPI transmit process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hspi->State != HAL_SPI_STATE_ABORT) - { - if (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR) - { -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->TxCpltCallback(hspi); -#else - HAL_SPI_TxCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } - else - { - /* Enable EOT interrupt */ - __HAL_SPI_ENABLE_IT(hspi, SPI_IT_EOT); - } - } -} - -/** - * @brief DMA SPI receive process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hspi->State != HAL_SPI_STATE_ABORT) - { - if (hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) - { -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->RxCpltCallback(hspi); -#else - HAL_SPI_RxCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } - else - { - /* Enable EOT interrupt */ - __HAL_SPI_ENABLE_IT(hspi, SPI_IT_EOT); - } - } -} - -/** - * @brief DMA SPI transmit receive process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hspi->State != HAL_SPI_STATE_ABORT) - { - if ((hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) && - (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR)) - { -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->TxRxCpltCallback(hspi); -#else - HAL_SPI_TxRxCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } - else - { - /* Enable EOT interrupt */ - __HAL_SPI_ENABLE_IT(hspi, SPI_IT_EOT); - } - } -} - -/** - * @brief DMA SPI half transmit process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) /* Derogation MISRAC2012-Rule-8.13 */ -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-8.13 */ - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->TxHalfCpltCallback(hspi); -#else - HAL_SPI_TxHalfCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPI half receive process complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) /* Derogation MISRAC2012-Rule-8.13 */ -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-8.13 */ - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->RxHalfCpltCallback(hspi); -#else - HAL_SPI_RxHalfCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPI half transmit receive process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) /* Derogation MISRAC2012-Rule-8.13 */ -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-8.13 */ - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->TxRxHalfCpltCallback(hspi); -#else - HAL_SPI_TxRxHalfCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPI communication error callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMAError(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* if DMA error is FIFO error ignore it */ - if (HAL_DMA_GetError(hdma) != HAL_DMA_ERROR_NONE) - { - /* Call SPI standard close procedure */ - SPI_CloseTransfer(hspi); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - hspi->State = HAL_SPI_STATE_READY; -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->ErrorCallback(hspi); -#else - HAL_SPI_ErrorCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DMA SPI communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - hspi->RxXferCount = (uint16_t) 0UL; - hspi->TxXferCount = (uint16_t) 0UL; - - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; - -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->ErrorCallback(hspi); -#else - HAL_SPI_ErrorCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPI Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hspi->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (hspi->hdmarx != NULL) - { - if (hspi->hdmarx->XferAbortCallback != NULL) - { - return; - } - } - - /* Call the Abort procedure */ - SPI_AbortTransfer(hspi); - - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->AbortCpltCallback(hspi); -#else - HAL_SPI_AbortCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SPI Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - hspi->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (hspi->hdmatx != NULL) - { - if (hspi->hdmatx->XferAbortCallback != NULL) - { - return; - } - } - - /* Call the Abort procedure */ - SPI_AbortTransfer(hspi); - - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) - hspi->AbortCpltCallback(hspi); -#else - HAL_SPI_AbortCpltCallback(hspi); -#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ -} - -/** - * @brief Manage the receive 8-bit in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_RxISR_8BIT(SPI_HandleTypeDef *hspi) -{ - /* Receive data in 8 Bit mode */ - *((uint8_t *)hspi->pRxBuffPtr) = (*(__IO uint8_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint8_t); - hspi->RxXferCount--; - - /* Disable IT if no more data excepted */ - if (hspi->RxXferCount == 0UL) - { - /* Disable RXP interrupts */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXP); - } -} - - -/** - * @brief Manage the 16-bit receive in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_RxISR_16BIT(SPI_HandleTypeDef *hspi) -{ - /* Receive data in 16 Bit mode */ -#if defined (__GNUC__) - __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); - - *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; -#else - *((uint16_t *)hspi->pRxBuffPtr) = (*(__IO uint16_t *)&hspi->Instance->RXDR); -#endif /* __GNUC__ */ - hspi->pRxBuffPtr += sizeof(uint16_t); - hspi->RxXferCount--; - - /* Disable IT if no more data excepted */ - if (hspi->RxXferCount == 0UL) - { - /* Disable RXP interrupts */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXP); - } -} - - -/** - * @brief Manage the 32-bit receive in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_RxISR_32BIT(SPI_HandleTypeDef *hspi) -{ - /* Receive data in 32 Bit mode */ - *((uint32_t *)hspi->pRxBuffPtr) = (*(__IO uint32_t *)&hspi->Instance->RXDR); - hspi->pRxBuffPtr += sizeof(uint32_t); - hspi->RxXferCount--; - - /* Disable IT if no more data excepted */ - if (hspi->RxXferCount == 0UL) - { - /* Disable RXP interrupts */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXP); - } -} - - -/** - * @brief Handle the data 8-bit transmit in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_TxISR_8BIT(SPI_HandleTypeDef *hspi) -{ - /* Transmit data in 8 Bit mode */ - *(__IO uint8_t *)&hspi->Instance->TXDR = *((const uint8_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint8_t); - hspi->TxXferCount--; - - /* Disable IT if no more data excepted */ - if (hspi->TxXferCount == 0UL) - { - /* Disable TXP interrupts */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXP); - } -} - -/** - * @brief Handle the data 16-bit transmit in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_TxISR_16BIT(SPI_HandleTypeDef *hspi) -{ - /* Transmit data in 16 Bit mode */ -#if defined (__GNUC__) - __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); - - *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); -#else - *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); -#endif /* __GNUC__ */ - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount--; - - /* Disable IT if no more data excepted */ - if (hspi->TxXferCount == 0UL) - { - /* Disable TXP interrupts */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXP); - } -} - -/** - * @brief Handle the data 32-bit transmit in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_TxISR_32BIT(SPI_HandleTypeDef *hspi) -{ - /* Transmit data in 32 Bit mode */ - *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint32_t); - hspi->TxXferCount--; - - /* Disable IT if no more data excepted */ - if (hspi->TxXferCount == 0UL) - { - /* Disable TXP interrupts */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXP); - } -} - -/** - * @brief Abort Transfer and clear flags. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_AbortTransfer(SPI_HandleTypeDef *hspi) -{ - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - - /* Disable ITs */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_TXP | SPI_IT_RXP | SPI_IT_DXP | SPI_IT_UDR | SPI_IT_OVR | \ - SPI_IT_FRE | SPI_IT_MODF)); - - /* Clear the Status flags in the SR register */ - __HAL_SPI_CLEAR_EOTFLAG(hspi); - __HAL_SPI_CLEAR_TXTFFLAG(hspi); - - /* Disable Tx DMA Request */ - CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); - - /* Clear the Error flags in the SR register */ - __HAL_SPI_CLEAR_OVRFLAG(hspi); - __HAL_SPI_CLEAR_UDRFLAG(hspi); - __HAL_SPI_CLEAR_FREFLAG(hspi); - __HAL_SPI_CLEAR_MODFFLAG(hspi); - __HAL_SPI_CLEAR_SUSPFLAG(hspi); - -#if (USE_SPI_CRC != 0U) - __HAL_SPI_CLEAR_CRCERRFLAG(hspi); -#endif /* USE_SPI_CRC */ - - hspi->TxXferCount = (uint16_t)0UL; - hspi->RxXferCount = (uint16_t)0UL; -} - - -/** - * @brief Close Transfer and clear flags. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval HAL_ERROR: if any error detected - * HAL_OK: if nothing detected - */ -static void SPI_CloseTransfer(SPI_HandleTypeDef *hspi) -{ - uint32_t itflag = hspi->Instance->SR; - - __HAL_SPI_CLEAR_EOTFLAG(hspi); - __HAL_SPI_CLEAR_TXTFFLAG(hspi); - - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - - /* Disable ITs */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_TXP | SPI_IT_RXP | SPI_IT_DXP | SPI_IT_UDR | SPI_IT_OVR | \ - SPI_IT_FRE | SPI_IT_MODF)); - - /* Disable Tx DMA Request */ - CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); - - /* Report UnderRun error for non RX Only communication */ - if (hspi->State != HAL_SPI_STATE_BUSY_RX) - { - if ((itflag & SPI_FLAG_UDR) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_UDR); - __HAL_SPI_CLEAR_UDRFLAG(hspi); - } - } - - /* Report OverRun error for non TX Only communication */ - if (hspi->State != HAL_SPI_STATE_BUSY_TX) - { - if ((itflag & SPI_FLAG_OVR) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR); - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } - -#if (USE_SPI_CRC != 0UL) - /* Check if CRC error occurred */ - if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - if ((itflag & SPI_FLAG_CRCERR) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - __HAL_SPI_CLEAR_CRCERRFLAG(hspi); - } - } -#endif /* USE_SPI_CRC */ - } - - /* SPI Mode Fault error interrupt occurred -------------------------------*/ - if ((itflag & SPI_FLAG_MODF) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_MODF); - __HAL_SPI_CLEAR_MODFFLAG(hspi); - } - - /* SPI Frame error interrupt occurred ------------------------------------*/ - if ((itflag & SPI_FLAG_FRE) != 0UL) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FRE); - __HAL_SPI_CLEAR_FREFLAG(hspi); - } - - hspi->TxXferCount = (uint16_t)0UL; - hspi->RxXferCount = (uint16_t)0UL; -} - -/** - * @brief Handle SPI Communication Timeout. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param Flag: SPI flag to check - * @param Status: flag state to check - * @param Timeout: Timeout duration - * @param Tickstart: Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(const SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, - uint32_t Timeout, uint32_t Tickstart) -{ - /* Wait until flag is set */ - while ((__HAL_SPI_GET_FLAG(hspi, Flag) ? SET : RESET) == Status) - { - /* Check for the Timeout */ - if ((((HAL_GetTick() - Tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) - { - return HAL_TIMEOUT; - } - } - return HAL_OK; -} - -/** - * @brief Compute configured packet size from fifo perspective. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval Packet size occupied in the fifo - */ -static uint32_t SPI_GetPacketSize(const SPI_HandleTypeDef *hspi) -{ - uint32_t fifo_threashold = (hspi->Init.FifoThreshold >> SPI_CFG1_FTHLV_Pos) + 1UL; - uint32_t data_size = (hspi->Init.DataSize >> SPI_CFG1_DSIZE_Pos) + 1UL; - - /* Convert data size to Byte */ - data_size = (data_size + 7UL) / 8UL; - - return data_size * fifo_threashold; -} - -/** - * @} - */ - -#endif /* HAL_SPI_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_spi.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 implementing 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 or DMA 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/Channel + (+++) Enable the DMAx clock + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx or Rx Stream/Channel + (+++) Associate the initialized 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/Channel + + (#) Program the Mode, BidirectionalMode , 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 customized HAL_SPI_MspInit() API. + [..] + Callback registration: + + (#) The compilation flag USE_HAL_SPI_REGISTER_CALLBACKS when set to 1UL + allows the user to configure dynamically the driver callbacks. + Use Functions HAL_SPI_RegisterCallback() to register an interrupt callback. + + Function HAL_SPI_RegisterCallback() allows to register following callbacks: + (+) TxCpltCallback : SPI Tx Completed callback + (+) RxCpltCallback : SPI Rx Completed callback + (+) TxRxCpltCallback : SPI TxRx Completed callback + (+) TxHalfCpltCallback : SPI Tx Half Completed callback + (+) RxHalfCpltCallback : SPI Rx Half Completed callback + (+) TxRxHalfCpltCallback : SPI TxRx Half Completed callback + (+) ErrorCallback : SPI Error callback + (+) AbortCpltCallback : SPI Abort callback + (+) SuspendCallback : SPI Suspend callback + (+) MspInitCallback : SPI Msp Init callback + (+) MspDeInitCallback : SPI Msp DeInit callback + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + + (#) Use function HAL_SPI_UnRegisterCallback to reset a callback to the default + weak function. + HAL_SPI_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxCpltCallback : SPI Tx Completed callback + (+) RxCpltCallback : SPI Rx Completed callback + (+) TxRxCpltCallback : SPI TxRx Completed callback + (+) TxHalfCpltCallback : SPI Tx Half Completed callback + (+) RxHalfCpltCallback : SPI Rx Half Completed callback + (+) TxRxHalfCpltCallback : SPI TxRx Half Completed callback + (+) ErrorCallback : SPI Error callback + (+) AbortCpltCallback : SPI Abort callback + (+) SuspendCallback : SPI Suspend callback + (+) MspInitCallback : SPI Msp Init callback + (+) MspDeInitCallback : SPI Msp DeInit callback + + By default, after the HAL_SPI_Init() and when the state is HAL_SPI_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_SPI_MasterTxCpltCallback(), HAL_SPI_MasterRxCpltCallback(). + Exception done for MspInit and MspDeInit functions that are + reset to the legacy weak functions in the HAL_SPI_Init()/ HAL_SPI_DeInit() only when + these callbacks are null (not registered beforehand). + If MspInit or MspDeInit are not null, the HAL_SPI_Init()/ HAL_SPI_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. + + Callbacks can be registered/unregistered in HAL_SPI_STATE_READY state only. + Exception done MspInit/MspDeInit functions that can be registered/unregistered + in HAL_SPI_STATE_READY or HAL_SPI_STATE_RESET state, + thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. + Then, the user first registers the MspInit/MspDeInit user callbacks + using HAL_SPI_RegisterCallback() before calling HAL_SPI_DeInit() + or HAL_SPI_Init() function. + + When The compilation define USE_HAL_PPP_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + SuspendCallback restriction: + SuspendCallback is called only when MasterReceiverAutoSusp is enabled and + EOT interrupt is activated. SuspendCallback is used in relation with functions + HAL_SPI_Transmit_IT, HAL_SPI_Receive_IT and HAL_SPI_TransmitReceive_IT. + + [..] + Circular mode restriction: + (+) The DMA circular mode cannot be used when the SPI is configured in these modes: + (++) Master 2Lines RxOnly + (++) Master 1Line Rx + (+) The CRC feature is not managed when the DMA circular mode is enabled + (+) The functions HAL_SPI_DMAPause()/ HAL_SPI_DMAResume() are not supported. Return always + HAL_ERROR with ErrorCode set to HAL_SPI_ERROR_NOT_SUPPORTED. + Those functions are maintained for backward compatibility reasons. + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SPI SPI + * @brief SPI HAL module driver + * @{ + */ +#ifdef HAL_SPI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/** @defgroup SPI_Private_Constants SPI Private Constants + * @{ + */ +#define SPI_DEFAULT_TIMEOUT 100UL +#define MAX_FIFO_LENGTH 16UL +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup SPI_Private_Functions SPI Private Functions + * @{ + */ +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAError(DMA_HandleTypeDef *hdma); +static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(const SPI_HandleTypeDef *hspi, uint32_t Flag, + FlagStatus FlagStatus, uint32_t Timeout, uint32_t Tickstart); +static void SPI_TxISR_8BIT(SPI_HandleTypeDef *hspi); +static void SPI_TxISR_16BIT(SPI_HandleTypeDef *hspi); +static void SPI_TxISR_32BIT(SPI_HandleTypeDef *hspi); +static void SPI_RxISR_8BIT(SPI_HandleTypeDef *hspi); +static void SPI_RxISR_16BIT(SPI_HandleTypeDef *hspi); +static void SPI_RxISR_32BIT(SPI_HandleTypeDef *hspi); +static void SPI_AbortTransfer(SPI_HandleTypeDef *hspi); +static void SPI_CloseTransfer(SPI_HandleTypeDef *hspi); +static uint32_t SPI_GetPacketSize(const SPI_HandleTypeDef *hspi); + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SPI_Exported_Functions SPI Exported Functions + * @{ + */ + +/** @defgroup SPI_Exported_Functions_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 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 + (++) CRC Length, used only with Data8 and Data16 + (++) FIFO reception threshold + (++) FIFO transmission threshold + + (+) Call the function HAL_SPI_DeInit() to restore the default configuration + of the selected SPIx peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the SPI according to the specified parameters + * in the SPI_InitTypeDef and initialize the associated handle. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) +{ + uint32_t crc_length; + uint32_t packet_length; + + /* Check the SPI handle allocation */ + if (hspi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); + assert_param(IS_SPI_MODE(hspi->Init.Mode)); + assert_param(IS_SPI_DIRECTION(hspi->Init.Direction)); + if (IS_SPI_LIMITED_INSTANCE(hspi->Instance)) + { + assert_param(IS_SPI_LIMITED_DATASIZE(hspi->Init.DataSize)); + assert_param(IS_SPI_LIMITED_FIFOTHRESHOLD(hspi->Init.FifoThreshold)); + } + else + { + assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); + assert_param(IS_SPI_FIFOTHRESHOLD(hspi->Init.FifoThreshold)); + } + assert_param(IS_SPI_NSS(hspi->Init.NSS)); + assert_param(IS_SPI_NSSP(hspi->Init.NSSPMode)); + 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)); + if (hspi->Init.TIMode == SPI_TIMODE_DISABLE) + { + assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); + assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); + } +#if (USE_SPI_CRC != 0UL) + assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + if (IS_SPI_LIMITED_INSTANCE(hspi->Instance)) + { + assert_param(IS_SPI_LIMITED_CRC_LENGTH(hspi->Init.CRCLength)); + } + else + { + assert_param(IS_SPI_CRC_LENGTH(hspi->Init.CRCLength)); + } + assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); + assert_param(IS_SPI_CRC_INITIALIZATION_PATTERN(hspi->Init.TxCRCInitializationPattern)); + assert_param(IS_SPI_CRC_INITIALIZATION_PATTERN(hspi->Init.RxCRCInitializationPattern)); + } +#else + hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; +#endif /* USE_SPI_CRC */ + + assert_param(IS_SPI_RDY_MASTER_MANAGEMENT(hspi->Init.ReadyMasterManagement)); + assert_param(IS_SPI_RDY_POLARITY(hspi->Init.ReadyPolarity)); + assert_param(IS_SPI_MASTER_RX_AUTOSUSP(hspi->Init.MasterReceiverAutoSusp)); + + /* Verify that the SPI instance supports Data Size higher than 16bits */ + if ((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (hspi->Init.DataSize > SPI_DATASIZE_16BIT)) + { + return HAL_ERROR; + } + + /* Verify that the SPI instance supports requested data packing */ + packet_length = SPI_GetPacketSize(hspi); + if (((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (packet_length > SPI_LOWEND_FIFO_SIZE)) || + ((IS_SPI_FULL_INSTANCE(hspi->Instance)) && (packet_length > SPI_HIGHEND_FIFO_SIZE))) + { + return HAL_ERROR; + } +#if (USE_SPI_CRC != 0UL) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Verify that the SPI instance supports CRC Length higher than 16bits */ + if ((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (hspi->Init.CRCLength > SPI_CRC_LENGTH_16BIT)) + { + return HAL_ERROR; + } + + /* Align the CRC Length on the data size */ + if (hspi->Init.CRCLength == SPI_CRC_LENGTH_DATASIZE) + { + crc_length = (hspi->Init.DataSize >> SPI_CFG1_DSIZE_Pos) << SPI_CFG1_CRCSIZE_Pos; + } + else + { + crc_length = hspi->Init.CRCLength; + } + + /* Verify that the CRC Length is higher than DataSize */ + if ((hspi->Init.DataSize >> SPI_CFG1_DSIZE_Pos) > (crc_length >> SPI_CFG1_CRCSIZE_Pos)) + { + return HAL_ERROR; + } + } + else + { + crc_length = hspi->Init.DataSize << SPI_CFG1_CRCSIZE_Pos; + } +#endif /* USE_SPI_CRC */ + + if (hspi->State == HAL_SPI_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hspi->Lock = HAL_UNLOCKED; + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + /* Init the SPI Callback settings */ + hspi->TxCpltCallback = HAL_SPI_TxCpltCallback; /* Legacy weak TxCpltCallback */ + hspi->RxCpltCallback = HAL_SPI_RxCpltCallback; /* Legacy weak RxCpltCallback */ + hspi->TxRxCpltCallback = HAL_SPI_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + hspi->TxHalfCpltCallback = HAL_SPI_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + hspi->RxHalfCpltCallback = HAL_SPI_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + hspi->TxRxHalfCpltCallback = HAL_SPI_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + hspi->ErrorCallback = HAL_SPI_ErrorCallback; /* Legacy weak ErrorCallback */ + hspi->AbortCpltCallback = HAL_SPI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + hspi->SuspendCallback = HAL_SPI_SuspendCallback; /* Legacy weak SuspendCallback */ + + if (hspi->MspInitCallback == NULL) + { + hspi->MspInitCallback = HAL_SPI_MspInit; /* Legacy weak MspInit */ + } + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + hspi->MspInitCallback(hspi); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_SPI_MspInit(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Disable the selected SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + +#if (USE_SPI_CRC == 0) + /* Keep the default value of CRCSIZE in case of CRC is not used */ + crc_length = hspi->Instance->CFG1 & SPI_CFG1_CRCSIZE; +#endif /* USE_SPI_CRC */ + + /*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/ + /* Configure : SPI Mode, Communication Mode, Clock polarity and phase, NSS management, + Communication speed, First bit, CRC calculation state, CRC Length */ + + /* SPIx NSS Software Management Configuration */ + if ((hspi->Init.NSS == SPI_NSS_SOFT) && (((hspi->Init.Mode == SPI_MODE_MASTER) && \ + (hspi->Init.NSSPolarity == SPI_NSS_POLARITY_LOW)) || \ + ((hspi->Init.Mode == SPI_MODE_SLAVE) && \ + (hspi->Init.NSSPolarity == SPI_NSS_POLARITY_HIGH)))) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_SSI); + } + + /* SPIx Master Rx Auto Suspend Configuration */ + if (((hspi->Init.Mode & SPI_MODE_MASTER) == SPI_MODE_MASTER) && (hspi->Init.DataSize >= SPI_DATASIZE_8BIT)) + { + MODIFY_REG(hspi->Instance->CR1, SPI_CR1_MASRX, hspi->Init.MasterReceiverAutoSusp); + } + else + { + CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_MASRX); + } + + /* SPIx CFG1 Configuration */ + WRITE_REG(hspi->Instance->CFG1, (hspi->Init.BaudRatePrescaler | hspi->Init.CRCCalculation | crc_length | + hspi->Init.FifoThreshold | hspi->Init.DataSize)); + + /* SPIx CFG2 Configuration */ + WRITE_REG(hspi->Instance->CFG2, (hspi->Init.NSSPMode | hspi->Init.TIMode | + hspi->Init.NSSPolarity | hspi->Init.NSS | + hspi->Init.CLKPolarity | hspi->Init.CLKPhase | + hspi->Init.FirstBit | hspi->Init.Mode | + hspi->Init.MasterInterDataIdleness | hspi->Init.Direction | + hspi->Init.MasterSSIdleness | hspi->Init.IOSwap | + hspi->Init.ReadyMasterManagement | hspi->Init.ReadyPolarity)); + +#if (USE_SPI_CRC != 0UL) + /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ + /* Configure : CRC Polynomial */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Initialize TXCRC Pattern Initial Value */ + if (hspi->Init.TxCRCInitializationPattern == SPI_CRC_INITIALIZATION_ALL_ONE_PATTERN) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_TCRCINI); + } + else + { + CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_TCRCINI); + } + + /* Initialize RXCRC Pattern Initial Value */ + if (hspi->Init.RxCRCInitializationPattern == SPI_CRC_INITIALIZATION_ALL_ONE_PATTERN) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_RCRCINI); + } + else + { + CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_RCRCINI); + } + + /* Enable 33/17 bits CRC computation */ + if (((IS_SPI_LIMITED_INSTANCE(hspi->Instance)) && (crc_length == SPI_CRC_LENGTH_16BIT)) || + ((IS_SPI_FULL_INSTANCE(hspi->Instance)) && (crc_length == SPI_CRC_LENGTH_32BIT))) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRC33_17); + } + else + { + CLEAR_BIT(hspi->Instance->CR1, SPI_CR1_CRC33_17); + } + + /* Write CRC polynomial in SPI Register */ + WRITE_REG(hspi->Instance->CRCPOLY, hspi->Init.CRCPolynomial); + } +#endif /* USE_SPI_CRC */ + + /* Insure that Underrun configuration is managed only by Salve */ + if (hspi->Init.Mode == SPI_MODE_SLAVE) + { +#if (USE_SPI_CRC != 0UL) + MODIFY_REG(hspi->Instance->CFG1, SPI_CFG1_UDRCFG, SPI_CFG1_UDRCFG); +#endif /* USE_SPI_CRC */ + } + +#if defined(SPI_I2SCFGR_I2SMOD) + /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ + CLEAR_BIT(hspi->Instance->I2SCFGR, SPI_I2SCFGR_I2SMOD); +#endif /* SPI_I2SCFGR_I2SMOD */ + + /* Insure that AFCNTR is managed only by Master */ + if ((hspi->Init.Mode & SPI_MODE_MASTER) == SPI_MODE_MASTER) + { + /* Alternate function GPIOs control */ + MODIFY_REG(hspi->Instance->CFG2, SPI_CFG2_AFCNTR, (hspi->Init.MasterKeepIOState)); + } + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State = HAL_SPI_STATE_READY; + + return HAL_OK; +} + +/** + * @brief De-Initialize the SPI peripheral. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if (hspi == NULL) + { + return HAL_ERROR; + } + + /* Check SPI Instance parameter */ + assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Disable the SPI Peripheral Clock */ + __HAL_SPI_DISABLE(hspi); + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + if (hspi->MspDeInitCallback == NULL) + { + hspi->MspDeInitCallback = HAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ + } + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + hspi->MspDeInitCallback(hspi); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_SPI_MspDeInit(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State = HAL_SPI_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hspi); + + return HAL_OK; +} + +/** + * @brief Initialize the SPI MSP. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_MspInit should be implemented in the user file + */ +} + +/** + * @brief De-Initialize the SPI MSP. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_MspDeInit should be implemented in the user file + */ +} + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) +/** + * @brief Register a User SPI Callback + * To be used instead of the weak predefined callback + * @param hspi Pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI. + * @param CallbackID ID of the callback to be registered + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_RegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_CallbackIDTypeDef CallbackID, + pSPI_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hspi->ErrorCode |= HAL_SPI_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + /* Lock the process */ + __HAL_LOCK(hspi); + + if (HAL_SPI_STATE_READY == hspi->State) + { + switch (CallbackID) + { + case HAL_SPI_TX_COMPLETE_CB_ID : + hspi->TxCpltCallback = pCallback; + break; + + case HAL_SPI_RX_COMPLETE_CB_ID : + hspi->RxCpltCallback = pCallback; + break; + + case HAL_SPI_TX_RX_COMPLETE_CB_ID : + hspi->TxRxCpltCallback = pCallback; + break; + + case HAL_SPI_TX_HALF_COMPLETE_CB_ID : + hspi->TxHalfCpltCallback = pCallback; + break; + + case HAL_SPI_RX_HALF_COMPLETE_CB_ID : + hspi->RxHalfCpltCallback = pCallback; + break; + + case HAL_SPI_TX_RX_HALF_COMPLETE_CB_ID : + hspi->TxRxHalfCpltCallback = pCallback; + break; + + case HAL_SPI_ERROR_CB_ID : + hspi->ErrorCallback = pCallback; + break; + + case HAL_SPI_ABORT_CB_ID : + hspi->AbortCpltCallback = pCallback; + break; + + case HAL_SPI_SUSPEND_CB_ID : + hspi->SuspendCallback = pCallback; + break; + + case HAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = pCallback; + break; + + case HAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SPI_STATE_RESET == hspi->State) + { + switch (CallbackID) + { + case HAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = pCallback; + break; + + case HAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hspi); + return status; +} + +/** + * @brief Unregister an SPI Callback + * SPI callback is redirected to the weak predefined callback + * @param hspi Pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI. + * @param CallbackID ID of the callback to be unregistered + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_UnRegisterCallback(SPI_HandleTypeDef *hspi, HAL_SPI_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Lock the process */ + __HAL_LOCK(hspi); + + if (HAL_SPI_STATE_READY == hspi->State) + { + switch (CallbackID) + { + case HAL_SPI_TX_COMPLETE_CB_ID : + hspi->TxCpltCallback = HAL_SPI_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_SPI_RX_COMPLETE_CB_ID : + hspi->RxCpltCallback = HAL_SPI_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_SPI_TX_RX_COMPLETE_CB_ID : + hspi->TxRxCpltCallback = HAL_SPI_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + break; + + case HAL_SPI_TX_HALF_COMPLETE_CB_ID : + hspi->TxHalfCpltCallback = HAL_SPI_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case HAL_SPI_RX_HALF_COMPLETE_CB_ID : + hspi->RxHalfCpltCallback = HAL_SPI_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case HAL_SPI_TX_RX_HALF_COMPLETE_CB_ID : + hspi->TxRxHalfCpltCallback = HAL_SPI_TxRxHalfCpltCallback; /* Legacy weak TxRxHalfCpltCallback */ + break; + + case HAL_SPI_ERROR_CB_ID : + hspi->ErrorCallback = HAL_SPI_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_SPI_ABORT_CB_ID : + hspi->AbortCpltCallback = HAL_SPI_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_SPI_SUSPEND_CB_ID : + hspi->SuspendCallback = HAL_SPI_SuspendCallback; /* Legacy weak SuspendCallback */ + break; + + case HAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = HAL_SPI_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = HAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_SPI_STATE_RESET == hspi->State) + { + switch (CallbackID) + { + case HAL_SPI_MSPINIT_CB_ID : + hspi->MspInitCallback = HAL_SPI_MspInit; /* Legacy weak MspInit */ + break; + + case HAL_SPI_MSPDEINIT_CB_ID : + hspi->MspDeInitCallback = HAL_SPI_MspDeInit; /* Legacy weak MspDeInit */ + break; + + default : + /* Update the error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_INVALID_CALLBACK); + + /* Return error status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hspi); + return status; +} +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup SPI_Exported_Functions_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 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. + (##) No-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 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 respectively at the end of the transmit or Receive process + The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected + + (#) APIs provided for these 2 transfer modes (Blocking mode or Non blocking mode using either Interrupt or DMA) + exist for 1Line (simplex) and 2Lines (full duplex) modes. + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @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, const uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); +#endif /* __GNUC__ */ + + uint32_t tickstart; + HAL_StatusTypeDef errorcode = HAL_OK; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_TXONLY(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (const uint8_t *)pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = (uint16_t) 0UL; + hspi->RxXferCount = (uint16_t) 0UL; + hspi->TxISR = NULL; + hspi->RxISR = NULL; + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_TX(hspi); + } + else + { + SPI_2LINES_TX(hspi); + } + + /* Set the number of data at current transfer */ + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Transmit data in 32 Bit mode */ + if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) + { + /* Transmit data in 32 Bit mode */ + while (hspi->TxXferCount > 0UL) + { + /* Wait until TXP flag is set to send data */ + if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) + { + *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint32_t); + hspi->TxXferCount--; + } + else + { + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + /* Transmit data in 16 Bit mode */ + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + /* Transmit data in 16 Bit mode */ + while (hspi->TxXferCount > 0UL) + { + /* Wait until TXP flag is set to send data */ + if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) + { + if ((hspi->TxXferCount > 1UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_01DATA)) + { + *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint32_t); + hspi->TxXferCount -= (uint16_t)2UL; + } + else + { +#if defined (__GNUC__) + *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); +#else + *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); +#endif /* __GNUC__ */ + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + } + } + else + { + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + /* Transmit data in 8 Bit mode */ + else + { + while (hspi->TxXferCount > 0UL) + { + /* Wait until TXP flag is set to send data */ + if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) + { + if ((hspi->TxXferCount > 3UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_03DATA)) + { + *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint32_t); + hspi->TxXferCount -= (uint16_t)4UL; + } + else if ((hspi->TxXferCount > 1UL) && (hspi->Init.FifoThreshold > SPI_FIFO_THRESHOLD_01DATA)) + { +#if defined (__GNUC__) + *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); +#else + *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); +#endif /* __GNUC__ */ + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount -= (uint16_t)2UL; + } + else + { + *((__IO uint8_t *)&hspi->Instance->TXDR) = *((const uint8_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + } + } + else + { + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + + /* Wait for Tx (and CRC) data to be sent */ + if (SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_EOT, RESET, Timeout, tickstart) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } + + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + return errorcode; +} + +/** + * @brief Receive an amount of data in blocking mode. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData : pointer to data buffer + * @param Size : amount of data to be received + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tickstart; + HAL_StatusTypeDef errorcode = HAL_OK; +#if defined (__GNUC__) + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); +#endif /* __GNUC__ */ + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_RXONLY(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = (uint16_t) 0UL; + hspi->TxXferCount = (uint16_t) 0UL; + hspi->RxISR = NULL; + hspi->TxISR = NULL; + + /* Configure communication direction: 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_RX(hspi); + } + else + { + SPI_2LINES_RX(hspi); + } + + /* Set the number of data at current transfer */ + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Receive data in 32 Bit mode */ + if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) + { + /* Transfer loop */ + while (hspi->RxXferCount > 0UL) + { + /* Check the RXWNE/EOT flag */ + if ((hspi->Instance->SR & (SPI_FLAG_RXWNE | SPI_FLAG_EOT)) != 0UL) + { + *((uint32_t *)hspi->pRxBuffPtr) = *((__IO uint32_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint32_t); + hspi->RxXferCount--; + } + else + { + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + /* Receive data in 16 Bit mode */ + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + /* Transfer loop */ + while (hspi->RxXferCount > 0UL) + { + /* Check the RXP flag */ + if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) + { +#if defined (__GNUC__) + *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hspi->pRxBuffPtr) = *((__IO uint16_t *)&hspi->Instance->RXDR); +#endif /* __GNUC__ */ + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + } + else + { + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + /* Receive data in 8 Bit mode */ + else + { + /* Transfer loop */ + while (hspi->RxXferCount > 0UL) + { + /* Check the RXP flag */ + if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) + { + *((uint8_t *)hspi->pRxBuffPtr) = *((__IO uint8_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint8_t); + hspi->RxXferCount--; + } + else + { + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + } + +#if (USE_SPI_CRC != 0UL) + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait for crc data to be received */ + if (SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_EOT, RESET, Timeout, tickstart) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } + } +#endif /* USE_SPI_CRC */ + + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + return errorcode; +} + +/** + * @brief Transmit and Receive an amount of data in blocking mode. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer + * @param Size : amount of data to be sent and received + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) +{ + HAL_StatusTypeDef errorcode = HAL_OK; +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); +#endif /* __GNUC__ */ + + uint32_t tickstart; + uint16_t initial_TxXferCount; + uint16_t initial_RxXferCount; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + /* Init tickstart for timeout management*/ + tickstart = HAL_GetTick(); + + initial_TxXferCount = Size; + initial_RxXferCount = Size; + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pRxData; + hspi->RxXferCount = Size; + hspi->RxXferSize = Size; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; + hspi->TxXferCount = Size; + hspi->TxXferSize = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = NULL; + hspi->TxISR = NULL; + + /* Set Full-Duplex mode */ + SPI_2LINES(hspi); + + /* Set the number of data at current transfer */ + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + + __HAL_SPI_ENABLE(hspi); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Transmit and Receive data in 32 Bit mode */ + if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) + { + while ((initial_TxXferCount > 0UL) || (initial_RxXferCount > 0UL)) + { + /* Check TXP flag */ + if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) && (initial_TxXferCount > 0UL)) + { + *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint32_t); + hspi->TxXferCount --; + initial_TxXferCount = hspi->TxXferCount; + } + + /* Check RXWNE/EOT flag */ + if (((hspi->Instance->SR & (SPI_FLAG_RXWNE | SPI_FLAG_EOT)) != 0UL) && (initial_RxXferCount > 0UL)) + { + *((uint32_t *)hspi->pRxBuffPtr) = *((__IO uint32_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint32_t); + hspi->RxXferCount --; + initial_RxXferCount = hspi->RxXferCount; + } + + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + /* Transmit and Receive data in 16 Bit mode */ + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + while ((initial_TxXferCount > 0UL) || (initial_RxXferCount > 0UL)) + { + /* Check the TXP flag */ + if (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP) && (initial_TxXferCount > 0UL)) + { +#if defined (__GNUC__) + *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); +#else + *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); +#endif /* __GNUC__ */ + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + initial_TxXferCount = hspi->TxXferCount; + } + + /* Check the RXP flag */ + if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) && (initial_RxXferCount > 0UL)) + { +#if defined (__GNUC__) + *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hspi->pRxBuffPtr) = *((__IO uint16_t *)&hspi->Instance->RXDR); +#endif /* __GNUC__ */ + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + initial_RxXferCount = hspi->RxXferCount; + } + + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + /* Transmit and Receive data in 8 Bit mode */ + else + { + while ((initial_TxXferCount > 0UL) || (initial_RxXferCount > 0UL)) + { + /* Check the TXP flag */ + if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) && (initial_TxXferCount > 0UL)) + { + *((__IO uint8_t *)&hspi->Instance->TXDR) = *((const uint8_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + initial_TxXferCount = hspi->TxXferCount; + } + + /* Check the RXP flag */ + if ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXP)) && (initial_RxXferCount > 0UL)) + { + *((uint8_t *)hspi->pRxBuffPtr) = *((__IO uint8_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint8_t); + hspi->RxXferCount--; + initial_RxXferCount = hspi->RxXferCount; + } + + /* Timeout management */ + if ((((HAL_GetTick() - tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_TIMEOUT); + hspi->State = HAL_SPI_STATE_READY; + return HAL_TIMEOUT; + } + } + } + + /* Wait for Tx/Rx (and CRC) data to be sent/received */ + if (SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_EOT, RESET, Timeout, tickstart) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } + + /* Call standard close procedure with error check */ + SPI_CloseTransfer(hspi); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + return errorcode; +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @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, const uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef errorcode = HAL_OK; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_TXONLY(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + if ((pData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (const uint8_t *)pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = (uint16_t) 0UL; + hspi->RxXferCount = (uint16_t) 0UL; + hspi->RxISR = NULL; + + /* Set the function for IT treatment */ + if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) + { + hspi->TxISR = SPI_TxISR_32BIT; + } + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->TxISR = SPI_TxISR_16BIT; + } + else + { + hspi->TxISR = SPI_TxISR_8BIT; + } + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_TX(hspi); + } + else + { + SPI_2LINES_TX(hspi); + } + + /* Set the number of data at current transfer */ + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + /* Enable EOT, TXP, FRE, MODF and UDR interrupts */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_TXP | SPI_IT_UDR | SPI_IT_FRE | SPI_IT_MODF)); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @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) +{ + HAL_StatusTypeDef errorcode = HAL_OK; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_RXONLY(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = (uint16_t) 0UL; + hspi->TxXferCount = (uint16_t) 0UL; + hspi->TxISR = NULL; + + /* Set the function for IT treatment */ + if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) + { + hspi->RxISR = SPI_RxISR_32BIT; + } + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->RxISR = SPI_RxISR_16BIT; + } + else + { + hspi->RxISR = SPI_RxISR_8BIT; + } + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_RX(hspi); + } + else + { + SPI_2LINES_RX(hspi); + } + + /* Note : The SPI must be enabled after unlocking current process + to avoid the risk of SPI interrupt handle execution before current + process unlock */ + + /* Set the number of data at current transfer */ + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + /* Enable EOT, RXP, OVR, FRE and MODF interrupts */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_RXP | SPI_IT_OVR | SPI_IT_FRE | SPI_IT_MODF)); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit and Receive an amount of data in non-blocking mode with Interrupt. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer + * @param Size : amount of data to be sent and received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + HAL_StatusTypeDef errorcode = HAL_OK; + uint32_t tmp_TxXferCount; + +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); +#endif /* __GNUC__ */ + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (const uint8_t *)pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = (uint8_t *)pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + tmp_TxXferCount = hspi->TxXferCount; + + /* Set the function for IT treatment */ + if ((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (IS_SPI_FULL_INSTANCE(hspi->Instance))) + { + hspi->TxISR = SPI_TxISR_32BIT; + hspi->RxISR = SPI_RxISR_32BIT; + } + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->RxISR = SPI_RxISR_16BIT; + hspi->TxISR = SPI_TxISR_16BIT; + } + else + { + hspi->RxISR = SPI_RxISR_8BIT; + hspi->TxISR = SPI_TxISR_8BIT; + } + + /* Set Full-Duplex mode */ + SPI_2LINES(hspi); + + /* Set the number of data at current transfer */ + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + /* Fill in the TxFIFO */ + while ((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXP)) && (tmp_TxXferCount != 0UL)) + { + /* Transmit data in 32 Bit mode */ + if (hspi->Init.DataSize > SPI_DATASIZE_16BIT) + { + *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint32_t); + hspi->TxXferCount--; + tmp_TxXferCount = hspi->TxXferCount; + } + /* Transmit data in 16 Bit mode */ + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { +#if defined (__GNUC__) + *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); +#else + *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); +#endif /* __GNUC__ */ + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + tmp_TxXferCount = hspi->TxXferCount; + } + /* Transmit data in 8 Bit mode */ + else + { + *((__IO uint8_t *)&hspi->Instance->TXDR) = *((const uint8_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + tmp_TxXferCount = hspi->TxXferCount; + } + } + + /* Enable EOT, DXP, UDR, OVR, FRE and MODF interrupts */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_DXP | SPI_IT_UDR | SPI_IT_OVR | SPI_IT_FRE | SPI_IT_MODF)); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Start Master transfer */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + return errorcode; +} + + + + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @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, const uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef errorcode; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_TXONLY(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (const uint8_t *)pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /* Init field not used in handle to zero */ + hspi->pRxBuffPtr = NULL; + hspi->TxISR = NULL; + hspi->RxISR = NULL; + hspi->RxXferSize = (uint16_t)0UL; + hspi->RxXferCount = (uint16_t)0UL; + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_TX(hspi); + } + else + { + SPI_2LINES_TX(hspi); + } + + /* Packing mode management is enabled by the DMA settings */ + if (((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (hspi->hdmatx->Init.SrcDataWidth != DMA_SRC_DATAWIDTH_WORD) && \ + (IS_SPI_FULL_INSTANCE(hspi->Instance))) || \ + ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) && (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_BYTE))) + { + /* Restriction the DMA data received is not allowed in this mode */ + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Adjust XferCount according to DMA alignment / Data size */ + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_HALFWORD) + { + hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; + } + if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) + { + hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 3UL) >> 2UL; + } + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) + { + hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; + } + } + else + { + /* Adjustment done */ + } + + /* Set the SPI TxDMA Half transfer complete callback */ + hspi->hdmatx->XferHalfCpltCallback = SPI_DMAHalfTransmitCplt; + + /* Set the SPI TxDMA transfer complete callback */ + hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; + + /* Set the DMA AbortCpltCallback */ + hspi->hdmatx->XferAbortCallback = NULL; + + /* Clear TXDMAEN bit*/ + CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN); + + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + hspi->TxXferCount = Size; + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + hspi->TxXferCount = Size * 2U; + } + else + { + hspi->TxXferCount = Size * 4U; + } + + /* Enable the Tx DMA Stream/Channel */ + if ((hspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hspi->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->TxXferCount; + + /* Set DMA source address */ + hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hspi->pTxBuffPtr; + + /* Set DMA destination address */ + hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->TXDR; + + errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmatx); + } + else + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->TXDR, + hspi->TxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + + /* Set the number of data at current transfer */ + if (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR) + { + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, 0UL); + } + else + { + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + } + + /* Enable Tx DMA Request */ + SET_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN); + + /* Enable the SPI Error Interrupt Bit */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_UDR | SPI_IT_FRE | SPI_IT_MODF)); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @param Size : amount of data to be sent + * @note When the CRC feature is enabled the pData Length must be Size + 1. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef errorcode; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE_2LINES_RXONLY(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = (uint8_t *)pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = NULL; + hspi->TxISR = NULL; + hspi->TxXferSize = (uint16_t) 0UL; + hspi->TxXferCount = (uint16_t) 0UL; + + /* Configure communication direction : 1Line */ + if (hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_RX(hspi); + } + else + { + SPI_2LINES_RX(hspi); + } + + /* Packing mode management is enabled by the DMA settings */ + if (((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (hspi->hdmarx->Init.DestDataWidth != DMA_DEST_DATAWIDTH_WORD) && \ + (IS_SPI_FULL_INSTANCE(hspi->Instance))) || \ + ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) && (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_BYTE))) + { + /* Restriction the DMA data received is not allowed in this mode */ + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Clear RXDMAEN bit */ + CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN); + + /* Adjust XferCount according to DMA alignment / Data size */ + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_HALFWORD) + { + hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; + } + if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) + { + hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 3UL) >> 2UL; + } + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) + { + hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; + } + } + else + { + /* Adjustment done */ + } + + /* Set the SPI RxDMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; + + /* Set the SPI Rx DMA transfer complete callback */ + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Set the DMA AbortCpltCallback */ + hspi->hdmarx->XferAbortCallback = NULL; + + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + hspi->RxXferCount = Size; + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + hspi->RxXferCount = Size * 2U; + } + else + { + hspi->RxXferCount = Size * 4U; + } + + /* Enable the Rx DMA Stream/Channel */ + if ((hspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hspi->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->RxXferCount; + + /* Set DMA source address */ + hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->RXDR; + + /* Set DMA destination address */ + hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hspi->pRxBuffPtr; + + errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmarx); + } + else + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->RXDR, (uint32_t)hspi->pRxBuffPtr, + hspi->RxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + + /* Set the number of data at current transfer */ + if (hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) + { + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, 0UL); + } + else + { + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + } + + /* Enable Rx DMA Request */ + SET_BIT(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN); + + /* Enable the SPI Error Interrupt Bit */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_OVR | SPI_IT_FRE | SPI_IT_MODF)); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Transmit and Receive an amount of data in non-blocking mode with DMA. + * @param hspi : pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer + * @param Size : amount of data to be sent + * @note When the CRC feature is enabled the pRxData Length must be Size + 1 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + HAL_StatusTypeDef errorcode; + + /* Check Direction parameter */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Lock the process */ + __HAL_LOCK(hspi); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + __HAL_UNLOCK(hspi); + return errorcode; + } + + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0UL)) + { + errorcode = HAL_ERROR; + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (const 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 = NULL; + hspi->TxISR = NULL; + + /* Set Full-Duplex mode */ + SPI_2LINES(hspi); + + /* Reset the Tx/Rx DMA bits */ + CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); + + /* Packing mode management is enabled by the DMA settings */ + if (((hspi->Init.DataSize > SPI_DATASIZE_16BIT) && (hspi->hdmarx->Init.DestDataWidth != DMA_DEST_DATAWIDTH_WORD) && \ + (IS_SPI_FULL_INSTANCE(hspi->Instance))) || \ + ((hspi->Init.DataSize > SPI_DATASIZE_8BIT) && (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_BYTE))) + { + /* Restriction the DMA data received is not allowed in this mode */ + errorcode = HAL_ERROR; + /* Unlock the process */ + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Adjust XferCount according to DMA alignment / Data size */ + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_HALFWORD) + { + hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; + } + if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) + { + hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 3UL) >> 2UL; + } + if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_HALFWORD) + { + hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; + } + if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) + { + hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 3UL) >> 2UL; + } + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + if (hspi->hdmatx->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD) + { + hspi->TxXferCount = (hspi->TxXferCount + (uint16_t) 1UL) >> 1UL; + } + if (hspi->hdmarx->Init.DestDataWidth == DMA_DEST_DATAWIDTH_WORD) + { + hspi->RxXferCount = (hspi->RxXferCount + (uint16_t) 1UL) >> 1UL; + } + } + else + { + /* Adjustment done */ + } + + /* Set the SPI Tx/Rx DMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfTransmitReceiveCplt; + hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt; + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Set the DMA AbortCallback */ + hspi->hdmarx->XferAbortCallback = NULL; + + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + hspi->RxXferCount = Size; + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + hspi->RxXferCount = Size * 2U; + } + else + { + hspi->RxXferCount = Size * 4U; + } + /* Enable the Rx DMA Stream/Channel */ + if ((hspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hspi->hdmarx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->RxXferCount; + + /* Set DMA source address */ + hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->RXDR; + + /* Set DMA destination address */ + hspi->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)hspi->pRxBuffPtr; + + errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmarx); + } + else + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->RXDR, (uint32_t)hspi->pRxBuffPtr, + hspi->RxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + + /* Enable Rx DMA Request */ + SET_BIT(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN); + + /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing + is performed in DMA reception complete callback */ + hspi->hdmatx->XferHalfCpltCallback = NULL; + hspi->hdmatx->XferCpltCallback = NULL; + hspi->hdmatx->XferAbortCallback = NULL; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; + + if (hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + hspi->TxXferCount = Size; + } + else if (hspi->Init.DataSize <= SPI_DATASIZE_16BIT) + { + hspi->TxXferCount = Size * 2U; + } + else + { + hspi->TxXferCount = Size * 4U; + } + + /* Enable the Tx DMA Stream/Channel */ + if ((hspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hspi->hdmatx->LinkedListQueue != NULL) + { + /* Set DMA data size */ + hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hspi->TxXferCount; + + /* Set DMA source address */ + hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)hspi->pTxBuffPtr; + + /* Set DMA destination address */ + hspi->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hspi->Instance->TXDR; + + errorcode = HAL_DMAEx_List_Start_IT(hspi->hdmatx); + } + else + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + } + else + { + errorcode = HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->TXDR, + hspi->TxXferCount); + } + + /* Check status */ + if (errorcode != HAL_OK) + { + /* Update SPI error code */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + hspi->State = HAL_SPI_STATE_READY; + errorcode = HAL_ERROR; + return errorcode; + } + + if ((hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) && (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR)) + { + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, 0UL); + } + else + { + MODIFY_REG(hspi->Instance->CR2, SPI_CR2_TSIZE, Size); + } + + /* Enable Tx DMA Request */ + SET_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN); + + /* Enable the SPI Error Interrupt Bit */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_OVR | SPI_IT_UDR | SPI_IT_FRE | SPI_IT_MODF)); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + + if (hspi->Init.Mode == SPI_MODE_MASTER) + { + /* Master transfer start */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSTART); + } + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Abort ongoing transfer (blocking mode). + * @param hspi SPI handle. + * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), + * started in Interrupt or DMA mode. + * @note This procedure performs following operations : + * + Disable SPI Interrupts (depending of transfer direction) + * + Disable the DMA transfer in the peripheral register (if enabled) + * + Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * + Set handle State to READY. + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Abort(SPI_HandleTypeDef *hspi) +{ + HAL_StatusTypeDef errorcode; + + __IO uint32_t count; + + /* Lock the process */ + __HAL_LOCK(hspi); + + /* Set hspi->state to aborting to avoid any interaction */ + hspi->State = HAL_SPI_STATE_ABORT; + + /* Initialized local variable */ + errorcode = HAL_OK; + count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24UL / 1000UL); + + /* If master communication on going, make sure current frame is done before closing the connection */ + if (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)) + { + /* Disable EOT interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_EOT); + do + { + count--; + if (count == 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + break; + } + } + while (HAL_IS_BIT_SET(hspi->Instance->IER, SPI_IT_EOT)); + + /* Request a Suspend transfer */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSUSP); + do + { + count--; + if (count == 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + break; + } + } + while (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)); + + /* Clear SUSP flag */ + __HAL_SPI_CLEAR_SUSPFLAG(hspi); + do + { + count--; + if (count == 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + break; + } + } + while (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_SUSP)); + } + + /* Disable the SPI DMA Tx request if enabled */ + if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN)) + { + if (hspi->hdmatx != NULL) + { + /* Abort the SPI DMA Tx Stream/Channel : use blocking DMA Abort API (no callback) */ + hspi->hdmatx->XferAbortCallback = NULL; + + /* Abort DMA Tx Handle linked to SPI Peripheral */ + if (HAL_DMA_Abort(hspi->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hspi->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + hspi->ErrorCode = HAL_SPI_ERROR_ABORT; + } + } + } + } + + /* Disable the SPI DMA Rx request if enabled */ + if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN)) + { + if (hspi->hdmarx != NULL) + { + /* Abort the SPI DMA Rx Stream/Channel : use blocking DMA Abort API (no callback) */ + hspi->hdmarx->XferAbortCallback = NULL; + + /* Abort DMA Rx Handle linked to SPI Peripheral */ + if (HAL_DMA_Abort(hspi->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hspi->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + hspi->ErrorCode = HAL_SPI_ERROR_ABORT; + } + } + } + } + + /* Proceed with abort procedure */ + SPI_AbortTransfer(hspi); + + /* Check error during Abort procedure */ + if (HAL_IS_BIT_SET(hspi->ErrorCode, HAL_SPI_ERROR_ABORT)) + { + /* return HAL_Error in case of error during Abort procedure */ + errorcode = HAL_ERROR; + } + else + { + /* Reset errorCode */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + } + + /* Unlock the process */ + __HAL_UNLOCK(hspi); + + /* Restore hspi->state to ready */ + hspi->State = HAL_SPI_STATE_READY; + + return errorcode; +} + +/** + * @brief Abort ongoing transfer (Interrupt mode). + * @param hspi SPI handle. + * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), + * started in Interrupt or DMA mode. + * @note This procedure performs following operations : + * + Disable SPI Interrupts (depending of transfer direction) + * + Disable the DMA transfer in the peripheral register (if enabled) + * + Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * + Set handle State to READY + * + At abort completion, call user abort complete callback. + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Abort_IT(SPI_HandleTypeDef *hspi) +{ + HAL_StatusTypeDef errorcode; + __IO uint32_t count; + uint32_t dma_tx_abort_done = 1UL; + uint32_t dma_rx_abort_done = 1UL; + + /* Set hspi->state to aborting to avoid any interaction */ + hspi->State = HAL_SPI_STATE_ABORT; + + /* Initialized local variable */ + errorcode = HAL_OK; + count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24UL / 1000UL); + + /* If master communication on going, make sure current frame is done before closing the connection */ + if (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)) + { + /* Disable EOT interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_EOT); + do + { + count--; + if (count == 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + break; + } + } + while (HAL_IS_BIT_SET(hspi->Instance->IER, SPI_IT_EOT)); + + /* Request a Suspend transfer */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CSUSP); + do + { + count--; + if (count == 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + break; + } + } + while (HAL_IS_BIT_SET(hspi->Instance->CR1, SPI_CR1_CSTART)); + + /* Clear SUSP flag */ + __HAL_SPI_CLEAR_SUSPFLAG(hspi); + do + { + count--; + if (count == 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + break; + } + } + while (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_SUSP)); + } + + /* If DMA Tx and/or DMA Rx Handles are associated to SPI Handle, DMA Abort complete callbacks should be initialized + before any call to DMA Abort functions */ + + if (hspi->hdmatx != NULL) + { + if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN)) + { + /* Set DMA Abort Complete callback if SPI DMA Tx request if enabled */ + hspi->hdmatx->XferAbortCallback = SPI_DMATxAbortCallback; + + dma_tx_abort_done = 0UL; + + /* Abort DMA Tx Handle linked to SPI Peripheral */ + if (HAL_DMA_Abort_IT(hspi->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(hspi->hdmatx) == HAL_DMA_ERROR_NO_XFER) + { + dma_tx_abort_done = 1UL; + hspi->hdmatx->XferAbortCallback = NULL; + } + } + } + else + { + hspi->hdmatx->XferAbortCallback = NULL; + } + } + + if (hspi->hdmarx != NULL) + { + if (HAL_IS_BIT_SET(hspi->Instance->CFG1, SPI_CFG1_RXDMAEN)) + { + /* Set DMA Abort Complete callback if SPI DMA Rx request if enabled */ + hspi->hdmarx->XferAbortCallback = SPI_DMARxAbortCallback; + + dma_rx_abort_done = 0UL; + + /* Abort DMA Rx Handle linked to SPI Peripheral */ + if (HAL_DMA_Abort_IT(hspi->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(hspi->hdmarx) == HAL_DMA_ERROR_NO_XFER) + { + dma_rx_abort_done = 1UL; + hspi->hdmarx->XferAbortCallback = NULL; + } + } + } + else + { + hspi->hdmarx->XferAbortCallback = NULL; + } + } + + /* If no running DMA transfer, finish cleanup and call callbacks */ + if ((dma_tx_abort_done == 1UL) && (dma_rx_abort_done == 1UL)) + { + /* Proceed with abort procedure */ + SPI_AbortTransfer(hspi); + + /* Check error during Abort procedure */ + if (HAL_IS_BIT_SET(hspi->ErrorCode, HAL_SPI_ERROR_ABORT)) + { + /* return HAL_Error in case of error during Abort procedure */ + errorcode = HAL_ERROR; + } + else + { + /* Reset errorCode */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + } + + /* Restore hspi->state to ready */ + hspi->State = HAL_SPI_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->AbortCpltCallback(hspi); +#else + HAL_SPI_AbortCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } + + return errorcode; +} + +/** + * @brief Pause the DMA Transfer. + * This API is not supported, it is maintained for backward compatibility. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval HAL_ERROR + */ +HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi) +{ + /* Set error code to not supported */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_NOT_SUPPORTED); + + return HAL_ERROR; +} + +/** + * @brief Resume the DMA Transfer. + * This API is not supported, it is maintained for backward compatibility. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval HAL_ERROR + */ +HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi) +{ + /* Set error code to not supported */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_NOT_SUPPORTED); + + return HAL_ERROR; +} + +/** + * @brief Stop the DMA Transfer. + * This API is not supported, it is maintained for backward compatibility. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval HAL_ERROR + */ +HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) +{ + /* Set error code to not supported */ + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_NOT_SUPPORTED); + + return HAL_ERROR; +} + +/** + * @brief Handle SPI interrupt request. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval None + */ +void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) +{ + uint32_t itsource = hspi->Instance->IER; + uint32_t itflag = hspi->Instance->SR; + uint32_t trigger = itsource & itflag; + uint32_t cfg1 = hspi->Instance->CFG1; + uint32_t handled = 0UL; + + HAL_SPI_StateTypeDef State = hspi->State; +#if defined (__GNUC__) + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); +#endif /* __GNUC__ */ + + /* SPI in SUSPEND mode ----------------------------------------------------*/ + if (HAL_IS_BIT_SET(itflag, SPI_FLAG_SUSP) && HAL_IS_BIT_SET(itsource, SPI_FLAG_EOT)) + { + /* Clear the Suspend flag */ + __HAL_SPI_CLEAR_SUSPFLAG(hspi); + + /* Suspend on going, Call the Suspend callback */ +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->SuspendCallback(hspi); +#else + HAL_SPI_SuspendCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + return; + } + + /* SPI in mode Transmitter and Receiver ------------------------------------*/ + if (HAL_IS_BIT_CLR(trigger, SPI_FLAG_OVR) && HAL_IS_BIT_CLR(trigger, SPI_FLAG_UDR) && \ + HAL_IS_BIT_SET(trigger, SPI_FLAG_DXP)) + { + hspi->TxISR(hspi); + hspi->RxISR(hspi); + handled = 1UL; + } + + /* SPI in mode Receiver ----------------------------------------------------*/ + if (HAL_IS_BIT_CLR(trigger, SPI_FLAG_OVR) && HAL_IS_BIT_SET(trigger, SPI_FLAG_RXP) && \ + HAL_IS_BIT_CLR(trigger, SPI_FLAG_DXP)) + { + hspi->RxISR(hspi); + handled = 1UL; + } + + /* SPI in mode Transmitter -------------------------------------------------*/ + if (HAL_IS_BIT_CLR(trigger, SPI_FLAG_UDR) && HAL_IS_BIT_SET(trigger, SPI_FLAG_TXP) && \ + HAL_IS_BIT_CLR(trigger, SPI_FLAG_DXP)) + { + hspi->TxISR(hspi); + handled = 1UL; + } + + + if (handled != 0UL) + { + return; + } + + /* SPI End Of Transfer: DMA or IT based transfer */ + if (HAL_IS_BIT_SET(trigger, SPI_FLAG_EOT)) + { + /* Clear EOT/TXTF/SUSP flag */ + __HAL_SPI_CLEAR_EOTFLAG(hspi); + __HAL_SPI_CLEAR_TXTFFLAG(hspi); + __HAL_SPI_CLEAR_SUSPFLAG(hspi); + + /* Disable EOT interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_EOT); + + /* For the IT based receive extra polling maybe required for last packet */ + if (HAL_IS_BIT_CLR(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN)) + { + /* Pooling remaining data */ + while (hspi->RxXferCount != 0UL) + { + /* Receive data in 32 Bit mode */ + if (hspi->Init.DataSize > SPI_DATASIZE_16BIT) + { + *((uint32_t *)hspi->pRxBuffPtr) = *((__IO uint32_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint32_t); + } + /* Receive data in 16 Bit mode */ + else if (hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { +#if defined (__GNUC__) + *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hspi->pRxBuffPtr) = *((__IO uint16_t *)&hspi->Instance->RXDR); +#endif /* __GNUC__ */ + hspi->pRxBuffPtr += sizeof(uint16_t); + } + /* Receive data in 8 Bit mode */ + else + { + *((uint8_t *)hspi->pRxBuffPtr) = *((__IO uint8_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint8_t); + } + + hspi->RxXferCount--; + } + } + + /* Call SPI Standard close procedure */ + SPI_CloseTransfer(hspi); + + hspi->State = HAL_SPI_STATE_READY; + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->ErrorCallback(hspi); +#else + HAL_SPI_ErrorCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + return; + } + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + /* Call appropriate user callback */ + if (State == HAL_SPI_STATE_BUSY_TX_RX) + { + hspi->TxRxCpltCallback(hspi); + } + else if (State == HAL_SPI_STATE_BUSY_RX) + { + hspi->RxCpltCallback(hspi); + } + else if (State == HAL_SPI_STATE_BUSY_TX) + { + hspi->TxCpltCallback(hspi); + } +#else + /* Call appropriate user callback */ + if (State == HAL_SPI_STATE_BUSY_TX_RX) + { + HAL_SPI_TxRxCpltCallback(hspi); + } + else if (State == HAL_SPI_STATE_BUSY_RX) + { + HAL_SPI_RxCpltCallback(hspi); + } + else if (State == HAL_SPI_STATE_BUSY_TX) + { + HAL_SPI_TxCpltCallback(hspi); + } +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + else + { + /* End of the appropriate call */ + } + + return; + } + + /* SPI in Error Treatment --------------------------------------------------*/ + if ((trigger & (SPI_FLAG_MODF | SPI_FLAG_OVR | SPI_FLAG_FRE | SPI_FLAG_UDR)) != 0UL) + { + /* SPI Overrun error interrupt occurred ----------------------------------*/ + if ((trigger & SPI_FLAG_OVR) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR); + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + /* SPI Mode Fault error interrupt occurred -------------------------------*/ + if ((trigger & SPI_FLAG_MODF) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_MODF); + __HAL_SPI_CLEAR_MODFFLAG(hspi); + } + + /* SPI Frame error interrupt occurred ------------------------------------*/ + if ((trigger & SPI_FLAG_FRE) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FRE); + __HAL_SPI_CLEAR_FREFLAG(hspi); + } + + /* SPI Underrun error interrupt occurred ------------------------------------*/ + if ((trigger & SPI_FLAG_UDR) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_UDR); + __HAL_SPI_CLEAR_UDRFLAG(hspi); + } + + if (hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Disable all interrupts */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_RXP | SPI_IT_TXP | SPI_IT_MODF | + SPI_IT_OVR | SPI_IT_FRE | SPI_IT_UDR)); + + /* Disable the SPI DMA requests if enabled */ + if (HAL_IS_BIT_SET(cfg1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN)) + { + /* Disable the SPI DMA requests */ + CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); + + /* Abort the SPI DMA Rx channel */ + if (hspi->hdmarx != NULL) + { + /* Set the SPI DMA Abort callback : + will lead to call HAL_SPI_ErrorCallback() at end of DMA abort procedure */ + hspi->hdmarx->XferAbortCallback = SPI_DMAAbortOnError; + if (HAL_OK != HAL_DMA_Abort_IT(hspi->hdmarx)) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + } + } + /* Abort the SPI DMA Tx channel */ + if (hspi->hdmatx != NULL) + { + /* Set the SPI DMA Abort callback : + will lead to call HAL_SPI_ErrorCallback() at end of DMA abort procedure */ + hspi->hdmatx->XferAbortCallback = SPI_DMAAbortOnError; + if (HAL_OK != HAL_DMA_Abort_IT(hspi->hdmatx)) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_ABORT); + } + } + } + else + { + /* Restore hspi->State to Ready */ + hspi->State = HAL_SPI_STATE_READY; + + /* Call user error callback */ +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->ErrorCallback(hspi); +#else + HAL_SPI_ErrorCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } + } + return; + } +} + +/** + * @brief Tx Transfer completed callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_TxCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_RxCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Tx and Rx Transfer completed callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_TxRxCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_TxHalfCpltCallback should be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_RxHalfCpltCallback() should be implemented in the user file + */ +} + +/** + * @brief Tx and Rx Half Transfer callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_TxRxHalfCpltCallback() should be implemented in the user file + */ +} + +/** + * @brief SPI error callback. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_ErrorCallback should be implemented in the user file + */ + /* NOTE : 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 occurred + */ +} + +/** + * @brief SPI Abort Complete callback. + * @param hspi SPI handle. + * @retval None + */ +__weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief SPI Suspend callback. + * @param hspi SPI handle. + * @retval None + */ +__weak void HAL_SPI_SuspendCallback(SPI_HandleTypeDef *hspi) /* Derogation MISRAC2012-Rule-8.13 */ +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SPI_SuspendCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup SPI_Exported_Functions_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 handle state. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval SPI state + */ +HAL_SPI_StateTypeDef HAL_SPI_GetState(const SPI_HandleTypeDef *hspi) +{ + /* Return SPI handle state */ + return hspi->State; +} + +/** + * @brief Return the SPI error code. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval SPI error code in bitmap format + */ +uint32_t HAL_SPI_GetError(const SPI_HandleTypeDef *hspi) +{ + /* Return SPI ErrorCode */ + return hspi->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SPI_Private_Functions + * @brief Private functions + * @{ + */ + +/** + * @brief DMA SPI transmit process complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hspi->State != HAL_SPI_STATE_ABORT) + { + if (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR) + { +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->TxCpltCallback(hspi); +#else + HAL_SPI_TxCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } + else + { + /* Enable EOT interrupt */ + __HAL_SPI_ENABLE_IT(hspi, SPI_IT_EOT); + } + } +} + +/** + * @brief DMA SPI receive process complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hspi->State != HAL_SPI_STATE_ABORT) + { + if (hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) + { +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->RxCpltCallback(hspi); +#else + HAL_SPI_RxCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } + else + { + /* Enable EOT interrupt */ + __HAL_SPI_ENABLE_IT(hspi, SPI_IT_EOT); + } + } +} + +/** + * @brief DMA SPI transmit receive process complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hspi->State != HAL_SPI_STATE_ABORT) + { + if ((hspi->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) && + (hspi->hdmatx->Mode == DMA_LINKEDLIST_CIRCULAR)) + { +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->TxRxCpltCallback(hspi); +#else + HAL_SPI_TxRxCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } + else + { + /* Enable EOT interrupt */ + __HAL_SPI_ENABLE_IT(hspi, SPI_IT_EOT); + } + } +} + +/** + * @brief DMA SPI half transmit process complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) /* Derogation MISRAC2012-Rule-8.13 */ +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-8.13 */ + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->TxHalfCpltCallback(hspi); +#else + HAL_SPI_TxHalfCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI half receive process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) /* Derogation MISRAC2012-Rule-8.13 */ +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-8.13 */ + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->RxHalfCpltCallback(hspi); +#else + HAL_SPI_RxHalfCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI half transmit receive process complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) /* Derogation MISRAC2012-Rule-8.13 */ +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-8.13 */ + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->TxRxHalfCpltCallback(hspi); +#else + HAL_SPI_TxRxHalfCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI communication error callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAError(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* if DMA error is FIFO error ignore it */ + if (HAL_DMA_GetError(hdma) != HAL_DMA_ERROR_NONE) + { + /* Call SPI standard close procedure */ + SPI_CloseTransfer(hspi); + + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + hspi->State = HAL_SPI_STATE_READY; +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->ErrorCallback(hspi); +#else + HAL_SPI_ErrorCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA SPI communication abort callback, when initiated by HAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + hspi->RxXferCount = (uint16_t) 0UL; + hspi->TxXferCount = (uint16_t) 0UL; + + /* Restore hspi->State to Ready */ + hspi->State = HAL_SPI_STATE_READY; + +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->ErrorCallback(hspi); +#else + HAL_SPI_ErrorCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hspi->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hspi->hdmarx != NULL) + { + if (hspi->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* Call the Abort procedure */ + SPI_AbortTransfer(hspi); + + /* Restore hspi->State to Ready */ + hspi->State = HAL_SPI_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->AbortCpltCallback(hspi); +#else + HAL_SPI_AbortCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SPI Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef *hspi = (SPI_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + hspi->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (hspi->hdmatx != NULL) + { + if (hspi->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* Call the Abort procedure */ + SPI_AbortTransfer(hspi); + + /* Restore hspi->State to Ready */ + hspi->State = HAL_SPI_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_SPI_REGISTER_CALLBACKS == 1UL) + hspi->AbortCpltCallback(hspi); +#else + HAL_SPI_AbortCpltCallback(hspi); +#endif /* USE_HAL_SPI_REGISTER_CALLBACKS */ +} + +/** + * @brief Manage the receive 8-bit in Interrupt context. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_8BIT(SPI_HandleTypeDef *hspi) +{ + /* Receive data in 8 Bit mode */ + *((uint8_t *)hspi->pRxBuffPtr) = (*(__IO uint8_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint8_t); + hspi->RxXferCount--; + + /* Disable IT if no more data excepted */ + if (hspi->RxXferCount == 0UL) + { + /* Disable RXP interrupts */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXP); + } +} + + +/** + * @brief Manage the 16-bit receive in Interrupt context. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_16BIT(SPI_HandleTypeDef *hspi) +{ + /* Receive data in 16 Bit mode */ +#if defined (__GNUC__) + __IO uint16_t *prxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->RXDR)); + + *((uint16_t *)hspi->pRxBuffPtr) = *prxdr_16bits; +#else + *((uint16_t *)hspi->pRxBuffPtr) = (*(__IO uint16_t *)&hspi->Instance->RXDR); +#endif /* __GNUC__ */ + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + + /* Disable IT if no more data excepted */ + if (hspi->RxXferCount == 0UL) + { + /* Disable RXP interrupts */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXP); + } +} + + +/** + * @brief Manage the 32-bit receive in Interrupt context. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxISR_32BIT(SPI_HandleTypeDef *hspi) +{ + /* Receive data in 32 Bit mode */ + *((uint32_t *)hspi->pRxBuffPtr) = (*(__IO uint32_t *)&hspi->Instance->RXDR); + hspi->pRxBuffPtr += sizeof(uint32_t); + hspi->RxXferCount--; + + /* Disable IT if no more data excepted */ + if (hspi->RxXferCount == 0UL) + { + /* Disable RXP interrupts */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXP); + } +} + + +/** + * @brief Handle the data 8-bit transmit in Interrupt mode. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_TxISR_8BIT(SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 8 Bit mode */ + *(__IO uint8_t *)&hspi->Instance->TXDR = *((const uint8_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint8_t); + hspi->TxXferCount--; + + /* Disable IT if no more data excepted */ + if (hspi->TxXferCount == 0UL) + { + /* Disable TXP interrupts */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXP); + } +} + +/** + * @brief Handle the data 16-bit transmit in Interrupt mode. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_TxISR_16BIT(SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 16 Bit mode */ +#if defined (__GNUC__) + __IO uint16_t *ptxdr_16bits = (__IO uint16_t *)(&(hspi->Instance->TXDR)); + + *ptxdr_16bits = *((const uint16_t *)hspi->pTxBuffPtr); +#else + *((__IO uint16_t *)&hspi->Instance->TXDR) = *((const uint16_t *)hspi->pTxBuffPtr); +#endif /* __GNUC__ */ + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + + /* Disable IT if no more data excepted */ + if (hspi->TxXferCount == 0UL) + { + /* Disable TXP interrupts */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXP); + } +} + +/** + * @brief Handle the data 32-bit transmit in Interrupt mode. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_TxISR_32BIT(SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 32 Bit mode */ + *((__IO uint32_t *)&hspi->Instance->TXDR) = *((const uint32_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint32_t); + hspi->TxXferCount--; + + /* Disable IT if no more data excepted */ + if (hspi->TxXferCount == 0UL) + { + /* Disable TXP interrupts */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXP); + } +} + +/** + * @brief Abort Transfer and clear flags. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_AbortTransfer(SPI_HandleTypeDef *hspi) +{ + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Disable ITs */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_TXP | SPI_IT_RXP | SPI_IT_DXP | SPI_IT_UDR | SPI_IT_OVR | \ + SPI_IT_FRE | SPI_IT_MODF)); + + /* Clear the Status flags in the SR register */ + __HAL_SPI_CLEAR_EOTFLAG(hspi); + __HAL_SPI_CLEAR_TXTFFLAG(hspi); + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); + + /* Clear the Error flags in the SR register */ + __HAL_SPI_CLEAR_OVRFLAG(hspi); + __HAL_SPI_CLEAR_UDRFLAG(hspi); + __HAL_SPI_CLEAR_FREFLAG(hspi); + __HAL_SPI_CLEAR_MODFFLAG(hspi); + __HAL_SPI_CLEAR_SUSPFLAG(hspi); + +#if (USE_SPI_CRC != 0U) + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); +#endif /* USE_SPI_CRC */ + + hspi->TxXferCount = (uint16_t)0UL; + hspi->RxXferCount = (uint16_t)0UL; +} + + +/** + * @brief Close Transfer and clear flags. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL_ERROR: if any error detected + * HAL_OK: if nothing detected + */ +static void SPI_CloseTransfer(SPI_HandleTypeDef *hspi) +{ + uint32_t itflag = hspi->Instance->SR; + + __HAL_SPI_CLEAR_EOTFLAG(hspi); + __HAL_SPI_CLEAR_TXTFFLAG(hspi); + + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Disable ITs */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_EOT | SPI_IT_TXP | SPI_IT_RXP | SPI_IT_DXP | SPI_IT_UDR | SPI_IT_OVR | \ + SPI_IT_FRE | SPI_IT_MODF)); + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CFG1, SPI_CFG1_TXDMAEN | SPI_CFG1_RXDMAEN); + + /* Report UnderRun error for non RX Only communication */ + if (hspi->State != HAL_SPI_STATE_BUSY_RX) + { + if ((itflag & SPI_FLAG_UDR) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_UDR); + __HAL_SPI_CLEAR_UDRFLAG(hspi); + } + } + + /* Report OverRun error for non TX Only communication */ + if (hspi->State != HAL_SPI_STATE_BUSY_TX) + { + if ((itflag & SPI_FLAG_OVR) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR); + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + +#if (USE_SPI_CRC != 0UL) + /* Check if CRC error occurred */ + if (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + if ((itflag & SPI_FLAG_CRCERR) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } + } +#endif /* USE_SPI_CRC */ + } + + /* SPI Mode Fault error interrupt occurred -------------------------------*/ + if ((itflag & SPI_FLAG_MODF) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_MODF); + __HAL_SPI_CLEAR_MODFFLAG(hspi); + } + + /* SPI Frame error interrupt occurred ------------------------------------*/ + if ((itflag & SPI_FLAG_FRE) != 0UL) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FRE); + __HAL_SPI_CLEAR_FREFLAG(hspi); + } + + hspi->TxXferCount = (uint16_t)0UL; + hspi->RxXferCount = (uint16_t)0UL; +} + +/** + * @brief Handle SPI Communication Timeout. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param Flag: SPI flag to check + * @param Status: flag state to check + * @param Timeout: Timeout duration + * @param Tickstart: Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(const SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, + uint32_t Timeout, uint32_t Tickstart) +{ + /* Wait until flag is set */ + while ((__HAL_SPI_GET_FLAG(hspi, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if ((((HAL_GetTick() - Tickstart) >= Timeout) && (Timeout != HAL_MAX_DELAY)) || (Timeout == 0U)) + { + return HAL_TIMEOUT; + } + } + return HAL_OK; +} + +/** + * @brief Compute configured packet size from fifo perspective. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval Packet size occupied in the fifo + */ +static uint32_t SPI_GetPacketSize(const SPI_HandleTypeDef *hspi) +{ + uint32_t fifo_threashold = (hspi->Init.FifoThreshold >> SPI_CFG1_FTHLV_Pos) + 1UL; + uint32_t data_size = (hspi->Init.DataSize >> SPI_CFG1_DSIZE_Pos) + 1UL; + + /* Convert data size to Byte */ + data_size = (data_size + 7UL) / 8UL; + + return data_size * fifo_threashold; +} + +/** + * @} + */ + +#endif /* HAL_SPI_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi_ex.c index 549b06509..8344ce57e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_spi_ex.c @@ -1,228 +1,228 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_spi_ex.c - * @author MCD Application Team - * @brief Extended SPI HAL module driver. - * This file provides firmware functions to manage the following - * SPI peripheral extended functionalities : - * + IO operation functions - * + Peripheral Control functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SPIEx SPIEx - * @brief SPI Extended HAL module driver - * @{ - */ -#ifdef HAL_SPI_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private defines -----------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup SPIEx_Exported_Functions SPIEx Exported Functions - * @{ - */ - -/** @defgroup SPIEx_Exported_Functions_Group1 IO operation functions - * @brief Data transfers functions - * -@verbatim - ============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of extended functions to manage the SPI - data transfers. - - (#) SPIEx function: - (++) HAL_SPIEx_FlushRxFifo() - (++) HAL_SPIEx_FlushRxFifo() - (++) HAL_SPIEx_EnableLockConfiguration() - (++) HAL_SPIEx_ConfigureUnderrun() - -@endverbatim - * @{ - */ - -/** - * @brief Flush the RX fifo. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(const SPI_HandleTypeDef *hspi) -{ - uint8_t count = 0; - uint32_t itflag = hspi->Instance->SR; - __IO uint32_t tmpreg; - - while (((hspi->Instance->SR & SPI_FLAG_FRLVL) != SPI_RX_FIFO_0PACKET) || ((itflag & SPI_FLAG_RXWNE) != 0UL)) - { - count += (uint8_t)4UL; - tmpreg = hspi->Instance->RXDR; - UNUSED(tmpreg); /* To avoid GCC warning */ - - if (IS_SPI_FULL_INSTANCE(hspi->Instance)) - { - if (count > SPI_HIGHEND_FIFO_SIZE) - { - return HAL_TIMEOUT; - } - } - else - { - if (count > SPI_LOWEND_FIFO_SIZE) - { - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - - -/** - * @brief Enable the Lock for the AF configuration of associated IOs - * and write protect the Content of Configuration register 2 - * when SPI is enabled - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -HAL_StatusTypeDef HAL_SPIEx_EnableLockConfiguration(SPI_HandleTypeDef *hspi) -{ - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Process Locked */ - __HAL_LOCK(hspi); - - if (hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - hspi->State = HAL_SPI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Check if the SPI is disabled to edit IOLOCK bit */ - if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_IOLOCK); - } - else - { - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - - SET_BIT(hspi->Instance->CR1, SPI_CR1_IOLOCK); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } - - hspi->State = HAL_SPI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Configure the UNDERRUN condition and behavior of slave transmitter. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param UnderrunDetection : Detection of underrun condition at slave transmitter - * This parameter is not supported in this SPI version. - * It is kept in order to not break the compatibility. - * @param UnderrunBehaviour : Behavior of slave transmitter at underrun condition - * This parameter can be a value of @ref SPI_Underrun_Behaviour. - * @retval None - */ -HAL_StatusTypeDef HAL_SPIEx_ConfigureUnderrun(SPI_HandleTypeDef *hspi, uint32_t UnderrunDetection, - uint32_t UnderrunBehaviour) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(UnderrunDetection); - - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Process Locked */ - __HAL_LOCK(hspi); - - /* Check State and Insure that Underrun configuration is managed only by Salve */ - if ((hspi->State != HAL_SPI_STATE_READY) || (hspi->Init.Mode != SPI_MODE_SLAVE)) - { - errorcode = HAL_BUSY; - hspi->State = HAL_SPI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; - } - - /* Check the parameters */ - assert_param(IS_SPI_UNDERRUN_BEHAVIOUR(UnderrunBehaviour)); - - /* Check if the SPI is disabled to edit CFG1 register */ - if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Configure Underrun fields */ - MODIFY_REG(hspi->Instance->CFG1, SPI_CFG1_UDRCFG, UnderrunBehaviour); - } - else - { - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - - /* Configure Underrun fields */ - MODIFY_REG(hspi->Instance->CFG1, SPI_CFG1_UDRCFG, UnderrunBehaviour); - - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } - - - hspi->State = HAL_SPI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_SPI_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_spi_ex.c + * @author MCD Application Team + * @brief Extended SPI HAL module driver. + * This file provides firmware functions to manage the following + * SPI peripheral extended functionalities : + * + IO operation functions + * + Peripheral Control functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SPIEx SPIEx + * @brief SPI Extended HAL module driver + * @{ + */ +#ifdef HAL_SPI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SPIEx_Exported_Functions SPIEx Exported Functions + * @{ + */ + +/** @defgroup SPIEx_Exported_Functions_Group1 IO operation functions + * @brief Data transfers functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of extended functions to manage the SPI + data transfers. + + (#) SPIEx function: + (++) HAL_SPIEx_FlushRxFifo() + (++) HAL_SPIEx_FlushRxFifo() + (++) HAL_SPIEx_EnableLockConfiguration() + (++) HAL_SPIEx_ConfigureUnderrun() + +@endverbatim + * @{ + */ + +/** + * @brief Flush the RX fifo. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for the specified SPI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPIEx_FlushRxFifo(const SPI_HandleTypeDef *hspi) +{ + uint8_t count = 0; + uint32_t itflag = hspi->Instance->SR; + __IO uint32_t tmpreg; + + while (((hspi->Instance->SR & SPI_FLAG_FRLVL) != SPI_RX_FIFO_0PACKET) || ((itflag & SPI_FLAG_RXWNE) != 0UL)) + { + count += (uint8_t)4UL; + tmpreg = hspi->Instance->RXDR; + UNUSED(tmpreg); /* To avoid GCC warning */ + + if (IS_SPI_FULL_INSTANCE(hspi->Instance)) + { + if (count > SPI_HIGHEND_FIFO_SIZE) + { + return HAL_TIMEOUT; + } + } + else + { + if (count > SPI_LOWEND_FIFO_SIZE) + { + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + + +/** + * @brief Enable the Lock for the AF configuration of associated IOs + * and write protect the Content of Configuration register 2 + * when SPI is enabled + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +HAL_StatusTypeDef HAL_SPIEx_EnableLockConfiguration(SPI_HandleTypeDef *hspi) +{ + HAL_StatusTypeDef errorcode = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(hspi); + + if (hspi->State != HAL_SPI_STATE_READY) + { + errorcode = HAL_BUSY; + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Check if the SPI is disabled to edit IOLOCK bit */ + if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_IOLOCK); + } + else + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + SET_BIT(hspi->Instance->CR1, SPI_CR1_IOLOCK); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @brief Configure the UNDERRUN condition and behavior of slave transmitter. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param UnderrunDetection : Detection of underrun condition at slave transmitter + * This parameter is not supported in this SPI version. + * It is kept in order to not break the compatibility. + * @param UnderrunBehaviour : Behavior of slave transmitter at underrun condition + * This parameter can be a value of @ref SPI_Underrun_Behaviour. + * @retval None + */ +HAL_StatusTypeDef HAL_SPIEx_ConfigureUnderrun(SPI_HandleTypeDef *hspi, uint32_t UnderrunDetection, + uint32_t UnderrunBehaviour) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(UnderrunDetection); + + HAL_StatusTypeDef errorcode = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Check State and Insure that Underrun configuration is managed only by Salve */ + if ((hspi->State != HAL_SPI_STATE_READY) || (hspi->Init.Mode != SPI_MODE_SLAVE)) + { + errorcode = HAL_BUSY; + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return errorcode; + } + + /* Check the parameters */ + assert_param(IS_SPI_UNDERRUN_BEHAVIOUR(UnderrunBehaviour)); + + /* Check if the SPI is disabled to edit CFG1 register */ + if ((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Configure Underrun fields */ + MODIFY_REG(hspi->Instance->CFG1, SPI_CFG1_UDRCFG, UnderrunBehaviour); + } + else + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Configure Underrun fields */ + MODIFY_REG(hspi->Instance->CFG1, SPI_CFG1_UDRCFG, UnderrunBehaviour); + + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + + hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return errorcode; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SPI_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sram.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sram.c index b68730152..d89188e9e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sram.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_sram.c @@ -1,1236 +1,1238 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_sram.c - * @author MCD Application Team - * @brief SRAM HAL module driver. - * This file provides a generic firmware to drive SRAM memories - * mounted as external device. - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 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() - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_SRAM_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - Use Functions HAL_SRAM_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) MspInitCallback : SRAM MspInit. - (+) MspDeInitCallback : SRAM MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - Use function HAL_SRAM_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) MspInitCallback : SRAM MspInit. - (+) MspDeInitCallback : SRAM MspDeInit. - This function) takes as parameters the HAL peripheral handle and the Callback ID. - - By default, after the HAL_SRAM_Init and if the state is HAL_SRAM_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_SRAM_Init - and HAL_SRAM_DeInit only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_SRAM_Init and HAL_SRAM_DeInit - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_SRAM_RegisterCallback before calling HAL_SRAM_DeInit - or HAL_SRAM_Init function. - - When The compilation define USE_HAL_SRAM_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_SRAM_MODULE_ENABLED - -/** @defgroup SRAM SRAM - * @brief SRAM driver modules - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SRAM_Private_Functions SRAM Private Functions - * @{ - */ -static void SRAM_DMACplt(DMA_HandleTypeDef *hdma); -static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma); -static void SRAM_DMAError(DMA_HandleTypeDef *hdma); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup SRAM_Exported_Functions SRAM Exported Functions - * @{ - */ - -/** @defgroup SRAM_Exported_Functions_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 a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) - { - /* Allocate lock resource and initialize it */ - hsram->Lock = HAL_UNLOCKED; - -#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) - if (hsram->MspInitCallback == NULL) - { - hsram->MspInitCallback = HAL_SRAM_MspInit; - } - hsram->DmaXferCpltCallback = HAL_SRAM_DMA_XferCpltCallback; - hsram->DmaXferErrorCallback = HAL_SRAM_DMA_XferErrorCallback; - - /* Init the low level hardware */ - hsram->MspInitCallback(hsram); -#else - /* Initialize the low level hardware (MSP) */ - HAL_SRAM_MspInit(hsram); -#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ - } - - /* Initialize SRAM control Interface */ - (void)FMC_NORSRAM_Init(hsram->Instance, &(hsram->Init)); - - /* Initialize SRAM timing Interface */ - (void)FMC_NORSRAM_Timing_Init(hsram->Instance, Timing, hsram->Init.NSBank); - - /* Initialize SRAM extended mode timing Interface */ - (void)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); - - /* Enable FMC Peripheral */ - __FMC_ENABLE(); - - /* Initialize the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Performs the SRAM device De-initialization sequence. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram) -{ -#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) - if (hsram->MspDeInitCallback == NULL) - { - hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; - } - - /* DeInit the low level hardware */ - hsram->MspDeInitCallback(hsram); -#else - /* De-Initialize the low level hardware (MSP) */ - HAL_SRAM_MspDeInit(hsram); -#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ - - /* Configure the SRAM registers with their reset values */ - (void)FMC_NORSRAM_DeInit(hsram->Instance, hsram->Extended, hsram->Init.NSBank); - - /* Reset the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_RESET; - - /* Release Lock */ - __HAL_UNLOCK(hsram); - - return HAL_OK; -} - -/** - * @brief SRAM MSP Init. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval None - */ -__weak void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval None - */ -__weak void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 hdma pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval None - */ -__weak void HAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 hdma pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval None - */ -__weak void HAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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_Exported_Functions_Group2 Input Output and memory control 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 a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - uint32_t size; - __IO uint8_t *psramaddress = (uint8_t *)pAddress; - uint8_t *pdestbuff = pDstBuffer; - HAL_SRAM_StateTypeDef state = hsram->State; - - /* Check the SRAM controller state */ - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Read data from memory */ - for (size = BufferSize; size != 0U; size--) - { - *pdestbuff = *psramaddress; - pdestbuff++; - psramaddress++; - } - - /* Update the SRAM controller state */ - hsram->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Writes 8-bit buffer to SRAM memory. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - uint32_t size; - __IO uint8_t *psramaddress = (uint8_t *)pAddress; - uint8_t *psrcbuff = pSrcBuffer; - - /* Check the SRAM controller state */ - if (hsram->State == HAL_SRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Write data to memory */ - for (size = BufferSize; size != 0U; size--) - { - *psramaddress = *psrcbuff; - psrcbuff++; - psramaddress++; - } - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Reads 16-bit buffer from SRAM memory. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *psramaddress = pAddress; - uint16_t *pdestbuff = pDstBuffer; - uint8_t limit; - HAL_SRAM_StateTypeDef state = hsram->State; - - /* Check the SRAM controller state */ - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Check if the size is a 32-bits multiple */ - limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); - - /* Read data from memory */ - for (size = BufferSize; size != limit; size -= 2U) - { - *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); - pdestbuff++; - *pdestbuff = (uint16_t)(((*psramaddress) & 0xFFFF0000U) >> 16U); - pdestbuff++; - psramaddress++; - } - - /* Read last 16-bits if size is not 32-bits multiple */ - if (limit != 0U) - { - *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); - } - - /* Update the SRAM controller state */ - hsram->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Writes 16-bit buffer to SRAM memory. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *psramaddress = pAddress; - uint16_t *psrcbuff = pSrcBuffer; - uint8_t limit; - - /* Check the SRAM controller state */ - if (hsram->State == HAL_SRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Check if the size is a 32-bits multiple */ - limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); - - /* Write data to memory */ - for (size = BufferSize; size != limit; size -= 2U) - { - *psramaddress = (uint32_t)(*psrcbuff); - psrcbuff++; - *psramaddress |= ((uint32_t)(*psrcbuff) << 16U); - psrcbuff++; - psramaddress++; - } - - /* Write last 16-bits if size is not 32-bits multiple */ - if (limit != 0U) - { - *psramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psramaddress) & 0xFFFF0000U); - } - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Reads 32-bit buffer from SRAM memory. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *psramaddress = pAddress; - uint32_t *pdestbuff = pDstBuffer; - HAL_SRAM_StateTypeDef state = hsram->State; - - /* Check the SRAM controller state */ - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Read data from memory */ - for (size = BufferSize; size != 0U; size--) - { - *pdestbuff = *psramaddress; - pdestbuff++; - psramaddress++; - } - - /* Update the SRAM controller state */ - hsram->State = state; - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Writes 32-bit buffer to SRAM memory. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - uint32_t size; - __IO uint32_t *psramaddress = pAddress; - uint32_t *psrcbuff = pSrcBuffer; - - /* Check the SRAM controller state */ - if (hsram->State == HAL_SRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Write data to memory */ - for (size = BufferSize; size != 0U; size--) - { - *psramaddress = *psrcbuff; - psrcbuff++; - psramaddress++; - } - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Reads a Words data from the SRAM memory using DMA transfer. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - HAL_StatusTypeDef status; - HAL_SRAM_StateTypeDef state = hsram->State; - uint32_t size; - uint32_t data_width; - - /* Check the SRAM controller state */ - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Configure DMA user callbacks */ - if (state == HAL_SRAM_STATE_READY) - { - hsram->hdma->XferCpltCallback = SRAM_DMACplt; - } - else - { - hsram->hdma->XferCpltCallback = SRAM_DMACpltProt; - } - hsram->hdma->XferErrorCallback = SRAM_DMAError; - - if ((hsram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hsram->hdma->LinkedListQueue != 0U) && (hsram->hdma->LinkedListQueue->Head != 0U)) - { - /* Check destination data width and set the size to be transferred */ - data_width = hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - /* Set Source , destination , buffer size */ - /* Set DMA data size */ - hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; - /* Set DMA source address */ - hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pAddress; - /* Set DMA destination address */ - hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pDstBuffer; - - /* Enable the DMA Stream */ - status = HAL_DMAEx_List_Start_IT(hsram->hdma); - } - else - { - /* Change SRAM state */ - hsram->State = HAL_SRAM_STATE_READY; - - __HAL_UNLOCK(hsram); - - status = HAL_ERROR; - } - } - else - { - /* Check destination data width and set the size to be transferred */ - data_width = hsram->hdma->Init.DestDataWidth; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - - /* Enable the DMA Stream */ - status = HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, size); - } - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Writes a Words data buffer to SRAM memory using DMA transfer. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @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) -{ - HAL_StatusTypeDef status; - uint32_t size; - uint32_t data_width; - - /* Check the SRAM controller state */ - if (hsram->State == HAL_SRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Configure DMA user callbacks */ - hsram->hdma->XferCpltCallback = SRAM_DMACplt; - hsram->hdma->XferErrorCallback = SRAM_DMAError; - - if ((hsram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hsram->hdma->LinkedListQueue != 0U) && (hsram->hdma->LinkedListQueue->Head != 0U)) - { - /* Check destination data width and set the size to be transferred */ - data_width = hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - /* Set Source , destination , buffer size */ - /* Set DMA data size */ - hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; - /* Set DMA source address */ - hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pSrcBuffer; - /* Set DMA destination address */ - hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pAddress; - /* Enable the DMA Stream */ - status = HAL_DMAEx_List_Start_IT(hsram->hdma); - } - else - { - /* Change SRAM state */ - hsram->State = HAL_SRAM_STATE_READY; - - __HAL_UNLOCK(hsram); - - status = HAL_ERROR; - } - } - else - { - /* Check destination data width and set the size to be transferred */ - data_width = hsram->hdma->Init.DestDataWidth; - - if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - size = (BufferSize * 4U); - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - size = (BufferSize * 2U); - } - else - { - size = (BufferSize); - } - - /* Enable the DMA Stream */ - status = HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, size); - } - - /* Process unlocked */ - __HAL_UNLOCK(hsram); - } - else - { - status = HAL_ERROR; - } - - return status; -} - -#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User SRAM Callback - * To be used to override the weak predefined callback - * @param hsram : SRAM handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID - * @arg @ref HAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_SRAM_RegisterCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId, - pSRAM_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_SRAM_StateTypeDef state; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - state = hsram->State; - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_RESET) || (state == HAL_SRAM_STATE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_SRAM_MSP_INIT_CB_ID : - hsram->MspInitCallback = pCallback; - break; - case HAL_SRAM_MSP_DEINIT_CB_ID : - hsram->MspDeInitCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User SRAM Callback - * SRAM Callback is redirected to the weak predefined callback - * @param hsram : SRAM handle - * @param CallbackId : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID - * @arg @ref HAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID - * @arg @ref HAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID - * @arg @ref HAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_SRAM_UnRegisterCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_SRAM_StateTypeDef state; - - state = hsram->State; - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_SRAM_MSP_INIT_CB_ID : - hsram->MspInitCallback = HAL_SRAM_MspInit; - break; - case HAL_SRAM_MSP_DEINIT_CB_ID : - hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; - break; - case HAL_SRAM_DMA_XFER_CPLT_CB_ID : - hsram->DmaXferCpltCallback = HAL_SRAM_DMA_XferCpltCallback; - break; - case HAL_SRAM_DMA_XFER_ERR_CB_ID : - hsram->DmaXferErrorCallback = HAL_SRAM_DMA_XferErrorCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (state == HAL_SRAM_STATE_RESET) - { - switch (CallbackId) - { - case HAL_SRAM_MSP_INIT_CB_ID : - hsram->MspInitCallback = HAL_SRAM_MspInit; - break; - case HAL_SRAM_MSP_DEINIT_CB_ID : - hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register a User SRAM Callback for DMA transfers - * To be used to override the weak predefined callback - * @param hsram : SRAM handle - * @param CallbackId : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID - * @arg @ref HAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_SRAM_RegisterDmaCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId, - pSRAM_DmaCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - HAL_SRAM_StateTypeDef state; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - /* Process locked */ - __HAL_LOCK(hsram); - - state = hsram->State; - if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) - { - switch (CallbackId) - { - case HAL_SRAM_DMA_XFER_CPLT_CB_ID : - hsram->DmaXferCpltCallback = pCallback; - break; - case HAL_SRAM_DMA_XFER_ERR_CB_ID : - hsram->DmaXferErrorCallback = pCallback; - break; - default : - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* update return status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hsram); - return status; -} -#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup SRAM_Exported_Functions_Group3 Control functions - * @brief Control 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 a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram) -{ - /* Check the SRAM controller state */ - if (hsram->State == HAL_SRAM_STATE_PROTECTED) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Enable write operation */ - (void)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); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Disables dynamically SRAM write operation. - * @param hsram pointer to a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram) -{ - /* Check the SRAM controller state */ - if (hsram->State == HAL_SRAM_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(hsram); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_BUSY; - - /* Disable write operation */ - (void)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); - } - else - { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup SRAM_Exported_Functions_Group4 Peripheral 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 a SRAM_HandleTypeDef structure that contains - * the configuration information for SRAM module. - * @retval HAL state - */ -HAL_SRAM_StateTypeDef HAL_SRAM_GetState(const SRAM_HandleTypeDef *hsram) -{ - return hsram->State; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup SRAM_Private_Functions SRAM Private Functions - * @{ - */ - -/** - * @brief DMA SRAM process complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) -{ - SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_READY; - -#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) - hsram->DmaXferCpltCallback(hdma); -#else - HAL_SRAM_DMA_XferCpltCallback(hdma); -#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SRAM process complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) -{ - SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_PROTECTED; - -#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) - hsram->DmaXferCpltCallback(hdma); -#else - HAL_SRAM_DMA_XferCpltCallback(hdma); -#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA SRAM error callback. - * @param hdma : DMA handle - * @retval None - */ -static void SRAM_DMAError(DMA_HandleTypeDef *hdma) -{ - SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); - - /* Disable the DMA channel */ - __HAL_DMA_DISABLE(hdma); - - /* Update the SRAM controller state */ - hsram->State = HAL_SRAM_STATE_ERROR; - -#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) - hsram->DmaXferErrorCallback(hdma); -#else - HAL_SRAM_DMA_XferErrorCallback(hdma); -#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ -} - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_SRAM_MODULE_ENABLED */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_sram.c + * @author MCD Application Team + * @brief SRAM HAL module driver. + * This file provides a generic firmware to drive SRAM memories + * mounted as external device. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 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() + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_SRAM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_SRAM_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) MspInitCallback : SRAM MspInit. + (+) MspDeInitCallback : SRAM MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + Use function HAL_SRAM_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) MspInitCallback : SRAM MspInit. + (+) MspDeInitCallback : SRAM MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + + By default, after the HAL_SRAM_Init and if the state is HAL_SRAM_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_SRAM_Init + and HAL_SRAM_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_SRAM_Init and HAL_SRAM_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SRAM_RegisterCallback before calling HAL_SRAM_DeInit + or HAL_SRAM_Init function. + + When The compilation define USE_HAL_SRAM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_SRAM_MODULE_ENABLED + +/** @defgroup SRAM SRAM + * @brief SRAM driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup SRAM_Private_Functions SRAM Private Functions + * @{ + */ +static void SRAM_DMACplt(DMA_HandleTypeDef *hdma); +static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma); +static void SRAM_DMAError(DMA_HandleTypeDef *hdma); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SRAM_Exported_Functions SRAM Exported Functions + * @{ + */ + +/** @defgroup SRAM_Exported_Functions_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 a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) + { + /* Allocate lock resource and initialize it */ + hsram->Lock = HAL_UNLOCKED; + +#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) + if (hsram->MspInitCallback == NULL) + { + hsram->MspInitCallback = HAL_SRAM_MspInit; + } + hsram->DmaXferCpltCallback = HAL_SRAM_DMA_XferCpltCallback; + hsram->DmaXferErrorCallback = HAL_SRAM_DMA_XferErrorCallback; + + /* Init the low level hardware */ + hsram->MspInitCallback(hsram); +#else + /* Initialize the low level hardware (MSP) */ + HAL_SRAM_MspInit(hsram); +#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ + } + + /* Initialize SRAM control Interface */ + (void)FMC_NORSRAM_Init(hsram->Instance, &(hsram->Init)); + + /* Initialize SRAM timing Interface */ + (void)FMC_NORSRAM_Timing_Init(hsram->Instance, Timing, hsram->Init.NSBank); + + /* Initialize SRAM extended mode timing Interface */ + (void)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); + + /* Enable FMC Peripheral */ + __FMC_ENABLE(); + + /* Initialize the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Performs the SRAM device De-initialization sequence. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SRAM_DeInit(SRAM_HandleTypeDef *hsram) +{ +#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) + if (hsram->MspDeInitCallback == NULL) + { + hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; + } + + /* DeInit the low level hardware */ + hsram->MspDeInitCallback(hsram); +#else + /* De-Initialize the low level hardware (MSP) */ + HAL_SRAM_MspDeInit(hsram); +#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ + + /* Configure the SRAM registers with their reset values */ + (void)FMC_NORSRAM_DeInit(hsram->Instance, hsram->Extended, hsram->Init.NSBank); + + /* Reset the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hsram); + + return HAL_OK; +} + +/** + * @brief SRAM MSP Init. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void HAL_SRAM_MspInit(SRAM_HandleTypeDef *hsram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void HAL_SRAM_MspDeInit(SRAM_HandleTypeDef *hsram) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 hdma pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void HAL_SRAM_DMA_XferCpltCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 hdma pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval None + */ +__weak void HAL_SRAM_DMA_XferErrorCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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_Exported_Functions_Group2 Input Output and memory control 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 a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + uint32_t size; + __IO uint8_t *psramaddress = (uint8_t *)pAddress; + uint8_t *pdestbuff = pDstBuffer; + HAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Read data from memory */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *psramaddress; + pdestbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Writes 8-bit buffer to SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + uint32_t size; + __IO uint8_t *psramaddress = (uint8_t *)pAddress; + uint8_t *psrcbuff = pSrcBuffer; + + /* Check the SRAM controller state */ + if (hsram->State == HAL_SRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *psramaddress = *psrcbuff; + psrcbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Reads 16-bit buffer from SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint16_t *pdestbuff = pDstBuffer; + uint8_t limit; + HAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Check if the size is a 32-bits multiple */ + limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); + + /* Read data from memory */ + for (size = BufferSize; size != limit; size -= 2U) + { + *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); + pdestbuff++; + *pdestbuff = (uint16_t)(((*psramaddress) & 0xFFFF0000U) >> 16U); + pdestbuff++; + psramaddress++; + } + + /* Read last 16-bits if size is not 32-bits multiple */ + if (limit != 0U) + { + *pdestbuff = (uint16_t)((*psramaddress) & 0x0000FFFFU); + } + + /* Update the SRAM controller state */ + hsram->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Writes 16-bit buffer to SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint16_t *psrcbuff = pSrcBuffer; + uint8_t limit; + + /* Check the SRAM controller state */ + if (hsram->State == HAL_SRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Check if the size is a 32-bits multiple */ + limit = (((BufferSize % 2U) != 0U) ? 1U : 0U); + + /* Write data to memory */ + for (size = BufferSize; size != limit; size -= 2U) + { + *psramaddress = (uint32_t)(*psrcbuff); + psrcbuff++; + *psramaddress |= ((uint32_t)(*psrcbuff) << 16U); + psrcbuff++; + psramaddress++; + } + + /* Write last 16-bits if size is not 32-bits multiple */ + if (limit != 0U) + { + *psramaddress = ((uint32_t)(*psrcbuff) & 0x0000FFFFU) | ((*psramaddress) & 0xFFFF0000U); + } + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Reads 32-bit buffer from SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint32_t *pdestbuff = pDstBuffer; + HAL_SRAM_StateTypeDef state = hsram->State; + + /* Check the SRAM controller state */ + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Read data from memory */ + for (size = BufferSize; size != 0U; size--) + { + *pdestbuff = *psramaddress; + pdestbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = state; + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Writes 32-bit buffer to SRAM memory. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + uint32_t size; + __IO uint32_t *psramaddress = pAddress; + uint32_t *psrcbuff = pSrcBuffer; + + /* Check the SRAM controller state */ + if (hsram->State == HAL_SRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Write data to memory */ + for (size = BufferSize; size != 0U; size--) + { + *psramaddress = *psrcbuff; + psrcbuff++; + psramaddress++; + } + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Reads a Words data from the SRAM memory using DMA transfer. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + HAL_StatusTypeDef status; + HAL_SRAM_StateTypeDef state = hsram->State; + uint32_t size; + uint32_t data_width; + + /* Check the SRAM controller state */ + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + if (state == HAL_SRAM_STATE_READY) + { + hsram->hdma->XferCpltCallback = SRAM_DMACplt; + } + else + { + hsram->hdma->XferCpltCallback = SRAM_DMACpltProt; + } + hsram->hdma->XferErrorCallback = SRAM_DMAError; + + if ((hsram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hsram->hdma->LinkedListQueue != 0U) && (hsram->hdma->LinkedListQueue->Head != 0U)) + { + /* Check destination data width and set the size to be transferred */ + data_width = hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + /* Set Source , destination , buffer size */ + /* Set DMA data size */ + hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; + /* Set DMA source address */ + hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pAddress; + /* Set DMA destination address */ + hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pDstBuffer; + + /* Enable the DMA Stream */ + status = HAL_DMAEx_List_Start_IT(hsram->hdma); + } + else + { + /* Change SRAM state */ + hsram->State = HAL_SRAM_STATE_READY; + + __HAL_UNLOCK(hsram); + + status = HAL_ERROR; + } + } + else + { + /* Check destination data width and set the size to be transferred */ + data_width = hsram->hdma->Init.DestDataWidth; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + + /* Enable the DMA Stream */ + status = HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pAddress, (uint32_t)pDstBuffer, size); + } + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Writes a Words data buffer to SRAM memory using DMA transfer. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @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) +{ + HAL_StatusTypeDef status; + uint32_t size; + uint32_t data_width; + + /* Check the SRAM controller state */ + if (hsram->State == HAL_SRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Configure DMA user callbacks */ + hsram->hdma->XferCpltCallback = SRAM_DMACplt; + hsram->hdma->XferErrorCallback = SRAM_DMAError; + + if ((hsram->hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hsram->hdma->LinkedListQueue != 0U) && (hsram->hdma->LinkedListQueue->Head != 0U)) + { + /* Check destination data width and set the size to be transferred */ + data_width = hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + /* Set Source , destination , buffer size */ + /* Set DMA data size */ + hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = size; + /* Set DMA source address */ + hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pSrcBuffer; + /* Set DMA destination address */ + hsram->hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pAddress; + /* Enable the DMA Stream */ + status = HAL_DMAEx_List_Start_IT(hsram->hdma); + } + else + { + /* Change SRAM state */ + hsram->State = HAL_SRAM_STATE_READY; + + __HAL_UNLOCK(hsram); + + status = HAL_ERROR; + } + } + else + { + /* Check destination data width and set the size to be transferred */ + data_width = hsram->hdma->Init.DestDataWidth; + + if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + size = (BufferSize * 4U); + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + size = (BufferSize * 2U); + } + else + { + size = (BufferSize); + } + + /* Enable the DMA Stream */ + status = HAL_DMA_Start_IT(hsram->hdma, (uint32_t)pSrcBuffer, (uint32_t)pAddress, size); + } + + /* Process unlocked */ + __HAL_UNLOCK(hsram); + } + else + { + status = HAL_ERROR; + } + + return status; +} + +#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User SRAM Callback + * To be used to override the weak predefined callback + * @param hsram : SRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID + * @arg @ref HAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SRAM_RegisterCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId, + pSRAM_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_SRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + state = hsram->State; + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_RESET) || (state == HAL_SRAM_STATE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_SRAM_MSP_INIT_CB_ID : + hsram->MspInitCallback = pCallback; + break; + case HAL_SRAM_MSP_DEINIT_CB_ID : + hsram->MspDeInitCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User SRAM Callback + * SRAM Callback is redirected to the weak predefined callback + * @param hsram : SRAM handle + * @param CallbackId : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_SRAM_MSP_INIT_CB_ID SRAM MspInit callback ID + * @arg @ref HAL_SRAM_MSP_DEINIT_CB_ID SRAM MspDeInit callback ID + * @arg @ref HAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID + * @arg @ref HAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_SRAM_UnRegisterCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_SRAM_StateTypeDef state; + + state = hsram->State; + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_SRAM_MSP_INIT_CB_ID : + hsram->MspInitCallback = HAL_SRAM_MspInit; + break; + case HAL_SRAM_MSP_DEINIT_CB_ID : + hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; + break; + case HAL_SRAM_DMA_XFER_CPLT_CB_ID : + hsram->DmaXferCpltCallback = HAL_SRAM_DMA_XferCpltCallback; + break; + case HAL_SRAM_DMA_XFER_ERR_CB_ID : + hsram->DmaXferErrorCallback = HAL_SRAM_DMA_XferErrorCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (state == HAL_SRAM_STATE_RESET) + { + switch (CallbackId) + { + case HAL_SRAM_MSP_INIT_CB_ID : + hsram->MspInitCallback = HAL_SRAM_MspInit; + break; + case HAL_SRAM_MSP_DEINIT_CB_ID : + hsram->MspDeInitCallback = HAL_SRAM_MspDeInit; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register a User SRAM Callback for DMA transfers + * To be used to override the weak predefined callback + * @param hsram : SRAM handle + * @param CallbackId : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SRAM_DMA_XFER_CPLT_CB_ID SRAM DMA Xfer Complete callback ID + * @arg @ref HAL_SRAM_DMA_XFER_ERR_CB_ID SRAM DMA Xfer Error callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SRAM_RegisterDmaCallback(SRAM_HandleTypeDef *hsram, HAL_SRAM_CallbackIDTypeDef CallbackId, + pSRAM_DmaCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + HAL_SRAM_StateTypeDef state; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hsram); + + state = hsram->State; + if ((state == HAL_SRAM_STATE_READY) || (state == HAL_SRAM_STATE_PROTECTED)) + { + switch (CallbackId) + { + case HAL_SRAM_DMA_XFER_CPLT_CB_ID : + hsram->DmaXferCpltCallback = pCallback; + break; + case HAL_SRAM_DMA_XFER_ERR_CB_ID : + hsram->DmaXferErrorCallback = pCallback; + break; + default : + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* update return status */ + status = HAL_ERROR; + } + + /* Release Lock */ + __HAL_UNLOCK(hsram); + return status; +} +#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup SRAM_Exported_Functions_Group3 Control functions + * @brief Control 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 a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SRAM_WriteOperation_Enable(SRAM_HandleTypeDef *hsram) +{ + /* Check the SRAM controller state */ + if (hsram->State == HAL_SRAM_STATE_PROTECTED) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Enable write operation */ + (void)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); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Disables dynamically SRAM write operation. + * @param hsram pointer to a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SRAM_WriteOperation_Disable(SRAM_HandleTypeDef *hsram) +{ + /* Check the SRAM controller state */ + if (hsram->State == HAL_SRAM_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsram); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_BUSY; + + /* Disable write operation */ + (void)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); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup SRAM_Exported_Functions_Group4 Peripheral 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 a SRAM_HandleTypeDef structure that contains + * the configuration information for SRAM module. + * @retval HAL state + */ +HAL_SRAM_StateTypeDef HAL_SRAM_GetState(const SRAM_HandleTypeDef *hsram) +{ + return hsram->State; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SRAM_Private_Functions SRAM Private Functions + * @{ + */ + +/** + * @brief DMA SRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SRAM_DMACplt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_READY; + +#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) + hsram->DmaXferCpltCallback(hdma); +#else + HAL_SRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SRAM process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void SRAM_DMACpltProt(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_PROTECTED; + +#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) + hsram->DmaXferCpltCallback(hdma); +#else + HAL_SRAM_DMA_XferCpltCallback(hdma); +#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA SRAM error callback. + * @param hdma : DMA handle + * @retval None + */ +static void SRAM_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Derogation MISRAC2012-Rule-11.5 */ + SRAM_HandleTypeDef *hsram = (SRAM_HandleTypeDef *)(hdma->Parent); + + /* Disable the DMA channel */ + __HAL_DMA_DISABLE(hdma); + + /* Update the SRAM controller state */ + hsram->State = HAL_SRAM_STATE_ERROR; + +#if (USE_HAL_SRAM_REGISTER_CALLBACKS == 1) + hsram->DmaXferErrorCallback(hdma); +#else + HAL_SRAM_DMA_XferErrorCallback(hdma); +#endif /* USE_HAL_SRAM_REGISTER_CALLBACKS */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SRAM_MODULE_ENABLED */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim.c index 5c9394798..78637cc38 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim.c @@ -1,8242 +1,8242 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_tim.c - * @author MCD Application Team - * @brief TIM HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Timer (TIM) peripheral: - * + TIM Time Base Initialization - * + TIM Time Base Start - * + TIM Time Base Start Interruption - * + TIM Time Base Start DMA - * + TIM Output Compare/PWM Initialization - * + TIM Output Compare/PWM Channel Configuration - * + TIM Output Compare/PWM Start - * + TIM Output Compare/PWM Start Interruption - * + TIM Output Compare/PWM Start DMA - * + TIM Input Capture Initialization - * + TIM Input Capture Channel Configuration - * + TIM Input Capture Start - * + TIM Input Capture Start Interruption - * + TIM Input Capture Start DMA - * + TIM One Pulse Initialization - * + TIM One Pulse Channel Configuration - * + TIM One Pulse Start - * + TIM Encoder Interface Initialization - * + TIM Encoder Interface Start - * + TIM Encoder Interface Start Interruption - * + TIM Encoder Interface Start DMA - * + Commutation Event configuration with Interruption and DMA - * + TIM OCRef clear configuration - * + TIM External Clock configuration - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 - (#) Synchronization circuit to control the timer with external signals and to interconnect - several timers together. - (#) Supports incremental encoder for positioning purposes - - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Initialize the TIM low level resources by implementing the following functions - depending on the selected feature: - (++) 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 __HAL_RCC_TIMx_CLK_ENABLE(); - (##) TIM pins configuration - (+++) Enable the clock for the TIM GPIOs using the following function: - __HAL_RCC_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, HAL_TIM_OC_ConfigChannel and optionally HAL_TIMEx_OC_ConfigPulseOnCompare: - 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() - - *** Callback registration *** - ============================================= - - [..] - The compilation define USE_HAL_TIM_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - [..] - Use Function HAL_TIM_RegisterCallback() to register a callback. - HAL_TIM_RegisterCallback() takes as parameters the HAL peripheral handle, - the Callback ID and a pointer to the user callback function. - - [..] - Use function HAL_TIM_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_TIM_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - - [..] - These functions allow to register/unregister following callbacks: - (+) Base_MspInitCallback : TIM Base Msp Init Callback. - (+) Base_MspDeInitCallback : TIM Base Msp DeInit Callback. - (+) IC_MspInitCallback : TIM IC Msp Init Callback. - (+) IC_MspDeInitCallback : TIM IC Msp DeInit Callback. - (+) OC_MspInitCallback : TIM OC Msp Init Callback. - (+) OC_MspDeInitCallback : TIM OC Msp DeInit Callback. - (+) PWM_MspInitCallback : TIM PWM Msp Init Callback. - (+) PWM_MspDeInitCallback : TIM PWM Msp DeInit Callback. - (+) OnePulse_MspInitCallback : TIM One Pulse Msp Init Callback. - (+) OnePulse_MspDeInitCallback : TIM One Pulse Msp DeInit Callback. - (+) Encoder_MspInitCallback : TIM Encoder Msp Init Callback. - (+) Encoder_MspDeInitCallback : TIM Encoder Msp DeInit Callback. - (+) HallSensor_MspInitCallback : TIM Hall Sensor Msp Init Callback. - (+) HallSensor_MspDeInitCallback : TIM Hall Sensor Msp DeInit Callback. - (+) PeriodElapsedCallback : TIM Period Elapsed Callback. - (+) PeriodElapsedHalfCpltCallback : TIM Period Elapsed half complete Callback. - (+) TriggerCallback : TIM Trigger Callback. - (+) TriggerHalfCpltCallback : TIM Trigger half complete Callback. - (+) IC_CaptureCallback : TIM Input Capture Callback. - (+) IC_CaptureHalfCpltCallback : TIM Input Capture half complete Callback. - (+) OC_DelayElapsedCallback : TIM Output Compare Delay Elapsed Callback. - (+) PWM_PulseFinishedCallback : TIM PWM Pulse Finished Callback. - (+) PWM_PulseFinishedHalfCpltCallback : TIM PWM Pulse Finished half complete Callback. - (+) ErrorCallback : TIM Error Callback. - (+) CommutationCallback : TIM Commutation Callback. - (+) CommutationHalfCpltCallback : TIM Commutation half complete Callback. - (+) BreakCallback : TIM Break Callback. - (+) Break2Callback : TIM Break2 Callback. - (+) EncoderIndexCallback : TIM Encoder Index Callback. - (+) DirectionChangeCallback : TIM Direction Change Callback - (+) IndexErrorCallback : TIM Index Error Callback. - (+) TransitionErrorCallback : TIM Transition Error Callback - - [..] -By default, after the Init and when the state is HAL_TIM_STATE_RESET -all interrupt callbacks are set to the corresponding weak functions: - examples HAL_TIM_TriggerCallback(), HAL_TIM_ErrorCallback(). - - [..] - Exception done for MspInit and MspDeInit functions that are reset to the legacy weak - functionalities in the Init / DeInit only when these callbacks are null - (not registered beforehand). If not, MspInit or MspDeInit are not null, the Init / DeInit - keep and use the user MspInit / MspDeInit callbacks(registered beforehand) - - [..] - Callbacks can be registered / unregistered in HAL_TIM_STATE_READY state only. - Exception done MspInit / MspDeInit that can be registered / unregistered - in HAL_TIM_STATE_READY or HAL_TIM_STATE_RESET state, - thus registered(user) MspInit / DeInit callbacks can be used during the Init / DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_TIM_RegisterCallback() before calling DeInit or Init function. - - [..] - When The compilation define USE_HAL_TIM_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup TIM TIM - * @brief TIM HAL module driver - * @{ - */ - -#ifdef HAL_TIM_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup TIM_Private_Functions - * @{ - */ -static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); -static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); -static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); -static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); -static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, const 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_ITRx_SetConfig(TIM_TypeDef *TIMx, uint32_t InputTriggerSource); -static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma); -static void TIM_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma); -static void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); -static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma); -static void TIM_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, - const TIM_SlaveConfigTypeDef *sSlaveConfig); -/** - * @} - */ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup TIM_Exported_Functions TIM Exported Functions - * @{ - */ - -/** @defgroup TIM_Exported_Functions_Group1 TIM 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 initialize the associated handle. - * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) - * requires a timer reset to avoid unexpected direction - * due to DIR bit readonly in center aligned mode. - * Ex: call @ref HAL_TIM_Base_DeInit() before HAL_TIM_Base_Init() - * @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)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - TIM_ResetCallback(htim); - - if (htim->Base_MspInitCallback == NULL) - { - htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->Base_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - HAL_TIM_Base_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* Set the Time Base configuration */ - TIM_Base_SetConfig(htim->Instance, &htim->Init); - - /* Initialize the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Initialize the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - - /* 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->Base_MspDeInitCallback == NULL) - { - htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; - } - /* DeInit the low level hardware */ - htim->Base_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_TIM_Base_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Change the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 Base handle - * @retval None - */ -__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Base handle - * @retval None - */ -__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Base handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(htim->Instance)); - - /* Check the TIM state */ - if (htim->State != HAL_TIM_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Base generation. - * @param htim TIM Base handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(htim->Instance)); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set 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 Base handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(htim->Instance)); - - /* Check the TIM state */ - if (htim->State != HAL_TIM_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* Enable the TIM Update interrupt */ - __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Base generation in interrupt mode. - * @param htim TIM Base 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); - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM Base generation in DMA mode. - * @param htim TIM Base 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, const uint32_t *pData, uint16_t Length) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); - - /* Set the TIM state */ - if (htim->State == HAL_TIM_STATE_BUSY) - { - return HAL_BUSY; - } - else if (htim->State == HAL_TIM_STATE_READY) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - htim->State = HAL_TIM_STATE_BUSY; - } - } - else - { - return HAL_ERROR; - } - - /* Set the DMA Period elapsed callbacks */ - htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; - htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Enable the TIM Update DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_UPDATE); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Base generation in DMA mode. - * @param htim TIM Base 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); - - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_READY; - - /* Return function status */ - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group2 TIM Output Compare functions - * @brief TIM Output Compare functions - * -@verbatim - ============================================================================== - ##### TIM Output Compare functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Initialize and configure the TIM Output Compare. - (+) De-initialize the TIM Output Compare. - (+) Start the TIM Output Compare. - (+) Stop the TIM Output Compare. - (+) Start the TIM Output Compare and enable interrupt. - (+) Stop the TIM Output Compare and disable interrupt. - (+) Start the TIM Output Compare and enable DMA transfer. - (+) Stop the TIM Output Compare and disable DMA transfer. - -@endverbatim - * @{ - */ -/** - * @brief Initializes the TIM Output Compare according to the specified - * parameters in the TIM_HandleTypeDef and initializes the associated handle. - * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) - * requires a timer reset to avoid unexpected direction - * due to DIR bit readonly in center aligned mode. - * Ex: call @ref HAL_TIM_OC_DeInit() before HAL_TIM_OC_Init() - * @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)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - TIM_ResetCallback(htim); - - if (htim->OC_MspInitCallback == NULL) - { - htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->OC_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_OC_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* 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 DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Initialize the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - - /* 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->OC_MspDeInitCallback == NULL) - { - htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; - } - /* DeInit the low level hardware */ - htim->OC_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_OC_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Change the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 Output Compare handle - * @retval None - */ -__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Output Compare handle - * @retval None - */ -__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); - - /* Check the TIM channel state */ - if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the Output compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Enable the main output */ - __HAL_TIM_MOE_ENABLE(htim); - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Output Compare signal generation. - * @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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 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_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM Output Compare signal generation in interrupt 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 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Check the TIM channel state */ - if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the Output compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Enable the main output */ - __HAL_TIM_MOE_ENABLE(htim); - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Output compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @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, const uint32_t *pData, - uint16_t Length) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Set the TIM channel state */ - if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) - { - return HAL_BUSY; - } - else if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Enable the TIM Capture/Compare 1 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - break; - } - - case TIM_CHANNEL_2: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Enable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); - break; - } - - case TIM_CHANNEL_3: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); - break; - } - - case TIM_CHANNEL_4: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 4 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the Output compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Enable the main output */ - __HAL_TIM_MOE_ENABLE(htim); - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - - case TIM_CHANNEL_2: - { - /* Disable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - - case TIM_CHANNEL_3: - { - /* Disable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - - case TIM_CHANNEL_4: - { - /* Disable the TIM Capture/Compare 4 interrupt */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Output compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group3 TIM PWM functions - * @brief TIM PWM functions - * -@verbatim - ============================================================================== - ##### TIM PWM functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Initialize and configure the TIM PWM. - (+) De-initialize the TIM PWM. - (+) Start the TIM PWM. - (+) Stop the TIM PWM. - (+) Start the TIM PWM and enable interrupt. - (+) Stop the TIM PWM and disable interrupt. - (+) Start the TIM PWM and enable DMA transfer. - (+) Stop the TIM PWM and disable DMA transfer. - -@endverbatim - * @{ - */ -/** - * @brief Initializes the TIM PWM Time Base according to the specified - * parameters in the TIM_HandleTypeDef and initializes the associated handle. - * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) - * requires a timer reset to avoid unexpected direction - * due to DIR bit readonly in center aligned mode. - * Ex: call @ref HAL_TIM_PWM_DeInit() before HAL_TIM_PWM_Init() - * @param htim TIM PWM 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)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - TIM_ResetCallback(htim); - - if (htim->PWM_MspInitCallback == NULL) - { - htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->PWM_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_PWM_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* 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 DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Initialize the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - - /* Initialize the TIM state*/ - htim->State = HAL_TIM_STATE_READY; - - return HAL_OK; -} - -/** - * @brief DeInitializes the TIM peripheral - * @param htim TIM PWM 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->PWM_MspDeInitCallback == NULL) - { - htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; - } - /* DeInit the low level hardware */ - htim->PWM_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_PWM_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Change the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 PWM handle - * @retval None - */ -__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 PWM handle - * @retval None - */ -__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); - - /* Check the TIM channel state */ - if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Enable the main output */ - __HAL_TIM_MOE_ENABLE(htim); - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the PWM signal generation. - * @param htim TIM PWM 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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 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_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the PWM signal generation in interrupt mode. - * @param htim TIM PWM 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_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Check the TIM channel state */ - if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Enable the main output */ - __HAL_TIM_MOE_ENABLE(htim); - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Stops the PWM signal generation in interrupt mode. - * @param htim TIM PWM 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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @brief Starts the TIM PWM signal generation in DMA mode. - * @param htim TIM PWM 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, const uint32_t *pData, - uint16_t Length) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Set the TIM channel state */ - if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) - { - return HAL_BUSY; - } - else if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Enable the TIM Capture/Compare 1 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - break; - } - - case TIM_CHANNEL_2: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); - break; - } - - case TIM_CHANNEL_3: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Output Capture/Compare 3 request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); - break; - } - - case TIM_CHANNEL_4: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 4 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Enable the main output */ - __HAL_TIM_MOE_ENABLE(htim); - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Stops the TIM PWM signal generation in DMA mode. - * @param htim TIM PWM 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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - - case TIM_CHANNEL_2: - { - /* Disable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - - case TIM_CHANNEL_3: - { - /* Disable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - - case TIM_CHANNEL_4: - { - /* Disable the TIM Capture/Compare 4 interrupt */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group4 TIM Input Capture functions - * @brief TIM Input Capture functions - * -@verbatim - ============================================================================== - ##### TIM Input Capture functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Initialize and configure the TIM Input Capture. - (+) De-initialize the TIM Input Capture. - (+) Start the TIM Input Capture. - (+) Stop the TIM Input Capture. - (+) Start the TIM Input Capture and enable interrupt. - (+) Stop the TIM Input Capture and disable interrupt. - (+) Start the TIM Input Capture and enable DMA transfer. - (+) Stop the TIM 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 initializes the associated handle. - * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) - * requires a timer reset to avoid unexpected direction - * due to DIR bit readonly in center aligned mode. - * Ex: call @ref HAL_TIM_IC_DeInit() before HAL_TIM_IC_Init() - * @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)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - TIM_ResetCallback(htim); - - if (htim->IC_MspInitCallback == NULL) - { - htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->IC_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_IC_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* 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 DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Initialize the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); - - /* 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->IC_MspDeInitCallback == NULL) - { - htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; - } - /* DeInit the low level hardware */ - htim->IC_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_IC_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Change the TIM channels state */ - TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 Input Capture handle - * @retval None - */ -__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 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 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - uint32_t tmpsmcr; - HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); - HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Check the TIM channel state */ - if ((channel_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the Input Capture channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Input Capture measurement. - * @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(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Disable the Input Capture channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM Input Capture measurement in interrupt 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 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); - HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - - /* Check the TIM channel state */ - if ((channel_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the Input Capture channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @brief Stops the TIM Input Capture measurement in interrupt 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_IT(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Input Capture channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @brief Starts the TIM Input Capture measurement 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) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); - HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); - - /* Set the TIM channel state */ - if ((channel_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_state == HAL_TIM_CHANNEL_STATE_BUSY)) - { - return HAL_BUSY; - } - else if ((channel_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_state == HAL_TIM_CHANNEL_STATE_READY)) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - - /* Enable the Input Capture channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 1 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - break; - } - - case TIM_CHANNEL_2: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); - break; - } - - case TIM_CHANNEL_3: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); - break; - } - - case TIM_CHANNEL_4: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 4 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); - break; - } - - default: - status = HAL_ERROR; - break; - } - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return status; -} - -/** - * @brief Stops the TIM Input Capture measurement 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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); - assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); - - /* Disable the Input Capture channel */ - TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Disable the TIM Capture/Compare 1 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - - case TIM_CHANNEL_2: - { - /* Disable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - - case TIM_CHANNEL_3: - { - /* Disable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - - case TIM_CHANNEL_4: - { - /* Disable the TIM Capture/Compare 4 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group5 TIM One Pulse functions - * @brief TIM One Pulse functions - * -@verbatim - ============================================================================== - ##### TIM One Pulse functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Initialize and configure the TIM One Pulse. - (+) De-initialize the TIM One Pulse. - (+) Start the TIM One Pulse. - (+) Stop the TIM One Pulse. - (+) Start the TIM One Pulse and enable interrupt. - (+) Stop the TIM One Pulse and disable interrupt. - (+) Start the TIM One Pulse and enable DMA transfer. - (+) Stop the TIM 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 initializes the associated handle. - * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) - * requires a timer reset to avoid unexpected direction - * due to DIR bit readonly in center aligned mode. - * Ex: call @ref HAL_TIM_OnePulse_DeInit() before HAL_TIM_OnePulse_Init() - * @note When the timer instance is initialized in One Pulse mode, timer - * channels 1 and channel 2 are reserved and cannot be used for other - * purpose. - * @param htim TIM One Pulse 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 will 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)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - TIM_ResetCallback(htim); - - if (htim->OnePulse_MspInitCallback == NULL) - { - htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->OnePulse_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_OnePulse_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* 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 DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Initialize the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->OnePulse_MspDeInitCallback == NULL) - { - htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; - } - /* DeInit the low level hardware */ - htim->OnePulse_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_TIM_OnePulse_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 One Pulse handle - * @retval None - */ -__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 One Pulse handle - * @retval None - */ -__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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. - * @note Though OutputChannel parameter is deprecated and ignored by the function - * it has been kept to avoid HAL_TIM API compatibility break. - * @note The pulse output channel is determined when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel See note above - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) -{ - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Prevent unused argument(s) compilation warning */ - UNUSED(OutputChannel); - - /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - - /* 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 - whatever the combination, 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_BREAK_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. - * @note Though OutputChannel parameter is deprecated and ignored by the function - * it has been kept to avoid HAL_TIM API compatibility break. - * @note The pulse output channel is determined when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel See note above - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 - whatever the combination, 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_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM One Pulse signal generation in interrupt mode. - * @note Though OutputChannel parameter is deprecated and ignored by the function - * it has been kept to avoid HAL_TIM API compatibility break. - * @note The pulse output channel is determined when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel See note above - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) -{ - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Prevent unused argument(s) compilation warning */ - UNUSED(OutputChannel); - - /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - - /* 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 - whatever the combination, 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_BREAK_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. - * @note Though OutputChannel parameter is deprecated and ignored by the function - * it has been kept to avoid HAL_TIM API compatibility break. - * @note The pulse output channel is determined when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel See note above - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 - whatever the combination, 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_BREAK_INSTANCE(htim->Instance) != RESET) - { - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group6 TIM Encoder functions - * @brief TIM Encoder functions - * -@verbatim - ============================================================================== - ##### TIM Encoder functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Initialize and configure the TIM Encoder. - (+) De-initialize the TIM Encoder. - (+) Start the TIM Encoder. - (+) Stop the TIM Encoder. - (+) Start the TIM Encoder and enable interrupt. - (+) Stop the TIM Encoder and disable interrupt. - (+) Start the TIM Encoder and enable DMA transfer. - (+) Stop the TIM Encoder and disable DMA transfer. - -@endverbatim - * @{ - */ -/** - * @brief Initializes the TIM Encoder Interface and initialize the associated handle. - * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) - * requires a timer reset to avoid unexpected direction - * due to DIR bit readonly in center aligned mode. - * Ex: call @ref HAL_TIM_Encoder_DeInit() before HAL_TIM_Encoder_Init() - * @note Encoder mode and External clock mode 2 are not compatible and must not be selected together - * Ex: A call for @ref HAL_TIM_Encoder_Init will erase the settings of @ref HAL_TIM_ConfigClockSource - * using TIM_CLOCKSOURCE_ETRMODE2 and vice versa - * @note When the timer instance is initialized in Encoder mode, timer - * channels 1 and channel 2 are reserved and cannot be used for other - * purpose. - * @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, const TIM_Encoder_InitTypeDef *sConfig) -{ - uint32_t tmpsmcr; - uint32_t tmpccmr1; - uint32_t tmpccer; - - /* Check the TIM handle allocation */ - if (htim == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_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_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - 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_ENCODERINPUT_POLARITY(sConfig->IC1Polarity)); - assert_param(IS_TIM_ENCODERINPUT_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)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy weak callbacks */ - TIM_ResetCallback(htim); - - if (htim->Encoder_MspInitCallback == NULL) - { - htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->Encoder_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_TIM_Encoder_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* Reset the SMS and ECE bits */ - htim->Instance->SMCR &= ~(TIM_SMCR_SMS | TIM_SMCR_ECE); - - /* 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 << 8U)); - - /* Set 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 << 8U); - tmpccmr1 |= (sConfig->IC1Filter << 4U) | (sConfig->IC2Filter << 12U); - - /* 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 << 4U); - - /* 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 DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Initialize the TIM state*/ - htim->State = HAL_TIM_STATE_READY; - - return HAL_OK; -} - - -/** - * @brief DeInitializes the TIM Encoder interface - * @param htim TIM Encoder Interface 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->Encoder_MspDeInitCallback == NULL) - { - htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; - } - /* DeInit the low level hardware */ - htim->Encoder_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_TIM_Encoder_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 Encoder Interface handle - * @retval None - */ -__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Encoder Interface handle - * @retval None - */ -__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 - * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - /* Set the TIM channel(s) state */ - if (Channel == TIM_CHANNEL_1) - { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else if (Channel == TIM_CHANNEL_2) - { - if ((channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - - /* 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 - * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_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); - - /* Set the TIM channel(s) state */ - if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) - { - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - } - - /* 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 - * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - /* Set the TIM channel(s) state */ - if (Channel == TIM_CHANNEL_1) - { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else if (Channel == TIM_CHANNEL_2) - { - if ((channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - - /* 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 - * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_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); - - /* Set the TIM channel(s) state */ - if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) - { - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_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 - * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are 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) -{ - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - /* Set the TIM channel(s) state */ - if (Channel == TIM_CHANNEL_1) - { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY)) - { - return HAL_BUSY; - } - else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY)) - { - if ((pData1 == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - } - else if (Channel == TIM_CHANNEL_2) - { - if ((channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) - { - return HAL_BUSY; - } - else if ((channel_2_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) - { - if ((pData2 == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - } - else - { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) - { - return HAL_BUSY; - } - else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) - { - if ((((pData1 == NULL) || (pData2 == NULL))) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - } - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Input Capture DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - - /* Enable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); - - /* Enable the Peripheral */ - __HAL_TIM_ENABLE(htim); - - break; - } - - case TIM_CHANNEL_2: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError; - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Input Capture DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); - - /* Enable the Capture compare channel */ - TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); - - /* Enable the Peripheral */ - __HAL_TIM_ENABLE(htim); - - break; - } - - default: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - - /* 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); - - /* 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 Peripheral */ - __HAL_TIM_ENABLE(htim); - - 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 - * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - } - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel(s) state */ - if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) - { - TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @} - */ -/** @defgroup TIM_Exported_Functions_Group7 TIM IRQ handler management - * @brief TIM 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) -{ - uint32_t itsource = htim->Instance->DIER; - uint32_t itflag = htim->Instance->SR; - - /* Capture compare 1 event */ - if ((itflag & (TIM_FLAG_CC1)) == (TIM_FLAG_CC1)) - { - if ((itsource & (TIM_IT_CC1)) == (TIM_IT_CC1)) - { - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC1); - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - - /* Input capture event */ - if ((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U) - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IC_CaptureCallback(htim); -#else - HAL_TIM_IC_CaptureCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - /* Output compare event */ - else - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->OC_DelayElapsedCallback(htim); - htim->PWM_PulseFinishedCallback(htim); -#else - HAL_TIM_OC_DelayElapsedCallback(htim); - HAL_TIM_PWM_PulseFinishedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; - } - } - } - /* Capture compare 2 event */ - if ((itflag & (TIM_FLAG_CC2)) == (TIM_FLAG_CC2)) - { - if ((itsource & (TIM_IT_CC2)) == (TIM_IT_CC2)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC2); - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - /* Input capture event */ - if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IC_CaptureCallback(htim); -#else - HAL_TIM_IC_CaptureCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - /* Output compare event */ - else - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->OC_DelayElapsedCallback(htim); - htim->PWM_PulseFinishedCallback(htim); -#else - HAL_TIM_OC_DelayElapsedCallback(htim); - HAL_TIM_PWM_PulseFinishedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; - } - } - /* Capture compare 3 event */ - if ((itflag & (TIM_FLAG_CC3)) == (TIM_FLAG_CC3)) - { - if ((itsource & (TIM_IT_CC3)) == (TIM_IT_CC3)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC3); - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - /* Input capture event */ - if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IC_CaptureCallback(htim); -#else - HAL_TIM_IC_CaptureCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - /* Output compare event */ - else - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->OC_DelayElapsedCallback(htim); - htim->PWM_PulseFinishedCallback(htim); -#else - HAL_TIM_OC_DelayElapsedCallback(htim); - HAL_TIM_PWM_PulseFinishedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; - } - } - /* Capture compare 4 event */ - if ((itflag & (TIM_FLAG_CC4)) == (TIM_FLAG_CC4)) - { - if ((itsource & (TIM_IT_CC4)) == (TIM_IT_CC4)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC4); - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - /* Input capture event */ - if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IC_CaptureCallback(htim); -#else - HAL_TIM_IC_CaptureCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - /* Output compare event */ - else - { -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->OC_DelayElapsedCallback(htim); - htim->PWM_PulseFinishedCallback(htim); -#else - HAL_TIM_OC_DelayElapsedCallback(htim); - HAL_TIM_PWM_PulseFinishedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; - } - } - /* TIM Update event */ - if ((itflag & (TIM_FLAG_UPDATE)) == (TIM_FLAG_UPDATE)) - { - if ((itsource & (TIM_IT_UPDATE)) == (TIM_IT_UPDATE)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_UPDATE); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->PeriodElapsedCallback(htim); -#else - HAL_TIM_PeriodElapsedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Break input event */ - if (((itflag & (TIM_FLAG_BREAK)) == (TIM_FLAG_BREAK)) || \ - ((itflag & (TIM_FLAG_SYSTEM_BREAK)) == (TIM_FLAG_SYSTEM_BREAK))) - { - if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK | TIM_FLAG_SYSTEM_BREAK); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->BreakCallback(htim); -#else - HAL_TIMEx_BreakCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Break2 input event */ - if ((itflag & (TIM_FLAG_BREAK2)) == (TIM_FLAG_BREAK2)) - { - if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK2); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->Break2Callback(htim); -#else - HAL_TIMEx_Break2Callback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Trigger detection event */ - if ((itflag & (TIM_FLAG_TRIGGER)) == (TIM_FLAG_TRIGGER)) - { - if ((itsource & (TIM_IT_TRIGGER)) == (TIM_IT_TRIGGER)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TRIGGER); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->TriggerCallback(htim); -#else - HAL_TIM_TriggerCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM commutation event */ - if ((itflag & (TIM_FLAG_COM)) == (TIM_FLAG_COM)) - { - if ((itsource & (TIM_IT_COM)) == (TIM_IT_COM)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_COM); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->CommutationCallback(htim); -#else - HAL_TIMEx_CommutCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Encoder index event */ - if ((itflag & (TIM_FLAG_IDX)) == (TIM_FLAG_IDX)) - { - if ((itsource & (TIM_IT_IDX)) == (TIM_IT_IDX)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_IDX); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->EncoderIndexCallback(htim); -#else - HAL_TIMEx_EncoderIndexCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Direction change event */ - if ((itflag & (TIM_FLAG_DIR)) == (TIM_FLAG_DIR)) - { - if ((itsource & (TIM_IT_DIR)) == (TIM_IT_DIR)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_DIR); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->DirectionChangeCallback(htim); -#else - HAL_TIMEx_DirectionChangeCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Index error event */ - if ((itflag & (TIM_FLAG_IERR)) == (TIM_FLAG_IERR)) - { - if ((itsource & (TIM_IT_IERR)) == (TIM_IT_IERR)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_IERR); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IndexErrorCallback(htim); -#else - HAL_TIMEx_IndexErrorCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } - /* TIM Transition error event */ - if ((itflag & (TIM_FLAG_TERR)) == (TIM_FLAG_TERR)) - { - if ((itsource & (TIM_IT_TERR)) == (TIM_IT_TERR)) - { - __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TERR); -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->TransitionErrorCallback(htim); -#else - HAL_TIMEx_TransitionErrorCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - } -} - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group8 TIM Peripheral Control functions - * @brief TIM 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 configure - * 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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, - const TIM_OC_InitTypeDef *sConfig, - uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_CHANNELS(Channel)); - assert_param(IS_TIM_OC_CHANNEL_MODE(sConfig->OCMode, Channel)); - assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); - - /* Process Locked */ - __HAL_LOCK(htim); - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Check the parameters */ - 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: - { - /* Check the parameters */ - 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: - { - /* Check the parameters */ - 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: - { - /* Check the parameters */ - assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); - - /* Configure the TIM Channel 4 in Output Compare */ - TIM_OC4_SetConfig(htim->Instance, sConfig); - break; - } - - case TIM_CHANNEL_5: - { - /* Check the parameters */ - assert_param(IS_TIM_CC5_INSTANCE(htim->Instance)); - - /* Configure the TIM Channel 5 in Output Compare */ - TIM_OC5_SetConfig(htim->Instance, sConfig); - break; - } - - case TIM_CHANNEL_6: - { - /* Check the parameters */ - assert_param(IS_TIM_CC6_INSTANCE(htim->Instance)); - - /* Configure the TIM Channel 6 in Output Compare */ - TIM_OC6_SetConfig(htim->Instance, sConfig); - break; - } - - default: - status = HAL_ERROR; - break; - } - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @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 Channel to configure - * 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, const TIM_IC_InitTypeDef *sConfig, uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* 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)); - - /* Process Locked */ - __HAL_LOCK(htim); - - 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 << 8U); - } - 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 if (Channel == TIM_CHANNEL_4) - { - /* 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 << 8U); - } - else - { - status = HAL_ERROR; - } - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @brief Initializes the TIM PWM channels according to the specified - * parameters in the TIM_OC_InitTypeDef. - * @param htim TIM PWM handle - * @param sConfig TIM PWM configuration structure - * @param Channel TIM Channels to be configured - * 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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 selected - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, - const TIM_OC_InitTypeDef *sConfig, - uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* 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_FAST_STATE(sConfig->OCFastMode)); - - /* Process Locked */ - __HAL_LOCK(htim); - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Check the parameters */ - 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: - { - /* Check the parameters */ - 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 << 8U; - break; - } - - case TIM_CHANNEL_3: - { - /* Check the parameters */ - 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: - { - /* Check the parameters */ - 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 << 8U; - break; - } - - case TIM_CHANNEL_5: - { - /* Check the parameters */ - assert_param(IS_TIM_CC5_INSTANCE(htim->Instance)); - - /* Configure the Channel 5 in PWM mode */ - TIM_OC5_SetConfig(htim->Instance, sConfig); - - /* Set the Preload enable bit for channel5*/ - htim->Instance->CCMR3 |= TIM_CCMR3_OC5PE; - - /* Configure the Output Fast mode */ - htim->Instance->CCMR3 &= ~TIM_CCMR3_OC5FE; - htim->Instance->CCMR3 |= sConfig->OCFastMode; - break; - } - - case TIM_CHANNEL_6: - { - /* Check the parameters */ - assert_param(IS_TIM_CC6_INSTANCE(htim->Instance)); - - /* Configure the Channel 6 in PWM mode */ - TIM_OC6_SetConfig(htim->Instance, sConfig); - - /* Set the Preload enable bit for channel6 */ - htim->Instance->CCMR3 |= TIM_CCMR3_OC6PE; - - /* Configure the Output Fast mode */ - htim->Instance->CCMR3 &= ~TIM_CCMR3_OC6FE; - htim->Instance->CCMR3 |= sConfig->OCFastMode << 8U; - break; - } - - default: - status = HAL_ERROR; - break; - } - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @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 output channel to configure - * 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 input Channel to configure - * 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 - * @note To output a waveform with a minimum delay user can enable the fast - * mode by calling the @ref __HAL_TIM_ENABLE_OCxFAST macro. Then CCx - * output is forced in response to the edge detection on TIx input, - * without taking in account the comparison. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef *sConfig, - uint32_t OutputChannel, uint32_t InputChannel) -{ - HAL_StatusTypeDef status = HAL_OK; - TIM_OC_InitTypeDef temp1; - - /* Check the parameters */ - assert_param(IS_TIM_OPM_CHANNELS(OutputChannel)); - assert_param(IS_TIM_OPM_CHANNELS(InputChannel)); - - if (OutputChannel != InputChannel) - { - /* Process Locked */ - __HAL_LOCK(htim); - - htim->State = HAL_TIM_STATE_BUSY; - - /* Extract the Output 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - 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: - status = HAL_ERROR; - break; - } - } - - htim->State = HAL_TIM_STATE_READY; - - __HAL_UNLOCK(htim); - - return status; - } - 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 where the DMA will start the Data write - * This parameter can be one 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_CCMR3 - * @arg TIM_DMABASE_CCR5 - * @arg TIM_DMABASE_CCR6 - * @arg TIM_DMABASE_DTR2 - * @arg TIM_DMABASE_ECR - * @arg TIM_DMABASE_TISEL - * @arg TIM_DMABASE_AF1 - * @arg TIM_DMABASE_AF2 - * @param BurstRequestSrc TIM DMA Request sources - * This parameter can be one 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_26TRANSFER. - * @note This function should be used only when BurstLength is equal to DMA data transfer length. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, - uint32_t BurstLength) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t BlockDataLength = 0; - uint32_t data_width; - const DMA_HandleTypeDef *hdma = NULL; - - assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); - - switch (BurstRequestSrc) - { - case TIM_DMA_UPDATE: - { - hdma = htim->hdma[TIM_DMA_ID_UPDATE]; - break; - } - case TIM_DMA_CC1: - { - hdma = htim->hdma[TIM_DMA_ID_CC1]; - break; - } - case TIM_DMA_CC2: - { - hdma = htim->hdma[TIM_DMA_ID_CC2]; - break; - } - case TIM_DMA_CC3: - { - hdma = htim->hdma[TIM_DMA_ID_CC3]; - break; - } - case TIM_DMA_CC4: - { - hdma = htim->hdma[TIM_DMA_ID_CC4]; - break; - } - case TIM_DMA_COM: - { - hdma = htim->hdma[TIM_DMA_ID_COMMUTATION]; - break; - } - case TIM_DMA_TRIGGER: - { - hdma = htim->hdma[TIM_DMA_ID_TRIGGER]; - break; - } - default: - status = HAL_ERROR; - break; - } - - if (hdma != NULL) - { - - if (((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) && (hdma->LinkedListQueue != 0U) - && (hdma->LinkedListQueue->Head != 0U)) - { - data_width = hdma->LinkedListQueue->Head->LinkRegisters[0] & DMA_CTR1_SDW_LOG2; - } - else - { - data_width = hdma->Init.SrcDataWidth; - } - - switch (data_width) - { - case DMA_SRC_DATAWIDTH_BYTE: - { - BlockDataLength = (BurstLength >> TIM_DCR_DBL_Pos) + 1UL; - break; - } - case DMA_SRC_DATAWIDTH_HALFWORD: - { - BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 2UL; - break; - } - case DMA_SRC_DATAWIDTH_WORD: - { - BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 4UL; - break; - } - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - status = HAL_TIM_DMABurst_MultiWriteStart(htim, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, - BlockDataLength); - } - } - - - return status; -} - -/** - * @brief Configure the DMA Burst to transfer multiple Data from the memory to the TIM peripheral - * @param htim TIM handle - * @param BurstBaseAddress TIM Base address from where the DMA will start the Data write - * This parameter can be one 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_CCMR3 - * @arg TIM_DMABASE_CCR5 - * @arg TIM_DMABASE_CCR6 - * @arg TIM_DMABASE_DTR2 - * @arg TIM_DMABASE_ECR - * @arg TIM_DMABASE_TISEL - * @arg TIM_DMABASE_AF1 - * @arg TIM_DMABASE_AF2 - * @param BurstRequestSrc TIM DMA Request sources - * This parameter can be one 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_26TRANSFER. - * @param DataLength Data length. This parameter can be one value - * between 1 and 0xFFFF. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_DMABurst_MultiWriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, - uint32_t BurstLength, uint32_t DataLength) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpDBSS = 0; - - /* 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)); - assert_param(IS_TIM_DMA_DATA_LENGTH(DataLength)); - - if (htim->DMABurstState == HAL_DMA_BURST_STATE_BUSY) - { - return HAL_BUSY; - } - else if (htim->DMABurstState == HAL_DMA_BURST_STATE_READY) - { - if ((BurstBuffer == NULL) && (BurstLength > 0U)) - { - return HAL_ERROR; - } - else - { - htim->DMABurstState = HAL_DMA_BURST_STATE_BUSY; - } - } - else - { - /* nothing to do */ - } - - switch (BurstRequestSrc) - { - case TIM_DMA_UPDATE: - { - /* Set the DMA Period elapsed callbacks */ - htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; - htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = TIM_DCR_DBSS_0; - break; - } - case TIM_DMA_CC1: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = TIM_DCR_DBSS_1; - break; - } - case TIM_DMA_CC2: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); - break; - } - case TIM_DMA_CC3: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = TIM_DCR_DBSS_2; - break; - } - case TIM_DMA_CC4: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_0); - break; - } - case TIM_DMA_COM: - { - /* Set the DMA commutation callbacks */ - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1); - break; - } - case TIM_DMA_TRIGGER: - { - /* Set the DMA trigger callbacks */ - htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; - htim->hdma[TIM_DMA_ID_TRIGGER]->XferHalfCpltCallback = TIM_DMATriggerHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, - (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); - break; - } - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Configure the DMA Burst Mode */ - htim->Instance->DCR = (BurstBaseAddress | BurstLength | tmpDBSS); - /* Enable the TIM DMA Request */ - __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); - - /* Abort the DMA transfer (at least disable the DMA channel) */ - switch (BurstRequestSrc) - { - case TIM_DMA_UPDATE: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); - break; - } - case TIM_DMA_CC1: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - case TIM_DMA_CC2: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - case TIM_DMA_CC3: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - case TIM_DMA_CC4: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - case TIM_DMA_COM: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]); - break; - } - case TIM_DMA_TRIGGER: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]); - break; - } - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the TIM Update DMA request */ - __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - } - - /* Return function status */ - return status; -} - -/** - * @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 where the DMA will start the Data read - * This parameter can be one 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_CCMR3 - * @arg TIM_DMABASE_CCR5 - * @arg TIM_DMABASE_CCR6 - * @arg TIM_DMABASE_DTR2 - * @arg TIM_DMABASE_ECR - * @arg TIM_DMABASE_TISEL - * @arg TIM_DMABASE_AF1 - * @arg TIM_DMABASE_AF2 - * @param BurstRequestSrc TIM DMA Request sources - * This parameter can be one 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_26TRANSFER. - * @note This function should be used only when BurstLength is equal to DMA data transfer length. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t BlockDataLength = 0; - uint32_t data_width; - const DMA_HandleTypeDef *hdma = NULL; - - assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); - - switch (BurstRequestSrc) - { - case TIM_DMA_UPDATE: - { - hdma = htim->hdma[TIM_DMA_ID_UPDATE]; - break; - } - case TIM_DMA_CC1: - { - hdma = htim->hdma[TIM_DMA_ID_CC1]; - break; - } - case TIM_DMA_CC2: - { - hdma = htim->hdma[TIM_DMA_ID_CC2]; - break; - } - case TIM_DMA_CC3: - { - hdma = htim->hdma[TIM_DMA_ID_CC3]; - break; - } - case TIM_DMA_CC4: - { - hdma = htim->hdma[TIM_DMA_ID_CC4]; - break; - } - case TIM_DMA_COM: - { - hdma = htim->hdma[TIM_DMA_ID_COMMUTATION]; - break; - } - case TIM_DMA_TRIGGER: - { - hdma = htim->hdma[TIM_DMA_ID_TRIGGER]; - break; - } - default: - status = HAL_ERROR; - break; - } - - if (hdma != NULL) - { - - if (((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) && (hdma->LinkedListQueue != 0U) - && (hdma->LinkedListQueue->Head != 0U)) - { - data_width = hdma->LinkedListQueue->Head->LinkRegisters[0] & DMA_CTR1_SDW_LOG2; - } - else - { - data_width = hdma->Init.SrcDataWidth; - } - - switch (data_width) - - { - case DMA_SRC_DATAWIDTH_BYTE: - { - BlockDataLength = ((BurstLength) >> TIM_DCR_DBL_Pos) + 1UL; - break; - } - case DMA_SRC_DATAWIDTH_HALFWORD: - { - BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 2UL; - break; - } - case DMA_SRC_DATAWIDTH_WORD: - { - BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 4UL; - break; - } - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - status = HAL_TIM_DMABurst_MultiReadStart(htim, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, - BlockDataLength); - } - } - - return status; -} - -/** - * @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 where the DMA will start the Data read - * This parameter can be one 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_CCMR3 - * @arg TIM_DMABASE_CCR5 - * @arg TIM_DMABASE_CCR6 - * @arg TIM_DMABASE_DTR2 - * @arg TIM_DMABASE_ECR - * @arg TIM_DMABASE_TISEL - * @arg TIM_DMABASE_AF1 - * @arg TIM_DMABASE_AF2 - * @param BurstRequestSrc TIM DMA Request sources - * This parameter can be one 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_26TRANSFER. - * @param DataLength Data length. This parameter can be one value - * between 1 and 0xFFFF. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_DMABurst_MultiReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, - uint32_t BurstRequestSrc, uint32_t *BurstBuffer, - uint32_t BurstLength, uint32_t DataLength) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpDBSS = 0; - - /* 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)); - assert_param(IS_TIM_DMA_DATA_LENGTH(DataLength)); - - if (htim->DMABurstState == HAL_DMA_BURST_STATE_BUSY) - { - return HAL_BUSY; - } - else if (htim->DMABurstState == HAL_DMA_BURST_STATE_READY) - { - if ((BurstBuffer == NULL) && (BurstLength > 0U)) - { - return HAL_ERROR; - } - else - { - htim->DMABurstState = HAL_DMA_BURST_STATE_BUSY; - } - } - else - { - /* nothing to do */ - } - switch (BurstRequestSrc) - { - case TIM_DMA_UPDATE: - { - /* Set the DMA Period elapsed callbacks */ - htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; - htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = TIM_DCR_DBSS_0; - break; - } - case TIM_DMA_CC1: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = TIM_DCR_DBSS_1; - break; - } - case TIM_DMA_CC2: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); - break; - } - case TIM_DMA_CC3: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = TIM_DCR_DBSS_2; - break; - } - case TIM_DMA_CC4: - { - /* Set the DMA capture callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_0); - break; - } - case TIM_DMA_COM: - { - /* Set the DMA commutation callbacks */ - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1); - break; - } - case TIM_DMA_TRIGGER: - { - /* Set the DMA trigger callbacks */ - htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; - htim->hdma[TIM_DMA_ID_TRIGGER]->XferHalfCpltCallback = TIM_DMATriggerHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, - DataLength) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Configure the DMA Burst Source Selection */ - tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); - break; - } - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Configure the DMA Burst Mode */ - htim->Instance->DCR = (BurstBaseAddress | BurstLength | tmpDBSS); - - /* Enable the TIM DMA Request */ - __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); - - /* Abort the DMA transfer (at least disable the DMA channel) */ - switch (BurstRequestSrc) - { - case TIM_DMA_UPDATE: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); - break; - } - case TIM_DMA_CC1: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - case TIM_DMA_CC2: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - case TIM_DMA_CC3: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - case TIM_DMA_CC4: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - case TIM_DMA_COM: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]); - break; - } - case TIM_DMA_TRIGGER: - { - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]); - break; - } - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the TIM Update DMA request */ - __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - } - - /* Return function status */ - return status; -} - -/** - * @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 - * @arg TIM_EVENTSOURCE_BREAK2: Timer Break2 event source - * @note Basic timers can only generate an update event. - * @note TIM_EVENTSOURCE_COM is relevant only with advanced timer instances. - * @note TIM_EVENTSOURCE_BREAK and TIM_EVENTSOURCE_BREAK2 are relevant - * only for timer instances supporting break input(s). - * @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 - * @arg TIM_CHANNEL_5: TIM Channel 5 - * @arg TIM_CHANNEL_6: TIM Channel 6 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, - const TIM_ClearInputConfigTypeDef *sClearInputConfig, - uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_TIM_OCXREF_CLEAR_INSTANCE(htim->Instance)); - assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource)); - - /* Process Locked */ - __HAL_LOCK(htim); - - htim->State = HAL_TIM_STATE_BUSY; - - switch (sClearInputConfig->ClearInputSource) - { - case TIM_CLEARINPUTSOURCE_NONE: - { - /* Clear the OCREF clear selection bit and the the ETR Bits */ - CLEAR_BIT(htim->Instance->SMCR, (TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); - break; - } - - case TIM_CLEARINPUTSOURCE_ETR: - { - /* Check the parameters */ - assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity)); - assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler)); - assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter)); - - /* When OCRef clear feature is used with ETR source, ETR prescaler must be off */ - if (sClearInputConfig->ClearInputPrescaler != TIM_CLEARINPUTPRESCALER_DIV1) - { - htim->State = HAL_TIM_STATE_READY; - __HAL_UNLOCK(htim); - return HAL_ERROR; - } - - TIM_ETR_SetConfig(htim->Instance, - sClearInputConfig->ClearInputPrescaler, - sClearInputConfig->ClearInputPolarity, - sClearInputConfig->ClearInputFilter); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - switch (Channel) - { - case TIM_CHANNEL_1: - { - if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) - { - /* Enable the OCREF clear feature for Channel 1 */ - SET_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC1CE); - } - else - { - /* Disable the OCREF clear feature for Channel 1 */ - CLEAR_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC1CE); - } - break; - } - case TIM_CHANNEL_2: - { - if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) - { - /* Enable the OCREF clear feature for Channel 2 */ - SET_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC2CE); - } - else - { - /* Disable the OCREF clear feature for Channel 2 */ - CLEAR_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC2CE); - } - break; - } - case TIM_CHANNEL_3: - { - if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) - { - /* Enable the OCREF clear feature for Channel 3 */ - SET_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC3CE); - } - else - { - /* Disable the OCREF clear feature for Channel 3 */ - CLEAR_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC3CE); - } - break; - } - case TIM_CHANNEL_4: - { - if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) - { - /* Enable the OCREF clear feature for Channel 4 */ - SET_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC4CE); - } - else - { - /* Disable the OCREF clear feature for Channel 4 */ - CLEAR_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC4CE); - } - break; - } - case TIM_CHANNEL_5: - { - if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) - { - /* Enable the OCREF clear feature for Channel 5 */ - SET_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC5CE); - } - else - { - /* Disable the OCREF clear feature for Channel 5 */ - CLEAR_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC5CE); - } - break; - } - case TIM_CHANNEL_6: - { - if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) - { - /* Enable the OCREF clear feature for Channel 6 */ - SET_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC6CE); - } - else - { - /* Disable the OCREF clear feature for Channel 6 */ - CLEAR_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC6CE); - } - break; - } - default: - break; - } - } - - htim->State = HAL_TIM_STATE_READY; - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @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, const TIM_ClockConfigTypeDef *sClockSourceConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Process Locked */ - __HAL_LOCK(htim); - - htim->State = HAL_TIM_STATE_BUSY; - - /* Check the parameters */ - assert_param(IS_TIM_CLOCKSOURCE(sClockSourceConfig->ClockSource)); - - /* 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)); - break; - } - - case TIM_CLOCKSOURCE_ETRMODE1: - { - /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/ - assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance)); - - /* Check ETR input conditioning related parameters */ - assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); - assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); - assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); - - /* Configure the ETR Clock source */ - TIM_ETR_SetConfig(htim->Instance, - sClockSourceConfig->ClockPrescaler, - sClockSourceConfig->ClockPolarity, - sClockSourceConfig->ClockFilter); - - /* Select the External clock mode1 and the ETRF trigger */ - tmpsmcr = htim->Instance->SMCR; - tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1); - /* Write to TIMx SMCR */ - htim->Instance->SMCR = tmpsmcr; - break; - } - - case TIM_CLOCKSOURCE_ETRMODE2: - { - /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/ - assert_param(IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(htim->Instance)); - - /* Check ETR input conditioning related parameters */ - assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); - assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); - assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); - - /* 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: - { - /* Check whether or not the timer instance supports external clock mode 1 */ - assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); - - /* Check TI1 input conditioning related parameters */ - assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); - assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); - - TIM_TI1_ConfigInputStage(htim->Instance, - sClockSourceConfig->ClockPolarity, - sClockSourceConfig->ClockFilter); - TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1); - break; - } - - case TIM_CLOCKSOURCE_TI2: - { - /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/ - assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); - - /* Check TI2 input conditioning related parameters */ - assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); - assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); - - TIM_TI2_ConfigInputStage(htim->Instance, - sClockSourceConfig->ClockPolarity, - sClockSourceConfig->ClockFilter); - TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2); - break; - } - - case TIM_CLOCKSOURCE_TI1ED: - { - /* Check whether or not the timer instance supports external clock mode 1 */ - assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); - - /* Check TI1 input conditioning related parameters */ - assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); - assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); - - TIM_TI1_ConfigInputStage(htim->Instance, - sClockSourceConfig->ClockPolarity, - sClockSourceConfig->ClockFilter); - TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED); - break; - } - - case TIM_CLOCKSOURCE_ITR0: - case TIM_CLOCKSOURCE_ITR1: - case TIM_CLOCKSOURCE_ITR2: - case TIM_CLOCKSOURCE_ITR3: - case TIM_CLOCKSOURCE_ITR4: - case TIM_CLOCKSOURCE_ITR5: - case TIM_CLOCKSOURCE_ITR6: - case TIM_CLOCKSOURCE_ITR7: - case TIM_CLOCKSOURCE_ITR8: - case TIM_CLOCKSOURCE_ITR9: - case TIM_CLOCKSOURCE_ITR10: - case TIM_CLOCKSOURCE_ITR11: - case TIM_CLOCKSOURCE_ITR13: - case TIM_CLOCKSOURCE_ITR14: - { - /* Check whether or not the timer instance supports internal trigger input */ - assert_param(IS_TIM_CLOCKSOURCE_INSTANCE((htim->Instance), sClockSourceConfig->ClockSource)); - - TIM_ITRx_SetConfig(htim->Instance, sClockSourceConfig->ClockSource); - break; - } - - default: - status = HAL_ERROR; - break; - } - htim->State = HAL_TIM_STATE_READY; - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @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; - - /* 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 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 Slave mode - * (Disable, Reset, Gated, Trigger, External clock mode 1, Reset + Trigger, Gated + Reset). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig) -{ - /* Check the parameters */ - assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); - assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); - assert_param(IS_TIM_TRIGGER_INSTANCE(htim->Instance, sSlaveConfig->InputTrigger)); - - __HAL_LOCK(htim); - - htim->State = HAL_TIM_STATE_BUSY; - - if (TIM_SlaveTimer_SetConfig(htim, sSlaveConfig) != HAL_OK) - { - htim->State = HAL_TIM_STATE_READY; - __HAL_UNLOCK(htim); - return HAL_ERROR; - } - - /* Disable Trigger Interrupt */ - __HAL_TIM_DISABLE_IT(htim, TIM_IT_TRIGGER); - - /* Disable Trigger DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_TRIGGER); - - htim->State = HAL_TIM_STATE_READY; - - __HAL_UNLOCK(htim); - - return HAL_OK; -} - -/** - * @brief Configures the TIM in Slave mode in interrupt 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 Slave mode - * (Disable, Reset, Gated, Trigger, External clock mode 1, Reset + Trigger, Gated + Reset). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro_IT(TIM_HandleTypeDef *htim, - const TIM_SlaveConfigTypeDef *sSlaveConfig) -{ - /* Check the parameters */ - assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); - assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); - assert_param(IS_TIM_TRIGGER_INSTANCE(htim->Instance, sSlaveConfig->InputTrigger)); - - __HAL_LOCK(htim); - - htim->State = HAL_TIM_STATE_BUSY; - - if (TIM_SlaveTimer_SetConfig(htim, sSlaveConfig) != HAL_OK) - { - htim->State = HAL_TIM_STATE_READY; - __HAL_UNLOCK(htim); - return HAL_ERROR; - } - - /* Enable Trigger Interrupt */ - __HAL_TIM_ENABLE_IT(htim, TIM_IT_TRIGGER); - - /* Disable Trigger DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_TRIGGER); - - 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(const TIM_HandleTypeDef *htim, uint32_t Channel) -{ - uint32_t tmpreg = 0U; - - 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; - } - - return tmpreg; -} - -/** - * @brief Start the DMA data transfer. - * @param hdma DMA handle - * @param src : The source memory Buffer address. - * @param dst : The destination memory Buffer address. - * @param length : The size of a source block transfer in byte. - * @retval HAL status - */ -HAL_StatusTypeDef TIM_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t src, uint32_t dst, - uint32_t length) -{ - HAL_StatusTypeDef status ; - - /* Enable the DMA channel */ - if ((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((hdma->LinkedListQueue != 0U) && (hdma->LinkedListQueue->Head != 0U)) - { - /* Enable the DMA channel */ - hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = length; - hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = src; - hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = dst; - - status = HAL_DMAEx_List_Start_IT(hdma); - } - else - { - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(hdma, src, dst, length); - } - - return status; -} - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group9 TIM Callbacks functions - * @brief TIM Callbacks functions - * -@verbatim - ============================================================================== - ##### TIM Callbacks functions ##### - ============================================================================== - [..] - This section provides TIM callback functions: - (+) TIM Period elapsed callback - (+) TIM Output Compare callback - (+) TIM Input capture callback - (+) TIM Trigger callback - (+) TIM Error callback - (+) TIM Index callback - (+) TIM Direction change callback - (+) TIM Index error callback - (+) TIM Transition 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Period elapsed half complete callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIM_PeriodElapsedHalfCpltCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIM_PeriodElapsedHalfCpltCallback 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Input Capture half complete callback in non-blocking mode - * @param htim TIM IC handle - * @retval None - */ -__weak void HAL_TIM_IC_CaptureHalfCpltCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIM_IC_CaptureHalfCpltCallback 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 PWM Pulse finished half complete callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIM_PWM_PulseFinishedHalfCpltCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIM_PWM_PulseFinishedHalfCpltCallback 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Hall Trigger detection half complete callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIM_TriggerHalfCpltCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIM_TriggerHalfCpltCallback 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIM_ErrorCallback could be implemented in the user file - */ -} - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User TIM callback to be used instead of the weak predefined callback - * @param htim tim handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_TIM_BASE_MSPINIT_CB_ID Base MspInit Callback ID - * @arg @ref HAL_TIM_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID - * @arg @ref HAL_TIM_IC_MSPINIT_CB_ID IC MspInit Callback ID - * @arg @ref HAL_TIM_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID - * @arg @ref HAL_TIM_OC_MSPINIT_CB_ID OC MspInit Callback ID - * @arg @ref HAL_TIM_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID - * @arg @ref HAL_TIM_PWM_MSPINIT_CB_ID PWM MspInit Callback ID - * @arg @ref HAL_TIM_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID - * @arg @ref HAL_TIM_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID - * @arg @ref HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID - * @arg @ref HAL_TIM_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID - * @arg @ref HAL_TIM_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID - * @arg @ref HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID - * @arg @ref HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID - * @arg @ref HAL_TIM_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID - * @arg @ref HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID - * @arg @ref HAL_TIM_TRIGGER_CB_ID Trigger Callback ID - * @arg @ref HAL_TIM_TRIGGER_HALF_CB_ID Trigger half complete Callback ID - * @arg @ref HAL_TIM_IC_CAPTURE_CB_ID Input Capture Callback ID - * @arg @ref HAL_TIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID - * @arg @ref HAL_TIM_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID - * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID - * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID - * @arg @ref HAL_TIM_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_TIM_COMMUTATION_CB_ID Commutation Callback ID - * @arg @ref HAL_TIM_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID - * @arg @ref HAL_TIM_BREAK_CB_ID Break Callback ID - * @arg @ref HAL_TIM_BREAK2_CB_ID Break2 Callback ID - * @arg @ref HAL_TIM_ENCODER_INDEX_CB_ID Encoder Index Callback ID - * @arg @ref HAL_TIM_DIRECTION_CHANGE_CB_ID Direction Change Callback ID - * @arg @ref HAL_TIM_INDEX_ERROR_CB_ID Index Error Callback ID - * @arg @ref HAL_TIM_TRANSITION_ERROR_CB_ID Transition Error Callback ID - * @param pCallback pointer to the callback function - * @retval status - */ -HAL_StatusTypeDef HAL_TIM_RegisterCallback(TIM_HandleTypeDef *htim, HAL_TIM_CallbackIDTypeDef CallbackID, - pTIM_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - return HAL_ERROR; - } - - if (htim->State == HAL_TIM_STATE_READY) - { - switch (CallbackID) - { - case HAL_TIM_BASE_MSPINIT_CB_ID : - htim->Base_MspInitCallback = pCallback; - break; - - case HAL_TIM_BASE_MSPDEINIT_CB_ID : - htim->Base_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_IC_MSPINIT_CB_ID : - htim->IC_MspInitCallback = pCallback; - break; - - case HAL_TIM_IC_MSPDEINIT_CB_ID : - htim->IC_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_OC_MSPINIT_CB_ID : - htim->OC_MspInitCallback = pCallback; - break; - - case HAL_TIM_OC_MSPDEINIT_CB_ID : - htim->OC_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_PWM_MSPINIT_CB_ID : - htim->PWM_MspInitCallback = pCallback; - break; - - case HAL_TIM_PWM_MSPDEINIT_CB_ID : - htim->PWM_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : - htim->OnePulse_MspInitCallback = pCallback; - break; - - case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : - htim->OnePulse_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_ENCODER_MSPINIT_CB_ID : - htim->Encoder_MspInitCallback = pCallback; - break; - - case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : - htim->Encoder_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : - htim->HallSensor_MspInitCallback = pCallback; - break; - - case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : - htim->HallSensor_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_PERIOD_ELAPSED_CB_ID : - htim->PeriodElapsedCallback = pCallback; - break; - - case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID : - htim->PeriodElapsedHalfCpltCallback = pCallback; - break; - - case HAL_TIM_TRIGGER_CB_ID : - htim->TriggerCallback = pCallback; - break; - - case HAL_TIM_TRIGGER_HALF_CB_ID : - htim->TriggerHalfCpltCallback = pCallback; - break; - - case HAL_TIM_IC_CAPTURE_CB_ID : - htim->IC_CaptureCallback = pCallback; - break; - - case HAL_TIM_IC_CAPTURE_HALF_CB_ID : - htim->IC_CaptureHalfCpltCallback = pCallback; - break; - - case HAL_TIM_OC_DELAY_ELAPSED_CB_ID : - htim->OC_DelayElapsedCallback = pCallback; - break; - - case HAL_TIM_PWM_PULSE_FINISHED_CB_ID : - htim->PWM_PulseFinishedCallback = pCallback; - break; - - case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID : - htim->PWM_PulseFinishedHalfCpltCallback = pCallback; - break; - - case HAL_TIM_ERROR_CB_ID : - htim->ErrorCallback = pCallback; - break; - - case HAL_TIM_COMMUTATION_CB_ID : - htim->CommutationCallback = pCallback; - break; - - case HAL_TIM_COMMUTATION_HALF_CB_ID : - htim->CommutationHalfCpltCallback = pCallback; - break; - - case HAL_TIM_BREAK_CB_ID : - htim->BreakCallback = pCallback; - break; - - case HAL_TIM_BREAK2_CB_ID : - htim->Break2Callback = pCallback; - break; - - case HAL_TIM_ENCODER_INDEX_CB_ID : - htim->EncoderIndexCallback = pCallback; - break; - - case HAL_TIM_DIRECTION_CHANGE_CB_ID : - htim->DirectionChangeCallback = pCallback; - break; - - case HAL_TIM_INDEX_ERROR_CB_ID : - htim->IndexErrorCallback = pCallback; - break; - - case HAL_TIM_TRANSITION_ERROR_CB_ID : - htim->TransitionErrorCallback = pCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (htim->State == HAL_TIM_STATE_RESET) - { - switch (CallbackID) - { - case HAL_TIM_BASE_MSPINIT_CB_ID : - htim->Base_MspInitCallback = pCallback; - break; - - case HAL_TIM_BASE_MSPDEINIT_CB_ID : - htim->Base_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_IC_MSPINIT_CB_ID : - htim->IC_MspInitCallback = pCallback; - break; - - case HAL_TIM_IC_MSPDEINIT_CB_ID : - htim->IC_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_OC_MSPINIT_CB_ID : - htim->OC_MspInitCallback = pCallback; - break; - - case HAL_TIM_OC_MSPDEINIT_CB_ID : - htim->OC_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_PWM_MSPINIT_CB_ID : - htim->PWM_MspInitCallback = pCallback; - break; - - case HAL_TIM_PWM_MSPDEINIT_CB_ID : - htim->PWM_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : - htim->OnePulse_MspInitCallback = pCallback; - break; - - case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : - htim->OnePulse_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_ENCODER_MSPINIT_CB_ID : - htim->Encoder_MspInitCallback = pCallback; - break; - - case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : - htim->Encoder_MspDeInitCallback = pCallback; - break; - - case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : - htim->HallSensor_MspInitCallback = pCallback; - break; - - case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : - htim->HallSensor_MspDeInitCallback = pCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a TIM callback - * TIM callback is redirected to the weak predefined callback - * @param htim tim handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_TIM_BASE_MSPINIT_CB_ID Base MspInit Callback ID - * @arg @ref HAL_TIM_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID - * @arg @ref HAL_TIM_IC_MSPINIT_CB_ID IC MspInit Callback ID - * @arg @ref HAL_TIM_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID - * @arg @ref HAL_TIM_OC_MSPINIT_CB_ID OC MspInit Callback ID - * @arg @ref HAL_TIM_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID - * @arg @ref HAL_TIM_PWM_MSPINIT_CB_ID PWM MspInit Callback ID - * @arg @ref HAL_TIM_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID - * @arg @ref HAL_TIM_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID - * @arg @ref HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID - * @arg @ref HAL_TIM_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID - * @arg @ref HAL_TIM_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID - * @arg @ref HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID - * @arg @ref HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID - * @arg @ref HAL_TIM_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID - * @arg @ref HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID - * @arg @ref HAL_TIM_TRIGGER_CB_ID Trigger Callback ID - * @arg @ref HAL_TIM_TRIGGER_HALF_CB_ID Trigger half complete Callback ID - * @arg @ref HAL_TIM_IC_CAPTURE_CB_ID Input Capture Callback ID - * @arg @ref HAL_TIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID - * @arg @ref HAL_TIM_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID - * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID - * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID - * @arg @ref HAL_TIM_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_TIM_COMMUTATION_CB_ID Commutation Callback ID - * @arg @ref HAL_TIM_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID - * @arg @ref HAL_TIM_BREAK_CB_ID Break Callback ID - * @arg @ref HAL_TIM_BREAK2_CB_ID Break2 Callback ID - * @arg @ref HAL_TIM_ENCODER_INDEX_CB_ID Encoder Index Callback ID - * @arg @ref HAL_TIM_DIRECTION_CHANGE_CB_ID Direction Change Callback ID - * @arg @ref HAL_TIM_INDEX_ERROR_CB_ID Index Error Callback ID - * @arg @ref HAL_TIM_TRANSITION_ERROR_CB_ID Transition Error Callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_TIM_UnRegisterCallback(TIM_HandleTypeDef *htim, HAL_TIM_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (htim->State == HAL_TIM_STATE_READY) - { - switch (CallbackID) - { - case HAL_TIM_BASE_MSPINIT_CB_ID : - /* Legacy weak Base MspInit Callback */ - htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; - break; - - case HAL_TIM_BASE_MSPDEINIT_CB_ID : - /* Legacy weak Base Msp DeInit Callback */ - htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; - break; - - case HAL_TIM_IC_MSPINIT_CB_ID : - /* Legacy weak IC Msp Init Callback */ - htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; - break; - - case HAL_TIM_IC_MSPDEINIT_CB_ID : - /* Legacy weak IC Msp DeInit Callback */ - htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; - break; - - case HAL_TIM_OC_MSPINIT_CB_ID : - /* Legacy weak OC Msp Init Callback */ - htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; - break; - - case HAL_TIM_OC_MSPDEINIT_CB_ID : - /* Legacy weak OC Msp DeInit Callback */ - htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; - break; - - case HAL_TIM_PWM_MSPINIT_CB_ID : - /* Legacy weak PWM Msp Init Callback */ - htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; - break; - - case HAL_TIM_PWM_MSPDEINIT_CB_ID : - /* Legacy weak PWM Msp DeInit Callback */ - htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; - break; - - case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : - /* Legacy weak One Pulse Msp Init Callback */ - htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; - break; - - case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : - /* Legacy weak One Pulse Msp DeInit Callback */ - htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; - break; - - case HAL_TIM_ENCODER_MSPINIT_CB_ID : - /* Legacy weak Encoder Msp Init Callback */ - htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; - break; - - case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : - /* Legacy weak Encoder Msp DeInit Callback */ - htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; - break; - - case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : - /* Legacy weak Hall Sensor Msp Init Callback */ - htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; - break; - - case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : - /* Legacy weak Hall Sensor Msp DeInit Callback */ - htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; - break; - - case HAL_TIM_PERIOD_ELAPSED_CB_ID : - /* Legacy weak Period Elapsed Callback */ - htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; - break; - - case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID : - /* Legacy weak Period Elapsed half complete Callback */ - htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; - break; - - case HAL_TIM_TRIGGER_CB_ID : - /* Legacy weak Trigger Callback */ - htim->TriggerCallback = HAL_TIM_TriggerCallback; - break; - - case HAL_TIM_TRIGGER_HALF_CB_ID : - /* Legacy weak Trigger half complete Callback */ - htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; - break; - - case HAL_TIM_IC_CAPTURE_CB_ID : - /* Legacy weak IC Capture Callback */ - htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; - break; - - case HAL_TIM_IC_CAPTURE_HALF_CB_ID : - /* Legacy weak IC Capture half complete Callback */ - htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; - break; - - case HAL_TIM_OC_DELAY_ELAPSED_CB_ID : - /* Legacy weak OC Delay Elapsed Callback */ - htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; - break; - - case HAL_TIM_PWM_PULSE_FINISHED_CB_ID : - /* Legacy weak PWM Pulse Finished Callback */ - htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; - break; - - case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID : - /* Legacy weak PWM Pulse Finished half complete Callback */ - htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; - break; - - case HAL_TIM_ERROR_CB_ID : - /* Legacy weak Error Callback */ - htim->ErrorCallback = HAL_TIM_ErrorCallback; - break; - - case HAL_TIM_COMMUTATION_CB_ID : - /* Legacy weak Commutation Callback */ - htim->CommutationCallback = HAL_TIMEx_CommutCallback; - break; - - case HAL_TIM_COMMUTATION_HALF_CB_ID : - /* Legacy weak Commutation half complete Callback */ - htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; - break; - - case HAL_TIM_BREAK_CB_ID : - /* Legacy weak Break Callback */ - htim->BreakCallback = HAL_TIMEx_BreakCallback; - break; - - case HAL_TIM_BREAK2_CB_ID : - /* Legacy weak Break2 Callback */ - htim->Break2Callback = HAL_TIMEx_Break2Callback; - break; - - case HAL_TIM_ENCODER_INDEX_CB_ID : - /* Legacy weak Encoder Index Callback */ - htim->EncoderIndexCallback = HAL_TIMEx_EncoderIndexCallback; - break; - - case HAL_TIM_DIRECTION_CHANGE_CB_ID : - /* Legacy weak Direction Change Callback */ - htim->DirectionChangeCallback = HAL_TIMEx_DirectionChangeCallback; - break; - - case HAL_TIM_INDEX_ERROR_CB_ID : - /* Legacy weak Index Error Callback */ - htim->IndexErrorCallback = HAL_TIMEx_IndexErrorCallback; - break; - - case HAL_TIM_TRANSITION_ERROR_CB_ID : - /* Legacy weak Transition Error Callback */ - htim->TransitionErrorCallback = HAL_TIMEx_TransitionErrorCallback; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (htim->State == HAL_TIM_STATE_RESET) - { - switch (CallbackID) - { - case HAL_TIM_BASE_MSPINIT_CB_ID : - /* Legacy weak Base MspInit Callback */ - htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; - break; - - case HAL_TIM_BASE_MSPDEINIT_CB_ID : - /* Legacy weak Base Msp DeInit Callback */ - htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; - break; - - case HAL_TIM_IC_MSPINIT_CB_ID : - /* Legacy weak IC Msp Init Callback */ - htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; - break; - - case HAL_TIM_IC_MSPDEINIT_CB_ID : - /* Legacy weak IC Msp DeInit Callback */ - htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; - break; - - case HAL_TIM_OC_MSPINIT_CB_ID : - /* Legacy weak OC Msp Init Callback */ - htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; - break; - - case HAL_TIM_OC_MSPDEINIT_CB_ID : - /* Legacy weak OC Msp DeInit Callback */ - htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; - break; - - case HAL_TIM_PWM_MSPINIT_CB_ID : - /* Legacy weak PWM Msp Init Callback */ - htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; - break; - - case HAL_TIM_PWM_MSPDEINIT_CB_ID : - /* Legacy weak PWM Msp DeInit Callback */ - htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; - break; - - case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : - /* Legacy weak One Pulse Msp Init Callback */ - htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; - break; - - case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : - /* Legacy weak One Pulse Msp DeInit Callback */ - htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; - break; - - case HAL_TIM_ENCODER_MSPINIT_CB_ID : - /* Legacy weak Encoder Msp Init Callback */ - htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; - break; - - case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : - /* Legacy weak Encoder Msp DeInit Callback */ - htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; - break; - - case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : - /* Legacy weak Hall Sensor Msp Init Callback */ - htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; - break; - - case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : - /* Legacy weak Hall Sensor Msp DeInit Callback */ - htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; - break; - - default : - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup TIM_Exported_Functions_Group10 TIM Peripheral State functions - * @brief TIM 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 Return the TIM Base handle state. - * @param htim TIM Base handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return the TIM OC handle state. - * @param htim TIM Output Compare handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return the TIM PWM handle state. - * @param htim TIM handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return the TIM Input Capture handle state. - * @param htim TIM IC handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return the TIM One Pulse Mode handle state. - * @param htim TIM OPM handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return the TIM Encoder Mode handle state. - * @param htim TIM Encoder Interface handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return the TIM Encoder Mode handle state. - * @param htim TIM handle - * @retval Active channel - */ -HAL_TIM_ActiveChannel HAL_TIM_GetActiveChannel(const TIM_HandleTypeDef *htim) -{ - return htim->Channel; -} - -/** - * @brief Return actual state of the TIM channel. - * @param htim TIM handle - * @param Channel 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 - * @arg TIM_CHANNEL_5: TIM Channel 5 - * @arg TIM_CHANNEL_6: TIM Channel 6 - * @retval TIM Channel state - */ -HAL_TIM_ChannelStateTypeDef HAL_TIM_GetChannelState(const TIM_HandleTypeDef *htim, uint32_t Channel) -{ - HAL_TIM_ChannelStateTypeDef channel_state; - - /* Check the parameters */ - assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); - - channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); - - return channel_state; -} - -/** - * @brief Return actual state of a DMA burst operation. - * @param htim TIM handle - * @retval DMA burst state - */ -HAL_TIM_DMABurstStateTypeDef HAL_TIM_DMABurstState(const TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); - - return htim->DMABurstState; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup TIM_Private_Functions TIM Private Functions - * @{ - */ - -/** - * @brief TIM DMA error callback - * @param hdma pointer to DMA handle. - * @retval None - */ -void TIM_DMAError(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); - } - else - { - htim->State = HAL_TIM_STATE_READY; - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->ErrorCallback(htim); -#else - HAL_TIM_ErrorCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief TIM DMA Delay Pulse complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -static void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->PWM_PulseFinishedCallback(htim); -#else - HAL_TIM_PWM_PulseFinishedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief TIM DMA Delay Pulse half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void TIM_DMADelayPulseHalfCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->PWM_PulseFinishedHalfCpltCallback(htim); -#else - HAL_TIM_PWM_PulseFinishedHalfCpltCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief TIM DMA Capture complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IC_CaptureCallback(htim); -#else - HAL_TIM_IC_CaptureCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief TIM DMA Capture half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void TIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->IC_CaptureHalfCpltCallback(htim); -#else - HAL_TIM_IC_CaptureHalfCpltCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @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; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->PeriodElapsedCallback(htim); -#else - HAL_TIM_PeriodElapsedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ -} - -/** - * @brief TIM DMA Period Elapse half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -static void TIM_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->PeriodElapsedHalfCpltCallback(htim); -#else - HAL_TIM_PeriodElapsedHalfCpltCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ -} - -/** - * @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; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->TriggerCallback(htim); -#else - HAL_TIM_TriggerCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ -} - -/** - * @brief TIM DMA Trigger half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -static void TIM_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->TriggerHalfCpltCallback(htim); -#else - HAL_TIM_TriggerHalfCpltCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ -} - -/** - * @brief Time Base configuration - * @param TIMx TIM peripheral - * @param Structure TIM Base configuration structure - * @retval None - */ -void TIM_Base_SetConfig(TIM_TypeDef *TIMx, const TIM_Base_InitTypeDef *Structure) -{ - uint32_t tmpcr1; - tmpcr1 = TIMx->CR1; - - /* Set TIM Time Base Unit parameters ---------------------------------------*/ - if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) - { - /* Select the Counter Mode */ - tmpcr1 &= ~(TIM_CR1_DIR | TIM_CR1_CMS); - tmpcr1 |= Structure->CounterMode; - } - - if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) - { - /* Set the clock division */ - tmpcr1 &= ~TIM_CR1_CKD; - tmpcr1 |= (uint32_t)Structure->ClockDivision; - } - - /* Set the auto-reload preload */ - MODIFY_REG(tmpcr1, TIM_CR1_ARPE, Structure->AutoReloadPreload); - - TIMx->CR1 = tmpcr1; - - /* Set the Autoreload value */ - TIMx->ARR = (uint32_t)Structure->Period ; - - /* Set the Prescaler value */ - TIMx->PSC = Structure->Prescaler; - - if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) - { - /* Set the Repetition Counter value */ - TIMx->RCR = Structure->RepetitionCounter; - } - - /* Generate an update event to reload the Prescaler - and the repetition counter (only for advanced timer) value immediately */ - TIMx->EGR = TIM_EGR_UG; - - /* Check if the update flag is set after the Update Generation, if so clear the UIF flag */ - if (HAL_IS_BIT_SET(TIMx->SR, TIM_FLAG_UPDATE)) - { - /* Clear the update flag */ - CLEAR_BIT(TIMx->SR, TIM_FLAG_UPDATE); - } -} - -/** - * @brief Timer Output Compare 1 configuration - * @param TIMx to select the TIM peripheral - * @param OC_Config The output configuration structure - * @retval None - */ -static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) -{ - uint32_t tmpccmrx; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Get the TIMx CCER register value */ - tmpccer = TIMx->CCER; - - /* Disable the Channel 1: Reset the CC1E Bit */ - TIMx->CCER &= ~TIM_CCER_CC1E; - - /* 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_CCXN_INSTANCE(TIMx, TIM_CHANNEL_1)) - { - /* Check parameters */ - assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); - - /* 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; - } - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - /* Check parameters */ - assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); - assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); - - /* 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 Timer Output Compare 2 configuration - * @param TIMx to select the TIM peripheral - * @param OC_Config The output configuration structure - * @retval None - */ -void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) -{ - uint32_t tmpccmrx; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Get the TIMx CCER register value */ - tmpccer = TIMx->CCER; - - /* Disable the Channel 2: Reset the CC2E Bit */ - TIMx->CCER &= ~TIM_CCER_CC2E; - - /* 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 << 8U); - - /* Reset the Output Polarity level */ - tmpccer &= ~TIM_CCER_CC2P; - /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 4U); - - if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2)) - { - assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); - - /* Reset the Output N Polarity level */ - tmpccer &= ~TIM_CCER_CC2NP; - /* Set the Output N Polarity */ - tmpccer |= (OC_Config->OCNPolarity << 4U); - /* Reset the Output N State */ - tmpccer &= ~TIM_CCER_CC2NE; - } - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - /* Check parameters */ - assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); - assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); - - /* 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 << 2U); - /* Set the Output N Idle state */ - tmpcr2 |= (OC_Config->OCNIdleState << 2U); - } - - /* 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 Timer Output Compare 3 configuration - * @param TIMx to select the TIM peripheral - * @param OC_Config The output configuration structure - * @retval None - */ -static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) -{ - uint32_t tmpccmrx; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Get the TIMx CCER register value */ - tmpccer = TIMx->CCER; - - /* Disable the Channel 3: Reset the CC2E Bit */ - TIMx->CCER &= ~TIM_CCER_CC3E; - - /* 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 << 8U); - - if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3)) - { - assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); - - /* Reset the Output N Polarity level */ - tmpccer &= ~TIM_CCER_CC3NP; - /* Set the Output N Polarity */ - tmpccer |= (OC_Config->OCNPolarity << 8U); - /* Reset the Output N State */ - tmpccer &= ~TIM_CCER_CC3NE; - } - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - /* Check parameters */ - assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); - assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); - - /* 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 << 4U); - /* Set the Output N Idle state */ - tmpcr2 |= (OC_Config->OCNIdleState << 4U); - } - - /* 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 Timer Output Compare 4 configuration - * @param TIMx to select the TIM peripheral - * @param OC_Config The output configuration structure - * @retval None - */ -static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) -{ - uint32_t tmpccmrx; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Get the TIMx CCER register value */ - tmpccer = TIMx->CCER; - - /* Disable the Channel 4: Reset the CC4E Bit */ - TIMx->CCER &= ~TIM_CCER_CC4E; - - /* 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 << 8U); - - /* Reset the Output Polarity level */ - tmpccer &= ~TIM_CCER_CC4P; - /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 12U); - - if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_4)) - { - assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); - - /* Reset the Output N Polarity level */ - tmpccer &= ~TIM_CCER_CC4NP; - /* Set the Output N Polarity */ - tmpccer |= (OC_Config->OCNPolarity << 12U); - /* Reset the Output N State */ - tmpccer &= ~TIM_CCER_CC4NE; - } - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - /* Check parameters */ - assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); - assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); - - /* Reset the Output Compare IDLE State */ - tmpcr2 &= ~TIM_CR2_OIS4; - /* Reset the Output Compare N IDLE State */ - tmpcr2 &= ~TIM_CR2_OIS4N; - - /* Set the Output Idle state */ - tmpcr2 |= (OC_Config->OCIdleState << 6U); - /* Set the Output N Idle state */ - tmpcr2 |= (OC_Config->OCNIdleState << 6U); - } - - /* 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 Timer Output Compare 5 configuration - * @param TIMx to select the TIM peripheral - * @param OC_Config The output configuration structure - * @retval None - */ -static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, - const TIM_OC_InitTypeDef *OC_Config) -{ - uint32_t tmpccmrx; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Get the TIMx CCER register value */ - tmpccer = TIMx->CCER; - - /* Disable the output: Reset the CCxE Bit */ - TIMx->CCER &= ~TIM_CCER_CC5E; - - /* Get the TIMx CR2 register value */ - tmpcr2 = TIMx->CR2; - /* Get the TIMx CCMR1 register value */ - tmpccmrx = TIMx->CCMR3; - - /* Reset the Output Compare Mode Bits */ - tmpccmrx &= ~(TIM_CCMR3_OC5M); - /* Select the Output Compare Mode */ - tmpccmrx |= OC_Config->OCMode; - - /* Reset the Output Polarity level */ - tmpccer &= ~TIM_CCER_CC5P; - /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 16U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - /* Reset the Output Compare IDLE State */ - tmpcr2 &= ~TIM_CR2_OIS5; - /* Set the Output Idle state */ - tmpcr2 |= (OC_Config->OCIdleState << 8U); - } - /* Write to TIMx CR2 */ - TIMx->CR2 = tmpcr2; - - /* Write to TIMx CCMR3 */ - TIMx->CCMR3 = tmpccmrx; - - /* Set the Capture Compare Register value */ - TIMx->CCR5 = OC_Config->Pulse; - - /* Write to TIMx CCER */ - TIMx->CCER = tmpccer; -} - -/** - * @brief Timer Output Compare 6 configuration - * @param TIMx to select the TIM peripheral - * @param OC_Config The output configuration structure - * @retval None - */ -static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, - const TIM_OC_InitTypeDef *OC_Config) -{ - uint32_t tmpccmrx; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Get the TIMx CCER register value */ - tmpccer = TIMx->CCER; - - /* Disable the output: Reset the CCxE Bit */ - TIMx->CCER &= ~TIM_CCER_CC6E; - - /* Get the TIMx CR2 register value */ - tmpcr2 = TIMx->CR2; - /* Get the TIMx CCMR1 register value */ - tmpccmrx = TIMx->CCMR3; - - /* Reset the Output Compare Mode Bits */ - tmpccmrx &= ~(TIM_CCMR3_OC6M); - /* Select the Output Compare Mode */ - tmpccmrx |= (OC_Config->OCMode << 8U); - - /* Reset the Output Polarity level */ - tmpccer &= (uint32_t)~TIM_CCER_CC6P; - /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 20U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - /* Reset the Output Compare IDLE State */ - tmpcr2 &= ~TIM_CR2_OIS6; - /* Set the Output Idle state */ - tmpcr2 |= (OC_Config->OCIdleState << 10U); - } - - /* Write to TIMx CR2 */ - TIMx->CR2 = tmpcr2; - - /* Write to TIMx CCMR3 */ - TIMx->CCMR3 = tmpccmrx; - - /* Set the Capture Compare Register value */ - TIMx->CCR6 = OC_Config->Pulse; - - /* Write to TIMx CCER */ - TIMx->CCER = tmpccer; -} - -/** - * @brief Slave Timer configuration function - * @param htim TIM handle - * @param sSlaveConfig Slave timer configuration - * @retval None - */ -static HAL_StatusTypeDef TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, - const TIM_SlaveConfigTypeDef *sSlaveConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - uint32_t tmpccmr1; - uint32_t tmpccer; - - /* 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_CLOCKSOURCE_ETRMODE1_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)); - - if ((sSlaveConfig->SlaveMode == TIM_SLAVEMODE_GATED) || \ - (sSlaveConfig->SlaveMode == TIM_SLAVEMODE_COMBINED_GATEDRESET)) - { - return HAL_ERROR; - } - - /* 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) << 4U); - - /* 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: - case TIM_TS_ITR1: - case TIM_TS_ITR2: - case TIM_TS_ITR3: - case TIM_TS_ITR4: - case TIM_TS_ITR5: - case TIM_TS_ITR6: - case TIM_TS_ITR7: - case TIM_TS_ITR8: - case TIM_TS_ITR9: - case TIM_TS_ITR10: - case TIM_TS_ITR11: - case TIM_TS_ITR13: - case TIM_TS_ITR14: - { - /* Check the parameter */ - assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE((htim->Instance), sSlaveConfig->InputTrigger)); - break; - } - - default: - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @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 - * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI2FP1 - * (on channel2 path) is used as the input signal. Therefore CCMR1 must be - * protected against un-initialized filter and polarity values. - */ -void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, - uint32_t TIM_ICFilter) -{ - uint32_t tmpccmr1; - uint32_t tmpccer; - - /* Disable the Channel 1: Reset the CC1E Bit */ - tmpccer = TIMx->CCER; - TIMx->CCER &= ~TIM_CCER_CC1E; - tmpccmr1 = TIMx->CCMR1; - - /* Select the Input */ - if (IS_TIM_CC2_INSTANCE(TIMx) != RESET) - { - tmpccmr1 &= ~TIM_CCMR1_CC1S; - tmpccmr1 |= TIM_ICSelection; - } - else - { - tmpccmr1 |= TIM_CCMR1_CC1S_0; - } - - /* Set the filter */ - tmpccmr1 &= ~TIM_CCMR1_IC1F; - tmpccmr1 |= ((TIM_ICFilter << 4U) & TIM_CCMR1_IC1F); - - /* Select the Polarity and set the CC1E Bit */ - tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); - tmpccer |= (TIM_ICPolarity & (TIM_CCER_CC1P | TIM_CCER_CC1NP)); - - /* 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; - uint32_t tmpccer; - - /* 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 << 4U); - - /* 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 - * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI1FP2 - * (on channel1 path) is used as the input signal. Therefore CCMR1 must be - * protected against un-initialized filter and polarity values. - */ -static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, - uint32_t TIM_ICFilter) -{ - uint32_t tmpccmr1; - uint32_t tmpccer; - - /* Disable the Channel 2: Reset the CC2E Bit */ - tmpccer = TIMx->CCER; - TIMx->CCER &= ~TIM_CCER_CC2E; - tmpccmr1 = TIMx->CCMR1; - - /* Select the Input */ - tmpccmr1 &= ~TIM_CCMR1_CC2S; - tmpccmr1 |= (TIM_ICSelection << 8U); - - /* Set the filter */ - tmpccmr1 &= ~TIM_CCMR1_IC2F; - tmpccmr1 |= ((TIM_ICFilter << 12U) & TIM_CCMR1_IC2F); - - /* Select the Polarity and set the CC2E Bit */ - tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= ((TIM_ICPolarity << 4U) & (TIM_CCER_CC2P | TIM_CCER_CC2NP)); - - /* 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; - uint32_t tmpccer; - - /* Disable the Channel 2: Reset the CC2E Bit */ - tmpccer = TIMx->CCER; - TIMx->CCER &= ~TIM_CCER_CC2E; - tmpccmr1 = TIMx->CCMR1; - - /* Set the filter */ - tmpccmr1 &= ~TIM_CCMR1_IC2F; - tmpccmr1 |= (TIM_ICFilter << 12U); - - /* Select the Polarity and set the CC2E Bit */ - tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= (TIM_ICPolarity << 4U); - - /* 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 - * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI3FP4 - * (on channel1 path) is used as the input signal. Therefore CCMR2 must be - * protected against un-initialized filter and polarity values. - */ -static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, - uint32_t TIM_ICFilter) -{ - uint32_t tmpccmr2; - uint32_t tmpccer; - - /* Disable the Channel 3: Reset the CC3E Bit */ - tmpccer = TIMx->CCER; - TIMx->CCER &= ~TIM_CCER_CC3E; - tmpccmr2 = TIMx->CCMR2; - - /* Select the Input */ - tmpccmr2 &= ~TIM_CCMR2_CC3S; - tmpccmr2 |= TIM_ICSelection; - - /* Set the filter */ - tmpccmr2 &= ~TIM_CCMR2_IC3F; - tmpccmr2 |= ((TIM_ICFilter << 4U) & TIM_CCMR2_IC3F); - - /* Select the Polarity and set the CC3E Bit */ - tmpccer &= ~(TIM_CCER_CC3P | TIM_CCER_CC3NP); - tmpccer |= ((TIM_ICPolarity << 8U) & (TIM_CCER_CC3P | TIM_CCER_CC3NP)); - - /* 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. - * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI4FP3 - * (on channel1 path) is used as the input signal. Therefore CCMR2 must be - * protected against un-initialized filter and polarity values. - * @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; - uint32_t tmpccer; - - /* Disable the Channel 4: Reset the CC4E Bit */ - tmpccer = TIMx->CCER; - TIMx->CCER &= ~TIM_CCER_CC4E; - tmpccmr2 = TIMx->CCMR2; - - /* Select the Input */ - tmpccmr2 &= ~TIM_CCMR2_CC4S; - tmpccmr2 |= (TIM_ICSelection << 8U); - - /* Set the filter */ - tmpccmr2 &= ~TIM_CCMR2_IC4F; - tmpccmr2 |= ((TIM_ICFilter << 12U) & TIM_CCMR2_IC4F); - - /* Select the Polarity and set the CC4E Bit */ - tmpccer &= ~(TIM_CCER_CC4P | TIM_CCER_CC4NP); - tmpccer |= ((TIM_ICPolarity << 12U) & (TIM_CCER_CC4P | TIM_CCER_CC4NP)); - - /* 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_CLOCKSOURCE_ITR3: Internal Trigger 3 - * @arg TIM_CLOCKSOURCE_ITR4: Internal Trigger 4 - * @arg TIM_CLOCKSOURCE_ITR5: Internal Trigger 5 - * @arg TIM_CLOCKSOURCE_ITR6: Internal Trigger 6 - * @arg TIM_CLOCKSOURCE_ITR7: Internal Trigger 7 - * @arg TIM_CLOCKSOURCE_ITR8: Internal Trigger 8 - * @arg TIM_CLOCKSOURCE_ITR9: Internal Trigger 9 - * @arg TIM_CLOCKSOURCE_ITR10: Internal Trigger 10 - * @arg TIM_CLOCKSOURCE_ITR11: Internal Trigger 11 - * @arg TIM_CLOCKSOURCE_ITR13: Internal Trigger 13 - * @arg TIM_CLOCKSOURCE_ITR14: Internal Trigger 14 - * @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, uint32_t InputTriggerSource) -{ - uint32_t tmpsmcr; - - /* 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 |= (InputTriggerSource | 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_ETRPRESCALER_DIV1: ETRP Prescaler OFF. - * @arg TIM_ETRPRESCALER_DIV2: ETRP frequency divided by 2. - * @arg TIM_ETRPRESCALER_DIV4: ETRP frequency divided by 4. - * @arg TIM_ETRPRESCALER_DIV8: ETRP frequency divided by 8. - * @param TIM_ExtTRGPolarity The external Trigger Polarity. - * This parameter can be one of the following values: - * @arg TIM_ETRPOLARITY_INVERTED: active low or falling edge active. - * @arg TIM_ETRPOLARITY_NONINVERTED: active high or rising edge active. - * @param ExtTRGFilter External Trigger Filter. - * This parameter must be a value between 0x00 and 0x0F - * @retval None - */ -void TIM_ETR_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ExtTRGPrescaler, - uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) -{ - uint32_t tmpsmcr; - - 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 << 8U))); - - /* 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 - * @arg TIM_CHANNEL_5: TIM Channel 5 selected - * @arg TIM_CHANNEL_6: TIM Channel 6 selected - * @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; - - /* Check the parameters */ - assert_param(IS_TIM_CC1_INSTANCE(TIMx)); - assert_param(IS_TIM_CHANNELS(Channel)); - - tmp = TIM_CCER_CC1E << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ - - /* Reset the CCxE Bit */ - TIMx->CCER &= ~tmp; - - /* Set or reset the CCxE Bit */ - TIMx->CCER |= (uint32_t)(ChannelState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ -} - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) -/** - * @brief Reset interrupt callbacks to the legacy weak callbacks. - * @param htim pointer to a TIM_HandleTypeDef structure that contains - * the configuration information for TIM module. - * @retval None - */ -void TIM_ResetCallback(TIM_HandleTypeDef *htim) -{ - /* Reset the TIM callback to the legacy weak callbacks */ - htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; - htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; - htim->TriggerCallback = HAL_TIM_TriggerCallback; - htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; - htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; - htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; - htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; - htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; - htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; - htim->ErrorCallback = HAL_TIM_ErrorCallback; - htim->CommutationCallback = HAL_TIMEx_CommutCallback; - htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; - htim->BreakCallback = HAL_TIMEx_BreakCallback; - htim->Break2Callback = HAL_TIMEx_Break2Callback; - htim->EncoderIndexCallback = HAL_TIMEx_EncoderIndexCallback; - htim->DirectionChangeCallback = HAL_TIMEx_DirectionChangeCallback; - htim->IndexErrorCallback = HAL_TIMEx_IndexErrorCallback; - htim->TransitionErrorCallback = HAL_TIMEx_TransitionErrorCallback; -} -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - -/** - * @} - */ - -#endif /* HAL_TIM_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_tim.c + * @author MCD Application Team + * @brief TIM HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Timer (TIM) peripheral: + * + TIM Time Base Initialization + * + TIM Time Base Start + * + TIM Time Base Start Interruption + * + TIM Time Base Start DMA + * + TIM Output Compare/PWM Initialization + * + TIM Output Compare/PWM Channel Configuration + * + TIM Output Compare/PWM Start + * + TIM Output Compare/PWM Start Interruption + * + TIM Output Compare/PWM Start DMA + * + TIM Input Capture Initialization + * + TIM Input Capture Channel Configuration + * + TIM Input Capture Start + * + TIM Input Capture Start Interruption + * + TIM Input Capture Start DMA + * + TIM One Pulse Initialization + * + TIM One Pulse Channel Configuration + * + TIM One Pulse Start + * + TIM Encoder Interface Initialization + * + TIM Encoder Interface Start + * + TIM Encoder Interface Start Interruption + * + TIM Encoder Interface Start DMA + * + Commutation Event configuration with Interruption and DMA + * + TIM OCRef clear configuration + * + TIM External Clock configuration + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 + (#) Synchronization circuit to control the timer with external signals and to interconnect + several timers together. + (#) Supports incremental encoder for positioning purposes + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the TIM low level resources by implementing the following functions + depending on the selected feature: + (++) 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 __HAL_RCC_TIMx_CLK_ENABLE(); + (##) TIM pins configuration + (+++) Enable the clock for the TIM GPIOs using the following function: + __HAL_RCC_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, HAL_TIM_OC_ConfigChannel and optionally HAL_TIMEx_OC_ConfigPulseOnCompare: + 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() + + *** Callback registration *** + ============================================= + + [..] + The compilation define USE_HAL_TIM_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function HAL_TIM_RegisterCallback() to register a callback. + HAL_TIM_RegisterCallback() takes as parameters the HAL peripheral handle, + the Callback ID and a pointer to the user callback function. + + [..] + Use function HAL_TIM_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_TIM_UnRegisterCallback takes as parameters the HAL peripheral handle, + and the Callback ID. + + [..] + These functions allow to register/unregister following callbacks: + (+) Base_MspInitCallback : TIM Base Msp Init Callback. + (+) Base_MspDeInitCallback : TIM Base Msp DeInit Callback. + (+) IC_MspInitCallback : TIM IC Msp Init Callback. + (+) IC_MspDeInitCallback : TIM IC Msp DeInit Callback. + (+) OC_MspInitCallback : TIM OC Msp Init Callback. + (+) OC_MspDeInitCallback : TIM OC Msp DeInit Callback. + (+) PWM_MspInitCallback : TIM PWM Msp Init Callback. + (+) PWM_MspDeInitCallback : TIM PWM Msp DeInit Callback. + (+) OnePulse_MspInitCallback : TIM One Pulse Msp Init Callback. + (+) OnePulse_MspDeInitCallback : TIM One Pulse Msp DeInit Callback. + (+) Encoder_MspInitCallback : TIM Encoder Msp Init Callback. + (+) Encoder_MspDeInitCallback : TIM Encoder Msp DeInit Callback. + (+) HallSensor_MspInitCallback : TIM Hall Sensor Msp Init Callback. + (+) HallSensor_MspDeInitCallback : TIM Hall Sensor Msp DeInit Callback. + (+) PeriodElapsedCallback : TIM Period Elapsed Callback. + (+) PeriodElapsedHalfCpltCallback : TIM Period Elapsed half complete Callback. + (+) TriggerCallback : TIM Trigger Callback. + (+) TriggerHalfCpltCallback : TIM Trigger half complete Callback. + (+) IC_CaptureCallback : TIM Input Capture Callback. + (+) IC_CaptureHalfCpltCallback : TIM Input Capture half complete Callback. + (+) OC_DelayElapsedCallback : TIM Output Compare Delay Elapsed Callback. + (+) PWM_PulseFinishedCallback : TIM PWM Pulse Finished Callback. + (+) PWM_PulseFinishedHalfCpltCallback : TIM PWM Pulse Finished half complete Callback. + (+) ErrorCallback : TIM Error Callback. + (+) CommutationCallback : TIM Commutation Callback. + (+) CommutationHalfCpltCallback : TIM Commutation half complete Callback. + (+) BreakCallback : TIM Break Callback. + (+) Break2Callback : TIM Break2 Callback. + (+) EncoderIndexCallback : TIM Encoder Index Callback. + (+) DirectionChangeCallback : TIM Direction Change Callback + (+) IndexErrorCallback : TIM Index Error Callback. + (+) TransitionErrorCallback : TIM Transition Error Callback + + [..] +By default, after the Init and when the state is HAL_TIM_STATE_RESET +all interrupt callbacks are set to the corresponding weak functions: + examples HAL_TIM_TriggerCallback(), HAL_TIM_ErrorCallback(). + + [..] + Exception done for MspInit and MspDeInit functions that are reset to the legacy weak + functionalities in the Init / DeInit only when these callbacks are null + (not registered beforehand). If not, MspInit or MspDeInit are not null, the Init / DeInit + keep and use the user MspInit / MspDeInit callbacks(registered beforehand) + + [..] + Callbacks can be registered / unregistered in HAL_TIM_STATE_READY state only. + Exception done MspInit / MspDeInit that can be registered / unregistered + in HAL_TIM_STATE_READY or HAL_TIM_STATE_RESET state, + thus registered(user) MspInit / DeInit callbacks can be used during the Init / DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_TIM_RegisterCallback() before calling DeInit or Init function. + + [..] + When The compilation define USE_HAL_TIM_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available and all callbacks + are set to the corresponding weak functions. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup TIM TIM + * @brief TIM HAL module driver + * @{ + */ + +#ifdef HAL_TIM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup TIM_Private_Functions + * @{ + */ +static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, const 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_ITRx_SetConfig(TIM_TypeDef *TIMx, uint32_t InputTriggerSource); +static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, + const TIM_SlaveConfigTypeDef *sSlaveConfig); +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup TIM_Exported_Functions TIM Exported Functions + * @{ + */ + +/** @defgroup TIM_Exported_Functions_Group1 TIM 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 initialize the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref HAL_TIM_Base_DeInit() before HAL_TIM_Base_Init() + * @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)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TIM_ResetCallback(htim); + + if (htim->Base_MspInitCallback == NULL) + { + htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->Base_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_TIM_Base_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Set the Time Base configuration */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Initialize the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + + /* 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->Base_MspDeInitCallback == NULL) + { + htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; + } + /* DeInit the low level hardware */ + htim->Base_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_Base_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Change the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 Base handle + * @retval None + */ +__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Base handle + * @retval None + */ +__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Base handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Check the TIM state */ + if (htim->State != HAL_TIM_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation. + * @param htim TIM Base handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set 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 Base handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Check the TIM state */ + if (htim->State != HAL_TIM_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Enable the TIM Update interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation in interrupt mode. + * @param htim TIM Base 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); + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Base generation in DMA mode. + * @param htim TIM Base 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, const uint32_t *pData, uint16_t Length) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); + + /* Set the TIM state */ + if (htim->State == HAL_TIM_STATE_BUSY) + { + return HAL_BUSY; + } + else if (htim->State == HAL_TIM_STATE_READY) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + else + { + return HAL_ERROR; + } + + /* Set the DMA Period elapsed callbacks */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Enable the TIM Update DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_UPDATE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation in DMA mode. + * @param htim TIM Base 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); + + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group2 TIM Output Compare functions + * @brief TIM Output Compare functions + * +@verbatim + ============================================================================== + ##### TIM Output Compare functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM Output Compare. + (+) De-initialize the TIM Output Compare. + (+) Start the TIM Output Compare. + (+) Stop the TIM Output Compare. + (+) Start the TIM Output Compare and enable interrupt. + (+) Stop the TIM Output Compare and disable interrupt. + (+) Start the TIM Output Compare and enable DMA transfer. + (+) Stop the TIM Output Compare and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Output Compare according to the specified + * parameters in the TIM_HandleTypeDef and initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref HAL_TIM_OC_DeInit() before HAL_TIM_OC_Init() + * @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)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TIM_ResetCallback(htim); + + if (htim->OC_MspInitCallback == NULL) + { + htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->OC_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OC_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* 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 DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Initialize the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + + /* 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->OC_MspDeInitCallback == NULL) + { + htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; + } + /* DeInit the low level hardware */ + htim->OC_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OC_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Change the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 Output Compare handle + * @retval None + */ +__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Output Compare handle + * @retval None + */ +__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Check the TIM channel state */ + if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation. + * @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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 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_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in interrupt 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 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Check the TIM channel state */ + if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @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, const uint32_t *pData, + uint16_t Length) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Set the TIM channel state */ + if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) + { + return HAL_BUSY; + } + else if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + break; + } + + case TIM_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + break; + } + + case TIM_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + break; + } + + case TIM_CHANNEL_4: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group3 TIM PWM functions + * @brief TIM PWM functions + * +@verbatim + ============================================================================== + ##### TIM PWM functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM PWM. + (+) De-initialize the TIM PWM. + (+) Start the TIM PWM. + (+) Stop the TIM PWM. + (+) Start the TIM PWM and enable interrupt. + (+) Stop the TIM PWM and disable interrupt. + (+) Start the TIM PWM and enable DMA transfer. + (+) Stop the TIM PWM and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM PWM Time Base according to the specified + * parameters in the TIM_HandleTypeDef and initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref HAL_TIM_PWM_DeInit() before HAL_TIM_PWM_Init() + * @param htim TIM PWM 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)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TIM_ResetCallback(htim); + + if (htim->PWM_MspInitCallback == NULL) + { + htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->PWM_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_PWM_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* 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 DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Initialize the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + + /* Initialize the TIM state*/ + htim->State = HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim TIM PWM 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->PWM_MspDeInitCallback == NULL) + { + htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; + } + /* DeInit the low level hardware */ + htim->PWM_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_PWM_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Change the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 PWM handle + * @retval None + */ +__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 PWM handle + * @retval None + */ +__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Check the TIM channel state */ + if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation. + * @param htim TIM PWM 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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 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_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the PWM signal generation in interrupt mode. + * @param htim TIM PWM 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_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Check the TIM channel state */ + if (TIM_CHANNEL_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the PWM signal generation in interrupt mode. + * @param htim TIM PWM 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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TIM PWM signal generation in DMA mode. + * @param htim TIM PWM 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, const uint32_t *pData, + uint16_t Length) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Set the TIM channel state */ + if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) + { + return HAL_BUSY; + } + else if (TIM_CHANNEL_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + break; + } + + case TIM_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + break; + } + + case TIM_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Output Capture/Compare 3 request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + break; + } + + case TIM_CHANNEL_4: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TIM PWM signal generation in DMA mode. + * @param htim TIM PWM 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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group4 TIM Input Capture functions + * @brief TIM Input Capture functions + * +@verbatim + ============================================================================== + ##### TIM Input Capture functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM Input Capture. + (+) De-initialize the TIM Input Capture. + (+) Start the TIM Input Capture. + (+) Stop the TIM Input Capture. + (+) Start the TIM Input Capture and enable interrupt. + (+) Stop the TIM Input Capture and disable interrupt. + (+) Start the TIM Input Capture and enable DMA transfer. + (+) Stop the TIM 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 initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref HAL_TIM_IC_DeInit() before HAL_TIM_IC_Init() + * @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)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TIM_ResetCallback(htim); + + if (htim->IC_MspInitCallback == NULL) + { + htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->IC_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_IC_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* 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 DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Initialize the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_READY); + + /* 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->IC_MspDeInitCallback == NULL) + { + htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; + } + /* DeInit the low level hardware */ + htim->IC_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_IC_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Change the TIM channels state */ + TIM_CHANNEL_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET_ALL(htim, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 Input Capture handle + * @retval None + */ +__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 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 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + uint32_t tmpsmcr; + HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); + HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Check the TIM channel state */ + if ((channel_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement. + * @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(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Input Capture measurement in interrupt 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 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); + HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + + /* Check the TIM channel state */ + if ((channel_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TIM Input Capture measurement in interrupt 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_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @brief Starts the TIM Input Capture measurement 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) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + HAL_TIM_ChannelStateTypeDef channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); + HAL_TIM_ChannelStateTypeDef complementary_channel_state = TIM_CHANNEL_N_STATE_GET(htim, Channel); + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + /* Set the TIM channel state */ + if ((channel_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (complementary_channel_state == HAL_TIM_CHANNEL_STATE_BUSY)) + { + return HAL_BUSY; + } + else if ((channel_state == HAL_TIM_CHANNEL_STATE_READY) + && (complementary_channel_state == HAL_TIM_CHANNEL_STATE_READY)) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + break; + } + + case TIM_CHANNEL_2: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + break; + } + + case TIM_CHANNEL_3: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + break; + } + + case TIM_CHANNEL_4: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + break; + } + + default: + status = HAL_ERROR; + break; + } + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return status; +} + +/** + * @brief Stops the TIM Input Capture measurement 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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_CHANNEL(htim->Instance, Channel)); + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group5 TIM One Pulse functions + * @brief TIM One Pulse functions + * +@verbatim + ============================================================================== + ##### TIM One Pulse functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM One Pulse. + (+) De-initialize the TIM One Pulse. + (+) Start the TIM One Pulse. + (+) Stop the TIM One Pulse. + (+) Start the TIM One Pulse and enable interrupt. + (+) Stop the TIM One Pulse and disable interrupt. + (+) Start the TIM One Pulse and enable DMA transfer. + (+) Stop the TIM 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 initializes the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref HAL_TIM_OnePulse_DeInit() before HAL_TIM_OnePulse_Init() + * @note When the timer instance is initialized in One Pulse mode, timer + * channels 1 and channel 2 are reserved and cannot be used for other + * purpose. + * @param htim TIM One Pulse 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 will 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)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TIM_ResetCallback(htim); + + if (htim->OnePulse_MspInitCallback == NULL) + { + htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->OnePulse_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OnePulse_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* 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 DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Initialize the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->OnePulse_MspDeInitCallback == NULL) + { + htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; + } + /* DeInit the low level hardware */ + htim->OnePulse_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_OnePulse_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 One Pulse handle + * @retval None + */ +__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 One Pulse handle + * @retval None + */ +__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid HAL_TIM API compatibility break. + * @note The pulse output channel is determined when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel See note above + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(OutputChannel); + + /* Check the TIM channels state */ + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + + /* 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 + whatever the combination, 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_BREAK_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. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid HAL_TIM API compatibility break. + * @note The pulse output channel is determined when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel See note above + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 + whatever the combination, 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_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM One Pulse signal generation in interrupt mode. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid HAL_TIM API compatibility break. + * @note The pulse output channel is determined when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel See note above + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(OutputChannel); + + /* Check the TIM channels state */ + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + + /* 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 + whatever the combination, 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_BREAK_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. + * @note Though OutputChannel parameter is deprecated and ignored by the function + * it has been kept to avoid HAL_TIM API compatibility break. + * @note The pulse output channel is determined when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel See note above + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 + whatever the combination, 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_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group6 TIM Encoder functions + * @brief TIM Encoder functions + * +@verbatim + ============================================================================== + ##### TIM Encoder functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM Encoder. + (+) De-initialize the TIM Encoder. + (+) Start the TIM Encoder. + (+) Stop the TIM Encoder. + (+) Start the TIM Encoder and enable interrupt. + (+) Stop the TIM Encoder and disable interrupt. + (+) Start the TIM Encoder and enable DMA transfer. + (+) Stop the TIM Encoder and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Encoder Interface and initialize the associated handle. + * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse) + * requires a timer reset to avoid unexpected direction + * due to DIR bit readonly in center aligned mode. + * Ex: call @ref HAL_TIM_Encoder_DeInit() before HAL_TIM_Encoder_Init() + * @note Encoder mode and External clock mode 2 are not compatible and must not be selected together + * Ex: A call for @ref HAL_TIM_Encoder_Init will erase the settings of @ref HAL_TIM_ConfigClockSource + * using TIM_CLOCKSOURCE_ETRMODE2 and vice versa + * @note When the timer instance is initialized in Encoder mode, timer + * channels 1 and channel 2 are reserved and cannot be used for other + * purpose. + * @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, const TIM_Encoder_InitTypeDef *sConfig) +{ + uint32_t tmpsmcr; + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Check the TIM handle allocation */ + if (htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_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_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + 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_ENCODERINPUT_POLARITY(sConfig->IC1Polarity)); + assert_param(IS_TIM_ENCODERINPUT_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)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy weak callbacks */ + TIM_ResetCallback(htim); + + if (htim->Encoder_MspInitCallback == NULL) + { + htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->Encoder_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_Encoder_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Reset the SMS and ECE bits */ + htim->Instance->SMCR &= ~(TIM_SMCR_SMS | TIM_SMCR_ECE); + + /* 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 << 8U)); + + /* Set 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 << 8U); + tmpccmr1 |= (sConfig->IC1Filter << 4U) | (sConfig->IC2Filter << 12U); + + /* 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 << 4U); + + /* 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 DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Initialize the TIM state*/ + htim->State = HAL_TIM_STATE_READY; + + return HAL_OK; +} + + +/** + * @brief DeInitializes the TIM Encoder interface + * @param htim TIM Encoder Interface 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->Encoder_MspDeInitCallback == NULL) + { + htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; + } + /* DeInit the low level hardware */ + htim->Encoder_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_Encoder_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 Encoder Interface handle + * @retval None + */ +__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Encoder Interface handle + * @retval None + */ +__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 + * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + /* Set the TIM channel(s) state */ + if (Channel == TIM_CHANNEL_1) + { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else if (Channel == TIM_CHANNEL_2) + { + if ((channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + + /* 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 + * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_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); + + /* Set the TIM channel(s) state */ + if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) + { + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + } + + /* 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 + * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + /* Set the TIM channel(s) state */ + if (Channel == TIM_CHANNEL_1) + { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else if (Channel == TIM_CHANNEL_2) + { + if ((channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + + /* 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 + * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_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); + + /* Set the TIM channel(s) state */ + if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) + { + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_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 + * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are 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) +{ + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + /* Set the TIM channel(s) state */ + if (Channel == TIM_CHANNEL_1) + { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY)) + { + return HAL_BUSY; + } + else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) + && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY)) + { + if ((pData1 == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + } + else if (Channel == TIM_CHANNEL_2) + { + if ((channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) + { + return HAL_BUSY; + } + else if ((channel_2_state == HAL_TIM_CHANNEL_STATE_READY) + && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) + { + if ((pData2 == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + } + else + { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) + { + return HAL_BUSY; + } + else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) + && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) + && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) + && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) + { + if ((((pData1 == NULL) || (pData2 == NULL))) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + break; + } + + case TIM_CHANNEL_2: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError; + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + break; + } + + default: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + + /* 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); + + /* 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 Peripheral */ + __HAL_TIM_ENABLE(htim); + + 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 + * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel(s) state */ + if ((Channel == TIM_CHANNEL_1) || (Channel == TIM_CHANNEL_2)) + { + TIM_CHANNEL_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ +/** @defgroup TIM_Exported_Functions_Group7 TIM IRQ handler management + * @brief TIM 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) +{ + uint32_t itsource = htim->Instance->DIER; + uint32_t itflag = htim->Instance->SR; + + /* Capture compare 1 event */ + if ((itflag & (TIM_FLAG_CC1)) == (TIM_FLAG_CC1)) + { + if ((itsource & (TIM_IT_CC1)) == (TIM_IT_CC1)) + { + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC1); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + + /* Input capture event */ + if ((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U) + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IC_CaptureCallback(htim); +#else + HAL_TIM_IC_CaptureCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->OC_DelayElapsedCallback(htim); + htim->PWM_PulseFinishedCallback(htim); +#else + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + } + /* Capture compare 2 event */ + if ((itflag & (TIM_FLAG_CC2)) == (TIM_FLAG_CC2)) + { + if ((itsource & (TIM_IT_CC2)) == (TIM_IT_CC2)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC2); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + /* Input capture event */ + if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IC_CaptureCallback(htim); +#else + HAL_TIM_IC_CaptureCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->OC_DelayElapsedCallback(htim); + htim->PWM_PulseFinishedCallback(htim); +#else + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 3 event */ + if ((itflag & (TIM_FLAG_CC3)) == (TIM_FLAG_CC3)) + { + if ((itsource & (TIM_IT_CC3)) == (TIM_IT_CC3)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC3); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + /* Input capture event */ + if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IC_CaptureCallback(htim); +#else + HAL_TIM_IC_CaptureCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->OC_DelayElapsedCallback(htim); + htim->PWM_PulseFinishedCallback(htim); +#else + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 4 event */ + if ((itflag & (TIM_FLAG_CC4)) == (TIM_FLAG_CC4)) + { + if ((itsource & (TIM_IT_CC4)) == (TIM_IT_CC4)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_CC4); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + /* Input capture event */ + if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IC_CaptureCallback(htim); +#else + HAL_TIM_IC_CaptureCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + /* Output compare event */ + else + { +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->OC_DelayElapsedCallback(htim); + htim->PWM_PulseFinishedCallback(htim); +#else + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* TIM Update event */ + if ((itflag & (TIM_FLAG_UPDATE)) == (TIM_FLAG_UPDATE)) + { + if ((itsource & (TIM_IT_UPDATE)) == (TIM_IT_UPDATE)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_UPDATE); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->PeriodElapsedCallback(htim); +#else + HAL_TIM_PeriodElapsedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Break input event */ + if (((itflag & (TIM_FLAG_BREAK)) == (TIM_FLAG_BREAK)) || \ + ((itflag & (TIM_FLAG_SYSTEM_BREAK)) == (TIM_FLAG_SYSTEM_BREAK))) + { + if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK | TIM_FLAG_SYSTEM_BREAK); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->BreakCallback(htim); +#else + HAL_TIMEx_BreakCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Break2 input event */ + if ((itflag & (TIM_FLAG_BREAK2)) == (TIM_FLAG_BREAK2)) + { + if ((itsource & (TIM_IT_BREAK)) == (TIM_IT_BREAK)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_BREAK2); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->Break2Callback(htim); +#else + HAL_TIMEx_Break2Callback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Trigger detection event */ + if ((itflag & (TIM_FLAG_TRIGGER)) == (TIM_FLAG_TRIGGER)) + { + if ((itsource & (TIM_IT_TRIGGER)) == (TIM_IT_TRIGGER)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TRIGGER); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->TriggerCallback(htim); +#else + HAL_TIM_TriggerCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM commutation event */ + if ((itflag & (TIM_FLAG_COM)) == (TIM_FLAG_COM)) + { + if ((itsource & (TIM_IT_COM)) == (TIM_IT_COM)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_COM); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->CommutationCallback(htim); +#else + HAL_TIMEx_CommutCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Encoder index event */ + if ((itflag & (TIM_FLAG_IDX)) == (TIM_FLAG_IDX)) + { + if ((itsource & (TIM_IT_IDX)) == (TIM_IT_IDX)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_IDX); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->EncoderIndexCallback(htim); +#else + HAL_TIMEx_EncoderIndexCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Direction change event */ + if ((itflag & (TIM_FLAG_DIR)) == (TIM_FLAG_DIR)) + { + if ((itsource & (TIM_IT_DIR)) == (TIM_IT_DIR)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_DIR); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->DirectionChangeCallback(htim); +#else + HAL_TIMEx_DirectionChangeCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Index error event */ + if ((itflag & (TIM_FLAG_IERR)) == (TIM_FLAG_IERR)) + { + if ((itsource & (TIM_IT_IERR)) == (TIM_IT_IERR)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_IERR); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IndexErrorCallback(htim); +#else + HAL_TIMEx_IndexErrorCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } + /* TIM Transition error event */ + if ((itflag & (TIM_FLAG_TERR)) == (TIM_FLAG_TERR)) + { + if ((itsource & (TIM_IT_TERR)) == (TIM_IT_TERR)) + { + __HAL_TIM_CLEAR_FLAG(htim, TIM_FLAG_TERR); +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->TransitionErrorCallback(htim); +#else + HAL_TIMEx_TransitionErrorCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + } +} + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group8 TIM Peripheral Control functions + * @brief TIM 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 configure + * 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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, + const TIM_OC_InitTypeDef *sConfig, + uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_CHANNELS(Channel)); + assert_param(IS_TIM_OC_CHANNEL_MODE(sConfig->OCMode, Channel)); + assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); + + /* Process Locked */ + __HAL_LOCK(htim); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Check the parameters */ + 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: + { + /* Check the parameters */ + 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: + { + /* Check the parameters */ + 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: + { + /* Check the parameters */ + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + + /* Configure the TIM Channel 4 in Output Compare */ + TIM_OC4_SetConfig(htim->Instance, sConfig); + break; + } + + case TIM_CHANNEL_5: + { + /* Check the parameters */ + assert_param(IS_TIM_CC5_INSTANCE(htim->Instance)); + + /* Configure the TIM Channel 5 in Output Compare */ + TIM_OC5_SetConfig(htim->Instance, sConfig); + break; + } + + case TIM_CHANNEL_6: + { + /* Check the parameters */ + assert_param(IS_TIM_CC6_INSTANCE(htim->Instance)); + + /* Configure the TIM Channel 6 in Output Compare */ + TIM_OC6_SetConfig(htim->Instance, sConfig); + break; + } + + default: + status = HAL_ERROR; + break; + } + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @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 Channel to configure + * 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, const TIM_IC_InitTypeDef *sConfig, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* 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)); + + /* Process Locked */ + __HAL_LOCK(htim); + + 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 << 8U); + } + 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 if (Channel == TIM_CHANNEL_4) + { + /* 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 << 8U); + } + else + { + status = HAL_ERROR; + } + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @brief Initializes the TIM PWM channels according to the specified + * parameters in the TIM_OC_InitTypeDef. + * @param htim TIM PWM handle + * @param sConfig TIM PWM configuration structure + * @param Channel TIM Channels to be configured + * 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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, + const TIM_OC_InitTypeDef *sConfig, + uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* 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_FAST_STATE(sConfig->OCFastMode)); + + /* Process Locked */ + __HAL_LOCK(htim); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Check the parameters */ + 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: + { + /* Check the parameters */ + 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 << 8U; + break; + } + + case TIM_CHANNEL_3: + { + /* Check the parameters */ + 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: + { + /* Check the parameters */ + 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 << 8U; + break; + } + + case TIM_CHANNEL_5: + { + /* Check the parameters */ + assert_param(IS_TIM_CC5_INSTANCE(htim->Instance)); + + /* Configure the Channel 5 in PWM mode */ + TIM_OC5_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel5*/ + htim->Instance->CCMR3 |= TIM_CCMR3_OC5PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR3 &= ~TIM_CCMR3_OC5FE; + htim->Instance->CCMR3 |= sConfig->OCFastMode; + break; + } + + case TIM_CHANNEL_6: + { + /* Check the parameters */ + assert_param(IS_TIM_CC6_INSTANCE(htim->Instance)); + + /* Configure the Channel 6 in PWM mode */ + TIM_OC6_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel6 */ + htim->Instance->CCMR3 |= TIM_CCMR3_OC6PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR3 &= ~TIM_CCMR3_OC6FE; + htim->Instance->CCMR3 |= sConfig->OCFastMode << 8U; + break; + } + + default: + status = HAL_ERROR; + break; + } + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @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 output channel to configure + * 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 input Channel to configure + * 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 + * @note To output a waveform with a minimum delay user can enable the fast + * mode by calling the @ref __HAL_TIM_ENABLE_OCxFAST macro. Then CCx + * output is forced in response to the edge detection on TIx input, + * without taking in account the comparison. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef *sConfig, + uint32_t OutputChannel, uint32_t InputChannel) +{ + HAL_StatusTypeDef status = HAL_OK; + TIM_OC_InitTypeDef temp1; + + /* Check the parameters */ + assert_param(IS_TIM_OPM_CHANNELS(OutputChannel)); + assert_param(IS_TIM_OPM_CHANNELS(InputChannel)); + + if (OutputChannel != InputChannel) + { + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Extract the Output 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + 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: + status = HAL_ERROR; + break; + } + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return status; + } + 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 where the DMA will start the Data write + * This parameter can be one 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_CCMR3 + * @arg TIM_DMABASE_CCR5 + * @arg TIM_DMABASE_CCR6 + * @arg TIM_DMABASE_DTR2 + * @arg TIM_DMABASE_ECR + * @arg TIM_DMABASE_TISEL + * @arg TIM_DMABASE_AF1 + * @arg TIM_DMABASE_AF2 + * @param BurstRequestSrc TIM DMA Request sources + * This parameter can be one 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_26TRANSFER. + * @note This function should be used only when BurstLength is equal to DMA data transfer length. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t BlockDataLength = 0; + uint32_t data_width; + const DMA_HandleTypeDef *hdma = NULL; + + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + switch (BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + hdma = htim->hdma[TIM_DMA_ID_UPDATE]; + break; + } + case TIM_DMA_CC1: + { + hdma = htim->hdma[TIM_DMA_ID_CC1]; + break; + } + case TIM_DMA_CC2: + { + hdma = htim->hdma[TIM_DMA_ID_CC2]; + break; + } + case TIM_DMA_CC3: + { + hdma = htim->hdma[TIM_DMA_ID_CC3]; + break; + } + case TIM_DMA_CC4: + { + hdma = htim->hdma[TIM_DMA_ID_CC4]; + break; + } + case TIM_DMA_COM: + { + hdma = htim->hdma[TIM_DMA_ID_COMMUTATION]; + break; + } + case TIM_DMA_TRIGGER: + { + hdma = htim->hdma[TIM_DMA_ID_TRIGGER]; + break; + } + default: + status = HAL_ERROR; + break; + } + + if (hdma != NULL) + { + + if (((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) && (hdma->LinkedListQueue != 0U) + && (hdma->LinkedListQueue->Head != 0U)) + { + data_width = hdma->LinkedListQueue->Head->LinkRegisters[0] & DMA_CTR1_SDW_LOG2; + } + else + { + data_width = hdma->Init.SrcDataWidth; + } + + switch (data_width) + { + case DMA_SRC_DATAWIDTH_BYTE: + { + BlockDataLength = (BurstLength >> TIM_DCR_DBL_Pos) + 1UL; + break; + } + case DMA_SRC_DATAWIDTH_HALFWORD: + { + BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 2UL; + break; + } + case DMA_SRC_DATAWIDTH_WORD: + { + BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 4UL; + break; + } + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + status = HAL_TIM_DMABurst_MultiWriteStart(htim, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, + BlockDataLength); + } + } + + + return status; +} + +/** + * @brief Configure the DMA Burst to transfer multiple Data from the memory to the TIM peripheral + * @param htim TIM handle + * @param BurstBaseAddress TIM Base address from where the DMA will start the Data write + * This parameter can be one 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_CCMR3 + * @arg TIM_DMABASE_CCR5 + * @arg TIM_DMABASE_CCR6 + * @arg TIM_DMABASE_DTR2 + * @arg TIM_DMABASE_ECR + * @arg TIM_DMABASE_TISEL + * @arg TIM_DMABASE_AF1 + * @arg TIM_DMABASE_AF2 + * @param BurstRequestSrc TIM DMA Request sources + * This parameter can be one 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_26TRANSFER. + * @param DataLength Data length. This parameter can be one value + * between 1 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_MultiWriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, const uint32_t *BurstBuffer, + uint32_t BurstLength, uint32_t DataLength) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpDBSS = 0; + + /* 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)); + assert_param(IS_TIM_DMA_DATA_LENGTH(DataLength)); + + if (htim->DMABurstState == HAL_DMA_BURST_STATE_BUSY) + { + return HAL_BUSY; + } + else if (htim->DMABurstState == HAL_DMA_BURST_STATE_READY) + { + if ((BurstBuffer == NULL) && (BurstLength > 0U)) + { + return HAL_ERROR; + } + else + { + htim->DMABurstState = HAL_DMA_BURST_STATE_BUSY; + } + } + else + { + /* nothing to do */ + } + + switch (BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + /* Set the DMA Period elapsed callbacks */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = TIM_DCR_DBSS_0; + break; + } + case TIM_DMA_CC1: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = TIM_DCR_DBSS_1; + break; + } + case TIM_DMA_CC2: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); + break; + } + case TIM_DMA_CC3: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = TIM_DCR_DBSS_2; + break; + } + case TIM_DMA_CC4: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_0); + break; + } + case TIM_DMA_COM: + { + /* Set the DMA commutation callbacks */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1); + break; + } + case TIM_DMA_TRIGGER: + { + /* Set the DMA trigger callbacks */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; + htim->hdma[TIM_DMA_ID_TRIGGER]->XferHalfCpltCallback = TIM_DMATriggerHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, + (uint32_t)&htim->Instance->DMAR, DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); + break; + } + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Configure the DMA Burst Mode */ + htim->Instance->DCR = (BurstBaseAddress | BurstLength | tmpDBSS); + /* Enable the TIM DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + /* Abort the DMA transfer (at least disable the DMA channel) */ + switch (BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); + break; + } + case TIM_DMA_CC1: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + case TIM_DMA_CC2: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + case TIM_DMA_CC3: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + case TIM_DMA_CC4: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + case TIM_DMA_COM: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]); + break; + } + case TIM_DMA_TRIGGER: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]); + break; + } + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @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 where the DMA will start the Data read + * This parameter can be one 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_CCMR3 + * @arg TIM_DMABASE_CCR5 + * @arg TIM_DMABASE_CCR6 + * @arg TIM_DMABASE_DTR2 + * @arg TIM_DMABASE_ECR + * @arg TIM_DMABASE_TISEL + * @arg TIM_DMABASE_AF1 + * @arg TIM_DMABASE_AF2 + * @param BurstRequestSrc TIM DMA Request sources + * This parameter can be one 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_26TRANSFER. + * @note This function should be used only when BurstLength is equal to DMA data transfer length. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t BlockDataLength = 0; + uint32_t data_width; + const DMA_HandleTypeDef *hdma = NULL; + + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + switch (BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + hdma = htim->hdma[TIM_DMA_ID_UPDATE]; + break; + } + case TIM_DMA_CC1: + { + hdma = htim->hdma[TIM_DMA_ID_CC1]; + break; + } + case TIM_DMA_CC2: + { + hdma = htim->hdma[TIM_DMA_ID_CC2]; + break; + } + case TIM_DMA_CC3: + { + hdma = htim->hdma[TIM_DMA_ID_CC3]; + break; + } + case TIM_DMA_CC4: + { + hdma = htim->hdma[TIM_DMA_ID_CC4]; + break; + } + case TIM_DMA_COM: + { + hdma = htim->hdma[TIM_DMA_ID_COMMUTATION]; + break; + } + case TIM_DMA_TRIGGER: + { + hdma = htim->hdma[TIM_DMA_ID_TRIGGER]; + break; + } + default: + status = HAL_ERROR; + break; + } + + if (hdma != NULL) + { + + if (((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) && (hdma->LinkedListQueue != 0U) + && (hdma->LinkedListQueue->Head != 0U)) + { + data_width = hdma->LinkedListQueue->Head->LinkRegisters[0] & DMA_CTR1_SDW_LOG2; + } + else + { + data_width = hdma->Init.SrcDataWidth; + } + + switch (data_width) + + { + case DMA_SRC_DATAWIDTH_BYTE: + { + BlockDataLength = ((BurstLength) >> TIM_DCR_DBL_Pos) + 1UL; + break; + } + case DMA_SRC_DATAWIDTH_HALFWORD: + { + BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 2UL; + break; + } + case DMA_SRC_DATAWIDTH_WORD: + { + BlockDataLength = ((BurstLength >> TIM_DCR_DBL_Pos) + 1UL) * 4UL; + break; + } + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + status = HAL_TIM_DMABurst_MultiReadStart(htim, BurstBaseAddress, BurstRequestSrc, BurstBuffer, BurstLength, + BlockDataLength); + } + } + + return status; +} + +/** + * @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 where the DMA will start the Data read + * This parameter can be one 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_CCMR3 + * @arg TIM_DMABASE_CCR5 + * @arg TIM_DMABASE_CCR6 + * @arg TIM_DMABASE_DTR2 + * @arg TIM_DMABASE_ECR + * @arg TIM_DMABASE_TISEL + * @arg TIM_DMABASE_AF1 + * @arg TIM_DMABASE_AF2 + * @param BurstRequestSrc TIM DMA Request sources + * This parameter can be one 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_26TRANSFER. + * @param DataLength Data length. This parameter can be one value + * between 1 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_MultiReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, + uint32_t BurstRequestSrc, uint32_t *BurstBuffer, + uint32_t BurstLength, uint32_t DataLength) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpDBSS = 0; + + /* 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)); + assert_param(IS_TIM_DMA_DATA_LENGTH(DataLength)); + + if (htim->DMABurstState == HAL_DMA_BURST_STATE_BUSY) + { + return HAL_BUSY; + } + else if (htim->DMABurstState == HAL_DMA_BURST_STATE_READY) + { + if ((BurstBuffer == NULL) && (BurstLength > 0U)) + { + return HAL_ERROR; + } + else + { + htim->DMABurstState = HAL_DMA_BURST_STATE_BUSY; + } + } + else + { + /* nothing to do */ + } + switch (BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + /* Set the DMA Period elapsed callbacks */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + htim->hdma[TIM_DMA_ID_UPDATE]->XferHalfCpltCallback = TIM_DMAPeriodElapsedHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = TIM_DCR_DBSS_0; + break; + } + case TIM_DMA_CC1: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = TIM_DCR_DBSS_1; + break; + } + case TIM_DMA_CC2: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); + break; + } + case TIM_DMA_CC3: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = TIM_DCR_DBSS_2; + break; + } + case TIM_DMA_CC4: + { + /* Set the DMA capture callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_0); + break; + } + case TIM_DMA_COM: + { + /* Set the DMA commutation callbacks */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt; + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1); + break; + } + case TIM_DMA_TRIGGER: + { + /* Set the DMA trigger callbacks */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; + htim->hdma[TIM_DMA_ID_TRIGGER]->XferHalfCpltCallback = TIM_DMATriggerHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, + DataLength) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Configure the DMA Burst Source Selection */ + tmpDBSS = (TIM_DCR_DBSS_2 | TIM_DCR_DBSS_1 | TIM_DCR_DBSS_0); + break; + } + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Configure the DMA Burst Mode */ + htim->Instance->DCR = (BurstBaseAddress | BurstLength | tmpDBSS); + + /* Enable the TIM DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + /* Abort the DMA transfer (at least disable the DMA channel) */ + switch (BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_UPDATE]); + break; + } + case TIM_DMA_CC1: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + case TIM_DMA_CC2: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + case TIM_DMA_CC3: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + case TIM_DMA_CC4: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + case TIM_DMA_COM: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_COMMUTATION]); + break; + } + case TIM_DMA_TRIGGER: + { + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_TRIGGER]); + break; + } + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + } + + /* Return function status */ + return status; +} + +/** + * @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 + * @arg TIM_EVENTSOURCE_BREAK2: Timer Break2 event source + * @note Basic timers can only generate an update event. + * @note TIM_EVENTSOURCE_COM is relevant only with advanced timer instances. + * @note TIM_EVENTSOURCE_BREAK and TIM_EVENTSOURCE_BREAK2 are relevant + * only for timer instances supporting break input(s). + * @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 + * @arg TIM_CHANNEL_5: TIM Channel 5 + * @arg TIM_CHANNEL_6: TIM Channel 6 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, + const TIM_ClearInputConfigTypeDef *sClearInputConfig, + uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_TIM_OCXREF_CLEAR_INSTANCE(htim->Instance)); + assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource)); + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + switch (sClearInputConfig->ClearInputSource) + { + case TIM_CLEARINPUTSOURCE_NONE: + { + /* Clear the OCREF clear selection bit and the the ETR Bits */ + CLEAR_BIT(htim->Instance->SMCR, (TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); + break; + } + + case TIM_CLEARINPUTSOURCE_ETR: + { + /* Check the parameters */ + assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity)); + assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler)); + assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter)); + + /* When OCRef clear feature is used with ETR source, ETR prescaler must be off */ + if (sClearInputConfig->ClearInputPrescaler != TIM_CLEARINPUTPRESCALER_DIV1) + { + htim->State = HAL_TIM_STATE_READY; + __HAL_UNLOCK(htim); + return HAL_ERROR; + } + + TIM_ETR_SetConfig(htim->Instance, + sClearInputConfig->ClearInputPrescaler, + sClearInputConfig->ClearInputPolarity, + sClearInputConfig->ClearInputFilter); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + switch (Channel) + { + case TIM_CHANNEL_1: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 1 */ + SET_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC1CE); + } + else + { + /* Disable the OCREF clear feature for Channel 1 */ + CLEAR_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC1CE); + } + break; + } + case TIM_CHANNEL_2: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 2 */ + SET_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC2CE); + } + else + { + /* Disable the OCREF clear feature for Channel 2 */ + CLEAR_BIT(htim->Instance->CCMR1, TIM_CCMR1_OC2CE); + } + break; + } + case TIM_CHANNEL_3: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 3 */ + SET_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC3CE); + } + else + { + /* Disable the OCREF clear feature for Channel 3 */ + CLEAR_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC3CE); + } + break; + } + case TIM_CHANNEL_4: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 4 */ + SET_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC4CE); + } + else + { + /* Disable the OCREF clear feature for Channel 4 */ + CLEAR_BIT(htim->Instance->CCMR2, TIM_CCMR2_OC4CE); + } + break; + } + case TIM_CHANNEL_5: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 5 */ + SET_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC5CE); + } + else + { + /* Disable the OCREF clear feature for Channel 5 */ + CLEAR_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC5CE); + } + break; + } + case TIM_CHANNEL_6: + { + if (sClearInputConfig->ClearInputState != (uint32_t)DISABLE) + { + /* Enable the OCREF clear feature for Channel 6 */ + SET_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC6CE); + } + else + { + /* Disable the OCREF clear feature for Channel 6 */ + CLEAR_BIT(htim->Instance->CCMR3, TIM_CCMR3_OC6CE); + } + break; + } + default: + break; + } + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @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, const TIM_ClockConfigTypeDef *sClockSourceConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_TIM_CLOCKSOURCE(sClockSourceConfig->ClockSource)); + + /* 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)); + break; + } + + case TIM_CLOCKSOURCE_ETRMODE1: + { + /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/ + assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance)); + + /* Check ETR input conditioning related parameters */ + assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + /* Configure the ETR Clock source */ + TIM_ETR_SetConfig(htim->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + + /* Select the External clock mode1 and the ETRF trigger */ + tmpsmcr = htim->Instance->SMCR; + tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1); + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + break; + } + + case TIM_CLOCKSOURCE_ETRMODE2: + { + /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/ + assert_param(IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(htim->Instance)); + + /* Check ETR input conditioning related parameters */ + assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + /* 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: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); + + /* Check TI1 input conditioning related parameters */ + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + TIM_TI1_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1); + break; + } + + case TIM_CLOCKSOURCE_TI2: + { + /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/ + assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); + + /* Check TI2 input conditioning related parameters */ + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + TIM_TI2_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2); + break; + } + + case TIM_CLOCKSOURCE_TI1ED: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); + + /* Check TI1 input conditioning related parameters */ + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + TIM_TI1_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED); + break; + } + + case TIM_CLOCKSOURCE_ITR0: + case TIM_CLOCKSOURCE_ITR1: + case TIM_CLOCKSOURCE_ITR2: + case TIM_CLOCKSOURCE_ITR3: + case TIM_CLOCKSOURCE_ITR4: + case TIM_CLOCKSOURCE_ITR5: + case TIM_CLOCKSOURCE_ITR6: + case TIM_CLOCKSOURCE_ITR7: + case TIM_CLOCKSOURCE_ITR8: + case TIM_CLOCKSOURCE_ITR9: + case TIM_CLOCKSOURCE_ITR10: + case TIM_CLOCKSOURCE_ITR11: + case TIM_CLOCKSOURCE_ITR13: + case TIM_CLOCKSOURCE_ITR14: + { + /* Check whether or not the timer instance supports internal trigger input */ + assert_param(IS_TIM_CLOCKSOURCE_INSTANCE((htim->Instance), sClockSourceConfig->ClockSource)); + + TIM_ITRx_SetConfig(htim->Instance, sClockSourceConfig->ClockSource); + break; + } + + default: + status = HAL_ERROR; + break; + } + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @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; + + /* 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 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 Slave mode + * (Disable, Reset, Gated, Trigger, External clock mode 1, Reset + Trigger, Gated + Reset). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro(TIM_HandleTypeDef *htim, const TIM_SlaveConfigTypeDef *sSlaveConfig) +{ + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); + assert_param(IS_TIM_TRIGGER_INSTANCE(htim->Instance, sSlaveConfig->InputTrigger)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + if (TIM_SlaveTimer_SetConfig(htim, sSlaveConfig) != HAL_OK) + { + htim->State = HAL_TIM_STATE_READY; + __HAL_UNLOCK(htim); + return HAL_ERROR; + } + + /* Disable Trigger Interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_TRIGGER); + + /* Disable Trigger DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_TRIGGER); + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the TIM in Slave mode in interrupt 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 Slave mode + * (Disable, Reset, Gated, Trigger, External clock mode 1, Reset + Trigger, Gated + Reset). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchro_IT(TIM_HandleTypeDef *htim, + const TIM_SlaveConfigTypeDef *sSlaveConfig) +{ + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); + assert_param(IS_TIM_TRIGGER_INSTANCE(htim->Instance, sSlaveConfig->InputTrigger)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + if (TIM_SlaveTimer_SetConfig(htim, sSlaveConfig) != HAL_OK) + { + htim->State = HAL_TIM_STATE_READY; + __HAL_UNLOCK(htim); + return HAL_ERROR; + } + + /* Enable Trigger Interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_TRIGGER); + + /* Disable Trigger DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_TRIGGER); + + 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(const TIM_HandleTypeDef *htim, uint32_t Channel) +{ + uint32_t tmpreg = 0U; + + 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; + } + + return tmpreg; +} + +/** + * @brief Start the DMA data transfer. + * @param hdma DMA handle + * @param src : The source memory Buffer address. + * @param dst : The destination memory Buffer address. + * @param length : The size of a source block transfer in byte. + * @retval HAL status + */ +HAL_StatusTypeDef TIM_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t src, uint32_t dst, + uint32_t length) +{ + HAL_StatusTypeDef status ; + + /* Enable the DMA channel */ + if ((hdma->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((hdma->LinkedListQueue != 0U) && (hdma->LinkedListQueue->Head != 0U)) + { + /* Enable the DMA channel */ + hdma->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = length; + hdma->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = src; + hdma->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = dst; + + status = HAL_DMAEx_List_Start_IT(hdma); + } + else + { + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(hdma, src, dst, length); + } + + return status; +} + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group9 TIM Callbacks functions + * @brief TIM Callbacks functions + * +@verbatim + ============================================================================== + ##### TIM Callbacks functions ##### + ============================================================================== + [..] + This section provides TIM callback functions: + (+) TIM Period elapsed callback + (+) TIM Output Compare callback + (+) TIM Input capture callback + (+) TIM Trigger callback + (+) TIM Error callback + (+) TIM Index callback + (+) TIM Direction change callback + (+) TIM Index error callback + (+) TIM Transition 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Period elapsed half complete callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIM_PeriodElapsedHalfCpltCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIM_PeriodElapsedHalfCpltCallback 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Input Capture half complete callback in non-blocking mode + * @param htim TIM IC handle + * @retval None + */ +__weak void HAL_TIM_IC_CaptureHalfCpltCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIM_IC_CaptureHalfCpltCallback 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 PWM Pulse finished half complete callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIM_PWM_PulseFinishedHalfCpltCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIM_PWM_PulseFinishedHalfCpltCallback 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Hall Trigger detection half complete callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIM_TriggerHalfCpltCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIM_TriggerHalfCpltCallback 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIM_ErrorCallback could be implemented in the user file + */ +} + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User TIM callback to be used instead of the weak predefined callback + * @param htim tim handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_TIM_BASE_MSPINIT_CB_ID Base MspInit Callback ID + * @arg @ref HAL_TIM_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID + * @arg @ref HAL_TIM_IC_MSPINIT_CB_ID IC MspInit Callback ID + * @arg @ref HAL_TIM_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID + * @arg @ref HAL_TIM_OC_MSPINIT_CB_ID OC MspInit Callback ID + * @arg @ref HAL_TIM_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID + * @arg @ref HAL_TIM_PWM_MSPINIT_CB_ID PWM MspInit Callback ID + * @arg @ref HAL_TIM_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID + * @arg @ref HAL_TIM_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID + * @arg @ref HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID + * @arg @ref HAL_TIM_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID + * @arg @ref HAL_TIM_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID + * @arg @ref HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID + * @arg @ref HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID + * @arg @ref HAL_TIM_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID + * @arg @ref HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID + * @arg @ref HAL_TIM_TRIGGER_CB_ID Trigger Callback ID + * @arg @ref HAL_TIM_TRIGGER_HALF_CB_ID Trigger half complete Callback ID + * @arg @ref HAL_TIM_IC_CAPTURE_CB_ID Input Capture Callback ID + * @arg @ref HAL_TIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID + * @arg @ref HAL_TIM_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID + * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID + * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID + * @arg @ref HAL_TIM_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_TIM_COMMUTATION_CB_ID Commutation Callback ID + * @arg @ref HAL_TIM_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID + * @arg @ref HAL_TIM_BREAK_CB_ID Break Callback ID + * @arg @ref HAL_TIM_BREAK2_CB_ID Break2 Callback ID + * @arg @ref HAL_TIM_ENCODER_INDEX_CB_ID Encoder Index Callback ID + * @arg @ref HAL_TIM_DIRECTION_CHANGE_CB_ID Direction Change Callback ID + * @arg @ref HAL_TIM_INDEX_ERROR_CB_ID Index Error Callback ID + * @arg @ref HAL_TIM_TRANSITION_ERROR_CB_ID Transition Error Callback ID + * @param pCallback pointer to the callback function + * @retval status + */ +HAL_StatusTypeDef HAL_TIM_RegisterCallback(TIM_HandleTypeDef *htim, HAL_TIM_CallbackIDTypeDef CallbackID, + pTIM_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + return HAL_ERROR; + } + + if (htim->State == HAL_TIM_STATE_READY) + { + switch (CallbackID) + { + case HAL_TIM_BASE_MSPINIT_CB_ID : + htim->Base_MspInitCallback = pCallback; + break; + + case HAL_TIM_BASE_MSPDEINIT_CB_ID : + htim->Base_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_IC_MSPINIT_CB_ID : + htim->IC_MspInitCallback = pCallback; + break; + + case HAL_TIM_IC_MSPDEINIT_CB_ID : + htim->IC_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_OC_MSPINIT_CB_ID : + htim->OC_MspInitCallback = pCallback; + break; + + case HAL_TIM_OC_MSPDEINIT_CB_ID : + htim->OC_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_PWM_MSPINIT_CB_ID : + htim->PWM_MspInitCallback = pCallback; + break; + + case HAL_TIM_PWM_MSPDEINIT_CB_ID : + htim->PWM_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : + htim->OnePulse_MspInitCallback = pCallback; + break; + + case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : + htim->OnePulse_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_ENCODER_MSPINIT_CB_ID : + htim->Encoder_MspInitCallback = pCallback; + break; + + case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : + htim->Encoder_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : + htim->HallSensor_MspInitCallback = pCallback; + break; + + case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : + htim->HallSensor_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_PERIOD_ELAPSED_CB_ID : + htim->PeriodElapsedCallback = pCallback; + break; + + case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID : + htim->PeriodElapsedHalfCpltCallback = pCallback; + break; + + case HAL_TIM_TRIGGER_CB_ID : + htim->TriggerCallback = pCallback; + break; + + case HAL_TIM_TRIGGER_HALF_CB_ID : + htim->TriggerHalfCpltCallback = pCallback; + break; + + case HAL_TIM_IC_CAPTURE_CB_ID : + htim->IC_CaptureCallback = pCallback; + break; + + case HAL_TIM_IC_CAPTURE_HALF_CB_ID : + htim->IC_CaptureHalfCpltCallback = pCallback; + break; + + case HAL_TIM_OC_DELAY_ELAPSED_CB_ID : + htim->OC_DelayElapsedCallback = pCallback; + break; + + case HAL_TIM_PWM_PULSE_FINISHED_CB_ID : + htim->PWM_PulseFinishedCallback = pCallback; + break; + + case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID : + htim->PWM_PulseFinishedHalfCpltCallback = pCallback; + break; + + case HAL_TIM_ERROR_CB_ID : + htim->ErrorCallback = pCallback; + break; + + case HAL_TIM_COMMUTATION_CB_ID : + htim->CommutationCallback = pCallback; + break; + + case HAL_TIM_COMMUTATION_HALF_CB_ID : + htim->CommutationHalfCpltCallback = pCallback; + break; + + case HAL_TIM_BREAK_CB_ID : + htim->BreakCallback = pCallback; + break; + + case HAL_TIM_BREAK2_CB_ID : + htim->Break2Callback = pCallback; + break; + + case HAL_TIM_ENCODER_INDEX_CB_ID : + htim->EncoderIndexCallback = pCallback; + break; + + case HAL_TIM_DIRECTION_CHANGE_CB_ID : + htim->DirectionChangeCallback = pCallback; + break; + + case HAL_TIM_INDEX_ERROR_CB_ID : + htim->IndexErrorCallback = pCallback; + break; + + case HAL_TIM_TRANSITION_ERROR_CB_ID : + htim->TransitionErrorCallback = pCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (htim->State == HAL_TIM_STATE_RESET) + { + switch (CallbackID) + { + case HAL_TIM_BASE_MSPINIT_CB_ID : + htim->Base_MspInitCallback = pCallback; + break; + + case HAL_TIM_BASE_MSPDEINIT_CB_ID : + htim->Base_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_IC_MSPINIT_CB_ID : + htim->IC_MspInitCallback = pCallback; + break; + + case HAL_TIM_IC_MSPDEINIT_CB_ID : + htim->IC_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_OC_MSPINIT_CB_ID : + htim->OC_MspInitCallback = pCallback; + break; + + case HAL_TIM_OC_MSPDEINIT_CB_ID : + htim->OC_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_PWM_MSPINIT_CB_ID : + htim->PWM_MspInitCallback = pCallback; + break; + + case HAL_TIM_PWM_MSPDEINIT_CB_ID : + htim->PWM_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : + htim->OnePulse_MspInitCallback = pCallback; + break; + + case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : + htim->OnePulse_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_ENCODER_MSPINIT_CB_ID : + htim->Encoder_MspInitCallback = pCallback; + break; + + case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : + htim->Encoder_MspDeInitCallback = pCallback; + break; + + case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : + htim->HallSensor_MspInitCallback = pCallback; + break; + + case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : + htim->HallSensor_MspDeInitCallback = pCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a TIM callback + * TIM callback is redirected to the weak predefined callback + * @param htim tim handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_TIM_BASE_MSPINIT_CB_ID Base MspInit Callback ID + * @arg @ref HAL_TIM_BASE_MSPDEINIT_CB_ID Base MspDeInit Callback ID + * @arg @ref HAL_TIM_IC_MSPINIT_CB_ID IC MspInit Callback ID + * @arg @ref HAL_TIM_IC_MSPDEINIT_CB_ID IC MspDeInit Callback ID + * @arg @ref HAL_TIM_OC_MSPINIT_CB_ID OC MspInit Callback ID + * @arg @ref HAL_TIM_OC_MSPDEINIT_CB_ID OC MspDeInit Callback ID + * @arg @ref HAL_TIM_PWM_MSPINIT_CB_ID PWM MspInit Callback ID + * @arg @ref HAL_TIM_PWM_MSPDEINIT_CB_ID PWM MspDeInit Callback ID + * @arg @ref HAL_TIM_ONE_PULSE_MSPINIT_CB_ID One Pulse MspInit Callback ID + * @arg @ref HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID One Pulse MspDeInit Callback ID + * @arg @ref HAL_TIM_ENCODER_MSPINIT_CB_ID Encoder MspInit Callback ID + * @arg @ref HAL_TIM_ENCODER_MSPDEINIT_CB_ID Encoder MspDeInit Callback ID + * @arg @ref HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID Hall Sensor MspInit Callback ID + * @arg @ref HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID Hall Sensor MspDeInit Callback ID + * @arg @ref HAL_TIM_PERIOD_ELAPSED_CB_ID Period Elapsed Callback ID + * @arg @ref HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID Period Elapsed half complete Callback ID + * @arg @ref HAL_TIM_TRIGGER_CB_ID Trigger Callback ID + * @arg @ref HAL_TIM_TRIGGER_HALF_CB_ID Trigger half complete Callback ID + * @arg @ref HAL_TIM_IC_CAPTURE_CB_ID Input Capture Callback ID + * @arg @ref HAL_TIM_IC_CAPTURE_HALF_CB_ID Input Capture half complete Callback ID + * @arg @ref HAL_TIM_OC_DELAY_ELAPSED_CB_ID Output Compare Delay Elapsed Callback ID + * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_CB_ID PWM Pulse Finished Callback ID + * @arg @ref HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID PWM Pulse Finished half complete Callback ID + * @arg @ref HAL_TIM_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_TIM_COMMUTATION_CB_ID Commutation Callback ID + * @arg @ref HAL_TIM_COMMUTATION_HALF_CB_ID Commutation half complete Callback ID + * @arg @ref HAL_TIM_BREAK_CB_ID Break Callback ID + * @arg @ref HAL_TIM_BREAK2_CB_ID Break2 Callback ID + * @arg @ref HAL_TIM_ENCODER_INDEX_CB_ID Encoder Index Callback ID + * @arg @ref HAL_TIM_DIRECTION_CHANGE_CB_ID Direction Change Callback ID + * @arg @ref HAL_TIM_INDEX_ERROR_CB_ID Index Error Callback ID + * @arg @ref HAL_TIM_TRANSITION_ERROR_CB_ID Transition Error Callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_TIM_UnRegisterCallback(TIM_HandleTypeDef *htim, HAL_TIM_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (htim->State == HAL_TIM_STATE_READY) + { + switch (CallbackID) + { + case HAL_TIM_BASE_MSPINIT_CB_ID : + /* Legacy weak Base MspInit Callback */ + htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; + break; + + case HAL_TIM_BASE_MSPDEINIT_CB_ID : + /* Legacy weak Base Msp DeInit Callback */ + htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; + break; + + case HAL_TIM_IC_MSPINIT_CB_ID : + /* Legacy weak IC Msp Init Callback */ + htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; + break; + + case HAL_TIM_IC_MSPDEINIT_CB_ID : + /* Legacy weak IC Msp DeInit Callback */ + htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; + break; + + case HAL_TIM_OC_MSPINIT_CB_ID : + /* Legacy weak OC Msp Init Callback */ + htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; + break; + + case HAL_TIM_OC_MSPDEINIT_CB_ID : + /* Legacy weak OC Msp DeInit Callback */ + htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; + break; + + case HAL_TIM_PWM_MSPINIT_CB_ID : + /* Legacy weak PWM Msp Init Callback */ + htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; + break; + + case HAL_TIM_PWM_MSPDEINIT_CB_ID : + /* Legacy weak PWM Msp DeInit Callback */ + htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; + break; + + case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : + /* Legacy weak One Pulse Msp Init Callback */ + htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; + break; + + case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : + /* Legacy weak One Pulse Msp DeInit Callback */ + htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; + break; + + case HAL_TIM_ENCODER_MSPINIT_CB_ID : + /* Legacy weak Encoder Msp Init Callback */ + htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; + break; + + case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : + /* Legacy weak Encoder Msp DeInit Callback */ + htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; + break; + + case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : + /* Legacy weak Hall Sensor Msp Init Callback */ + htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; + break; + + case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : + /* Legacy weak Hall Sensor Msp DeInit Callback */ + htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; + break; + + case HAL_TIM_PERIOD_ELAPSED_CB_ID : + /* Legacy weak Period Elapsed Callback */ + htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; + break; + + case HAL_TIM_PERIOD_ELAPSED_HALF_CB_ID : + /* Legacy weak Period Elapsed half complete Callback */ + htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; + break; + + case HAL_TIM_TRIGGER_CB_ID : + /* Legacy weak Trigger Callback */ + htim->TriggerCallback = HAL_TIM_TriggerCallback; + break; + + case HAL_TIM_TRIGGER_HALF_CB_ID : + /* Legacy weak Trigger half complete Callback */ + htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; + break; + + case HAL_TIM_IC_CAPTURE_CB_ID : + /* Legacy weak IC Capture Callback */ + htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; + break; + + case HAL_TIM_IC_CAPTURE_HALF_CB_ID : + /* Legacy weak IC Capture half complete Callback */ + htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; + break; + + case HAL_TIM_OC_DELAY_ELAPSED_CB_ID : + /* Legacy weak OC Delay Elapsed Callback */ + htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; + break; + + case HAL_TIM_PWM_PULSE_FINISHED_CB_ID : + /* Legacy weak PWM Pulse Finished Callback */ + htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; + break; + + case HAL_TIM_PWM_PULSE_FINISHED_HALF_CB_ID : + /* Legacy weak PWM Pulse Finished half complete Callback */ + htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; + break; + + case HAL_TIM_ERROR_CB_ID : + /* Legacy weak Error Callback */ + htim->ErrorCallback = HAL_TIM_ErrorCallback; + break; + + case HAL_TIM_COMMUTATION_CB_ID : + /* Legacy weak Commutation Callback */ + htim->CommutationCallback = HAL_TIMEx_CommutCallback; + break; + + case HAL_TIM_COMMUTATION_HALF_CB_ID : + /* Legacy weak Commutation half complete Callback */ + htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; + break; + + case HAL_TIM_BREAK_CB_ID : + /* Legacy weak Break Callback */ + htim->BreakCallback = HAL_TIMEx_BreakCallback; + break; + + case HAL_TIM_BREAK2_CB_ID : + /* Legacy weak Break2 Callback */ + htim->Break2Callback = HAL_TIMEx_Break2Callback; + break; + + case HAL_TIM_ENCODER_INDEX_CB_ID : + /* Legacy weak Encoder Index Callback */ + htim->EncoderIndexCallback = HAL_TIMEx_EncoderIndexCallback; + break; + + case HAL_TIM_DIRECTION_CHANGE_CB_ID : + /* Legacy weak Direction Change Callback */ + htim->DirectionChangeCallback = HAL_TIMEx_DirectionChangeCallback; + break; + + case HAL_TIM_INDEX_ERROR_CB_ID : + /* Legacy weak Index Error Callback */ + htim->IndexErrorCallback = HAL_TIMEx_IndexErrorCallback; + break; + + case HAL_TIM_TRANSITION_ERROR_CB_ID : + /* Legacy weak Transition Error Callback */ + htim->TransitionErrorCallback = HAL_TIMEx_TransitionErrorCallback; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (htim->State == HAL_TIM_STATE_RESET) + { + switch (CallbackID) + { + case HAL_TIM_BASE_MSPINIT_CB_ID : + /* Legacy weak Base MspInit Callback */ + htim->Base_MspInitCallback = HAL_TIM_Base_MspInit; + break; + + case HAL_TIM_BASE_MSPDEINIT_CB_ID : + /* Legacy weak Base Msp DeInit Callback */ + htim->Base_MspDeInitCallback = HAL_TIM_Base_MspDeInit; + break; + + case HAL_TIM_IC_MSPINIT_CB_ID : + /* Legacy weak IC Msp Init Callback */ + htim->IC_MspInitCallback = HAL_TIM_IC_MspInit; + break; + + case HAL_TIM_IC_MSPDEINIT_CB_ID : + /* Legacy weak IC Msp DeInit Callback */ + htim->IC_MspDeInitCallback = HAL_TIM_IC_MspDeInit; + break; + + case HAL_TIM_OC_MSPINIT_CB_ID : + /* Legacy weak OC Msp Init Callback */ + htim->OC_MspInitCallback = HAL_TIM_OC_MspInit; + break; + + case HAL_TIM_OC_MSPDEINIT_CB_ID : + /* Legacy weak OC Msp DeInit Callback */ + htim->OC_MspDeInitCallback = HAL_TIM_OC_MspDeInit; + break; + + case HAL_TIM_PWM_MSPINIT_CB_ID : + /* Legacy weak PWM Msp Init Callback */ + htim->PWM_MspInitCallback = HAL_TIM_PWM_MspInit; + break; + + case HAL_TIM_PWM_MSPDEINIT_CB_ID : + /* Legacy weak PWM Msp DeInit Callback */ + htim->PWM_MspDeInitCallback = HAL_TIM_PWM_MspDeInit; + break; + + case HAL_TIM_ONE_PULSE_MSPINIT_CB_ID : + /* Legacy weak One Pulse Msp Init Callback */ + htim->OnePulse_MspInitCallback = HAL_TIM_OnePulse_MspInit; + break; + + case HAL_TIM_ONE_PULSE_MSPDEINIT_CB_ID : + /* Legacy weak One Pulse Msp DeInit Callback */ + htim->OnePulse_MspDeInitCallback = HAL_TIM_OnePulse_MspDeInit; + break; + + case HAL_TIM_ENCODER_MSPINIT_CB_ID : + /* Legacy weak Encoder Msp Init Callback */ + htim->Encoder_MspInitCallback = HAL_TIM_Encoder_MspInit; + break; + + case HAL_TIM_ENCODER_MSPDEINIT_CB_ID : + /* Legacy weak Encoder Msp DeInit Callback */ + htim->Encoder_MspDeInitCallback = HAL_TIM_Encoder_MspDeInit; + break; + + case HAL_TIM_HALL_SENSOR_MSPINIT_CB_ID : + /* Legacy weak Hall Sensor Msp Init Callback */ + htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; + break; + + case HAL_TIM_HALL_SENSOR_MSPDEINIT_CB_ID : + /* Legacy weak Hall Sensor Msp DeInit Callback */ + htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; + break; + + default : + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup TIM_Exported_Functions_Group10 TIM Peripheral State functions + * @brief TIM 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 Return the TIM Base handle state. + * @param htim TIM Base handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM OC handle state. + * @param htim TIM Output Compare handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM PWM handle state. + * @param htim TIM handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Input Capture handle state. + * @param htim TIM IC handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM One Pulse Mode handle state. + * @param htim TIM OPM handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Encoder Mode handle state. + * @param htim TIM Encoder Interface handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Encoder Mode handle state. + * @param htim TIM handle + * @retval Active channel + */ +HAL_TIM_ActiveChannel HAL_TIM_GetActiveChannel(const TIM_HandleTypeDef *htim) +{ + return htim->Channel; +} + +/** + * @brief Return actual state of the TIM channel. + * @param htim TIM handle + * @param Channel 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 + * @arg TIM_CHANNEL_5: TIM Channel 5 + * @arg TIM_CHANNEL_6: TIM Channel 6 + * @retval TIM Channel state + */ +HAL_TIM_ChannelStateTypeDef HAL_TIM_GetChannelState(const TIM_HandleTypeDef *htim, uint32_t Channel) +{ + HAL_TIM_ChannelStateTypeDef channel_state; + + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + channel_state = TIM_CHANNEL_STATE_GET(htim, Channel); + + return channel_state; +} + +/** + * @brief Return actual state of a DMA burst operation. + * @param htim TIM handle + * @retval DMA burst state + */ +HAL_TIM_DMABurstStateTypeDef HAL_TIM_DMABurstState(const TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); + + return htim->DMABurstState; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup TIM_Private_Functions TIM Private Functions + * @{ + */ + +/** + * @brief TIM DMA error callback + * @param hdma pointer to DMA handle. + * @retval None + */ +void TIM_DMAError(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); + } + else + { + htim->State = HAL_TIM_STATE_READY; + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->ErrorCallback(htim); +#else + HAL_TIM_ErrorCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TIM DMA Delay Pulse complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->PWM_PulseFinishedCallback(htim); +#else + HAL_TIM_PWM_PulseFinishedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TIM DMA Delay Pulse half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TIM_DMADelayPulseHalfCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->PWM_PulseFinishedHalfCpltCallback(htim); +#else + HAL_TIM_PWM_PulseFinishedHalfCpltCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TIM DMA Capture complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IC_CaptureCallback(htim); +#else + HAL_TIM_IC_CaptureCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TIM DMA Capture half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TIM_DMACaptureHalfCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->IC_CaptureHalfCpltCallback(htim); +#else + HAL_TIM_IC_CaptureHalfCpltCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @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; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->PeriodElapsedCallback(htim); +#else + HAL_TIM_PeriodElapsedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ +} + +/** + * @brief TIM DMA Period Elapse half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TIM_DMAPeriodElapsedHalfCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->PeriodElapsedHalfCpltCallback(htim); +#else + HAL_TIM_PeriodElapsedHalfCpltCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ +} + +/** + * @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; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->TriggerCallback(htim); +#else + HAL_TIM_TriggerCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ +} + +/** + * @brief TIM DMA Trigger half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TIM_DMATriggerHalfCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->TriggerHalfCpltCallback(htim); +#else + HAL_TIM_TriggerHalfCpltCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ +} + +/** + * @brief Time Base configuration + * @param TIMx TIM peripheral + * @param Structure TIM Base configuration structure + * @retval None + */ +void TIM_Base_SetConfig(TIM_TypeDef *TIMx, const TIM_Base_InitTypeDef *Structure) +{ + uint32_t tmpcr1; + tmpcr1 = TIMx->CR1; + + /* Set TIM Time Base Unit parameters ---------------------------------------*/ + if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) + { + /* Select the Counter Mode */ + tmpcr1 &= ~(TIM_CR1_DIR | TIM_CR1_CMS); + tmpcr1 |= Structure->CounterMode; + } + + if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) + { + /* Set the clock division */ + tmpcr1 &= ~TIM_CR1_CKD; + tmpcr1 |= (uint32_t)Structure->ClockDivision; + } + + /* Set the auto-reload preload */ + MODIFY_REG(tmpcr1, TIM_CR1_ARPE, Structure->AutoReloadPreload); + + TIMx->CR1 = tmpcr1; + + /* Set the Autoreload value */ + TIMx->ARR = (uint32_t)Structure->Period ; + + /* Set the Prescaler value */ + TIMx->PSC = Structure->Prescaler; + + if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) + { + /* Set the Repetition Counter value */ + TIMx->RCR = Structure->RepetitionCounter; + } + + /* Generate an update event to reload the Prescaler + and the repetition counter (only for advanced timer) value immediately */ + TIMx->EGR = TIM_EGR_UG; + + /* Check if the update flag is set after the Update Generation, if so clear the UIF flag */ + if (HAL_IS_BIT_SET(TIMx->SR, TIM_FLAG_UPDATE)) + { + /* Clear the update flag */ + CLEAR_BIT(TIMx->SR, TIM_FLAG_UPDATE); + } +} + +/** + * @brief Timer Output Compare 1 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + + /* Disable the Channel 1: Reset the CC1E Bit */ + TIMx->CCER &= ~TIM_CCER_CC1E; + + /* 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_CCXN_INSTANCE(TIMx, TIM_CHANNEL_1)) + { + /* Check parameters */ + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* 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; + } + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* 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 Timer Output Compare 2 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= ~TIM_CCER_CC2E; + + /* 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 << 8U); + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC2P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 4U); + + if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2)) + { + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= ~TIM_CCER_CC2NP; + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 4U); + /* Reset the Output N State */ + tmpccer &= ~TIM_CCER_CC2NE; + } + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* 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 << 2U); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 2U); + } + + /* 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 Timer Output Compare 3 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + + /* Disable the Channel 3: Reset the CC2E Bit */ + TIMx->CCER &= ~TIM_CCER_CC3E; + + /* 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 << 8U); + + if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3)) + { + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= ~TIM_CCER_CC3NP; + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 8U); + /* Reset the Output N State */ + tmpccer &= ~TIM_CCER_CC3NE; + } + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* 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 << 4U); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 4U); + } + + /* 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 Timer Output Compare 4 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, const TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + + /* Disable the Channel 4: Reset the CC4E Bit */ + TIMx->CCER &= ~TIM_CCER_CC4E; + + /* 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 << 8U); + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC4P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 12U); + + if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_4)) + { + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= ~TIM_CCER_CC4NP; + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 12U); + /* Reset the Output N State */ + tmpccer &= ~TIM_CCER_CC4NE; + } + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare IDLE State */ + tmpcr2 &= ~TIM_CR2_OIS4; + /* Reset the Output Compare N IDLE State */ + tmpcr2 &= ~TIM_CR2_OIS4N; + + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 6U); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 6U); + } + + /* 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 Timer Output Compare 5 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TIM_OC5_SetConfig(TIM_TypeDef *TIMx, + const TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + + /* Disable the output: Reset the CCxE Bit */ + TIMx->CCER &= ~TIM_CCER_CC5E; + + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + /* Get the TIMx CCMR1 register value */ + tmpccmrx = TIMx->CCMR3; + + /* Reset the Output Compare Mode Bits */ + tmpccmrx &= ~(TIM_CCMR3_OC5M); + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC5P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 16U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Reset the Output Compare IDLE State */ + tmpcr2 &= ~TIM_CR2_OIS5; + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 8U); + } + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR3 */ + TIMx->CCMR3 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR5 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Timer Output Compare 6 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config The output configuration structure + * @retval None + */ +static void TIM_OC6_SetConfig(TIM_TypeDef *TIMx, + const TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + + /* Disable the output: Reset the CCxE Bit */ + TIMx->CCER &= ~TIM_CCER_CC6E; + + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + /* Get the TIMx CCMR1 register value */ + tmpccmrx = TIMx->CCMR3; + + /* Reset the Output Compare Mode Bits */ + tmpccmrx &= ~(TIM_CCMR3_OC6M); + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8U); + + /* Reset the Output Polarity level */ + tmpccer &= (uint32_t)~TIM_CCER_CC6P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 20U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Reset the Output Compare IDLE State */ + tmpcr2 &= ~TIM_CR2_OIS6; + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 10U); + } + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR3 */ + TIMx->CCMR3 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR6 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Slave Timer configuration function + * @param htim TIM handle + * @param sSlaveConfig Slave timer configuration + * @retval None + */ +static HAL_StatusTypeDef TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, + const TIM_SlaveConfigTypeDef *sSlaveConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* 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_CLOCKSOURCE_ETRMODE1_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)); + + if ((sSlaveConfig->SlaveMode == TIM_SLAVEMODE_GATED) || \ + (sSlaveConfig->SlaveMode == TIM_SLAVEMODE_COMBINED_GATEDRESET)) + { + return HAL_ERROR; + } + + /* 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) << 4U); + + /* 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: + case TIM_TS_ITR1: + case TIM_TS_ITR2: + case TIM_TS_ITR3: + case TIM_TS_ITR4: + case TIM_TS_ITR5: + case TIM_TS_ITR6: + case TIM_TS_ITR7: + case TIM_TS_ITR8: + case TIM_TS_ITR9: + case TIM_TS_ITR10: + case TIM_TS_ITR11: + case TIM_TS_ITR13: + case TIM_TS_ITR14: + { + /* Check the parameter */ + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE((htim->Instance), sSlaveConfig->InputTrigger)); + break; + } + + default: + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @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 + * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI2FP1 + * (on channel2 path) is used as the input signal. Therefore CCMR1 must be + * protected against un-initialized filter and polarity values. + */ +void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Disable the Channel 1: Reset the CC1E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= ~TIM_CCER_CC1E; + tmpccmr1 = TIMx->CCMR1; + + /* Select the Input */ + if (IS_TIM_CC2_INSTANCE(TIMx) != RESET) + { + tmpccmr1 &= ~TIM_CCMR1_CC1S; + tmpccmr1 |= TIM_ICSelection; + } + else + { + tmpccmr1 |= TIM_CCMR1_CC1S_0; + } + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC1F; + tmpccmr1 |= ((TIM_ICFilter << 4U) & TIM_CCMR1_IC1F); + + /* Select the Polarity and set the CC1E Bit */ + tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); + tmpccer |= (TIM_ICPolarity & (TIM_CCER_CC1P | TIM_CCER_CC1NP)); + + /* 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; + uint32_t tmpccer; + + /* 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 << 4U); + + /* 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 + * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI1FP2 + * (on channel1 path) is used as the input signal. Therefore CCMR1 must be + * protected against un-initialized filter and polarity values. + */ +static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Disable the Channel 2: Reset the CC2E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= ~TIM_CCER_CC2E; + tmpccmr1 = TIMx->CCMR1; + + /* Select the Input */ + tmpccmr1 &= ~TIM_CCMR1_CC2S; + tmpccmr1 |= (TIM_ICSelection << 8U); + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC2F; + tmpccmr1 |= ((TIM_ICFilter << 12U) & TIM_CCMR1_IC2F); + + /* Select the Polarity and set the CC2E Bit */ + tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); + tmpccer |= ((TIM_ICPolarity << 4U) & (TIM_CCER_CC2P | TIM_CCER_CC2NP)); + + /* 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; + uint32_t tmpccer; + + /* Disable the Channel 2: Reset the CC2E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= ~TIM_CCER_CC2E; + tmpccmr1 = TIMx->CCMR1; + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC2F; + tmpccmr1 |= (TIM_ICFilter << 12U); + + /* Select the Polarity and set the CC2E Bit */ + tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); + tmpccer |= (TIM_ICPolarity << 4U); + + /* 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 + * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI3FP4 + * (on channel1 path) is used as the input signal. Therefore CCMR2 must be + * protected against un-initialized filter and polarity values. + */ +static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + + /* Disable the Channel 3: Reset the CC3E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= ~TIM_CCER_CC3E; + tmpccmr2 = TIMx->CCMR2; + + /* Select the Input */ + tmpccmr2 &= ~TIM_CCMR2_CC3S; + tmpccmr2 |= TIM_ICSelection; + + /* Set the filter */ + tmpccmr2 &= ~TIM_CCMR2_IC3F; + tmpccmr2 |= ((TIM_ICFilter << 4U) & TIM_CCMR2_IC3F); + + /* Select the Polarity and set the CC3E Bit */ + tmpccer &= ~(TIM_CCER_CC3P | TIM_CCER_CC3NP); + tmpccer |= ((TIM_ICPolarity << 8U) & (TIM_CCER_CC3P | TIM_CCER_CC3NP)); + + /* 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. + * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI4FP3 + * (on channel1 path) is used as the input signal. Therefore CCMR2 must be + * protected against un-initialized filter and polarity values. + * @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; + uint32_t tmpccer; + + /* Disable the Channel 4: Reset the CC4E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= ~TIM_CCER_CC4E; + tmpccmr2 = TIMx->CCMR2; + + /* Select the Input */ + tmpccmr2 &= ~TIM_CCMR2_CC4S; + tmpccmr2 |= (TIM_ICSelection << 8U); + + /* Set the filter */ + tmpccmr2 &= ~TIM_CCMR2_IC4F; + tmpccmr2 |= ((TIM_ICFilter << 12U) & TIM_CCMR2_IC4F); + + /* Select the Polarity and set the CC4E Bit */ + tmpccer &= ~(TIM_CCER_CC4P | TIM_CCER_CC4NP); + tmpccer |= ((TIM_ICPolarity << 12U) & (TIM_CCER_CC4P | TIM_CCER_CC4NP)); + + /* 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_CLOCKSOURCE_ITR3: Internal Trigger 3 + * @arg TIM_CLOCKSOURCE_ITR4: Internal Trigger 4 + * @arg TIM_CLOCKSOURCE_ITR5: Internal Trigger 5 + * @arg TIM_CLOCKSOURCE_ITR6: Internal Trigger 6 + * @arg TIM_CLOCKSOURCE_ITR7: Internal Trigger 7 + * @arg TIM_CLOCKSOURCE_ITR8: Internal Trigger 8 + * @arg TIM_CLOCKSOURCE_ITR9: Internal Trigger 9 + * @arg TIM_CLOCKSOURCE_ITR10: Internal Trigger 10 + * @arg TIM_CLOCKSOURCE_ITR11: Internal Trigger 11 + * @arg TIM_CLOCKSOURCE_ITR13: Internal Trigger 13 + * @arg TIM_CLOCKSOURCE_ITR14: Internal Trigger 14 + * @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, uint32_t InputTriggerSource) +{ + uint32_t tmpsmcr; + + /* 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 |= (InputTriggerSource | 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_ETRPRESCALER_DIV1: ETRP Prescaler OFF. + * @arg TIM_ETRPRESCALER_DIV2: ETRP frequency divided by 2. + * @arg TIM_ETRPRESCALER_DIV4: ETRP frequency divided by 4. + * @arg TIM_ETRPRESCALER_DIV8: ETRP frequency divided by 8. + * @param TIM_ExtTRGPolarity The external Trigger Polarity. + * This parameter can be one of the following values: + * @arg TIM_ETRPOLARITY_INVERTED: active low or falling edge active. + * @arg TIM_ETRPOLARITY_NONINVERTED: active high or rising edge active. + * @param ExtTRGFilter External Trigger Filter. + * This parameter must be a value between 0x00 and 0x0F + * @retval None + */ +void TIM_ETR_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ExtTRGPrescaler, + uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) +{ + uint32_t tmpsmcr; + + 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 << 8U))); + + /* 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 + * @arg TIM_CHANNEL_5: TIM Channel 5 selected + * @arg TIM_CHANNEL_6: TIM Channel 6 selected + * @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; + + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(TIMx)); + assert_param(IS_TIM_CHANNELS(Channel)); + + tmp = TIM_CCER_CC1E << (Channel & 0x1FU); /* 0x1FU = 31 bits max shift */ + + /* Reset the CCxE Bit */ + TIMx->CCER &= ~tmp; + + /* Set or reset the CCxE Bit */ + TIMx->CCER |= (uint32_t)(ChannelState << (Channel & 0x1FU)); /* 0x1FU = 31 bits max shift */ +} + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) +/** + * @brief Reset interrupt callbacks to the legacy weak callbacks. + * @param htim pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +void TIM_ResetCallback(TIM_HandleTypeDef *htim) +{ + /* Reset the TIM callback to the legacy weak callbacks */ + htim->PeriodElapsedCallback = HAL_TIM_PeriodElapsedCallback; + htim->PeriodElapsedHalfCpltCallback = HAL_TIM_PeriodElapsedHalfCpltCallback; + htim->TriggerCallback = HAL_TIM_TriggerCallback; + htim->TriggerHalfCpltCallback = HAL_TIM_TriggerHalfCpltCallback; + htim->IC_CaptureCallback = HAL_TIM_IC_CaptureCallback; + htim->IC_CaptureHalfCpltCallback = HAL_TIM_IC_CaptureHalfCpltCallback; + htim->OC_DelayElapsedCallback = HAL_TIM_OC_DelayElapsedCallback; + htim->PWM_PulseFinishedCallback = HAL_TIM_PWM_PulseFinishedCallback; + htim->PWM_PulseFinishedHalfCpltCallback = HAL_TIM_PWM_PulseFinishedHalfCpltCallback; + htim->ErrorCallback = HAL_TIM_ErrorCallback; + htim->CommutationCallback = HAL_TIMEx_CommutCallback; + htim->CommutationHalfCpltCallback = HAL_TIMEx_CommutHalfCpltCallback; + htim->BreakCallback = HAL_TIMEx_BreakCallback; + htim->Break2Callback = HAL_TIMEx_Break2Callback; + htim->EncoderIndexCallback = HAL_TIMEx_EncoderIndexCallback; + htim->DirectionChangeCallback = HAL_TIMEx_DirectionChangeCallback; + htim->IndexErrorCallback = HAL_TIMEx_IndexErrorCallback; + htim->TransitionErrorCallback = HAL_TIMEx_TransitionErrorCallback; +} +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + +/** + * @} + */ + +#endif /* HAL_TIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim_ex.c index 2acba6ba2..320762990 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_tim_ex.c @@ -1,3351 +1,3351 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_tim_ex.c - * @author MCD Application Team - * @brief TIM HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Timer Extended peripheral: - * + Time Hall Sensor Interface Initialization - * + Time Hall Sensor Interface Start - * + Time Complementary signal break and dead time configuration - * + Time Master and Slave synchronization configuration - * + Time Output Compare/PWM Channel Configuration (for channels 5 and 6) - * + Timer remapping capabilities configuration - * + Timer encoder index configuration - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### TIMER Extended features ##### - ============================================================================== - [..] - The Timer Extended features include: - (#) Complementary outputs with programmable dead-time for : - (++) 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 - (#) In case of Pulse on compare, configure pulse length and delay - (#) Encoder index configuration - - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Initialize the TIM low level resources by implementing the following functions - depending on the selected feature: - (++) Hall Sensor output : HAL_TIMEx_HallSensor_MspInit() - - (#) Initialize the TIM low level resources : - (##) Enable the TIM interface clock using __HAL_RCC_TIMx_CLK_ENABLE(); - (##) TIM pins configuration - (+++) Enable the clock for the TIM GPIOs using the following function: - __HAL_RCC_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_ConfigCommutEvent(): 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). - (#) In case of Pulse On Compare: - (++) HAL_TIMEx_OC_ConfigPulseOnCompare(): to configure pulse width and prescaler - - - (#) Activate the TIM peripheral using one of the start functions: - (++) Complementary Output Compare : HAL_TIMEx_OCN_Start(), HAL_TIMEx_OCN_Start_DMA(), - HAL_TIMEx_OCN_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 - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup TIMEx TIMEx - * @brief TIM Extended HAL module driver - * @{ - */ - -#ifdef HAL_TIM_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup TIMEx_Private_Constants TIM Extended Private Constants - * @{ - */ -/* Timeout for break input rearm */ -#define TIM_BREAKINPUT_REARM_TIMEOUT 5UL /* 5 milliseconds */ -/** - * @} - */ -/* End of private constants --------------------------------------------------*/ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma); -static void TIM_DMAErrorCCxN(DMA_HandleTypeDef *hdma); -static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState); - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup TIMEx_Exported_Functions TIM Extended Exported Functions - * @{ - */ - -/** @defgroup TIMEx_Exported_Functions_Group1 Extended 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 initialize the associated handle. - * @note When the timer instance is initialized in Hall Sensor Interface mode, - * timer channels 1 and channel 2 are reserved and cannot be used for - * other purpose. - * @param htim TIM Hall Sensor Interface handle - * @param sConfig TIM Hall Sensor configuration structure - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, const TIM_HallSensor_InitTypeDef *sConfig) -{ - TIM_OC_InitTypeDef OC_Config; - - /* Check the TIM handle allocation */ - if (htim == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_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_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); - assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); - assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); - assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); - assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); - - if (htim->State == HAL_TIM_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - htim->Lock = HAL_UNLOCKED; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - /* Reset interrupt callbacks to legacy week callbacks */ - TIM_ResetCallback(htim); - - if (htim->HallSensor_MspInitCallback == NULL) - { - htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; - } - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - htim->HallSensor_MspInitCallback(htim); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ - HAL_TIMEx_HallSensor_MspInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - } - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* 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 DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_READY; - - /* Initialize the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* 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 Interface 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); - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - if (htim->HallSensor_MspDeInitCallback == NULL) - { - htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; - } - /* DeInit the low level hardware */ - htim->HallSensor_MspDeInitCallback(htim); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_TIMEx_HallSensor_MspDeInit(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - /* Change the DMA burst operation state */ - htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; - - /* Change the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); - - /* 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 Hall Sensor Interface handle - * @retval None - */ -__weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Hall Sensor Interface handle - * @retval None - */ -__weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(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 Interface handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) -{ - uint32_t tmpsmcr; - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); - - /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the Input Capture channel 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, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Hall sensor Interface. - * @param htim TIM Hall Sensor Interface handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_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); - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM Hall Sensor Interface in interrupt mode. - * @param htim TIM Hall Sensor Interface handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) -{ - uint32_t tmpsmcr; - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); - - /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the capture compare Interrupts 1 event */ - __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); - - /* Enable the Input Capture channel 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, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Hall Sensor Interface in interrupt mode. - * @param htim TIM Hall Sensor Interface handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); - - /* Disable the Input Capture channel 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); - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM Hall Sensor Interface in DMA mode. - * @param htim TIM Hall Sensor Interface 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) -{ - uint32_t tmpsmcr; - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); - - /* Set the TIM channel state */ - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY)) - { - return HAL_BUSY; - } - else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY)) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - - /* Enable the Input Capture channel 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 Callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; - - /* Enable the DMA channel for Capture 1*/ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the capture compare 1 Interrupt */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM Hall Sensor Interface in DMA mode. - * @param htim TIM Hall Sensor Interface handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); - - /* Disable the Input Capture channel 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); - - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channel state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup TIMEx_Exported_Functions_Group2 Extended 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) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); - - /* Check the TIM complementary channel state */ - if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the Capture compare channel N */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); - - /* Enable the Main Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __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 Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - - /* 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) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); - - /* Check the TIM complementary channel state */ - if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the TIM Break interrupt */ - __HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK); - - /* Enable the Capture compare channel N */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); - - /* Enable the Main Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpccer; - - /* 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Capture compare channel N */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); - - /* Disable the TIM Break interrupt (only if no more channel is active) */ - tmpccer = htim->Instance->CCER; - if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) - { - __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); - } - - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @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, const uint32_t *pData, - uint16_t Length) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); - - /* Set the TIM complementary channel state */ - if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) - { - return HAL_BUSY; - } - else if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Output Compare DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - break; - } - - case TIM_CHANNEL_2: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Output Compare DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); - break; - } - - case TIM_CHANNEL_3: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Output Compare DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); - break; - } - - case TIM_CHANNEL_4: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Output Compare DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the Capture compare channel N */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); - - /* Enable the Main Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* 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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - - case TIM_CHANNEL_2: - { - /* Disable the TIM Output Compare DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - - case TIM_CHANNEL_3: - { - /* Disable the TIM Output Compare DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - - case TIM_CHANNEL_4: - { - /* Disable the TIM Output Compare interrupt */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the Capture compare channel N */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); - - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @} - */ - -/** @defgroup TIMEx_Exported_Functions_Group3 Extended 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. -@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) -{ - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); - - /* Check the TIM complementary channel state */ - if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the complementary PWM output */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); - - /* Enable the Main Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __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 Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - - /* 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) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); - - /* Check the TIM complementary channel state */ - if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) - { - return HAL_ERROR; - } - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - - 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: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* 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 Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpccer; - - /* 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 4 interrupt */ - __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the complementary PWM output */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); - - /* Disable the TIM Break interrupt (only if no more channel is active) */ - tmpccer = htim->Instance->CCER; - if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) - { - __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); - } - - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @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, const uint32_t *pData, - uint16_t Length) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); - - /* Set the TIM complementary channel state */ - if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) - { - return HAL_BUSY; - } - else if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) - { - if ((pData == NULL) || (Length == 0U)) - { - return HAL_ERROR; - } - else - { - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); - } - } - else - { - return HAL_ERROR; - } - - switch (Channel) - { - case TIM_CHANNEL_1: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 1 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); - break; - } - - case TIM_CHANNEL_2: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); - break; - } - - case TIM_CHANNEL_3: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); - break; - } - - case TIM_CHANNEL_4: - { - /* Set the DMA compare callbacks */ - htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseNCplt; - htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; - - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAErrorCCxN ; - - /* Enable the DMA channel */ - if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, - Length) != HAL_OK) - { - /* Return error status */ - return HAL_ERROR; - } - /* Enable the TIM Capture/Compare 4 DMA request */ - __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Enable the complementary PWM output */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); - - /* Enable the Main Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; - if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) - { - __HAL_TIM_ENABLE(htim); - } - } - else - { - __HAL_TIM_ENABLE(htim); - } - } - - /* Return function status */ - return status; -} - -/** - * @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) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* 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); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); - break; - } - - case TIM_CHANNEL_2: - { - /* Disable the TIM Capture/Compare 2 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); - break; - } - - case TIM_CHANNEL_3: - { - /* Disable the TIM Capture/Compare 3 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); - break; - } - - case TIM_CHANNEL_4: - { - /* Disable the TIM Capture/Compare 4 DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); - (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); - break; - } - - default: - status = HAL_ERROR; - break; - } - - if (status == HAL_OK) - { - /* Disable the complementary PWM output */ - TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); - - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM complementary channel state */ - TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); - } - - /* Return function status */ - return status; -} - -/** - * @} - */ - -/** @defgroup TIMEx_Exported_Functions_Group4 Extended 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 complementary - * output. - * @note OutputChannel must match the pulse output channel chosen when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel pulse output channel to enable - * 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) -{ - uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); - - /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - - /* Enable the complementary One Pulse output channel and the Input Capture channel */ - TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); - TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_ENABLE); - - /* Enable the Main Output */ - __HAL_TIM_MOE_ENABLE(htim); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Stops the TIM One Pulse signal generation on the complementary - * output. - * @note OutputChannel must match the pulse output channel chosen when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel pulse output channel to 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_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) -{ - uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); - - /* Disable the complementary One Pulse output channel and the Input Capture channel */ - TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); - TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_DISABLE); - - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Starts the TIM One Pulse signal generation in interrupt mode on the - * complementary channel. - * @note OutputChannel must match the pulse output channel chosen when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel pulse output channel to enable - * 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) -{ - uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; - HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); - HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); - HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); - - /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) - { - return HAL_ERROR; - } - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); - - /* 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 channel and the Input Capture channel */ - TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); - TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_ENABLE); - - /* 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 on the - * complementary channel. - * @note OutputChannel must match the pulse output channel chosen when calling - * @ref HAL_TIM_OnePulse_ConfigChannel(). - * @param htim TIM One Pulse handle - * @param OutputChannel pulse output channel to 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_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) -{ - uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; - - /* 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 channel and the Input Capture channel */ - TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); - TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_DISABLE); - - /* Disable the Main Output */ - __HAL_TIM_MOE_DISABLE(htim); - - /* Disable the Peripheral */ - __HAL_TIM_DISABLE(htim); - - /* Set the TIM channels state */ - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - - /* Return function status */ - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup TIMEx_Exported_Functions_Group5 Extended Peripheral Control functions - * @brief Peripheral Control functions - * -@verbatim - ============================================================================== - ##### Peripheral Control functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Configure the commutation event in case of use of the Hall sensor interface. - (+) Configure Output channels for OC and PWM mode. - - (+) Configure Complementary channels, break features and dead time. - (+) Configure Master synchronization. - (+) Configure timer remapping capabilities. - (+) Select timer input source. - (+) Enable or disable channel grouping. - (+) Configure Pulse on compare. - (+) Configure Encoder index. - -@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_ITR4: Internal trigger 4 selected - * @arg TIM_TS_ITR5: Internal trigger 5 selected - * @arg TIM_TS_ITR6: Internal trigger 6 selected - * @arg TIM_TS_ITR7: Internal trigger 7 selected - * @arg TIM_TS_ITR8: Internal trigger 8 selected - * @arg TIM_TS_ITR9: Internal trigger 9 selected - * @arg TIM_TS_ITR10: Internal trigger 10 selected - * @arg TIM_TS_ITR11: Internal trigger 11 selected - * @arg TIM_TS_ITR13: Internal trigger 13 selected - * @arg TIM_TS_ITR14: Internal trigger 14 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_ConfigCommutEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, - uint32_t CommutationSource) -{ - /* Check the parameters */ - assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); - assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); - - __HAL_LOCK(htim); - - if (CommutationSource == TIM_COMMUTATION_TRGI) - { - /* 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; - - /* Disable Commutation Interrupt */ - __HAL_TIM_DISABLE_IT(htim, TIM_IT_COM); - - /* Disable Commutation DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_COM); - - __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_ITR4: Internal trigger 4 selected - * @arg TIM_TS_ITR5: Internal trigger 5 selected - * @arg TIM_TS_ITR6: Internal trigger 6 selected - * @arg TIM_TS_ITR7: Internal trigger 7 selected - * @arg TIM_TS_ITR8: Internal trigger 8 selected - * @arg TIM_TS_ITR9: Internal trigger 9 selected - * @arg TIM_TS_ITR10: Internal trigger 10 selected - * @arg TIM_TS_ITR11: Internal trigger 11 selected - * @arg TIM_TS_ITR13: Internal trigger 13 selected - * @arg TIM_TS_ITR14: Internal trigger 14 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_ConfigCommutEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, - uint32_t CommutationSource) -{ - /* Check the parameters */ - assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); - assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); - - __HAL_LOCK(htim); - - if (CommutationSource == TIM_COMMUTATION_TRGI) - { - /* 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; - - /* Disable Commutation DMA request */ - __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_COM); - - /* Enable the Commutation Interrupt */ - __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_ITR4: Internal trigger 4 selected - * @arg TIM_TS_ITR5: Internal trigger 5 selected - * @arg TIM_TS_ITR6: Internal trigger 6 selected - * @arg TIM_TS_ITR7: Internal trigger 7 selected - * @arg TIM_TS_ITR8: Internal trigger 8 selected - * @arg TIM_TS_ITR9: Internal trigger 9 selected - * @arg TIM_TS_ITR10: Internal trigger 10 selected - * @arg TIM_TS_ITR11: Internal trigger 11 selected - * @arg TIM_TS_ITR13: Internal trigger 13 selected - * @arg TIM_TS_ITR14: Internal trigger 14 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_ConfigCommutEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, - uint32_t CommutationSource) -{ - /* Check the parameters */ - assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); - assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); - - __HAL_LOCK(htim); - - if (CommutationSource == TIM_COMMUTATION_TRGI) - { - /* 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 = TIMEx_DMACommutationCplt; - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; - /* Set the DMA error callback */ - htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError; - - /* Disable Commutation Interrupt */ - __HAL_TIM_DISABLE_IT(htim, TIM_IT_COM); - - /* 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, - const TIM_MasterConfigTypeDef *sMasterConfig) -{ - uint32_t tmpcr2; - uint32_t tmpsmcr; - - /* 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)); - - /* Check input state */ - __HAL_LOCK(htim); - - /* Change the handler state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* Get the TIMx CR2 register value */ - tmpcr2 = htim->Instance->CR2; - - /* Get the TIMx SMCR register value */ - tmpsmcr = htim->Instance->SMCR; - - /* If the timer supports ADC synchronization through TRGO2, set the master mode selection 2 */ - if (IS_TIM_TRGO2_INSTANCE(htim->Instance)) - { - /* Check the parameters */ - assert_param(IS_TIM_TRGO2_SOURCE(sMasterConfig->MasterOutputTrigger2)); - - /* Clear the MMS2 bits */ - tmpcr2 &= ~TIM_CR2_MMS2; - /* Select the TRGO2 source*/ - tmpcr2 |= sMasterConfig->MasterOutputTrigger2; - } - - /* Reset the MMS Bits */ - tmpcr2 &= ~TIM_CR2_MMS; - /* Select the TRGO source */ - tmpcr2 |= sMasterConfig->MasterOutputTrigger; - - /* Update TIMx CR2 */ - htim->Instance->CR2 = tmpcr2; - - if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) - { - /* Reset the MSM Bit */ - tmpsmcr &= ~TIM_SMCR_MSM; - /* Set master mode */ - tmpsmcr |= sMasterConfig->MasterSlaveMode; - - /* Update TIMx SMCR */ - htim->Instance->SMCR = tmpsmcr; - } - - /* Change the htim state */ - 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_ConfigBreakDeadConfigTypeDef structure that - * contains the BDTR Register configuration information for the TIM peripheral. - * @note Interrupts can be generated when an active level is detected on the - * break input, the break 2 input or the system break input. Break - * interrupt can be enabled by calling the @ref __HAL_TIM_ENABLE_IT macro. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, - const TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) -{ - /* Keep this variable initialized to 0 as it is used to configure BDTR register */ - uint32_t tmpbdtr = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_BREAK_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_DEADTIME(sBreakDeadTimeConfig->DeadTime)); - assert_param(IS_TIM_BREAK_STATE(sBreakDeadTimeConfig->BreakState)); - assert_param(IS_TIM_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity)); - assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->BreakFilter)); - assert_param(IS_TIM_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput)); - assert_param(IS_TIM_BREAK_AFMODE(sBreakDeadTimeConfig->BreakAFMode)); - - /* Check input state */ - __HAL_LOCK(htim); - - /* 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 */ - - /* Set the BDTR bits */ - MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, sBreakDeadTimeConfig->DeadTime); - MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, sBreakDeadTimeConfig->LockLevel); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, sBreakDeadTimeConfig->OffStateIDLEMode); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, sBreakDeadTimeConfig->OffStateRunMode); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, sBreakDeadTimeConfig->BreakState); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, sBreakDeadTimeConfig->BreakPolarity); - MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, sBreakDeadTimeConfig->AutomaticOutput); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, (sBreakDeadTimeConfig->BreakFilter << TIM_BDTR_BKF_Pos)); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, sBreakDeadTimeConfig->BreakAFMode); - - if (IS_TIM_BKIN2_INSTANCE(htim->Instance)) - { - /* Check the parameters */ - assert_param(IS_TIM_BREAK2_STATE(sBreakDeadTimeConfig->Break2State)); - assert_param(IS_TIM_BREAK2_POLARITY(sBreakDeadTimeConfig->Break2Polarity)); - assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->Break2Filter)); - assert_param(IS_TIM_BREAK2_AFMODE(sBreakDeadTimeConfig->Break2AFMode)); - - /* Set the BREAK2 input related BDTR bits */ - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (sBreakDeadTimeConfig->Break2Filter << TIM_BDTR_BK2F_Pos)); - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, sBreakDeadTimeConfig->Break2State); - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, sBreakDeadTimeConfig->Break2Polarity); - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, sBreakDeadTimeConfig->Break2AFMode); - } - - /* Set TIMx_BDTR */ - htim->Instance->BDTR = tmpbdtr; - - __HAL_UNLOCK(htim); - - return HAL_OK; -} - -/** - * @brief Configures the break input source. - * @param htim TIM handle. - * @param BreakInput Break input to configure - * This parameter can be one of the following values: - * @arg TIM_BREAKINPUT_BRK: Timer break input - * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input - * @param sBreakInputConfig Break input source configuration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ConfigBreakInput(TIM_HandleTypeDef *htim, - uint32_t BreakInput, - const TIMEx_BreakInputConfigTypeDef *sBreakInputConfig) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmporx; - uint32_t bkin_enable_mask; - uint32_t bkin_polarity_mask; - uint32_t bkin_enable_bitpos; - uint32_t bkin_polarity_bitpos; - - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - assert_param(IS_TIM_BREAKINPUT(BreakInput)); - assert_param(IS_TIM_BREAKINPUTSOURCE(sBreakInputConfig->Source)); - assert_param(IS_TIM_BREAKINPUTSOURCE_STATE(sBreakInputConfig->Enable)); - assert_param(IS_TIM_BREAKINPUTSOURCE_POLARITY(sBreakInputConfig->Polarity)); - - /* Check input state */ - __HAL_LOCK(htim); - - switch (sBreakInputConfig->Source) - { - case TIM_BREAKINPUTSOURCE_BKIN: - { - bkin_enable_mask = TIM_AF1_BKINE; - bkin_enable_bitpos = TIM_AF1_BKINE_Pos; - bkin_polarity_mask = TIM_AF1_BKINP; - bkin_polarity_bitpos = TIM_AF1_BKINP_Pos; - break; - } - - default: - { - bkin_enable_mask = 0U; - bkin_polarity_mask = 0U; - bkin_enable_bitpos = 0U; - bkin_polarity_bitpos = 0U; - break; - } - } - - switch (BreakInput) - { - case TIM_BREAKINPUT_BRK: - { - /* Get the TIMx_AF1 register value */ - tmporx = htim->Instance->AF1; - - /* Enable the break input */ - tmporx &= ~bkin_enable_mask; - tmporx |= (sBreakInputConfig->Enable << bkin_enable_bitpos) & bkin_enable_mask; - - /* Set the break input polarity */ - tmporx &= ~bkin_polarity_mask; - tmporx |= (sBreakInputConfig->Polarity << bkin_polarity_bitpos) & bkin_polarity_mask; - - /* Set TIMx_AF1 */ - htim->Instance->AF1 = tmporx; - break; - } - case TIM_BREAKINPUT_BRK2: - { - /* Get the TIMx_AF2 register value */ - tmporx = htim->Instance->AF2; - - /* Enable the break input */ - tmporx &= ~bkin_enable_mask; - tmporx |= (sBreakInputConfig->Enable << bkin_enable_bitpos) & bkin_enable_mask; - - /* Set the break input polarity */ - tmporx &= ~bkin_polarity_mask; - tmporx |= (sBreakInputConfig->Polarity << bkin_polarity_bitpos) & bkin_polarity_mask; - - /* Set TIMx_AF2 */ - htim->Instance->AF2 = tmporx; - break; - } - default: - status = HAL_ERROR; - break; - } - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @brief Configures the TIMx Remapping input capabilities. - * @param htim TIM handle. - * @param Remap specifies the TIM remapping source. - * For TIM1, the parameter can take one of the following values: - * @arg TIM_TIM1_ETR_GPIO TIM1 ETR is connected to GPIO - * @arg TIM_TIM1_ETR_ADC1_AWD1 TIM1 ETR is connected to ADC1 AWD1 - * @arg TIM_TIM1_ETR_ADC1_AWD2 TIM1 ETR is connected to ADC1 AWD2 - * @arg TIM_TIM1_ETR_ADC1_AWD3 TIM1 ETR is connected to ADC1 AWD3 - * @arg TIM_TIM1_ETR_ADC2_AWD1 TIM1 ETR is connected to ADC2 AWD1 - * @arg TIM_TIM1_ETR_ADC2_AWD2 TIM1 ETR is connected to ADC2 AWD2 - * @arg TIM_TIM1_ETR_ADC2_AWD3 TIM1 ETR is connected to ADC2 AWD3 - * - * For TIM2, the parameter can take one of the following values: - * @arg TIM_TIM2_ETR_GPIO TIM2 ETR is connected to GPIO - * @arg TIM_TIM2_ETR_DCMIPP_HSYNC TIM2 ETR is connected to DCMIPP HSYNC pin - * @arg TIM_TIM2_ETR_LTDC_HSYNC TIM2 ETR is connected to LTDC HSYNC pin - * @arg TIM_TIM2_ETR_SAI1_FSA TIM2_ETR is connected to SAI1 FS_A - * @arg TIM_TIM2_ETR_SAI1_FSB TIM2_ETR is connected to SAI1 FS_B - * @arg TIM_TIM2_ETR_GFXTIM_TE TIM2_ETR is connected to GFXTIM TE - * @arg TIM_TIM2_ETR_DCMIPP_HSYNC TIM2 ETR is connected to DCMIPP HSYNC pin - * @arg TIM_TIM2_ETR_LTDC_HSYNC TIM2 ETR is connected to LTDC HSYNC pin - * @arg TIM_TIM3_ETR_TIM3_ETR TIM3_ETR is connected to TIM3 ETR - * @arg TIM_TIM3_ETR_TIM4_ETR TIM3_ETR is connected to TIM4 ETR - * @arg TIM_TIM3_ETR_TIM5_ETR TIM3_ETR is connected to TIM5 ETR - * @arg TIM_TIM2_ETR_ETH_PPS TIM2_ETR is connected to ETH PPS - * - * For TIM3, the parameter can take one of the following values: - * @arg TIM_TIM3_ETR_GPIO TIM3_ETR is not connected to I/O - * @arg TIM_TIM3_ETR_DCMIPP_HSYNC TIM3_ETR is connected to DCMIPP HSYNC - * @arg TIM_TIM3_ETR_LTDC_HSYNC TIM3_ETR is connected to LTDC HSYNC - * @arg TIM_TIM3_ETR_GFXTIM_TE TIM3_ETR is connected to GFXTIM TE - * @arg TIM_TIM3_ETR_DCMIPP_HSYNC TIM3_ETR is connected to DCMIPP VSYNC - * @arg TIM_TIM3_ETR_LTDC_VSYNC TIM3_ETR is connected to LTDC VSYNC - * @arg TIM_TIM3_ETR_TIM2_ETR TIM3_ETR is connected to TIM2 ETR - * @arg TIM_TIM3_ETR_TIM4_ETR TIM3_ETR is connected to TIM4 ETR - * @arg TIM_TIM3_ETR_TIM5_ETR TIM3_ETR is connected to TIM5 ETR - * @arg TIM_TIM3_ETR_ETH_PPS TIM3_ETR is connected to ETH PPS - * - * For TIM4, the parameter can take one of the following values: - * @arg TIM_TIM4_ETR_GPIO TIM4 ETR is connected to GPIO - * @arg TIM_TIM4_ETR_DCMIPP_HSYNC TIM4_ETR is connected to DCMIPP HSYNC - * @arg TIM_TIM4_ETR_LTDC_HSYNC TIM4_ETR is connected to LTDC HSYNC - * @arg TIM_TIM4_ETR_GFXTIM_TE TIM4_ETR is connected to GFXTIM TE - * @arg TIM_TIM4_ETR_DCMIPP_HSYNC TIM4_ETR is connected to DCMIPP VSYNC - * @arg TIM_TIM4_ETR_LTDC_VSYNC TIM4_ETR is connected to LTDC VSYNC - * @arg TIM_TIM4_ETR_TIM2_ETR TIM4_ETR is connected to TIM2 ETR - * @arg TIM_TIM4_ETR_TIM3_ETR TIM4_ETR is connected to TIM3 ETR - * @arg TIM_TIM4_ETR_TIM5_ETR TIM4_ETR is connected to TIM5 ETR - * @arg TIM_TIM4_ETR_ETH1_PPS TIM4_ETR is connected to ETH1 PPS - * - * For TIM5, the parameter can take one of the following values: - * @arg TIM_TIM5_ETR_GPIO TIM5 ETR is connected to GPIO - * @arg TIM_TIM5_ETR_SAI2_FSA TIM5_ETR is connected to SAI2 FS_A - * @arg TIM_TIM5_ETR_SAI2_FSB TIM5_ETR is connected to SAI2 FS_B - * @arg TIM_TIM5_ETR_DCMIPP_HSYNC TIM5_ETR is connected to DCMIPP HSYNC - * @arg TIM_TIM5_ETR_LTDC_HSYNC TIM5_ETR is connected to LTDC HSYNC - * @arg TIM_TIM5_ETR_GFXTIM_TE TIM5_ETR is connected to GFXTIM TE - * @arg TIM_TIM5_ETR_DCMIPP_HSYNC TIM5_ETR is connected to DCMIPP VSYNC - * @arg TIM_TIM5_ETR_LTDC_VSYNC TIM5_ETR is connected to LTDC VSYNC - * @arg TIM_TIM5_ETR_TIM2_ETR TIM5_ETR is connected to TIM2 ETR - * @arg TIM_TIM5_ETR_TIM3_ETR TIM5_ETR is connected to TIM3 ETR - * @arg TIM_TIM5_ETR_TIM3_ETR TIM5_ETR is connected to TIM4 ETR - * - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) -{ - /* Check parameters */ - assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance)); - assert_param(IS_TIM_REMAP(htim->Instance, Remap)); - - __HAL_LOCK(htim); - - MODIFY_REG(htim->Instance->AF1, TIM_AF1_ETRSEL_Msk, Remap); - - __HAL_UNLOCK(htim); - - return HAL_OK; -} - -/** - * @brief Select the timer input source - * @param htim TIM handle. - * @param Channel specifies the TIM Channel - * This parameter can be one of the following values: - * @arg TIM_CHANNEL_1: TI1 input channel - * @arg TIM_CHANNEL_2: TI2 input channel - * @param TISelection parameter of the TIM_TISelectionStruct structure is detailed as follows: - * For TIM2, the parameter is one of the following values: - * @arg TIM_TIM2_TI1_GPIO: TIM2 TI1 is connected to GPIO - * @arg TIM_TIM2_TI1_ETH_PPS: TIM2 TI1 is connected to ETH PPS - * - * For TIM3, the parameter is one of the following values: - * @arg TIM_TIM3_TI1_GPIO: TIM3 TI1 is connected to GPIO - * @arg TIM_TIM3_TI1_ETH_PPS: TIM3 TI1 is connected to ETH PPS - * - * For TIM9, the parameter is one of the following values: - * @arg TIM_TIM9_TI1_GPIO: TIM9 TI1 is connected to GPIO - * @arg TIM_TIM9_TI1_MCO1: TIM9 TI1 is connected to MCO1 - * @arg TIM_TIM9_TI1_MCO2: TIM9 TI1 is connected to MCO2 - * - * For TIM12, the parameter is one of the following values: - * @arg TIM_TIM12_TI1_GPIO: TIM12 TI1 is connected to GPIO - * @arg TIM_TIM12_TI1_SPDIF_FS: TIM12 TI1 is connected to SPDIF FS - * @arg TIM_TIM12_TI1_HSI_1024: TIM12 TI1 is connected to HSI/1024 - * @arg TIM_TIM12_TI1_CSI_128: TIM12_TI1 is connected to CSI/128 - * @arg TIM_TIM12_TI1_MCO1: TIM12 TI1 is connected to MCO1 - * @arg TIM_TIM12_TI1_MCO2: TIM12 TI1 is connected to MCO2 - * - * For TIM15, the parameter is one of the following values: - * @arg TIM_TIM15_TI1_GPIO: TIM15 TI1 is connected to GPIO - * @arg TIM_TIM15_TI1_TIM2_CH1: TIM15 TI1 is connected to TIM2 CH1 - * @arg TIM_TIM15_TI1_TIM3_CH1: TIM15 TI1 is connected to TIM3 CH1 - * @arg TIM_TIM15_TI1_TIM4_CH1: TIM15 TI1 is connected to TIM4 CH1 - * @arg TIM_TIM15_TI1_MCO1: TIM15 TI1 is connected to MCO1 - * @arg TIM_TIM15_TI1_MCO2: TIM15 TI1 is connected to MCO2 - * @arg TIM_TIM15_TI2_GPIO: TIM15 TI2 is connected to GPIO - * @arg TIM_TIM15_TI2_TIM2_CH2: TIM15 TI2 is connected to TIM2 CH2 - * @arg TIM_TIM15_TI2_TIM3_CH2: TIM15 TI2 is connected to TIM3 CH2 - * @arg TIM_TIM15_TI2_TIM4_CH2: TIM15 TI2 is connected to TIM4 CH2 - * - * For TIM16, the parameter is one of the following values: - * @arg TIM_TIM16_TI1_GPIO: TIM16 TI1 is connected to GPIO - * @arg TIM_TIM16_TI1_RTC_WKUP: TIM16 TI1 is connected to RTC wakeup interrupt - * - * For TIM17, the parameter is one of the following values: - * @arg TIM_TIM17_TI1_GPIO: TIM17 TI1 is connected to GPIO - * @arg TIM_TIM17_TI1_SPDIF_FS: TIM17 TI1 is connected to SPDIF FS - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_TISelection(TIM_HandleTypeDef *htim, uint32_t TISelection, uint32_t Channel) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check parameters */ - assert_param(IS_TIM_TISEL_TIX_INSTANCE(htim->Instance, Channel)); - assert_param(IS_TIM_TISEL(TISelection)); - - __HAL_LOCK(htim); - - switch (Channel) - { - case TIM_CHANNEL_1: - MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI1SEL, TISelection); - break; - case TIM_CHANNEL_2: - MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI2SEL, TISelection); - break; - default: - status = HAL_ERROR; - break; - } - - __HAL_UNLOCK(htim); - - return status; -} - -/** - * @brief Group channel 5 and channel 1, 2 or 3 - * @param htim TIM handle. - * @param Channels specifies the reference signal(s) the OC5REF is combined with. - * This parameter can be any combination of the following values: - * TIM_GROUPCH5_NONE: No effect of OC5REF on OC1REFC, OC2REFC and OC3REFC - * TIM_GROUPCH5_OC1REFC: OC1REFC is the logical AND of OC1REFC and OC5REF - * TIM_GROUPCH5_OC2REFC: OC2REFC is the logical AND of OC2REFC and OC5REF - * TIM_GROUPCH5_OC3REFC: OC3REFC is the logical AND of OC3REFC and OC5REF - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_GroupChannel5(TIM_HandleTypeDef *htim, uint32_t Channels) -{ - /* Check parameters */ - assert_param(IS_TIM_COMBINED3PHASEPWM_INSTANCE(htim->Instance)); - assert_param(IS_TIM_GROUPCH5(Channels)); - - /* Process Locked */ - __HAL_LOCK(htim); - - htim->State = HAL_TIM_STATE_BUSY; - - /* Clear GC5Cx bit fields */ - htim->Instance->CCR5 &= ~(TIM_CCR5_GC5C3 | TIM_CCR5_GC5C2 | TIM_CCR5_GC5C1); - - /* Set GC5Cx bit fields */ - htim->Instance->CCR5 |= Channels; - - /* Change the htim state */ - htim->State = HAL_TIM_STATE_READY; - - __HAL_UNLOCK(htim); - - return HAL_OK; -} - -/** - * @brief Disarm the designated break input (when it operates in bidirectional mode). - * @param htim TIM handle. - * @param BreakInput Break input to disarm - * This parameter can be one of the following values: - * @arg TIM_BREAKINPUT_BRK: Timer break input - * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input - * @note The break input can be disarmed only when it is configured in - * bidirectional mode and when when MOE is reset. - * @note Purpose is to be able to have the input voltage back to high-state, - * whatever the time constant on the output . - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DisarmBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tmpbdtr; - - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - assert_param(IS_TIM_BREAKINPUT(BreakInput)); - - switch (BreakInput) - { - case TIM_BREAKINPUT_BRK: - { - /* Check initial conditions */ - tmpbdtr = READ_REG(htim->Instance->BDTR); - if ((READ_BIT(tmpbdtr, TIM_BDTR_BKBID) == TIM_BDTR_BKBID) && - (READ_BIT(tmpbdtr, TIM_BDTR_MOE) == 0U)) - { - /* Break input BRK is disarmed */ - SET_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM); - } - break; - } - case TIM_BREAKINPUT_BRK2: - { - /* Check initial conditions */ - tmpbdtr = READ_REG(htim->Instance->BDTR); - if ((READ_BIT(tmpbdtr, TIM_BDTR_BK2BID) == TIM_BDTR_BK2BID) && - (READ_BIT(tmpbdtr, TIM_BDTR_MOE) == 0U)) - { - /* Break input BRK is disarmed */ - SET_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM); - } - break; - } - default: - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @brief Arm the designated break input (when it operates in bidirectional mode). - * @param htim TIM handle. - * @param BreakInput Break input to arm - * This parameter can be one of the following values: - * @arg TIM_BREAKINPUT_BRK: Timer break input - * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input - * @note Arming is possible at anytime, even if fault is present. - * @note Break input is automatically armed as soon as MOE bit is set. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ReArmBreakInput(const TIM_HandleTypeDef *htim, uint32_t BreakInput) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tickstart; - - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - assert_param(IS_TIM_BREAKINPUT(BreakInput)); - - switch (BreakInput) - { - case TIM_BREAKINPUT_BRK: - { - /* Check initial conditions */ - if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKBID) == TIM_BDTR_BKBID) - { - /* Break input BRK is re-armed automatically by hardware. Poll to check whether fault condition disappeared */ - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - while (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM) != 0UL) - { - if ((HAL_GetTick() - tickstart) > TIM_BREAKINPUT_REARM_TIMEOUT) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM) != 0UL) - { - return HAL_TIMEOUT; - } - } - } - } - break; - } - - case TIM_BREAKINPUT_BRK2: - { - /* Check initial conditions */ - if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2BID) == TIM_BDTR_BK2BID) - { - /* Break input BRK2 is re-armed automatically by hardware. Poll to check whether fault condition disappeared */ - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - while (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM) != 0UL) - { - if ((HAL_GetTick() - tickstart) > TIM_BREAKINPUT_REARM_TIMEOUT) - { - /* New check to avoid false timeout detection in case of preemption */ - if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM) != 0UL) - { - return HAL_TIMEOUT; - } - } - } - } - break; - } - default: - status = HAL_ERROR; - break; - } - - return status; -} - -/** - * @brief Enable dithering - * @param htim TIM handle - * @note Main usage is PWM mode - * @note This function must be called when timer is stopped or disabled (CEN =0) - * @note If dithering is activated, pay attention to ARR, CCRx, CNT interpretation: - * - CNT: only CNT[11:0] holds the non-dithered part for 16b timers (or CNT[26:0] for 32b timers) - * - ARR: ARR[15:4] holds the non-dithered part, and ARR[3:0] the dither part for 16b timers - * - CCRx: CCRx[15:4] holds the non-dithered part, and CCRx[3:0] the dither part for 16b timers - * - ARR and CCRx values are limited to 0xFFEF in dithering mode for 16b timers - * (corresponds to 4094 for the integer part and 15 for the dithered part). - * @note Macros @ref __HAL_TIM_CALC_PERIOD_DITHER() __HAL_TIM_CALC_DELAY_DITHER() __HAL_TIM_CALC_PULSE_DITHER() - * can be used to calculate period (ARR) and delay (CCRx) value. - * @note Enabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. - * @note Enabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. - * So it may be necessary to read ARR value or CCRx value with macros @ref __HAL_TIM_GET_AUTORELOAD() - * __HAL_TIM_GET_COMPARE() and if necessary update Init structure field htim->Init.Period . - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DitheringEnable(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(htim->Instance)); - - SET_BIT(htim->Instance->CR1, TIM_CR1_DITHEN); - return HAL_OK; -} - -/** - * @brief Disable dithering - * @param htim TIM handle - * @note This function must be called when timer is stopped or disabled (CEN =0) - * @note If dithering is activated, pay attention to ARR, CCRx, CNT interpretation: - * - CNT: only CNT[11:0] holds the non-dithered part for 16b timers (or CNT[26:0] for 32b timers) - * - ARR: ARR[15:4] holds the non-dithered part, and ARR[3:0] the dither part for 16b timers - * - CCRx: CCRx[15:4] holds the non-dithered part, and CCRx[3:0] the dither part for 16b timers - * - ARR and CCRx values are limited to 0xFFEF in dithering mode - * (corresponds to 4094 for the integer part and 15 for the dithered part). - * @note Disabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. - * So it may be necessary to read ARR value or CCRx value with macros @ref __HAL_TIM_GET_AUTORELOAD() - * __HAL_TIM_GET_COMPARE() and if necessary update Init structure field htim->Init.Period . - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DitheringDisable(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(htim->Instance)); - - CLEAR_BIT(htim->Instance->CR1, TIM_CR1_DITHEN); - return HAL_OK; -} - -/** - * @brief Initializes the pulse on compare pulse width and pulse prescaler - * @param htim TIM Output Compare handle - * @param PulseWidthPrescaler Pulse width prescaler - * This parameter can be a number between Min_Data = 0x0 and Max_Data = 0x7 - * @param PulseWidth Pulse width - * This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_OC_ConfigPulseOnCompare(TIM_HandleTypeDef *htim, - uint32_t PulseWidthPrescaler, - uint32_t PulseWidth) -{ - uint32_t tmpecr; - - /* Check the parameters */ - assert_param(IS_TIM_PULSEONCOMPARE_INSTANCE(htim->Instance)); - assert_param(IS_TIM_PULSEONCOMPARE_WIDTH(PulseWidth)); - assert_param(IS_TIM_PULSEONCOMPARE_WIDTHPRESCALER(PulseWidthPrescaler)); - - /* Process Locked */ - __HAL_LOCK(htim); - - /* Set the TIM state */ - htim->State = HAL_TIM_STATE_BUSY; - - /* Get the TIMx ECR register value */ - tmpecr = htim->Instance->ECR; - /* Reset the Pulse width prescaler and the Pulse width */ - tmpecr &= ~(TIM_ECR_PWPRSC | TIM_ECR_PW); - /* Set the Pulse width prescaler and Pulse width*/ - tmpecr |= PulseWidthPrescaler << TIM_ECR_PWPRSC_Pos; - tmpecr |= PulseWidth << TIM_ECR_PW_Pos; - /* Write to TIMx ECR */ - htim->Instance->ECR = tmpecr; - - /* Change the TIM state */ - htim->State = HAL_TIM_STATE_READY; - - /* Release Lock */ - __HAL_UNLOCK(htim); - - return HAL_OK; -} - -/** - * @brief Configure preload source of Slave Mode Selection bitfield (SMS in SMCR register) - * @param htim TIM handle - * @param Source Source of slave mode selection preload - * This parameter can be one of the following values: - * @arg TIM_SMS_PRELOAD_SOURCE_UPDATE: Timer update event is used as source of Slave Mode Selection preload - * @arg TIM_SMS_PRELOAD_SOURCE_INDEX: Timer index event is used as source of Slave Mode Selection preload - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ConfigSlaveModePreload(TIM_HandleTypeDef *htim, uint32_t Source) -{ - /* Check the parameters */ - assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); - assert_param(IS_TIM_SLAVE_PRELOAD_SOURCE(Source)); - - MODIFY_REG(htim->Instance->SMCR, TIM_SMCR_SMSPS, Source); - return HAL_OK; -} - -/** - * @brief Enable preload of Slave Mode Selection bitfield (SMS in SMCR register) - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_EnableSlaveModePreload(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); - - SET_BIT(htim->Instance->SMCR, TIM_SMCR_SMSPE); - return HAL_OK; -} - -/** - * @brief Disable preload of Slave Mode Selection bitfield (SMS in SMCR register) - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DisableSlaveModePreload(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); - - CLEAR_BIT(htim->Instance->SMCR, TIM_SMCR_SMSPE); - return HAL_OK; -} - -/** - * @brief Enable deadtime preload - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_EnableDeadTimePreload(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - - SET_BIT(htim->Instance->DTR2, TIM_DTR2_DTPE); - return HAL_OK; -} - -/** - * @brief Disable deadtime preload - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DisableDeadTimePreload(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - - CLEAR_BIT(htim->Instance->DTR2, TIM_DTR2_DTPE); - return HAL_OK; -} - -/** - * @brief Configure deadtime - * @param htim TIM handle - * @param Deadtime Deadtime value - * @note This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ConfigDeadTime(TIM_HandleTypeDef *htim, uint32_t Deadtime) -{ - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - assert_param(IS_TIM_DEADTIME(Deadtime)); - - MODIFY_REG(htim->Instance->BDTR, TIM_BDTR_DTG, Deadtime); - return HAL_OK; -} - -/** - * @brief Configure asymmetrical deadtime - * @param htim TIM handle - * @param FallingDeadtime Falling edge deadtime value - * @note This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ConfigAsymmetricalDeadTime(TIM_HandleTypeDef *htim, uint32_t FallingDeadtime) -{ - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - assert_param(IS_TIM_DEADTIME(FallingDeadtime)); - - MODIFY_REG(htim->Instance->DTR2, TIM_DTR2_DTGF, FallingDeadtime); - return HAL_OK; -} - -/** - * @brief Enable asymmetrical deadtime - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_EnableAsymmetricalDeadTime(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - - SET_BIT(htim->Instance->DTR2, TIM_DTR2_DTAE); - return HAL_OK; -} - -/** - * @brief Disable asymmetrical deadtime - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DisableAsymmetricalDeadTime(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); - - CLEAR_BIT(htim->Instance->DTR2, TIM_DTR2_DTAE); - return HAL_OK; -} - -/** - * @brief Configures the encoder index. - * @note warning in case of encoder mode clock plus direction - * @ref TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X1 or @ref TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X2 - * Direction must be set to @ref TIM_ENCODERINDEX_DIRECTION_UP_DOWN - * @param htim TIM handle. - * @param sEncoderIndexConfig Encoder index configuration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_ConfigEncoderIndex(TIM_HandleTypeDef *htim, - TIMEx_EncoderIndexConfigTypeDef *sEncoderIndexConfig) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - assert_param(IS_TIM_ENCODERINDEX_POLARITY(sEncoderIndexConfig->Polarity)); - assert_param(IS_TIM_ENCODERINDEX_PRESCALER(sEncoderIndexConfig->Prescaler)); - assert_param(IS_TIM_ENCODERINDEX_FILTER(sEncoderIndexConfig->Filter)); - assert_param(IS_TIM_ENCODERINDEX_BLANKING(sEncoderIndexConfig->Blanking)); - assert_param(IS_FUNCTIONAL_STATE(sEncoderIndexConfig->FirstIndexEnable)); - assert_param(IS_TIM_ENCODERINDEX_POSITION(sEncoderIndexConfig->Position)); - assert_param(IS_TIM_ENCODERINDEX_DIRECTION(sEncoderIndexConfig->Direction)); - - /* Process Locked */ - __HAL_LOCK(htim); - - /* Configures the TIMx External Trigger (ETR) which is used as Index input */ - TIM_ETR_SetConfig(htim->Instance, - sEncoderIndexConfig->Prescaler, - sEncoderIndexConfig->Polarity, - sEncoderIndexConfig->Filter); - - /* Configures the encoder index */ - MODIFY_REG(htim->Instance->ECR, - TIM_ECR_IDIR_Msk | TIM_ECR_IBLK_Msk | TIM_ECR_FIDX_Msk | TIM_ECR_IPOS_Msk, - (sEncoderIndexConfig->Direction | - (sEncoderIndexConfig->Blanking) | - ((sEncoderIndexConfig->FirstIndexEnable == ENABLE) ? (0x1U << TIM_ECR_FIDX_Pos) : 0U) | - sEncoderIndexConfig->Position | - TIM_ECR_IE)); - - __HAL_UNLOCK(htim); - - return HAL_OK; -} - -/** - * @brief Enable encoder index - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_EnableEncoderIndex(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - SET_BIT(htim->Instance->ECR, TIM_ECR_IE); - return HAL_OK; -} - -/** - * @brief Disable encoder index - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DisableEncoderIndex(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - CLEAR_BIT(htim->Instance->ECR, TIM_ECR_IE); - return HAL_OK; -} - -/** - * @brief Enable encoder first index - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_EnableEncoderFirstIndex(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - SET_BIT(htim->Instance->ECR, TIM_ECR_FIDX); - return HAL_OK; -} - -/** - * @brief Disable encoder first index - * @param htim TIM handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_TIMEx_DisableEncoderFirstIndex(TIM_HandleTypeDef *htim) -{ - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); - - CLEAR_BIT(htim->Instance->ECR, TIM_ECR_FIDX); - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup TIMEx_Exported_Functions_Group6 Extended Callbacks functions - * @brief Extended Callbacks functions - * -@verbatim - ============================================================================== - ##### Extended Callbacks functions ##### - ============================================================================== - [..] - This section provides Extended TIM callback functions: - (+) Timer Commutation callback - (+) Timer Break callback - -@endverbatim - * @{ - */ - -/** - * @brief Commutation callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_CommutCallback could be implemented in the user file - */ -} -/** - * @brief Commutation half complete callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_CommutHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Break detection callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_BreakCallback could be implemented in the user file - */ -} - -/** - * @brief Break2 detection callback in non blocking mode - * @param htim: TIM handle - * @retval None - */ -__weak void HAL_TIMEx_Break2Callback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_TIMEx_Break2Callback could be implemented in the user file - */ -} - -/** - * @brief Encoder index callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_EncoderIndexCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_EncoderIndexCallback could be implemented in the user file - */ -} - -/** - * @brief Direction change callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_DirectionChangeCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_DirectionChangeCallback could be implemented in the user file - */ -} - -/** - * @brief Index error callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_IndexErrorCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_IndexErrorCallback could be implemented in the user file - */ -} - -/** - * @brief Transition error callback in non-blocking mode - * @param htim TIM handle - * @retval None - */ -__weak void HAL_TIMEx_TransitionErrorCallback(TIM_HandleTypeDef *htim) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(htim); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_TIMEx_TransitionErrorCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup TIMEx_Exported_Functions_Group7 Extended Peripheral State functions - * @brief Extended Peripheral State functions - * -@verbatim - ============================================================================== - ##### Extended Peripheral State functions ##### - ============================================================================== - [..] - This subsection permits to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the TIM Hall Sensor interface handle state. - * @param htim TIM Hall Sensor handle - * @retval HAL state - */ -HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(const TIM_HandleTypeDef *htim) -{ - return htim->State; -} - -/** - * @brief Return actual state of the TIM complementary channel. - * @param htim TIM handle - * @param ChannelN TIM Complementary 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 TIM Complementary channel state - */ -HAL_TIM_ChannelStateTypeDef HAL_TIMEx_GetChannelNState(const TIM_HandleTypeDef *htim, uint32_t ChannelN) -{ - HAL_TIM_ChannelStateTypeDef channel_state; - - /* Check the parameters */ - assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, ChannelN)); - - channel_state = TIM_CHANNEL_N_STATE_GET(htim, ChannelN); - - return channel_state; -} -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup TIMEx_Private_Functions TIM Extended Private Functions - * @{ - */ - -/** - * @brief TIM DMA Commutation callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Change the htim state */ - htim->State = HAL_TIM_STATE_READY; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->CommutationCallback(htim); -#else - HAL_TIMEx_CommutCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ -} - -/** - * @brief TIM DMA Commutation half complete callback. - * @param hdma pointer to DMA handle. - * @retval None - */ -void TIMEx_DMACommutationHalfCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Change the htim state */ - htim->State = HAL_TIM_STATE_READY; - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->CommutationHalfCpltCallback(htim); -#else - HAL_TIMEx_CommutHalfCpltCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ -} - - -/** - * @brief TIM DMA Delay Pulse complete callback (complementary channel). - * @param hdma pointer to DMA handle. - * @retval None - */ -static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->PWM_PulseFinishedCallback(htim); -#else - HAL_TIM_PWM_PulseFinishedCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @brief TIM DMA error callback (complementary channel) - * @param hdma pointer to DMA handle. - * @retval None - */ -static void TIM_DMAErrorCCxN(DMA_HandleTypeDef *hdma) -{ - TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - if (hdma == htim->hdma[TIM_DMA_ID_CC1]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); - } - else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) - { - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; - TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); - } - else - { - /* nothing to do */ - } - -#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) - htim->ErrorCallback(htim); -#else - HAL_TIM_ErrorCallback(htim); -#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ - - htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; -} - -/** - * @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 - * @arg TIM_CHANNEL_4: TIM Channel 4 - * @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; - - tmp = TIM_CCER_CC1NE << (Channel & 0xFU); /* 0xFU = 15 bits max shift */ - - /* Reset the CCxNE Bit */ - TIMx->CCER &= ~tmp; - - /* Set or reset the CCxNE Bit */ - TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0xFU)); /* 0xFU = 15 bits max shift */ -} -/** - * @} - */ - -#endif /* HAL_TIM_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_tim_ex.c + * @author MCD Application Team + * @brief TIM HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Timer Extended peripheral: + * + Time Hall Sensor Interface Initialization + * + Time Hall Sensor Interface Start + * + Time Complementary signal break and dead time configuration + * + Time Master and Slave synchronization configuration + * + Time Output Compare/PWM Channel Configuration (for channels 5 and 6) + * + Timer remapping capabilities configuration + * + Timer encoder index configuration + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### TIMER Extended features ##### + ============================================================================== + [..] + The Timer Extended features include: + (#) Complementary outputs with programmable dead-time for : + (++) 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 + (#) In case of Pulse on compare, configure pulse length and delay + (#) Encoder index configuration + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the TIM low level resources by implementing the following functions + depending on the selected feature: + (++) Hall Sensor output : HAL_TIMEx_HallSensor_MspInit() + + (#) Initialize the TIM low level resources : + (##) Enable the TIM interface clock using __HAL_RCC_TIMx_CLK_ENABLE(); + (##) TIM pins configuration + (+++) Enable the clock for the TIM GPIOs using the following function: + __HAL_RCC_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_ConfigCommutEvent(): 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). + (#) In case of Pulse On Compare: + (++) HAL_TIMEx_OC_ConfigPulseOnCompare(): to configure pulse width and prescaler + + + (#) Activate the TIM peripheral using one of the start functions: + (++) Complementary Output Compare : HAL_TIMEx_OCN_Start(), HAL_TIMEx_OCN_Start_DMA(), + HAL_TIMEx_OCN_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 + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup TIMEx TIMEx + * @brief TIM Extended HAL module driver + * @{ + */ + +#ifdef HAL_TIM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup TIMEx_Private_Constants TIM Extended Private Constants + * @{ + */ +/* Timeout for break input rearm */ +#define TIM_BREAKINPUT_REARM_TIMEOUT 5UL /* 5 milliseconds */ +/** + * @} + */ +/* End of private constants --------------------------------------------------*/ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMAErrorCCxN(DMA_HandleTypeDef *hdma); +static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup TIMEx_Exported_Functions TIM Extended Exported Functions + * @{ + */ + +/** @defgroup TIMEx_Exported_Functions_Group1 Extended 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 initialize the associated handle. + * @note When the timer instance is initialized in Hall Sensor Interface mode, + * timer channels 1 and channel 2 are reserved and cannot be used for + * other purpose. + * @param htim TIM Hall Sensor Interface handle + * @param sConfig TIM Hall Sensor configuration structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, const TIM_HallSensor_InitTypeDef *sConfig) +{ + TIM_OC_InitTypeDef OC_Config; + + /* Check the TIM handle allocation */ + if (htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_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_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); + assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); + assert_param(IS_TIM_PERIOD(htim, htim->Init.Period)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); + assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); + + if (htim->State == HAL_TIM_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + htim->Lock = HAL_UNLOCKED; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + /* Reset interrupt callbacks to legacy week callbacks */ + TIM_ResetCallback(htim); + + if (htim->HallSensor_MspInitCallback == NULL) + { + htim->HallSensor_MspInitCallback = HAL_TIMEx_HallSensor_MspInit; + } + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + htim->HallSensor_MspInitCallback(htim); +#else + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIMEx_HallSensor_MspInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + } + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* 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 DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_READY; + + /* Initialize the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* 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 Interface 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); + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + if (htim->HallSensor_MspDeInitCallback == NULL) + { + htim->HallSensor_MspDeInitCallback = HAL_TIMEx_HallSensor_MspDeInit; + } + /* DeInit the low level hardware */ + htim->HallSensor_MspDeInitCallback(htim); +#else + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIMEx_HallSensor_MspDeInit(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + /* Change the DMA burst operation state */ + htim->DMABurstState = HAL_DMA_BURST_STATE_RESET; + + /* Change the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_RESET); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_RESET); + + /* 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 Hall Sensor Interface handle + * @retval None + */ +__weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Hall Sensor Interface handle + * @retval None + */ +__weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(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 Interface handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) +{ + uint32_t tmpsmcr; + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); + + /* Check the TIM channels state */ + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the Input Capture channel 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, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Hall sensor Interface. + * @param htim TIM Hall Sensor Interface handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_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); + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Hall Sensor Interface in interrupt mode. + * @param htim TIM Hall Sensor Interface handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) +{ + uint32_t tmpsmcr; + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); + + /* Check the TIM channels state */ + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the capture compare Interrupts 1 event */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + + /* Enable the Input Capture channel 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, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Hall Sensor Interface in interrupt mode. + * @param htim TIM Hall Sensor Interface handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channel 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); + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Hall Sensor Interface in DMA mode. + * @param htim TIM Hall Sensor Interface 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) +{ + uint32_t tmpsmcr; + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); + + /* Set the TIM channel state */ + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) + || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY)) + { + return HAL_BUSY; + } + else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) + && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY)) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + + /* Enable the Input Capture channel 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 Callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMACaptureHalfCplt; + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; + + /* Enable the DMA channel for Capture 1*/ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the capture compare 1 Interrupt */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Hall Sensor Interface in DMA mode. + * @param htim TIM Hall Sensor Interface handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channel 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); + + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channel state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Exported_Functions_Group2 Extended 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) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Check the TIM complementary channel state */ + if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __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 Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + + /* 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) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Check the TIM complementary channel state */ + if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the TIM Break interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK); + + /* Enable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpccer; + + /* 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the TIM Break interrupt (only if no more channel is active) */ + tmpccer = htim->Instance->CCER; + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) + { + __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); + } + + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @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, const uint32_t *pData, + uint16_t Length) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Set the TIM complementary channel state */ + if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) + { + return HAL_BUSY; + } + else if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + break; + } + + case TIM_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + break; + } + + case TIM_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + break; + } + + case TIM_CHANNEL_4: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* 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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + + case TIM_CHANNEL_2: + { + /* Disable the TIM Output Compare DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + + case TIM_CHANNEL_3: + { + /* Disable the TIM Output Compare DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + + case TIM_CHANNEL_4: + { + /* Disable the TIM Output Compare interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Exported_Functions_Group3 Extended 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. +@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) +{ + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Check the TIM complementary channel state */ + if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __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 Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + + /* 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) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Check the TIM complementary channel state */ + if (TIM_CHANNEL_N_STATE_GET(htim, Channel) != HAL_TIM_CHANNEL_STATE_READY) + { + return HAL_ERROR; + } + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + + 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: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* 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 Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpccer; + + /* 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 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the TIM Break interrupt (only if no more channel is active) */ + tmpccer = htim->Instance->CCER; + if ((tmpccer & TIM_CCER_CCxNE_MASK) == (uint32_t)RESET) + { + __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); + } + + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @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, const uint32_t *pData, + uint16_t Length) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Set the TIM complementary channel state */ + if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_BUSY) + { + return HAL_BUSY; + } + else if (TIM_CHANNEL_N_STATE_GET(htim, Channel) == HAL_TIM_CHANNEL_STATE_READY) + { + if ((pData == NULL) || (Length == 0U)) + { + return HAL_ERROR; + } + else + { + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_BUSY); + } + } + else + { + return HAL_ERROR; + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC1]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + break; + } + + case TIM_CHANNEL_2: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC2]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + break; + } + + case TIM_CHANNEL_3: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC3]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + break; + } + + case TIM_CHANNEL_4: + { + /* Set the DMA compare callbacks */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseNCplt; + htim->hdma[TIM_DMA_ID_CC4]->XferHalfCpltCallback = TIM_DMADelayPulseHalfCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAErrorCCxN ; + + /* Enable the DMA channel */ + if (TIM_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, + Length) != HAL_OK) + { + /* Return error status */ + return HAL_ERROR; + } + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Enable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral, except in trigger mode where enable is automatically done with trigger */ + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + tmpsmcr = htim->Instance->SMCR & TIM_SMCR_SMS; + if (!IS_TIM_SLAVEMODE_TRIGGER_ENABLED(tmpsmcr)) + { + __HAL_TIM_ENABLE(htim); + } + } + else + { + __HAL_TIM_ENABLE(htim); + } + } + + /* Return function status */ + return status; +} + +/** + * @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) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* 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); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC1]); + break; + } + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC2]); + break; + } + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC3]); + break; + } + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + (void)HAL_DMA_Abort_IT(htim->hdma[TIM_DMA_ID_CC4]); + break; + } + + default: + status = HAL_ERROR; + break; + } + + if (status == HAL_OK) + { + /* Disable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM complementary channel state */ + TIM_CHANNEL_N_STATE_SET(htim, Channel, HAL_TIM_CHANNEL_STATE_READY); + } + + /* Return function status */ + return status; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Exported_Functions_Group4 Extended 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 complementary + * output. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel pulse output channel to enable + * 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) +{ + uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Check the TIM channels state */ + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + + /* Enable the complementary One Pulse output channel and the Input Capture channel */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); + TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_ENABLE); + + /* Enable the Main Output */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM One Pulse signal generation on the complementary + * output. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel pulse output channel to 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_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Disable the complementary One Pulse output channel and the Input Capture channel */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); + TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_DISABLE); + + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM One Pulse signal generation in interrupt mode on the + * complementary channel. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel pulse output channel to enable + * 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) +{ + uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; + HAL_TIM_ChannelStateTypeDef channel_1_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef channel_2_state = TIM_CHANNEL_STATE_GET(htim, TIM_CHANNEL_2); + HAL_TIM_ChannelStateTypeDef complementary_channel_1_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_1); + HAL_TIM_ChannelStateTypeDef complementary_channel_2_state = TIM_CHANNEL_N_STATE_GET(htim, TIM_CHANNEL_2); + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Check the TIM channels state */ + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) + || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) + { + return HAL_ERROR; + } + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); + + /* 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 channel and the Input Capture channel */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); + TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_ENABLE); + + /* 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 on the + * complementary channel. + * @note OutputChannel must match the pulse output channel chosen when calling + * @ref HAL_TIM_OnePulse_ConfigChannel(). + * @param htim TIM One Pulse handle + * @param OutputChannel pulse output channel to 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_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + uint32_t input_channel = (OutputChannel == TIM_CHANNEL_1) ? TIM_CHANNEL_2 : TIM_CHANNEL_1; + + /* 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 channel and the Input Capture channel */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); + TIM_CCxChannelCmd(htim->Instance, input_channel, TIM_CCx_DISABLE); + + /* Disable the Main Output */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Set the TIM channels state */ + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Exported_Functions_Group5 Extended Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Configure the commutation event in case of use of the Hall sensor interface. + (+) Configure Output channels for OC and PWM mode. + + (+) Configure Complementary channels, break features and dead time. + (+) Configure Master synchronization. + (+) Configure timer remapping capabilities. + (+) Select timer input source. + (+) Enable or disable channel grouping. + (+) Configure Pulse on compare. + (+) Configure Encoder index. + +@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_ITR4: Internal trigger 4 selected + * @arg TIM_TS_ITR5: Internal trigger 5 selected + * @arg TIM_TS_ITR6: Internal trigger 6 selected + * @arg TIM_TS_ITR7: Internal trigger 7 selected + * @arg TIM_TS_ITR8: Internal trigger 8 selected + * @arg TIM_TS_ITR9: Internal trigger 9 selected + * @arg TIM_TS_ITR10: Internal trigger 10 selected + * @arg TIM_TS_ITR11: Internal trigger 11 selected + * @arg TIM_TS_ITR13: Internal trigger 13 selected + * @arg TIM_TS_ITR14: Internal trigger 14 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_ConfigCommutEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, + uint32_t CommutationSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); + + __HAL_LOCK(htim); + + if (CommutationSource == TIM_COMMUTATION_TRGI) + { + /* 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; + + /* Disable Commutation Interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_COM); + + /* Disable Commutation DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_COM); + + __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_ITR4: Internal trigger 4 selected + * @arg TIM_TS_ITR5: Internal trigger 5 selected + * @arg TIM_TS_ITR6: Internal trigger 6 selected + * @arg TIM_TS_ITR7: Internal trigger 7 selected + * @arg TIM_TS_ITR8: Internal trigger 8 selected + * @arg TIM_TS_ITR9: Internal trigger 9 selected + * @arg TIM_TS_ITR10: Internal trigger 10 selected + * @arg TIM_TS_ITR11: Internal trigger 11 selected + * @arg TIM_TS_ITR13: Internal trigger 13 selected + * @arg TIM_TS_ITR14: Internal trigger 14 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_ConfigCommutEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, + uint32_t CommutationSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); + + __HAL_LOCK(htim); + + if (CommutationSource == TIM_COMMUTATION_TRGI) + { + /* 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; + + /* Disable Commutation DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_COM); + + /* Enable the Commutation Interrupt */ + __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_ITR4: Internal trigger 4 selected + * @arg TIM_TS_ITR5: Internal trigger 5 selected + * @arg TIM_TS_ITR6: Internal trigger 6 selected + * @arg TIM_TS_ITR7: Internal trigger 7 selected + * @arg TIM_TS_ITR8: Internal trigger 8 selected + * @arg TIM_TS_ITR9: Internal trigger 9 selected + * @arg TIM_TS_ITR10: Internal trigger 10 selected + * @arg TIM_TS_ITR11: Internal trigger 11 selected + * @arg TIM_TS_ITR13: Internal trigger 13 selected + * @arg TIM_TS_ITR14: Internal trigger 14 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_ConfigCommutEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, + uint32_t CommutationSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(htim->Instance, InputTrigger)); + + __HAL_LOCK(htim); + + if (CommutationSource == TIM_COMMUTATION_TRGI) + { + /* 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 = TIMEx_DMACommutationCplt; + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferHalfCpltCallback = TIMEx_DMACommutationHalfCplt; + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError; + + /* Disable Commutation Interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_COM); + + /* 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, + const TIM_MasterConfigTypeDef *sMasterConfig) +{ + uint32_t tmpcr2; + uint32_t tmpsmcr; + + /* 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)); + + /* Check input state */ + __HAL_LOCK(htim); + + /* Change the handler state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Get the TIMx CR2 register value */ + tmpcr2 = htim->Instance->CR2; + + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + + /* If the timer supports ADC synchronization through TRGO2, set the master mode selection 2 */ + if (IS_TIM_TRGO2_INSTANCE(htim->Instance)) + { + /* Check the parameters */ + assert_param(IS_TIM_TRGO2_SOURCE(sMasterConfig->MasterOutputTrigger2)); + + /* Clear the MMS2 bits */ + tmpcr2 &= ~TIM_CR2_MMS2; + /* Select the TRGO2 source*/ + tmpcr2 |= sMasterConfig->MasterOutputTrigger2; + } + + /* Reset the MMS Bits */ + tmpcr2 &= ~TIM_CR2_MMS; + /* Select the TRGO source */ + tmpcr2 |= sMasterConfig->MasterOutputTrigger; + + /* Update TIMx CR2 */ + htim->Instance->CR2 = tmpcr2; + + if (IS_TIM_SLAVE_INSTANCE(htim->Instance)) + { + /* Reset the MSM Bit */ + tmpsmcr &= ~TIM_SMCR_MSM; + /* Set master mode */ + tmpsmcr |= sMasterConfig->MasterSlaveMode; + + /* Update TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + } + + /* Change the htim state */ + 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_ConfigBreakDeadConfigTypeDef structure that + * contains the BDTR Register configuration information for the TIM peripheral. + * @note Interrupts can be generated when an active level is detected on the + * break input, the break 2 input or the system break input. Break + * interrupt can be enabled by calling the @ref __HAL_TIM_ENABLE_IT macro. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, + const TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) +{ + /* Keep this variable initialized to 0 as it is used to configure BDTR register */ + uint32_t tmpbdtr = 0U; + + /* Check the parameters */ + assert_param(IS_TIM_BREAK_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_DEADTIME(sBreakDeadTimeConfig->DeadTime)); + assert_param(IS_TIM_BREAK_STATE(sBreakDeadTimeConfig->BreakState)); + assert_param(IS_TIM_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity)); + assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->BreakFilter)); + assert_param(IS_TIM_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput)); + assert_param(IS_TIM_BREAK_AFMODE(sBreakDeadTimeConfig->BreakAFMode)); + + /* Check input state */ + __HAL_LOCK(htim); + + /* 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 */ + + /* Set the BDTR bits */ + MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, sBreakDeadTimeConfig->DeadTime); + MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, sBreakDeadTimeConfig->LockLevel); + MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, sBreakDeadTimeConfig->OffStateIDLEMode); + MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, sBreakDeadTimeConfig->OffStateRunMode); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, sBreakDeadTimeConfig->BreakState); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, sBreakDeadTimeConfig->BreakPolarity); + MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, sBreakDeadTimeConfig->AutomaticOutput); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, (sBreakDeadTimeConfig->BreakFilter << TIM_BDTR_BKF_Pos)); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, sBreakDeadTimeConfig->BreakAFMode); + + if (IS_TIM_BKIN2_INSTANCE(htim->Instance)) + { + /* Check the parameters */ + assert_param(IS_TIM_BREAK2_STATE(sBreakDeadTimeConfig->Break2State)); + assert_param(IS_TIM_BREAK2_POLARITY(sBreakDeadTimeConfig->Break2Polarity)); + assert_param(IS_TIM_BREAK_FILTER(sBreakDeadTimeConfig->Break2Filter)); + assert_param(IS_TIM_BREAK2_AFMODE(sBreakDeadTimeConfig->Break2AFMode)); + + /* Set the BREAK2 input related BDTR bits */ + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (sBreakDeadTimeConfig->Break2Filter << TIM_BDTR_BK2F_Pos)); + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, sBreakDeadTimeConfig->Break2State); + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, sBreakDeadTimeConfig->Break2Polarity); + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, sBreakDeadTimeConfig->Break2AFMode); + } + + /* Set TIMx_BDTR */ + htim->Instance->BDTR = tmpbdtr; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the break input source. + * @param htim TIM handle. + * @param BreakInput Break input to configure + * This parameter can be one of the following values: + * @arg TIM_BREAKINPUT_BRK: Timer break input + * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input + * @param sBreakInputConfig Break input source configuration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigBreakInput(TIM_HandleTypeDef *htim, + uint32_t BreakInput, + const TIMEx_BreakInputConfigTypeDef *sBreakInputConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmporx; + uint32_t bkin_enable_mask; + uint32_t bkin_polarity_mask; + uint32_t bkin_enable_bitpos; + uint32_t bkin_polarity_bitpos; + + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + assert_param(IS_TIM_BREAKINPUT(BreakInput)); + assert_param(IS_TIM_BREAKINPUTSOURCE(sBreakInputConfig->Source)); + assert_param(IS_TIM_BREAKINPUTSOURCE_STATE(sBreakInputConfig->Enable)); + assert_param(IS_TIM_BREAKINPUTSOURCE_POLARITY(sBreakInputConfig->Polarity)); + + /* Check input state */ + __HAL_LOCK(htim); + + switch (sBreakInputConfig->Source) + { + case TIM_BREAKINPUTSOURCE_BKIN: + { + bkin_enable_mask = TIM_AF1_BKINE; + bkin_enable_bitpos = TIM_AF1_BKINE_Pos; + bkin_polarity_mask = TIM_AF1_BKINP; + bkin_polarity_bitpos = TIM_AF1_BKINP_Pos; + break; + } + + default: + { + bkin_enable_mask = 0U; + bkin_polarity_mask = 0U; + bkin_enable_bitpos = 0U; + bkin_polarity_bitpos = 0U; + break; + } + } + + switch (BreakInput) + { + case TIM_BREAKINPUT_BRK: + { + /* Get the TIMx_AF1 register value */ + tmporx = htim->Instance->AF1; + + /* Enable the break input */ + tmporx &= ~bkin_enable_mask; + tmporx |= (sBreakInputConfig->Enable << bkin_enable_bitpos) & bkin_enable_mask; + + /* Set the break input polarity */ + tmporx &= ~bkin_polarity_mask; + tmporx |= (sBreakInputConfig->Polarity << bkin_polarity_bitpos) & bkin_polarity_mask; + + /* Set TIMx_AF1 */ + htim->Instance->AF1 = tmporx; + break; + } + case TIM_BREAKINPUT_BRK2: + { + /* Get the TIMx_AF2 register value */ + tmporx = htim->Instance->AF2; + + /* Enable the break input */ + tmporx &= ~bkin_enable_mask; + tmporx |= (sBreakInputConfig->Enable << bkin_enable_bitpos) & bkin_enable_mask; + + /* Set the break input polarity */ + tmporx &= ~bkin_polarity_mask; + tmporx |= (sBreakInputConfig->Polarity << bkin_polarity_bitpos) & bkin_polarity_mask; + + /* Set TIMx_AF2 */ + htim->Instance->AF2 = tmporx; + break; + } + default: + status = HAL_ERROR; + break; + } + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @brief Configures the TIMx Remapping input capabilities. + * @param htim TIM handle. + * @param Remap specifies the TIM remapping source. + * For TIM1, the parameter can take one of the following values: + * @arg TIM_TIM1_ETR_GPIO TIM1 ETR is connected to GPIO + * @arg TIM_TIM1_ETR_ADC1_AWD1 TIM1 ETR is connected to ADC1 AWD1 + * @arg TIM_TIM1_ETR_ADC1_AWD2 TIM1 ETR is connected to ADC1 AWD2 + * @arg TIM_TIM1_ETR_ADC1_AWD3 TIM1 ETR is connected to ADC1 AWD3 + * @arg TIM_TIM1_ETR_ADC2_AWD1 TIM1 ETR is connected to ADC2 AWD1 + * @arg TIM_TIM1_ETR_ADC2_AWD2 TIM1 ETR is connected to ADC2 AWD2 + * @arg TIM_TIM1_ETR_ADC2_AWD3 TIM1 ETR is connected to ADC2 AWD3 + * + * For TIM2, the parameter can take one of the following values: + * @arg TIM_TIM2_ETR_GPIO TIM2 ETR is connected to GPIO + * @arg TIM_TIM2_ETR_DCMIPP_HSYNC TIM2 ETR is connected to DCMIPP HSYNC pin + * @arg TIM_TIM2_ETR_LTDC_HSYNC TIM2 ETR is connected to LTDC HSYNC pin + * @arg TIM_TIM2_ETR_SAI1_FSA TIM2_ETR is connected to SAI1 FS_A + * @arg TIM_TIM2_ETR_SAI1_FSB TIM2_ETR is connected to SAI1 FS_B + * @arg TIM_TIM2_ETR_GFXTIM_TE TIM2_ETR is connected to GFXTIM TE + * @arg TIM_TIM2_ETR_DCMIPP_HSYNC TIM2 ETR is connected to DCMIPP HSYNC pin + * @arg TIM_TIM2_ETR_LTDC_HSYNC TIM2 ETR is connected to LTDC HSYNC pin + * @arg TIM_TIM3_ETR_TIM3_ETR TIM3_ETR is connected to TIM3 ETR + * @arg TIM_TIM3_ETR_TIM4_ETR TIM3_ETR is connected to TIM4 ETR + * @arg TIM_TIM3_ETR_TIM5_ETR TIM3_ETR is connected to TIM5 ETR + * @arg TIM_TIM2_ETR_ETH_PPS TIM2_ETR is connected to ETH PPS + * + * For TIM3, the parameter can take one of the following values: + * @arg TIM_TIM3_ETR_GPIO TIM3_ETR is not connected to I/O + * @arg TIM_TIM3_ETR_DCMIPP_HSYNC TIM3_ETR is connected to DCMIPP HSYNC + * @arg TIM_TIM3_ETR_LTDC_HSYNC TIM3_ETR is connected to LTDC HSYNC + * @arg TIM_TIM3_ETR_GFXTIM_TE TIM3_ETR is connected to GFXTIM TE + * @arg TIM_TIM3_ETR_DCMIPP_HSYNC TIM3_ETR is connected to DCMIPP VSYNC + * @arg TIM_TIM3_ETR_LTDC_VSYNC TIM3_ETR is connected to LTDC VSYNC + * @arg TIM_TIM3_ETR_TIM2_ETR TIM3_ETR is connected to TIM2 ETR + * @arg TIM_TIM3_ETR_TIM4_ETR TIM3_ETR is connected to TIM4 ETR + * @arg TIM_TIM3_ETR_TIM5_ETR TIM3_ETR is connected to TIM5 ETR + * @arg TIM_TIM3_ETR_ETH_PPS TIM3_ETR is connected to ETH PPS + * + * For TIM4, the parameter can take one of the following values: + * @arg TIM_TIM4_ETR_GPIO TIM4 ETR is connected to GPIO + * @arg TIM_TIM4_ETR_DCMIPP_HSYNC TIM4_ETR is connected to DCMIPP HSYNC + * @arg TIM_TIM4_ETR_LTDC_HSYNC TIM4_ETR is connected to LTDC HSYNC + * @arg TIM_TIM4_ETR_GFXTIM_TE TIM4_ETR is connected to GFXTIM TE + * @arg TIM_TIM4_ETR_DCMIPP_HSYNC TIM4_ETR is connected to DCMIPP VSYNC + * @arg TIM_TIM4_ETR_LTDC_VSYNC TIM4_ETR is connected to LTDC VSYNC + * @arg TIM_TIM4_ETR_TIM2_ETR TIM4_ETR is connected to TIM2 ETR + * @arg TIM_TIM4_ETR_TIM3_ETR TIM4_ETR is connected to TIM3 ETR + * @arg TIM_TIM4_ETR_TIM5_ETR TIM4_ETR is connected to TIM5 ETR + * @arg TIM_TIM4_ETR_ETH1_PPS TIM4_ETR is connected to ETH1 PPS + * + * For TIM5, the parameter can take one of the following values: + * @arg TIM_TIM5_ETR_GPIO TIM5 ETR is connected to GPIO + * @arg TIM_TIM5_ETR_SAI2_FSA TIM5_ETR is connected to SAI2 FS_A + * @arg TIM_TIM5_ETR_SAI2_FSB TIM5_ETR is connected to SAI2 FS_B + * @arg TIM_TIM5_ETR_DCMIPP_HSYNC TIM5_ETR is connected to DCMIPP HSYNC + * @arg TIM_TIM5_ETR_LTDC_HSYNC TIM5_ETR is connected to LTDC HSYNC + * @arg TIM_TIM5_ETR_GFXTIM_TE TIM5_ETR is connected to GFXTIM TE + * @arg TIM_TIM5_ETR_DCMIPP_HSYNC TIM5_ETR is connected to DCMIPP VSYNC + * @arg TIM_TIM5_ETR_LTDC_VSYNC TIM5_ETR is connected to LTDC VSYNC + * @arg TIM_TIM5_ETR_TIM2_ETR TIM5_ETR is connected to TIM2 ETR + * @arg TIM_TIM5_ETR_TIM3_ETR TIM5_ETR is connected to TIM3 ETR + * @arg TIM_TIM5_ETR_TIM3_ETR TIM5_ETR is connected to TIM4 ETR + * + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) +{ + /* Check parameters */ + assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance)); + assert_param(IS_TIM_REMAP(htim->Instance, Remap)); + + __HAL_LOCK(htim); + + MODIFY_REG(htim->Instance->AF1, TIM_AF1_ETRSEL_Msk, Remap); + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Select the timer input source + * @param htim TIM handle. + * @param Channel specifies the TIM Channel + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TI1 input channel + * @arg TIM_CHANNEL_2: TI2 input channel + * @param TISelection parameter of the TIM_TISelectionStruct structure is detailed as follows: + * For TIM2, the parameter is one of the following values: + * @arg TIM_TIM2_TI1_GPIO: TIM2 TI1 is connected to GPIO + * @arg TIM_TIM2_TI1_ETH_PPS: TIM2 TI1 is connected to ETH PPS + * + * For TIM3, the parameter is one of the following values: + * @arg TIM_TIM3_TI1_GPIO: TIM3 TI1 is connected to GPIO + * @arg TIM_TIM3_TI1_ETH_PPS: TIM3 TI1 is connected to ETH PPS + * + * For TIM9, the parameter is one of the following values: + * @arg TIM_TIM9_TI1_GPIO: TIM9 TI1 is connected to GPIO + * @arg TIM_TIM9_TI1_MCO1: TIM9 TI1 is connected to MCO1 + * @arg TIM_TIM9_TI1_MCO2: TIM9 TI1 is connected to MCO2 + * + * For TIM12, the parameter is one of the following values: + * @arg TIM_TIM12_TI1_GPIO: TIM12 TI1 is connected to GPIO + * @arg TIM_TIM12_TI1_SPDIF_FS: TIM12 TI1 is connected to SPDIF FS + * @arg TIM_TIM12_TI1_HSI_1024: TIM12 TI1 is connected to HSI/1024 + * @arg TIM_TIM12_TI1_CSI_128: TIM12_TI1 is connected to CSI/128 + * @arg TIM_TIM12_TI1_MCO1: TIM12 TI1 is connected to MCO1 + * @arg TIM_TIM12_TI1_MCO2: TIM12 TI1 is connected to MCO2 + * + * For TIM15, the parameter is one of the following values: + * @arg TIM_TIM15_TI1_GPIO: TIM15 TI1 is connected to GPIO + * @arg TIM_TIM15_TI1_TIM2_CH1: TIM15 TI1 is connected to TIM2 CH1 + * @arg TIM_TIM15_TI1_TIM3_CH1: TIM15 TI1 is connected to TIM3 CH1 + * @arg TIM_TIM15_TI1_TIM4_CH1: TIM15 TI1 is connected to TIM4 CH1 + * @arg TIM_TIM15_TI1_MCO1: TIM15 TI1 is connected to MCO1 + * @arg TIM_TIM15_TI1_MCO2: TIM15 TI1 is connected to MCO2 + * @arg TIM_TIM15_TI2_GPIO: TIM15 TI2 is connected to GPIO + * @arg TIM_TIM15_TI2_TIM2_CH2: TIM15 TI2 is connected to TIM2 CH2 + * @arg TIM_TIM15_TI2_TIM3_CH2: TIM15 TI2 is connected to TIM3 CH2 + * @arg TIM_TIM15_TI2_TIM4_CH2: TIM15 TI2 is connected to TIM4 CH2 + * + * For TIM16, the parameter is one of the following values: + * @arg TIM_TIM16_TI1_GPIO: TIM16 TI1 is connected to GPIO + * @arg TIM_TIM16_TI1_RTC_WKUP: TIM16 TI1 is connected to RTC wakeup interrupt + * + * For TIM17, the parameter is one of the following values: + * @arg TIM_TIM17_TI1_GPIO: TIM17 TI1 is connected to GPIO + * @arg TIM_TIM17_TI1_SPDIF_FS: TIM17 TI1 is connected to SPDIF FS + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_TISelection(TIM_HandleTypeDef *htim, uint32_t TISelection, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check parameters */ + assert_param(IS_TIM_TISEL_TIX_INSTANCE(htim->Instance, Channel)); + assert_param(IS_TIM_TISEL(TISelection)); + + __HAL_LOCK(htim); + + switch (Channel) + { + case TIM_CHANNEL_1: + MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI1SEL, TISelection); + break; + case TIM_CHANNEL_2: + MODIFY_REG(htim->Instance->TISEL, TIM_TISEL_TI2SEL, TISelection); + break; + default: + status = HAL_ERROR; + break; + } + + __HAL_UNLOCK(htim); + + return status; +} + +/** + * @brief Group channel 5 and channel 1, 2 or 3 + * @param htim TIM handle. + * @param Channels specifies the reference signal(s) the OC5REF is combined with. + * This parameter can be any combination of the following values: + * TIM_GROUPCH5_NONE: No effect of OC5REF on OC1REFC, OC2REFC and OC3REFC + * TIM_GROUPCH5_OC1REFC: OC1REFC is the logical AND of OC1REFC and OC5REF + * TIM_GROUPCH5_OC2REFC: OC2REFC is the logical AND of OC2REFC and OC5REF + * TIM_GROUPCH5_OC3REFC: OC3REFC is the logical AND of OC3REFC and OC5REF + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_GroupChannel5(TIM_HandleTypeDef *htim, uint32_t Channels) +{ + /* Check parameters */ + assert_param(IS_TIM_COMBINED3PHASEPWM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_GROUPCH5(Channels)); + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Clear GC5Cx bit fields */ + htim->Instance->CCR5 &= ~(TIM_CCR5_GC5C3 | TIM_CCR5_GC5C2 | TIM_CCR5_GC5C1); + + /* Set GC5Cx bit fields */ + htim->Instance->CCR5 |= Channels; + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Disarm the designated break input (when it operates in bidirectional mode). + * @param htim TIM handle. + * @param BreakInput Break input to disarm + * This parameter can be one of the following values: + * @arg TIM_BREAKINPUT_BRK: Timer break input + * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input + * @note The break input can be disarmed only when it is configured in + * bidirectional mode and when when MOE is reset. + * @note Purpose is to be able to have the input voltage back to high-state, + * whatever the time constant on the output . + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DisarmBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpbdtr; + + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + assert_param(IS_TIM_BREAKINPUT(BreakInput)); + + switch (BreakInput) + { + case TIM_BREAKINPUT_BRK: + { + /* Check initial conditions */ + tmpbdtr = READ_REG(htim->Instance->BDTR); + if ((READ_BIT(tmpbdtr, TIM_BDTR_BKBID) == TIM_BDTR_BKBID) && + (READ_BIT(tmpbdtr, TIM_BDTR_MOE) == 0U)) + { + /* Break input BRK is disarmed */ + SET_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM); + } + break; + } + case TIM_BREAKINPUT_BRK2: + { + /* Check initial conditions */ + tmpbdtr = READ_REG(htim->Instance->BDTR); + if ((READ_BIT(tmpbdtr, TIM_BDTR_BK2BID) == TIM_BDTR_BK2BID) && + (READ_BIT(tmpbdtr, TIM_BDTR_MOE) == 0U)) + { + /* Break input BRK is disarmed */ + SET_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM); + } + break; + } + default: + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Arm the designated break input (when it operates in bidirectional mode). + * @param htim TIM handle. + * @param BreakInput Break input to arm + * This parameter can be one of the following values: + * @arg TIM_BREAKINPUT_BRK: Timer break input + * @arg TIM_BREAKINPUT_BRK2: Timer break 2 input + * @note Arming is possible at anytime, even if fault is present. + * @note Break input is automatically armed as soon as MOE bit is set. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ReArmBreakInput(const TIM_HandleTypeDef *htim, uint32_t BreakInput) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + assert_param(IS_TIM_BREAKINPUT(BreakInput)); + + switch (BreakInput) + { + case TIM_BREAKINPUT_BRK: + { + /* Check initial conditions */ + if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKBID) == TIM_BDTR_BKBID) + { + /* Break input BRK is re-armed automatically by hardware. Poll to check whether fault condition disappeared */ + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + while (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM) != 0UL) + { + if ((HAL_GetTick() - tickstart) > TIM_BREAKINPUT_REARM_TIMEOUT) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BKDSRM) != 0UL) + { + return HAL_TIMEOUT; + } + } + } + } + break; + } + + case TIM_BREAKINPUT_BRK2: + { + /* Check initial conditions */ + if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2BID) == TIM_BDTR_BK2BID) + { + /* Break input BRK2 is re-armed automatically by hardware. Poll to check whether fault condition disappeared */ + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + while (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM) != 0UL) + { + if ((HAL_GetTick() - tickstart) > TIM_BREAKINPUT_REARM_TIMEOUT) + { + /* New check to avoid false timeout detection in case of preemption */ + if (READ_BIT(htim->Instance->BDTR, TIM_BDTR_BK2DSRM) != 0UL) + { + return HAL_TIMEOUT; + } + } + } + } + break; + } + default: + status = HAL_ERROR; + break; + } + + return status; +} + +/** + * @brief Enable dithering + * @param htim TIM handle + * @note Main usage is PWM mode + * @note This function must be called when timer is stopped or disabled (CEN =0) + * @note If dithering is activated, pay attention to ARR, CCRx, CNT interpretation: + * - CNT: only CNT[11:0] holds the non-dithered part for 16b timers (or CNT[26:0] for 32b timers) + * - ARR: ARR[15:4] holds the non-dithered part, and ARR[3:0] the dither part for 16b timers + * - CCRx: CCRx[15:4] holds the non-dithered part, and CCRx[3:0] the dither part for 16b timers + * - ARR and CCRx values are limited to 0xFFEF in dithering mode for 16b timers + * (corresponds to 4094 for the integer part and 15 for the dithered part). + * @note Macros @ref __HAL_TIM_CALC_PERIOD_DITHER() __HAL_TIM_CALC_DELAY_DITHER() __HAL_TIM_CALC_PULSE_DITHER() + * can be used to calculate period (ARR) and delay (CCRx) value. + * @note Enabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. + * @note Enabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. + * So it may be necessary to read ARR value or CCRx value with macros @ref __HAL_TIM_GET_AUTORELOAD() + * __HAL_TIM_GET_COMPARE() and if necessary update Init structure field htim->Init.Period . + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DitheringEnable(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + SET_BIT(htim->Instance->CR1, TIM_CR1_DITHEN); + return HAL_OK; +} + +/** + * @brief Disable dithering + * @param htim TIM handle + * @note This function must be called when timer is stopped or disabled (CEN =0) + * @note If dithering is activated, pay attention to ARR, CCRx, CNT interpretation: + * - CNT: only CNT[11:0] holds the non-dithered part for 16b timers (or CNT[26:0] for 32b timers) + * - ARR: ARR[15:4] holds the non-dithered part, and ARR[3:0] the dither part for 16b timers + * - CCRx: CCRx[15:4] holds the non-dithered part, and CCRx[3:0] the dither part for 16b timers + * - ARR and CCRx values are limited to 0xFFEF in dithering mode + * (corresponds to 4094 for the integer part and 15 for the dithered part). + * @note Disabling dithering, modifies automatically values of registers ARR/CCRx to keep the same integer part. + * So it may be necessary to read ARR value or CCRx value with macros @ref __HAL_TIM_GET_AUTORELOAD() + * __HAL_TIM_GET_COMPARE() and if necessary update Init structure field htim->Init.Period . + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DitheringDisable(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + CLEAR_BIT(htim->Instance->CR1, TIM_CR1_DITHEN); + return HAL_OK; +} + +/** + * @brief Initializes the pulse on compare pulse width and pulse prescaler + * @param htim TIM Output Compare handle + * @param PulseWidthPrescaler Pulse width prescaler + * This parameter can be a number between Min_Data = 0x0 and Max_Data = 0x7 + * @param PulseWidth Pulse width + * This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OC_ConfigPulseOnCompare(TIM_HandleTypeDef *htim, + uint32_t PulseWidthPrescaler, + uint32_t PulseWidth) +{ + uint32_t tmpecr; + + /* Check the parameters */ + assert_param(IS_TIM_PULSEONCOMPARE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_PULSEONCOMPARE_WIDTH(PulseWidth)); + assert_param(IS_TIM_PULSEONCOMPARE_WIDTHPRESCALER(PulseWidthPrescaler)); + + /* Process Locked */ + __HAL_LOCK(htim); + + /* Set the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Get the TIMx ECR register value */ + tmpecr = htim->Instance->ECR; + /* Reset the Pulse width prescaler and the Pulse width */ + tmpecr &= ~(TIM_ECR_PWPRSC | TIM_ECR_PW); + /* Set the Pulse width prescaler and Pulse width*/ + tmpecr |= PulseWidthPrescaler << TIM_ECR_PWPRSC_Pos; + tmpecr |= PulseWidth << TIM_ECR_PW_Pos; + /* Write to TIMx ECR */ + htim->Instance->ECR = tmpecr; + + /* Change the TIM state */ + htim->State = HAL_TIM_STATE_READY; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configure preload source of Slave Mode Selection bitfield (SMS in SMCR register) + * @param htim TIM handle + * @param Source Source of slave mode selection preload + * This parameter can be one of the following values: + * @arg TIM_SMS_PRELOAD_SOURCE_UPDATE: Timer update event is used as source of Slave Mode Selection preload + * @arg TIM_SMS_PRELOAD_SOURCE_INDEX: Timer index event is used as source of Slave Mode Selection preload + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigSlaveModePreload(TIM_HandleTypeDef *htim, uint32_t Source) +{ + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_SLAVE_PRELOAD_SOURCE(Source)); + + MODIFY_REG(htim->Instance->SMCR, TIM_SMCR_SMSPS, Source); + return HAL_OK; +} + +/** + * @brief Enable preload of Slave Mode Selection bitfield (SMS in SMCR register) + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_EnableSlaveModePreload(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + + SET_BIT(htim->Instance->SMCR, TIM_SMCR_SMSPE); + return HAL_OK; +} + +/** + * @brief Disable preload of Slave Mode Selection bitfield (SMS in SMCR register) + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DisableSlaveModePreload(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + + CLEAR_BIT(htim->Instance->SMCR, TIM_SMCR_SMSPE); + return HAL_OK; +} + +/** + * @brief Enable deadtime preload + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_EnableDeadTimePreload(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + + SET_BIT(htim->Instance->DTR2, TIM_DTR2_DTPE); + return HAL_OK; +} + +/** + * @brief Disable deadtime preload + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DisableDeadTimePreload(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + + CLEAR_BIT(htim->Instance->DTR2, TIM_DTR2_DTPE); + return HAL_OK; +} + +/** + * @brief Configure deadtime + * @param htim TIM handle + * @param Deadtime Deadtime value + * @note This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigDeadTime(TIM_HandleTypeDef *htim, uint32_t Deadtime) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + assert_param(IS_TIM_DEADTIME(Deadtime)); + + MODIFY_REG(htim->Instance->BDTR, TIM_BDTR_DTG, Deadtime); + return HAL_OK; +} + +/** + * @brief Configure asymmetrical deadtime + * @param htim TIM handle + * @param FallingDeadtime Falling edge deadtime value + * @note This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigAsymmetricalDeadTime(TIM_HandleTypeDef *htim, uint32_t FallingDeadtime) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + assert_param(IS_TIM_DEADTIME(FallingDeadtime)); + + MODIFY_REG(htim->Instance->DTR2, TIM_DTR2_DTGF, FallingDeadtime); + return HAL_OK; +} + +/** + * @brief Enable asymmetrical deadtime + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_EnableAsymmetricalDeadTime(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + + SET_BIT(htim->Instance->DTR2, TIM_DTR2_DTAE); + return HAL_OK; +} + +/** + * @brief Disable asymmetrical deadtime + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DisableAsymmetricalDeadTime(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + + CLEAR_BIT(htim->Instance->DTR2, TIM_DTR2_DTAE); + return HAL_OK; +} + +/** + * @brief Configures the encoder index. + * @note warning in case of encoder mode clock plus direction + * @ref TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X1 or @ref TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X2 + * Direction must be set to @ref TIM_ENCODERINDEX_DIRECTION_UP_DOWN + * @param htim TIM handle. + * @param sEncoderIndexConfig Encoder index configuration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigEncoderIndex(TIM_HandleTypeDef *htim, + TIMEx_EncoderIndexConfigTypeDef *sEncoderIndexConfig) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_ENCODERINDEX_POLARITY(sEncoderIndexConfig->Polarity)); + assert_param(IS_TIM_ENCODERINDEX_PRESCALER(sEncoderIndexConfig->Prescaler)); + assert_param(IS_TIM_ENCODERINDEX_FILTER(sEncoderIndexConfig->Filter)); + assert_param(IS_TIM_ENCODERINDEX_BLANKING(sEncoderIndexConfig->Blanking)); + assert_param(IS_FUNCTIONAL_STATE(sEncoderIndexConfig->FirstIndexEnable)); + assert_param(IS_TIM_ENCODERINDEX_POSITION(sEncoderIndexConfig->Position)); + assert_param(IS_TIM_ENCODERINDEX_DIRECTION(sEncoderIndexConfig->Direction)); + + /* Process Locked */ + __HAL_LOCK(htim); + + /* Configures the TIMx External Trigger (ETR) which is used as Index input */ + TIM_ETR_SetConfig(htim->Instance, + sEncoderIndexConfig->Prescaler, + sEncoderIndexConfig->Polarity, + sEncoderIndexConfig->Filter); + + /* Configures the encoder index */ + MODIFY_REG(htim->Instance->ECR, + TIM_ECR_IDIR_Msk | TIM_ECR_IBLK_Msk | TIM_ECR_FIDX_Msk | TIM_ECR_IPOS_Msk, + (sEncoderIndexConfig->Direction | + (sEncoderIndexConfig->Blanking) | + ((sEncoderIndexConfig->FirstIndexEnable == ENABLE) ? (0x1U << TIM_ECR_FIDX_Pos) : 0U) | + sEncoderIndexConfig->Position | + TIM_ECR_IE)); + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Enable encoder index + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_EnableEncoderIndex(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + SET_BIT(htim->Instance->ECR, TIM_ECR_IE); + return HAL_OK; +} + +/** + * @brief Disable encoder index + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DisableEncoderIndex(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + CLEAR_BIT(htim->Instance->ECR, TIM_ECR_IE); + return HAL_OK; +} + +/** + * @brief Enable encoder first index + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_EnableEncoderFirstIndex(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + SET_BIT(htim->Instance->ECR, TIM_ECR_FIDX); + return HAL_OK; +} + +/** + * @brief Disable encoder first index + * @param htim TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_DisableEncoderFirstIndex(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(htim->Instance)); + + CLEAR_BIT(htim->Instance->ECR, TIM_ECR_FIDX); + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Exported_Functions_Group6 Extended Callbacks functions + * @brief Extended Callbacks functions + * +@verbatim + ============================================================================== + ##### Extended Callbacks functions ##### + ============================================================================== + [..] + This section provides Extended TIM callback functions: + (+) Timer Commutation callback + (+) Timer Break callback + +@endverbatim + * @{ + */ + +/** + * @brief Commutation callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_CommutCallback could be implemented in the user file + */ +} +/** + * @brief Commutation half complete callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_CommutHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Break detection callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_BreakCallback could be implemented in the user file + */ +} + +/** + * @brief Break2 detection callback in non blocking mode + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIMEx_Break2Callback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIMEx_Break2Callback could be implemented in the user file + */ +} + +/** + * @brief Encoder index callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_EncoderIndexCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_EncoderIndexCallback could be implemented in the user file + */ +} + +/** + * @brief Direction change callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_DirectionChangeCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_DirectionChangeCallback could be implemented in the user file + */ +} + +/** + * @brief Index error callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_IndexErrorCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_IndexErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Transition error callback in non-blocking mode + * @param htim TIM handle + * @retval None + */ +__weak void HAL_TIMEx_TransitionErrorCallback(TIM_HandleTypeDef *htim) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(htim); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TIMEx_TransitionErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup TIMEx_Exported_Functions_Group7 Extended Peripheral State functions + * @brief Extended Peripheral State functions + * +@verbatim + ============================================================================== + ##### Extended Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TIM Hall Sensor interface handle state. + * @param htim TIM Hall Sensor handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(const TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return actual state of the TIM complementary channel. + * @param htim TIM handle + * @param ChannelN TIM Complementary 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 TIM Complementary channel state + */ +HAL_TIM_ChannelStateTypeDef HAL_TIMEx_GetChannelNState(const TIM_HandleTypeDef *htim, uint32_t ChannelN) +{ + HAL_TIM_ChannelStateTypeDef channel_state; + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, ChannelN)); + + channel_state = TIM_CHANNEL_N_STATE_GET(htim, ChannelN); + + return channel_state; +} +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup TIMEx_Private_Functions TIM Extended Private Functions + * @{ + */ + +/** + * @brief TIM DMA Commutation callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->CommutationCallback(htim); +#else + HAL_TIMEx_CommutCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ +} + +/** + * @brief TIM DMA Commutation half complete callback. + * @param hdma pointer to DMA handle. + * @retval None + */ +void TIMEx_DMACommutationHalfCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->CommutationHalfCpltCallback(htim); +#else + HAL_TIMEx_CommutHalfCpltCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ +} + + +/** + * @brief TIM DMA Delay Pulse complete callback (complementary channel). + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TIM_DMADelayPulseNCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->PWM_PulseFinishedCallback(htim); +#else + HAL_TIM_PWM_PulseFinishedCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TIM DMA error callback (complementary channel) + * @param hdma pointer to DMA handle. + * @retval None + */ +static void TIM_DMAErrorCCxN(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_READY); + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_READY); + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_3, HAL_TIM_CHANNEL_STATE_READY); + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_4, HAL_TIM_CHANNEL_STATE_READY); + } + else + { + /* nothing to do */ + } + +#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1) + htim->ErrorCallback(htim); +#else + HAL_TIM_ErrorCallback(htim); +#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */ + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @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 + * @arg TIM_CHANNEL_4: TIM Channel 4 + * @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; + + tmp = TIM_CCER_CC1NE << (Channel & 0xFU); /* 0xFU = 15 bits max shift */ + + /* Reset the CCxNE Bit */ + TIMx->CCER &= ~tmp; + + /* Set or reset the CCxNE Bit */ + TIMx->CCER |= (uint32_t)(ChannelNState << (Channel & 0xFU)); /* 0xFU = 15 bits max shift */ +} +/** + * @} + */ + +#endif /* HAL_TIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_timebase_rtc_wakeup_template.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_timebase_rtc_wakeup_template.c index 03103b4f4..a0b6ae102 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_timebase_rtc_wakeup_template.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_timebase_rtc_wakeup_template.c @@ -187,7 +187,7 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) if (Status == HAL_OK) { - uint32_t WakeUpCounter = ((uint32_t)uwTickFreq / (uint32_t)HAL_TICK_FREQ_1KHZ) - 1U; + uint32_t WakeUpCounter = ((uint32_t)uwTickFreq / (uint32_t)HAL_TICK_FREQ_1KHZ) - 1U; Status = HAL_RTCEx_SetWakeUpTimer_IT(&hRTC_Handle, WakeUpCounter, RTC_WAKEUPCLOCK_CK_SPRE_16BITS, 0); } diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart.c index 036b840fb..d04d9c574 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart.c @@ -1,4867 +1,4890 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_uart.c - * @author MCD Application Team - * @brief UART HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral Control functions - * - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - =============================================================================== - ##### How to use this driver ##### - =============================================================================== - [..] - The UART HAL driver can be used as follows: - - (#) Declare a UART_HandleTypeDef handle structure (eg. UART_HandleTypeDef huart). - (#) Initialize the UART low level resources by implementing 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. - (++) UART interrupts handling: - -@@- The specific UART interrupts (Transmission complete interrupt, - RXNE interrupt, RX/TX FIFOs related interrupts and Error Interrupts) - are managed using the macros __HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() - inside the transmit and receive processes. - (++) 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 channel. - (+++) Enable the DMAx interface clock. - (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. - (+++) Configure the DMA Tx/Rx channel. - (+++) 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 channel. - - (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Prescaler value , Hardware - flow control and Mode (Receiver/Transmitter) in the huart handle Init structure. - - (#) If required, program UART advanced features (TX/RX pins swap, auto Baud rate detection,...) - in the huart handle AdvancedInit 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 UART LIN (Local Interconnection Network) mode, initialize the UART registers - by calling the HAL_LIN_Init() API. - - (#) For the UART Multiprocessor mode, initialize the UART registers - by calling the HAL_MultiProcessor_Init() API. - - (#) For the UART RS485 Driver Enabled mode, initialize the UART registers - by calling the HAL_RS485Ex_Init() API. - - [..] - (@) These API's (HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init(), HAL_MultiProcessor_Init(), - also configure the low level Hardware GPIO, CLOCK, CORTEX...etc) by - calling the customized HAL_UART_MspInit() API. - - ##### Callback registration ##### - ================================== - - [..] - The compilation define USE_HAL_UART_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - [..] - Use Function HAL_UART_RegisterCallback() to register a user callback. - Function HAL_UART_RegisterCallback() allows to register following callbacks: - (+) TxHalfCpltCallback : Tx Half Complete Callback. - (+) TxCpltCallback : Tx Complete Callback. - (+) RxHalfCpltCallback : Rx Half Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. - (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. - (+) WakeupCallback : Wakeup Callback. - (+) RxFifoFullCallback : Rx Fifo Full Callback. - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) MspInitCallback : UART MspInit. - (+) MspDeInitCallback : UART MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_UART_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_UART_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxHalfCpltCallback : Tx Half Complete Callback. - (+) TxCpltCallback : Tx Complete Callback. - (+) RxHalfCpltCallback : Rx Half Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. - (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. - (+) WakeupCallback : Wakeup Callback. - (+) RxFifoFullCallback : Rx Fifo Full Callback. - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) MspInitCallback : UART MspInit. - (+) MspDeInitCallback : UART MspDeInit. - - [..] - For specific callback RxEventCallback, use dedicated registration/reset functions: - respectively HAL_UART_RegisterRxEventCallback() , HAL_UART_UnRegisterRxEventCallback(). - - [..] - By default, after the HAL_UART_Init() and when the state is HAL_UART_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_UART_TxCpltCallback(), HAL_UART_RxHalfCpltCallback(). - Exception done for MspInit and MspDeInit functions that are respectively - reset to the legacy weak functions in the HAL_UART_Init() - and HAL_UART_DeInit() only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_UART_Init() and HAL_UART_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in HAL_UART_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_UART_STATE_READY or HAL_UART_STATE_RESET state, thus registered (user) - MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_UART_RegisterCallback() before calling HAL_UART_DeInit() - or HAL_UART_Init() function. - - [..] - When The compilation define USE_HAL_UART_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available - and weak callbacks are used. - - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup UART UART - * @brief HAL UART module driver - * @{ - */ - -#ifdef HAL_UART_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup UART_Private_Constants UART Private Constants - * @{ - */ -#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | \ - USART_CR1_OVER8 | USART_CR1_FIFOEN)) /*!< UART or USART CR1 fields of parameters set by UART_SetConfig API */ - -#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT | USART_CR3_TXFTCFG | \ - USART_CR3_RXFTCFG)) /*!< UART or USART CR3 fields of parameters set by UART_SetConfig API */ - -#define LPUART_BRR_MIN 0x00000300U /* LPUART BRR minimum authorized value */ -#define LPUART_BRR_MAX 0x000FFFFFU /* LPUART BRR maximum authorized value */ - -#define UART_BRR_MIN 0x10U /* UART BRR minimum authorized value */ -#define UART_BRR_MAX 0x0000FFFFU /* UART BRR maximum authorized value */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup UART_Private_Functions - * @{ - */ -static void UART_EndRxTransfer(UART_HandleTypeDef *huart); -#if defined(HAL_DMA_MODULE_ENABLED) -static void UART_EndTxTransfer(UART_HandleTypeDef *huart); -static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); -static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); -static void UART_DMAError(DMA_HandleTypeDef *hdma); -static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -#endif /* HAL_DMA_MODULE_ENABLED */ -static void UART_TxISR_8BIT(UART_HandleTypeDef *huart); -static void UART_TxISR_16BIT(UART_HandleTypeDef *huart); -static void UART_TxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart); -static void UART_TxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart); -static void UART_EndTransmit_IT(UART_HandleTypeDef *huart); -static void UART_RxISR_8BIT(UART_HandleTypeDef *huart); -static void UART_RxISR_16BIT(UART_HandleTypeDef *huart); -static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart); -static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart); -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/** @addtogroup UART_Private_variables - * @{ - */ -const uint16_t UARTPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; -/** - * @} - */ - -/* Exported Constants --------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup UART_Exported_Functions UART Exported Functions - * @{ - */ - -/** @defgroup UART_Exported_Functions_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 the parameters below 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. - (++) Hardware flow control - (++) Receiver/transmitter modes - (++) Over Sampling Method - (++) One-Bit Sampling Method - (+) For the asynchronous mode, the following advanced features can be configured as well: - (++) TX and/or RX pin level inversion - (++) data logical level inversion - (++) RX and TX pins swap - (++) RX overrun detection disabling - (++) DMA disabling on RX error - (++) MSB first on communication line - (++) auto Baud rate detection - [..] - The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init()and HAL_MultiProcessor_Init()API - follow respectively the UART asynchronous, UART Half duplex, UART LIN mode - and UART multiprocessor mode configuration procedures (details for the procedures - are available in reference manual). - -@endverbatim - - Depending on the frame length defined by the M1 and M0 bits (7-bit, - 8-bit or 9-bit), the possible UART formats are listed in the - following table. - - Table 1. UART frame format. - +-----------------------------------------------------------------------+ - | M1 bit | M0 bit | PCE bit | UART frame | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 0 | | SB | 8 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 0 | | SB | 9 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 0 | | SB | 7 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | - +-----------------------------------------------------------------------+ - - * @{ - */ - -/** - * @brief Initialize the UART mode according to the specified - * parameters in the UART_InitTypeDef and initialize 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)) || (IS_LPUART_INSTANCE(huart->Instance))); - } - - if (huart->gState == HAL_UART_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - huart->Lock = HAL_UNLOCKED; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - UART_InitCallbacksToDefault(huart); - - if (huart->MspInitCallback == NULL) - { - huart->MspInitCallback = HAL_UART_MspInit; - } - - /* Init the low level hardware */ - huart->MspInitCallback(huart); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_UART_MspInit(huart); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - - huart->gState = HAL_UART_STATE_BUSY; - - __HAL_UART_DISABLE(huart); - - /* Perform advanced settings configuration */ - /* For some items, configuration requires to be done prior TE and RE bits are set */ - if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) - { - UART_AdvFeatureConfig(huart); - } - - /* Set the UART Communication parameters */ - if (UART_SetConfig(huart) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* 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.*/ - CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); - - __HAL_UART_ENABLE(huart); - - /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ - return (UART_CheckIdleState(huart)); -} - -/** - * @brief Initialize the half-duplex mode according to the specified - * parameters in the UART_InitTypeDef and creates 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; - } - - /* Check UART instance */ - assert_param(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance)); - - if (huart->gState == HAL_UART_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - huart->Lock = HAL_UNLOCKED; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - UART_InitCallbacksToDefault(huart); - - if (huart->MspInitCallback == NULL) - { - huart->MspInitCallback = HAL_UART_MspInit; - } - - /* Init the low level hardware */ - huart->MspInitCallback(huart); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_UART_MspInit(huart); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - - huart->gState = HAL_UART_STATE_BUSY; - - __HAL_UART_DISABLE(huart); - - /* Perform advanced settings configuration */ - /* For some items, configuration requires to be done prior TE and RE bits are set */ - if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) - { - UART_AdvFeatureConfig(huart); - } - - /* Set the UART Communication parameters */ - if (UART_SetConfig(huart) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* 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.*/ - CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(huart->Instance->CR3, (USART_CR3_IREN | USART_CR3_SCEN)); - - /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */ - SET_BIT(huart->Instance->CR3, USART_CR3_HDSEL); - - __HAL_UART_ENABLE(huart); - - /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ - return (UART_CheckIdleState(huart)); -} - - -/** - * @brief Initialize the LIN mode according to the specified - * parameters in the UART_InitTypeDef and creates 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 @ref UART_LINBREAKDETECTLENGTH_10B 10-bit break detection - * @arg @ref 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 LIN UART instance */ - assert_param(IS_UART_LIN_INSTANCE(huart->Instance)); - /* Check the Break detection length parameter */ - assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); - - /* LIN mode limited to 16-bit oversampling only */ - if (huart->Init.OverSampling == UART_OVERSAMPLING_8) - { - return HAL_ERROR; - } - /* LIN mode limited to 8-bit data length */ - if (huart->Init.WordLength != UART_WORDLENGTH_8B) - { - return HAL_ERROR; - } - - if (huart->gState == HAL_UART_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - huart->Lock = HAL_UNLOCKED; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - UART_InitCallbacksToDefault(huart); - - if (huart->MspInitCallback == NULL) - { - huart->MspInitCallback = HAL_UART_MspInit; - } - - /* Init the low level hardware */ - huart->MspInitCallback(huart); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_UART_MspInit(huart); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - - huart->gState = HAL_UART_STATE_BUSY; - - __HAL_UART_DISABLE(huart); - - /* Perform advanced settings configuration */ - /* For some items, configuration requires to be done prior TE and RE bits are set */ - if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) - { - UART_AdvFeatureConfig(huart); - } - - /* Set the UART Communication parameters */ - if (UART_SetConfig(huart) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* 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.*/ - CLEAR_BIT(huart->Instance->CR2, USART_CR2_CLKEN); - CLEAR_BIT(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 */ - SET_BIT(huart->Instance->CR2, USART_CR2_LINEN); - - /* Set the USART LIN Break detection length. */ - MODIFY_REG(huart->Instance->CR2, USART_CR2_LBDL, BreakDetectLength); - - __HAL_UART_ENABLE(huart); - - /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ - return (UART_CheckIdleState(huart)); -} - - -/** - * @brief Initialize the multiprocessor mode according to the specified - * parameters in the UART_InitTypeDef and initialize the associated handle. - * @param huart UART handle. - * @param Address UART node address (4-, 6-, 7- or 8-bit long). - * @param WakeUpMethod Specifies the UART wakeup method. - * This parameter can be one of the following values: - * @arg @ref UART_WAKEUPMETHOD_IDLELINE WakeUp by an idle line detection - * @arg @ref UART_WAKEUPMETHOD_ADDRESSMARK WakeUp by an address mark - * @note If the user resorts to idle line detection wake up, the Address parameter - * is useless and ignored by the initialization function. - * @note If the user resorts to address mark wake up, the address length detection - * is configured by default to 4 bits only. For the UART to be able to - * manage 6-, 7- or 8-bit long addresses detection, the API - * HAL_MultiProcessorEx_AddressLength_Set() must be called after - * HAL_MultiProcessor_Init(). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) -{ - /* Check the UART handle allocation */ - if (huart == NULL) - { - return HAL_ERROR; - } - - /* Check the wake up method parameter */ - assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod)); - - if (huart->gState == HAL_UART_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - huart->Lock = HAL_UNLOCKED; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - UART_InitCallbacksToDefault(huart); - - if (huart->MspInitCallback == NULL) - { - huart->MspInitCallback = HAL_UART_MspInit; - } - - /* Init the low level hardware */ - huart->MspInitCallback(huart); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_UART_MspInit(huart); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - - huart->gState = HAL_UART_STATE_BUSY; - - __HAL_UART_DISABLE(huart); - - /* Perform advanced settings configuration */ - /* For some items, configuration requires to be done prior TE and RE bits are set */ - if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) - { - UART_AdvFeatureConfig(huart); - } - - /* Set the UART Communication parameters */ - if (UART_SetConfig(huart) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* In multiprocessor 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. */ - CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); - - if (WakeUpMethod == UART_WAKEUPMETHOD_ADDRESSMARK) - { - /* If address mark wake up method is chosen, set the USART address node */ - MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)Address << UART_CR2_ADDRESS_LSB_POS)); - } - - /* Set the wake up method by setting the WAKE bit in the CR1 register */ - MODIFY_REG(huart->Instance->CR1, USART_CR1_WAKE, WakeUpMethod); - - __HAL_UART_ENABLE(huart); - - /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ - return (UART_CheckIdleState(huart)); -} - - -/** - * @brief DeInitialize 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)) || (IS_LPUART_INSTANCE(huart->Instance))); - - huart->gState = HAL_UART_STATE_BUSY; - - __HAL_UART_DISABLE(huart); - - huart->Instance->CR1 = 0x0U; - huart->Instance->CR2 = 0x0U; - huart->Instance->CR3 = 0x0U; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - if (huart->MspDeInitCallback == NULL) - { - huart->MspDeInitCallback = HAL_UART_MspDeInit; - } - /* DeInit the low level hardware */ - huart->MspDeInitCallback(huart); -#else - /* DeInit the low level hardware */ - HAL_UART_MspDeInit(huart); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_RESET; - huart->RxState = HAL_UART_STATE_RESET; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - huart->RxEventType = HAL_UART_RXEVENT_TC; - - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Initialize the UART MSP. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_MspInit can be implemented in the user file - */ -} - -/** - * @brief DeInitialize the UART MSP. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User UART Callback - * To be used to override the weak predefined callback - * @note The HAL_UART_RegisterCallback() may be called before HAL_UART_Init(), HAL_HalfDuplex_Init(), - * HAL_LIN_Init(), HAL_MultiProcessor_Init() or HAL_RS485Ex_Init() in HAL_UART_STATE_RESET to register - * callbacks for HAL_UART_MSPINIT_CB_ID and HAL_UART_MSPDEINIT_CB_ID - * @param huart uart handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID - * @arg @ref HAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID - * @arg @ref HAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_UART_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID - * @arg @ref HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID - * @arg @ref HAL_UART_WAKEUP_CB_ID Wakeup Callback ID - * @arg @ref HAL_UART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID - * @arg @ref HAL_UART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID - * @arg @ref HAL_UART_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_RegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID, - pUART_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (huart->gState == HAL_UART_STATE_READY) - { - switch (CallbackID) - { - case HAL_UART_TX_HALFCOMPLETE_CB_ID : - huart->TxHalfCpltCallback = pCallback; - break; - - case HAL_UART_TX_COMPLETE_CB_ID : - huart->TxCpltCallback = pCallback; - break; - - case HAL_UART_RX_HALFCOMPLETE_CB_ID : - huart->RxHalfCpltCallback = pCallback; - break; - - case HAL_UART_RX_COMPLETE_CB_ID : - huart->RxCpltCallback = pCallback; - break; - - case HAL_UART_ERROR_CB_ID : - huart->ErrorCallback = pCallback; - break; - - case HAL_UART_ABORT_COMPLETE_CB_ID : - huart->AbortCpltCallback = pCallback; - break; - - case HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : - huart->AbortTransmitCpltCallback = pCallback; - break; - - case HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : - huart->AbortReceiveCpltCallback = pCallback; - break; - - case HAL_UART_WAKEUP_CB_ID : - huart->WakeupCallback = pCallback; - break; - - case HAL_UART_RX_FIFO_FULL_CB_ID : - huart->RxFifoFullCallback = pCallback; - break; - - case HAL_UART_TX_FIFO_EMPTY_CB_ID : - huart->TxFifoEmptyCallback = pCallback; - break; - - case HAL_UART_MSPINIT_CB_ID : - huart->MspInitCallback = pCallback; - break; - - case HAL_UART_MSPDEINIT_CB_ID : - huart->MspDeInitCallback = pCallback; - break; - - default : - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - break; - } - } - else if (huart->gState == HAL_UART_STATE_RESET) - { - switch (CallbackID) - { - case HAL_UART_MSPINIT_CB_ID : - huart->MspInitCallback = pCallback; - break; - - case HAL_UART_MSPDEINIT_CB_ID : - huart->MspDeInitCallback = pCallback; - break; - - default : - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - break; - } - } - else - { - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an UART Callback - * UART callaback is redirected to the weak predefined callback - * @note The HAL_UART_UnRegisterCallback() may be called before HAL_UART_Init(), HAL_HalfDuplex_Init(), - * HAL_LIN_Init(), HAL_MultiProcessor_Init() or HAL_RS485Ex_Init() in HAL_UART_STATE_RESET to un-register - * callbacks for HAL_UART_MSPINIT_CB_ID and HAL_UART_MSPDEINIT_CB_ID - * @param huart uart handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID - * @arg @ref HAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID - * @arg @ref HAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_UART_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID - * @arg @ref HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID - * @arg @ref HAL_UART_WAKEUP_CB_ID Wakeup Callback ID - * @arg @ref HAL_UART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID - * @arg @ref HAL_UART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID - * @arg @ref HAL_UART_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_UnRegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_UART_STATE_READY == huart->gState) - { - switch (CallbackID) - { - case HAL_UART_TX_HALFCOMPLETE_CB_ID : - huart->TxHalfCpltCallback = HAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - break; - - case HAL_UART_TX_COMPLETE_CB_ID : - huart->TxCpltCallback = HAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_UART_RX_HALFCOMPLETE_CB_ID : - huart->RxHalfCpltCallback = HAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - break; - - case HAL_UART_RX_COMPLETE_CB_ID : - huart->RxCpltCallback = HAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_UART_ERROR_CB_ID : - huart->ErrorCallback = HAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_UART_ABORT_COMPLETE_CB_ID : - huart->AbortCpltCallback = HAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : - huart->AbortTransmitCpltCallback = HAL_UART_AbortTransmitCpltCallback; /* Legacy weak - AbortTransmitCpltCallback */ - break; - - case HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : - huart->AbortReceiveCpltCallback = HAL_UART_AbortReceiveCpltCallback; /* Legacy weak - AbortReceiveCpltCallback */ - break; - - case HAL_UART_WAKEUP_CB_ID : - huart->WakeupCallback = HAL_UARTEx_WakeupCallback; /* Legacy weak WakeupCallback */ - break; - - case HAL_UART_RX_FIFO_FULL_CB_ID : - huart->RxFifoFullCallback = HAL_UARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ - break; - - case HAL_UART_TX_FIFO_EMPTY_CB_ID : - huart->TxFifoEmptyCallback = HAL_UARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ - break; - - case HAL_UART_MSPINIT_CB_ID : - huart->MspInitCallback = HAL_UART_MspInit; /* Legacy weak MspInitCallback */ - break; - - case HAL_UART_MSPDEINIT_CB_ID : - huart->MspDeInitCallback = HAL_UART_MspDeInit; /* Legacy weak MspDeInitCallback */ - break; - - default : - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - break; - } - } - else if (HAL_UART_STATE_RESET == huart->gState) - { - switch (CallbackID) - { - case HAL_UART_MSPINIT_CB_ID : - huart->MspInitCallback = HAL_UART_MspInit; - break; - - case HAL_UART_MSPDEINIT_CB_ID : - huart->MspDeInitCallback = HAL_UART_MspDeInit; - break; - - default : - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - break; - } - } - else - { - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Register a User UART Rx Event Callback - * To be used instead of the weak predefined callback - * @param huart Uart handle - * @param pCallback Pointer to the Rx Event Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pUART_RxEventCallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (huart->RxState == HAL_UART_STATE_READY) - { - huart->RxEventCallback = pCallback; - } - else - { - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief UnRegister the UART Rx Event Callback - * UART Rx Event Callback is redirected to the weak HAL_UARTEx_RxEventCallback() predefined callback - * @param huart Uart handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (huart->RxState == HAL_UART_STATE_READY) - { - huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak UART Rx Event Callback */ - } - else - { - huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; - - status = HAL_ERROR; - } - - return status; -} - -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup UART_Exported_Functions_Group2 IO operation functions - * @brief UART Transmit/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 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. - (+) Non-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 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 respectively 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() - - (#) Non-Blocking mode API's with DMA are : - (+) HAL_UART_Transmit_DMA() - (+) HAL_UART_Receive_DMA() - (+) HAL_UART_DMAPause() - (+) HAL_UART_DMAResume() - (+) HAL_UART_DMAStop() - - (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: - (+) HAL_UART_TxHalfCpltCallback() - (+) HAL_UART_TxCpltCallback() - (+) HAL_UART_RxHalfCpltCallback() - (+) HAL_UART_RxCpltCallback() - (+) HAL_UART_ErrorCallback() - - (#) Non-Blocking mode transfers could be aborted using Abort API's : - (+) HAL_UART_Abort() - (+) HAL_UART_AbortTransmit() - (+) HAL_UART_AbortReceive() - (+) HAL_UART_Abort_IT() - (+) HAL_UART_AbortTransmit_IT() - (+) HAL_UART_AbortReceive_IT() - - (#) For Abort services based on interrupts (HAL_UART_Abortxxx_IT), a set of Abort Complete Callbacks are provided: - (+) HAL_UART_AbortCpltCallback() - (+) HAL_UART_AbortTransmitCpltCallback() - (+) HAL_UART_AbortReceiveCpltCallback() - - (#) A Rx Event Reception Callback (Rx event notification) is available for Non_Blocking modes of enhanced - reception services: - (+) HAL_UARTEx_RxEventCallback() - - (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. - Errors are handled as follows : - (+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is - to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error - in Interrupt mode reception . - Received character is then retrieved and stored in Rx buffer, Error code is set to allow user - to identify error type, and HAL_UART_ErrorCallback() user callback is executed. - Transfer is kept ongoing on UART side. - If user wants to abort it, Abort services should be called by user. - (+) Error is considered as Blocking : Transfer could not be completed properly and is aborted. - This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. - Error code is set to allow user to identify error type, and HAL_UART_ErrorCallback() - user callback is executed. - - -@- 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 Send an amount of data in blocking mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must indicate the number - * of u16 provided through pData. - * @note When FIFO mode is enabled, writing a data in the TDR register adds one - * data to the TXFIFO. Write operations to the TDR register are performed - * when TXFNF flag is set. From hardware perspective, TXFNF flag and - * TXE are mapped on the same bit-field. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @param Timeout Timeout duration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout) -{ - const uint8_t *pdata8bits; - const uint16_t *pdata16bits; - uint32_t tickstart; - - /* Check that a Tx process is not already ongoing */ - if (huart->gState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_BUSY_TX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - huart->TxXferSize = Size; - huart->TxXferCount = Size; - - /* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - pdata8bits = NULL; - pdata16bits = (const uint16_t *) pData; - } - else - { - pdata8bits = pData; - pdata16bits = NULL; - } - - while (huart->TxXferCount > 0U) - { - if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - - huart->gState = HAL_UART_STATE_READY; - - return HAL_TIMEOUT; - } - if (pdata8bits == NULL) - { - huart->Instance->TDR = (uint16_t)(*pdata16bits & 0x01FFU); - pdata16bits++; - } - else - { - huart->Instance->TDR = (uint8_t)(*pdata8bits & 0xFFU); - pdata8bits++; - } - huart->TxXferCount--; - } - - if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) - { - huart->gState = HAL_UART_STATE_READY; - - return HAL_TIMEOUT; - } - - /* At end of Tx process, restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in blocking mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must indicate the number - * of u16 available through pData. - * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO - * is not empty. Read operations from the RDR register are performed when - * RXFNE flag is set. From hardware perspective, RXFNE flag and - * RXNE are mapped on the same bit-field. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) 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) -{ - uint8_t *pdata8bits; - uint16_t *pdata16bits; - uint16_t uhMask; - uint32_t tickstart; - - /* Check that a Rx process is not already ongoing */ - if (huart->RxState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - huart->RxXferSize = Size; - huart->RxXferCount = Size; - - /* Computation of UART mask to apply to RDR register */ - UART_MASK_COMPUTATION(huart); - uhMask = huart->Mask; - - /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - pdata8bits = NULL; - pdata16bits = (uint16_t *) pData; - } - else - { - pdata8bits = pData; - pdata16bits = NULL; - } - - /* as long as data have to be received */ - while (huart->RxXferCount > 0U) - { - if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { - huart->RxState = HAL_UART_STATE_READY; - - return HAL_TIMEOUT; - } - if (pdata8bits == NULL) - { - *pdata16bits = (uint16_t)(huart->Instance->RDR & uhMask); - pdata16bits++; - } - else - { - *pdata8bits = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); - pdata8bits++; - } - huart->RxXferCount--; - } - - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Send an amount of data in interrupt mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must indicate the number - * of u16 provided through pData. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) -{ - /* Check that a Tx process is not already ongoing */ - if (huart->gState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - huart->pTxBuffPtr = pData; - huart->TxXferSize = Size; - huart->TxXferCount = Size; - huart->TxISR = NULL; - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_BUSY_TX; - - /* Configure Tx interrupt processing */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - /* Set the Tx ISR function pointer according to the data word length */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - huart->TxISR = UART_TxISR_16BIT_FIFOEN; - } - else - { - huart->TxISR = UART_TxISR_8BIT_FIFOEN; - } - - /* Enable the TX FIFO threshold interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); - } - else - { - /* Set the Tx ISR function pointer according to the data word length */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - huart->TxISR = UART_TxISR_16BIT; - } - else - { - huart->TxISR = UART_TxISR_8BIT; - } - - /* Enable the Transmit Data Register Empty interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in interrupt mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must indicate the number - * of u16 available through pData. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) -{ - /* Check that a Rx process is not already ongoing */ - if (huart->RxState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Set Reception type to Standard reception */ - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - /* Check that USART RTOEN bit is set */ - if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) - { - /* Enable the UART Receiver Timeout Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RTOIE); - } - } - - return (UART_Start_Receive_IT(huart, pData, Size)); - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Send an amount of data in DMA mode. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must indicate the number - * of u16 provided through pData. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - uint16_t nbByte = Size; - - /* Check that a Tx process is not already ongoing */ - if (huart->gState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - huart->pTxBuffPtr = pData; - huart->TxXferSize = Size; - huart->TxXferCount = Size; - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_BUSY_TX; - - if (huart->hdmatx != NULL) - { - /* 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; - - /* Set the DMA abort callback */ - huart->hdmatx->XferAbortCallback = NULL; - - /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size * 2 */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - /* Check linked list mode */ - if ((huart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((huart->hdmatx->LinkedListQueue != NULL) && (huart->hdmatx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - huart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - huart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)huart->pTxBuffPtr; - - /* Set DMA destination address */ - huart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&huart->Instance->TDR; - - /* Enable the UART transmit DMA channel */ - status = HAL_DMAEx_List_Start_IT(huart->hdmatx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the UART transmit DMA channel */ - status = HAL_DMA_Start_IT(huart->hdmatx, (uint32_t)huart->pTxBuffPtr, (uint32_t)&huart->Instance->TDR, nbByte); - } - - if (status != HAL_OK) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - /* Restore huart->gState to ready */ - huart->gState = HAL_UART_STATE_READY; - - return HAL_ERROR; - } - } - /* Clear the TC flag in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_TCF); - - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the UART CR3 register */ - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in DMA mode. - * @note When the UART parity is enabled (PCE = 1), the received data contain - * the parity bit (MSB position). - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must indicate the number - * of u16 available through pData. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) -{ - /* Check that a Rx process is not already ongoing */ - if (huart->RxState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Set Reception type to Standard reception */ - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - /* Check that USART RTOEN bit is set */ - if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) - { - /* Enable the UART Receiver Timeout Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RTOIE); - } - } - - return (UART_Start_Receive_DMA(huart, pData, Size)); - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Pause the DMA Transfer. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart) -{ - const HAL_UART_StateTypeDef gstate = huart->gState; - const HAL_UART_StateTypeDef rxstate = huart->RxState; - - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && - (gstate == HAL_UART_STATE_BUSY_TX)) - { - /* Suspend the UART DMA Tx channel : use blocking DMA Suspend API (no callback) */ - if (huart->hdmatx != NULL) - { - /* Set the UART DMA Suspend callback to Null. - No call back execution at end of DMA Suspend procedure */ - huart->hdmatx->XferSuspendCallback = NULL; - - if (HAL_DMAEx_Suspend(huart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && - (rxstate == HAL_UART_STATE_BUSY_RX)) - { - /* Suspend the UART DMA Rx channel : use blocking DMA Suspend API (no callback) */ - if (huart->hdmarx != NULL) - { - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Set the UART DMA Suspend callback to Null. - No call back execution at end of DMA Suspend procedure */ - huart->hdmarx->XferSuspendCallback = NULL; - - if (HAL_DMAEx_Suspend(huart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - - return HAL_OK; -} - -/** - * @brief Resume the DMA Transfer. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart) -{ - if (huart->gState == HAL_UART_STATE_BUSY_TX) - { - /* Resume the UART DMA Tx channel */ - if (huart->hdmatx != NULL) - { - if (HAL_DMAEx_Resume(huart->hdmatx) != HAL_OK) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_ERROR; - } - } - } - if (huart->RxState == HAL_UART_STATE_BUSY_RX) - { - /* Clear the Overrun flag before resuming the Rx transfer */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); - - /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ - if (huart->Init.Parity != UART_PARITY_NONE) - { - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); - } - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Resume the UART DMA Rx channel */ - if (huart->hdmarx != NULL) - { - if (HAL_DMAEx_Resume(huart->hdmarx) != HAL_OK) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_ERROR; - } - } - } - - return HAL_OK; -} - -/** - * @brief Stop the DMA Transfer. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart) -{ - /* The Lock is not implemented on this API to allow the user application - to call the HAL UART API under callbacks HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback() / - HAL_UART_TxHalfCpltCallback / HAL_UART_RxHalfCpltCallback: - indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete - interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of - the stream and the corresponding call back is executed. */ - - const HAL_UART_StateTypeDef gstate = huart->gState; - const HAL_UART_StateTypeDef rxstate = huart->RxState; - - /* Stop UART DMA Tx request if ongoing */ - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && - (gstate == HAL_UART_STATE_BUSY_TX)) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel */ - if (huart->hdmatx != NULL) - { - if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - - UART_EndTxTransfer(huart); - } - - /* Stop UART DMA Rx request if ongoing */ - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && - (rxstate == HAL_UART_STATE_BUSY_RX)) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel */ - if (huart->hdmarx != NULL) - { - if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - - UART_EndRxTransfer(huart); - } - - return HAL_OK; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Abort ongoing transfers (blocking mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable UART Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Abort(UART_HandleTypeDef *huart) -{ - /* Disable TXE, TC, RXNE, PE, RXFT, TXFT and ERR (Frame error, noise error, overrun error) interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | - USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE); - - /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the UART DMA Tx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable the UART DMA Tx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (huart->hdmatx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - - /* Abort the UART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the UART DMA Rx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx and Rx transfer counters */ - huart->TxXferCount = 0U; - huart->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Flush the whole TX FIFO (if needed) */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); - } - - /* Discard the received data */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - huart->ErrorCode = HAL_UART_ERROR_NONE; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (blocking mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable UART Interrupts (Tx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_AbortTransmit(UART_HandleTypeDef *huart) -{ - /* Disable TCIE, TXEIE and TXFTIE interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TCIE | USART_CR1_TXEIE_TXFNFIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the UART DMA Tx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable the UART DMA Tx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (huart->hdmatx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx transfer counter */ - huart->TxXferCount = 0U; - - /* Flush the whole TX FIFO (if needed) */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); - } - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (blocking mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable UART Interrupts (Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_AbortReceive(UART_HandleTypeDef *huart) -{ - /* Disable PEIE, EIE, RXNEIE and RXFTIE interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE | USART_CR3_RXFTIE); - - /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the UART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the UART DMA Rx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Rx transfer counter */ - huart->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Discard the received data */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (Interrupt mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable UART Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_Abort_IT(UART_HandleTypeDef *huart) -{ - uint32_t abortcplt = 1U; - - /* Disable interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_TCIE | USART_CR1_RXNEIE_RXFNEIE | - USART_CR1_TXEIE_TXFNFIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); - - /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* If DMA Tx and/or DMA Rx Handles are associated to UART Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if (huart->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - huart->hdmatx->XferAbortCallback = UART_DMATxAbortCallback; - } - else - { - huart->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if (huart->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - huart->hdmarx->XferAbortCallback = UART_DMARxAbortCallback; - } - else - { - huart->hdmarx->XferAbortCallback = NULL; - } - } - - /* Abort the UART DMA Tx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at UART level */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (huart->hdmatx != NULL) - { - /* UART Tx DMA Abort callback has already been initialised : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) - { - huart->hdmatx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } - } - } - - /* Abort the UART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the UART DMA Rx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (huart->hdmarx != NULL) - { - /* UART Rx DMA Abort callback has already been initialised : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) - { - huart->hdmarx->XferAbortCallback = NULL; - abortcplt = 1U; - } - else - { - abortcplt = 0U; - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if (abortcplt == 1U) - { - /* Reset Tx and Rx transfer counters */ - huart->TxXferCount = 0U; - huart->RxXferCount = 0U; - - /* Clear ISR function pointers */ - huart->RxISR = NULL; - huart->TxISR = NULL; - - /* Reset errorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Flush the whole TX FIFO (if needed) */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); - } - - /* Discard the received data */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - huart->AbortCpltCallback(huart); -#else - /* Call legacy weak Abort complete callback */ - HAL_UART_AbortCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (Interrupt mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable UART Interrupts (Tx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart) -{ - /* Disable interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TCIE | USART_CR1_TXEIE_TXFNFIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the UART DMA Tx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable the UART DMA Tx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (huart->hdmatx != NULL) - { - /* Set the UART DMA Abort callback : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - huart->hdmatx->XferAbortCallback = UART_DMATxOnlyAbortCallback; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) - { - /* Call Directly huart->hdmatx->XferAbortCallback function in case of error */ - huart->hdmatx->XferAbortCallback(huart->hdmatx); - } - } - else - { - /* Reset Tx transfer counter */ - huart->TxXferCount = 0U; - - /* Clear TxISR function pointers */ - huart->TxISR = NULL; - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - huart->AbortTransmitCpltCallback(huart); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_UART_AbortTransmitCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Reset Tx transfer counter */ - huart->TxXferCount = 0U; - - /* Clear TxISR function pointers */ - huart->TxISR = NULL; - - /* Flush the whole TX FIFO (if needed) */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); - } - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - huart->AbortTransmitCpltCallback(huart); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_UART_AbortTransmitCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (Interrupt mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable UART Interrupts (Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the UART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the UART DMA Rx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = UART_DMARxOnlyAbortCallback; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) - { - /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ - huart->hdmarx->XferAbortCallback(huart->hdmarx); - } - } - else - { - /* Reset Rx transfer counter */ - huart->RxXferCount = 0U; - - /* Clear RxISR function pointer */ - huart->pRxBuffPtr = NULL; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Discard the received data */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - huart->AbortReceiveCpltCallback(huart); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_UART_AbortReceiveCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Reset Rx transfer counter */ - huart->RxXferCount = 0U; - - /* Clear RxISR function pointer */ - huart->pRxBuffPtr = NULL; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - huart->AbortReceiveCpltCallback(huart); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_UART_AbortReceiveCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @brief Handle UART interrupt request. - * @param huart UART handle. - * @retval None - */ -void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) -{ - uint32_t isrflags = READ_REG(huart->Instance->ISR); - uint32_t cr1its = READ_REG(huart->Instance->CR1); - uint32_t cr3its = READ_REG(huart->Instance->CR3); - - uint32_t errorflags; - uint32_t errorcode; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF)); - if (errorflags == 0U) - { - /* UART in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U))) - { - if (huart->RxISR != NULL) - { - huart->RxISR(huart); - } - return; - } - } - - /* If some errors occur */ - if ((errorflags != 0U) - && ((((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) - || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE)) != 0U)))) - { - /* UART parity error interrupt occurred -------------------------------------*/ - if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); - - huart->ErrorCode |= HAL_UART_ERROR_PE; - } - - /* UART frame error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); - - huart->ErrorCode |= HAL_UART_ERROR_FE; - } - - /* UART noise error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); - - huart->ErrorCode |= HAL_UART_ERROR_NE; - } - - /* UART Over-Run interrupt occurred -----------------------------------------*/ - if (((isrflags & USART_ISR_ORE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || - ((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U))) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); - - huart->ErrorCode |= HAL_UART_ERROR_ORE; - } - - /* UART Receiver Timeout interrupt occurred ---------------------------------*/ - if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF); - - huart->ErrorCode |= HAL_UART_ERROR_RTO; - } - - /* Call UART Error Call back function if need be ----------------------------*/ - if (huart->ErrorCode != HAL_UART_ERROR_NONE) - { - /* UART in mode Receiver --------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U))) - { - if (huart->RxISR != NULL) - { - huart->RxISR(huart); - } - } - - /* If Error is to be considered as blocking : - - Receiver Timeout error in Reception - - Overrun error in Reception - - any error occurs in DMA mode reception - */ - errorcode = huart->ErrorCode; - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) || - ((errorcode & (HAL_UART_ERROR_RTO | HAL_UART_ERROR_ORE)) != 0U)) - { - /* Blocking error : transfer is aborted - Set the UART state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - UART_EndRxTransfer(huart); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the UART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the UART DMA Rx request if enabled */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel */ - if (huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback : - will lead to call HAL_UART_ErrorCallback() at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = UART_DMAAbortOnError; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) - { - /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ - huart->hdmarx->XferAbortCallback(huart->hdmarx); - } - } - else - { - /* Call user error callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Call user error callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - } - } - return; - - } /* End if some error occurs */ - - /* Check current reception Mode : - If Reception till IDLE event has been selected : */ - if ((huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - && ((isrflags & USART_ISR_IDLE) != 0U) - && ((cr1its & USART_ISR_IDLE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Check if DMA mode is enabled in UART */ - if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - /* DMA mode enabled */ - /* Check received length : If all expected data are received, do nothing, - (DMA cplt callback will be called). - Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ - uint16_t nb_remaining_rx_data = (uint16_t) __HAL_DMA_GET_COUNTER(huart->hdmarx); - if ((nb_remaining_rx_data > 0U) - && (nb_remaining_rx_data < huart->RxXferSize)) - { - /* Reception is not complete */ - huart->RxXferCount = nb_remaining_rx_data; - - /* In Normal mode, end DMA xfer and HAL UART Rx process*/ - if (huart->hdmarx->Mode != DMA_LINKEDLIST_CIRCULAR) - { - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Disable the DMA transfer for the receiver request by resetting the DMAR bit - in the UART CR3 register */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - - /* Last bytes received, so no need as the abort is immediate */ - (void)HAL_DMA_Abort(huart->hdmarx); - } - - /* Initialize type of RxEvent that correspond to RxEvent callback execution; - In this case, Rx Event type is Idle Event */ - huart->RxEventType = HAL_UART_RXEVENT_IDLE; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - return; - } - else - { -#endif /* HAL_DMA_MODULE_ENABLED */ - /* DMA mode not enabled */ - /* Check received length : If all expected data are received, do nothing. - Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ - uint16_t nb_rx_data = huart->RxXferSize - huart->RxXferCount; - if ((huart->RxXferCount > 0U) - && (nb_rx_data > 0U)) - { - /* Disable the UART Parity Error Interrupt and RXNE interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - - /* Disable the UART Error Interrupt:(Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Rx process is completed, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Clear RxISR function pointer */ - huart->RxISR = NULL; - - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - - /* Initialize type of RxEvent that correspond to RxEvent callback execution; - In this case, Rx Event type is Idle Event */ - huart->RxEventType = HAL_UART_RXEVENT_IDLE; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx complete callback*/ - huart->RxEventCallback(huart, nb_rx_data); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, nb_rx_data); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - return; -#if defined(HAL_DMA_MODULE_ENABLED) - } -#endif /* HAL_DMA_MODULE_ENABLED */ - } - - /* UART wakeup from Stop mode interrupt occurred ---------------------------*/ - if (((isrflags & USART_ISR_WUF) != 0U) && ((cr3its & USART_CR3_WUFIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_WUF); - - /* UART Rx state is not reset as a reception process might be ongoing. - If UART handle state fields need to be reset to READY, this could be done in Wakeup callback */ - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Wakeup Callback */ - huart->WakeupCallback(huart); -#else - /* Call legacy weak Wakeup Callback */ - HAL_UARTEx_WakeupCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - return; - } - - /* UART in mode Transmitter ------------------------------------------------*/ - if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) - && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) - || ((cr3its & USART_CR3_TXFTIE) != 0U))) - { - if (huart->TxISR != NULL) - { - huart->TxISR(huart); - } - return; - } - - /* UART in mode Transmitter (transmission end) -----------------------------*/ - if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) - { - UART_EndTransmit_IT(huart); - return; - } - - /* UART TX Fifo Empty occurred ----------------------------------------------*/ - if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) - { -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Fifo Empty Callback */ - huart->TxFifoEmptyCallback(huart); -#else - /* Call legacy weak Tx Fifo Empty Callback */ - HAL_UARTEx_TxFifoEmptyCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - return; - } - - /* UART RX Fifo Full occurred ----------------------------------------------*/ - if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) - { -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Fifo Full Callback */ - huart->RxFifoFullCallback(huart); -#else - /* Call legacy weak Rx Fifo Full Callback */ - HAL_UARTEx_RxFifoFullCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - return; - } -} - -/** - * @brief Tx Transfer completed callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_TxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Tx Half Transfer completed callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_UART_TxHalfCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_RxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Half Transfer completed callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_UART_RxHalfCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief UART error callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_ErrorCallback can be implemented in the user file. - */ -} - -/** - * @brief UART Abort Complete callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief UART Abort Complete callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_AbortTransmitCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_AbortTransmitCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief UART Abort Receive Complete callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_AbortReceiveCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Reception Event Callback (Rx event notification called after use of advanced reception service). - * @param huart UART handle - * @param Size Number of data available in application reception buffer (indicates a position in - * reception buffer until which, data are available) - * @retval None - */ -__weak void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - UNUSED(Size); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UARTEx_RxEventCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup UART_Exported_Functions_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_UART_ReceiverTimeout_Config() API allows to configure the receiver timeout value on the fly - (+) HAL_UART_EnableReceiverTimeout() API enables the receiver timeout feature - (+) HAL_UART_DisableReceiverTimeout() API disables the receiver timeout feature - (+) HAL_MultiProcessor_EnableMuteMode() API enables mute mode - (+) HAL_MultiProcessor_DisableMuteMode() API disables mute mode - (+) HAL_MultiProcessor_EnterMuteMode() API enters mute mode - (+) UART_SetConfig() API configures the UART peripheral - (+) UART_AdvFeatureConfig() API optionally configures the UART advanced features - (+) UART_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization - (+) HAL_HalfDuplex_EnableTransmitter() API disables receiver and enables transmitter - (+) HAL_HalfDuplex_EnableReceiver() API disables transmitter and enables receiver - (+) HAL_LIN_SendBreak() API transmits the break characters -@endverbatim - * @{ - */ - -/** - * @brief Update on the fly the receiver timeout value in RTOR register. - * @param huart Pointer to a UART_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @param TimeoutValue receiver timeout value in number of baud blocks. The timeout - * value must be less or equal to 0x0FFFFFFFF. - * @retval None - */ -void HAL_UART_ReceiverTimeout_Config(UART_HandleTypeDef *huart, uint32_t TimeoutValue) -{ - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - assert_param(IS_UART_RECEIVER_TIMEOUT_VALUE(TimeoutValue)); - MODIFY_REG(huart->Instance->RTOR, USART_RTOR_RTO, TimeoutValue); - } -} - -/** - * @brief Enable the UART receiver timeout feature. - * @param huart Pointer to a UART_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_EnableReceiverTimeout(UART_HandleTypeDef *huart) -{ - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - if (huart->gState == HAL_UART_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Set the USART RTOEN bit */ - SET_BIT(huart->Instance->CR2, USART_CR2_RTOEN); - - huart->gState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } - } - else - { - return HAL_ERROR; - } -} - -/** - * @brief Disable the UART receiver timeout feature. - * @param huart Pointer to a UART_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UART_DisableReceiverTimeout(UART_HandleTypeDef *huart) -{ - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - if (huart->gState == HAL_UART_STATE_READY) - { - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Clear the USART RTOEN bit */ - CLEAR_BIT(huart->Instance->CR2, USART_CR2_RTOEN); - - huart->gState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } - } - else - { - return HAL_ERROR; - } -} - -/** - * @brief Enable UART in mute mode (does not mean UART enters mute mode; - * to enter mute mode, HAL_MultiProcessor_EnterMuteMode() API must be called). - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart) -{ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Enable USART mute mode by setting the MME bit in the CR1 register */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_MME); - - huart->gState = HAL_UART_STATE_READY; - - return (UART_CheckIdleState(huart)); -} - -/** - * @brief Disable UART mute mode (does not mean the UART actually exits mute mode - * as it may not have been in mute mode at this very moment). - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart) -{ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Disable USART mute mode by clearing the MME bit in the CR1 register */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_MME); - - huart->gState = HAL_UART_STATE_READY; - - return (UART_CheckIdleState(huart)); -} - -/** - * @brief Enter UART mute mode (means UART actually enters mute mode). - * @note To exit from mute mode, HAL_MultiProcessor_DisableMuteMode() API must be called. - * @param huart UART handle. - * @retval None - */ -void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) -{ - __HAL_UART_SEND_REQ(huart, UART_MUTE_MODE_REQUEST); -} - -/** - * @brief Enable the UART transmitter and disable the UART receiver. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) -{ - __HAL_LOCK(huart); - huart->gState = HAL_UART_STATE_BUSY; - - /* Clear TE and RE bits */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); - - /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TE); - - huart->gState = HAL_UART_STATE_READY; - - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Enable the UART receiver and disable the UART transmitter. - * @param huart UART handle. - * @retval HAL status. - */ -HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) -{ - __HAL_LOCK(huart); - huart->gState = HAL_UART_STATE_BUSY; - - /* Clear TE and RE bits */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); - - /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RE); - - huart->gState = HAL_UART_STATE_READY; - - __HAL_UNLOCK(huart); - - return HAL_OK; -} - - -/** - * @brief Transmit break characters. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart) -{ - /* Check the parameters */ - assert_param(IS_UART_LIN_INSTANCE(huart->Instance)); - - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Send break characters */ - __HAL_UART_SEND_REQ(huart, UART_SENDBREAK_REQUEST); - - huart->gState = HAL_UART_STATE_READY; - - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup UART_Exported_Functions_Group4 Peripheral State and Error functions - * @brief UART Peripheral State functions - * -@verbatim - ============================================================================== - ##### Peripheral State and Error functions ##### - ============================================================================== - [..] - This subsection provides functions allowing to : - (+) Return the UART handle state. - (+) Return the UART handle error code - -@endverbatim - * @{ - */ - -/** - * @brief Return the UART handle state. - * @param huart Pointer to a UART_HandleTypeDef structure that contains - * the configuration information for the specified UART. - * @retval HAL state - */ -HAL_UART_StateTypeDef HAL_UART_GetState(const UART_HandleTypeDef *huart) -{ - uint32_t temp1; - uint32_t temp2; - temp1 = huart->gState; - temp2 = huart->RxState; - - return (HAL_UART_StateTypeDef)(temp1 | temp2); -} - -/** - * @brief Return the UART handle 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(const UART_HandleTypeDef *huart) -{ - return huart->ErrorCode; -} -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup UART_Private_Functions UART Private Functions - * @{ - */ - -/** - * @brief Initialize the callbacks to their default values. - * @param huart UART handle. - * @retval none - */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) -void UART_InitCallbacksToDefault(UART_HandleTypeDef *huart) -{ - /* Init the UART Callback settings */ - huart->TxHalfCpltCallback = HAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - huart->TxCpltCallback = HAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ - huart->RxHalfCpltCallback = HAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - huart->RxCpltCallback = HAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ - huart->ErrorCallback = HAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ - huart->AbortCpltCallback = HAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - huart->AbortTransmitCpltCallback = HAL_UART_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ - huart->AbortReceiveCpltCallback = HAL_UART_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ - huart->WakeupCallback = HAL_UARTEx_WakeupCallback; /* Legacy weak WakeupCallback */ - huart->RxFifoFullCallback = HAL_UARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ - huart->TxFifoEmptyCallback = HAL_UARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ - huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak RxEventCallback */ - -} -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - -/** - * @brief Configure the UART peripheral. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart) -{ - uint32_t tmpreg; - uint16_t brrtemp; - UART_ClockSourceTypeDef clocksource; - uint32_t usartdiv; - HAL_StatusTypeDef ret = HAL_OK; - uint32_t lpuart_ker_ck_pres; - uint32_t pclk; - - /* Check the parameters */ - assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); - assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); - if (UART_INSTANCE_LOWPOWER(huart)) - { - assert_param(IS_LPUART_STOPBITS(huart->Init.StopBits)); - } - else - { - assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); - assert_param(IS_UART_ONE_BIT_SAMPLE(huart->Init.OneBitSampling)); - } - - 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)); - assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); - assert_param(IS_UART_PRESCALER(huart->Init.ClockPrescaler)); - - /*-------------------------- USART CR1 Configuration -----------------------*/ - /* Clear M, PCE, PS, TE, RE and OVER8 bits and configure - * the UART Word Length, Parity, Mode and oversampling: - * 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 ; - MODIFY_REG(huart->Instance->CR1, USART_CR1_FIELDS, tmpreg); - - /*-------------------------- USART CR2 Configuration -----------------------*/ - /* Configure the UART Stop Bits: Set STOP[13:12] bits according - * to huart->Init.StopBits value */ - MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits); - - /*-------------------------- USART CR3 Configuration -----------------------*/ - /* Configure - * - UART HardWare Flow Control: set CTSE and RTSE bits according - * to huart->Init.HwFlowCtl value - * - one-bit sampling method versus three samples' majority rule according - * to huart->Init.OneBitSampling (not applicable to LPUART) */ - tmpreg = (uint32_t)huart->Init.HwFlowCtl; - - if (!(UART_INSTANCE_LOWPOWER(huart))) - { - tmpreg |= huart->Init.OneBitSampling; - } - MODIFY_REG(huart->Instance->CR3, USART_CR3_FIELDS, tmpreg); - - /*-------------------------- USART PRESC Configuration -----------------------*/ - /* Configure - * - UART Clock Prescaler : set PRESCALER according to huart->Init.ClockPrescaler value */ - MODIFY_REG(huart->Instance->PRESC, USART_PRESC_PRESCALER, huart->Init.ClockPrescaler); - - /*-------------------------- USART BRR Configuration -----------------------*/ - UART_GETCLOCKSOURCE(huart, clocksource); - - /* Check LPUART instance */ - if (UART_INSTANCE_LOWPOWER(huart)) - { - /* Retrieve frequency clock */ - switch (clocksource) - { - case UART_CLOCKSOURCE_PLL2Q: - pclk = HAL_RCC_GetPLL2QFreq(); - break; - case UART_CLOCKSOURCE_PLL3Q: - pclk = HAL_RCC_GetPLL3QFreq(); - break; - case UART_CLOCKSOURCE_PCLK4: - pclk = HAL_RCC_GetPCLK4Freq(); - break; - case UART_CLOCKSOURCE_HSI: - if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) - { - pclk = (uint32_t)(HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)); - } - else - { - pclk = (uint32_t) HSI_VALUE; - } - break; - case UART_CLOCKSOURCE_CSI: - pclk = (uint32_t) CSI_VALUE; - break; - case UART_CLOCKSOURCE_LSE: - pclk = (uint32_t) LSE_VALUE; - break; - default: - pclk = 0U; - ret = HAL_ERROR; - break; - } - - /* If proper clock source reported */ - if (pclk != 0U) - { - /* Compute clock after Prescaler */ - lpuart_ker_ck_pres = (pclk / UARTPrescTable[huart->Init.ClockPrescaler]); - - /* Ensure that Frequency clock is in the range [3 * baudrate, 4096 * baudrate] */ - if ((lpuart_ker_ck_pres < (3U * huart->Init.BaudRate)) || - (lpuart_ker_ck_pres > (4096U * huart->Init.BaudRate))) - { - ret = HAL_ERROR; - } - else - { - /* Check computed UsartDiv value is in allocated range - (it is forbidden to write values lower than 0x300 in the LPUART_BRR register) */ - usartdiv = (uint32_t)(UART_DIV_LPUART(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); - if ((usartdiv >= LPUART_BRR_MIN) && (usartdiv <= LPUART_BRR_MAX)) - { - huart->Instance->BRR = usartdiv; - } - else - { - ret = HAL_ERROR; - } - } /* if ( (lpuart_ker_ck_pres < (3 * huart->Init.BaudRate) ) || - (lpuart_ker_ck_pres > (4096 * huart->Init.BaudRate) )) */ - } /* if (pclk != 0) */ - } - /* Check UART Over Sampling to set Baud Rate Register */ - else if (huart->Init.OverSampling == UART_OVERSAMPLING_8) - { - switch (clocksource) - { - case UART_CLOCKSOURCE_PCLK1: - pclk = HAL_RCC_GetPCLK1Freq(); - break; - case UART_CLOCKSOURCE_PCLK2: - pclk = HAL_RCC_GetPCLK2Freq(); - break; - case UART_CLOCKSOURCE_PLL2Q: - pclk = HAL_RCC_GetPLL2QFreq(); - break; - case UART_CLOCKSOURCE_PLL3Q: - pclk = HAL_RCC_GetPLL3QFreq(); - break; - case UART_CLOCKSOURCE_HSI: - if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) - { - pclk = (uint32_t)(HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)); - } - else - { - pclk = (uint32_t) HSI_VALUE; - } - break; - case UART_CLOCKSOURCE_CSI: - pclk = (uint32_t) CSI_VALUE; - break; - case UART_CLOCKSOURCE_LSE: - pclk = (uint32_t) LSE_VALUE; - break; - default: - pclk = 0U; - ret = HAL_ERROR; - break; - } - - /* USARTDIV must be greater than or equal to 0d16 */ - if (pclk != 0U) - { - usartdiv = (uint32_t)(UART_DIV_SAMPLING8(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); - if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) - { - brrtemp = (uint16_t)(usartdiv & 0xFFF0U); - brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U); - huart->Instance->BRR = brrtemp; - } - else - { - ret = HAL_ERROR; - } - } - } - else - { - switch (clocksource) - { - case UART_CLOCKSOURCE_PCLK1: - pclk = HAL_RCC_GetPCLK1Freq(); - break; - case UART_CLOCKSOURCE_PCLK2: - pclk = HAL_RCC_GetPCLK2Freq(); - break; - case UART_CLOCKSOURCE_PLL2Q: - pclk = HAL_RCC_GetPLL2QFreq(); - break; - case UART_CLOCKSOURCE_PLL3Q: - pclk = HAL_RCC_GetPLL3QFreq(); - break; - case UART_CLOCKSOURCE_HSI: - if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) - { - pclk = (uint32_t)(HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)); - } - else - { - pclk = (uint32_t) HSI_VALUE; - } - break; - case UART_CLOCKSOURCE_CSI: - pclk = (uint32_t) CSI_VALUE; - break; - case UART_CLOCKSOURCE_LSE: - pclk = (uint32_t) LSE_VALUE; - break; - default: - pclk = 0U; - ret = HAL_ERROR; - break; - } - - if (pclk != 0U) - { - /* USARTDIV must be greater than or equal to 0d16 */ - usartdiv = (uint32_t)(UART_DIV_SAMPLING16(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); - if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) - { - huart->Instance->BRR = (uint16_t)usartdiv; - } - else - { - ret = HAL_ERROR; - } - } - } - - /* Initialize the number of data to process during RX/TX ISR execution */ - huart->NbTxDataToProcess = 1; - huart->NbRxDataToProcess = 1; - - /* Clear ISR function pointers */ - huart->RxISR = NULL; - huart->TxISR = NULL; - - return ret; -} - -/** - * @brief Configure the UART peripheral advanced features. - * @param huart UART handle. - * @retval None - */ -void UART_AdvFeatureConfig(UART_HandleTypeDef *huart) -{ - /* Check whether the set of advanced features to configure is properly set */ - assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit)); - - /* if required, configure RX/TX pins swap */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_SWAP_INIT)) - { - assert_param(IS_UART_ADVFEATURE_SWAP(huart->AdvancedInit.Swap)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_SWAP, huart->AdvancedInit.Swap); - } - - /* if required, configure TX pin active level inversion */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_TXINVERT_INIT)) - { - assert_param(IS_UART_ADVFEATURE_TXINV(huart->AdvancedInit.TxPinLevelInvert)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_TXINV, huart->AdvancedInit.TxPinLevelInvert); - } - - /* if required, configure RX pin active level inversion */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXINVERT_INIT)) - { - assert_param(IS_UART_ADVFEATURE_RXINV(huart->AdvancedInit.RxPinLevelInvert)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_RXINV, huart->AdvancedInit.RxPinLevelInvert); - } - - /* if required, configure data inversion */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DATAINVERT_INIT)) - { - assert_param(IS_UART_ADVFEATURE_DATAINV(huart->AdvancedInit.DataInvert)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_DATAINV, huart->AdvancedInit.DataInvert); - } - - /* if required, configure RX overrun detection disabling */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT)) - { - assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable)); - MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable); - } - -#if defined(HAL_DMA_MODULE_ENABLED) - /* if required, configure DMA disabling on reception error */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT)) - { - assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError)); - MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError); - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* if required, configure auto Baud rate detection scheme */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT)) - { - assert_param(IS_USART_AUTOBAUDRATE_DETECTION_INSTANCE(huart->Instance)); - assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(huart->AdvancedInit.AutoBaudRateEnable)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_ABREN, huart->AdvancedInit.AutoBaudRateEnable); - /* set auto Baudrate detection parameters if detection is enabled */ - if (huart->AdvancedInit.AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE) - { - assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(huart->AdvancedInit.AutoBaudRateMode)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_ABRMODE, huart->AdvancedInit.AutoBaudRateMode); - } - } - - /* if required, configure MSB first on communication line */ - if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_MSBFIRST_INIT)) - { - assert_param(IS_UART_ADVFEATURE_MSBFIRST(huart->AdvancedInit.MSBFirst)); - MODIFY_REG(huart->Instance->CR2, USART_CR2_MSBFIRST, huart->AdvancedInit.MSBFirst); - } -} - -/** - * @brief Check the UART Idle State. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart) -{ - uint32_t tickstart; - - /* Initialize the UART ErrorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check if the Transmitter is enabled */ - if ((huart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) - { - /* Wait until TEACK flag is set */ - if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_TEACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) - { - /* Disable TXE interrupt for the interrupt process */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE)); - - huart->gState = HAL_UART_STATE_READY; - - __HAL_UNLOCK(huart); - - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - - /* Check if the Receiver is enabled */ - if ((huart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) - { - /* Wait until REACK flag is set */ - if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) - { - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) - interrupts for the interrupt process */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - huart->RxState = HAL_UART_STATE_READY; - - __HAL_UNLOCK(huart); - - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - - /* Initialize the UART State */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - huart->RxEventType = HAL_UART_RXEVENT_TC; - - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief This function handles UART Communication Timeout. It waits - * until a flag is no longer in the specified status. - * @param huart UART handle. - * @param Flag Specifies the UART flag to check - * @param Status The actual Flag status (SET or RESET) - * @param Tickstart Tick start value - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is set */ - while ((__HAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - - return HAL_TIMEOUT; - } - - if ((READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) && (Flag != UART_FLAG_TXE) && (Flag != UART_FLAG_TC)) - { - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) == SET) - { - /* Clear Overrun Error flag*/ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); - - /* Blocking error : transfer is aborted - Set the UART state ready to be able to start again the process, - Disable Rx Interrupts if ongoing */ - UART_EndRxTransfer(huart); - - huart->ErrorCode = HAL_UART_ERROR_ORE; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_ERROR; - } - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RTOF) == SET) - { - /* Clear Receiver Timeout flag*/ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF); - - /* Blocking error : transfer is aborted - Set the UART state ready to be able to start again the process, - Disable Rx Interrupts if ongoing */ - UART_EndRxTransfer(huart); - - huart->ErrorCode = HAL_UART_ERROR_RTO; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_TIMEOUT; - } - } - } - } - return HAL_OK; -} - -/** - * @brief Start Receive operation in interrupt mode. - * @note This function could be called by all HAL UART API providing reception in Interrupt mode. - * @note When calling this function, parameters validity is considered as already checked, - * i.e. Rx State, buffer address, ... - * UART Handle is assumed as Locked. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef UART_Start_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) -{ - huart->pRxBuffPtr = pData; - huart->RxXferSize = Size; - huart->RxXferCount = Size; - huart->RxISR = NULL; - - /* Computation of UART mask to apply to RDR register */ - UART_MASK_COMPUTATION(huart); - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; - - /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Configure Rx interrupt processing */ - if ((huart->FifoMode == UART_FIFOMODE_ENABLE) && (Size >= huart->NbRxDataToProcess)) - { - /* Set the Rx ISR function pointer according to the data word length */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - huart->RxISR = UART_RxISR_16BIT_FIFOEN; - } - else - { - huart->RxISR = UART_RxISR_8BIT_FIFOEN; - } - - /* Enable the UART Parity Error interrupt and RX FIFO Threshold interrupt */ - if (huart->Init.Parity != UART_PARITY_NONE) - { - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); - } - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); - } - else - { - /* Set the Rx ISR function pointer according to the data word length */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - huart->RxISR = UART_RxISR_16BIT; - } - else - { - huart->RxISR = UART_RxISR_8BIT; - } - - /* Enable the UART Parity Error interrupt and Data Register Not Empty interrupt */ - if (huart->Init.Parity != UART_PARITY_NONE) - { - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); - } - else - { - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - } - return HAL_OK; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Start Receive operation in DMA mode. - * @note This function could be called by all HAL UART API providing reception in DMA mode. - * @note When calling this function, parameters validity is considered as already checked, - * i.e. Rx State, buffer address, ... - * UART Handle is assumed as Locked. - * @param huart UART handle. - * @param pData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef UART_Start_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - uint16_t nbByte = Size; - - huart->pRxBuffPtr = pData; - huart->RxXferSize = Size; - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; - - if (huart->hdmarx != NULL) - { - /* 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; - - /* Set the DMA abort callback */ - huart->hdmarx->XferAbortCallback = NULL; - - /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size * 2 */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - /* Check linked list mode */ - if ((huart->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((huart->hdmarx->LinkedListQueue != NULL) && (huart->hdmarx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - huart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - huart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)&huart->Instance->RDR; - - /* Set DMA destination address */ - huart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)huart->pRxBuffPtr; - - /* Enable the UART receive DMA channel */ - status = HAL_DMAEx_List_Start_IT(huart->hdmarx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the UART receive DMA channel */ - status = HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->RDR, (uint32_t)huart->pRxBuffPtr, nbByte); - } - - if (status != HAL_OK) - { - /* Set error code to DMA */ - huart->ErrorCode = HAL_UART_ERROR_DMA; - - /* Restore huart->RxState to ready */ - huart->RxState = HAL_UART_STATE_READY; - - return HAL_ERROR; - } - } - - /* Enable the UART Parity Error Interrupt */ - if (huart->Init.Parity != UART_PARITY_NONE) - { - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); - } - - /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the UART CR3 register */ - ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - return HAL_OK; -} - - -/** - * @brief End ongoing Tx transfer on UART peripheral (following error detection or Transmit completion). - * @param huart UART handle. - * @retval None - */ -static void UART_EndTxTransfer(UART_HandleTypeDef *huart) -{ - /* Disable TXEIE, TCIE, TXFT interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_TXFTIE)); - - /* At end of Tx process, restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - - -/** - * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). - * @param huart UART handle. - * @retval None - */ -static void UART_EndRxTransfer(UART_HandleTypeDef *huart) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* In case of reception waiting for IDLE event, disable also the IDLE IE interrupt source */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - } - - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Reset RxIsr function pointer */ - huart->RxISR = NULL; -} - - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @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 *)(hdma->Parent); - - /* Check if DMA in circular mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - huart->TxXferCount = 0U; - - /* Disable the DMA transfer for transmit request by resetting the DMAT bit - in the UART CR3 register */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Enable the UART Transmit Complete Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); - } - /* DMA Circular mode */ - else - { -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Tx complete callback*/ - huart->TxCpltCallback(huart); -#else - /*Call legacy weak Tx complete callback*/ - HAL_UART_TxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } -} - -/** - * @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 *)(hdma->Parent); - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Tx Half complete callback*/ - huart->TxHalfCpltCallback(huart); -#else - /*Call legacy weak Tx Half complete callback*/ - HAL_UART_TxHalfCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - -/** - * @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 *)(hdma->Parent); - - /* Check if DMA in circular mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - huart->RxXferCount = 0U; - - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Disable the DMA transfer for the receiver request by resetting the DMAR bit - in the UART CR3 register */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* If Reception till IDLE event has been selected, Disable IDLE Interrupt */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - } - } - - /* Initialize type of RxEvent that correspond to RxEvent callback execution; - In this case, Rx Event type is Transfer Complete */ - huart->RxEventType = HAL_UART_RXEVENT_TC; - - /* Check current reception Mode : - If Reception till IDLE event has been selected : use Rx Event callback */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, huart->RxXferSize); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - else - { - /* In other cases : use Rx Complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx complete callback*/ - huart->RxCpltCallback(huart); -#else - /*Call legacy weak Rx complete callback*/ - HAL_UART_RxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } -} - -/** - * @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 *)(hdma->Parent); - - /* Initialize type of RxEvent that correspond to RxEvent callback execution; - In this case, Rx Event type is Half Transfer */ - huart->RxEventType = HAL_UART_RXEVENT_HT; - - /* Check current reception Mode : - If Reception till IDLE event has been selected : use Rx Event callback */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, huart->RxXferSize / 2U); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize / 2U); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - else - { - /* In other cases : use Rx Half Complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Half complete callback*/ - huart->RxHalfCpltCallback(huart); -#else - /*Call legacy weak Rx Half complete callback*/ - HAL_UART_RxHalfCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } -} - -/** - * @brief DMA UART communication error callback. - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMAError(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); - - const HAL_UART_StateTypeDef gstate = huart->gState; - const HAL_UART_StateTypeDef rxstate = huart->RxState; - - /* Stop UART DMA Tx request if ongoing */ - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && - (gstate == HAL_UART_STATE_BUSY_TX)) - { - huart->TxXferCount = 0U; - UART_EndTxTransfer(huart); - } - - /* Stop UART DMA Rx request if ongoing */ - if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && - (rxstate == HAL_UART_STATE_BUSY_RX)) - { - huart->RxXferCount = 0U; - UART_EndRxTransfer(huart); - } - - huart->ErrorCode |= HAL_UART_ERROR_DMA; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA UART communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); - huart->RxXferCount = 0U; - huart->TxXferCount = 0U; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA UART Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); - - huart->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (huart->hdmarx != NULL) - { - if (huart->hdmarx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - huart->TxXferCount = 0U; - huart->RxXferCount = 0U; - - /* Reset errorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Flush the whole TX FIFO (if needed) */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); - } - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Call user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - huart->AbortCpltCallback(huart); -#else - /* Call legacy weak Abort complete callback */ - HAL_UART_AbortCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - - -/** - * @brief DMA UART Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); - - huart->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (huart->hdmatx != NULL) - { - if (huart->hdmatx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - huart->TxXferCount = 0U; - huart->RxXferCount = 0U; - - /* Reset errorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Discard the received data */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Call user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort complete callback */ - huart->AbortCpltCallback(huart); -#else - /* Call legacy weak Abort complete callback */ - HAL_UART_AbortCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - - -/** - * @brief DMA UART Tx communication abort callback, when initiated by user by a call to - * HAL_UART_AbortTransmit_IT API (Abort only Tx transfer) - * (This callback is executed at end of DMA Tx Abort procedure following user abort request, - * and leads to user Tx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); - - huart->TxXferCount = 0U; - - /* Flush the whole TX FIFO (if needed) */ - if (huart->FifoMode == UART_FIFOMODE_ENABLE) - { - __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); - } - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Transmit Complete Callback */ - huart->AbortTransmitCpltCallback(huart); -#else - /* Call legacy weak Abort Transmit Complete Callback */ - HAL_UART_AbortTransmitCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA UART Rx communication abort callback, when initiated by user by a call to - * HAL_UART_AbortReceive_IT API (Abort only Rx transfer) - * (This callback is executed at end of DMA Rx Abort procedure following user abort request, - * and leads to user Rx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - huart->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); - - /* Discard the received data */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Call user Abort complete callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Receive Complete Callback */ - huart->AbortReceiveCpltCallback(huart); -#else - /* Call legacy weak Abort Receive Complete Callback */ - HAL_UART_AbortReceiveCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief TX interrupt handler for 7 or 8 bits data word length . - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Transmit_IT(). - * @param huart UART handle. - * @retval None - */ -static void UART_TxISR_8BIT(UART_HandleTypeDef *huart) -{ - /* Check that a Tx process is ongoing */ - if (huart->gState == HAL_UART_STATE_BUSY_TX) - { - if (huart->TxXferCount == 0U) - { - /* Disable the UART Transmit Data Register Empty Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - - /* Enable the UART Transmit Complete Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); - } - else - { - huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr & (uint8_t)0xFF); - huart->pTxBuffPtr++; - huart->TxXferCount--; - } - } -} - -/** - * @brief TX interrupt handler for 9 bits data word length. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Transmit_IT(). - * @param huart UART handle. - * @retval None - */ -static void UART_TxISR_16BIT(UART_HandleTypeDef *huart) -{ - const uint16_t *tmp; - - /* Check that a Tx process is ongoing */ - if (huart->gState == HAL_UART_STATE_BUSY_TX) - { - if (huart->TxXferCount == 0U) - { - /* Disable the UART Transmit Data Register Empty Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - - /* Enable the UART Transmit Complete Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); - } - else - { - tmp = (const uint16_t *) huart->pTxBuffPtr; - huart->Instance->TDR = (((uint32_t)(*tmp)) & 0x01FFUL); - huart->pTxBuffPtr += 2U; - huart->TxXferCount--; - } - } -} - -/** - * @brief TX interrupt handler for 7 or 8 bits data word length and FIFO mode is enabled. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Transmit_IT(). - * @param huart UART handle. - * @retval None - */ -static void UART_TxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) -{ - uint16_t nb_tx_data; - - /* Check that a Tx process is ongoing */ - if (huart->gState == HAL_UART_STATE_BUSY_TX) - { - for (nb_tx_data = huart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) - { - if (huart->TxXferCount == 0U) - { - /* Disable the TX FIFO threshold interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); - - /* Enable the UART Transmit Complete Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); - - break; /* force exit loop */ - } - else if (READ_BIT(huart->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) - { - huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr & (uint8_t)0xFF); - huart->pTxBuffPtr++; - huart->TxXferCount--; - } - else - { - /* Nothing to do */ - } - } - } -} - -/** - * @brief TX interrupt handler for 9 bits data word length and FIFO mode is enabled. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Transmit_IT(). - * @param huart UART handle. - * @retval None - */ -static void UART_TxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) -{ - const uint16_t *tmp; - uint16_t nb_tx_data; - - /* Check that a Tx process is ongoing */ - if (huart->gState == HAL_UART_STATE_BUSY_TX) - { - for (nb_tx_data = huart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) - { - if (huart->TxXferCount == 0U) - { - /* Disable the TX FIFO threshold interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); - - /* Enable the UART Transmit Complete Interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); - - break; /* force exit loop */ - } - else if (READ_BIT(huart->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) - { - tmp = (const uint16_t *) huart->pTxBuffPtr; - huart->Instance->TDR = (((uint32_t)(*tmp)) & 0x01FFUL); - huart->pTxBuffPtr += 2U; - huart->TxXferCount--; - } - else - { - /* Nothing to do */ - } - } - } -} - -/** - * @brief Wrap up transmission in non-blocking mode. - * @param huart pointer to a UART_HandleTypeDef structure that contains - * the configuration information for the specified UART module. - * @retval None - */ -static void UART_EndTransmit_IT(UART_HandleTypeDef *huart) -{ - /* Disable the UART Transmit Complete Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TCIE); - - /* Tx process is ended, restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* Cleat TxISR function pointer */ - huart->TxISR = NULL; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Tx complete callback*/ - huart->TxCpltCallback(huart); -#else - /*Call legacy weak Tx complete callback*/ - HAL_UART_TxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ -} - -/** - * @brief RX interrupt handler for 7 or 8 bits data word length . - * @param huart UART handle. - * @retval None - */ -static void UART_RxISR_8BIT(UART_HandleTypeDef *huart) -{ - uint16_t uhMask = huart->Mask; - uint16_t uhdata; - - /* Check that a Rx process is ongoing */ - if (huart->RxState == HAL_UART_STATE_BUSY_RX) - { - uhdata = (uint16_t) READ_REG(huart->Instance->RDR); - *huart->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); - huart->pRxBuffPtr++; - huart->RxXferCount--; - - if (huart->RxXferCount == 0U) - { - /* Disable the UART Parity Error Interrupt and RXNE interrupts */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - - /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Rx process is completed, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* Clear RxISR function pointer */ - huart->RxISR = NULL; - - /* Initialize type of RxEvent to Transfer Complete */ - huart->RxEventType = HAL_UART_RXEVENT_TC; - - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - /* Check that USART RTOEN bit is set */ - if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) - { - /* Enable the UART Receiver Timeout Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); - } - } - - /* Check current reception Mode : - If Reception till IDLE event has been selected : */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - /* Set reception type to Standard */ - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Disable IDLE interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) - { - /* Clear IDLE Flag */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - } - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, huart->RxXferSize); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - else - { - /* Standard reception API called */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx complete callback*/ - huart->RxCpltCallback(huart); -#else - /*Call legacy weak Rx complete callback*/ - HAL_UART_RxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @brief RX interrupt handler for 9 bits data word length . - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Receive_IT() - * @param huart UART handle. - * @retval None - */ -static void UART_RxISR_16BIT(UART_HandleTypeDef *huart) -{ - uint16_t *tmp; - uint16_t uhMask = huart->Mask; - uint16_t uhdata; - - /* Check that a Rx process is ongoing */ - if (huart->RxState == HAL_UART_STATE_BUSY_RX) - { - uhdata = (uint16_t) READ_REG(huart->Instance->RDR); - tmp = (uint16_t *) huart->pRxBuffPtr ; - *tmp = (uint16_t)(uhdata & uhMask); - huart->pRxBuffPtr += 2U; - huart->RxXferCount--; - - if (huart->RxXferCount == 0U) - { - /* Disable the UART Parity Error Interrupt and RXNE interrupt*/ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - - /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Rx process is completed, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* Clear RxISR function pointer */ - huart->RxISR = NULL; - - /* Initialize type of RxEvent to Transfer Complete */ - huart->RxEventType = HAL_UART_RXEVENT_TC; - - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - /* Check that USART RTOEN bit is set */ - if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) - { - /* Enable the UART Receiver Timeout Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); - } - } - - /* Check current reception Mode : - If Reception till IDLE event has been selected : */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - /* Set reception type to Standard */ - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Disable IDLE interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) - { - /* Clear IDLE Flag */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - } - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, huart->RxXferSize); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - else - { - /* Standard reception API called */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx complete callback*/ - huart->RxCpltCallback(huart); -#else - /*Call legacy weak Rx complete callback*/ - HAL_UART_RxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @brief RX interrupt handler for 7 or 8 bits data word length and FIFO mode is enabled. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Receive_IT() - * @param huart UART handle. - * @retval None - */ -static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) -{ - uint16_t uhMask = huart->Mask; - uint16_t uhdata; - uint16_t nb_rx_data; - uint16_t rxdatacount; - uint32_t isrflags = READ_REG(huart->Instance->ISR); - uint32_t cr1its = READ_REG(huart->Instance->CR1); - uint32_t cr3its = READ_REG(huart->Instance->CR3); - - /* Check that a Rx process is ongoing */ - if (huart->RxState == HAL_UART_STATE_BUSY_RX) - { - nb_rx_data = huart->NbRxDataToProcess; - while ((nb_rx_data > 0U) && ((isrflags & USART_ISR_RXNE_RXFNE) != 0U)) - { - uhdata = (uint16_t) READ_REG(huart->Instance->RDR); - *huart->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); - huart->pRxBuffPtr++; - huart->RxXferCount--; - isrflags = READ_REG(huart->Instance->ISR); - - /* If some non blocking errors occurred */ - if ((isrflags & (USART_ISR_PE | USART_ISR_FE | USART_ISR_NE)) != 0U) - { - /* UART parity error interrupt occurred -------------------------------------*/ - if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); - - huart->ErrorCode |= HAL_UART_ERROR_PE; - } - - /* UART frame error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); - - huart->ErrorCode |= HAL_UART_ERROR_FE; - } - - /* UART noise error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); - - huart->ErrorCode |= HAL_UART_ERROR_NE; - } - - /* Call UART Error Call back function if need be ----------------------------*/ - if (huart->ErrorCode != HAL_UART_ERROR_NONE) - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - } - } - - if (huart->RxXferCount == 0U) - { - /* Disable the UART Parity Error Interrupt and RXFT interrupt*/ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - - /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) - and RX FIFO Threshold interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Rx process is completed, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* Clear RxISR function pointer */ - huart->RxISR = NULL; - - /* Initialize type of RxEvent to Transfer Complete */ - huart->RxEventType = HAL_UART_RXEVENT_TC; - - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - /* Check that USART RTOEN bit is set */ - if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) - { - /* Enable the UART Receiver Timeout Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); - } - } - - /* Check current reception Mode : - If Reception till IDLE event has been selected : */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - /* Set reception type to Standard */ - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Disable IDLE interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) - { - /* Clear IDLE Flag */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - } - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, huart->RxXferSize); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - else - { - /* Standard reception API called */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx complete callback*/ - huart->RxCpltCallback(huart); -#else - /*Call legacy weak Rx complete callback*/ - HAL_UART_RxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - } - - /* When remaining number of bytes to receive is less than the RX FIFO - threshold, next incoming frames are processed as if FIFO mode was - disabled (i.e. one interrupt per received frame). - */ - rxdatacount = huart->RxXferCount; - if ((rxdatacount != 0U) && (rxdatacount < huart->NbRxDataToProcess)) - { - /* Disable the UART RXFT interrupt*/ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); - - /* Update the RxISR function pointer */ - huart->RxISR = UART_RxISR_8BIT; - - /* Enable the UART Data Register Not Empty interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @brief RX interrupt handler for 9 bits data word length and FIFO mode is enabled. - * @note Function is called under interruption only, once - * interruptions have been enabled by HAL_UART_Receive_IT() - * @param huart UART handle. - * @retval None - */ -static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) -{ - uint16_t *tmp; - uint16_t uhMask = huart->Mask; - uint16_t uhdata; - uint16_t nb_rx_data; - uint16_t rxdatacount; - uint32_t isrflags = READ_REG(huart->Instance->ISR); - uint32_t cr1its = READ_REG(huart->Instance->CR1); - uint32_t cr3its = READ_REG(huart->Instance->CR3); - - /* Check that a Rx process is ongoing */ - if (huart->RxState == HAL_UART_STATE_BUSY_RX) - { - nb_rx_data = huart->NbRxDataToProcess; - while ((nb_rx_data > 0U) && ((isrflags & USART_ISR_RXNE_RXFNE) != 0U)) - { - uhdata = (uint16_t) READ_REG(huart->Instance->RDR); - tmp = (uint16_t *) huart->pRxBuffPtr ; - *tmp = (uint16_t)(uhdata & uhMask); - huart->pRxBuffPtr += 2U; - huart->RxXferCount--; - isrflags = READ_REG(huart->Instance->ISR); - - /* If some non blocking errors occurred */ - if ((isrflags & (USART_ISR_PE | USART_ISR_FE | USART_ISR_NE)) != 0U) - { - /* UART parity error interrupt occurred -------------------------------------*/ - if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); - - huart->ErrorCode |= HAL_UART_ERROR_PE; - } - - /* UART frame error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); - - huart->ErrorCode |= HAL_UART_ERROR_FE; - } - - /* UART noise error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); - - huart->ErrorCode |= HAL_UART_ERROR_NE; - } - - /* Call UART Error Call back function if need be ----------------------------*/ - if (huart->ErrorCode != HAL_UART_ERROR_NONE) - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered error callback*/ - huart->ErrorCallback(huart); -#else - /*Call legacy weak error callback*/ - HAL_UART_ErrorCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - } - } - - if (huart->RxXferCount == 0U) - { - /* Disable the UART Parity Error Interrupt and RXFT interrupt*/ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - - /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) - and RX FIFO Threshold interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Rx process is completed, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* Clear RxISR function pointer */ - huart->RxISR = NULL; - - /* Initialize type of RxEvent to Transfer Complete */ - huart->RxEventType = HAL_UART_RXEVENT_TC; - - if (!(IS_LPUART_INSTANCE(huart->Instance))) - { - /* Check that USART RTOEN bit is set */ - if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) - { - /* Enable the UART Receiver Timeout Interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); - } - } - - /* Check current reception Mode : - If Reception till IDLE event has been selected : */ - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - /* Set reception type to Standard */ - huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; - - /* Disable IDLE interrupt */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) - { - /* Clear IDLE Flag */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - } - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx Event callback*/ - huart->RxEventCallback(huart, huart->RxXferSize); -#else - /*Call legacy weak Rx Event callback*/ - HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - else - { - /* Standard reception API called */ -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - /*Call registered Rx complete callback*/ - huart->RxCpltCallback(huart); -#else - /*Call legacy weak Rx complete callback*/ - HAL_UART_RxCpltCallback(huart); -#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ - } - } - } - - /* When remaining number of bytes to receive is less than the RX FIFO - threshold, next incoming frames are processed as if FIFO mode was - disabled (i.e. one interrupt per received frame). - */ - rxdatacount = huart->RxXferCount; - if ((rxdatacount != 0U) && (rxdatacount < huart->NbRxDataToProcess)) - { - /* Disable the UART RXFT interrupt*/ - ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); - - /* Update the RxISR function pointer */ - huart->RxISR = UART_RxISR_16BIT; - - /* Enable the UART Data Register Not Empty interrupt */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @} - */ - -#endif /* HAL_UART_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_uart.c + * @author MCD Application Team + * @brief UART HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The UART HAL driver can be used as follows: + + (#) Declare a UART_HandleTypeDef handle structure (eg. UART_HandleTypeDef huart). + (#) Initialize the UART low level resources by implementing 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. + (++) UART interrupts handling: + -@@- The specific UART interrupts (Transmission complete interrupt, + RXNE interrupt, RX/TX FIFOs related interrupts and Error Interrupts) + are managed using the macros __HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() + inside the transmit and receive processes. + (++) 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 channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx channel. + (+++) 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 channel. + + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Prescaler value , Hardware + flow control and Mode (Receiver/Transmitter) in the huart handle Init structure. + + (#) If required, program UART advanced features (TX/RX pins swap, auto Baud rate detection,...) + in the huart handle AdvancedInit 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 UART LIN (Local Interconnection Network) mode, initialize the UART registers + by calling the HAL_LIN_Init() API. + + (#) For the UART Multiprocessor mode, initialize the UART registers + by calling the HAL_MultiProcessor_Init() API. + + (#) For the UART RS485 Driver Enabled mode, initialize the UART registers + by calling the HAL_RS485Ex_Init() API. + + [..] + (@) These API's (HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init(), HAL_MultiProcessor_Init(), + also configure the low level Hardware GPIO, CLOCK, CORTEX...etc) by + calling the customized HAL_UART_MspInit() API. + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_HAL_UART_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function HAL_UART_RegisterCallback() to register a user callback. + Function HAL_UART_RegisterCallback() allows to register following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) WakeupCallback : Wakeup Callback. + (+) RxFifoFullCallback : Rx Fifo Full Callback. + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) MspInitCallback : UART MspInit. + (+) MspDeInitCallback : UART MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_UART_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_UART_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) AbortTransmitCpltCallback : Abort Transmit Complete Callback. + (+) AbortReceiveCpltCallback : Abort Receive Complete Callback. + (+) WakeupCallback : Wakeup Callback. + (+) RxFifoFullCallback : Rx Fifo Full Callback. + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) MspInitCallback : UART MspInit. + (+) MspDeInitCallback : UART MspDeInit. + + [..] + For specific callback RxEventCallback, use dedicated registration/reset functions: + respectively HAL_UART_RegisterRxEventCallback() , HAL_UART_UnRegisterRxEventCallback(). + + [..] + By default, after the HAL_UART_Init() and when the state is HAL_UART_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_UART_TxCpltCallback(), HAL_UART_RxHalfCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak functions in the HAL_UART_Init() + and HAL_UART_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_UART_Init() and HAL_UART_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in HAL_UART_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_UART_STATE_READY or HAL_UART_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_UART_RegisterCallback() before calling HAL_UART_DeInit() + or HAL_UART_Init() function. + + [..] + When The compilation define USE_HAL_UART_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak callbacks are used. + + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup UART UART + * @brief HAL UART module driver + * @{ + */ + +#ifdef HAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup UART_Private_Constants UART Private Constants + * @{ + */ +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | \ + USART_CR1_OVER8 | USART_CR1_FIFOEN)) /*!< UART or USART CR1 fields of parameters set by UART_SetConfig API */ + +#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT | USART_CR3_TXFTCFG | \ + USART_CR3_RXFTCFG)) /*!< UART or USART CR3 fields of parameters set by UART_SetConfig API */ + +#define LPUART_BRR_MIN 0x00000300U /* LPUART BRR minimum authorized value */ +#define LPUART_BRR_MAX 0x000FFFFFU /* LPUART BRR maximum authorized value */ + +#define UART_BRR_MIN 0x10U /* UART BRR minimum authorized value */ +#define UART_BRR_MAX 0x0000FFFFU /* UART BRR maximum authorized value */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup UART_Private_Functions + * @{ + */ +static void UART_EndRxTransfer(UART_HandleTypeDef *huart); +#if defined(HAL_DMA_MODULE_ENABLED) +static void UART_EndTxTransfer(UART_HandleTypeDef *huart); +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAError(DMA_HandleTypeDef *hdma); +static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +#endif /* HAL_DMA_MODULE_ENABLED */ +static void UART_TxISR_8BIT(UART_HandleTypeDef *huart); +static void UART_TxISR_16BIT(UART_HandleTypeDef *huart); +static void UART_TxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart); +static void UART_TxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart); +static void UART_EndTransmit_IT(UART_HandleTypeDef *huart); +static void UART_RxISR_8BIT(UART_HandleTypeDef *huart); +static void UART_RxISR_16BIT(UART_HandleTypeDef *huart); +static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart); +static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart); +/** + * @} + */ + +/* Private variables ---------------------------------------------------------*/ +/** @addtogroup UART_Private_variables + * @{ + */ +const uint16_t UARTPrescTable[12] = {1U, 2U, 4U, 6U, 8U, 10U, 12U, 16U, 32U, 64U, 128U, 256U}; +/** + * @} + */ + +/* Exported Constants --------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup UART_Exported_Functions UART Exported Functions + * @{ + */ + +/** @defgroup UART_Exported_Functions_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 the parameters below 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. + (++) Hardware flow control + (++) Receiver/transmitter modes + (++) Over Sampling Method + (++) One-Bit Sampling Method + (+) For the asynchronous mode, the following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) auto Baud rate detection + [..] + The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init()and HAL_MultiProcessor_Init()API + follow respectively the UART asynchronous, UART Half duplex, UART LIN mode + and UART multiprocessor mode configuration procedures (details for the procedures + are available in reference manual). + +@endverbatim + + Depending on the frame length defined by the M1 and M0 bits (7-bit, + 8-bit or 9-bit), the possible UART formats are listed in the + following table. + + Table 1. UART frame format. + +-----------------------------------------------------------------------+ + | M1 bit | M0 bit | PCE bit | UART frame | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 0 | | SB | 8 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 0 | | SB | 9 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 0 | | SB | 7 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | + +-----------------------------------------------------------------------+ + + * @{ + */ + +/** + * @brief Initialize the UART mode according to the specified + * parameters in the UART_InitTypeDef and initialize 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)) || (IS_LPUART_INSTANCE(huart->Instance))); + } + + if (huart->gState == HAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = HAL_UNLOCKED; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = HAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = HAL_UART_STATE_BUSY; + + __HAL_UART_DISABLE(huart); + + /* Perform advanced settings configuration */ + /* For some items, configuration requires to be done prior TE and RE bits are set */ + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* 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.*/ + CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); + CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); + + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Initialize the half-duplex mode according to the specified + * parameters in the UART_InitTypeDef and creates 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; + } + + /* Check UART instance */ + assert_param(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance)); + + if (huart->gState == HAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = HAL_UNLOCKED; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = HAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = HAL_UART_STATE_BUSY; + + __HAL_UART_DISABLE(huart); + + /* Perform advanced settings configuration */ + /* For some items, configuration requires to be done prior TE and RE bits are set */ + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* 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.*/ + CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); + CLEAR_BIT(huart->Instance->CR3, (USART_CR3_IREN | USART_CR3_SCEN)); + + /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */ + SET_BIT(huart->Instance->CR3, USART_CR3_HDSEL); + + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ + return (UART_CheckIdleState(huart)); +} + + +/** + * @brief Initialize the LIN mode according to the specified + * parameters in the UART_InitTypeDef and creates 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 @ref UART_LINBREAKDETECTLENGTH_10B 10-bit break detection + * @arg @ref 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 LIN UART instance */ + assert_param(IS_UART_LIN_INSTANCE(huart->Instance)); + /* Check the Break detection length parameter */ + assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); + + /* LIN mode limited to 16-bit oversampling only */ + if (huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + return HAL_ERROR; + } + /* LIN mode limited to 8-bit data length */ + if (huart->Init.WordLength != UART_WORDLENGTH_8B) + { + return HAL_ERROR; + } + + if (huart->gState == HAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = HAL_UNLOCKED; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = HAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = HAL_UART_STATE_BUSY; + + __HAL_UART_DISABLE(huart); + + /* Perform advanced settings configuration */ + /* For some items, configuration requires to be done prior TE and RE bits are set */ + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* 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.*/ + CLEAR_BIT(huart->Instance->CR2, USART_CR2_CLKEN); + CLEAR_BIT(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 */ + SET_BIT(huart->Instance->CR2, USART_CR2_LINEN); + + /* Set the USART LIN Break detection length. */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_LBDL, BreakDetectLength); + + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ + return (UART_CheckIdleState(huart)); +} + + +/** + * @brief Initialize the multiprocessor mode according to the specified + * parameters in the UART_InitTypeDef and initialize the associated handle. + * @param huart UART handle. + * @param Address UART node address (4-, 6-, 7- or 8-bit long). + * @param WakeUpMethod Specifies the UART wakeup method. + * This parameter can be one of the following values: + * @arg @ref UART_WAKEUPMETHOD_IDLELINE WakeUp by an idle line detection + * @arg @ref UART_WAKEUPMETHOD_ADDRESSMARK WakeUp by an address mark + * @note If the user resorts to idle line detection wake up, the Address parameter + * is useless and ignored by the initialization function. + * @note If the user resorts to address mark wake up, the address length detection + * is configured by default to 4 bits only. For the UART to be able to + * manage 6-, 7- or 8-bit long addresses detection, the API + * HAL_MultiProcessorEx_AddressLength_Set() must be called after + * HAL_MultiProcessor_Init(). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return HAL_ERROR; + } + + /* Check the wake up method parameter */ + assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod)); + + if (huart->gState == HAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = HAL_UNLOCKED; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = HAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = HAL_UART_STATE_BUSY; + + __HAL_UART_DISABLE(huart); + + /* Perform advanced settings configuration */ + /* For some items, configuration requires to be done prior TE and RE bits are set */ + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* In multiprocessor 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. */ + CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); + CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); + + if (WakeUpMethod == UART_WAKEUPMETHOD_ADDRESSMARK) + { + /* If address mark wake up method is chosen, set the USART address node */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)Address << UART_CR2_ADDRESS_LSB_POS)); + } + + /* Set the wake up method by setting the WAKE bit in the CR1 register */ + MODIFY_REG(huart->Instance->CR1, USART_CR1_WAKE, WakeUpMethod); + + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ + return (UART_CheckIdleState(huart)); +} + + +/** + * @brief DeInitialize 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)) || (IS_LPUART_INSTANCE(huart->Instance))); + + huart->gState = HAL_UART_STATE_BUSY; + + __HAL_UART_DISABLE(huart); + + huart->Instance->CR1 = 0x0U; + huart->Instance->CR2 = 0x0U; + huart->Instance->CR3 = 0x0U; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + if (huart->MspDeInitCallback == NULL) + { + huart->MspDeInitCallback = HAL_UART_MspDeInit; + } + /* DeInit the low level hardware */ + huart->MspDeInitCallback(huart); +#else + /* DeInit the low level hardware */ + HAL_UART_MspDeInit(huart); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->gState = HAL_UART_STATE_RESET; + huart->RxState = HAL_UART_STATE_RESET; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + huart->RxEventType = HAL_UART_RXEVENT_TC; + + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Initialize the UART MSP. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitialize the UART MSP. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_MspDeInit can be implemented in the user file + */ +} + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User UART Callback + * To be used to override the weak predefined callback + * @note The HAL_UART_RegisterCallback() may be called before HAL_UART_Init(), HAL_HalfDuplex_Init(), + * HAL_LIN_Init(), HAL_MultiProcessor_Init() or HAL_RS485Ex_Init() in HAL_UART_STATE_RESET to register + * callbacks for HAL_UART_MSPINIT_CB_ID and HAL_UART_MSPDEINIT_CB_ID + * @param huart uart handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref HAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref HAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_UART_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref HAL_UART_WAKEUP_CB_ID Wakeup Callback ID + * @arg @ref HAL_UART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID + * @arg @ref HAL_UART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID + * @arg @ref HAL_UART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_RegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID, + pUART_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (huart->gState == HAL_UART_STATE_READY) + { + switch (CallbackID) + { + case HAL_UART_TX_HALFCOMPLETE_CB_ID : + huart->TxHalfCpltCallback = pCallback; + break; + + case HAL_UART_TX_COMPLETE_CB_ID : + huart->TxCpltCallback = pCallback; + break; + + case HAL_UART_RX_HALFCOMPLETE_CB_ID : + huart->RxHalfCpltCallback = pCallback; + break; + + case HAL_UART_RX_COMPLETE_CB_ID : + huart->RxCpltCallback = pCallback; + break; + + case HAL_UART_ERROR_CB_ID : + huart->ErrorCallback = pCallback; + break; + + case HAL_UART_ABORT_COMPLETE_CB_ID : + huart->AbortCpltCallback = pCallback; + break; + + case HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : + huart->AbortTransmitCpltCallback = pCallback; + break; + + case HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : + huart->AbortReceiveCpltCallback = pCallback; + break; + + case HAL_UART_WAKEUP_CB_ID : + huart->WakeupCallback = pCallback; + break; + + case HAL_UART_RX_FIFO_FULL_CB_ID : + huart->RxFifoFullCallback = pCallback; + break; + + case HAL_UART_TX_FIFO_EMPTY_CB_ID : + huart->TxFifoEmptyCallback = pCallback; + break; + + case HAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = pCallback; + break; + + case HAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = pCallback; + break; + + default : + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + break; + } + } + else if (huart->gState == HAL_UART_STATE_RESET) + { + switch (CallbackID) + { + case HAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = pCallback; + break; + + case HAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = pCallback; + break; + + default : + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + break; + } + } + else + { + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an UART Callback + * UART callaback is redirected to the weak predefined callback + * @note The HAL_UART_UnRegisterCallback() may be called before HAL_UART_Init(), HAL_HalfDuplex_Init(), + * HAL_LIN_Init(), HAL_MultiProcessor_Init() or HAL_RS485Ex_Init() in HAL_UART_STATE_RESET to un-register + * callbacks for HAL_UART_MSPINIT_CB_ID and HAL_UART_MSPDEINIT_CB_ID + * @param huart uart handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_UART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref HAL_UART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_UART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref HAL_UART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_UART_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_UART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID Abort Transmit Complete Callback ID + * @arg @ref HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID Abort Receive Complete Callback ID + * @arg @ref HAL_UART_WAKEUP_CB_ID Wakeup Callback ID + * @arg @ref HAL_UART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID + * @arg @ref HAL_UART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID + * @arg @ref HAL_UART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_UART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_UnRegisterCallback(UART_HandleTypeDef *huart, HAL_UART_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_UART_STATE_READY == huart->gState) + { + switch (CallbackID) + { + case HAL_UART_TX_HALFCOMPLETE_CB_ID : + huart->TxHalfCpltCallback = HAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case HAL_UART_TX_COMPLETE_CB_ID : + huart->TxCpltCallback = HAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_UART_RX_HALFCOMPLETE_CB_ID : + huart->RxHalfCpltCallback = HAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case HAL_UART_RX_COMPLETE_CB_ID : + huart->RxCpltCallback = HAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_UART_ERROR_CB_ID : + huart->ErrorCallback = HAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_UART_ABORT_COMPLETE_CB_ID : + huart->AbortCpltCallback = HAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_UART_ABORT_TRANSMIT_COMPLETE_CB_ID : + huart->AbortTransmitCpltCallback = HAL_UART_AbortTransmitCpltCallback; /* Legacy weak + AbortTransmitCpltCallback */ + break; + + case HAL_UART_ABORT_RECEIVE_COMPLETE_CB_ID : + huart->AbortReceiveCpltCallback = HAL_UART_AbortReceiveCpltCallback; /* Legacy weak + AbortReceiveCpltCallback */ + break; + + case HAL_UART_WAKEUP_CB_ID : + huart->WakeupCallback = HAL_UARTEx_WakeupCallback; /* Legacy weak WakeupCallback */ + break; + + case HAL_UART_RX_FIFO_FULL_CB_ID : + huart->RxFifoFullCallback = HAL_UARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ + break; + + case HAL_UART_TX_FIFO_EMPTY_CB_ID : + huart->TxFifoEmptyCallback = HAL_UARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ + break; + + case HAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = HAL_UART_MspInit; /* Legacy weak MspInitCallback */ + break; + + case HAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = HAL_UART_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + break; + } + } + else if (HAL_UART_STATE_RESET == huart->gState) + { + switch (CallbackID) + { + case HAL_UART_MSPINIT_CB_ID : + huart->MspInitCallback = HAL_UART_MspInit; + break; + + case HAL_UART_MSPDEINIT_CB_ID : + huart->MspDeInitCallback = HAL_UART_MspDeInit; + break; + + default : + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + break; + } + } + else + { + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Register a User UART Rx Event Callback + * To be used instead of the weak predefined callback + * @param huart Uart handle + * @param pCallback Pointer to the Rx Event Callback function + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_RegisterRxEventCallback(UART_HandleTypeDef *huart, pUART_RxEventCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (huart->RxState == HAL_UART_STATE_READY) + { + huart->RxEventCallback = pCallback; + } + else + { + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief UnRegister the UART Rx Event Callback + * UART Rx Event Callback is redirected to the weak HAL_UARTEx_RxEventCallback() predefined callback + * @param huart Uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_UnRegisterRxEventCallback(UART_HandleTypeDef *huart) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (huart->RxState == HAL_UART_STATE_READY) + { + huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak UART Rx Event Callback */ + } + else + { + huart->ErrorCode |= HAL_UART_ERROR_INVALID_CALLBACK; + + status = HAL_ERROR; + } + + return status; +} + +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup UART_Exported_Functions_Group2 IO operation functions + * @brief UART Transmit/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 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. + (+) Non-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 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 respectively 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() + + (#) Non-Blocking mode API's with DMA are : + (+) HAL_UART_Transmit_DMA() + (+) HAL_UART_Receive_DMA() + (+) HAL_UART_DMAPause() + (+) HAL_UART_DMAResume() + (+) HAL_UART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: + (+) HAL_UART_TxHalfCpltCallback() + (+) HAL_UART_TxCpltCallback() + (+) HAL_UART_RxHalfCpltCallback() + (+) HAL_UART_RxCpltCallback() + (+) HAL_UART_ErrorCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (+) HAL_UART_Abort() + (+) HAL_UART_AbortTransmit() + (+) HAL_UART_AbortReceive() + (+) HAL_UART_Abort_IT() + (+) HAL_UART_AbortTransmit_IT() + (+) HAL_UART_AbortReceive_IT() + + (#) For Abort services based on interrupts (HAL_UART_Abortxxx_IT), a set of Abort Complete Callbacks are provided: + (+) HAL_UART_AbortCpltCallback() + (+) HAL_UART_AbortTransmitCpltCallback() + (+) HAL_UART_AbortReceiveCpltCallback() + + (#) A Rx Event Reception Callback (Rx event notification) is available for Non_Blocking modes of enhanced + reception services: + (+) HAL_UARTEx_RxEventCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error + in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user + to identify error type, and HAL_UART_ErrorCallback() user callback is executed. + Transfer is kept ongoing on UART side. + If user wants to abort it, Abort services should be called by user. + (+) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, and HAL_UART_ErrorCallback() + user callback is executed. + + -@- 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 Send an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pData. + * @note When FIFO mode is enabled, writing a data in the TDR register adds one + * data to the TXFIFO. Write operations to the TDR register are performed + * when TXFNF flag is set. From hardware perspective, TXFNF flag and + * TXE are mapped on the same bit-field. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @param Timeout Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + const uint8_t *pdata8bits; + const uint16_t *pdata16bits; + uint32_t tickstart; + + /* Check that a Tx process is not already ongoing */ + if (huart->gState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->gState = HAL_UART_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pData needs to be handled as a uint16_t pointer */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (const uint16_t *) pData; + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + while (huart->TxXferCount > 0U) + { + if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + + huart->gState = HAL_UART_STATE_READY; + + return HAL_TIMEOUT; + } + if (pdata8bits == NULL) + { + huart->Instance->TDR = (uint16_t)(*pdata16bits & 0x01FFU); + pdata16bits++; + } + else + { + huart->Instance->TDR = (uint8_t)(*pdata8bits & 0xFFU); + pdata8bits++; + } + huart->TxXferCount--; + } + + if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) + { + huart->gState = HAL_UART_STATE_READY; + + return HAL_TIMEOUT; + } + + /* At end of Tx process, restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pData. + * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO + * is not empty. Read operations from the RDR register are performed when + * RXFNE flag is set. From hardware perspective, RXFNE flag and + * RXNE are mapped on the same bit-field. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) 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) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + uint16_t uhMask; + uint32_t tickstart; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->RxState = HAL_UART_STATE_BUSY_RX; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + UART_MASK_COMPUTATION(huart); + uhMask = huart->Mask; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) pData; + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + /* as long as data have to be received */ + while (huart->RxXferCount > 0U) + { + if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + { + huart->RxState = HAL_UART_STATE_READY; + + return HAL_TIMEOUT; + } + if (pdata8bits == NULL) + { + *pdata16bits = (uint16_t)(huart->Instance->RDR & uhMask); + pdata16bits++; + } + else + { + *pdata8bits = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); + pdata8bits++; + } + huart->RxXferCount--; + } + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) +{ + /* Check that a Tx process is not already ongoing */ + if (huart->gState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + huart->TxISR = NULL; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->gState = HAL_UART_STATE_BUSY_TX; + + /* Configure Tx interrupt processing */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + /* Set the Tx ISR function pointer according to the data word length */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + huart->TxISR = UART_TxISR_16BIT_FIFOEN; + } + else + { + huart->TxISR = UART_TxISR_8BIT_FIFOEN; + } + + /* Enable the TX FIFO threshold interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); + } + else + { + /* Set the Tx ISR function pointer according to the data word length */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + huart->TxISR = UART_TxISR_16BIT; + } + else + { + huart->TxISR = UART_TxISR_8BIT; + } + + /* Enable the Transmit Data Register Empty interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Set Reception type to Standard reception */ + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + /* Check that USART RTOEN bit is set */ + if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) + { + /* Enable the UART Receiver Timeout Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RTOIE); + } + } + + return (UART_Start_Receive_IT(huart, pData, Size)); + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Send an amount of data in DMA mode. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + uint16_t nbByte = Size; + + /* Check that a Tx process is not already ongoing */ + if (huart->gState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->gState = HAL_UART_STATE_BUSY_TX; + + if (huart->hdmatx != NULL) + { + /* 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; + + /* Set the DMA abort callback */ + huart->hdmatx->XferAbortCallback = NULL; + + /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size * 2 */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + /* Check linked list mode */ + if ((huart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((huart->hdmatx->LinkedListQueue != NULL) && (huart->hdmatx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + huart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + huart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)huart->pTxBuffPtr; + + /* Set DMA destination address */ + huart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&huart->Instance->TDR; + + /* Enable the UART transmit DMA channel */ + status = HAL_DMAEx_List_Start_IT(huart->hdmatx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the UART transmit DMA channel */ + status = HAL_DMA_Start_IT(huart->hdmatx, (uint32_t)huart->pTxBuffPtr, (uint32_t)&huart->Instance->TDR, nbByte); + } + + if (status != HAL_OK) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + /* Restore huart->gState to ready */ + huart->gState = HAL_UART_STATE_READY; + + return HAL_ERROR; + } + } + /* Clear the TC flag in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_TCF); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the UART CR3 register */ + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode. + * @note When the UART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position). + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Set Reception type to Standard reception */ + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + /* Check that USART RTOEN bit is set */ + if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) + { + /* Enable the UART Receiver Timeout Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RTOIE); + } + } + + return (UART_Start_Receive_DMA(huart, pData, Size)); + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pause the DMA Transfer. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart) +{ + const HAL_UART_StateTypeDef gstate = huart->gState; + const HAL_UART_StateTypeDef rxstate = huart->RxState; + + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && + (gstate == HAL_UART_STATE_BUSY_TX)) + { + /* Suspend the UART DMA Tx channel : use blocking DMA Suspend API (no callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Suspend callback to Null. + No call back execution at end of DMA Suspend procedure */ + huart->hdmatx->XferSuspendCallback = NULL; + + if (HAL_DMAEx_Suspend(huart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && + (rxstate == HAL_UART_STATE_BUSY_RX)) + { + /* Suspend the UART DMA Rx channel : use blocking DMA Suspend API (no callback) */ + if (huart->hdmarx != NULL) + { + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Set the UART DMA Suspend callback to Null. + No call back execution at end of DMA Suspend procedure */ + huart->hdmarx->XferSuspendCallback = NULL; + + if (HAL_DMAEx_Suspend(huart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + + return HAL_OK; +} + +/** + * @brief Resume the DMA Transfer. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart) +{ + if (huart->gState == HAL_UART_STATE_BUSY_TX) + { + /* Resume the UART DMA Tx channel */ + if (huart->hdmatx != NULL) + { + if (HAL_DMAEx_Resume(huart->hdmatx) != HAL_OK) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_ERROR; + } + } + } + if (huart->RxState == HAL_UART_STATE_BUSY_RX) + { + /* Clear the Overrun flag before resuming the Rx transfer */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); + + /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ + if (huart->Init.Parity != UART_PARITY_NONE) + { + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); + } + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Resume the UART DMA Rx channel */ + if (huart->hdmarx != NULL) + { + if (HAL_DMAEx_Resume(huart->hdmarx) != HAL_OK) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_ERROR; + } + } + } + + return HAL_OK; +} + +/** + * @brief Stop the DMA Transfer. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart) +{ + /* The Lock is not implemented on this API to allow the user application + to call the HAL UART API under callbacks HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback() / + HAL_UART_TxHalfCpltCallback / HAL_UART_RxHalfCpltCallback: + indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete + interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of + the stream and the corresponding call back is executed. */ + + const HAL_UART_StateTypeDef gstate = huart->gState; + const HAL_UART_StateTypeDef rxstate = huart->RxState; + + /* Stop UART DMA Tx request if ongoing */ + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && + (gstate == HAL_UART_STATE_BUSY_TX)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the UART DMA Tx channel */ + if (huart->hdmatx != NULL) + { + if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + + UART_EndTxTransfer(huart); + } + + /* Stop UART DMA Rx request if ongoing */ + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && + (rxstate == HAL_UART_STATE_BUSY_RX)) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the UART DMA Rx channel */ + if (huart->hdmarx != NULL) + { + if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + + UART_EndRxTransfer(huart); + } + + return HAL_OK; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Abort(UART_HandleTypeDef *huart) +{ + /* Disable TXE, TC, RXNE, PE, RXFT, TXFT and ERR (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | + USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE); + + /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the UART DMA Tx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable the UART DMA Tx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + + /* Abort the UART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the UART DMA Rx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx and Rx transfer counters */ + huart->TxXferCount = 0U; + huart->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Flush the whole TX FIFO (if needed) */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); + } + + /* Discard the received data */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = HAL_UART_STATE_READY; + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + + return HAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (blocking mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_AbortTransmit(UART_HandleTypeDef *huart) +{ + /* Disable TCIE, TXEIE and TXFTIE interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TCIE | USART_CR1_TXEIE_TXFNFIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the UART DMA Tx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable the UART DMA Tx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(huart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx transfer counter */ + huart->TxXferCount = 0U; + + /* Flush the whole TX FIFO (if needed) */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); + } + + /* Restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (blocking mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_AbortReceive(UART_HandleTypeDef *huart) +{ + /* Disable PEIE, EIE, RXNEIE and RXFTIE interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE | USART_CR3_RXFTIE); + + /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the UART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the UART DMA Rx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(huart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(huart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Rx transfer counter */ + huart->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Discard the received data */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + + /* Restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + return HAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Abort_IT(UART_HandleTypeDef *huart) +{ + uint32_t abortcplt = 1U; + + /* Disable interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_TCIE | USART_CR1_RXNEIE_RXFNEIE | + USART_CR1_TXEIE_TXFNFIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); + + /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* If DMA Tx and/or DMA Rx Handles are associated to UART Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (huart->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) + { + huart->hdmatx->XferAbortCallback = UART_DMATxAbortCallback; + } + else + { + huart->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (huart->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + huart->hdmarx->XferAbortCallback = UART_DMARxAbortCallback; + } + else + { + huart->hdmarx->XferAbortCallback = NULL; + } + } + + /* Abort the UART DMA Tx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable DMA Tx at UART level */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (huart->hdmatx != NULL) + { + /* UART Tx DMA Abort callback has already been initialised : + will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) + { + huart->hdmatx->XferAbortCallback = NULL; + } + else + { + abortcplt = 0U; + } + } + } + + /* Abort the UART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the UART DMA Rx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (huart->hdmarx != NULL) + { + /* UART Rx DMA Abort callback has already been initialised : + will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) + { + huart->hdmarx->XferAbortCallback = NULL; + abortcplt = 1U; + } + else + { + abortcplt = 0U; + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (abortcplt == 1U) + { + /* Reset Tx and Rx transfer counters */ + huart->TxXferCount = 0U; + huart->RxXferCount = 0U; + + /* Clear ISR function pointers */ + huart->RxISR = NULL; + huart->TxISR = NULL; + + /* Reset errorCode */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Flush the whole TX FIFO (if needed) */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); + } + + /* Discard the received data */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = HAL_UART_STATE_READY; + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + huart->AbortCpltCallback(huart); +#else + /* Call legacy weak Abort complete callback */ + HAL_UART_AbortCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @brief Abort ongoing Transmit transfer (Interrupt mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Tx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart) +{ + /* Disable interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TCIE | USART_CR1_TXEIE_TXFNFIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the UART DMA Tx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable the UART DMA Tx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (huart->hdmatx != NULL) + { + /* Set the UART DMA Abort callback : + will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + huart->hdmatx->XferAbortCallback = UART_DMATxOnlyAbortCallback; + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) + { + /* Call Directly huart->hdmatx->XferAbortCallback function in case of error */ + huart->hdmatx->XferAbortCallback(huart->hdmatx); + } + } + else + { + /* Reset Tx transfer counter */ + huart->TxXferCount = 0U; + + /* Clear TxISR function pointers */ + huart->TxISR = NULL; + + /* Restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + huart->AbortTransmitCpltCallback(huart); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_UART_AbortTransmitCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Reset Tx transfer counter */ + huart->TxXferCount = 0U; + + /* Clear TxISR function pointers */ + huart->TxISR = NULL; + + /* Flush the whole TX FIFO (if needed) */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); + } + + /* Restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + huart->AbortTransmitCpltCallback(huart); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_UART_AbortTransmitCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @brief Abort ongoing Receive transfer (Interrupt mode). + * @param huart UART handle. + * @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable UART Interrupts (Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* If Reception till IDLE event was ongoing, disable IDLEIE interrupt */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_IDLEIE)); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the UART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the UART DMA Rx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback : + will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = UART_DMARxOnlyAbortCallback; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) + { + /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ + huart->hdmarx->XferAbortCallback(huart->hdmarx); + } + } + else + { + /* Reset Rx transfer counter */ + huart->RxXferCount = 0U; + + /* Clear RxISR function pointer */ + huart->pRxBuffPtr = NULL; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Discard the received data */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + + /* Restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + huart->AbortReceiveCpltCallback(huart); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_UART_AbortReceiveCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Reset Rx transfer counter */ + huart->RxXferCount = 0U; + + /* Clear RxISR function pointer */ + huart->pRxBuffPtr = NULL; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + huart->AbortReceiveCpltCallback(huart); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_UART_AbortReceiveCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @brief Handle UART interrupt request. + * @param huart UART handle. + * @retval None + */ +void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) +{ + uint32_t isrflags = READ_REG(huart->Instance->ISR); + uint32_t cr1its = READ_REG(huart->Instance->CR1); + uint32_t cr3its = READ_REG(huart->Instance->CR3); + + uint32_t errorflags; + uint32_t errorcode; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF)); + if (errorflags == 0U) + { + /* UART in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U))) + { + if (huart->RxISR != NULL) + { + huart->RxISR(huart); + } + return; + } + } + + /* If some errors occur */ + if ((errorflags != 0U) + && ((((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) + || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_RTOIE)) != 0U)))) + { + /* UART parity error interrupt occurred -------------------------------------*/ + if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); + + huart->ErrorCode |= HAL_UART_ERROR_PE; + } + + /* UART frame error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); + + huart->ErrorCode |= HAL_UART_ERROR_FE; + } + + /* UART noise error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); + + huart->ErrorCode |= HAL_UART_ERROR_NE; + } + + /* UART Over-Run interrupt occurred -----------------------------------------*/ + if (((isrflags & USART_ISR_ORE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || + ((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U))) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); + + huart->ErrorCode |= HAL_UART_ERROR_ORE; + } + + /* UART Receiver Timeout interrupt occurred ---------------------------------*/ + if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF); + + huart->ErrorCode |= HAL_UART_ERROR_RTO; + } + + /* Call UART Error Call back function if need be ----------------------------*/ + if (huart->ErrorCode != HAL_UART_ERROR_NONE) + { + /* UART in mode Receiver --------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U))) + { + if (huart->RxISR != NULL) + { + huart->RxISR(huart); + } + } + + /* If Error is to be considered as blocking : + - Receiver Timeout error in Reception + - Overrun error in Reception + - any error occurs in DMA mode reception + */ + errorcode = huart->ErrorCode; + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) || + ((errorcode & (HAL_UART_ERROR_RTO | HAL_UART_ERROR_ORE)) != 0U)) + { + /* Blocking error : transfer is aborted + Set the UART state ready to be able to start again the process, + Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ + UART_EndRxTransfer(huart); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the UART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the UART DMA Rx request if enabled */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the UART DMA Rx channel */ + if (huart->hdmarx != NULL) + { + /* Set the UART DMA Abort callback : + will lead to call HAL_UART_ErrorCallback() at end of DMA abort procedure */ + huart->hdmarx->XferAbortCallback = UART_DMAAbortOnError; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) + { + /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ + huart->hdmarx->XferAbortCallback(huart->hdmarx); + } + } + else + { + /* Call user error callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Call user error callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + } + } + return; + + } /* End if some error occurs */ + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if ((huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + && ((isrflags & USART_ISR_IDLE) != 0U) + && ((cr1its & USART_ISR_IDLE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Check if DMA mode is enabled in UART */ + if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) + { + /* DMA mode enabled */ + /* Check received length : If all expected data are received, do nothing, + (DMA cplt callback will be called). + Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ + uint16_t nb_remaining_rx_data = (uint16_t) __HAL_DMA_GET_COUNTER(huart->hdmarx); + if ((nb_remaining_rx_data > 0U) + && (nb_remaining_rx_data < huart->RxXferSize)) + { + /* Reception is not complete */ + huart->RxXferCount = nb_remaining_rx_data; + + /* In Normal mode, end DMA xfer and HAL UART Rx process*/ + if (huart->hdmarx->Mode != DMA_LINKEDLIST_CIRCULAR) + { + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Disable the DMA transfer for the receiver request by resetting the DMAR bit + in the UART CR3 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + + /* Last bytes received, so no need as the abort is immediate */ + (void)HAL_DMA_Abort(huart->hdmarx); + } + + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Idle Event */ + huart->RxEventType = HAL_UART_RXEVENT_IDLE; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount)); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + else + { + /* If DMA is in Circular mode, Idle event is to be reported to user + even if occurring after a Transfer Complete event from DMA */ + if (nb_remaining_rx_data == huart->RxXferSize) + { + if (huart->hdmarx->Mode == DMA_LINKEDLIST_CIRCULAR) + { + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Idle Event */ + huart->RxEventType = HAL_UART_RXEVENT_IDLE; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + } + } + return; + } + else + { +#endif /* HAL_DMA_MODULE_ENABLED */ + /* DMA mode not enabled */ + /* Check received length : If all expected data are received, do nothing. + Otherwise, if at least one data has already been received, IDLE event is to be notified to user */ + uint16_t nb_rx_data = huart->RxXferSize - huart->RxXferCount; + if ((huart->RxXferCount > 0U) + && (nb_rx_data > 0U)) + { + /* Disable the UART Parity Error Interrupt and RXNE interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + + /* Disable the UART Error Interrupt:(Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Clear RxISR function pointer */ + huart->RxISR = NULL; + + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Idle Event */ + huart->RxEventType = HAL_UART_RXEVENT_IDLE; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxEventCallback(huart, nb_rx_data); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, nb_rx_data); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + return; +#if defined(HAL_DMA_MODULE_ENABLED) + } +#endif /* HAL_DMA_MODULE_ENABLED */ + } + + /* UART wakeup from Stop mode interrupt occurred ---------------------------*/ + if (((isrflags & USART_ISR_WUF) != 0U) && ((cr3its & USART_CR3_WUFIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_WUF); + + /* UART Rx state is not reset as a reception process might be ongoing. + If UART handle state fields need to be reset to READY, this could be done in Wakeup callback */ + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Wakeup Callback */ + huart->WakeupCallback(huart); +#else + /* Call legacy weak Wakeup Callback */ + HAL_UARTEx_WakeupCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + return; + } + + /* UART in mode Transmitter ------------------------------------------------*/ + if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) + && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) + || ((cr3its & USART_CR3_TXFTIE) != 0U))) + { + if (huart->TxISR != NULL) + { + huart->TxISR(huart); + } + return; + } + + /* UART in mode Transmitter (transmission end) -----------------------------*/ + if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) + { + UART_EndTransmit_IT(huart); + return; + } + + /* UART TX Fifo Empty occurred ----------------------------------------------*/ + if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) + { +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Fifo Empty Callback */ + huart->TxFifoEmptyCallback(huart); +#else + /* Call legacy weak Tx Fifo Empty Callback */ + HAL_UARTEx_TxFifoEmptyCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + return; + } + + /* UART RX Fifo Full occurred ----------------------------------------------*/ + if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) + { +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Fifo Full Callback */ + huart->RxFifoFullCallback(huart); +#else + /* Call legacy weak Rx Fifo Full Callback */ + HAL_UARTEx_RxFifoFullCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + return; + } +} + +/** + * @brief Tx Transfer completed callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_TxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_RxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Half Transfer completed callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_RxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief UART error callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief UART Abort Complete callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief UART Abort Complete callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_AbortTransmitCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_AbortTransmitCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief UART Abort Receive Complete callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_AbortReceiveCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Reception Event Callback (Rx event notification called after use of advanced reception service). + * @param huart UART handle + * @param Size Number of data available in application reception buffer (indicates a position in + * reception buffer until which, data are available) + * @retval None + */ +__weak void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + UNUSED(Size); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UARTEx_RxEventCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup UART_Exported_Functions_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_UART_ReceiverTimeout_Config() API allows to configure the receiver timeout value on the fly + (+) HAL_UART_EnableReceiverTimeout() API enables the receiver timeout feature + (+) HAL_UART_DisableReceiverTimeout() API disables the receiver timeout feature + (+) HAL_MultiProcessor_EnableMuteMode() API enables mute mode + (+) HAL_MultiProcessor_DisableMuteMode() API disables mute mode + (+) HAL_MultiProcessor_EnterMuteMode() API enters mute mode + (+) UART_SetConfig() API configures the UART peripheral + (+) UART_AdvFeatureConfig() API optionally configures the UART advanced features + (+) UART_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization + (+) HAL_HalfDuplex_EnableTransmitter() API disables receiver and enables transmitter + (+) HAL_HalfDuplex_EnableReceiver() API disables transmitter and enables receiver + (+) HAL_LIN_SendBreak() API transmits the break characters +@endverbatim + * @{ + */ + +/** + * @brief Update on the fly the receiver timeout value in RTOR register. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @param TimeoutValue receiver timeout value in number of baud blocks. The timeout + * value must be less or equal to 0x0FFFFFFFF. + * @retval None + */ +void HAL_UART_ReceiverTimeout_Config(UART_HandleTypeDef *huart, uint32_t TimeoutValue) +{ + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + assert_param(IS_UART_RECEIVER_TIMEOUT_VALUE(TimeoutValue)); + MODIFY_REG(huart->Instance->RTOR, USART_RTOR_RTO, TimeoutValue); + } +} + +/** + * @brief Enable the UART receiver timeout feature. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_EnableReceiverTimeout(UART_HandleTypeDef *huart) +{ + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + if (huart->gState == HAL_UART_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Set the USART RTOEN bit */ + SET_BIT(huart->Instance->CR2, USART_CR2_RTOEN); + + huart->gState = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Disable the UART receiver timeout feature. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_DisableReceiverTimeout(UART_HandleTypeDef *huart) +{ + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + if (huart->gState == HAL_UART_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Clear the USART RTOEN bit */ + CLEAR_BIT(huart->Instance->CR2, USART_CR2_RTOEN); + + huart->gState = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Enable UART in mute mode (does not mean UART enters mute mode; + * to enter mute mode, HAL_MultiProcessor_EnterMuteMode() API must be called). + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart) +{ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Enable USART mute mode by setting the MME bit in the CR1 register */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_MME); + + huart->gState = HAL_UART_STATE_READY; + + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Disable UART mute mode (does not mean the UART actually exits mute mode + * as it may not have been in mute mode at this very moment). + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart) +{ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Disable USART mute mode by clearing the MME bit in the CR1 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_MME); + + huart->gState = HAL_UART_STATE_READY; + + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Enter UART mute mode (means UART actually enters mute mode). + * @note To exit from mute mode, HAL_MultiProcessor_DisableMuteMode() API must be called. + * @param huart UART handle. + * @retval None + */ +void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) +{ + __HAL_UART_SEND_REQ(huart, UART_MUTE_MODE_REQUEST); +} + +/** + * @brief Enable the UART transmitter and disable the UART receiver. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) +{ + __HAL_LOCK(huart); + huart->gState = HAL_UART_STATE_BUSY; + + /* Clear TE and RE bits */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + + /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TE); + + huart->gState = HAL_UART_STATE_READY; + + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Enable the UART receiver and disable the UART transmitter. + * @param huart UART handle. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) +{ + __HAL_LOCK(huart); + huart->gState = HAL_UART_STATE_BUSY; + + /* Clear TE and RE bits */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + + /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RE); + + huart->gState = HAL_UART_STATE_READY; + + __HAL_UNLOCK(huart); + + return HAL_OK; +} + + +/** + * @brief Transmit break characters. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart) +{ + /* Check the parameters */ + assert_param(IS_UART_LIN_INSTANCE(huart->Instance)); + + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Send break characters */ + __HAL_UART_SEND_REQ(huart, UART_SENDBREAK_REQUEST); + + huart->gState = HAL_UART_STATE_READY; + + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup UART_Exported_Functions_Group4 Peripheral State and Error functions + * @brief UART Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Error functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to : + (+) Return the UART handle state. + (+) Return the UART handle error code + +@endverbatim + * @{ + */ + +/** + * @brief Return the UART handle state. + * @param huart Pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART. + * @retval HAL state + */ +HAL_UART_StateTypeDef HAL_UART_GetState(const UART_HandleTypeDef *huart) +{ + uint32_t temp1; + uint32_t temp2; + temp1 = huart->gState; + temp2 = huart->RxState; + + return (HAL_UART_StateTypeDef)(temp1 | temp2); +} + +/** + * @brief Return the UART handle 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(const UART_HandleTypeDef *huart) +{ + return huart->ErrorCode; +} +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup UART_Private_Functions UART Private Functions + * @{ + */ + +/** + * @brief Initialize the callbacks to their default values. + * @param huart UART handle. + * @retval none + */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) +void UART_InitCallbacksToDefault(UART_HandleTypeDef *huart) +{ + /* Init the UART Callback settings */ + huart->TxHalfCpltCallback = HAL_UART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + huart->TxCpltCallback = HAL_UART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + huart->RxHalfCpltCallback = HAL_UART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + huart->RxCpltCallback = HAL_UART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + huart->ErrorCallback = HAL_UART_ErrorCallback; /* Legacy weak ErrorCallback */ + huart->AbortCpltCallback = HAL_UART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + huart->AbortTransmitCpltCallback = HAL_UART_AbortTransmitCpltCallback; /* Legacy weak AbortTransmitCpltCallback */ + huart->AbortReceiveCpltCallback = HAL_UART_AbortReceiveCpltCallback; /* Legacy weak AbortReceiveCpltCallback */ + huart->WakeupCallback = HAL_UARTEx_WakeupCallback; /* Legacy weak WakeupCallback */ + huart->RxFifoFullCallback = HAL_UARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ + huart->TxFifoEmptyCallback = HAL_UARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ + huart->RxEventCallback = HAL_UARTEx_RxEventCallback; /* Legacy weak RxEventCallback */ + +} +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + +/** + * @brief Configure the UART peripheral. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart) +{ + uint32_t tmpreg; + uint16_t brrtemp; + UART_ClockSourceTypeDef clocksource; + uint32_t usartdiv; + HAL_StatusTypeDef ret = HAL_OK; + uint32_t lpuart_ker_ck_pres; + uint32_t pclk; + + /* Check the parameters */ + assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); + assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); + if (UART_INSTANCE_LOWPOWER(huart)) + { + assert_param(IS_LPUART_STOPBITS(huart->Init.StopBits)); + } + else + { + assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); + assert_param(IS_UART_ONE_BIT_SAMPLE(huart->Init.OneBitSampling)); + } + + 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)); + assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); + assert_param(IS_UART_PRESCALER(huart->Init.ClockPrescaler)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE, RE and OVER8 bits and configure + * the UART Word Length, Parity, Mode and oversampling: + * 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 ; + MODIFY_REG(huart->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR2 Configuration -----------------------*/ + /* Configure the UART Stop Bits: Set STOP[13:12] bits according + * to huart->Init.StopBits value */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* Configure + * - UART HardWare Flow Control: set CTSE and RTSE bits according + * to huart->Init.HwFlowCtl value + * - one-bit sampling method versus three samples' majority rule according + * to huart->Init.OneBitSampling (not applicable to LPUART) */ + tmpreg = (uint32_t)huart->Init.HwFlowCtl; + + if (!(UART_INSTANCE_LOWPOWER(huart))) + { + tmpreg |= huart->Init.OneBitSampling; + } + MODIFY_REG(huart->Instance->CR3, USART_CR3_FIELDS, tmpreg); + + /*-------------------------- USART PRESC Configuration -----------------------*/ + /* Configure + * - UART Clock Prescaler : set PRESCALER according to huart->Init.ClockPrescaler value */ + MODIFY_REG(huart->Instance->PRESC, USART_PRESC_PRESCALER, huart->Init.ClockPrescaler); + + /*-------------------------- USART BRR Configuration -----------------------*/ + UART_GETCLOCKSOURCE(huart, clocksource); + + /* Check LPUART instance */ + if (UART_INSTANCE_LOWPOWER(huart)) + { + /* Retrieve frequency clock */ + switch (clocksource) + { + case UART_CLOCKSOURCE_PLL2Q: + pclk = HAL_RCC_GetPLL2QFreq(); + break; + case UART_CLOCKSOURCE_PLL3Q: + pclk = HAL_RCC_GetPLL3QFreq(); + break; + case UART_CLOCKSOURCE_PCLK4: + pclk = HAL_RCC_GetPCLK4Freq(); + break; + case UART_CLOCKSOURCE_HSI: + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) + { + pclk = (uint32_t)(HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)); + } + else + { + pclk = (uint32_t) HSI_VALUE; + } + break; + case UART_CLOCKSOURCE_CSI: + pclk = (uint32_t) CSI_VALUE; + break; + case UART_CLOCKSOURCE_LSE: + pclk = (uint32_t) LSE_VALUE; + break; + default: + pclk = 0U; + ret = HAL_ERROR; + break; + } + + /* If proper clock source reported */ + if (pclk != 0U) + { + /* Compute clock after Prescaler */ + lpuart_ker_ck_pres = (pclk / UARTPrescTable[huart->Init.ClockPrescaler]); + + /* Ensure that Frequency clock is in the range [3 * baudrate, 4096 * baudrate] */ + if ((lpuart_ker_ck_pres < (3U * huart->Init.BaudRate)) || + (lpuart_ker_ck_pres > (4096U * huart->Init.BaudRate))) + { + ret = HAL_ERROR; + } + else + { + /* Check computed UsartDiv value is in allocated range + (it is forbidden to write values lower than 0x300 in the LPUART_BRR register) */ + usartdiv = (uint32_t)(UART_DIV_LPUART(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); + if ((usartdiv >= LPUART_BRR_MIN) && (usartdiv <= LPUART_BRR_MAX)) + { + huart->Instance->BRR = usartdiv; + } + else + { + ret = HAL_ERROR; + } + } /* if ( (lpuart_ker_ck_pres < (3 * huart->Init.BaudRate) ) || + (lpuart_ker_ck_pres > (4096 * huart->Init.BaudRate) )) */ + } /* if (pclk != 0) */ + } + /* Check UART Over Sampling to set Baud Rate Register */ + else if (huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + pclk = HAL_RCC_GetPCLK1Freq(); + break; + case UART_CLOCKSOURCE_PCLK2: + pclk = HAL_RCC_GetPCLK2Freq(); + break; + case UART_CLOCKSOURCE_PLL2Q: + pclk = HAL_RCC_GetPLL2QFreq(); + break; + case UART_CLOCKSOURCE_PLL3Q: + pclk = HAL_RCC_GetPLL3QFreq(); + break; + case UART_CLOCKSOURCE_HSI: + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) + { + pclk = (uint32_t)(HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)); + } + else + { + pclk = (uint32_t) HSI_VALUE; + } + break; + case UART_CLOCKSOURCE_CSI: + pclk = (uint32_t) CSI_VALUE; + break; + case UART_CLOCKSOURCE_LSE: + pclk = (uint32_t) LSE_VALUE; + break; + default: + pclk = 0U; + ret = HAL_ERROR; + break; + } + + /* USARTDIV must be greater than or equal to 0d16 */ + if (pclk != 0U) + { + usartdiv = (uint32_t)(UART_DIV_SAMPLING8(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); + if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) + { + brrtemp = (uint16_t)(usartdiv & 0xFFF0U); + brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U); + huart->Instance->BRR = brrtemp; + } + else + { + ret = HAL_ERROR; + } + } + } + else + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + pclk = HAL_RCC_GetPCLK1Freq(); + break; + case UART_CLOCKSOURCE_PCLK2: + pclk = HAL_RCC_GetPCLK2Freq(); + break; + case UART_CLOCKSOURCE_PLL2Q: + pclk = HAL_RCC_GetPLL2QFreq(); + break; + case UART_CLOCKSOURCE_PLL3Q: + pclk = HAL_RCC_GetPLL3QFreq(); + break; + case UART_CLOCKSOURCE_HSI: + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) + { + pclk = (uint32_t)(HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)); + } + else + { + pclk = (uint32_t) HSI_VALUE; + } + break; + case UART_CLOCKSOURCE_CSI: + pclk = (uint32_t) CSI_VALUE; + break; + case UART_CLOCKSOURCE_LSE: + pclk = (uint32_t) LSE_VALUE; + break; + default: + pclk = 0U; + ret = HAL_ERROR; + break; + } + + if (pclk != 0U) + { + /* USARTDIV must be greater than or equal to 0d16 */ + usartdiv = (uint32_t)(UART_DIV_SAMPLING16(pclk, huart->Init.BaudRate, huart->Init.ClockPrescaler)); + if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) + { + huart->Instance->BRR = (uint16_t)usartdiv; + } + else + { + ret = HAL_ERROR; + } + } + } + + /* Initialize the number of data to process during RX/TX ISR execution */ + huart->NbTxDataToProcess = 1; + huart->NbRxDataToProcess = 1; + + /* Clear ISR function pointers */ + huart->RxISR = NULL; + huart->TxISR = NULL; + + return ret; +} + +/** + * @brief Configure the UART peripheral advanced features. + * @param huart UART handle. + * @retval None + */ +void UART_AdvFeatureConfig(UART_HandleTypeDef *huart) +{ + /* Check whether the set of advanced features to configure is properly set */ + assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit)); + + /* if required, configure RX/TX pins swap */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_SWAP_INIT)) + { + assert_param(IS_UART_ADVFEATURE_SWAP(huart->AdvancedInit.Swap)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_SWAP, huart->AdvancedInit.Swap); + } + + /* if required, configure TX pin active level inversion */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_TXINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_TXINV(huart->AdvancedInit.TxPinLevelInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_TXINV, huart->AdvancedInit.TxPinLevelInvert); + } + + /* if required, configure RX pin active level inversion */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_RXINV(huart->AdvancedInit.RxPinLevelInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_RXINV, huart->AdvancedInit.RxPinLevelInvert); + } + + /* if required, configure data inversion */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DATAINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_DATAINV(huart->AdvancedInit.DataInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_DATAINV, huart->AdvancedInit.DataInvert); + } + + /* if required, configure RX overrun detection disabling */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT)) + { + assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable)); + MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable); + } + +#if defined(HAL_DMA_MODULE_ENABLED) + /* if required, configure DMA disabling on reception error */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT)) + { + assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError)); + MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError); + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* if required, configure auto Baud rate detection scheme */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT)) + { + assert_param(IS_USART_AUTOBAUDRATE_DETECTION_INSTANCE(huart->Instance)); + assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(huart->AdvancedInit.AutoBaudRateEnable)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_ABREN, huart->AdvancedInit.AutoBaudRateEnable); + /* set auto Baudrate detection parameters if detection is enabled */ + if (huart->AdvancedInit.AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE) + { + assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(huart->AdvancedInit.AutoBaudRateMode)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_ABRMODE, huart->AdvancedInit.AutoBaudRateMode); + } + } + + /* if required, configure MSB first on communication line */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_MSBFIRST_INIT)) + { + assert_param(IS_UART_ADVFEATURE_MSBFIRST(huart->AdvancedInit.MSBFirst)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_MSBFIRST, huart->AdvancedInit.MSBFirst); + } +} + +/** + * @brief Check the UART Idle State. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart) +{ + uint32_t tickstart; + + /* Initialize the UART ErrorCode */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check if the Transmitter is enabled */ + if ((huart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_TEACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) + { + /* Disable TXE interrupt for the interrupt process */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE)); + + huart->gState = HAL_UART_STATE_READY; + + __HAL_UNLOCK(huart); + + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + + /* Check if the Receiver is enabled */ + if ((huart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) + { + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) + interrupts for the interrupt process */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + + huart->RxState = HAL_UART_STATE_READY; + + __HAL_UNLOCK(huart); + + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + + /* Initialize the UART State */ + huart->gState = HAL_UART_STATE_READY; + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + huart->RxEventType = HAL_UART_RXEVENT_TC; + + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief This function handles UART Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param huart UART handle. + * @param Flag Specifies the UART flag to check + * @param Status The actual Flag status (SET or RESET) + * @param Tickstart Tick start value + * @param Timeout Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__HAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + + return HAL_TIMEOUT; + } + + if ((READ_BIT(huart->Instance->CR1, USART_CR1_RE) != 0U) && (Flag != UART_FLAG_TXE) && (Flag != UART_FLAG_TC)) + { + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) == SET) + { + /* Clear Overrun Error flag*/ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF); + + /* Blocking error : transfer is aborted + Set the UART state ready to be able to start again the process, + Disable Rx Interrupts if ongoing */ + UART_EndRxTransfer(huart); + + huart->ErrorCode = HAL_UART_ERROR_ORE; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_ERROR; + } + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RTOF) == SET) + { + /* Clear Receiver Timeout flag*/ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_RTOF); + + /* Blocking error : transfer is aborted + Set the UART state ready to be able to start again the process, + Disable Rx Interrupts if ongoing */ + UART_EndRxTransfer(huart); + + huart->ErrorCode = HAL_UART_ERROR_RTO; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief Start Receive operation in interrupt mode. + * @note This function could be called by all HAL UART API providing reception in Interrupt mode. + * @note When calling this function, parameters validity is considered as already checked, + * i.e. Rx State, buffer address, ... + * UART Handle is assumed as Locked. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef UART_Start_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + huart->RxXferCount = Size; + huart->RxISR = NULL; + + /* Computation of UART mask to apply to RDR register */ + UART_MASK_COMPUTATION(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->RxState = HAL_UART_STATE_BUSY_RX; + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Configure Rx interrupt processing */ + if ((huart->FifoMode == UART_FIFOMODE_ENABLE) && (Size >= huart->NbRxDataToProcess)) + { + /* Set the Rx ISR function pointer according to the data word length */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + huart->RxISR = UART_RxISR_16BIT_FIFOEN; + } + else + { + huart->RxISR = UART_RxISR_8BIT_FIFOEN; + } + + /* Enable the UART Parity Error interrupt and RX FIFO Threshold interrupt */ + if (huart->Init.Parity != UART_PARITY_NONE) + { + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); + } + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); + } + else + { + /* Set the Rx ISR function pointer according to the data word length */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + huart->RxISR = UART_RxISR_16BIT; + } + else + { + huart->RxISR = UART_RxISR_8BIT; + } + + /* Enable the UART Parity Error interrupt and Data Register Not Empty interrupt */ + if (huart->Init.Parity != UART_PARITY_NONE) + { + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); + } + else + { + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + } + return HAL_OK; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Start Receive operation in DMA mode. + * @note This function could be called by all HAL UART API providing reception in DMA mode. + * @note When calling this function, parameters validity is considered as already checked, + * i.e. Rx State, buffer address, ... + * UART Handle is assumed as Locked. + * @param huart UART handle. + * @param pData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef UART_Start_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + uint16_t nbByte = Size; + + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->RxState = HAL_UART_STATE_BUSY_RX; + + if (huart->hdmarx != NULL) + { + /* 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; + + /* Set the DMA abort callback */ + huart->hdmarx->XferAbortCallback = NULL; + + /* In case of 9bits/No Parity transfer, pData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size * 2 */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + /* Check linked list mode */ + if ((huart->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((huart->hdmarx->LinkedListQueue != NULL) && (huart->hdmarx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + huart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + huart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)&huart->Instance->RDR; + + /* Set DMA destination address */ + huart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)huart->pRxBuffPtr; + + /* Enable the UART receive DMA channel */ + status = HAL_DMAEx_List_Start_IT(huart->hdmarx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the UART receive DMA channel */ + status = HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->RDR, (uint32_t)huart->pRxBuffPtr, nbByte); + } + + if (status != HAL_OK) + { + /* Set error code to DMA */ + huart->ErrorCode = HAL_UART_ERROR_DMA; + + /* Restore huart->RxState to ready */ + huart->RxState = HAL_UART_STATE_READY; + + return HAL_ERROR; + } + } + + /* Enable the UART Parity Error Interrupt */ + if (huart->Init.Parity != UART_PARITY_NONE) + { + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); + } + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CR3 register */ + ATOMIC_SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + return HAL_OK; +} + + +/** + * @brief End ongoing Tx transfer on UART peripheral (following error detection or Transmit completion). + * @param huart UART handle. + * @retval None + */ +static void UART_EndTxTransfer(UART_HandleTypeDef *huart) +{ + /* Disable TXEIE, TCIE, TXFT interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_TXFTIE)); + + /* At end of Tx process, restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + + +/** + * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). + * @param huart UART handle. + * @retval None + */ +static void UART_EndRxTransfer(UART_HandleTypeDef *huart) +{ + /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* In case of reception waiting for IDLE event, disable also the IDLE IE interrupt source */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + } + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Reset RxIsr function pointer */ + huart->RxISR = NULL; +} + + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @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 *)(hdma->Parent); + + /* Check if DMA in circular mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + huart->TxXferCount = 0U; + + /* Disable the DMA transfer for transmit request by resetting the DMAT bit + in the UART CR3 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); + + /* Enable the UART Transmit Complete Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); + } + /* DMA Circular mode */ + else + { +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Tx complete callback*/ + huart->TxCpltCallback(huart); +#else + /*Call legacy weak Tx complete callback*/ + HAL_UART_TxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } +} + +/** + * @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 *)(hdma->Parent); + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Tx Half complete callback*/ + huart->TxHalfCpltCallback(huart); +#else + /*Call legacy weak Tx Half complete callback*/ + HAL_UART_TxHalfCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @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 *)(hdma->Parent); + + /* Check if DMA in circular mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + huart->RxXferCount = 0U; + + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Disable the DMA transfer for the receiver request by resetting the DMAR bit + in the UART CR3 register */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); + + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + /* If Reception till IDLE event has been selected, Disable IDLE Interrupt */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + } + } + + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Transfer Complete */ + huart->RxEventType = HAL_UART_RXEVENT_TC; + + /* Check current reception Mode : + If Reception till IDLE event has been selected : use Rx Event callback */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + else + { + /* In other cases : use Rx Complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + HAL_UART_RxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } +} + +/** + * @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 *)(hdma->Parent); + + /* Initialize type of RxEvent that correspond to RxEvent callback execution; + In this case, Rx Event type is Half Transfer */ + huart->RxEventType = HAL_UART_RXEVENT_HT; + + /* Check current reception Mode : + If Reception till IDLE event has been selected : use Rx Event callback */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize / 2U); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize / 2U); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + else + { + /* In other cases : use Rx Half Complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Half complete callback*/ + huart->RxHalfCpltCallback(huart); +#else + /*Call legacy weak Rx Half complete callback*/ + HAL_UART_RxHalfCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } +} + +/** + * @brief DMA UART communication error callback. + * @param hdma DMA handle. + * @retval None + */ +static void UART_DMAError(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); + + const HAL_UART_StateTypeDef gstate = huart->gState; + const HAL_UART_StateTypeDef rxstate = huart->RxState; + + /* Stop UART DMA Tx request if ongoing */ + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) && + (gstate == HAL_UART_STATE_BUSY_TX)) + { + huart->TxXferCount = 0U; + UART_EndTxTransfer(huart); + } + + /* Stop UART DMA Rx request if ongoing */ + if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) && + (rxstate == HAL_UART_STATE_BUSY_RX)) + { + huart->RxXferCount = 0U; + UART_EndRxTransfer(huart); + } + + huart->ErrorCode |= HAL_UART_ERROR_DMA; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART communication abort callback, when initiated by HAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); + huart->RxXferCount = 0U; + huart->TxXferCount = 0U; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); + + huart->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (huart->hdmarx != NULL) + { + if (huart->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + huart->TxXferCount = 0U; + huart->RxXferCount = 0U; + + /* Reset errorCode */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Flush the whole TX FIFO (if needed) */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); + } + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = HAL_UART_STATE_READY; + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Call user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + huart->AbortCpltCallback(huart); +#else + /* Call legacy weak Abort complete callback */ + HAL_UART_AbortCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + + +/** + * @brief DMA UART Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); + + huart->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (huart->hdmatx != NULL) + { + if (huart->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + huart->TxXferCount = 0U; + huart->RxXferCount = 0U; + + /* Reset errorCode */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Discard the received data */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + + /* Restore huart->gState and huart->RxState to Ready */ + huart->gState = HAL_UART_STATE_READY; + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Call user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort complete callback */ + huart->AbortCpltCallback(huart); +#else + /* Call legacy weak Abort complete callback */ + HAL_UART_AbortCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + + +/** + * @brief DMA UART Tx communication abort callback, when initiated by user by a call to + * HAL_UART_AbortTransmit_IT API (Abort only Tx transfer) + * (This callback is executed at end of DMA Tx Abort procedure following user abort request, + * and leads to user Tx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)(hdma->Parent); + + huart->TxXferCount = 0U; + + /* Flush the whole TX FIFO (if needed) */ + if (huart->FifoMode == UART_FIFOMODE_ENABLE) + { + __HAL_UART_SEND_REQ(huart, UART_TXDATA_FLUSH_REQUEST); + } + + /* Restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Transmit Complete Callback */ + huart->AbortTransmitCpltCallback(huart); +#else + /* Call legacy weak Abort Transmit Complete Callback */ + HAL_UART_AbortTransmitCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA UART Rx communication abort callback, when initiated by user by a call to + * HAL_UART_AbortReceive_IT API (Abort only Rx transfer) + * (This callback is executed at end of DMA Rx Abort procedure following user abort request, + * and leads to user Rx Abort Complete callback execution). + * @param hdma DMA handle. + * @retval None + */ +static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef *huart = (UART_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; + + huart->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF | UART_CLEAR_NEF | UART_CLEAR_PEF | UART_CLEAR_FEF); + + /* Discard the received data */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + + /* Restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Call user Abort complete callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Receive Complete Callback */ + huart->AbortReceiveCpltCallback(huart); +#else + /* Call legacy weak Abort Receive Complete Callback */ + HAL_UART_AbortReceiveCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief TX interrupt handler for 7 or 8 bits data word length . + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Transmit_IT(). + * @param huart UART handle. + * @retval None + */ +static void UART_TxISR_8BIT(UART_HandleTypeDef *huart) +{ + /* Check that a Tx process is ongoing */ + if (huart->gState == HAL_UART_STATE_BUSY_TX) + { + if (huart->TxXferCount == 0U) + { + /* Disable the UART Transmit Data Register Empty Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + + /* Enable the UART Transmit Complete Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); + } + else + { + huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr & (uint8_t)0xFF); + huart->pTxBuffPtr++; + huart->TxXferCount--; + } + } +} + +/** + * @brief TX interrupt handler for 9 bits data word length. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Transmit_IT(). + * @param huart UART handle. + * @retval None + */ +static void UART_TxISR_16BIT(UART_HandleTypeDef *huart) +{ + const uint16_t *tmp; + + /* Check that a Tx process is ongoing */ + if (huart->gState == HAL_UART_STATE_BUSY_TX) + { + if (huart->TxXferCount == 0U) + { + /* Disable the UART Transmit Data Register Empty Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + + /* Enable the UART Transmit Complete Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); + } + else + { + tmp = (const uint16_t *) huart->pTxBuffPtr; + huart->Instance->TDR = (((uint32_t)(*tmp)) & 0x01FFUL); + huart->pTxBuffPtr += 2U; + huart->TxXferCount--; + } + } +} + +/** + * @brief TX interrupt handler for 7 or 8 bits data word length and FIFO mode is enabled. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Transmit_IT(). + * @param huart UART handle. + * @retval None + */ +static void UART_TxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) +{ + uint16_t nb_tx_data; + + /* Check that a Tx process is ongoing */ + if (huart->gState == HAL_UART_STATE_BUSY_TX) + { + for (nb_tx_data = huart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) + { + if (huart->TxXferCount == 0U) + { + /* Disable the TX FIFO threshold interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); + + /* Enable the UART Transmit Complete Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); + + break; /* force exit loop */ + } + else if (READ_BIT(huart->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) + { + huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr & (uint8_t)0xFF); + huart->pTxBuffPtr++; + huart->TxXferCount--; + } + else + { + /* Nothing to do */ + } + } + } +} + +/** + * @brief TX interrupt handler for 9 bits data word length and FIFO mode is enabled. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Transmit_IT(). + * @param huart UART handle. + * @retval None + */ +static void UART_TxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) +{ + const uint16_t *tmp; + uint16_t nb_tx_data; + + /* Check that a Tx process is ongoing */ + if (huart->gState == HAL_UART_STATE_BUSY_TX) + { + for (nb_tx_data = huart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) + { + if (huart->TxXferCount == 0U) + { + /* Disable the TX FIFO threshold interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_TXFTIE); + + /* Enable the UART Transmit Complete Interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); + + break; /* force exit loop */ + } + else if (READ_BIT(huart->Instance->ISR, USART_ISR_TXE_TXFNF) != 0U) + { + tmp = (const uint16_t *) huart->pTxBuffPtr; + huart->Instance->TDR = (((uint32_t)(*tmp)) & 0x01FFUL); + huart->pTxBuffPtr += 2U; + huart->TxXferCount--; + } + else + { + /* Nothing to do */ + } + } + } +} + +/** + * @brief Wrap up transmission in non-blocking mode. + * @param huart pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval None + */ +static void UART_EndTransmit_IT(UART_HandleTypeDef *huart) +{ + /* Disable the UART Transmit Complete Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_TCIE); + + /* Tx process is ended, restore huart->gState to Ready */ + huart->gState = HAL_UART_STATE_READY; + + /* Cleat TxISR function pointer */ + huart->TxISR = NULL; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Tx complete callback*/ + huart->TxCpltCallback(huart); +#else + /*Call legacy weak Tx complete callback*/ + HAL_UART_TxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ +} + +/** + * @brief RX interrupt handler for 7 or 8 bits data word length . + * @param huart UART handle. + * @retval None + */ +static void UART_RxISR_8BIT(UART_HandleTypeDef *huart) +{ + uint16_t uhMask = huart->Mask; + uint16_t uhdata; + + /* Check that a Rx process is ongoing */ + if (huart->RxState == HAL_UART_STATE_BUSY_RX) + { + uhdata = (uint16_t) READ_REG(huart->Instance->RDR); + *huart->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); + huart->pRxBuffPtr++; + huart->RxXferCount--; + + if (huart->RxXferCount == 0U) + { + /* Disable the UART Parity Error Interrupt and RXNE interrupts */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + /* Clear RxISR function pointer */ + huart->RxISR = NULL; + + /* Initialize type of RxEvent to Transfer Complete */ + huart->RxEventType = HAL_UART_RXEVENT_TC; + + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + /* Check that USART RTOEN bit is set */ + if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) + { + /* Enable the UART Receiver Timeout Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); + } + } + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + /* Set reception type to Standard */ + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Disable IDLE interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) + { + /* Clear IDLE Flag */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + } + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + else + { + /* Standard reception API called */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + HAL_UART_RxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @brief RX interrupt handler for 9 bits data word length . + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Receive_IT() + * @param huart UART handle. + * @retval None + */ +static void UART_RxISR_16BIT(UART_HandleTypeDef *huart) +{ + uint16_t *tmp; + uint16_t uhMask = huart->Mask; + uint16_t uhdata; + + /* Check that a Rx process is ongoing */ + if (huart->RxState == HAL_UART_STATE_BUSY_RX) + { + uhdata = (uint16_t) READ_REG(huart->Instance->RDR); + tmp = (uint16_t *) huart->pRxBuffPtr ; + *tmp = (uint16_t)(uhdata & uhMask); + huart->pRxBuffPtr += 2U; + huart->RxXferCount--; + + if (huart->RxXferCount == 0U) + { + /* Disable the UART Parity Error Interrupt and RXNE interrupt*/ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + /* Clear RxISR function pointer */ + huart->RxISR = NULL; + + /* Initialize type of RxEvent to Transfer Complete */ + huart->RxEventType = HAL_UART_RXEVENT_TC; + + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + /* Check that USART RTOEN bit is set */ + if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) + { + /* Enable the UART Receiver Timeout Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); + } + } + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + /* Set reception type to Standard */ + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Disable IDLE interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) + { + /* Clear IDLE Flag */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + } + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + else + { + /* Standard reception API called */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + HAL_UART_RxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @brief RX interrupt handler for 7 or 8 bits data word length and FIFO mode is enabled. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Receive_IT() + * @param huart UART handle. + * @retval None + */ +static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) +{ + uint16_t uhMask = huart->Mask; + uint16_t uhdata; + uint16_t nb_rx_data; + uint16_t rxdatacount; + uint32_t isrflags = READ_REG(huart->Instance->ISR); + uint32_t cr1its = READ_REG(huart->Instance->CR1); + uint32_t cr3its = READ_REG(huart->Instance->CR3); + + /* Check that a Rx process is ongoing */ + if (huart->RxState == HAL_UART_STATE_BUSY_RX) + { + nb_rx_data = huart->NbRxDataToProcess; + while ((nb_rx_data > 0U) && ((isrflags & USART_ISR_RXNE_RXFNE) != 0U)) + { + uhdata = (uint16_t) READ_REG(huart->Instance->RDR); + *huart->pRxBuffPtr = (uint8_t)(uhdata & (uint8_t)uhMask); + huart->pRxBuffPtr++; + huart->RxXferCount--; + isrflags = READ_REG(huart->Instance->ISR); + + /* If some non blocking errors occurred */ + if ((isrflags & (USART_ISR_PE | USART_ISR_FE | USART_ISR_NE)) != 0U) + { + /* UART parity error interrupt occurred -------------------------------------*/ + if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); + + huart->ErrorCode |= HAL_UART_ERROR_PE; + } + + /* UART frame error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); + + huart->ErrorCode |= HAL_UART_ERROR_FE; + } + + /* UART noise error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); + + huart->ErrorCode |= HAL_UART_ERROR_NE; + } + + /* Call UART Error Call back function if need be ----------------------------*/ + if (huart->ErrorCode != HAL_UART_ERROR_NONE) + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + } + } + + if (huart->RxXferCount == 0U) + { + /* Disable the UART Parity Error Interrupt and RXFT interrupt*/ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) + and RX FIFO Threshold interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + /* Clear RxISR function pointer */ + huart->RxISR = NULL; + + /* Initialize type of RxEvent to Transfer Complete */ + huart->RxEventType = HAL_UART_RXEVENT_TC; + + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + /* Check that USART RTOEN bit is set */ + if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) + { + /* Enable the UART Receiver Timeout Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); + } + } + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + /* Set reception type to Standard */ + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Disable IDLE interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) + { + /* Clear IDLE Flag */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + } + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + else + { + /* Standard reception API called */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + HAL_UART_RxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + break; + } + } + + /* When remaining number of bytes to receive is less than the RX FIFO + threshold, next incoming frames are processed as if FIFO mode was + disabled (i.e. one interrupt per received frame). + */ + rxdatacount = huart->RxXferCount; + if ((rxdatacount != 0U) && (rxdatacount < huart->NbRxDataToProcess)) + { + /* Disable the UART RXFT interrupt*/ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); + + /* Update the RxISR function pointer */ + huart->RxISR = UART_RxISR_8BIT; + + /* Enable the UART Data Register Not Empty interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @brief RX interrupt handler for 9 bits data word length and FIFO mode is enabled. + * @note Function is called under interruption only, once + * interruptions have been enabled by HAL_UART_Receive_IT() + * @param huart UART handle. + * @retval None + */ +static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) +{ + uint16_t *tmp; + uint16_t uhMask = huart->Mask; + uint16_t uhdata; + uint16_t nb_rx_data; + uint16_t rxdatacount; + uint32_t isrflags = READ_REG(huart->Instance->ISR); + uint32_t cr1its = READ_REG(huart->Instance->CR1); + uint32_t cr3its = READ_REG(huart->Instance->CR3); + + /* Check that a Rx process is ongoing */ + if (huart->RxState == HAL_UART_STATE_BUSY_RX) + { + nb_rx_data = huart->NbRxDataToProcess; + while ((nb_rx_data > 0U) && ((isrflags & USART_ISR_RXNE_RXFNE) != 0U)) + { + uhdata = (uint16_t) READ_REG(huart->Instance->RDR); + tmp = (uint16_t *) huart->pRxBuffPtr ; + *tmp = (uint16_t)(uhdata & uhMask); + huart->pRxBuffPtr += 2U; + huart->RxXferCount--; + isrflags = READ_REG(huart->Instance->ISR); + + /* If some non blocking errors occurred */ + if ((isrflags & (USART_ISR_PE | USART_ISR_FE | USART_ISR_NE)) != 0U) + { + /* UART parity error interrupt occurred -------------------------------------*/ + if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF); + + huart->ErrorCode |= HAL_UART_ERROR_PE; + } + + /* UART frame error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF); + + huart->ErrorCode |= HAL_UART_ERROR_FE; + } + + /* UART noise error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF); + + huart->ErrorCode |= HAL_UART_ERROR_NE; + } + + /* Call UART Error Call back function if need be ----------------------------*/ + if (huart->ErrorCode != HAL_UART_ERROR_NONE) + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered error callback*/ + huart->ErrorCallback(huart); +#else + /*Call legacy weak error callback*/ + HAL_UART_ErrorCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + } + } + + if (huart->RxXferCount == 0U) + { + /* Disable the UART Parity Error Interrupt and RXFT interrupt*/ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) + and RX FIFO Threshold interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Rx process is completed, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + /* Clear RxISR function pointer */ + huart->RxISR = NULL; + + /* Initialize type of RxEvent to Transfer Complete */ + huart->RxEventType = HAL_UART_RXEVENT_TC; + + if (!(IS_LPUART_INSTANCE(huart->Instance))) + { + /* Check that USART RTOEN bit is set */ + if (READ_BIT(huart->Instance->CR2, USART_CR2_RTOEN) != 0U) + { + /* Enable the UART Receiver Timeout Interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_RTOIE); + } + } + + /* Check current reception Mode : + If Reception till IDLE event has been selected : */ + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + /* Set reception type to Standard */ + huart->ReceptionType = HAL_UART_RECEPTION_STANDARD; + + /* Disable IDLE interrupt */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == SET) + { + /* Clear IDLE Flag */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + } + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx Event callback*/ + huart->RxEventCallback(huart, huart->RxXferSize); +#else + /*Call legacy weak Rx Event callback*/ + HAL_UARTEx_RxEventCallback(huart, huart->RxXferSize); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + else + { + /* Standard reception API called */ +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + /*Call registered Rx complete callback*/ + huart->RxCpltCallback(huart); +#else + /*Call legacy weak Rx complete callback*/ + HAL_UART_RxCpltCallback(huart); +#endif /* USE_HAL_UART_REGISTER_CALLBACKS */ + } + break; + } + } + + /* When remaining number of bytes to receive is less than the RX FIFO + threshold, next incoming frames are processed as if FIFO mode was + disabled (i.e. one interrupt per received frame). + */ + rxdatacount = huart->RxXferCount; + if ((rxdatacount != 0U) && (rxdatacount < huart->NbRxDataToProcess)) + { + /* Disable the UART RXFT interrupt*/ + ATOMIC_CLEAR_BIT(huart->Instance->CR3, USART_CR3_RXFTIE); + + /* Update the RxISR function pointer */ + huart->RxISR = UART_RxISR_16BIT; + + /* Enable the UART Data Register Not Empty interrupt */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @} + */ + +#endif /* HAL_UART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart_ex.c index d6422ceaf..5307b9bd7 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_uart_ex.c @@ -1,1044 +1,1043 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_uart_ex.c - * @author MCD Application Team - * @brief Extended UART HAL module driver. - * This file provides firmware functions to manage the following extended - * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). - * + Initialization and de-initialization functions - * + Peripheral Control functions - * - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### UART peripheral extended features ##### - ============================================================================== - - (#) Declare a UART_HandleTypeDef handle structure. - - (#) For the UART RS485 Driver Enable mode, initialize the UART registers - by calling the HAL_RS485Ex_Init() API. - - (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. - - -@- When UART operates in FIFO mode, FIFO mode must be enabled prior - starting RX/TX transfers. Also RX/TX FIFO thresholds must be - configured prior starting RX/TX transfers. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup UARTEx UARTEx - * @brief UART Extended HAL module driver - * @{ - */ - -#ifdef HAL_UART_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup UARTEX_Private_Constants UARTEx Private Constants - * @{ - */ -/* UART RX FIFO depth */ -#define RX_FIFO_DEPTH 16U - -/* UART TX FIFO depth */ -#define TX_FIFO_DEPTH 16U -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup UARTEx_Private_Functions UARTEx Private Functions - * @{ - */ -static void UARTEx_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); -static void UARTEx_SetNbDataToProcess(UART_HandleTypeDef *huart); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup UARTEx_Exported_Functions UARTEx Exported Functions - * @{ - */ - -/** @defgroup UARTEx_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Extended 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 the parameters below 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. - (++) Hardware flow control - (++) Receiver/transmitter modes - (++) Over Sampling Method - (++) One-Bit Sampling Method - (+) For the asynchronous mode, the following advanced features can be configured as well: - (++) TX and/or RX pin level inversion - (++) data logical level inversion - (++) RX and TX pins swap - (++) RX overrun detection disabling - (++) DMA disabling on RX error - (++) MSB first on communication line - (++) auto Baud rate detection - [..] - The HAL_RS485Ex_Init() API follows the UART RS485 mode configuration - procedures (details for the procedures are available in reference manual). - -@endverbatim - - Depending on the frame length defined by the M1 and M0 bits (7-bit, - 8-bit or 9-bit), the possible UART formats are listed in the - following table. - - Table 1. UART frame format. - +-----------------------------------------------------------------------+ - | M1 bit | M0 bit | PCE bit | UART frame | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 0 | | SB | 8 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 0 | | SB | 9 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 0 | | SB | 7 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | - +-----------------------------------------------------------------------+ - - * @{ - */ - -/** - * @brief Initialize the RS485 Driver enable feature according to the specified - * parameters in the UART_InitTypeDef and creates the associated handle. - * @param huart UART handle. - * @param Polarity Select the driver enable polarity. - * This parameter can be one of the following values: - * @arg @ref UART_DE_POLARITY_HIGH DE signal is active high - * @arg @ref UART_DE_POLARITY_LOW DE signal is active low - * @param AssertionTime Driver Enable assertion time: - * 5-bit value defining the time between the activation of the DE (Driver Enable) - * signal and the beginning of the start bit. It is expressed in sample time - * units (1/8 or 1/16 bit time, depending on the oversampling rate) - * @param DeassertionTime Driver Enable deassertion time: - * 5-bit value defining the time between the end of the last stop bit, in a - * transmitted message, and the de-activation of the DE (Driver Enable) signal. - * It is expressed in sample time units (1/8 or 1/16 bit time, depending on the - * oversampling rate). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t Polarity, uint32_t AssertionTime, - uint32_t DeassertionTime) -{ - uint32_t temp; - - /* Check the UART handle allocation */ - if (huart == NULL) - { - return HAL_ERROR; - } - /* Check the Driver Enable UART instance */ - assert_param(IS_UART_DRIVER_ENABLE_INSTANCE(huart->Instance)); - - /* Check the Driver Enable polarity */ - assert_param(IS_UART_DE_POLARITY(Polarity)); - - /* Check the Driver Enable assertion time */ - assert_param(IS_UART_ASSERTIONTIME(AssertionTime)); - - /* Check the Driver Enable deassertion time */ - assert_param(IS_UART_DEASSERTIONTIME(DeassertionTime)); - - if (huart->gState == HAL_UART_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - huart->Lock = HAL_UNLOCKED; - -#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) - UART_InitCallbacksToDefault(huart); - - if (huart->MspInitCallback == NULL) - { - huart->MspInitCallback = HAL_UART_MspInit; - } - - /* Init the low level hardware */ - huart->MspInitCallback(huart); -#else - /* Init the low level hardware : GPIO, CLOCK, CORTEX */ - HAL_UART_MspInit(huart); -#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ - } - - huart->gState = HAL_UART_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_UART_DISABLE(huart); - - /* Perform advanced settings configuration */ - /* For some items, configuration requires to be done prior TE and RE bits are set */ - if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) - { - UART_AdvFeatureConfig(huart); - } - - /* Set the UART Communication parameters */ - if (UART_SetConfig(huart) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* Enable the Driver Enable mode by setting the DEM bit in the CR3 register */ - SET_BIT(huart->Instance->CR3, USART_CR3_DEM); - - /* Set the Driver Enable polarity */ - MODIFY_REG(huart->Instance->CR3, USART_CR3_DEP, Polarity); - - /* Set the Driver Enable assertion and deassertion times */ - temp = (AssertionTime << UART_CR1_DEAT_ADDRESS_LSB_POS); - temp |= (DeassertionTime << UART_CR1_DEDT_ADDRESS_LSB_POS); - MODIFY_REG(huart->Instance->CR1, (USART_CR1_DEDT | USART_CR1_DEAT), temp); - - /* Enable the Peripheral */ - __HAL_UART_ENABLE(huart); - - /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ - return (UART_CheckIdleState(huart)); -} - -/** - * @} - */ - -/** @defgroup UARTEx_Exported_Functions_Group2 IO operation functions - * @brief Extended functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - This subsection provides a set of Wakeup and FIFO mode related callback functions. - - (#) Wakeup from Stop mode Callback: - (+) HAL_UARTEx_WakeupCallback() - - (#) TX/RX Fifos Callbacks: - (+) HAL_UARTEx_RxFifoFullCallback() - (+) HAL_UARTEx_TxFifoEmptyCallback() - -@endverbatim - * @{ - */ - -/** - * @brief UART wakeup from Stop mode callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UARTEx_WakeupCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UARTEx_WakeupCallback can be implemented in the user file. - */ -} - -/** - * @brief UART RX Fifo full callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UARTEx_RxFifoFullCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UARTEx_RxFifoFullCallback can be implemented in the user file. - */ -} - -/** - * @brief UART TX Fifo empty callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UARTEx_TxFifoEmptyCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UARTEx_TxFifoEmptyCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup UARTEx_Exported_Functions_Group3 Peripheral Control functions - * @brief Extended Peripheral Control functions - * -@verbatim - =============================================================================== - ##### Peripheral Control functions ##### - =============================================================================== - [..] This section provides the following functions: - (+) HAL_MultiProcessorEx_AddressLength_Set() API optionally sets the UART node address - detection length to more than 4 bits for multiprocessor address mark wake up. - (+) HAL_UARTEx_StopModeWakeUpSourceConfig() API defines the wake-up from stop mode - trigger: address match, Start Bit detection or RXNE bit status. - (+) HAL_UARTEx_EnableStopMode() API enables the UART to wake up the MCU from stop mode - (+) HAL_UARTEx_DisableStopMode() API disables the above functionality - (+) HAL_UARTEx_EnableFifoMode() API enables the FIFO mode - (+) HAL_UARTEx_DisableFifoMode() API disables the FIFO mode - (+) HAL_UARTEx_SetTxFifoThreshold() API sets the TX FIFO threshold - (+) HAL_UARTEx_SetRxFifoThreshold() API sets the RX FIFO threshold - - [..] This subsection also provides a set of additional functions providing enhanced reception - services to user. (For example, these functions allow application to handle use cases - where number of data to be received is unknown). - - (#) Compared to standard reception services which only consider number of received - data elements as reception completion criteria, these functions also consider additional events - as triggers for updating reception status to caller : - (+) Detection of inactivity period (RX line has not been active for a given period). - (++) RX inactivity detected by IDLE event, i.e. RX line has been in idle state (normally high state) - for 1 frame time, after last received byte. - (++) RX inactivity detected by RTO, i.e. line has been in idle state - for a programmable time, after last received byte. - (+) Detection that a specific character has been received. - - (#) There are two mode of transfer: - (+) Blocking mode: The reception is performed in polling mode, until either expected number of data is received, - or till IDLE event occurs. Reception is handled only during function execution. - When function exits, no data reception could occur. HAL status and number of actually received data elements, - are returned by function after finishing transfer. - (+) Non-Blocking mode: The reception 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 UART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. - The HAL_UARTEx_RxEventCallback() user callback will be executed during Receive process - The HAL_UART_ErrorCallback()user callback will be executed when a reception error is detected. - - (#) Blocking mode API: - (+) HAL_UARTEx_ReceiveToIdle() - - (#) Non-Blocking mode API with Interrupt: - (+) HAL_UARTEx_ReceiveToIdle_IT() - - (#) Non-Blocking mode API with DMA: - (+) HAL_UARTEx_ReceiveToIdle_DMA() - -@endverbatim - * @{ - */ - -/** - * @brief By default in multiprocessor mode, when the wake up method is set - * to address mark, the UART handles only 4-bit long addresses detection; - * this API allows to enable longer addresses detection (6-, 7- or 8-bit - * long). - * @note Addresses detection lengths are: 6-bit address detection in 7-bit data mode, - * 7-bit address detection in 8-bit data mode, 8-bit address detection in 9-bit data mode. - * @param huart UART handle. - * @param AddressLength This parameter can be one of the following values: - * @arg @ref UART_ADDRESS_DETECT_4B 4-bit long address - * @arg @ref UART_ADDRESS_DETECT_7B 6-, 7- or 8-bit long address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength) -{ - /* Check the UART handle allocation */ - if (huart == NULL) - { - return HAL_ERROR; - } - - /* Check the address length parameter */ - assert_param(IS_UART_ADDRESSLENGTH_DETECT(AddressLength)); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_UART_DISABLE(huart); - - /* Set the address length */ - MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, AddressLength); - - /* Enable the Peripheral */ - __HAL_UART_ENABLE(huart); - - /* TEACK and/or REACK to check before moving huart->gState to Ready */ - return (UART_CheckIdleState(huart)); -} - -/** - * @brief Set Wakeup from Stop mode interrupt flag selection. - * @note It is the application responsibility to enable the interrupt used as - * usart_wkup interrupt source before entering low-power mode. - * @param huart UART handle. - * @param WakeUpSelection Address match, Start Bit detection or RXNE/RXFNE bit status. - * This parameter can be one of the following values: - * @arg @ref UART_WAKEUP_ON_ADDRESS - * @arg @ref UART_WAKEUP_ON_STARTBIT - * @arg @ref UART_WAKEUP_ON_READDATA_NONEMPTY - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tickstart; - - /* check the wake-up from stop mode UART instance */ - assert_param(IS_UART_WAKEUP_FROMSTOP_INSTANCE(huart->Instance)); - /* check the wake-up selection parameter */ - assert_param(IS_UART_WAKEUP_SELECTION(WakeUpSelection.WakeUpEvent)); - - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_UART_DISABLE(huart); - - /* Set the wake-up selection scheme */ - MODIFY_REG(huart->Instance->CR3, USART_CR3_WUS, WakeUpSelection.WakeUpEvent); - - if (WakeUpSelection.WakeUpEvent == UART_WAKEUP_ON_ADDRESS) - { - UARTEx_Wakeup_AddressConfig(huart, WakeUpSelection); - } - - /* Enable the Peripheral */ - __HAL_UART_ENABLE(huart); - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Wait until REACK flag is set */ - if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) - { - status = HAL_TIMEOUT; - } - else - { - /* Initialize the UART State */ - huart->gState = HAL_UART_STATE_READY; - } - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return status; -} - -/** - * @brief Enable UART Stop Mode. - * @note The UART is able to wake up the MCU from Stop 1 mode as long as UART clock is HSI or LSE. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart) -{ - /* Process Locked */ - __HAL_LOCK(huart); - - /* Set UESM bit */ - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_UESM); - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Disable UART Stop Mode. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart) -{ - /* Process Locked */ - __HAL_LOCK(huart); - - /* Clear UESM bit */ - ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_UESM); - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Enable the FIFO mode. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_EnableFifoMode(UART_HandleTypeDef *huart) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); - - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Save actual UART configuration */ - tmpcr1 = READ_REG(huart->Instance->CR1); - - /* Disable UART */ - __HAL_UART_DISABLE(huart); - - /* Enable FIFO mode */ - SET_BIT(tmpcr1, USART_CR1_FIFOEN); - huart->FifoMode = UART_FIFOMODE_ENABLE; - - /* Restore UART configuration */ - WRITE_REG(huart->Instance->CR1, tmpcr1); - - /* Determine the number of data to process during RX/TX ISR execution */ - UARTEx_SetNbDataToProcess(huart); - - huart->gState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Disable the FIFO mode. - * @param huart UART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); - - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Save actual UART configuration */ - tmpcr1 = READ_REG(huart->Instance->CR1); - - /* Disable UART */ - __HAL_UART_DISABLE(huart); - - /* Enable FIFO mode */ - CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); - huart->FifoMode = UART_FIFOMODE_DISABLE; - - /* Restore UART configuration */ - WRITE_REG(huart->Instance->CR1, tmpcr1); - - huart->gState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Set the TXFIFO threshold. - * @param huart UART handle. - * @param Threshold TX FIFO threshold value - * This parameter can be one of the following values: - * @arg @ref UART_TXFIFO_THRESHOLD_1_8 - * @arg @ref UART_TXFIFO_THRESHOLD_1_4 - * @arg @ref UART_TXFIFO_THRESHOLD_1_2 - * @arg @ref UART_TXFIFO_THRESHOLD_3_4 - * @arg @ref UART_TXFIFO_THRESHOLD_7_8 - * @arg @ref UART_TXFIFO_THRESHOLD_8_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_SetTxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); - assert_param(IS_UART_TXFIFO_THRESHOLD(Threshold)); - - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Save actual UART configuration */ - tmpcr1 = READ_REG(huart->Instance->CR1); - - /* Disable UART */ - __HAL_UART_DISABLE(huart); - - /* Update TX threshold configuration */ - MODIFY_REG(huart->Instance->CR3, USART_CR3_TXFTCFG, Threshold); - - /* Determine the number of data to process during RX/TX ISR execution */ - UARTEx_SetNbDataToProcess(huart); - - /* Restore UART configuration */ - WRITE_REG(huart->Instance->CR1, tmpcr1); - - huart->gState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Set the RXFIFO threshold. - * @param huart UART handle. - * @param Threshold RX FIFO threshold value - * This parameter can be one of the following values: - * @arg @ref UART_RXFIFO_THRESHOLD_1_8 - * @arg @ref UART_RXFIFO_THRESHOLD_1_4 - * @arg @ref UART_RXFIFO_THRESHOLD_1_2 - * @arg @ref UART_RXFIFO_THRESHOLD_3_4 - * @arg @ref UART_RXFIFO_THRESHOLD_7_8 - * @arg @ref UART_RXFIFO_THRESHOLD_8_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_SetRxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold) -{ - uint32_t tmpcr1; - - /* Check the parameters */ - assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); - assert_param(IS_UART_RXFIFO_THRESHOLD(Threshold)); - - /* Process Locked */ - __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; - - /* Save actual UART configuration */ - tmpcr1 = READ_REG(huart->Instance->CR1); - - /* Disable UART */ - __HAL_UART_DISABLE(huart); - - /* Update RX threshold configuration */ - MODIFY_REG(huart->Instance->CR3, USART_CR3_RXFTCFG, Threshold); - - /* Determine the number of data to process during RX/TX ISR execution */ - UARTEx_SetNbDataToProcess(huart); - - /* Restore UART configuration */ - WRITE_REG(huart->Instance->CR1, tmpcr1); - - huart->gState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_OK; -} - -/** - * @brief Receive an amount of data in blocking mode till either the expected number of data - * is received or an IDLE event occurs. - * @note HAL_OK is returned if reception is completed (expected number of data has been received) - * or if reception is stopped after IDLE event (less than the expected number of data has been received) - * In this case, RxLen output parameter indicates number of data available in reception buffer. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of uint16_t. In this case, Size must indicate the number - * of uint16_t available through pData. - * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO - * is not empty. Read operations from the RDR register are performed when - * RXFNE flag is set. From hardware perspective, RXFNE flag and - * RXNE are mapped on the same bit-field. - * @param huart UART handle. - * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). - * @param Size Amount of data elements (uint8_t or uint16_t) to be received. - * @param RxLen Number of data elements finally received - * (could be lower than Size, in case reception ends on IDLE event) - * @param Timeout Timeout duration expressed in ms (covers the whole reception sequence). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint16_t *RxLen, - uint32_t Timeout) -{ - uint8_t *pdata8bits; - uint16_t *pdata16bits; - uint16_t uhMask; - uint32_t tickstart; - - /* Check that a Rx process is not already ongoing */ - if (huart->RxState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; - huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; - huart->RxEventType = HAL_UART_RXEVENT_TC; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - huart->RxXferSize = Size; - huart->RxXferCount = Size; - - /* Computation of UART mask to apply to RDR register */ - UART_MASK_COMPUTATION(huart); - uhMask = huart->Mask; - - /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ - if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) - { - pdata8bits = NULL; - pdata16bits = (uint16_t *) pData; - } - else - { - pdata8bits = pData; - pdata16bits = NULL; - } - - /* Initialize output number of received elements */ - *RxLen = 0U; - - /* as long as data have to be received */ - while (huart->RxXferCount > 0U) - { - /* Check if IDLE flag is set */ - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) - { - /* Clear IDLE flag in ISR */ - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - - /* If Set, but no data ever received, clear flag without exiting loop */ - /* If Set, and data has already been received, this means Idle Event is valid : End reception */ - if (*RxLen > 0U) - { - huart->RxEventType = HAL_UART_RXEVENT_IDLE; - huart->RxState = HAL_UART_STATE_READY; - - return HAL_OK; - } - } - - /* Check if RXNE flag is set */ - if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE)) - { - if (pdata8bits == NULL) - { - *pdata16bits = (uint16_t)(huart->Instance->RDR & uhMask); - pdata16bits++; - } - else - { - *pdata8bits = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); - pdata8bits++; - } - /* Increment number of received elements */ - *RxLen += 1U; - huart->RxXferCount--; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - huart->RxState = HAL_UART_STATE_READY; - - return HAL_TIMEOUT; - } - } - } - - /* Set number of received elements in output parameter : RxLen */ - *RxLen = huart->RxXferSize - huart->RxXferCount; - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in interrupt mode till either the expected number of data - * is received or an IDLE event occurs. - * @note Reception is initiated by this function call. Further progress of reception is achieved thanks - * to UART interrupts raised by RXNE and IDLE events. Callback is called at end of reception indicating - * number of received data elements. - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of uint16_t. In this case, Size must indicate the number - * of uint16_t available through pData. - * @param huart UART handle. - * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). - * @param Size Amount of data elements (uint8_t or uint16_t) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check that a Rx process is not already ongoing */ - if (huart->RxState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Set Reception type to reception till IDLE Event*/ - huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; - huart->RxEventType = HAL_UART_RXEVENT_TC; - - (void)UART_Start_Receive_IT(huart, pData, Size); - - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - } - else - { - /* In case of errors already pending when reception is started, - Interrupts may have already been raised and lead to reception abortion. - (Overrun error for instance). - In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ - status = HAL_ERROR; - } - - return status; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Receive an amount of data in DMA mode till either the expected number - * of data is received or an IDLE event occurs. - * @note Reception is initiated by this function call. Further progress of reception is achieved thanks - * to DMA services, transferring automatically received data elements in user reception buffer and - * calling registered callbacks at half/end of reception. UART IDLE events are also used to consider - * reception phase as ended. In all cases, callback execution will indicate number of received data elements. - * @note When the UART parity is enabled (PCE = 1), the received data contain - * the parity bit (MSB position). - * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of uint16_t. In this case, Size must indicate the number - * of uint16_t available through pData. - * @param huart UART handle. - * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). - * @param Size Amount of data elements (uint8_t or uint16_t) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) -{ - HAL_StatusTypeDef status; - - /* Check that a Rx process is not already ongoing */ - if (huart->RxState == HAL_UART_STATE_READY) - { - if ((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Set Reception type to reception till IDLE Event*/ - huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; - huart->RxEventType = HAL_UART_RXEVENT_TC; - - status = UART_Start_Receive_DMA(huart, pData, Size); - - /* Check Rx process has been successfully started */ - if (status == HAL_OK) - { - if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) - { - __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); - ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); - } - else - { - /* In case of errors already pending when reception is started, - Interrupts may have already been raised and lead to reception abortion. - (Overrun error for instance). - In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ - status = HAL_ERROR; - } - } - - return status; - } - else - { - return HAL_BUSY; - } -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Provide Rx Event type that has lead to RxEvent callback execution. - * @note When HAL_UARTEx_ReceiveToIdle_IT() or HAL_UARTEx_ReceiveToIdle_DMA() API are called, progress - * of reception process is provided to application through calls of Rx Event callback (either default one - * HAL_UARTEx_RxEventCallback() or user registered one). As several types of events could occur (IDLE event, - * Half Transfer, or Transfer Complete), this function allows to retrieve the Rx Event type that has lead - * to Rx Event callback execution. - * @note This function is expected to be called within the user implementation of Rx Event Callback, - * in order to provide the accurate value : - * In Interrupt Mode : - * - HAL_UART_RXEVENT_TC : when Reception has been completed (expected nb of data has been received) - * - HAL_UART_RXEVENT_IDLE : when Idle event occurred prior reception has been completed (nb of - * received data is lower than expected one) - * In DMA Mode : - * - HAL_UART_RXEVENT_TC : when Reception has been completed (expected nb of data has been received) - * - HAL_UART_RXEVENT_HT : when half of expected nb of data has been received - * - HAL_UART_RXEVENT_IDLE : when Idle event occurred prior reception has been completed (nb of - * received data is lower than expected one). - * In DMA mode, RxEvent callback could be called several times; - * When DMA is configured in Normal Mode, HT event does not stop Reception process; - * When DMA is configured in Circular Mode, HT, TC or IDLE events don't stop Reception process; - * @param huart UART handle. - * @retval Rx Event Type (return vale will be a value of @ref UART_RxEvent_Type_Values) - */ -HAL_UART_RxEventTypeTypeDef HAL_UARTEx_GetRxEventType(const UART_HandleTypeDef *huart) -{ - /* Return Rx Event type value, as stored in UART handle */ - return (huart->RxEventType); -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup UARTEx_Private_Functions - * @{ - */ - -/** - * @brief Initialize the UART wake-up from stop mode parameters when triggered by address detection. - * @param huart UART handle. - * @param WakeUpSelection UART wake up from stop mode parameters. - * @retval None - */ -static void UARTEx_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) -{ - assert_param(IS_UART_ADDRESSLENGTH_DETECT(WakeUpSelection.AddressLength)); - - /* Set the USART address length */ - MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, WakeUpSelection.AddressLength); - - /* Set the USART address node */ - MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)WakeUpSelection.Address << UART_CR2_ADDRESS_LSB_POS)); -} - -/** - * @brief Calculate the number of data to process in RX/TX ISR. - * @note The RX FIFO depth and the TX FIFO depth is extracted from - * the UART configuration registers. - * @param huart UART handle. - * @retval None - */ -static void UARTEx_SetNbDataToProcess(UART_HandleTypeDef *huart) -{ - uint8_t rx_fifo_depth; - uint8_t tx_fifo_depth; - uint8_t rx_fifo_threshold; - uint8_t tx_fifo_threshold; - static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; - static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; - - if (huart->FifoMode == UART_FIFOMODE_DISABLE) - { - huart->NbTxDataToProcess = 1U; - huart->NbRxDataToProcess = 1U; - } - else - { - rx_fifo_depth = RX_FIFO_DEPTH; - tx_fifo_depth = TX_FIFO_DEPTH; - rx_fifo_threshold = (uint8_t)(READ_BIT(huart->Instance->CR3, USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos); - tx_fifo_threshold = (uint8_t)(READ_BIT(huart->Instance->CR3, USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos); - huart->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / - (uint16_t)denominator[tx_fifo_threshold]; - huart->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / - (uint16_t)denominator[rx_fifo_threshold]; - } -} -/** - * @} - */ - -#endif /* HAL_UART_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_uart_ex.c + * @author MCD Application Team + * @brief Extended UART HAL module driver. + * This file provides firmware functions to manage the following extended + * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### UART peripheral extended features ##### + ============================================================================== + + (#) Declare a UART_HandleTypeDef handle structure. + + (#) For the UART RS485 Driver Enable mode, initialize the UART registers + by calling the HAL_RS485Ex_Init() API. + + (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. + + -@- When UART operates in FIFO mode, FIFO mode must be enabled prior + starting RX/TX transfers. Also RX/TX FIFO thresholds must be + configured prior starting RX/TX transfers. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup UARTEx UARTEx + * @brief UART Extended HAL module driver + * @{ + */ + +#ifdef HAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup UARTEX_Private_Constants UARTEx Private Constants + * @{ + */ +/* UART RX FIFO depth */ +#define RX_FIFO_DEPTH 16U + +/* UART TX FIFO depth */ +#define TX_FIFO_DEPTH 16U +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup UARTEx_Private_Functions UARTEx Private Functions + * @{ + */ +static void UARTEx_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); +static void UARTEx_SetNbDataToProcess(UART_HandleTypeDef *huart); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup UARTEx_Exported_Functions UARTEx Exported Functions + * @{ + */ + +/** @defgroup UARTEx_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Extended 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 the parameters below 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. + (++) Hardware flow control + (++) Receiver/transmitter modes + (++) Over Sampling Method + (++) One-Bit Sampling Method + (+) For the asynchronous mode, the following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) auto Baud rate detection + [..] + The HAL_RS485Ex_Init() API follows the UART RS485 mode configuration + procedures (details for the procedures are available in reference manual). + +@endverbatim + + Depending on the frame length defined by the M1 and M0 bits (7-bit, + 8-bit or 9-bit), the possible UART formats are listed in the + following table. + + Table 1. UART frame format. + +-----------------------------------------------------------------------+ + | M1 bit | M0 bit | PCE bit | UART frame | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 0 | | SB | 8 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 0 | | SB | 9 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 0 | | SB | 7 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | + +-----------------------------------------------------------------------+ + + * @{ + */ + +/** + * @brief Initialize the RS485 Driver enable feature according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle. + * @param huart UART handle. + * @param Polarity Select the driver enable polarity. + * This parameter can be one of the following values: + * @arg @ref UART_DE_POLARITY_HIGH DE signal is active high + * @arg @ref UART_DE_POLARITY_LOW DE signal is active low + * @param AssertionTime Driver Enable assertion time: + * 5-bit value defining the time between the activation of the DE (Driver Enable) + * signal and the beginning of the start bit. It is expressed in sample time + * units (1/8 or 1/16 bit time, depending on the oversampling rate) + * @param DeassertionTime Driver Enable deassertion time: + * 5-bit value defining the time between the end of the last stop bit, in a + * transmitted message, and the de-activation of the DE (Driver Enable) signal. + * It is expressed in sample time units (1/8 or 1/16 bit time, depending on the + * oversampling rate). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t Polarity, uint32_t AssertionTime, + uint32_t DeassertionTime) +{ + uint32_t temp; + + /* Check the UART handle allocation */ + if (huart == NULL) + { + return HAL_ERROR; + } + /* Check the Driver Enable UART instance */ + assert_param(IS_UART_DRIVER_ENABLE_INSTANCE(huart->Instance)); + + /* Check the Driver Enable polarity */ + assert_param(IS_UART_DE_POLARITY(Polarity)); + + /* Check the Driver Enable assertion time */ + assert_param(IS_UART_ASSERTIONTIME(AssertionTime)); + + /* Check the Driver Enable deassertion time */ + assert_param(IS_UART_DEASSERTIONTIME(DeassertionTime)); + + if (huart->gState == HAL_UART_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + huart->Lock = HAL_UNLOCKED; + +#if (USE_HAL_UART_REGISTER_CALLBACKS == 1) + UART_InitCallbacksToDefault(huart); + + if (huart->MspInitCallback == NULL) + { + huart->MspInitCallback = HAL_UART_MspInit; + } + + /* Init the low level hardware */ + huart->MspInitCallback(huart); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_UART_MspInit(huart); +#endif /* (USE_HAL_UART_REGISTER_CALLBACKS) */ + } + + huart->gState = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Perform advanced settings configuration */ + /* For some items, configuration requires to be done prior TE and RE bits are set */ + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* Enable the Driver Enable mode by setting the DEM bit in the CR3 register */ + SET_BIT(huart->Instance->CR3, USART_CR3_DEM); + + /* Set the Driver Enable polarity */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_DEP, Polarity); + + /* Set the Driver Enable assertion and deassertion times */ + temp = (AssertionTime << UART_CR1_DEAT_ADDRESS_LSB_POS); + temp |= (DeassertionTime << UART_CR1_DEDT_ADDRESS_LSB_POS); + MODIFY_REG(huart->Instance->CR1, (USART_CR1_DEDT | USART_CR1_DEAT), temp); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->gState and huart->RxState to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @} + */ + +/** @defgroup UARTEx_Exported_Functions_Group2 IO operation functions + * @brief Extended functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + This subsection provides a set of Wakeup and FIFO mode related callback functions. + + (#) Wakeup from Stop mode Callback: + (+) HAL_UARTEx_WakeupCallback() + + (#) TX/RX Fifos Callbacks: + (+) HAL_UARTEx_RxFifoFullCallback() + (+) HAL_UARTEx_TxFifoEmptyCallback() + +@endverbatim + * @{ + */ + +/** + * @brief UART wakeup from Stop mode callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UARTEx_WakeupCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UARTEx_WakeupCallback can be implemented in the user file. + */ +} + +/** + * @brief UART RX Fifo full callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UARTEx_RxFifoFullCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UARTEx_RxFifoFullCallback can be implemented in the user file. + */ +} + +/** + * @brief UART TX Fifo empty callback. + * @param huart UART handle. + * @retval None + */ +__weak void HAL_UARTEx_TxFifoEmptyCallback(UART_HandleTypeDef *huart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(huart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UARTEx_TxFifoEmptyCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup UARTEx_Exported_Functions_Group3 Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides the following functions: + (+) HAL_MultiProcessorEx_AddressLength_Set() API optionally sets the UART node address + detection length to more than 4 bits for multiprocessor address mark wake up. + (+) HAL_UARTEx_StopModeWakeUpSourceConfig() API defines the wake-up from stop mode + trigger: address match, Start Bit detection or RXNE bit status. + (+) HAL_UARTEx_EnableStopMode() API enables the UART to wake up the MCU from stop mode + (+) HAL_UARTEx_DisableStopMode() API disables the above functionality + (+) HAL_UARTEx_EnableFifoMode() API enables the FIFO mode + (+) HAL_UARTEx_DisableFifoMode() API disables the FIFO mode + (+) HAL_UARTEx_SetTxFifoThreshold() API sets the TX FIFO threshold + (+) HAL_UARTEx_SetRxFifoThreshold() API sets the RX FIFO threshold + + [..] This subsection also provides a set of additional functions providing enhanced reception + services to user. (For example, these functions allow application to handle use cases + where number of data to be received is unknown). + + (#) Compared to standard reception services which only consider number of received + data elements as reception completion criteria, these functions also consider additional events + as triggers for updating reception status to caller : + (+) Detection of inactivity period (RX line has not been active for a given period). + (++) RX inactivity detected by IDLE event, i.e. RX line has been in idle state (normally high state) + for 1 frame time, after last received byte. + (++) RX inactivity detected by RTO, i.e. line has been in idle state + for a programmable time, after last received byte. + (+) Detection that a specific character has been received. + + (#) There are two mode of transfer: + (+) Blocking mode: The reception is performed in polling mode, until either expected number of data is received, + or till IDLE event occurs. Reception is handled only during function execution. + When function exits, no data reception could occur. HAL status and number of actually received data elements, + are returned by function after finishing transfer. + (+) Non-Blocking mode: The reception 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 UART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. + The HAL_UARTEx_RxEventCallback() user callback will be executed during Receive process + The HAL_UART_ErrorCallback()user callback will be executed when a reception error is detected. + + (#) Blocking mode API: + (+) HAL_UARTEx_ReceiveToIdle() + + (#) Non-Blocking mode API with Interrupt: + (+) HAL_UARTEx_ReceiveToIdle_IT() + + (#) Non-Blocking mode API with DMA: + (+) HAL_UARTEx_ReceiveToIdle_DMA() + +@endverbatim + * @{ + */ + +/** + * @brief By default in multiprocessor mode, when the wake up method is set + * to address mark, the UART handles only 4-bit long addresses detection; + * this API allows to enable longer addresses detection (6-, 7- or 8-bit + * long). + * @note Addresses detection lengths are: 6-bit address detection in 7-bit data mode, + * 7-bit address detection in 8-bit data mode, 8-bit address detection in 9-bit data mode. + * @param huart UART handle. + * @param AddressLength This parameter can be one of the following values: + * @arg @ref UART_ADDRESS_DETECT_4B 4-bit long address + * @arg @ref UART_ADDRESS_DETECT_7B 6-, 7- or 8-bit long address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength) +{ + /* Check the UART handle allocation */ + if (huart == NULL) + { + return HAL_ERROR; + } + + /* Check the address length parameter */ + assert_param(IS_UART_ADDRESSLENGTH_DETECT(AddressLength)); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the address length */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, AddressLength); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->gState to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Set Wakeup from Stop mode interrupt flag selection. + * @note It is the application responsibility to enable the interrupt used as + * usart_wkup interrupt source before entering low-power mode. + * @param huart UART handle. + * @param WakeUpSelection Address match, Start Bit detection or RXNE/RXFNE bit status. + * This parameter can be one of the following values: + * @arg @ref UART_WAKEUP_ON_ADDRESS + * @arg @ref UART_WAKEUP_ON_STARTBIT + * @arg @ref UART_WAKEUP_ON_READDATA_NONEMPTY + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tickstart; + + /* check the wake-up from stop mode UART instance */ + assert_param(IS_UART_WAKEUP_FROMSTOP_INSTANCE(huart->Instance)); + /* check the wake-up selection parameter */ + assert_param(IS_UART_WAKEUP_SELECTION(WakeUpSelection.WakeUpEvent)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the wake-up selection scheme */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_WUS, WakeUpSelection.WakeUpEvent); + + if (WakeUpSelection.WakeUpEvent == UART_WAKEUP_ON_ADDRESS) + { + UARTEx_Wakeup_AddressConfig(huart, WakeUpSelection); + } + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Wait until REACK flag is set */ + if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) + { + status = HAL_TIMEOUT; + } + else + { + /* Initialize the UART State */ + huart->gState = HAL_UART_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return status; +} + +/** + * @brief Enable UART Stop Mode. + * @note The UART is able to wake up the MCU from Stop 1 mode as long as UART clock is HSI or LSE. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + /* Set UESM bit */ + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_UESM); + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Disable UART Stop Mode. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + /* Clear UESM bit */ + ATOMIC_CLEAR_BIT(huart->Instance->CR1, USART_CR1_UESM); + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Enable the FIFO mode. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_EnableFifoMode(UART_HandleTypeDef *huart) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Save actual UART configuration */ + tmpcr1 = READ_REG(huart->Instance->CR1); + + /* Disable UART */ + __HAL_UART_DISABLE(huart); + + /* Enable FIFO mode */ + SET_BIT(tmpcr1, USART_CR1_FIFOEN); + huart->FifoMode = UART_FIFOMODE_ENABLE; + + /* Restore UART configuration */ + WRITE_REG(huart->Instance->CR1, tmpcr1); + + /* Determine the number of data to process during RX/TX ISR execution */ + UARTEx_SetNbDataToProcess(huart); + + huart->gState = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Disable the FIFO mode. + * @param huart UART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Save actual UART configuration */ + tmpcr1 = READ_REG(huart->Instance->CR1); + + /* Disable UART */ + __HAL_UART_DISABLE(huart); + + /* Disable FIFO mode */ + CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); + huart->FifoMode = UART_FIFOMODE_DISABLE; + + /* Restore UART configuration */ + WRITE_REG(huart->Instance->CR1, tmpcr1); + + huart->gState = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Set the TXFIFO threshold. + * @param huart UART handle. + * @param Threshold TX FIFO threshold value + * This parameter can be one of the following values: + * @arg @ref UART_TXFIFO_THRESHOLD_1_8 + * @arg @ref UART_TXFIFO_THRESHOLD_1_4 + * @arg @ref UART_TXFIFO_THRESHOLD_1_2 + * @arg @ref UART_TXFIFO_THRESHOLD_3_4 + * @arg @ref UART_TXFIFO_THRESHOLD_7_8 + * @arg @ref UART_TXFIFO_THRESHOLD_8_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_SetTxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); + assert_param(IS_UART_TXFIFO_THRESHOLD(Threshold)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Save actual UART configuration */ + tmpcr1 = READ_REG(huart->Instance->CR1); + + /* Disable UART */ + __HAL_UART_DISABLE(huart); + + /* Update TX threshold configuration */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_TXFTCFG, Threshold); + + /* Determine the number of data to process during RX/TX ISR execution */ + UARTEx_SetNbDataToProcess(huart); + + /* Restore UART configuration */ + WRITE_REG(huart->Instance->CR1, tmpcr1); + + huart->gState = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Set the RXFIFO threshold. + * @param huart UART handle. + * @param Threshold RX FIFO threshold value + * This parameter can be one of the following values: + * @arg @ref UART_RXFIFO_THRESHOLD_1_8 + * @arg @ref UART_RXFIFO_THRESHOLD_1_4 + * @arg @ref UART_RXFIFO_THRESHOLD_1_2 + * @arg @ref UART_RXFIFO_THRESHOLD_3_4 + * @arg @ref UART_RXFIFO_THRESHOLD_7_8 + * @arg @ref UART_RXFIFO_THRESHOLD_8_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_SetRxFifoThreshold(UART_HandleTypeDef *huart, uint32_t Threshold) +{ + uint32_t tmpcr1; + + /* Check the parameters */ + assert_param(IS_UART_FIFO_INSTANCE(huart->Instance)); + assert_param(IS_UART_RXFIFO_THRESHOLD(Threshold)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->gState = HAL_UART_STATE_BUSY; + + /* Save actual UART configuration */ + tmpcr1 = READ_REG(huart->Instance->CR1); + + /* Disable UART */ + __HAL_UART_DISABLE(huart); + + /* Update RX threshold configuration */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_RXFTCFG, Threshold); + + /* Determine the number of data to process during RX/TX ISR execution */ + UARTEx_SetNbDataToProcess(huart); + + /* Restore UART configuration */ + WRITE_REG(huart->Instance->CR1, tmpcr1); + + huart->gState = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Receive an amount of data in blocking mode till either the expected number of data + * is received or an IDLE event occurs. + * @note HAL_OK is returned if reception is completed (expected number of data has been received) + * or if reception is stopped after IDLE event (less than the expected number of data has been received) + * In this case, RxLen output parameter indicates number of data available in reception buffer. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of uint16_t. In this case, Size must indicate the number + * of uint16_t available through pData. + * @note When FIFO mode is enabled, the RXFNE flag is set as long as the RXFIFO + * is not empty. Read operations from the RDR register are performed when + * RXFNE flag is set. From hardware perspective, RXFNE flag and + * RXNE are mapped on the same bit-field. + * @param huart UART handle. + * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). + * @param Size Amount of data elements (uint8_t or uint16_t) to be received. + * @param RxLen Number of data elements finally received + * (could be lower than Size, in case reception ends on IDLE event) + * @param Timeout Timeout duration expressed in ms (covers the whole reception sequence). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint16_t *RxLen, + uint32_t Timeout) +{ + uint8_t *pdata8bits; + uint16_t *pdata16bits; + uint16_t uhMask; + uint32_t tickstart; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->RxState = HAL_UART_STATE_BUSY_RX; + huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; + huart->RxEventType = HAL_UART_RXEVENT_TC; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + UART_MASK_COMPUTATION(huart); + uhMask = huart->Mask; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + pdata8bits = NULL; + pdata16bits = (uint16_t *) pData; + } + else + { + pdata8bits = pData; + pdata16bits = NULL; + } + + /* Initialize output number of received elements */ + *RxLen = 0U; + + /* as long as data have to be received */ + while (huart->RxXferCount > 0U) + { + /* Check if IDLE flag is set */ + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) + { + /* Clear IDLE flag in ISR */ + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + + /* If Set, but no data ever received, clear flag without exiting loop */ + /* If Set, and data has already been received, this means Idle Event is valid : End reception */ + if (*RxLen > 0U) + { + huart->RxEventType = HAL_UART_RXEVENT_IDLE; + huart->RxState = HAL_UART_STATE_READY; + + return HAL_OK; + } + } + + /* Check if RXNE flag is set */ + if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE)) + { + if (pdata8bits == NULL) + { + *pdata16bits = (uint16_t)(huart->Instance->RDR & uhMask); + pdata16bits++; + } + else + { + *pdata8bits = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); + pdata8bits++; + } + /* Increment number of received elements */ + *RxLen += 1U; + huart->RxXferCount--; + } + + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + huart->RxState = HAL_UART_STATE_READY; + + return HAL_TIMEOUT; + } + } + } + + /* Set number of received elements in output parameter : RxLen */ + *RxLen = huart->RxXferSize - huart->RxXferCount; + /* At end of Rx process, restore huart->RxState to Ready */ + huart->RxState = HAL_UART_STATE_READY; + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode till either the expected number of data + * is received or an IDLE event occurs. + * @note Reception is initiated by this function call. Further progress of reception is achieved thanks + * to UART interrupts raised by RXNE and IDLE events. Callback is called at end of reception indicating + * number of received data elements. + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of uint16_t. In this case, Size must indicate the number + * of uint16_t available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). + * @param Size Amount of data elements (uint8_t or uint16_t) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Set Reception type to reception till IDLE Event*/ + huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; + huart->RxEventType = HAL_UART_RXEVENT_TC; + + (void)UART_Start_Receive_IT(huart, pData, Size); + + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + } + else + { + /* In case of errors already pending when reception is started, + Interrupts may have already been raised and lead to reception abortion. + (Overrun error for instance). + In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ + status = HAL_ERROR; + } + + return status; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Receive an amount of data in DMA mode till either the expected number + * of data is received or an IDLE event occurs. + * @note Reception is initiated by this function call. Further progress of reception is achieved thanks + * to DMA services, transferring automatically received data elements in user reception buffer and + * calling registered callbacks at half/end of reception. UART IDLE events are also used to consider + * reception phase as ended. In all cases, callback execution will indicate number of received data elements. + * @note When the UART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position). + * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of uint16_t. In this case, Size must indicate the number + * of uint16_t available through pData. + * @param huart UART handle. + * @param pData Pointer to data buffer (uint8_t or uint16_t data elements). + * @param Size Amount of data elements (uint8_t or uint16_t) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_ReceiveToIdle_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + HAL_StatusTypeDef status; + + /* Check that a Rx process is not already ongoing */ + if (huart->RxState == HAL_UART_STATE_READY) + { + if ((pData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Set Reception type to reception till IDLE Event*/ + huart->ReceptionType = HAL_UART_RECEPTION_TOIDLE; + huart->RxEventType = HAL_UART_RXEVENT_TC; + + status = UART_Start_Receive_DMA(huart, pData, Size); + + /* Check Rx process has been successfully started */ + if (status == HAL_OK) + { + if (huart->ReceptionType == HAL_UART_RECEPTION_TOIDLE) + { + __HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_IDLEF); + ATOMIC_SET_BIT(huart->Instance->CR1, USART_CR1_IDLEIE); + } + else + { + /* In case of errors already pending when reception is started, + Interrupts may have already been raised and lead to reception abortion. + (Overrun error for instance). + In such case Reception Type has been reset to HAL_UART_RECEPTION_STANDARD. */ + status = HAL_ERROR; + } + } + + return status; + } + else + { + return HAL_BUSY; + } +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Provide Rx Event type that has lead to RxEvent callback execution. + * @note When HAL_UARTEx_ReceiveToIdle_IT() or HAL_UARTEx_ReceiveToIdle_DMA() API are called, progress + * of reception process is provided to application through calls of Rx Event callback (either default one + * HAL_UARTEx_RxEventCallback() or user registered one). As several types of events could occur (IDLE event, + * Half Transfer, or Transfer Complete), this function allows to retrieve the Rx Event type that has lead + * to Rx Event callback execution. + * @note This function is expected to be called within the user implementation of Rx Event Callback, + * in order to provide the accurate value : + * In Interrupt Mode : + * - HAL_UART_RXEVENT_TC : when Reception has been completed (expected nb of data has been received) + * - HAL_UART_RXEVENT_IDLE : when Idle event occurred prior reception has been completed (nb of + * received data is lower than expected one) + * In DMA Mode : + * - HAL_UART_RXEVENT_TC : when Reception has been completed (expected nb of data has been received) + * - HAL_UART_RXEVENT_HT : when half of expected nb of data has been received + * - HAL_UART_RXEVENT_IDLE : when Idle event occurred prior reception has been completed (nb of + * received data is lower than expected one). + * In DMA mode, RxEvent callback could be called several times; + * When DMA is configured in Normal Mode, HT event does not stop Reception process; + * When DMA is configured in Circular Mode, HT, TC or IDLE events don't stop Reception process; + * @param huart UART handle. + * @retval Rx Event Type (return vale will be a value of @ref UART_RxEvent_Type_Values) + */ +HAL_UART_RxEventTypeTypeDef HAL_UARTEx_GetRxEventType(const UART_HandleTypeDef *huart) +{ + /* Return Rx Event type value, as stored in UART handle */ + return (huart->RxEventType); +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup UARTEx_Private_Functions + * @{ + */ + +/** + * @brief Initialize the UART wake-up from stop mode parameters when triggered by address detection. + * @param huart UART handle. + * @param WakeUpSelection UART wake up from stop mode parameters. + * @retval None + */ +static void UARTEx_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) +{ + assert_param(IS_UART_ADDRESSLENGTH_DETECT(WakeUpSelection.AddressLength)); + + /* Set the USART address length */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, WakeUpSelection.AddressLength); + + /* Set the USART address node */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)WakeUpSelection.Address << UART_CR2_ADDRESS_LSB_POS)); +} + +/** + * @brief Calculate the number of data to process in RX/TX ISR. + * @note The RX FIFO depth and the TX FIFO depth is extracted from + * the UART configuration registers. + * @param huart UART handle. + * @retval None + */ +static void UARTEx_SetNbDataToProcess(UART_HandleTypeDef *huart) +{ + uint8_t rx_fifo_depth; + uint8_t tx_fifo_depth; + uint8_t rx_fifo_threshold; + uint8_t tx_fifo_threshold; + static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; + static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; + + if (huart->FifoMode == UART_FIFOMODE_DISABLE) + { + huart->NbTxDataToProcess = 1U; + huart->NbRxDataToProcess = 1U; + } + else + { + rx_fifo_depth = RX_FIFO_DEPTH; + tx_fifo_depth = TX_FIFO_DEPTH; + rx_fifo_threshold = (uint8_t)(READ_BIT(huart->Instance->CR3, USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos); + tx_fifo_threshold = (uint8_t)(READ_BIT(huart->Instance->CR3, USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos); + huart->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / + (uint16_t)denominator[tx_fifo_threshold]; + huart->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / + (uint16_t)denominator[rx_fifo_threshold]; + } +} +/** + * @} + */ + +#endif /* HAL_UART_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart.c index 6efce4287..40fcc2e35 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart.c @@ -1,3959 +1,3957 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_usart.c - * @author MCD Application Team - * @brief USART HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Universal Synchronous/Asynchronous Receiver Transmitter - * Peripheral (USART). - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral Control functions - * + Peripheral State and Error functions - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - =============================================================================== - ##### How to use this driver ##### - =============================================================================== - [..] - The USART HAL driver can be used as follows: - - (#) Declare a USART_HandleTypeDef handle structure (eg. USART_HandleTypeDef husart). - (#) Initialize the USART low level resources by implementing 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. - (++) USART interrupts handling: - -@@- The specific USART interrupts (Transmission complete interrupt, - RXNE interrupt and Error Interrupts) will be managed using the macros - __HAL_USART_ENABLE_IT() and __HAL_USART_DISABLE_IT() inside the transmit and receive process. - (++) DMA Configuration if you need to use DMA process (HAL_USART_Transmit_DMA() - HAL_USART_Receive_DMA() and HAL_USART_TransmitReceive_DMA() APIs): - (+++) Declare a DMA handle structure for the Tx/Rx channel. - (+++) Enable the DMAx interface clock. - (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. - (+++) Configure the DMA Tx/Rx channel. - (+++) Associate the initialized 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 channel. - - (#) Program the Baud Rate, Word Length, Stop Bit, Parity, and Mode - (Receiver/Transmitter) in the husart handle Init structure. - - (#) Initialize the USART registers by calling the HAL_USART_Init() API: - (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_USART_MspInit(&husart) API. - - [..] - (@) To configure and enable/disable the USART to wake up the MCU from stop mode, resort to UART API's - HAL_UARTEx_StopModeWakeUpSourceConfig(), HAL_UARTEx_EnableStopMode() and - HAL_UARTEx_DisableStopMode() in casting the USART handle to UART type UART_HandleTypeDef. - - ##### Callback registration ##### - ================================== - - [..] - The compilation define USE_HAL_USART_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - [..] - Use Function HAL_USART_RegisterCallback() to register a user callback. - Function HAL_USART_RegisterCallback() allows to register following callbacks: - (+) TxHalfCpltCallback : Tx Half Complete Callback. - (+) TxCpltCallback : Tx Complete Callback. - (+) RxHalfCpltCallback : Rx Half Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) TxRxCpltCallback : Tx Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) RxFifoFullCallback : Rx Fifo Full Callback. - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) MspInitCallback : USART MspInit. - (+) MspDeInitCallback : USART MspDeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_USART_UnRegisterCallback() to reset a callback to the default - weak function. - HAL_USART_UnRegisterCallback() takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) TxHalfCpltCallback : Tx Half Complete Callback. - (+) TxCpltCallback : Tx Complete Callback. - (+) RxHalfCpltCallback : Rx Half Complete Callback. - (+) RxCpltCallback : Rx Complete Callback. - (+) TxRxCpltCallback : Tx Rx Complete Callback. - (+) ErrorCallback : Error Callback. - (+) AbortCpltCallback : Abort Complete Callback. - (+) RxFifoFullCallback : Rx Fifo Full Callback. - (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. - (+) MspInitCallback : USART MspInit. - (+) MspDeInitCallback : USART MspDeInit. - - [..] - By default, after the HAL_USART_Init() and when the state is HAL_USART_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples HAL_USART_TxCpltCallback(), HAL_USART_RxHalfCpltCallback(). - Exception done for MspInit and MspDeInit functions that are respectively - reset to the legacy weak functions in the HAL_USART_Init() - and HAL_USART_DeInit() only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_USART_Init() and HAL_USART_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand). - - [..] - Callbacks can be registered/unregistered in HAL_USART_STATE_READY state only. - Exception done MspInit/MspDeInit that can be registered/unregistered - in HAL_USART_STATE_READY or HAL_USART_STATE_RESET state, thus registered (user) - MspInit/DeInit callbacks can be used during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_USART_RegisterCallback() before calling HAL_USART_DeInit() - or HAL_USART_Init() function. - - [..] - When The compilation define USE_HAL_USART_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available - and weak callbacks are used. - - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup USART USART - * @brief HAL USART Synchronous module driver - * @{ - */ - -#ifdef HAL_USART_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @defgroup USART_Private_Constants USART Private Constants - * @{ - */ -#define USART_DUMMY_DATA ((uint16_t) 0xFFFF) /*!< USART transmitted dummy data */ -#define USART_TEACK_REACK_TIMEOUT 1000U /*!< USART TX or RX enable acknowledge time-out value */ -#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ - USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8 | \ - USART_CR1_FIFOEN )) /*!< USART CR1 fields of parameters set by USART_SetConfig API */ - -#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | \ - USART_CR2_LBCL | USART_CR2_STOP | USART_CR2_SLVEN | \ - USART_CR2_DIS_NSS)) /*!< USART CR2 fields of parameters set by USART_SetConfig API */ - -#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_TXFTCFG | USART_CR3_RXFTCFG )) /*!< USART or USART CR3 fields of parameters set by USART_SetConfig API */ - -#define USART_BRR_MIN 0x10U /* USART BRR minimum authorized value */ -#define USART_BRR_MAX 0xFFFFU /* USART BRR maximum authorized value */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup USART_Private_Functions - * @{ - */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) -void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ -static void USART_EndTransfer(USART_HandleTypeDef *husart); -#if defined(HAL_DMA_MODULE_ENABLED) -static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); -static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); -static void USART_DMAError(DMA_HandleTypeDef *hdma); -static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -#endif /* HAL_DMA_MODULE_ENABLED */ -static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout); -static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart); -static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart); -static void USART_TxISR_8BIT(USART_HandleTypeDef *husart); -static void USART_TxISR_16BIT(USART_HandleTypeDef *husart); -static void USART_TxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart); -static void USART_TxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); -static void USART_EndTransmit_IT(USART_HandleTypeDef *husart); -static void USART_RxISR_8BIT(USART_HandleTypeDef *husart); -static void USART_RxISR_16BIT(USART_HandleTypeDef *husart); -static void USART_RxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart); -static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); - - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup USART_Exported_Functions USART Exported Functions - * @{ - */ - -/** @defgroup USART_Exported_Functions_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 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. - (++) 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). - -@endverbatim - - Depending on the frame length defined by the M1 and M0 bits (7-bit, - 8-bit or 9-bit), the possible USART formats are listed in the - following table. - - Table 1. USART frame format. - +-----------------------------------------------------------------------+ - | M1 bit | M0 bit | PCE bit | USART frame | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 0 | | SB | 8 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 0 | | SB | 9 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 0 | | SB | 7 bit data | STB | | - |---------|---------|-----------|---------------------------------------| - | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | - +-----------------------------------------------------------------------+ - - * @{ - */ - -/** - * @brief Initialize the USART mode according to the specified - * parameters in the USART_InitTypeDef and initialize 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) - { - /* Allocate lock resource and initialize it */ - husart->Lock = HAL_UNLOCKED; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - USART_InitCallbacksToDefault(husart); - - if (husart->MspInitCallback == NULL) - { - husart->MspInitCallback = HAL_USART_MspInit; - } - - /* Init the low level hardware */ - husart->MspInitCallback(husart); -#else - /* Init the low level hardware : GPIO, CLOCK */ - HAL_USART_MspInit(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - - husart->State = HAL_USART_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_USART_DISABLE(husart); - - /* Set the Usart Communication parameters */ - if (USART_SetConfig(husart) == HAL_ERROR) - { - return HAL_ERROR; - } - - /* In Synchronous 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_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); - - /* Enable the Peripheral */ - __HAL_USART_ENABLE(husart); - - /* TEACK and/or REACK to check before moving husart->State to Ready */ - return (USART_CheckIdleState(husart)); -} - -/** - * @brief DeInitialize 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; - - husart->Instance->CR1 = 0x0U; - husart->Instance->CR2 = 0x0U; - husart->Instance->CR3 = 0x0U; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - if (husart->MspDeInitCallback == NULL) - { - husart->MspDeInitCallback = HAL_USART_MspDeInit; - } - /* DeInit the low level hardware */ - husart->MspDeInitCallback(husart); -#else - /* DeInit the low level hardware */ - HAL_USART_MspDeInit(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - - husart->ErrorCode = HAL_USART_ERROR_NONE; - husart->State = HAL_USART_STATE_RESET; - - /* Process Unlock */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Initialize the USART MSP. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_MspInit can be implemented in the user file - */ -} - -/** - * @brief DeInitialize the USART MSP. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_MspDeInit can be implemented in the user file - */ -} - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User USART Callback - * To be used to override the weak predefined callback - * @note The HAL_USART_RegisterCallback() may be called before HAL_USART_Init() in HAL_USART_STATE_RESET - * to register callbacks for HAL_USART_MSPINIT_CB_ID and HAL_USART_MSPDEINIT_CB_ID - * @param husart usart handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID - * @arg @ref HAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID - * @arg @ref HAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_USART_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_USART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID - * @arg @ref HAL_USART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID - * @arg @ref HAL_USART_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status -+ */ -HAL_StatusTypeDef HAL_USART_RegisterCallback(USART_HandleTypeDef *husart, HAL_USART_CallbackIDTypeDef CallbackID, - pUSART_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - - if (husart->State == HAL_USART_STATE_READY) - { - switch (CallbackID) - { - case HAL_USART_TX_HALFCOMPLETE_CB_ID : - husart->TxHalfCpltCallback = pCallback; - break; - - case HAL_USART_TX_COMPLETE_CB_ID : - husart->TxCpltCallback = pCallback; - break; - - case HAL_USART_RX_HALFCOMPLETE_CB_ID : - husart->RxHalfCpltCallback = pCallback; - break; - - case HAL_USART_RX_COMPLETE_CB_ID : - husart->RxCpltCallback = pCallback; - break; - - case HAL_USART_TX_RX_COMPLETE_CB_ID : - husart->TxRxCpltCallback = pCallback; - break; - - case HAL_USART_ERROR_CB_ID : - husart->ErrorCallback = pCallback; - break; - - case HAL_USART_ABORT_COMPLETE_CB_ID : - husart->AbortCpltCallback = pCallback; - break; - - case HAL_USART_RX_FIFO_FULL_CB_ID : - husart->RxFifoFullCallback = pCallback; - break; - - case HAL_USART_TX_FIFO_EMPTY_CB_ID : - husart->TxFifoEmptyCallback = pCallback; - break; - - case HAL_USART_MSPINIT_CB_ID : - husart->MspInitCallback = pCallback; - break; - - case HAL_USART_MSPDEINIT_CB_ID : - husart->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (husart->State == HAL_USART_STATE_RESET) - { - switch (CallbackID) - { - case HAL_USART_MSPINIT_CB_ID : - husart->MspInitCallback = pCallback; - break; - - case HAL_USART_MSPDEINIT_CB_ID : - husart->MspDeInitCallback = pCallback; - break; - - default : - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister an USART Callback - * USART callaback is redirected to the weak predefined callback - * @note The HAL_USART_UnRegisterCallback() may be called before HAL_USART_Init() in HAL_USART_STATE_RESET - * to un-register callbacks for HAL_USART_MSPINIT_CB_ID and HAL_USART_MSPDEINIT_CB_ID - * @param husart usart handle - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID - * @arg @ref HAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID - * @arg @ref HAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID - * @arg @ref HAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID - * @arg @ref HAL_USART_ERROR_CB_ID Error Callback ID - * @arg @ref HAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID - * @arg @ref HAL_USART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID - * @arg @ref HAL_USART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID - * @arg @ref HAL_USART_MSPINIT_CB_ID MspInit Callback ID - * @arg @ref HAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, HAL_USART_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (HAL_USART_STATE_READY == husart->State) - { - switch (CallbackID) - { - case HAL_USART_TX_HALFCOMPLETE_CB_ID : - husart->TxHalfCpltCallback = HAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - break; - - case HAL_USART_TX_COMPLETE_CB_ID : - husart->TxCpltCallback = HAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ - break; - - case HAL_USART_RX_HALFCOMPLETE_CB_ID : - husart->RxHalfCpltCallback = HAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - break; - - case HAL_USART_RX_COMPLETE_CB_ID : - husart->RxCpltCallback = HAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ - break; - - case HAL_USART_TX_RX_COMPLETE_CB_ID : - husart->TxRxCpltCallback = HAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ - break; - - case HAL_USART_ERROR_CB_ID : - husart->ErrorCallback = HAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_USART_ABORT_COMPLETE_CB_ID : - husart->AbortCpltCallback = HAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_USART_RX_FIFO_FULL_CB_ID : - husart->RxFifoFullCallback = HAL_USARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ - break; - - case HAL_USART_TX_FIFO_EMPTY_CB_ID : - husart->TxFifoEmptyCallback = HAL_USARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ - break; - - case HAL_USART_MSPINIT_CB_ID : - husart->MspInitCallback = HAL_USART_MspInit; /* Legacy weak MspInitCallback */ - break; - - case HAL_USART_MSPDEINIT_CB_ID : - husart->MspDeInitCallback = HAL_USART_MspDeInit; /* Legacy weak MspDeInitCallback */ - break; - - default : - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else if (HAL_USART_STATE_RESET == husart->State) - { - switch (CallbackID) - { - case HAL_USART_MSPINIT_CB_ID : - husart->MspInitCallback = HAL_USART_MspInit; - break; - - case HAL_USART_MSPDEINIT_CB_ID : - husart->MspDeInitCallback = HAL_USART_MspDeInit; - break; - - default : - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - - -/** - * @} - */ - -/** @defgroup USART_Exported_Functions_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 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. - (++) 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 respectively 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 API's with DMA are : - (++) HAL_USART_Transmit_DMA() in simplex mode - (++) HAL_USART_Receive_DMA() in full duplex receive only - (++) HAL_USART_TransmitReceive_DMA() in full duplex mode - (++) HAL_USART_DMAPause() - (++) HAL_USART_DMAResume() - (++) HAL_USART_DMAStop() - - (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: - (++) HAL_USART_TxCpltCallback() - (++) HAL_USART_RxCpltCallback() - (++) HAL_USART_TxHalfCpltCallback() - (++) HAL_USART_RxHalfCpltCallback() - (++) HAL_USART_ErrorCallback() - (++) HAL_USART_TxRxCpltCallback() - - (#) Non-Blocking mode transfers could be aborted using Abort API's : - (++) HAL_USART_Abort() - (++) HAL_USART_Abort_IT() - - (#) For Abort services based on interrupts (HAL_USART_Abort_IT), a Abort Complete Callbacks is provided: - (++) HAL_USART_AbortCpltCallback() - - (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. - Errors are handled as follows : - (++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is - to be evaluated by user : this concerns Frame Error, - Parity Error or Noise Error in Interrupt mode reception . - Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify - error type, and HAL_USART_ErrorCallback() user callback is executed. - Transfer is kept ongoing on USART side. - If user wants to abort it, Abort services should be called by user. - (++) Error is considered as Blocking : Transfer could not be completed properly and is aborted. - This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. - Error code is set to allow user to identify error type, - and HAL_USART_ErrorCallback() user callback is executed. - -@endverbatim - * @{ - */ - -/** - * @brief Simplex send an amount of data in blocking mode. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must indicate the number - * of u16 provided through pTxData. - * @param husart USART handle. - * @param pTxData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be sent. - * @param Timeout Timeout duration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size, - uint32_t Timeout) -{ - const uint8_t *ptxdata8bits; - const uint16_t *ptxdata16bits; - uint32_t tickstart; - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pTxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->ErrorCode = HAL_USART_ERROR_NONE; - husart->State = HAL_USART_STATE_BUSY_TX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - husart->TxXferSize = Size; - husart->TxXferCount = Size; - - /* In case of 9bits/No Parity transfer, pTxData needs to be handled as a uint16_t pointer */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - ptxdata8bits = NULL; - ptxdata16bits = (const uint16_t *) pTxData; - } - else - { - ptxdata8bits = pTxData; - ptxdata16bits = NULL; - } - - /* Check the remaining data to be sent */ - while (husart->TxXferCount > 0U) - { - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - if (ptxdata8bits == NULL) - { - husart->Instance->TDR = (uint16_t)(*ptxdata16bits & 0x01FFU); - ptxdata16bits++; - } - else - { - husart->Instance->TDR = (uint8_t)(*ptxdata8bits & 0xFFU); - ptxdata8bits++; - } - - husart->TxXferCount--; - } - - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - - /* Clear Transmission Complete Flag */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); - - /* Clear overrun flag and discard the received data */ - __HAL_USART_CLEAR_OREFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - - /* At end of Tx process, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in blocking mode. - * @note To receive synchronous data, dummy data are simultaneously transmitted. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must indicate the number - * of u16 available through pRxData. - * @param husart USART handle. - * @param pRxData Pointer to data buffer (u8 or u16 data elements). - * @param Size Amount of data elements (u8 or u16) to be received. - * @param Timeout Timeout duration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) -{ - uint8_t *prxdata8bits; - uint16_t *prxdata16bits; - uint16_t uhMask; - uint32_t tickstart; - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pRxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->ErrorCode = HAL_USART_ERROR_NONE; - husart->State = HAL_USART_STATE_BUSY_RX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - husart->RxXferSize = Size; - husart->RxXferCount = Size; - - /* Computation of USART mask to apply to RDR register */ - USART_MASK_COMPUTATION(husart); - uhMask = husart->Mask; - - /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - prxdata8bits = NULL; - prxdata16bits = (uint16_t *) pRxData; - } - else - { - prxdata8bits = pRxData; - prxdata16bits = NULL; - } - - /* as long as data have to be received */ - while (husart->RxXferCount > 0U) - { - if (husart->SlaveMode == USART_SLAVEMODE_DISABLE) - { - /* Wait until TXE flag is set to send dummy byte in order to generate the - * clock for the slave to send data. - * Whatever the frame length (7, 8 or 9-bit long), the same dummy value - * can be written for all the cases. */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x0FF); - } - - /* Wait for RXNE Flag */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - - if (prxdata8bits == NULL) - { - *prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask); - prxdata16bits++; - } - else - { - *prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); - prxdata8bits++; - } - - husart->RxXferCount--; - - } - - /* Clear SPI slave underrun flag and discard transmit data */ - if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) - { - __HAL_USART_CLEAR_UDRFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* At end of Rx process, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Full-Duplex Send and Receive an amount of data in blocking mode. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number - * of u16 available through pTxData and through pRxData. - * @param husart USART handle. - * @param pTxData pointer to TX data buffer (u8 or u16 data elements). - * @param pRxData pointer to RX data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be sent (same amount to be received). - * @param Timeout Timeout duration. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, - uint16_t Size, uint32_t Timeout) -{ - uint8_t *prxdata8bits; - uint16_t *prxdata16bits; - const uint8_t *ptxdata8bits; - const uint16_t *ptxdata16bits; - uint16_t uhMask; - uint16_t rxdatacount; - uint32_t tickstart; - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->ErrorCode = HAL_USART_ERROR_NONE; - husart->State = HAL_USART_STATE_BUSY_RX; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - husart->RxXferSize = Size; - husart->TxXferSize = Size; - husart->TxXferCount = Size; - husart->RxXferCount = Size; - - /* Computation of USART mask to apply to RDR register */ - USART_MASK_COMPUTATION(husart); - uhMask = husart->Mask; - - /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - prxdata8bits = NULL; - ptxdata8bits = NULL; - ptxdata16bits = (const uint16_t *) pTxData; - prxdata16bits = (uint16_t *) pRxData; - } - else - { - prxdata8bits = pRxData; - ptxdata8bits = pTxData; - ptxdata16bits = NULL; - prxdata16bits = NULL; - } - - if ((husart->TxXferCount == 0x01U) || (husart->SlaveMode == USART_SLAVEMODE_ENABLE)) - { - /* Wait until TXE flag is set to send data */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - if (ptxdata8bits == NULL) - { - husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask); - ptxdata16bits++; - } - else - { - husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU)); - ptxdata8bits++; - } - - husart->TxXferCount--; - } - - /* Check the remain data to be sent */ - /* rxdatacount is a temporary variable for MISRAC2012-Rule-13.5 */ - rxdatacount = husart->RxXferCount; - while ((husart->TxXferCount > 0U) || (rxdatacount > 0U)) - { - if (husart->TxXferCount > 0U) - { - /* Wait until TXE flag is set to send data */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - if (ptxdata8bits == NULL) - { - husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask); - ptxdata16bits++; - } - else - { - husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU)); - ptxdata8bits++; - } - - husart->TxXferCount--; - } - - if (husart->RxXferCount > 0U) - { - /* Wait for RXNE Flag */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { - return HAL_TIMEOUT; - } - - if (prxdata8bits == NULL) - { - *prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask); - prxdata16bits++; - } - else - { - *prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); - prxdata8bits++; - } - - husart->RxXferCount--; - } - rxdatacount = husart->RxXferCount; - } - - /* At end of TxRx process, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Send an amount of data in interrupt mode. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must indicate the number - * of u16 provided through pTxData. - * @param husart USART handle. - * @param pTxData pointer to data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size) -{ - if (husart->State == HAL_USART_STATE_READY) - { - if ((pTxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->pTxBuffPtr = pTxData; - husart->TxXferSize = Size; - husart->TxXferCount = Size; - husart->TxISR = NULL; - - 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" */ - - /* Configure Tx interrupt processing */ - if (husart->FifoMode == USART_FIFOMODE_ENABLE) - { - /* Set the Tx ISR function pointer according to the data word length */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - husart->TxISR = USART_TxISR_16BIT_FIFOEN; - } - else - { - husart->TxISR = USART_TxISR_8BIT_FIFOEN; - } - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the TX FIFO threshold interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TXFT); - } - else - { - /* Set the Tx ISR function pointer according to the data word length */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - husart->TxISR = USART_TxISR_16BIT; - } - else - { - husart->TxISR = USART_TxISR_8BIT; - } - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Transmit Data Register Empty Interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TXE); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in interrupt mode. - * @note To receive synchronous data, dummy data are simultaneously transmitted. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must indicate the number - * of u16 available through pRxData. - * @param husart USART handle. - * @param pRxData pointer to data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) -{ - uint16_t nb_dummy_data; - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pRxData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->pRxBuffPtr = pRxData; - husart->RxXferSize = Size; - husart->RxXferCount = Size; - husart->RxISR = NULL; - - USART_MASK_COMPUTATION(husart); - - husart->ErrorCode = HAL_USART_ERROR_NONE; - husart->State = HAL_USART_STATE_BUSY_RX; - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Configure Rx interrupt processing */ - if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) - { - /* Set the Rx ISR function pointer according to the data word length */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - husart->RxISR = USART_RxISR_16BIT_FIFOEN; - } - else - { - husart->RxISR = USART_RxISR_8BIT_FIFOEN; - } - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Parity Error interrupt and RX FIFO Threshold interrupt */ - if (husart->Init.Parity != USART_PARITY_NONE) - { - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - } - SET_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); - } - else - { - /* Set the Rx ISR function pointer according to the data word length */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - husart->RxISR = USART_RxISR_16BIT; - } - else - { - husart->RxISR = USART_RxISR_8BIT; - } - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Parity Error and Data Register not empty Interrupts */ - if (husart->Init.Parity != USART_PARITY_NONE) - { - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); - } - else - { - SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - } - - if (husart->SlaveMode == USART_SLAVEMODE_DISABLE) - { - /* Send dummy data in order to generate the clock for the Slave to send the next data. - When FIFO mode is disabled only one data must be transferred. - When FIFO mode is enabled data must be transmitted until the RX FIFO reaches its threshold. - */ - if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) - { - for (nb_dummy_data = husart->NbRxDataToProcess ; nb_dummy_data > 0U ; nb_dummy_data--) - { - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - } - else - { - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Full-Duplex Send and Receive an amount of data in interrupt mode. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number - * of u16 available through pTxData and through pRxData. - * @param husart USART handle. - * @param pTxData pointer to TX data buffer (u8 or u16 data elements). - * @param pRxData pointer to RX data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be sent (same amount to be received). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, - uint16_t Size) -{ - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - 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; - - /* Computation of USART mask to apply to RDR register */ - USART_MASK_COMPUTATION(husart); - - husart->ErrorCode = HAL_USART_ERROR_NONE; - husart->State = HAL_USART_STATE_BUSY_TX_RX; - - /* Configure TxRx interrupt processing */ - if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) - { - /* Set the Rx ISR function pointer according to the data word length */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - husart->TxISR = USART_TxISR_16BIT_FIFOEN; - husart->RxISR = USART_RxISR_16BIT_FIFOEN; - } - else - { - husart->TxISR = USART_TxISR_8BIT_FIFOEN; - husart->RxISR = USART_RxISR_8BIT_FIFOEN; - } - - /* Process Locked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - if (husart->Init.Parity != USART_PARITY_NONE) - { - /* Enable the USART Parity Error interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - } - - /* Enable the TX and RX FIFO Threshold interrupts */ - SET_BIT(husart->Instance->CR3, (USART_CR3_TXFTIE | USART_CR3_RXFTIE)); - } - else - { - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - husart->TxISR = USART_TxISR_16BIT; - husart->RxISR = USART_RxISR_16BIT; - } - else - { - husart->TxISR = USART_TxISR_8BIT; - husart->RxISR = USART_RxISR_8BIT; - } - - /* Process Locked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Enable the USART Parity Error and USART Data Register not empty Interrupts */ - if (husart->Init.Parity != USART_PARITY_NONE) - { - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); - } - else - { - SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - } - - /* Enable the USART Transmit Data Register Empty Interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @brief Send an amount of data in DMA mode. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data is handled as a set of u16. In this case, Size must indicate the number - * of u16 provided through pTxData. - * @param husart USART handle. - * @param pTxData pointer to data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size) -{ - HAL_StatusTypeDef status = HAL_OK; - const uint32_t *tmp; - uint16_t nbByte = Size; - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pTxData == NULL) || (Size == 0U)) - { - 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; - - if (husart->hdmatx != NULL) - { - /* 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; - - /* In case of 9bits/No Parity transfer, pTxData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - tmp = (const uint32_t *)&pTxData; - - /* Check linked list mode */ - if ((husart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((husart->hdmatx->LinkedListQueue != NULL) && (husart->hdmatx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = *(const uint32_t *)tmp; - - /* Set DMA destination address */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&husart->Instance->TDR; - - /* Enable the USART transmit DMA channel */ - status = HAL_DMAEx_List_Start_IT(husart->hdmatx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the USART transmit DMA channel */ - status = HAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, nbByte); - } - } - - if (status == HAL_OK) - { - /* Clear the TC flag in the ICR register */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the USART CR3 register */ - SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - return HAL_OK; - } - else - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Restore husart->State to ready */ - husart->State = HAL_USART_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Receive an amount of data in DMA mode. - * @note When the USART parity is enabled (PCE = 1), the received data contain - * the parity bit (MSB position). - * @note The USART DMA transmit channel must be configured in order to generate the clock for the slave. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the received data is handled as a set of u16. In this case, Size must indicate the number - * of u16 available through pRxData. - * @param husart USART handle. - * @param pRxData pointer to data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be received. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t *tmp = (uint32_t *)&pRxData; - uint16_t nbByte = Size; - - /* Check that a Rx process is not already ongoing */ - if (husart->State == HAL_USART_STATE_READY) - { - if ((pRxData == NULL) || (Size == 0U)) - { - 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; - - if (husart->hdmarx != NULL) - { - /* 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; - - /* In case of 9bits/No Parity transfer, pTxData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - /* Check linked list mode */ - if ((husart->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((husart->hdmarx->LinkedListQueue != NULL) && (husart->hdmarx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)&husart->Instance->RDR; - - /* Set DMA destination address */ - husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = *(uint32_t *)tmp; - - /* Enable the USART receive DMA channel */ - status = HAL_DMAEx_List_Start_IT(husart->hdmarx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the USART receive DMA channel */ - status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t *)tmp, nbByte); - } - } - - if ((status == HAL_OK) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Enable the USART transmit DMA channel: the transmit channel 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 mode */ - - /* Set the USART DMA Tx Complete and Error callback to Null */ - if (husart->hdmatx != NULL) - { - husart->hdmatx->XferErrorCallback = NULL; - husart->hdmatx->XferHalfCpltCallback = NULL; - husart->hdmatx->XferCpltCallback = NULL; - - /* Check linked list mode */ - if ((husart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((husart->hdmatx->LinkedListQueue != NULL) && (husart->hdmatx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = *(uint32_t *)tmp; - - /* Set DMA destination address */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&husart->Instance->TDR; - - /* Enable the USART transmit DMA channel */ - status = HAL_DMAEx_List_Start_IT(husart->hdmatx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, nbByte); - } - } - } - - if (status == HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - if (husart->Init.Parity != USART_PARITY_NONE) - { - /* Enable the USART Parity Error Interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - } - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the USART CR3 register */ - SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the USART CR3 register */ - SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - return HAL_OK; - } - else - { - if ((husart->hdmarx != NULL) && ((husart->hdmarx->Mode & DMA_LINKEDLIST) != DMA_LINKEDLIST)) - { - status = HAL_DMA_Abort(husart->hdmarx); - } - - /* No need to check on error code */ - UNUSED(status); - - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Restore husart->State to ready */ - husart->State = HAL_USART_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Full-Duplex Transmit Receive an amount of data in non-blocking mode. - * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. - * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), - * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number - * of u16 available through pTxData and through pRxData. - * @param husart USART handle. - * @param pTxData pointer to TX data buffer (u8 or u16 data elements). - * @param pRxData pointer to RX data buffer (u8 or u16 data elements). - * @param Size amount of data elements (u8 or u16) to be received/sent. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, - uint16_t Size) -{ - HAL_StatusTypeDef status; - const uint32_t *tmp; - uint16_t nbByte = Size; - - if (husart->State == HAL_USART_STATE_READY) - { - if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - 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; - - if ((husart->hdmarx != NULL) && (husart->hdmatx != NULL)) - { - /* 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; - - /* In case of 9bits/No Parity transfer, pTxData buffer provided as input parameter - should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ - if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) - { - nbByte = Size * 2U; - } - - /* Check linked list mode */ - tmp = (uint32_t *)&pRxData; - if ((husart->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((husart->hdmarx->LinkedListQueue != NULL) && (husart->hdmarx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = - (uint32_t)&husart->Instance->RDR; - - /* Set DMA destination address */ - husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = *(const uint32_t *)tmp; - - /* Enable the USART receive DMA channel */ - status = HAL_DMAEx_List_Start_IT(husart->hdmarx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - /* Enable the USART receive DMA channel */ - status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(const uint32_t *)tmp, nbByte); - } - - /* Enable the USART transmit DMA channel */ - if (status == HAL_OK) - { - tmp = (const uint32_t *)&pTxData; - - /* Check linked list mode */ - if ((husart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if ((husart->hdmatx->LinkedListQueue != NULL) && (husart->hdmatx->LinkedListQueue->Head != NULL)) - { - /* Set DMA data size */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; - - /* Set DMA source address */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = *(const uint32_t *)tmp; - - /* Set DMA destination address */ - husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = - (uint32_t)&husart->Instance->TDR; - - /* Enable the USART transmit DMA channel */ - status = HAL_DMAEx_List_Start_IT(husart->hdmatx); - } - else - { - /* Update status */ - status = HAL_ERROR; - } - } - else - { - status = HAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, nbByte); - } - } - } - else - { - status = HAL_ERROR; - } - - if (status == HAL_OK) - { - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - if (husart->Init.Parity != USART_PARITY_NONE) - { - /* Enable the USART Parity Error Interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - } - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Clear the TC flag in the ICR register */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the USART CR3 register */ - SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the USART CR3 register */ - SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - return HAL_OK; - } - else - { - if ((husart->hdmarx != NULL) && ((husart->hdmarx->Mode & DMA_LINKEDLIST) != DMA_LINKEDLIST)) - { - status = HAL_DMA_Abort(husart->hdmarx); - } - - /* No need to check on error code */ - UNUSED(status); - - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Restore husart->State to ready */ - husart->State = HAL_USART_STATE_READY; - - return HAL_ERROR; - } - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Pause the DMA Transfer. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - - /* Process Locked */ - __HAL_LOCK(husart); - - if ((HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) && - (state == HAL_USART_STATE_BUSY_TX)) - { - /* Suspend the USART DMA Tx channel : use blocking DMA Suspend API (no callback) */ - if (husart->hdmatx != NULL) - { - /* Set the USART DMA Suspend callback to Null. - No call back execution at end of DMA Suspend procedure */ - husart->hdmatx->XferSuspendCallback = NULL; - - if (HAL_DMAEx_Suspend(husart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - else if ((state == HAL_USART_STATE_BUSY_RX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Set the USART DMA Suspend callback to Null. - No call back execution at end of DMA Suspend procedure */ - husart->hdmarx->XferSuspendCallback = NULL; - - if (HAL_DMAEx_Suspend(husart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - - if (state == HAL_USART_STATE_BUSY_TX_RX) - { - /* Set the USART DMA Suspend callback to Null. - No call back execution at end of DMA Suspend procedure */ - husart->hdmatx->XferSuspendCallback = NULL; - - if (HAL_DMAEx_Suspend(husart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Resume the DMA Transfer. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - - /* Process Locked */ - __HAL_LOCK(husart); - - if (state == HAL_USART_STATE_BUSY_TX) - { - /* Resume the USART DMA Tx channel */ - if (husart->hdmatx != NULL) - { - if (HAL_DMAEx_Resume(husart->hdmatx) != HAL_OK) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_ERROR; - } - } - } - else if ((state == HAL_USART_STATE_BUSY_RX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - /* Clear the Overrun flag before resuming the Rx transfer*/ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF); - - /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ - if (husart->Init.Parity != USART_PARITY_NONE) - { - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - } - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Resume the USART DMA Rx channel */ - if (husart->hdmarx != NULL) - { - if (HAL_DMAEx_Resume(husart->hdmarx) != HAL_OK) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_ERROR; - } - } - - if (state == HAL_USART_STATE_BUSY_TX_RX) - { - /* Resume the USART DMA Tx channel */ - if (husart->hdmatx != NULL) - { - if (HAL_DMAEx_Resume(husart->hdmatx) != HAL_OK) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_ERROR; - } - } - } - } - else - { - /* Nothing to do */ - } - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Stop the DMA Transfer. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart) -{ - /* The Lock is not implemented on this API to allow the user application - to call the HAL USART API under callbacks HAL_USART_TxCpltCallback() / HAL_USART_RxCpltCallback() / - HAL_USART_TxHalfCpltCallback / HAL_USART_RxHalfCpltCallback: - indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete - interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of - the stream and the corresponding call back is executed. */ - - /* Disable the USART Tx/Rx DMA requests */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the USART DMA tx channel */ - if (husart->hdmatx != NULL) - { - if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - /* Abort the USART DMA rx channel */ - if (husart->hdmarx != NULL) - { - if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - - USART_EndTransfer(husart); - husart->State = HAL_USART_STATE_READY; - - return HAL_OK; -} -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Abort ongoing transfers (blocking mode). - * @param husart USART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable USART Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Abort(USART_HandleTypeDef *husart) -{ - /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | - USART_CR1_TCIE)); - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the USART DMA Tx channel if enabled */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable the USART DMA Tx request if enabled */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the USART DMA Tx channel : use blocking DMA Abort API (no callback) */ - if (husart->hdmatx != NULL) - { - /* Set the USART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - husart->hdmatx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } - - /* Abort the USART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the USART DMA Rx request if enabled */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the USART DMA Rx channel : use blocking DMA Abort API (no callback) */ - if (husart->hdmarx != NULL) - { - /* Set the USART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - husart->hdmarx->XferAbortCallback = NULL; - - if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK) - { - if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) - { - /* Set error code to DMA */ - husart->ErrorCode = HAL_USART_ERROR_DMA; - - return HAL_TIMEOUT; - } - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* Reset Tx and Rx transfer counters */ - husart->TxXferCount = 0U; - husart->RxXferCount = 0U; - - /* Clear the Error flags in the ICR register */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); - - /* Flush the whole TX FIFO (if needed) */ - if (husart->FifoMode == USART_FIFOMODE_ENABLE) - { - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* Discard the received data */ - __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); - - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Reset Handle ErrorCode to No Error */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (Interrupt mode). - * @param husart USART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable USART Interrupts (Tx and Rx) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USART_Abort_IT(USART_HandleTypeDef *husart) -{ - uint32_t abortcplt = 1U; - - /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | - USART_CR1_TCIE)); - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* If DMA Tx and/or DMA Rx Handles are associated to USART Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if (husart->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if USART DMA Tx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) - { - husart->hdmatx->XferAbortCallback = USART_DMATxAbortCallback; - } - else - { - husart->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if (husart->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if USART DMA Rx request if enabled. - Otherwise, set it to NULL */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - husart->hdmarx->XferAbortCallback = USART_DMARxAbortCallback; - } - else - { - husart->hdmarx->XferAbortCallback = NULL; - } - } - - /* Abort the USART DMA Tx channel if enabled */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at USART level */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the USART DMA Tx channel : use non blocking DMA Abort API (callback) */ - if (husart->hdmatx != NULL) - { - /* USART Tx DMA Abort callback has already been initialised : - will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(husart->hdmatx) != HAL_OK) - { - husart->hdmatx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } - } - } - - /* Abort the USART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the USART DMA Rx request if enabled */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the USART DMA Rx channel : use non blocking DMA Abort API (callback) */ - if (husart->hdmarx != NULL) - { - /* USART Rx DMA Abort callback has already been initialised : - will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) - { - husart->hdmarx->XferAbortCallback = NULL; - abortcplt = 1U; - } - else - { - abortcplt = 0U; - } - } - } -#endif /* HAL_DMA_MODULE_ENABLED */ - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if (abortcplt == 1U) - { - /* Reset Tx and Rx transfer counters */ - husart->TxXferCount = 0U; - husart->RxXferCount = 0U; - - /* Reset errorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); - - /* Flush the whole TX FIFO (if needed) */ - if (husart->FifoMode == USART_FIFOMODE_ENABLE) - { - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* Discard the received data */ - __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); - - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Complete Callback */ - husart->AbortCpltCallback(husart); -#else - /* Call legacy weak Abort Complete Callback */ - HAL_USART_AbortCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - - return HAL_OK; -} - -/** - * @brief Handle USART interrupt request. - * @param husart USART handle. - * @retval None - */ -void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) -{ - uint32_t isrflags = READ_REG(husart->Instance->ISR); - uint32_t cr1its = READ_REG(husart->Instance->CR1); - uint32_t cr3its = READ_REG(husart->Instance->CR3); - - uint32_t errorflags; - uint32_t errorcode; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF | - USART_ISR_UDR)); - if (errorflags == 0U) - { - /* USART in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U))) - { - if (husart->RxISR != NULL) - { - husart->RxISR(husart); - } - return; - } - } - - /* If some errors occur */ - if ((errorflags != 0U) - && (((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) - || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U))) - { - /* USART parity error interrupt occurred -------------------------------------*/ - if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) - { - __HAL_USART_CLEAR_IT(husart, USART_CLEAR_PEF); - - husart->ErrorCode |= HAL_USART_ERROR_PE; - } - - /* USART frame error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_USART_CLEAR_IT(husart, USART_CLEAR_FEF); - - husart->ErrorCode |= HAL_USART_ERROR_FE; - } - - /* USART noise error interrupt occurred --------------------------------------*/ - if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - __HAL_USART_CLEAR_IT(husart, USART_CLEAR_NEF); - - husart->ErrorCode |= HAL_USART_ERROR_NE; - } - - /* USART Over-Run interrupt occurred -----------------------------------------*/ - if (((isrflags & USART_ISR_ORE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || - ((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U))) - { - __HAL_USART_CLEAR_IT(husart, USART_CLEAR_OREF); - - husart->ErrorCode |= HAL_USART_ERROR_ORE; - } - - /* USART Receiver Timeout interrupt occurred ---------------------------------*/ - if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) - { - __HAL_USART_CLEAR_IT(husart, USART_CLEAR_RTOF); - - husart->ErrorCode |= HAL_USART_ERROR_RTO; - } - - /* USART SPI slave underrun error interrupt occurred -------------------------*/ - if (((isrflags & USART_ISR_UDR) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) - { - /* Ignore SPI slave underrun errors when reception is going on */ - if (husart->State == HAL_USART_STATE_BUSY_RX) - { - __HAL_USART_CLEAR_UDRFLAG(husart); - return; - } - else - { - __HAL_USART_CLEAR_UDRFLAG(husart); - husart->ErrorCode |= HAL_USART_ERROR_UDR; - } - } - - /* Call USART Error Call back function if need be --------------------------*/ - if (husart->ErrorCode != HAL_USART_ERROR_NONE) - { - /* USART in mode Receiver ---------------------------------------------------*/ - if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) - && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) - || ((cr3its & USART_CR3_RXFTIE) != 0U))) - { - if (husart->RxISR != NULL) - { - husart->RxISR(husart); - } - } - - /* If Overrun error occurs, or if any error occurs in DMA mode reception, - consider error as blocking */ - errorcode = husart->ErrorCode & HAL_USART_ERROR_ORE; - if ((HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) || - (errorcode != 0U)) - { - /* Blocking error : transfer is aborted - Set the USART state ready to be able to start again the process, - Disable Interrupts, and disable DMA requests, if ongoing */ - USART_EndTransfer(husart); - -#if defined(HAL_DMA_MODULE_ENABLED) - /* Abort the USART DMA Rx channel if enabled */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - /* Disable the USART DMA Rx request if enabled */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR | USART_CR3_DMAR); - - /* Abort the USART DMA Tx channel */ - if (husart->hdmatx != NULL) - { - /* Set the USART Tx DMA Abort callback to NULL : no callback - executed at end of DMA abort procedure */ - husart->hdmatx->XferAbortCallback = NULL; - - /* Abort DMA TX */ - (void)HAL_DMA_Abort_IT(husart->hdmatx); - } - - /* Abort the USART DMA Rx channel */ - if (husart->hdmarx != NULL) - { - /* Set the USART Rx DMA Abort callback : - will lead to call HAL_USART_ErrorCallback() at end of DMA abort procedure */ - husart->hdmarx->XferAbortCallback = USART_DMAAbortOnError; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) - { - /* Call Directly husart->hdmarx->XferAbortCallback function in case of error */ - husart->hdmarx->XferAbortCallback(husart->hdmarx); - } - } - else - { - /* Call user error callback */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Error Callback */ - husart->ErrorCallback(husart); -#else - /* Call legacy weak Error Callback */ - HAL_USART_ErrorCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - } - else -#endif /* HAL_DMA_MODULE_ENABLED */ - { - /* Call user error callback */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Error Callback */ - husart->ErrorCallback(husart); -#else - /* Call legacy weak Error Callback */ - HAL_USART_ErrorCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Error Callback */ - husart->ErrorCallback(husart); -#else - /* Call legacy weak Error Callback */ - HAL_USART_ErrorCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - } - } - return; - - } /* End if some error occurs */ - - - /* USART in mode Transmitter ------------------------------------------------*/ - if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) - && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) - || ((cr3its & USART_CR3_TXFTIE) != 0U))) - { - if (husart->TxISR != NULL) - { - husart->TxISR(husart); - } - return; - } - - /* USART in mode Transmitter (transmission end) -----------------------------*/ - if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) - { - USART_EndTransmit_IT(husart); - return; - } - - /* USART TX Fifo Empty occurred ----------------------------------------------*/ - if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Fifo Empty Callback */ - husart->TxFifoEmptyCallback(husart); -#else - /* Call legacy weak Tx Fifo Empty Callback */ - HAL_USARTEx_TxFifoEmptyCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - return; - } - - /* USART RX Fifo Full occurred ----------------------------------------------*/ - if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Fifo Full Callback */ - husart->RxFifoFullCallback(husart); -#else - /* Call legacy weak Rx Fifo Full Callback */ - HAL_USARTEx_RxFifoFullCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - return; - } -} - -/** - * @brief Tx Transfer completed callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_TxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Tx Half Transfer completed callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_TxHalfCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_RxCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief Rx Half Transfer completed callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_RxHalfCpltCallback can 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) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_TxRxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief USART error callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_ErrorCallback can be implemented in the user file. - */ -} - -/** - * @brief USART Abort Complete callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_AbortCpltCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup USART_Exported_Functions_Group4 Peripheral State and Error functions - * @brief USART Peripheral State and Error functions - * -@verbatim - ============================================================================== - ##### Peripheral State and Error functions ##### - ============================================================================== - [..] - This subsection provides functions allowing to : - (+) Return the USART handle state - (+) Return the USART handle error code - -@endverbatim - * @{ - */ - - -/** - * @brief Return the USART handle state. - * @param husart pointer to a USART_HandleTypeDef structure that contains - * the configuration information for the specified USART. - * @retval USART handle state - */ -HAL_USART_StateTypeDef HAL_USART_GetState(const 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 handle Error Code - */ -uint32_t HAL_USART_GetError(const USART_HandleTypeDef *husart) -{ - return husart->ErrorCode; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup USART_Private_Functions USART Private Functions - * @{ - */ - -/** - * @brief Initialize the callbacks to their default values. - * @param husart USART handle. - * @retval none - */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) -void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart) -{ - /* Init the USART Callback settings */ - husart->TxHalfCpltCallback = HAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ - husart->TxCpltCallback = HAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ - husart->RxHalfCpltCallback = HAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ - husart->RxCpltCallback = HAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ - husart->TxRxCpltCallback = HAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ - husart->ErrorCallback = HAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ - husart->AbortCpltCallback = HAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - husart->RxFifoFullCallback = HAL_USARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ - husart->TxFifoEmptyCallback = HAL_USARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ -} -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - -/** - * @brief End ongoing transfer on USART peripheral (following error detection or Transfer completion). - * @param husart USART handle. - * @retval None - */ -static void USART_EndTransfer(USART_HandleTypeDef *husart) -{ - /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | - USART_CR1_TCIE)); - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); - - /* At end of process, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; -} - -#if defined(HAL_DMA_MODULE_ENABLED) -/** - * @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 *)(hdma->Parent); - - /* Check if DMA in circular mode */ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - husart->TxXferCount = 0U; - - if (husart->State == HAL_USART_STATE_BUSY_TX) - { - /* Disable the DMA transfer for transmit request by resetting the DMAT bit - in the USART CR3 register */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - /* Enable the USART Transmit Complete Interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TC); - } - } - /* DMA Circular mode */ - else - { - if (husart->State == HAL_USART_STATE_BUSY_TX) - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Complete Callback */ - husart->TxCpltCallback(husart); -#else - /* Call legacy weak Tx Complete Callback */ - HAL_USART_TxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - } -} - -/** - * @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 *)(hdma->Parent); - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Half Complete Callback */ - husart->TxHalfCpltCallback(husart); -#else - /* Call legacy weak Tx Half Complete Callback */ - HAL_USART_TxHalfCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ -} - -/** - * @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 *)(hdma->Parent); - - /* Check if DMA in circular mode*/ - if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) - { - husart->RxXferCount = 0U; - - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Disable the DMA RX transfer for the receiver request by resetting the DMAR bit - in USART CR3 register */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - /* similarly, disable the DMA TX transfer that was started to provide the - clock to the slave device */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - if (husart->State == HAL_USART_STATE_BUSY_RX) - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Complete Callback */ - husart->RxCpltCallback(husart); -#else - /* Call legacy weak Rx Complete Callback */ - HAL_USART_RxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ - else - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - husart->State = HAL_USART_STATE_READY; - } - /* DMA circular mode */ - else - { - if (husart->State == HAL_USART_STATE_BUSY_RX) - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Complete Callback */ - husart->RxCpltCallback(husart); -#else - /* Call legacy weak Rx Complete Callback */ - HAL_USART_RxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ - else - { -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - } -} - -/** - * @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 *)(hdma->Parent); - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Half Complete Callback */ - husart->RxHalfCpltCallback(husart); -#else - /* Call legacy weak Rx Half Complete Callback */ - HAL_USART_RxHalfCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA USART communication error callback. - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMAError(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); - - husart->RxXferCount = 0U; - husart->TxXferCount = 0U; - USART_EndTransfer(husart); - - husart->ErrorCode |= HAL_USART_ERROR_DMA; - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Error Callback */ - husart->ErrorCallback(husart); -#else - /* Call legacy weak Error Callback */ - HAL_USART_ErrorCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA USART communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); - husart->RxXferCount = 0U; - husart->TxXferCount = 0U; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Error Callback */ - husart->ErrorCallback(husart); -#else - /* Call legacy weak Error Callback */ - HAL_USART_ErrorCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA USART Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); - - husart->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (husart->hdmarx != NULL) - { - if (husart->hdmarx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - husart->TxXferCount = 0U; - husart->RxXferCount = 0U; - - /* Reset errorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); - - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Complete Callback */ - husart->AbortCpltCallback(husart); -#else - /* Call legacy weak Abort Complete Callback */ - HAL_USART_AbortCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - -} - - -/** - * @brief DMA USART Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); - - husart->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if (husart->hdmatx != NULL) - { - if (husart->hdmatx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - husart->TxXferCount = 0U; - husart->RxXferCount = 0U; - - /* Reset errorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - - /* Clear the Error flags in the ICR register */ - __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); - - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Call user Abort complete callback */ -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Abort Complete Callback */ - husart->AbortCpltCallback(husart); -#else - /* Call legacy weak Abort Complete Callback */ - HAL_USART_AbortCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ -} - -#endif /* HAL_DMA_MODULE_ENABLED */ - -/** - * @brief Handle USART Communication Timeout. It waits - * until a flag is no longer in the specified status. - * @param husart USART handle. - * @param Flag Specifies the USART flag to check. - * @param Status the actual Flag status (SET or RESET). - * @param Tickstart Tick start value - * @param Timeout timeout duration. - * @retval HAL status - */ -static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, - uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is set */ - while ((__HAL_USART_GET_FLAG(husart, Flag) ? SET : RESET) == Status) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief Configure the USART peripheral. - * @param husart USART handle. - * @retval HAL status - */ -static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart) -{ - uint32_t tmpreg; - USART_ClockSourceTypeDef clocksource; - HAL_StatusTypeDef ret = HAL_OK; - uint16_t brrtemp; - uint32_t usartdiv = 0x00000000; - uint32_t pclk; - - /* Check the parameters */ - 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)); - assert_param(IS_USART_PRESCALER(husart->Init.ClockPrescaler)); - - /*-------------------------- USART CR1 Configuration -----------------------*/ - /* Clear M, PCE, PS, TE and RE bits and 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 - * force OVER8 to 1 to allow to reach the maximum speed (Fclock/8) */ - tmpreg = (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode | USART_CR1_OVER8; - MODIFY_REG(husart->Instance->CR1, USART_CR1_FIELDS, tmpreg); - - /*---------------------------- USART CR2 Configuration ---------------------*/ - /* Clear and configure the USART Clock, CPOL, CPHA, LBCL STOP and SLVEN bits: - * 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 (used in SPI master mode only) - * set STOP[13:12] bits according to husart->Init.StopBits value */ - tmpreg = (uint32_t)(USART_CLOCK_ENABLE); - tmpreg |= (uint32_t)husart->Init.CLKLastBit; - tmpreg |= ((uint32_t)husart->Init.CLKPolarity | (uint32_t)husart->Init.CLKPhase); - tmpreg |= (uint32_t)husart->Init.StopBits; - MODIFY_REG(husart->Instance->CR2, USART_CR2_FIELDS, tmpreg); - - /*-------------------------- USART PRESC Configuration -----------------------*/ - /* Configure - * - USART Clock Prescaler : set PRESCALER according to husart->Init.ClockPrescaler value */ - MODIFY_REG(husart->Instance->PRESC, USART_PRESC_PRESCALER, husart->Init.ClockPrescaler); - - /*-------------------------- USART BRR Configuration -----------------------*/ - /* BRR is filled-up according to OVER8 bit setting which is forced to 1 */ - USART_GETCLOCKSOURCE(husart, clocksource); - - switch (clocksource) - { - case USART_CLOCKSOURCE_PCLK1: - pclk = HAL_RCC_GetPCLK1Freq(); - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - break; - case USART_CLOCKSOURCE_PCLK2: - pclk = HAL_RCC_GetPCLK2Freq(); - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - break; - case USART_CLOCKSOURCE_PLL2Q: - pclk = HAL_RCC_GetPLL2QFreq(); - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - break; - case USART_CLOCKSOURCE_PLL3Q: - pclk = HAL_RCC_GetPLL3QFreq(); - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - break; - case USART_CLOCKSOURCE_HSI: - if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) - { - usartdiv = (uint32_t)(USART_DIV_SAMPLING8((HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)), - husart->Init.BaudRate, husart->Init.ClockPrescaler)); - } - else - { - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(HSI_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - } - break; - case USART_CLOCKSOURCE_CSI: - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(CSI_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - break; - case USART_CLOCKSOURCE_LSE: - usartdiv = (uint32_t)(USART_DIV_SAMPLING8(LSE_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); - break; - default: - ret = HAL_ERROR; - break; - } - - /* USARTDIV must be greater than or equal to 0d16 and smaller than or equal to ffff */ - if ((usartdiv >= USART_BRR_MIN) && (usartdiv <= USART_BRR_MAX)) - { - brrtemp = (uint16_t)(usartdiv & 0xFFF0U); - brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U); - husart->Instance->BRR = brrtemp; - } - else - { - ret = HAL_ERROR; - } - - /* Initialize the number of data to process during RX/TX ISR execution */ - husart->NbTxDataToProcess = 1U; - husart->NbRxDataToProcess = 1U; - - /* Clear ISR function pointers */ - husart->RxISR = NULL; - husart->TxISR = NULL; - - return ret; -} - -/** - * @brief Check the USART Idle State. - * @param husart USART handle. - * @retval HAL status - */ -static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart) -{ - uint32_t tickstart; - - /* Initialize the USART ErrorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - - /* Init tickstart for timeout management */ - tickstart = HAL_GetTick(); - - /* Check if the Transmitter is enabled */ - if ((husart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) - { - /* Wait until TEACK flag is set */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_ISR_TEACK, RESET, tickstart, USART_TEACK_REACK_TIMEOUT) != HAL_OK) - { - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - /* Check if the Receiver is enabled */ - if ((husart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) - { - /* Wait until REACK flag is set */ - if (USART_WaitOnFlagUntilTimeout(husart, USART_ISR_REACK, RESET, tickstart, USART_TEACK_REACK_TIMEOUT) != HAL_OK) - { - /* Timeout occurred */ - return HAL_TIMEOUT; - } - } - - /* Initialize the USART state*/ - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Simplex send an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Transmit_IT(). - * @note The USART errors are not managed to avoid the overrun error. - * @note ISR function executed when FIFO mode is disabled and when the - * data word length is less than 9 bits long. - * @param husart USART handle. - * @retval None - */ -static void USART_TxISR_8BIT(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - - /* Check that a Tx process is ongoing */ - if ((state == HAL_USART_STATE_BUSY_TX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - if (husart->TxXferCount == 0U) - { - /* Disable the USART Transmit data register empty interrupt */ - __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); - - /* Enable the USART Transmit Complete Interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TC); - } - else - { - husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr & (uint8_t)0xFF); - husart->pTxBuffPtr++; - husart->TxXferCount--; - } - } -} - -/** - * @brief Simplex send an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Transmit_IT(). - * @note The USART errors are not managed to avoid the overrun error. - * @note ISR function executed when FIFO mode is disabled and when the - * data word length is 9 bits long. - * @param husart USART handle. - * @retval None - */ -static void USART_TxISR_16BIT(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - const uint16_t *tmp; - - if ((state == HAL_USART_STATE_BUSY_TX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - if (husart->TxXferCount == 0U) - { - /* Disable the USART Transmit data register empty interrupt */ - __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); - - /* Enable the USART Transmit Complete Interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TC); - } - else - { - tmp = (const uint16_t *) husart->pTxBuffPtr; - husart->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); - husart->pTxBuffPtr += 2U; - husart->TxXferCount--; - } - } -} - -/** - * @brief Simplex send an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Transmit_IT(). - * @note The USART errors are not managed to avoid the overrun error. - * @note ISR function executed when FIFO mode is enabled and when the - * data word length is less than 9 bits long. - * @param husart USART handle. - * @retval None - */ -static void USART_TxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - uint16_t nb_tx_data; - - /* Check that a Tx process is ongoing */ - if ((state == HAL_USART_STATE_BUSY_TX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - for (nb_tx_data = husart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) - { - if (husart->TxXferCount == 0U) - { - /* Disable the TX FIFO threshold interrupt */ - __HAL_USART_DISABLE_IT(husart, USART_IT_TXFT); - - /* Enable the USART Transmit Complete Interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TC); - - break; /* force exit loop */ - } - else if (__HAL_USART_GET_FLAG(husart, USART_FLAG_TXFNF) == SET) - { - husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr & (uint8_t)0xFF); - husart->pTxBuffPtr++; - husart->TxXferCount--; - } - else - { - /* Nothing to do */ - } - } - } -} - -/** - * @brief Simplex send an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Transmit_IT(). - * @note The USART errors are not managed to avoid the overrun error. - * @note ISR function executed when FIFO mode is enabled and when the - * data word length is 9 bits long. - * @param husart USART handle. - * @retval None - */ -static void USART_TxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - const uint16_t *tmp; - uint16_t nb_tx_data; - - /* Check that a Tx process is ongoing */ - if ((state == HAL_USART_STATE_BUSY_TX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - for (nb_tx_data = husart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) - { - if (husart->TxXferCount == 0U) - { - /* Disable the TX FIFO threshold interrupt */ - __HAL_USART_DISABLE_IT(husart, USART_IT_TXFT); - - /* Enable the USART Transmit Complete Interrupt */ - __HAL_USART_ENABLE_IT(husart, USART_IT_TC); - - break; /* force exit loop */ - } - else if (__HAL_USART_GET_FLAG(husart, USART_FLAG_TXFNF) == SET) - { - tmp = (const uint16_t *) husart->pTxBuffPtr; - husart->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); - husart->pTxBuffPtr += 2U; - husart->TxXferCount--; - } - else - { - /* Nothing to do */ - } - } - } -} - -/** - * @brief Wraps up transmission in non-blocking mode. - * @param husart Pointer to a USART_HandleTypeDef structure that contains - * the configuration information for the specified USART module. - * @retval None - */ -static void USART_EndTransmit_IT(USART_HandleTypeDef *husart) -{ - /* Disable the USART Transmit Complete Interrupt */ - __HAL_USART_DISABLE_IT(husart, USART_IT_TC); - - /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); - - /* Clear TxISR function pointer */ - husart->TxISR = NULL; - - if (husart->State == HAL_USART_STATE_BUSY_TX) - { - /* Clear overrun flag and discard the received data */ - __HAL_USART_CLEAR_OREFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); - - /* Tx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Complete Callback */ - husart->TxCpltCallback(husart); -#else - /* Call legacy weak Tx Complete Callback */ - HAL_USART_TxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else if (husart->RxXferCount == 0U) - { - /* TxRx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } -} - - -/** - * @brief Simplex receive an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Receive_IT(). - * @note ISR function executed when FIFO mode is disabled and when the - * data word length is less than 9 bits long. - * @param husart USART handle - * @retval None - */ -static void USART_RxISR_8BIT(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - uint16_t txdatacount; - uint16_t uhMask = husart->Mask; - uint32_t txftie; - - if ((state == HAL_USART_STATE_BUSY_RX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - *husart->pRxBuffPtr = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); - husart->pRxBuffPtr++; - husart->RxXferCount--; - - if (husart->RxXferCount == 0U) - { - /* Disable the USART Parity Error Interrupt and RXNE interrupt*/ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - - /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Clear RxISR function pointer */ - husart->RxISR = NULL; - - /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ - txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); - txdatacount = husart->TxXferCount; - - if (state == HAL_USART_STATE_BUSY_RX) - { - /* Clear SPI slave underrun flag and discard transmit data */ - if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) - { - __HAL_USART_CLEAR_UDRFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* Rx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Complete Callback */ - husart->RxCpltCallback(husart); -#else - /* Call legacy weak Rx Complete Callback */ - HAL_USART_RxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && - (txftie != USART_CR3_TXFTIE) && - (txdatacount == 0U)) - { - /* TxRx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - else if ((state == HAL_USART_STATE_BUSY_RX) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - else - { - /* Nothing to do */ - } - } -} - -/** - * @brief Simplex receive an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Receive_IT(). - * @note ISR function executed when FIFO mode is disabled and when the - * data word length is 9 bits long. - * @param husart USART handle - * @retval None - */ -static void USART_RxISR_16BIT(USART_HandleTypeDef *husart) -{ - const HAL_USART_StateTypeDef state = husart->State; - uint16_t txdatacount; - uint16_t *tmp; - uint16_t uhMask = husart->Mask; - uint32_t txftie; - - if ((state == HAL_USART_STATE_BUSY_RX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - tmp = (uint16_t *) husart->pRxBuffPtr; - *tmp = (uint16_t)(husart->Instance->RDR & uhMask); - husart->pRxBuffPtr += 2U; - husart->RxXferCount--; - - if (husart->RxXferCount == 0U) - { - /* Disable the USART Parity Error Interrupt and RXNE interrupt*/ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); - - /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Clear RxISR function pointer */ - husart->RxISR = NULL; - - /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ - txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); - txdatacount = husart->TxXferCount; - - if (state == HAL_USART_STATE_BUSY_RX) - { - /* Clear SPI slave underrun flag and discard transmit data */ - if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) - { - __HAL_USART_CLEAR_UDRFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* Rx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Complete Callback */ - husart->RxCpltCallback(husart); -#else - /* Call legacy weak Rx Complete Callback */ - HAL_USART_RxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && - (txftie != USART_CR3_TXFTIE) && - (txdatacount == 0U)) - { - /* TxRx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - else if ((state == HAL_USART_STATE_BUSY_RX) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - else - { - /* Nothing to do */ - } - } -} - -/** - * @brief Simplex receive an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Receive_IT(). - * @note ISR function executed when FIFO mode is enabled and when the - * data word length is less than 9 bits long. - * @param husart USART handle - * @retval None - */ -static void USART_RxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart) -{ - HAL_USART_StateTypeDef state = husart->State; - uint16_t txdatacount; - uint16_t rxdatacount; - uint16_t uhMask = husart->Mask; - uint16_t nb_rx_data; - uint32_t txftie; - - /* Check that a Rx process is ongoing */ - if ((state == HAL_USART_STATE_BUSY_RX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - for (nb_rx_data = husart->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) - { - if (__HAL_USART_GET_FLAG(husart, USART_FLAG_RXFNE) == SET) - { - *husart->pRxBuffPtr = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); - husart->pRxBuffPtr++; - husart->RxXferCount--; - - if (husart->RxXferCount == 0U) - { - /* Disable the USART Parity Error Interrupt */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); - - /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) - and RX FIFO Threshold interrupt */ - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Clear RxISR function pointer */ - husart->RxISR = NULL; - - /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ - txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); - txdatacount = husart->TxXferCount; - - if (state == HAL_USART_STATE_BUSY_RX) - { - /* Clear SPI slave underrun flag and discard transmit data */ - if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) - { - __HAL_USART_CLEAR_UDRFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* Rx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - state = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Complete Callback */ - husart->RxCpltCallback(husart); -#else - /* Call legacy weak Rx Complete Callback */ - HAL_USART_RxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && - (txftie != USART_CR3_TXFTIE) && - (txdatacount == 0U)) - { - /* TxRx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - state = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - else if ((state == HAL_USART_STATE_BUSY_RX) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - else - { - /* Nothing to do */ - } - } - } - - /* When remaining number of bytes to receive is less than the RX FIFO - threshold, next incoming frames are processed as if FIFO mode was - disabled (i.e. one interrupt per received frame). - */ - rxdatacount = husart->RxXferCount; - if (((rxdatacount != 0U)) && (rxdatacount < husart->NbRxDataToProcess)) - { - /* Disable the USART RXFT interrupt*/ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); - - /* Update the RxISR function pointer */ - husart->RxISR = USART_RxISR_8BIT; - - /* Enable the USART Data Register Not Empty interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - - if ((husart->TxXferCount == 0U) && - (state == HAL_USART_STATE_BUSY_TX_RX) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @brief Simplex receive an amount of data in non-blocking mode. - * @note Function called under interruption only, once - * interruptions have been enabled by HAL_USART_Receive_IT(). - * @note ISR function executed when FIFO mode is enabled and when the - * data word length is 9 bits long. - * @param husart USART handle - * @retval None - */ -static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart) -{ - HAL_USART_StateTypeDef state = husart->State; - uint16_t txdatacount; - uint16_t rxdatacount; - uint16_t *tmp; - uint16_t uhMask = husart->Mask; - uint16_t nb_rx_data; - uint32_t txftie; - - /* Check that a Tx process is ongoing */ - if ((state == HAL_USART_STATE_BUSY_RX) || - (state == HAL_USART_STATE_BUSY_TX_RX)) - { - for (nb_rx_data = husart->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) - { - if (__HAL_USART_GET_FLAG(husart, USART_FLAG_RXFNE) == SET) - { - tmp = (uint16_t *) husart->pRxBuffPtr; - *tmp = (uint16_t)(husart->Instance->RDR & uhMask); - husart->pRxBuffPtr += 2U; - husart->RxXferCount--; - - if (husart->RxXferCount == 0U) - { - /* Disable the USART Parity Error Interrupt */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); - - /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) - and RX FIFO Threshold interrupt */ - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); - - /* Clear RxISR function pointer */ - husart->RxISR = NULL; - - /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ - txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); - txdatacount = husart->TxXferCount; - - if (state == HAL_USART_STATE_BUSY_RX) - { - /* Clear SPI slave underrun flag and discard transmit data */ - if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) - { - __HAL_USART_CLEAR_UDRFLAG(husart); - __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); - } - - /* Rx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - state = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Rx Complete Callback */ - husart->RxCpltCallback(husart); -#else - /* Call legacy weak Rx Complete Callback */ - HAL_USART_RxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && - (txftie != USART_CR3_TXFTIE) && - (txdatacount == 0U)) - { - /* TxRx process is completed, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - state = HAL_USART_STATE_READY; - -#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) - /* Call registered Tx Rx Complete Callback */ - husart->TxRxCpltCallback(husart); -#else - /* Call legacy weak Tx Rx Complete Callback */ - HAL_USART_TxRxCpltCallback(husart); -#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ - } - else - { - /* Nothing to do */ - } - } - else if ((state == HAL_USART_STATE_BUSY_RX) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - else - { - /* Nothing to do */ - } - } - } - - /* When remaining number of bytes to receive is less than the RX FIFO - threshold, next incoming frames are processed as if FIFO mode was - disabled (i.e. one interrupt per received frame). - */ - rxdatacount = husart->RxXferCount; - if (((rxdatacount != 0U)) && (rxdatacount < husart->NbRxDataToProcess)) - { - /* Disable the USART RXFT interrupt*/ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); - - /* Update the RxISR function pointer */ - husart->RxISR = USART_RxISR_16BIT; - - /* Enable the USART Data Register Not Empty interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); - - if ((husart->TxXferCount == 0U) && - (state == HAL_USART_STATE_BUSY_TX_RX) && - (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) - { - /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ - husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); - } - } - } - else - { - /* Clear RXNE interrupt flag */ - __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); - } -} - -/** - * @} - */ - -#endif /* HAL_USART_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_usart.c + * @author MCD Application Team + * @brief USART HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Universal Synchronous/Asynchronous Receiver Transmitter + * Peripheral (USART). + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Error functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The USART HAL driver can be used as follows: + + (#) Declare a USART_HandleTypeDef handle structure (eg. USART_HandleTypeDef husart). + (#) Initialize the USART low level resources by implementing 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. + (++) USART interrupts handling: + -@@- The specific USART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_USART_ENABLE_IT() and __HAL_USART_DISABLE_IT() inside the transmit and receive process. + (++) DMA Configuration if you need to use DMA process (HAL_USART_Transmit_DMA() + HAL_USART_Receive_DMA() and HAL_USART_TransmitReceive_DMA() APIs): + (+++) Declare a DMA handle structure for the Tx/Rx channel. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx channel. + (+++) Associate the initialized 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 channel. + + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, and Mode + (Receiver/Transmitter) in the husart handle Init structure. + + (#) Initialize the USART registers by calling the HAL_USART_Init() API: + (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized HAL_USART_MspInit(&husart) API. + + [..] + (@) To configure and enable/disable the USART to wake up the MCU from stop mode, resort to UART API's + HAL_UARTEx_StopModeWakeUpSourceConfig(), HAL_UARTEx_EnableStopMode() and + HAL_UARTEx_DisableStopMode() in casting the USART handle to UART type UART_HandleTypeDef. + + ##### Callback registration ##### + ================================== + + [..] + The compilation define USE_HAL_USART_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use Function HAL_USART_RegisterCallback() to register a user callback. + Function HAL_USART_RegisterCallback() allows to register following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) TxRxCpltCallback : Tx Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) RxFifoFullCallback : Rx Fifo Full Callback. + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) MspInitCallback : USART MspInit. + (+) MspDeInitCallback : USART MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_USART_UnRegisterCallback() to reset a callback to the default + weak function. + HAL_USART_UnRegisterCallback() takes as parameters the HAL peripheral handle, + and the Callback ID. + This function allows to reset following callbacks: + (+) TxHalfCpltCallback : Tx Half Complete Callback. + (+) TxCpltCallback : Tx Complete Callback. + (+) RxHalfCpltCallback : Rx Half Complete Callback. + (+) RxCpltCallback : Rx Complete Callback. + (+) TxRxCpltCallback : Tx Rx Complete Callback. + (+) ErrorCallback : Error Callback. + (+) AbortCpltCallback : Abort Complete Callback. + (+) RxFifoFullCallback : Rx Fifo Full Callback. + (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. + (+) MspInitCallback : USART MspInit. + (+) MspDeInitCallback : USART MspDeInit. + + [..] + By default, after the HAL_USART_Init() and when the state is HAL_USART_STATE_RESET + all callbacks are set to the corresponding weak functions: + examples HAL_USART_TxCpltCallback(), HAL_USART_RxHalfCpltCallback(). + Exception done for MspInit and MspDeInit functions that are respectively + reset to the legacy weak functions in the HAL_USART_Init() + and HAL_USART_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_USART_Init() and HAL_USART_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand). + + [..] + Callbacks can be registered/unregistered in HAL_USART_STATE_READY state only. + Exception done MspInit/MspDeInit that can be registered/unregistered + in HAL_USART_STATE_READY or HAL_USART_STATE_RESET state, thus registered (user) + MspInit/DeInit callbacks can be used during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_USART_RegisterCallback() before calling HAL_USART_DeInit() + or HAL_USART_Init() function. + + [..] + When The compilation define USE_HAL_USART_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registration feature is not available + and weak callbacks are used. + + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup USART USART + * @brief HAL USART Synchronous SPI module driver + * @{ + */ + +#ifdef HAL_USART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** @defgroup USART_Private_Constants USART Private Constants + * @{ + */ +#define USART_DUMMY_DATA ((uint16_t) 0xFFFF) /*!< USART transmitted dummy data */ +#define USART_TEACK_REACK_TIMEOUT 1000U /*!< USART TX or RX enable acknowledge time-out value */ +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ + USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8 | \ + USART_CR1_FIFOEN )) /*!< USART CR1 fields of parameters set by USART_SetConfig API */ + +#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | \ + USART_CR2_LBCL | USART_CR2_STOP | USART_CR2_SLVEN | \ + USART_CR2_DIS_NSS)) /*!< USART CR2 fields of parameters set by USART_SetConfig API */ + +#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_TXFTCFG | USART_CR3_RXFTCFG )) /*!< USART or USART CR3 fields of parameters set by USART_SetConfig API */ + +#define USART_BRR_MIN 0x10U /* USART BRR minimum authorized value */ +#define USART_BRR_MAX 0xFFFFU /* USART BRR maximum authorized value */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @addtogroup USART_Private_Functions + * @{ + */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) +void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ +static void USART_EndTransfer(USART_HandleTypeDef *husart); +#if defined(HAL_DMA_MODULE_ENABLED) +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAError(DMA_HandleTypeDef *hdma); +static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma); +static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); +static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); +#endif /* HAL_DMA_MODULE_ENABLED */ +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout); +static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart); +static void USART_TxISR_8BIT(USART_HandleTypeDef *husart); +static void USART_TxISR_16BIT(USART_HandleTypeDef *husart); +static void USART_TxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart); +static void USART_TxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); +static void USART_EndTransmit_IT(USART_HandleTypeDef *husart); +static void USART_RxISR_8BIT(USART_HandleTypeDef *husart); +static void USART_RxISR_16BIT(USART_HandleTypeDef *husart); +static void USART_RxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart); +static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup USART_Exported_Functions USART Exported Functions + * @{ + */ + +/** @defgroup USART_Exported_Functions_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 USART + in synchronous SPI master/slave mode. + (+) For the synchronous SPI 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. + (++) USART polarity + (++) USART phase + (++) USART LastBit + (++) Receiver/transmitter modes + + [..] + The HAL_USART_Init() function follows the USART synchronous SPI configuration + procedure (details for the procedure are available in reference manual). + +@endverbatim + + Depending on the frame length defined by the M1 and M0 bits (7-bit, + 8-bit or 9-bit), the possible USART formats are listed in the + following table. + + Table 1. USART frame format. + +-----------------------------------------------------------------------+ + | M1 bit | M0 bit | PCE bit | USART frame | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 0 | | SB | 8 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 0 | | SB | 9 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 0 | | SB | 7 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | + +-----------------------------------------------------------------------+ + + * @{ + */ + +/** + * @brief Initialize the USART mode according to the specified + * parameters in the USART_InitTypeDef and initialize 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) + { + /* Allocate lock resource and initialize it */ + husart->Lock = HAL_UNLOCKED; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + USART_InitCallbacksToDefault(husart); + + if (husart->MspInitCallback == NULL) + { + husart->MspInitCallback = HAL_USART_MspInit; + } + + /* Init the low level hardware */ + husart->MspInitCallback(husart); +#else + /* Init the low level hardware : GPIO, CLOCK */ + HAL_USART_MspInit(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + + husart->State = HAL_USART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_USART_DISABLE(husart); + + /* Set the Usart Communication parameters */ + if (USART_SetConfig(husart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* In Synchronous SPI 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_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + /* Enable the Peripheral */ + __HAL_USART_ENABLE(husart); + + /* TEACK and/or REACK to check before moving husart->State to Ready */ + return (USART_CheckIdleState(husart)); +} + +/** + * @brief DeInitialize 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; + + husart->Instance->CR1 = 0x0U; + husart->Instance->CR2 = 0x0U; + husart->Instance->CR3 = 0x0U; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + if (husart->MspDeInitCallback == NULL) + { + husart->MspDeInitCallback = HAL_USART_MspDeInit; + } + /* DeInit the low level hardware */ + husart->MspDeInitCallback(husart); +#else + /* DeInit the low level hardware */ + HAL_USART_MspDeInit(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Initialize the USART MSP. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitialize the USART MSP. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_MspDeInit can be implemented in the user file + */ +} + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User USART Callback + * To be used to override the weak predefined callback + * @note The HAL_USART_RegisterCallback() may be called before HAL_USART_Init() in HAL_USART_STATE_RESET + * to register callbacks for HAL_USART_MSPINIT_CB_ID and HAL_USART_MSPDEINIT_CB_ID + * @param husart usart handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref HAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref HAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_USART_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_USART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID + * @arg @ref HAL_USART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID + * @arg @ref HAL_USART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @param pCallback pointer to the Callback function + * @retval HAL status ++ */ +HAL_StatusTypeDef HAL_USART_RegisterCallback(USART_HandleTypeDef *husart, HAL_USART_CallbackIDTypeDef CallbackID, + pUSART_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + return HAL_ERROR; + } + + if (husart->State == HAL_USART_STATE_READY) + { + switch (CallbackID) + { + case HAL_USART_TX_HALFCOMPLETE_CB_ID : + husart->TxHalfCpltCallback = pCallback; + break; + + case HAL_USART_TX_COMPLETE_CB_ID : + husart->TxCpltCallback = pCallback; + break; + + case HAL_USART_RX_HALFCOMPLETE_CB_ID : + husart->RxHalfCpltCallback = pCallback; + break; + + case HAL_USART_RX_COMPLETE_CB_ID : + husart->RxCpltCallback = pCallback; + break; + + case HAL_USART_TX_RX_COMPLETE_CB_ID : + husart->TxRxCpltCallback = pCallback; + break; + + case HAL_USART_ERROR_CB_ID : + husart->ErrorCallback = pCallback; + break; + + case HAL_USART_ABORT_COMPLETE_CB_ID : + husart->AbortCpltCallback = pCallback; + break; + + case HAL_USART_RX_FIFO_FULL_CB_ID : + husart->RxFifoFullCallback = pCallback; + break; + + case HAL_USART_TX_FIFO_EMPTY_CB_ID : + husart->TxFifoEmptyCallback = pCallback; + break; + + case HAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = pCallback; + break; + + case HAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (husart->State == HAL_USART_STATE_RESET) + { + switch (CallbackID) + { + case HAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = pCallback; + break; + + case HAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = pCallback; + break; + + default : + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister an USART Callback + * USART callaback is redirected to the weak predefined callback + * @note The HAL_USART_UnRegisterCallback() may be called before HAL_USART_Init() in HAL_USART_STATE_RESET + * to un-register callbacks for HAL_USART_MSPINIT_CB_ID and HAL_USART_MSPDEINIT_CB_ID + * @param husart usart handle + * @param CallbackID ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID + * @arg @ref HAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID + * @arg @ref HAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID + * @arg @ref HAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID + * @arg @ref HAL_USART_ERROR_CB_ID Error Callback ID + * @arg @ref HAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID + * @arg @ref HAL_USART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID + * @arg @ref HAL_USART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID + * @arg @ref HAL_USART_MSPINIT_CB_ID MspInit Callback ID + * @arg @ref HAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, HAL_USART_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (HAL_USART_STATE_READY == husart->State) + { + switch (CallbackID) + { + case HAL_USART_TX_HALFCOMPLETE_CB_ID : + husart->TxHalfCpltCallback = HAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + break; + + case HAL_USART_TX_COMPLETE_CB_ID : + husart->TxCpltCallback = HAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + break; + + case HAL_USART_RX_HALFCOMPLETE_CB_ID : + husart->RxHalfCpltCallback = HAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + break; + + case HAL_USART_RX_COMPLETE_CB_ID : + husart->RxCpltCallback = HAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + break; + + case HAL_USART_TX_RX_COMPLETE_CB_ID : + husart->TxRxCpltCallback = HAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + break; + + case HAL_USART_ERROR_CB_ID : + husart->ErrorCallback = HAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ + break; + + case HAL_USART_ABORT_COMPLETE_CB_ID : + husart->AbortCpltCallback = HAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + break; + + case HAL_USART_RX_FIFO_FULL_CB_ID : + husart->RxFifoFullCallback = HAL_USARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ + break; + + case HAL_USART_TX_FIFO_EMPTY_CB_ID : + husart->TxFifoEmptyCallback = HAL_USARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ + break; + + case HAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = HAL_USART_MspInit; /* Legacy weak MspInitCallback */ + break; + + case HAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = HAL_USART_MspDeInit; /* Legacy weak MspDeInitCallback */ + break; + + default : + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else if (HAL_USART_STATE_RESET == husart->State) + { + switch (CallbackID) + { + case HAL_USART_MSPINIT_CB_ID : + husart->MspInitCallback = HAL_USART_MspInit; + break; + + case HAL_USART_MSPDEINIT_CB_ID : + husart->MspDeInitCallback = HAL_USART_MspDeInit; + break; + + default : + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; + + /* Return error status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + + +/** + * @} + */ + +/** @defgroup USART_Exported_Functions_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 SPI + data transfers. + + [..] The USART Synchronous SPI supports master and slave modes (SCLK as output or input). + + [..] + + (#) 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. + (++) 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 respectively 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 API's with DMA are : + (++) HAL_USART_Transmit_DMA() in simplex mode + (++) HAL_USART_Receive_DMA() in full duplex receive only + (++) HAL_USART_TransmitReceive_DMA() in full duplex mode + (++) HAL_USART_DMAPause() + (++) HAL_USART_DMAResume() + (++) HAL_USART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: + (++) HAL_USART_TxCpltCallback() + (++) HAL_USART_RxCpltCallback() + (++) HAL_USART_TxHalfCpltCallback() + (++) HAL_USART_RxHalfCpltCallback() + (++) HAL_USART_ErrorCallback() + (++) HAL_USART_TxRxCpltCallback() + + (#) Non-Blocking mode transfers could be aborted using Abort API's : + (++) HAL_USART_Abort() + (++) HAL_USART_Abort_IT() + + (#) For Abort services based on interrupts (HAL_USART_Abort_IT), a Abort Complete Callbacks is provided: + (++) HAL_USART_AbortCpltCallback() + + (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. + Errors are handled as follows : + (++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is + to be evaluated by user : this concerns Frame Error, + Parity Error or Noise Error in Interrupt mode reception . + Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify + error type, and HAL_USART_ErrorCallback() user callback is executed. + Transfer is kept ongoing on USART side. + If user wants to abort it, Abort services should be called by user. + (++) Error is considered as Blocking : Transfer could not be completed properly and is aborted. + This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. + Error code is set to allow user to identify error type, + and HAL_USART_ErrorCallback() user callback is executed. + +@endverbatim + * @{ + */ + +/** + * @brief Simplex send an amount of data in blocking mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pTxData. + * @param husart USART handle. + * @param pTxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be sent. + * @param Timeout Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size, + uint32_t Timeout) +{ + const uint8_t *ptxdata8bits; + const uint16_t *ptxdata16bits; + uint32_t tickstart; + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + /* In case of 9bits/No Parity transfer, pTxData needs to be handled as a uint16_t pointer */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + ptxdata8bits = NULL; + ptxdata16bits = (const uint16_t *) pTxData; + } + else + { + ptxdata8bits = pTxData; + ptxdata16bits = NULL; + } + + /* Check the remaining data to be sent */ + while (husart->TxXferCount > 0U) + { + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if (ptxdata8bits == NULL) + { + husart->Instance->TDR = (uint16_t)(*ptxdata16bits & 0x01FFU); + ptxdata16bits++; + } + else + { + husart->Instance->TDR = (uint8_t)(*ptxdata8bits & 0xFFU); + ptxdata8bits++; + } + + husart->TxXferCount--; + } + + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear Transmission Complete Flag */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); + + /* Clear overrun flag and discard the received data */ + __HAL_USART_CLEAR_OREFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + + /* At end of Tx process, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode. + * @note To receive synchronous data, dummy data are simultaneously transmitted. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pRxData. + * @param husart USART handle. + * @param pRxData Pointer to data buffer (u8 or u16 data elements). + * @param Size Amount of data elements (u8 or u16) to be received. + * @param Timeout Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + uint8_t *prxdata8bits; + uint16_t *prxdata16bits; + uint16_t uhMask; + uint32_t tickstart; + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pRxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + /* Computation of USART mask to apply to RDR register */ + USART_MASK_COMPUTATION(husart); + uhMask = husart->Mask; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + prxdata8bits = NULL; + prxdata16bits = (uint16_t *) pRxData; + } + else + { + prxdata8bits = pRxData; + prxdata16bits = NULL; + } + + /* as long as data have to be received */ + while (husart->RxXferCount > 0U) + { + if (husart->SlaveMode == USART_SLAVEMODE_DISABLE) + { + /* Wait until TXE flag is set to send dummy byte in order to generate the + * clock for the slave to send data. + * Whatever the frame length (7, 8 or 9-bit long), the same dummy value + * can be written for all the cases. */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x0FF); + } + + /* Wait for RXNE Flag */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if (prxdata8bits == NULL) + { + *prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask); + prxdata16bits++; + } + else + { + *prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); + prxdata8bits++; + } + + husart->RxXferCount--; + + } + + /* Clear SPI slave underrun flag and discard transmit data */ + if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) + { + __HAL_USART_CLEAR_UDRFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* At end of Rx process, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in blocking mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number + * of u16 available through pTxData and through pRxData. + * @param husart USART handle. + * @param pTxData pointer to TX data buffer (u8 or u16 data elements). + * @param pRxData pointer to RX data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be sent (same amount to be received). + * @param Timeout Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size, uint32_t Timeout) +{ + uint8_t *prxdata8bits; + uint16_t *prxdata16bits; + const uint8_t *ptxdata8bits; + const uint16_t *ptxdata16bits; + uint16_t uhMask; + uint16_t rxdatacount; + uint32_t tickstart; + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + husart->RxXferSize = Size; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + husart->RxXferCount = Size; + + /* Computation of USART mask to apply to RDR register */ + USART_MASK_COMPUTATION(husart); + uhMask = husart->Mask; + + /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + prxdata8bits = NULL; + ptxdata8bits = NULL; + ptxdata16bits = (const uint16_t *) pTxData; + prxdata16bits = (uint16_t *) pRxData; + } + else + { + prxdata8bits = pRxData; + ptxdata8bits = pTxData; + ptxdata16bits = NULL; + prxdata16bits = NULL; + } + + if ((husart->TxXferCount == 0x01U) || (husart->SlaveMode == USART_SLAVEMODE_ENABLE)) + { + /* Wait until TXE flag is set to send data */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if (ptxdata8bits == NULL) + { + husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask); + ptxdata16bits++; + } + else + { + husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU)); + ptxdata8bits++; + } + + husart->TxXferCount--; + } + + /* Check the remain data to be sent */ + /* rxdatacount is a temporary variable for MISRAC2012-Rule-13.5 */ + rxdatacount = husart->RxXferCount; + while ((husart->TxXferCount > 0U) || (rxdatacount > 0U)) + { + if (husart->TxXferCount > 0U) + { + /* Wait until TXE flag is set to send data */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if (ptxdata8bits == NULL) + { + husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask); + ptxdata16bits++; + } + else + { + husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU)); + ptxdata8bits++; + } + + husart->TxXferCount--; + } + + if (husart->RxXferCount > 0U) + { + /* Wait for RXNE Flag */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if (prxdata8bits == NULL) + { + *prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask); + prxdata16bits++; + } + else + { + *prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); + prxdata8bits++; + } + + husart->RxXferCount--; + } + rxdatacount = husart->RxXferCount; + } + + /* At end of TxRx process, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pTxData. + * @param husart USART handle. + * @param pTxData pointer to data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size) +{ + if (husart->State == HAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + husart->TxISR = NULL; + + 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" */ + + /* Configure Tx interrupt processing */ + if (husart->FifoMode == USART_FIFOMODE_ENABLE) + { + /* Set the Tx ISR function pointer according to the data word length */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + husart->TxISR = USART_TxISR_16BIT_FIFOEN; + } + else + { + husart->TxISR = USART_TxISR_8BIT_FIFOEN; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the TX FIFO threshold interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TXFT); + } + else + { + /* Set the Tx ISR function pointer according to the data word length */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + husart->TxISR = USART_TxISR_16BIT; + } + else + { + husart->TxISR = USART_TxISR_8BIT; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Transmit Data Register Empty Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TXE); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode. + * @note To receive synchronous data, dummy data are simultaneously transmitted. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pRxData. + * @param husart USART handle. + * @param pRxData pointer to data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + uint16_t nb_dummy_data; + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pRxData == NULL) || (Size == 0U)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + husart->RxISR = NULL; + + USART_MASK_COMPUTATION(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Configure Rx interrupt processing */ + if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) + { + /* Set the Rx ISR function pointer according to the data word length */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + husart->RxISR = USART_RxISR_16BIT_FIFOEN; + } + else + { + husart->RxISR = USART_RxISR_8BIT_FIFOEN; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Parity Error interrupt and RX FIFO Threshold interrupt */ + if (husart->Init.Parity != USART_PARITY_NONE) + { + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); + } + SET_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); + } + else + { + /* Set the Rx ISR function pointer according to the data word length */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + husart->RxISR = USART_RxISR_16BIT; + } + else + { + husart->RxISR = USART_RxISR_8BIT; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Parity Error and Data Register not empty Interrupts */ + if (husart->Init.Parity != USART_PARITY_NONE) + { + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); + } + else + { + SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + } + + if (husart->SlaveMode == USART_SLAVEMODE_DISABLE) + { + /* Send dummy data in order to generate the clock for the Slave to send the next data. + When FIFO mode is disabled only one data must be transferred. + When FIFO mode is enabled data must be transmitted until the RX FIFO reaches its threshold. + */ + if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) + { + for (nb_dummy_data = husart->NbRxDataToProcess ; nb_dummy_data > 0U ; nb_dummy_data--) + { + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + } + else + { + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in interrupt mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number + * of u16 available through pTxData and through pRxData. + * @param husart USART handle. + * @param pTxData pointer to TX data buffer (u8 or u16 data elements). + * @param pRxData pointer to RX data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be sent (same amount to be received). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + 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; + + /* Computation of USART mask to apply to RDR register */ + USART_MASK_COMPUTATION(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX_RX; + + /* Configure TxRx interrupt processing */ + if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) + { + /* Set the Rx ISR function pointer according to the data word length */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + husart->TxISR = USART_TxISR_16BIT_FIFOEN; + husart->RxISR = USART_RxISR_16BIT_FIFOEN; + } + else + { + husart->TxISR = USART_TxISR_8BIT_FIFOEN; + husart->RxISR = USART_RxISR_8BIT_FIFOEN; + } + + /* Process Locked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CR3, USART_CR3_EIE); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error interrupt */ + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); + } + + /* Enable the TX and RX FIFO Threshold interrupts */ + SET_BIT(husart->Instance->CR3, (USART_CR3_TXFTIE | USART_CR3_RXFTIE)); + } + else + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + husart->TxISR = USART_TxISR_16BIT; + husart->RxISR = USART_RxISR_16BIT; + } + else + { + husart->TxISR = USART_TxISR_8BIT; + husart->RxISR = USART_RxISR_8BIT; + } + + /* Process Locked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Enable the USART Parity Error and USART Data Register not empty Interrupts */ + if (husart->Init.Parity != USART_PARITY_NONE) + { + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); + } + else + { + SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + } + + /* Enable the USART Transmit Data Register Empty Interrupt */ + SET_BIT(husart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @brief Send an amount of data in DMA mode. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data is handled as a set of u16. In this case, Size must indicate the number + * of u16 provided through pTxData. + * @param husart USART handle. + * @param pTxData pointer to data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint16_t Size) +{ + HAL_StatusTypeDef status = HAL_OK; + const uint32_t *tmp; + uint16_t nbByte = Size; + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (Size == 0U)) + { + 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; + + if (husart->hdmatx != NULL) + { + /* 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; + + /* In case of 9bits/No Parity transfer, pTxData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + tmp = (const uint32_t *)&pTxData; + + /* Check linked list mode */ + if ((husart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((husart->hdmatx->LinkedListQueue != NULL) && (husart->hdmatx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = *(const uint32_t *)tmp; + + /* Set DMA destination address */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&husart->Instance->TDR; + + /* Enable the USART transmit DMA channel */ + status = HAL_DMAEx_List_Start_IT(husart->hdmatx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the USART transmit DMA channel */ + status = HAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, nbByte); + } + } + + if (status == HAL_OK) + { + /* Clear the TC flag in the ICR register */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + return HAL_OK; + } + else + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Restore husart->State to ready */ + husart->State = HAL_USART_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode. + * @note When the USART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position). + * @note The USART DMA transmit channel must be configured in order to generate the clock for the slave. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the received data is handled as a set of u16. In this case, Size must indicate the number + * of u16 available through pRxData. + * @param husart USART handle. + * @param pRxData pointer to data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be received. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t *tmp = (uint32_t *)&pRxData; + uint16_t nbByte = Size; + + /* Check that a Rx process is not already ongoing */ + if (husart->State == HAL_USART_STATE_READY) + { + if ((pRxData == NULL) || (Size == 0U)) + { + 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; + + if (husart->hdmarx != NULL) + { + /* 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; + + /* In case of 9bits/No Parity transfer, pTxData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + /* Check linked list mode */ + if ((husart->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((husart->hdmarx->LinkedListQueue != NULL) && (husart->hdmarx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)&husart->Instance->RDR; + + /* Set DMA destination address */ + husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = *(uint32_t *)tmp; + + /* Enable the USART receive DMA channel */ + status = HAL_DMAEx_List_Start_IT(husart->hdmarx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the USART receive DMA channel */ + status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t *)tmp, nbByte); + } + } + + if ((status == HAL_OK) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Enable the USART transmit DMA channel: the transmit channel 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 mode */ + + /* Set the USART DMA Tx Complete and Error callback to Null */ + if (husart->hdmatx != NULL) + { + husart->hdmatx->XferErrorCallback = NULL; + husart->hdmatx->XferHalfCpltCallback = NULL; + husart->hdmatx->XferCpltCallback = NULL; + + /* Check linked list mode */ + if ((husart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((husart->hdmatx->LinkedListQueue != NULL) && (husart->hdmatx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = *(uint32_t *)tmp; + + /* Set DMA destination address */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&husart->Instance->TDR; + + /* Enable the USART transmit DMA channel */ + status = HAL_DMAEx_List_Start_IT(husart->hdmatx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, nbByte); + } + } + } + + if (status == HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error Interrupt */ + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); + } + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + return HAL_OK; + } + else + { + if ((husart->hdmarx != NULL) && ((husart->hdmarx->Mode & DMA_LINKEDLIST) != DMA_LINKEDLIST)) + { + status = HAL_DMA_Abort(husart->hdmarx); + } + + /* No need to check on error code */ + UNUSED(status); + + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Restore husart->State to ready */ + husart->State = HAL_USART_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Transmit Receive an amount of data in non-blocking mode. + * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. + * @note When USART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), + * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number + * of u16 available through pTxData and through pRxData. + * @param husart USART handle. + * @param pTxData pointer to TX data buffer (u8 or u16 data elements). + * @param pRxData pointer to RX data buffer (u8 or u16 data elements). + * @param Size amount of data elements (u8 or u16) to be received/sent. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, const uint8_t *pTxData, uint8_t *pRxData, + uint16_t Size) +{ + HAL_StatusTypeDef status; + const uint32_t *tmp; + uint16_t nbByte = Size; + + if (husart->State == HAL_USART_STATE_READY) + { + if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + { + 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; + + if ((husart->hdmarx != NULL) && (husart->hdmatx != NULL)) + { + /* 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; + + /* In case of 9bits/No Parity transfer, pTxData buffer provided as input parameter + should be aligned on a u16 frontier, so nbByte should be equal to Size multiplied by 2 */ + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + nbByte = Size * 2U; + } + + /* Check linked list mode */ + tmp = (uint32_t *)&pRxData; + if ((husart->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((husart->hdmarx->LinkedListQueue != NULL) && (husart->hdmarx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = + (uint32_t)&husart->Instance->RDR; + + /* Set DMA destination address */ + husart->hdmarx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = *(const uint32_t *)tmp; + + /* Enable the USART receive DMA channel */ + status = HAL_DMAEx_List_Start_IT(husart->hdmarx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + /* Enable the USART receive DMA channel */ + status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(const uint32_t *)tmp, nbByte); + } + + /* Enable the USART transmit DMA channel */ + if (status == HAL_OK) + { + tmp = (const uint32_t *)&pTxData; + + /* Check linked list mode */ + if ((husart->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if ((husart->hdmatx->LinkedListQueue != NULL) && (husart->hdmatx->LinkedListQueue->Head != NULL)) + { + /* Set DMA data size */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = nbByte; + + /* Set DMA source address */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = *(const uint32_t *)tmp; + + /* Set DMA destination address */ + husart->hdmatx->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = + (uint32_t)&husart->Instance->TDR; + + /* Enable the USART transmit DMA channel */ + status = HAL_DMAEx_List_Start_IT(husart->hdmatx); + } + else + { + /* Update status */ + status = HAL_ERROR; + } + } + else + { + status = HAL_DMA_Start_IT(husart->hdmatx, *(const uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, nbByte); + } + } + } + else + { + status = HAL_ERROR; + } + + if (status == HAL_OK) + { + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + if (husart->Init.Parity != USART_PARITY_NONE) + { + /* Enable the USART Parity Error Interrupt */ + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); + } + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + SET_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Clear the TC flag in the ICR register */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + return HAL_OK; + } + else + { + if ((husart->hdmarx != NULL) && ((husart->hdmarx->Mode & DMA_LINKEDLIST) != DMA_LINKEDLIST)) + { + status = HAL_DMA_Abort(husart->hdmarx); + } + + /* No need to check on error code */ + UNUSED(status); + + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Restore husart->State to ready */ + husart->State = HAL_USART_STATE_READY; + + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pause the DMA Transfer. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + + /* Process Locked */ + __HAL_LOCK(husart); + + if ((HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) && + (state == HAL_USART_STATE_BUSY_TX)) + { + /* Suspend the USART DMA Tx channel : use blocking DMA Suspend API (no callback) */ + if (husart->hdmatx != NULL) + { + /* Set the USART DMA Suspend callback to Null. + No call back execution at end of DMA Suspend procedure */ + husart->hdmatx->XferSuspendCallback = NULL; + + if (HAL_DMAEx_Suspend(husart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + else if ((state == HAL_USART_STATE_BUSY_RX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); + CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Set the USART DMA Suspend callback to Null. + No call back execution at end of DMA Suspend procedure */ + husart->hdmarx->XferSuspendCallback = NULL; + + if (HAL_DMAEx_Suspend(husart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + + if (state == HAL_USART_STATE_BUSY_TX_RX) + { + /* Set the USART DMA Suspend callback to Null. + No call back execution at end of DMA Suspend procedure */ + husart->hdmatx->XferSuspendCallback = NULL; + + if (HAL_DMAEx_Suspend(husart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Resume the DMA Transfer. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + + /* Process Locked */ + __HAL_LOCK(husart); + + if (state == HAL_USART_STATE_BUSY_TX) + { + /* Resume the USART DMA Tx channel */ + if (husart->hdmatx != NULL) + { + if (HAL_DMAEx_Resume(husart->hdmatx) != HAL_OK) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_ERROR; + } + } + } + else if ((state == HAL_USART_STATE_BUSY_RX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + /* Clear the Overrun flag before resuming the Rx transfer*/ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF); + + /* Re-enable PE and ERR (Frame error, noise error, overrun error) interrupts */ + if (husart->Init.Parity != USART_PARITY_NONE) + { + SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); + } + SET_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Resume the USART DMA Rx channel */ + if (husart->hdmarx != NULL) + { + if (HAL_DMAEx_Resume(husart->hdmarx) != HAL_OK) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_ERROR; + } + } + + if (state == HAL_USART_STATE_BUSY_TX_RX) + { + /* Resume the USART DMA Tx channel */ + if (husart->hdmatx != NULL) + { + if (HAL_DMAEx_Resume(husart->hdmatx) != HAL_OK) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_ERROR; + } + } + } + } + else + { + /* Nothing to do */ + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Stop the DMA Transfer. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart) +{ + /* The Lock is not implemented on this API to allow the user application + to call the HAL USART API under callbacks HAL_USART_TxCpltCallback() / HAL_USART_RxCpltCallback() / + HAL_USART_TxHalfCpltCallback / HAL_USART_RxHalfCpltCallback: + indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete + interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of + the stream and the corresponding call back is executed. */ + + /* Disable the USART Tx/Rx DMA requests */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the USART DMA tx channel */ + if (husart->hdmatx != NULL) + { + if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + /* Abort the USART DMA rx channel */ + if (husart->hdmarx != NULL) + { + if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + + USART_EndTransfer(husart); + husart->State = HAL_USART_STATE_READY; + + return HAL_OK; +} +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Abort ongoing transfers (blocking mode). + * @param husart USART handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable USART Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) + * - Set handle State to READY + * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Abort(USART_HandleTypeDef *husart) +{ + /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | + USART_CR1_TCIE)); + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the USART DMA Tx channel if enabled */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable the USART DMA Tx request if enabled */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the USART DMA Tx channel : use blocking DMA Abort API (no callback) */ + if (husart->hdmatx != NULL) + { + /* Set the USART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + husart->hdmatx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } + + /* Abort the USART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the USART DMA Rx request if enabled */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the USART DMA Rx channel : use blocking DMA Abort API (no callback) */ + if (husart->hdmarx != NULL) + { + /* Set the USART DMA Abort callback to Null. + No call back execution at end of DMA abort procedure */ + husart->hdmarx->XferAbortCallback = NULL; + + if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK) + { + if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) + { + /* Set error code to DMA */ + husart->ErrorCode = HAL_USART_ERROR_DMA; + + return HAL_TIMEOUT; + } + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* Reset Tx and Rx transfer counters */ + husart->TxXferCount = 0U; + husart->RxXferCount = 0U; + + /* Clear the Error flags in the ICR register */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); + + /* Flush the whole TX FIFO (if needed) */ + if (husart->FifoMode == USART_FIFOMODE_ENABLE) + { + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* Discard the received data */ + __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); + + /* Restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* Reset Handle ErrorCode to No Error */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + return HAL_OK; +} + +/** + * @brief Abort ongoing transfers (Interrupt mode). + * @param husart USART handle. + * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. + * This procedure performs following operations : + * - Disable USART Interrupts (Tx and Rx) + * - Disable the DMA transfer in the peripheral register (if enabled) + * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) + * - Set handle State to READY + * - At abort completion, call user abort complete callback + * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be + * considered as completed only when user abort complete callback is executed (not when exiting function). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Abort_IT(USART_HandleTypeDef *husart) +{ + uint32_t abortcplt = 1U; + + /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | + USART_CR1_TCIE)); + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* If DMA Tx and/or DMA Rx Handles are associated to USART Handle, DMA Abort complete callbacks should be initialised + before any call to DMA Abort functions */ + /* DMA Tx Handle is valid */ + if (husart->hdmatx != NULL) + { + /* Set DMA Abort Complete callback if USART DMA Tx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) + { + husart->hdmatx->XferAbortCallback = USART_DMATxAbortCallback; + } + else + { + husart->hdmatx->XferAbortCallback = NULL; + } + } + /* DMA Rx Handle is valid */ + if (husart->hdmarx != NULL) + { + /* Set DMA Abort Complete callback if USART DMA Rx request if enabled. + Otherwise, set it to NULL */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) + { + husart->hdmarx->XferAbortCallback = USART_DMARxAbortCallback; + } + else + { + husart->hdmarx->XferAbortCallback = NULL; + } + } + + /* Abort the USART DMA Tx channel if enabled */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) + { + /* Disable DMA Tx at USART level */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + /* Abort the USART DMA Tx channel : use non blocking DMA Abort API (callback) */ + if (husart->hdmatx != NULL) + { + /* USART Tx DMA Abort callback has already been initialised : + will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA TX */ + if (HAL_DMA_Abort_IT(husart->hdmatx) != HAL_OK) + { + husart->hdmatx->XferAbortCallback = NULL; + } + else + { + abortcplt = 0U; + } + } + } + + /* Abort the USART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the USART DMA Rx request if enabled */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); + + /* Abort the USART DMA Rx channel : use non blocking DMA Abort API (callback) */ + if (husart->hdmarx != NULL) + { + /* USART Rx DMA Abort callback has already been initialised : + will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) + { + husart->hdmarx->XferAbortCallback = NULL; + abortcplt = 1U; + } + else + { + abortcplt = 0U; + } + } + } +#endif /* HAL_DMA_MODULE_ENABLED */ + + /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ + if (abortcplt == 1U) + { + /* Reset Tx and Rx transfer counters */ + husart->TxXferCount = 0U; + husart->RxXferCount = 0U; + + /* Reset errorCode */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); + + /* Flush the whole TX FIFO (if needed) */ + if (husart->FifoMode == USART_FIFOMODE_ENABLE) + { + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* Discard the received data */ + __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); + + /* Restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* As no DMA to be aborted, call directly user Abort complete callback */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Complete Callback */ + husart->AbortCpltCallback(husart); +#else + /* Call legacy weak Abort Complete Callback */ + HAL_USART_AbortCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + + return HAL_OK; +} + +/** + * @brief Handle USART interrupt request. + * @param husart USART handle. + * @retval None + */ +void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) +{ + uint32_t isrflags = READ_REG(husart->Instance->ISR); + uint32_t cr1its = READ_REG(husart->Instance->CR1); + uint32_t cr3its = READ_REG(husart->Instance->CR3); + + uint32_t errorflags; + uint32_t errorcode; + + /* If no error occurs */ + errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_RTOF | + USART_ISR_UDR)); + if (errorflags == 0U) + { + /* USART in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U))) + { + if (husart->RxISR != NULL) + { + husart->RxISR(husart); + } + return; + } + } + + /* If some errors occur */ + if ((errorflags != 0U) + && (((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) + || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U))) + { + /* USART parity error interrupt occurred -------------------------------------*/ + if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) + { + __HAL_USART_CLEAR_IT(husart, USART_CLEAR_PEF); + + husart->ErrorCode |= HAL_USART_ERROR_PE; + } + + /* USART frame error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_USART_CLEAR_IT(husart, USART_CLEAR_FEF); + + husart->ErrorCode |= HAL_USART_ERROR_FE; + } + + /* USART noise error interrupt occurred --------------------------------------*/ + if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + __HAL_USART_CLEAR_IT(husart, USART_CLEAR_NEF); + + husart->ErrorCode |= HAL_USART_ERROR_NE; + } + + /* USART Over-Run interrupt occurred -----------------------------------------*/ + if (((isrflags & USART_ISR_ORE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || + ((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U))) + { + __HAL_USART_CLEAR_IT(husart, USART_CLEAR_OREF); + + husart->ErrorCode |= HAL_USART_ERROR_ORE; + } + + /* USART Receiver Timeout interrupt occurred ---------------------------------*/ + if (((isrflags & USART_ISR_RTOF) != 0U) && ((cr1its & USART_CR1_RTOIE) != 0U)) + { + __HAL_USART_CLEAR_IT(husart, USART_CLEAR_RTOF); + + husart->ErrorCode |= HAL_USART_ERROR_RTO; + } + + /* USART SPI slave underrun error interrupt occurred -------------------------*/ + if (((isrflags & USART_ISR_UDR) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) + { + /* Ignore SPI slave underrun errors when reception is going on */ + if (husart->State == HAL_USART_STATE_BUSY_RX) + { + __HAL_USART_CLEAR_UDRFLAG(husart); + return; + } + else + { + __HAL_USART_CLEAR_UDRFLAG(husart); + husart->ErrorCode |= HAL_USART_ERROR_UDR; + } + } + + /* Call USART Error Call back function if need be --------------------------*/ + if (husart->ErrorCode != HAL_USART_ERROR_NONE) + { + /* USART in mode Receiver ---------------------------------------------------*/ + if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) + && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) + || ((cr3its & USART_CR3_RXFTIE) != 0U))) + { + if (husart->RxISR != NULL) + { + husart->RxISR(husart); + } + } + + /* If Overrun error occurs, or if any error occurs in DMA mode reception, + consider error as blocking */ + errorcode = husart->ErrorCode & HAL_USART_ERROR_ORE; + if ((HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) || + (errorcode != 0U)) + { + /* Blocking error : transfer is aborted + Set the USART state ready to be able to start again the process, + Disable Interrupts, and disable DMA requests, if ongoing */ + USART_EndTransfer(husart); + +#if defined(HAL_DMA_MODULE_ENABLED) + /* Abort the USART DMA Rx channel if enabled */ + if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) + { + /* Disable the USART DMA Rx request if enabled */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR | USART_CR3_DMAR); + + /* Abort the USART DMA Tx channel */ + if (husart->hdmatx != NULL) + { + /* Set the USART Tx DMA Abort callback to NULL : no callback + executed at end of DMA abort procedure */ + husart->hdmatx->XferAbortCallback = NULL; + + /* Abort DMA TX */ + (void)HAL_DMA_Abort_IT(husart->hdmatx); + } + + /* Abort the USART DMA Rx channel */ + if (husart->hdmarx != NULL) + { + /* Set the USART Rx DMA Abort callback : + will lead to call HAL_USART_ErrorCallback() at end of DMA abort procedure */ + husart->hdmarx->XferAbortCallback = USART_DMAAbortOnError; + + /* Abort DMA RX */ + if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) + { + /* Call Directly husart->hdmarx->XferAbortCallback function in case of error */ + husart->hdmarx->XferAbortCallback(husart->hdmarx); + } + } + else + { + /* Call user error callback */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + HAL_USART_ErrorCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + } + else +#endif /* HAL_DMA_MODULE_ENABLED */ + { + /* Call user error callback */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + HAL_USART_ErrorCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + } + else + { + /* Non Blocking error : transfer could go on. + Error is notified to user through user error callback */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + HAL_USART_ErrorCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + } + } + return; + + } /* End if some error occurs */ + + + /* USART in mode Transmitter ------------------------------------------------*/ + if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) + && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) + || ((cr3its & USART_CR3_TXFTIE) != 0U))) + { + if (husart->TxISR != NULL) + { + husart->TxISR(husart); + } + return; + } + + /* USART in mode Transmitter (transmission end) -----------------------------*/ + if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) + { + USART_EndTransmit_IT(husart); + return; + } + + /* USART TX Fifo Empty occurred ----------------------------------------------*/ + if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Fifo Empty Callback */ + husart->TxFifoEmptyCallback(husart); +#else + /* Call legacy weak Tx Fifo Empty Callback */ + HAL_USARTEx_TxFifoEmptyCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + return; + } + + /* USART RX Fifo Full occurred ----------------------------------------------*/ + if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Fifo Full Callback */ + husart->RxFifoFullCallback(husart); +#else + /* Call legacy weak Rx Fifo Full Callback */ + HAL_USARTEx_RxFifoFullCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + return; + } +} + +/** + * @brief Tx Transfer completed callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_USART_TxHalfCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_USART_RxCpltCallback can be implemented in the user file. + */ +} + +/** + * @brief Rx Half Transfer completed callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_RxHalfCpltCallback can 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) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_TxRxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief USART error callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_ErrorCallback can be implemented in the user file. + */ +} + +/** + * @brief USART Abort Complete callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USART_AbortCpltCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_AbortCpltCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup USART_Exported_Functions_Group4 Peripheral State and Error functions + * @brief USART Peripheral State and Error functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Error functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to : + (+) Return the USART handle state + (+) Return the USART handle error code + +@endverbatim + * @{ + */ + + +/** + * @brief Return the USART handle state. + * @param husart pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART. + * @retval USART handle state + */ +HAL_USART_StateTypeDef HAL_USART_GetState(const 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 handle Error Code + */ +uint32_t HAL_USART_GetError(const USART_HandleTypeDef *husart) +{ + return husart->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup USART_Private_Functions USART Private Functions + * @{ + */ + +/** + * @brief Initialize the callbacks to their default values. + * @param husart USART handle. + * @retval none + */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) +void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart) +{ + /* Init the USART Callback settings */ + husart->TxHalfCpltCallback = HAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ + husart->TxCpltCallback = HAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ + husart->RxHalfCpltCallback = HAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ + husart->RxCpltCallback = HAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ + husart->TxRxCpltCallback = HAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ + husart->ErrorCallback = HAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ + husart->AbortCpltCallback = HAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ + husart->RxFifoFullCallback = HAL_USARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ + husart->TxFifoEmptyCallback = HAL_USARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ +} +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + +/** + * @brief End ongoing transfer on USART peripheral (following error detection or Transfer completion). + * @param husart USART handle. + * @retval None + */ +static void USART_EndTransfer(USART_HandleTypeDef *husart) +{ + /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | + USART_CR1_TCIE)); + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); + + /* At end of process, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; +} + +#if defined(HAL_DMA_MODULE_ENABLED) +/** + * @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 *)(hdma->Parent); + + /* Check if DMA in circular mode */ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + husart->TxXferCount = 0U; + + if (husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Disable the DMA transfer for transmit request by resetting the DMAT bit + in the USART CR3 register */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + } + } + /* DMA Circular mode */ + else + { + if (husart->State == HAL_USART_STATE_BUSY_TX) + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Complete Callback */ + husart->TxCpltCallback(husart); +#else + /* Call legacy weak Tx Complete Callback */ + HAL_USART_TxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + } +} + +/** + * @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 *)(hdma->Parent); + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Half Complete Callback */ + husart->TxHalfCpltCallback(husart); +#else + /* Call legacy weak Tx Half Complete Callback */ + HAL_USART_TxHalfCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @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 *)(hdma->Parent); + + /* Check if DMA in circular mode*/ + if (hdma->Mode != DMA_LINKEDLIST_CIRCULAR) + { + husart->RxXferCount = 0U; + + /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ + CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); + CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Disable the DMA RX transfer for the receiver request by resetting the DMAR bit + in USART CR3 register */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); + /* similarly, disable the DMA TX transfer that was started to provide the + clock to the slave device */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); + + if (husart->State == HAL_USART_STATE_BUSY_RX) + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + HAL_USART_RxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ + else + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + husart->State = HAL_USART_STATE_READY; + } + /* DMA circular mode */ + else + { + if (husart->State == HAL_USART_STATE_BUSY_RX) + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + HAL_USART_RxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ + else + { +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + } +} + +/** + * @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 *)(hdma->Parent); + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Half Complete Callback */ + husart->RxHalfCpltCallback(husart); +#else + /* Call legacy weak Rx Half Complete Callback */ + HAL_USART_RxHalfCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART communication error callback. + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMAError(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); + + husart->RxXferCount = 0U; + husart->TxXferCount = 0U; + USART_EndTransfer(husart); + + husart->ErrorCode |= HAL_USART_ERROR_DMA; + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + HAL_USART_ErrorCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART communication abort callback, when initiated by HAL services on Error + * (To be called at end of DMA Abort procedure following error occurrence). + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); + husart->RxXferCount = 0U; + husart->TxXferCount = 0U; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Error Callback */ + husart->ErrorCallback(husart); +#else + /* Call legacy weak Error Callback */ + HAL_USART_ErrorCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ +} + +/** + * @brief DMA USART Tx communication abort callback, when initiated by user + * (To be called at end of DMA Tx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Rx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); + + husart->hdmatx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (husart->hdmarx != NULL) + { + if (husart->hdmarx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + husart->TxXferCount = 0U; + husart->RxXferCount = 0U; + + /* Reset errorCode */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); + + /* Restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Complete Callback */ + husart->AbortCpltCallback(husart); +#else + /* Call legacy weak Abort Complete Callback */ + HAL_USART_AbortCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + +} + + +/** + * @brief DMA USART Rx communication abort callback, when initiated by user + * (To be called at end of DMA Rx Abort procedure following user abort request). + * @note When this callback is executed, User Abort complete call back is called only if no + * Abort still ongoing for Tx DMA Handle. + * @param hdma DMA handle. + * @retval None + */ +static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); + + husart->hdmarx->XferAbortCallback = NULL; + + /* Check if an Abort process is still ongoing */ + if (husart->hdmatx != NULL) + { + if (husart->hdmatx->XferAbortCallback != NULL) + { + return; + } + } + + /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ + husart->TxXferCount = 0U; + husart->RxXferCount = 0U; + + /* Reset errorCode */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + /* Clear the Error flags in the ICR register */ + __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); + + /* Restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + + /* Call user Abort complete callback */ +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Abort Complete Callback */ + husart->AbortCpltCallback(husart); +#else + /* Call legacy weak Abort Complete Callback */ + HAL_USART_AbortCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ +} + +#endif /* HAL_DMA_MODULE_ENABLED */ + +/** + * @brief Handle USART Communication Timeout. It waits + * until a flag is no longer in the specified status. + * @param husart USART handle. + * @param Flag Specifies the USART flag to check. + * @param Status the actual Flag status (SET or RESET). + * @param Tickstart Tick start value + * @param Timeout timeout duration. + * @retval HAL status + */ +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, + uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is set */ + while ((__HAL_USART_GET_FLAG(husart, Flag) ? SET : RESET) == Status) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + +/** + * @brief Configure the USART peripheral. + * @param husart USART handle. + * @retval HAL status + */ +static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart) +{ + uint32_t tmpreg; + USART_ClockSourceTypeDef clocksource; + HAL_StatusTypeDef ret = HAL_OK; + uint16_t brrtemp; + uint32_t usartdiv = 0x00000000; + uint32_t pclk; + + /* Check the parameters */ + 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)); + assert_param(IS_USART_PRESCALER(husart->Init.ClockPrescaler)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE and RE bits and 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 + * force OVER8 to 1 to allow to reach the maximum speed (Fclock/8) */ + tmpreg = (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode | USART_CR1_OVER8; + MODIFY_REG(husart->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*---------------------------- USART CR2 Configuration ---------------------*/ + /* Clear and configure the USART Clock, CPOL, CPHA, LBCL STOP and SLVEN bits: + * 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 (used in USART Synchronous SPI master mode only) + * set STOP[13:12] bits according to husart->Init.StopBits value */ + tmpreg = (uint32_t)(USART_CLOCK_ENABLE); + tmpreg |= (uint32_t)husart->Init.CLKLastBit; + tmpreg |= ((uint32_t)husart->Init.CLKPolarity | (uint32_t)husart->Init.CLKPhase); + tmpreg |= (uint32_t)husart->Init.StopBits; + MODIFY_REG(husart->Instance->CR2, USART_CR2_FIELDS, tmpreg); + + /*-------------------------- USART PRESC Configuration -----------------------*/ + /* Configure + * - USART Clock Prescaler : set PRESCALER according to husart->Init.ClockPrescaler value */ + MODIFY_REG(husart->Instance->PRESC, USART_PRESC_PRESCALER, husart->Init.ClockPrescaler); + + /*-------------------------- USART BRR Configuration -----------------------*/ + /* BRR is filled-up according to OVER8 bit setting which is forced to 1 */ + USART_GETCLOCKSOURCE(husart, clocksource); + + switch (clocksource) + { + case USART_CLOCKSOURCE_PCLK1: + pclk = HAL_RCC_GetPCLK1Freq(); + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + break; + case USART_CLOCKSOURCE_PCLK2: + pclk = HAL_RCC_GetPCLK2Freq(); + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + break; + case USART_CLOCKSOURCE_PLL2Q: + pclk = HAL_RCC_GetPLL2QFreq(); + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + break; + case USART_CLOCKSOURCE_PLL3Q: + pclk = HAL_RCC_GetPLL3QFreq(); + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + break; + case USART_CLOCKSOURCE_HSI: + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIDIV) != 0U) + { + usartdiv = (uint32_t)(USART_DIV_SAMPLING8((HSI_VALUE >> (__HAL_RCC_GET_HSI_DIVIDER() >> 3U)), + husart->Init.BaudRate, husart->Init.ClockPrescaler)); + } + else + { + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(HSI_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + } + break; + case USART_CLOCKSOURCE_CSI: + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(CSI_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + break; + case USART_CLOCKSOURCE_LSE: + usartdiv = (uint32_t)(USART_DIV_SAMPLING8(LSE_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); + break; + default: + ret = HAL_ERROR; + break; + } + + /* USARTDIV must be greater than or equal to 0d16 and smaller than or equal to ffff */ + if ((usartdiv >= USART_BRR_MIN) && (usartdiv <= USART_BRR_MAX)) + { + brrtemp = (uint16_t)(usartdiv & 0xFFF0U); + brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U); + husart->Instance->BRR = brrtemp; + } + else + { + ret = HAL_ERROR; + } + + /* Initialize the number of data to process during RX/TX ISR execution */ + husart->NbTxDataToProcess = 1U; + husart->NbRxDataToProcess = 1U; + + /* Clear ISR function pointers */ + husart->RxISR = NULL; + husart->TxISR = NULL; + + return ret; +} + +/** + * @brief Check the USART Idle State. + * @param husart USART handle. + * @retval HAL status + */ +static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart) +{ + uint32_t tickstart; + + /* Initialize the USART ErrorCode */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + /* Init tickstart for timeout management */ + tickstart = HAL_GetTick(); + + /* Check if the Transmitter is enabled */ + if ((husart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_ISR_TEACK, RESET, tickstart, USART_TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if ((husart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if (USART_WaitOnFlagUntilTimeout(husart, USART_ISR_REACK, RESET, tickstart, USART_TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout occurred */ + return HAL_TIMEOUT; + } + } + + /* Initialize the USART state*/ + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Simplex send an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Transmit_IT(). + * @note The USART errors are not managed to avoid the overrun error. + * @note ISR function executed when FIFO mode is disabled and when the + * data word length is less than 9 bits long. + * @param husart USART handle. + * @retval None + */ +static void USART_TxISR_8BIT(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + + /* Check that a Tx process is ongoing */ + if ((state == HAL_USART_STATE_BUSY_TX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + if (husart->TxXferCount == 0U) + { + /* Disable the USART Transmit data register empty interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + } + else + { + husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr & (uint8_t)0xFF); + husart->pTxBuffPtr++; + husart->TxXferCount--; + } + } +} + +/** + * @brief Simplex send an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Transmit_IT(). + * @note The USART errors are not managed to avoid the overrun error. + * @note ISR function executed when FIFO mode is disabled and when the + * data word length is 9 bits long. + * @param husart USART handle. + * @retval None + */ +static void USART_TxISR_16BIT(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + const uint16_t *tmp; + + if ((state == HAL_USART_STATE_BUSY_TX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + if (husart->TxXferCount == 0U) + { + /* Disable the USART Transmit data register empty interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + } + else + { + tmp = (const uint16_t *) husart->pTxBuffPtr; + husart->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); + husart->pTxBuffPtr += 2U; + husart->TxXferCount--; + } + } +} + +/** + * @brief Simplex send an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Transmit_IT(). + * @note The USART errors are not managed to avoid the overrun error. + * @note ISR function executed when FIFO mode is enabled and when the + * data word length is less than 9 bits long. + * @param husart USART handle. + * @retval None + */ +static void USART_TxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + uint16_t nb_tx_data; + + /* Check that a Tx process is ongoing */ + if ((state == HAL_USART_STATE_BUSY_TX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + for (nb_tx_data = husart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) + { + if (husart->TxXferCount == 0U) + { + /* Disable the TX FIFO threshold interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXFT); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + + break; /* force exit loop */ + } + else if (__HAL_USART_GET_FLAG(husart, USART_FLAG_TXFNF) == SET) + { + husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr & (uint8_t)0xFF); + husart->pTxBuffPtr++; + husart->TxXferCount--; + } + else + { + /* Nothing to do */ + } + } + } +} + +/** + * @brief Simplex send an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Transmit_IT(). + * @note The USART errors are not managed to avoid the overrun error. + * @note ISR function executed when FIFO mode is enabled and when the + * data word length is 9 bits long. + * @param husart USART handle. + * @retval None + */ +static void USART_TxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + const uint16_t *tmp; + uint16_t nb_tx_data; + + /* Check that a Tx process is ongoing */ + if ((state == HAL_USART_STATE_BUSY_TX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + for (nb_tx_data = husart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) + { + if (husart->TxXferCount == 0U) + { + /* Disable the TX FIFO threshold interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXFT); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + + break; /* force exit loop */ + } + else if (__HAL_USART_GET_FLAG(husart, USART_FLAG_TXFNF) == SET) + { + tmp = (const uint16_t *) husart->pTxBuffPtr; + husart->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); + husart->pTxBuffPtr += 2U; + husart->TxXferCount--; + } + else + { + /* Nothing to do */ + } + } + } +} + +/** + * @brief Wraps up transmission in non-blocking mode. + * @param husart Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +static void USART_EndTransmit_IT(USART_HandleTypeDef *husart) +{ + /* Disable the USART Transmit Complete Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TC); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + /* Clear TxISR function pointer */ + husart->TxISR = NULL; + + if (husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Clear overrun flag and discard the received data */ + __HAL_USART_CLEAR_OREFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); + + /* Tx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Complete Callback */ + husart->TxCpltCallback(husart); +#else + /* Call legacy weak Tx Complete Callback */ + HAL_USART_TxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else if (husart->RxXferCount == 0U) + { + /* TxRx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } +} + + +/** + * @brief Simplex receive an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Receive_IT(). + * @note ISR function executed when FIFO mode is disabled and when the + * data word length is less than 9 bits long. + * @param husart USART handle + * @retval None + */ +static void USART_RxISR_8BIT(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + uint16_t txdatacount; + uint16_t uhMask = husart->Mask; + uint32_t txftie; + + if ((state == HAL_USART_STATE_BUSY_RX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + *husart->pRxBuffPtr = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + husart->pRxBuffPtr++; + husart->RxXferCount--; + + if (husart->RxXferCount == 0U) + { + /* Disable the USART Parity Error Interrupt and RXNE interrupt*/ + CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Clear RxISR function pointer */ + husart->RxISR = NULL; + + /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ + txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); + txdatacount = husart->TxXferCount; + + if (state == HAL_USART_STATE_BUSY_RX) + { + /* Clear SPI slave underrun flag and discard transmit data */ + if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) + { + __HAL_USART_CLEAR_UDRFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* Rx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + HAL_USART_RxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && + (txftie != USART_CR3_TXFTIE) && + (txdatacount == 0U)) + { + /* TxRx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + else if ((state == HAL_USART_STATE_BUSY_RX) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + else + { + /* Nothing to do */ + } + } +} + +/** + * @brief Simplex receive an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Receive_IT(). + * @note ISR function executed when FIFO mode is disabled and when the + * data word length is 9 bits long. + * @param husart USART handle + * @retval None + */ +static void USART_RxISR_16BIT(USART_HandleTypeDef *husart) +{ + const HAL_USART_StateTypeDef state = husart->State; + uint16_t txdatacount; + uint16_t *tmp; + uint16_t uhMask = husart->Mask; + uint32_t txftie; + + if ((state == HAL_USART_STATE_BUSY_RX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + tmp = (uint16_t *) husart->pRxBuffPtr; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + husart->pRxBuffPtr += 2U; + husart->RxXferCount--; + + if (husart->RxXferCount == 0U) + { + /* Disable the USART Parity Error Interrupt and RXNE interrupt*/ + CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); + + /* Clear RxISR function pointer */ + husart->RxISR = NULL; + + /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ + txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); + txdatacount = husart->TxXferCount; + + if (state == HAL_USART_STATE_BUSY_RX) + { + /* Clear SPI slave underrun flag and discard transmit data */ + if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) + { + __HAL_USART_CLEAR_UDRFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* Rx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + HAL_USART_RxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && + (txftie != USART_CR3_TXFTIE) && + (txdatacount == 0U)) + { + /* TxRx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + else if ((state == HAL_USART_STATE_BUSY_RX) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + else + { + /* Nothing to do */ + } + } +} + +/** + * @brief Simplex receive an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Receive_IT(). + * @note ISR function executed when FIFO mode is enabled and when the + * data word length is less than 9 bits long. + * @param husart USART handle + * @retval None + */ +static void USART_RxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart) +{ + HAL_USART_StateTypeDef state = husart->State; + uint16_t txdatacount; + uint16_t rxdatacount; + uint16_t uhMask = husart->Mask; + uint16_t nb_rx_data; + uint32_t txftie; + + /* Check that a Rx process is ongoing */ + if ((state == HAL_USART_STATE_BUSY_RX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + for (nb_rx_data = husart->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) + { + if (__HAL_USART_GET_FLAG(husart, USART_FLAG_RXFNE) == SET) + { + *husart->pRxBuffPtr = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); + husart->pRxBuffPtr++; + husart->RxXferCount--; + + if (husart->RxXferCount == 0U) + { + /* Disable the USART Parity Error Interrupt */ + CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) + and RX FIFO Threshold interrupt */ + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Clear RxISR function pointer */ + husart->RxISR = NULL; + + /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ + txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); + txdatacount = husart->TxXferCount; + + if (state == HAL_USART_STATE_BUSY_RX) + { + /* Clear SPI slave underrun flag and discard transmit data */ + if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) + { + __HAL_USART_CLEAR_UDRFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* Rx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + state = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + HAL_USART_RxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && + (txftie != USART_CR3_TXFTIE) && + (txdatacount == 0U)) + { + /* TxRx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + state = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + else if ((state == HAL_USART_STATE_BUSY_RX) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + else + { + /* Nothing to do */ + } + } + } + + /* When remaining number of bytes to receive is less than the RX FIFO + threshold, next incoming frames are processed as if FIFO mode was + disabled (i.e. one interrupt per received frame). + */ + rxdatacount = husart->RxXferCount; + if (((rxdatacount != 0U)) && (rxdatacount < husart->NbRxDataToProcess)) + { + /* Disable the USART RXFT interrupt*/ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); + + /* Update the RxISR function pointer */ + husart->RxISR = USART_RxISR_8BIT; + + /* Enable the USART Data Register Not Empty interrupt */ + SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + + if ((husart->TxXferCount == 0U) && + (state == HAL_USART_STATE_BUSY_TX_RX) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @brief Simplex receive an amount of data in non-blocking mode. + * @note Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Receive_IT(). + * @note ISR function executed when FIFO mode is enabled and when the + * data word length is 9 bits long. + * @param husart USART handle + * @retval None + */ +static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart) +{ + HAL_USART_StateTypeDef state = husart->State; + uint16_t txdatacount; + uint16_t rxdatacount; + uint16_t *tmp; + uint16_t uhMask = husart->Mask; + uint16_t nb_rx_data; + uint32_t txftie; + + /* Check that a Tx process is ongoing */ + if ((state == HAL_USART_STATE_BUSY_RX) || + (state == HAL_USART_STATE_BUSY_TX_RX)) + { + for (nb_rx_data = husart->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) + { + if (__HAL_USART_GET_FLAG(husart, USART_FLAG_RXFNE) == SET) + { + tmp = (uint16_t *) husart->pRxBuffPtr; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + husart->pRxBuffPtr += 2U; + husart->RxXferCount--; + + if (husart->RxXferCount == 0U) + { + /* Disable the USART Parity Error Interrupt */ + CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) + and RX FIFO Threshold interrupt */ + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); + + /* Clear RxISR function pointer */ + husart->RxISR = NULL; + + /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ + txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); + txdatacount = husart->TxXferCount; + + if (state == HAL_USART_STATE_BUSY_RX) + { + /* Clear SPI slave underrun flag and discard transmit data */ + if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) + { + __HAL_USART_CLEAR_UDRFLAG(husart); + __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); + } + + /* Rx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + state = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Rx Complete Callback */ + husart->RxCpltCallback(husart); +#else + /* Call legacy weak Rx Complete Callback */ + HAL_USART_RxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && + (txftie != USART_CR3_TXFTIE) && + (txdatacount == 0U)) + { + /* TxRx process is completed, restore husart->State to Ready */ + husart->State = HAL_USART_STATE_READY; + state = HAL_USART_STATE_READY; + +#if (USE_HAL_USART_REGISTER_CALLBACKS == 1) + /* Call registered Tx Rx Complete Callback */ + husart->TxRxCpltCallback(husart); +#else + /* Call legacy weak Tx Rx Complete Callback */ + HAL_USART_TxRxCpltCallback(husart); +#endif /* USE_HAL_USART_REGISTER_CALLBACKS */ + } + else + { + /* Nothing to do */ + } + } + else if ((state == HAL_USART_STATE_BUSY_RX) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + else + { + /* Nothing to do */ + } + } + } + + /* When remaining number of bytes to receive is less than the RX FIFO + threshold, next incoming frames are processed as if FIFO mode was + disabled (i.e. one interrupt per received frame). + */ + rxdatacount = husart->RxXferCount; + if (((rxdatacount != 0U)) && (rxdatacount < husart->NbRxDataToProcess)) + { + /* Disable the USART RXFT interrupt*/ + CLEAR_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); + + /* Update the RxISR function pointer */ + husart->RxISR = USART_RxISR_16BIT; + + /* Enable the USART Data Register Not Empty interrupt */ + SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); + + if ((husart->TxXferCount == 0U) && + (state == HAL_USART_STATE_BUSY_TX_RX) && + (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) + { + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); + } + } + } + else + { + /* Clear RXNE interrupt flag */ + __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); + } +} + +/** + * @} + */ + +#endif /* HAL_USART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart_ex.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart_ex.c index 73d05a937..04265efa8 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart_ex.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_usart_ex.c @@ -1,541 +1,540 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_usart_ex.c - * @author MCD Application Team - * @brief Extended USART HAL module driver. - * This file provides firmware functions to manage the following extended - * functionalities of the Universal Synchronous Receiver Transmitter Peripheral (USART). - * + Peripheral Control functions - * - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### USART peripheral extended features ##### - ============================================================================== - - (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. - - -@- When USART operates in FIFO mode, FIFO mode must be enabled prior - starting RX/TX transfers. Also RX/TX FIFO thresholds must be - configured prior starting RX/TX transfers. - - (#) Slave mode enabling/disabling and NSS pin configuration. - - -@- When USART operates in Slave mode, Slave mode must be enabled prior - starting RX/TX transfers. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup USARTEx USARTEx - * @brief USART Extended HAL module driver - * @{ - */ - -#ifdef HAL_USART_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/** @defgroup USARTEx_Private_Constants USARTEx Private Constants - * @{ - */ -/* USART RX FIFO depth */ -#define RX_FIFO_DEPTH 16U - -/* USART TX FIFO depth */ -#define TX_FIFO_DEPTH 16U -/** - * @} - */ - -/* Private define ------------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup USARTEx_Private_Functions USARTEx Private Functions - * @{ - */ -static void USARTEx_SetNbDataToProcess(USART_HandleTypeDef *husart); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup USARTEx_Exported_Functions USARTEx Exported Functions - * @{ - */ - -/** @defgroup USARTEx_Exported_Functions_Group1 IO operation functions - * @brief Extended USART Transmit/Receive functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - This subsection provides a set of FIFO mode related callback functions. - - (#) TX/RX Fifos Callbacks: - (+) HAL_USARTEx_RxFifoFullCallback() - (+) HAL_USARTEx_TxFifoEmptyCallback() - -@endverbatim - * @{ - */ - -/** - * @brief USART RX Fifo full callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USARTEx_RxFifoFullCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USARTEx_RxFifoFullCallback can be implemented in the user file. - */ -} - -/** - * @brief USART TX Fifo empty callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USARTEx_TxFifoEmptyCallback(USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USARTEx_TxFifoEmptyCallback can be implemented in the user file. - */ -} - -/** - * @} - */ - -/** @defgroup USARTEx_Exported_Functions_Group2 Peripheral Control functions - * @brief Extended Peripheral Control functions - * -@verbatim - =============================================================================== - ##### Peripheral Control functions ##### - =============================================================================== - [..] This section provides the following functions: - (+) HAL_USARTEx_EnableSPISlaveMode() API enables the SPI slave mode - (+) HAL_USARTEx_DisableSPISlaveMode() API disables the SPI slave mode - (+) HAL_USARTEx_ConfigNSS API configures the Slave Select input pin (NSS) - (+) HAL_USARTEx_EnableFifoMode() API enables the FIFO mode - (+) HAL_USARTEx_DisableFifoMode() API disables the FIFO mode - (+) HAL_USARTEx_SetTxFifoThreshold() API sets the TX FIFO threshold - (+) HAL_USARTEx_SetRxFifoThreshold() API sets the RX FIFO threshold - - -@endverbatim - * @{ - */ - -/** - * @brief Enable the SPI slave mode. - * @note When the USART operates in SPI slave mode, it handles data flow using - * the serial interface clock derived from the external SCLK signal - * provided by the external master SPI device. - * @note In SPI slave mode, the USART must be enabled before starting the master - * communications (or between frames while the clock is stable). Otherwise, - * if the USART slave is enabled while the master is in the middle of a - * frame, it will become desynchronized with the master. - * @note The data register of the slave needs to be ready before the first edge - * of the communication clock or before the end of the ongoing communication, - * otherwise the SPI slave will transmit zeros. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_EnableSlaveMode(USART_HandleTypeDef *husart) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_SPI_SLAVE_INSTANCE(husart->Instance)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* In SPI slave mode mode, the following bits must be kept cleared: - - LINEN and CLKEN bit in the USART_CR2 register - - HDSEL, SCEN and IREN bits in the USART_CR3 register.*/ - CLEAR_BIT(husart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); - - /* Enable SPI slave mode */ - SET_BIT(husart->Instance->CR2, USART_CR2_SLVEN); - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - husart->SlaveMode = USART_SLAVEMODE_ENABLE; - - husart->State = HAL_USART_STATE_READY; - - /* Enable USART */ - __HAL_USART_ENABLE(husart); - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Disable the SPI slave mode. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_DisableSlaveMode(USART_HandleTypeDef *husart) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_SPI_SLAVE_INSTANCE(husart->Instance)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* Disable SPI slave mode */ - CLEAR_BIT(husart->Instance->CR2, USART_CR2_SLVEN); - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - husart->SlaveMode = USART_SLAVEMODE_DISABLE; - - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Configure the Slave Select input pin (NSS). - * @note Software NSS management: SPI slave will always be selected and NSS - * input pin will be ignored. - * @note Hardware NSS management: the SPI slave selection depends on NSS - * input pin. The slave is selected when NSS is low and deselected when - * NSS is high. - * @param husart USART handle. - * @param NSSConfig NSS configuration. - * This parameter can be one of the following values: - * @arg @ref USART_NSS_HARD - * @arg @ref USART_NSS_SOFT - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_ConfigNSS(USART_HandleTypeDef *husart, uint32_t NSSConfig) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_SPI_SLAVE_INSTANCE(husart->Instance)); - assert_param(IS_USART_NSS(NSSConfig)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* Program DIS_NSS bit in the USART_CR2 register */ - MODIFY_REG(husart->Instance->CR2, USART_CR2_DIS_NSS, NSSConfig); - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Enable the FIFO mode. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_EnableFifoMode(USART_HandleTypeDef *husart) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* Enable FIFO mode */ - SET_BIT(tmpcr1, USART_CR1_FIFOEN); - husart->FifoMode = USART_FIFOMODE_ENABLE; - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - /* Determine the number of data to process during RX/TX ISR execution */ - USARTEx_SetNbDataToProcess(husart); - - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Disable the FIFO mode. - * @param husart USART handle. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_DisableFifoMode(USART_HandleTypeDef *husart) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* Enable FIFO mode */ - CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); - husart->FifoMode = USART_FIFOMODE_DISABLE; - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Set the TXFIFO threshold. - * @param husart USART handle. - * @param Threshold TX FIFO threshold value - * This parameter can be one of the following values: - * @arg @ref USART_TXFIFO_THRESHOLD_1_8 - * @arg @ref USART_TXFIFO_THRESHOLD_1_4 - * @arg @ref USART_TXFIFO_THRESHOLD_1_2 - * @arg @ref USART_TXFIFO_THRESHOLD_3_4 - * @arg @ref USART_TXFIFO_THRESHOLD_7_8 - * @arg @ref USART_TXFIFO_THRESHOLD_8_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_SetTxFifoThreshold(USART_HandleTypeDef *husart, uint32_t Threshold) -{ - uint32_t tmpcr1; - - /* Check parameters */ - assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); - assert_param(IS_USART_TXFIFO_THRESHOLD(Threshold)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* Update TX threshold configuration */ - MODIFY_REG(husart->Instance->CR3, USART_CR3_TXFTCFG, Threshold); - - /* Determine the number of data to process during RX/TX ISR execution */ - USARTEx_SetNbDataToProcess(husart); - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @brief Set the RXFIFO threshold. - * @param husart USART handle. - * @param Threshold RX FIFO threshold value - * This parameter can be one of the following values: - * @arg @ref USART_RXFIFO_THRESHOLD_1_8 - * @arg @ref USART_RXFIFO_THRESHOLD_1_4 - * @arg @ref USART_RXFIFO_THRESHOLD_1_2 - * @arg @ref USART_RXFIFO_THRESHOLD_3_4 - * @arg @ref USART_RXFIFO_THRESHOLD_7_8 - * @arg @ref USART_RXFIFO_THRESHOLD_8_8 - * @retval HAL status - */ -HAL_StatusTypeDef HAL_USARTEx_SetRxFifoThreshold(USART_HandleTypeDef *husart, uint32_t Threshold) -{ - uint32_t tmpcr1; - - /* Check the parameters */ - assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); - assert_param(IS_USART_RXFIFO_THRESHOLD(Threshold)); - - /* Process Locked */ - __HAL_LOCK(husart); - - husart->State = HAL_USART_STATE_BUSY; - - /* Save actual USART configuration */ - tmpcr1 = READ_REG(husart->Instance->CR1); - - /* Disable USART */ - __HAL_USART_DISABLE(husart); - - /* Update RX threshold configuration */ - MODIFY_REG(husart->Instance->CR3, USART_CR3_RXFTCFG, Threshold); - - /* Determine the number of data to process during RX/TX ISR execution */ - USARTEx_SetNbDataToProcess(husart); - - /* Restore USART configuration */ - WRITE_REG(husart->Instance->CR1, tmpcr1); - - husart->State = HAL_USART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup USARTEx_Private_Functions - * @{ - */ - -/** - * @brief Calculate the number of data to process in RX/TX ISR. - * @note The RX FIFO depth and the TX FIFO depth is extracted from - * the USART configuration registers. - * @param husart USART handle. - * @retval None - */ -static void USARTEx_SetNbDataToProcess(USART_HandleTypeDef *husart) -{ - uint8_t rx_fifo_depth; - uint8_t tx_fifo_depth; - uint8_t rx_fifo_threshold; - uint8_t tx_fifo_threshold; - /* 2 0U/1U added for MISRAC2012-Rule-18.1_b and MISRAC2012-Rule-18.1_d */ - static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; - static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; - - if (husart->FifoMode == USART_FIFOMODE_DISABLE) - { - husart->NbTxDataToProcess = 1U; - husart->NbRxDataToProcess = 1U; - } - else - { - rx_fifo_depth = RX_FIFO_DEPTH; - tx_fifo_depth = TX_FIFO_DEPTH; - rx_fifo_threshold = (uint8_t)((READ_BIT(husart->Instance->CR3, - USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos) & 0xFFU); - tx_fifo_threshold = (uint8_t)((READ_BIT(husart->Instance->CR3, - USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos) & 0xFFU); - husart->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / - (uint16_t)denominator[tx_fifo_threshold]; - husart->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / - (uint16_t)denominator[rx_fifo_threshold]; - } -} -/** - * @} - */ - -#endif /* HAL_USART_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_usart_ex.c + * @author MCD Application Team + * @brief Extended USART HAL module driver. + * This file provides firmware functions to manage the following extended + * functionalities of the Universal Synchronous Receiver Transmitter Peripheral (USART). + * + Peripheral Control functions + * + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### USART peripheral extended features ##### + ============================================================================== + + (#) FIFO mode enabling/disabling and RX/TX FIFO threshold programming. + + -@- When USART operates in FIFO mode, FIFO mode must be enabled prior + starting RX/TX transfers. Also RX/TX FIFO thresholds must be + configured prior starting RX/TX transfers. + + (#) Slave mode enabling/disabling and NSS pin configuration. + + -@- When USART operates in Slave mode, Slave mode must be enabled prior + starting RX/TX transfers. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup USARTEx USARTEx + * @brief USART Extended HAL module driver + * @{ + */ + +#ifdef HAL_USART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/** @defgroup USARTEx_Private_Constants USARTEx Private Constants + * @{ + */ +/* USART RX FIFO depth */ +#define RX_FIFO_DEPTH 16U + +/* USART TX FIFO depth */ +#define TX_FIFO_DEPTH 16U +/** + * @} + */ + +/* Private define ------------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup USARTEx_Private_Functions USARTEx Private Functions + * @{ + */ +static void USARTEx_SetNbDataToProcess(USART_HandleTypeDef *husart); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup USARTEx_Exported_Functions USARTEx Exported Functions + * @{ + */ + +/** @defgroup USARTEx_Exported_Functions_Group1 IO operation functions + * @brief Extended USART Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + This subsection provides a set of FIFO mode related callback functions. + + (#) TX/RX Fifos Callbacks: + (+) HAL_USARTEx_RxFifoFullCallback() + (+) HAL_USARTEx_TxFifoEmptyCallback() + +@endverbatim + * @{ + */ + +/** + * @brief USART RX Fifo full callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USARTEx_RxFifoFullCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USARTEx_RxFifoFullCallback can be implemented in the user file. + */ +} + +/** + * @brief USART TX Fifo empty callback. + * @param husart USART handle. + * @retval None + */ +__weak void HAL_USARTEx_TxFifoEmptyCallback(USART_HandleTypeDef *husart) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(husart); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USARTEx_TxFifoEmptyCallback can be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup USARTEx_Exported_Functions_Group2 Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides the following functions: + (+) HAL_USARTEx_EnableSPISlaveMode() API enables the SPI slave mode + (+) HAL_USARTEx_DisableSPISlaveMode() API disables the SPI slave mode + (+) HAL_USARTEx_ConfigNSS API configures the Slave Select input pin (NSS) + (+) HAL_USARTEx_EnableFifoMode() API enables the FIFO mode + (+) HAL_USARTEx_DisableFifoMode() API disables the FIFO mode + (+) HAL_USARTEx_SetTxFifoThreshold() API sets the TX FIFO threshold + (+) HAL_USARTEx_SetRxFifoThreshold() API sets the RX FIFO threshold + + +@endverbatim + * @{ + */ + +/** + * @brief Enable the SPI slave mode. + * @note When the USART operates in SPI slave mode, it handles data flow using + * the serial interface clock derived from the external SCLK signal + * provided by the external master SPI device. + * @note In SPI slave mode, the USART must be enabled before starting the master + * communications (or between frames while the clock is stable). Otherwise, + * if the USART slave is enabled while the master is in the middle of a + * frame, it will become desynchronized with the master. + * @note The data register of the slave needs to be ready before the first edge + * of the communication clock or before the end of the ongoing communication, + * otherwise the SPI slave will transmit zeros. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_EnableSlaveMode(USART_HandleTypeDef *husart) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_SPI_SLAVE_INSTANCE(husart->Instance)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* In SPI slave mode mode, the following bits must be kept cleared: + - LINEN and CLKEN bit in the USART_CR2 register + - HDSEL, SCEN and IREN bits in the USART_CR3 register.*/ + CLEAR_BIT(husart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); + + /* Enable SPI slave mode */ + SET_BIT(husart->Instance->CR2, USART_CR2_SLVEN); + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + husart->SlaveMode = USART_SLAVEMODE_ENABLE; + + husart->State = HAL_USART_STATE_READY; + + /* Enable USART */ + __HAL_USART_ENABLE(husart); + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Disable the SPI slave mode. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_DisableSlaveMode(USART_HandleTypeDef *husart) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_SPI_SLAVE_INSTANCE(husart->Instance)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* Disable SPI slave mode */ + CLEAR_BIT(husart->Instance->CR2, USART_CR2_SLVEN); + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + husart->SlaveMode = USART_SLAVEMODE_DISABLE; + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Configure the Slave Select input pin (NSS). + * @note Software NSS management: SPI slave will always be selected and NSS + * input pin will be ignored. + * @note Hardware NSS management: the SPI slave selection depends on NSS + * input pin. The slave is selected when NSS is low and deselected when + * NSS is high. + * @param husart USART handle. + * @param NSSConfig NSS configuration. + * This parameter can be one of the following values: + * @arg @ref USART_NSS_HARD + * @arg @ref USART_NSS_SOFT + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_ConfigNSS(USART_HandleTypeDef *husart, uint32_t NSSConfig) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_SPI_SLAVE_INSTANCE(husart->Instance)); + assert_param(IS_USART_NSS(NSSConfig)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* Program DIS_NSS bit in the USART_CR2 register */ + MODIFY_REG(husart->Instance->CR2, USART_CR2_DIS_NSS, NSSConfig); + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Enable the FIFO mode. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_EnableFifoMode(USART_HandleTypeDef *husart) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* Enable FIFO mode */ + SET_BIT(tmpcr1, USART_CR1_FIFOEN); + husart->FifoMode = USART_FIFOMODE_ENABLE; + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + /* Determine the number of data to process during RX/TX ISR execution */ + USARTEx_SetNbDataToProcess(husart); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Disable the FIFO mode. + * @param husart USART handle. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_DisableFifoMode(USART_HandleTypeDef *husart) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* Disable FIFO mode */ + CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); + husart->FifoMode = USART_FIFOMODE_DISABLE; + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Set the TXFIFO threshold. + * @param husart USART handle. + * @param Threshold TX FIFO threshold value + * This parameter can be one of the following values: + * @arg @ref USART_TXFIFO_THRESHOLD_1_8 + * @arg @ref USART_TXFIFO_THRESHOLD_1_4 + * @arg @ref USART_TXFIFO_THRESHOLD_1_2 + * @arg @ref USART_TXFIFO_THRESHOLD_3_4 + * @arg @ref USART_TXFIFO_THRESHOLD_7_8 + * @arg @ref USART_TXFIFO_THRESHOLD_8_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_SetTxFifoThreshold(USART_HandleTypeDef *husart, uint32_t Threshold) +{ + uint32_t tmpcr1; + + /* Check parameters */ + assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); + assert_param(IS_USART_TXFIFO_THRESHOLD(Threshold)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* Update TX threshold configuration */ + MODIFY_REG(husart->Instance->CR3, USART_CR3_TXFTCFG, Threshold); + + /* Determine the number of data to process during RX/TX ISR execution */ + USARTEx_SetNbDataToProcess(husart); + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Set the RXFIFO threshold. + * @param husart USART handle. + * @param Threshold RX FIFO threshold value + * This parameter can be one of the following values: + * @arg @ref USART_RXFIFO_THRESHOLD_1_8 + * @arg @ref USART_RXFIFO_THRESHOLD_1_4 + * @arg @ref USART_RXFIFO_THRESHOLD_1_2 + * @arg @ref USART_RXFIFO_THRESHOLD_3_4 + * @arg @ref USART_RXFIFO_THRESHOLD_7_8 + * @arg @ref USART_RXFIFO_THRESHOLD_8_8 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USARTEx_SetRxFifoThreshold(USART_HandleTypeDef *husart, uint32_t Threshold) +{ + uint32_t tmpcr1; + + /* Check the parameters */ + assert_param(IS_UART_FIFO_INSTANCE(husart->Instance)); + assert_param(IS_USART_RXFIFO_THRESHOLD(Threshold)); + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->State = HAL_USART_STATE_BUSY; + + /* Save actual USART configuration */ + tmpcr1 = READ_REG(husart->Instance->CR1); + + /* Disable USART */ + __HAL_USART_DISABLE(husart); + + /* Update RX threshold configuration */ + MODIFY_REG(husart->Instance->CR3, USART_CR3_RXFTCFG, Threshold); + + /* Determine the number of data to process during RX/TX ISR execution */ + USARTEx_SetNbDataToProcess(husart); + + /* Restore USART configuration */ + WRITE_REG(husart->Instance->CR1, tmpcr1); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup USARTEx_Private_Functions + * @{ + */ + +/** + * @brief Calculate the number of data to process in RX/TX ISR. + * @note The RX FIFO depth and the TX FIFO depth is extracted from + * the USART configuration registers. + * @param husart USART handle. + * @retval None + */ +static void USARTEx_SetNbDataToProcess(USART_HandleTypeDef *husart) +{ + uint8_t rx_fifo_depth; + uint8_t tx_fifo_depth; + uint8_t rx_fifo_threshold; + uint8_t tx_fifo_threshold; + /* 2 0U/1U added for MISRAC2012-Rule-18.1_b and MISRAC2012-Rule-18.1_d */ + static const uint8_t numerator[] = {1U, 1U, 1U, 3U, 7U, 1U, 0U, 0U}; + static const uint8_t denominator[] = {8U, 4U, 2U, 4U, 8U, 1U, 1U, 1U}; + + if (husart->FifoMode == USART_FIFOMODE_DISABLE) + { + husart->NbTxDataToProcess = 1U; + husart->NbRxDataToProcess = 1U; + } + else + { + rx_fifo_depth = RX_FIFO_DEPTH; + tx_fifo_depth = TX_FIFO_DEPTH; + rx_fifo_threshold = (uint8_t)((READ_BIT(husart->Instance->CR3, + USART_CR3_RXFTCFG) >> USART_CR3_RXFTCFG_Pos) & 0xFFU); + tx_fifo_threshold = (uint8_t)((READ_BIT(husart->Instance->CR3, + USART_CR3_TXFTCFG) >> USART_CR3_TXFTCFG_Pos) & 0xFFU); + husart->NbTxDataToProcess = ((uint16_t)tx_fifo_depth * numerator[tx_fifo_threshold]) / + (uint16_t)denominator[tx_fifo_threshold]; + husart->NbRxDataToProcess = ((uint16_t)rx_fifo_depth * numerator[rx_fifo_threshold]) / + (uint16_t)denominator[rx_fifo_threshold]; + } +} +/** + * @} + */ + +#endif /* HAL_USART_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_wwdg.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_wwdg.c index bed2c5ee7..2d321f1c4 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_wwdg.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_wwdg.c @@ -1,420 +1,419 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_wwdg.c - * @author MCD Application Team - * @brief WWDG HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Window Watchdog (WWDG) peripheral: - * + Initialization and Configuration functions - * + IO operation functions - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @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 (T[6;0] downcounter) - before reaching 0x3F value (i.e. a reset is generated when the counter - value rolls down 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. - (+) If required by application, an Early Wakeup Interrupt can be triggered - in order to be warned before WWDG expiration. The Early Wakeup Interrupt - (EWI) can be used if specific safety operations or data logging must - be performed before the actual reset is generated. When the downcounter - reaches 0x40, interrupt occurs. This mechanism requires WWDG interrupt - line to be enabled in NVIC. Once enabled, EWI interrupt 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 * (T[5;0] + 1) / WWDG clock (Hz) - where T[5;0] are the lowest 6 bits of Counter. - (+) 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 - (+) Typical values: - (++) Counter min (T[5;0] = 0x00) at 30 MHz (PCLK1) with zero prescaler: - max timeout before reset: approximately 136.53us - (++) Counter max (T[5;0] = 0x3F) at 30 MHz (PCLK1) with prescaler - dividing by 128: - max timeout before reset: approximately 69.91ms - - ##### How to use this driver ##### - ============================================================================== - - *** Common driver usage *** - =========================== - - [..] - (+) Enable WWDG APB1 clock using __HAL_RCC_WWDG_CLK_ENABLE(). - (+) Configure the WWDG prescaler, refresh window value, counter value and early - interrupt status using HAL_WWDG_Init() function. This will automatically - enable WWDG and start its downcounter. Time reference can be taken from - function exit. Care must be taken to provide a counter value - greater than 0x40 to prevent generation of immediate reset. - (+) If the Early Wakeup Interrupt (EWI) feature is enabled, an interrupt is - generated when the counter reaches 0x40. When HAL_WWDG_IRQHandler is - triggered by the interrupt service routine, flag will be automatically - cleared and HAL_WWDG_WakeupCallback user callback will be executed. User - can add his own code by customization of callback HAL_WWDG_WakeupCallback. - (+) 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. - - *** Callback registration *** - ============================= - - [..] - The compilation define USE_HAL_WWDG_REGISTER_CALLBACKS when set to 1 allows - the user to configure dynamically the driver callbacks. Use Functions - HAL_WWDG_RegisterCallback() to register a user callback. - - (+) Function HAL_WWDG_RegisterCallback() allows to register following - callbacks: - (++) EwiCallback : callback for Early WakeUp Interrupt. - (++) MspInitCallback : WWDG MspInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - (+) Use function HAL_WWDG_UnRegisterCallback() to reset a callback to - the default weak (surcharged) function. HAL_WWDG_UnRegisterCallback() - takes as parameters the HAL peripheral handle and the Callback ID. - This function allows to reset following callbacks: - (++) EwiCallback : callback for Early WakeUp Interrupt. - (++) MspInitCallback : WWDG MspInit. - - [..] - When calling HAL_WWDG_Init function, callbacks are reset to the - corresponding legacy weak (surcharged) functions: - HAL_WWDG_EarlyWakeupCallback() and HAL_WWDG_MspInit() only if they have - not been registered before. - - [..] - When compilation define USE_HAL_WWDG_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (surcharged) callbacks are used. - - *** WWDG HAL driver macros list *** - =================================== - [..] - Below the list of available macros in WWDG HAL driver. - (+) __HAL_WWDG_ENABLE: Enable the WWDG peripheral - (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status - (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags - (+) __HAL_WWDG_ENABLE_IT: Enable the WWDG early wakeup interrupt - - @endverbatim - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -#ifdef HAL_WWDG_MODULE_ENABLED -/** @defgroup WWDG WWDG - * @brief WWDG HAL module driver. - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup WWDG_Exported_Functions WWDG Exported Functions - * @{ - */ - -/** @defgroup WWDG_Exported_Functions_Group1 Initialization and Configuration functions - * @brief Initialization and Configuration functions. - * -@verbatim - ============================================================================== - ##### Initialization and Configuration functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Initialize and start the WWDG according to the specified parameters - in the WWDG_InitTypeDef of associated handle. - (+) Initialize the WWDG MSP. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the WWDG according to the specified. - * parameters in the WWDG_InitTypeDef of associated handle. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg) -{ - /* Check the WWDG handle allocation */ - if (hwwdg == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_WWDG_ALL_INSTANCE(hwwdg->Instance)); - assert_param(IS_WWDG_PRESCALER(hwwdg->Init.Prescaler)); - assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window)); - assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter)); - assert_param(IS_WWDG_EWI_MODE(hwwdg->Init.EWIMode)); - -#if (USE_HAL_WWDG_REGISTER_CALLBACKS == 1) - /* Reset Callback pointers */ - if (hwwdg->EwiCallback == NULL) - { - hwwdg->EwiCallback = HAL_WWDG_EarlyWakeupCallback; - } - - if (hwwdg->MspInitCallback == NULL) - { - hwwdg->MspInitCallback = HAL_WWDG_MspInit; - } - - /* Init the low level hardware */ - hwwdg->MspInitCallback(hwwdg); -#else - /* Init the low level hardware */ - HAL_WWDG_MspInit(hwwdg); -#endif /* USE_HAL_WWDG_REGISTER_CALLBACKS */ - - /* Set WWDG Counter */ - WRITE_REG(hwwdg->Instance->CR, (WWDG_CR_WDGA | hwwdg->Init.Counter)); - - /* Set WWDG Prescaler and Window */ - WRITE_REG(hwwdg->Instance->CFR, (hwwdg->Init.EWIMode | hwwdg->Init.Prescaler | hwwdg->Init.Window)); - - /* Return function status */ - return HAL_OK; -} - - -/** - * @brief Initialize the WWDG MSP. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. - * @note When rewriting this function in user file, mechanism may be added - * to avoid multiple initialize when HAL_WWDG_Init function is called - * again to change parameters. - * @retval None - */ -__weak void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hwwdg); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_WWDG_MspInit could be implemented in the user file - */ -} - - -#if (USE_HAL_WWDG_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User WWDG Callback - * To be used instead of the weak (surcharged) predefined callback - * @param hwwdg WWDG handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_WWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID - * @arg @ref HAL_WWDG_MSPINIT_CB_ID MspInit callback ID - * @param pCallback pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_WWDG_RegisterCallback(WWDG_HandleTypeDef *hwwdg, HAL_WWDG_CallbackIDTypeDef CallbackID, - pWWDG_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - status = HAL_ERROR; - } - else - { - switch (CallbackID) - { - case HAL_WWDG_EWI_CB_ID: - hwwdg->EwiCallback = pCallback; - break; - - case HAL_WWDG_MSPINIT_CB_ID: - hwwdg->MspInitCallback = pCallback; - break; - - default: - status = HAL_ERROR; - break; - } - } - - return status; -} - - -/** - * @brief Unregister a WWDG Callback - * WWDG Callback is redirected to the weak (surcharged) predefined callback - * @param hwwdg WWDG handle - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_WWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID - * @arg @ref HAL_WWDG_MSPINIT_CB_ID MspInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_WWDG_UnRegisterCallback(WWDG_HandleTypeDef *hwwdg, HAL_WWDG_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - switch (CallbackID) - { - case HAL_WWDG_EWI_CB_ID: - hwwdg->EwiCallback = HAL_WWDG_EarlyWakeupCallback; - break; - - case HAL_WWDG_MSPINIT_CB_ID: - hwwdg->MspInitCallback = HAL_WWDG_MspInit; - break; - - default: - status = HAL_ERROR; - break; - } - - return status; -} -#endif /* USE_HAL_WWDG_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup WWDG_Exported_Functions_Group2 IO operation functions - * @brief IO operation functions - * -@verbatim - ============================================================================== - ##### IO operation functions ##### - ============================================================================== - [..] - This section provides functions allowing to: - (+) Refresh the WWDG. - (+) Handle WWDG interrupt request and associated function callback. - -@endverbatim - * @{ - */ - -/** - * @brief Refresh the WWDG. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg) -{ - /* Write to WWDG CR the WWDG Counter value to refresh with */ - WRITE_REG(hwwdg->Instance->CR, (hwwdg->Init.Counter)); - - /* Return function status */ - return HAL_OK; -} - -/** - * @brief Handle 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 by calling HAL_WWDG_Init function with - * EWIMode set to WWDG_EWI_ENABLE. - * 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 pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. - * @retval None - */ -void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg) -{ - /* Check if Early Wakeup Interrupt is enable */ - if (__HAL_WWDG_GET_IT_SOURCE(hwwdg, WWDG_IT_EWI) != RESET) - { - /* Check if WWDG Early Wakeup Interrupt occurred */ - if (__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET) - { - /* Clear the WWDG Early Wakeup flag */ - __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF); - -#if (USE_HAL_WWDG_REGISTER_CALLBACKS == 1) - /* Early Wakeup registered callback */ - hwwdg->EwiCallback(hwwdg); -#else - /* Early Wakeup callback */ - HAL_WWDG_EarlyWakeupCallback(hwwdg); -#endif /* USE_HAL_WWDG_REGISTER_CALLBACKS */ - } - } -} - - -/** - * @brief WWDG Early Wakeup callback. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. - * @retval None - */ -__weak void HAL_WWDG_EarlyWakeupCallback(WWDG_HandleTypeDef *hwwdg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hwwdg); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_WWDG_EarlyWakeupCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_WWDG_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_wwdg.c + * @author MCD Application Team + * @brief WWDG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Window Watchdog (WWDG) peripheral: + * + Initialization and Configuration functions + * + IO operation functions + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @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 (T[6;0] downcounter) + before reaching 0x3F value (i.e. a reset is generated when the counter + value rolls down 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. + (+) If required by application, an Early Wakeup Interrupt can be triggered + in order to be warned before WWDG expiration. The Early Wakeup Interrupt + (EWI) can be used if specific safety operations or data logging must + be performed before the actual reset is generated. When the downcounter + reaches 0x40, interrupt occurs. This mechanism requires WWDG interrupt + line to be enabled in NVIC. Once enabled, EWI interrupt 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 * (T[5;0] + 1) / WWDG clock (Hz) + where T[5;0] are the lowest 6 bits of Counter. + (+) 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 + (+) Typical values: + (++) Counter min (T[5;0] = 0x00) at 30 MHz (PCLK1) with zero prescaler: + max timeout before reset: approximately 136.53us + (++) Counter max (T[5;0] = 0x3F) at 30 MHz (PCLK1) with prescaler + dividing by 128: + max timeout before reset: approximately 69.91ms + + ##### How to use this driver ##### + ============================================================================== + + *** Common driver usage *** + =========================== + + [..] + (+) Enable WWDG APB1 clock using __HAL_RCC_WWDG_CLK_ENABLE(). + (+) Configure the WWDG prescaler, refresh window value, counter value and early + interrupt status using HAL_WWDG_Init() function. This will automatically + enable WWDG and start its downcounter. Time reference can be taken from + function exit. Care must be taken to provide a counter value + greater than 0x40 to prevent generation of immediate reset. + (+) If the Early Wakeup Interrupt (EWI) feature is enabled, an interrupt is + generated when the counter reaches 0x40. When HAL_WWDG_IRQHandler is + triggered by the interrupt service routine, flag will be automatically + cleared and HAL_WWDG_WakeupCallback user callback will be executed. User + can add his own code by customization of callback HAL_WWDG_WakeupCallback. + (+) 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. + + *** Callback registration *** + ============================= + + [..] + The compilation define USE_HAL_WWDG_REGISTER_CALLBACKS when set to 1 allows + the user to configure dynamically the driver callbacks. Use Functions + HAL_WWDG_RegisterCallback() to register a user callback. + + (+) Function HAL_WWDG_RegisterCallback() allows to register following + callbacks: + (++) EwiCallback : callback for Early WakeUp Interrupt. + (++) MspInitCallback : WWDG MspInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + (+) Use function HAL_WWDG_UnRegisterCallback() to reset a callback to + the default weak (surcharged) function. HAL_WWDG_UnRegisterCallback() + takes as parameters the HAL peripheral handle and the Callback ID. + This function allows to reset following callbacks: + (++) EwiCallback : callback for Early WakeUp Interrupt. + (++) MspInitCallback : WWDG MspInit. + + [..] + When calling HAL_WWDG_Init function, callbacks are reset to the + corresponding legacy weak (surcharged) functions: + HAL_WWDG_EarlyWakeupCallback() and HAL_WWDG_MspInit() only if they have + not been registered before. + + [..] + When compilation define USE_HAL_WWDG_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (surcharged) callbacks are used. + + *** WWDG HAL driver macros list *** + =================================== + [..] + Below the list of available macros in WWDG HAL driver. + (+) __HAL_WWDG_ENABLE: Enable the WWDG peripheral + (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status + (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags + (+) __HAL_WWDG_ENABLE_IT: Enable the WWDG early wakeup interrupt + + @endverbatim + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +#ifdef HAL_WWDG_MODULE_ENABLED +/** @defgroup WWDG WWDG + * @brief WWDG HAL module driver. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup WWDG_Exported_Functions WWDG Exported Functions + * @{ + */ + +/** @defgroup WWDG_Exported_Functions_Group1 Initialization and Configuration functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and Configuration functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and start the WWDG according to the specified parameters + in the WWDG_InitTypeDef of associated handle. + (+) Initialize the WWDG MSP. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the WWDG according to the specified. + * parameters in the WWDG_InitTypeDef of associated handle. + * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg) +{ + /* Check the WWDG handle allocation */ + if (hwwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_WWDG_ALL_INSTANCE(hwwdg->Instance)); + assert_param(IS_WWDG_PRESCALER(hwwdg->Init.Prescaler)); + assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window)); + assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter)); + assert_param(IS_WWDG_EWI_MODE(hwwdg->Init.EWIMode)); + +#if (USE_HAL_WWDG_REGISTER_CALLBACKS == 1) + /* Reset Callback pointers */ + if (hwwdg->EwiCallback == NULL) + { + hwwdg->EwiCallback = HAL_WWDG_EarlyWakeupCallback; + } + + if (hwwdg->MspInitCallback == NULL) + { + hwwdg->MspInitCallback = HAL_WWDG_MspInit; + } + + /* Init the low level hardware */ + hwwdg->MspInitCallback(hwwdg); +#else + /* Init the low level hardware */ + HAL_WWDG_MspInit(hwwdg); +#endif /* USE_HAL_WWDG_REGISTER_CALLBACKS */ + + /* Set WWDG Counter */ + WRITE_REG(hwwdg->Instance->CR, (WWDG_CR_WDGA | hwwdg->Init.Counter)); + + /* Set WWDG Prescaler and Window */ + WRITE_REG(hwwdg->Instance->CFR, (hwwdg->Init.EWIMode | hwwdg->Init.Prescaler | hwwdg->Init.Window)); + + /* Return function status */ + return HAL_OK; +} + + +/** + * @brief Initialize the WWDG MSP. + * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @note When rewriting this function in user file, mechanism may be added + * to avoid multiple initialize when HAL_WWDG_Init function is called + * again to change parameters. + * @retval None + */ +__weak void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hwwdg); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_WWDG_MspInit could be implemented in the user file + */ +} + + +#if (USE_HAL_WWDG_REGISTER_CALLBACKS == 1) +/** + * @brief Register a User WWDG Callback + * To be used instead of the weak (surcharged) predefined callback + * @param hwwdg WWDG handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_WWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID + * @arg @ref HAL_WWDG_MSPINIT_CB_ID MspInit callback ID + * @param pCallback pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_WWDG_RegisterCallback(WWDG_HandleTypeDef *hwwdg, HAL_WWDG_CallbackIDTypeDef CallbackID, + pWWDG_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + status = HAL_ERROR; + } + else + { + switch (CallbackID) + { + case HAL_WWDG_EWI_CB_ID: + hwwdg->EwiCallback = pCallback; + break; + + case HAL_WWDG_MSPINIT_CB_ID: + hwwdg->MspInitCallback = pCallback; + break; + + default: + status = HAL_ERROR; + break; + } + } + + return status; +} + + +/** + * @brief Unregister a WWDG Callback + * WWDG Callback is redirected to the weak (surcharged) predefined callback + * @param hwwdg WWDG handle + * @param CallbackID ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_WWDG_EWI_CB_ID Early WakeUp Interrupt Callback ID + * @arg @ref HAL_WWDG_MSPINIT_CB_ID MspInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_WWDG_UnRegisterCallback(WWDG_HandleTypeDef *hwwdg, HAL_WWDG_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + switch (CallbackID) + { + case HAL_WWDG_EWI_CB_ID: + hwwdg->EwiCallback = HAL_WWDG_EarlyWakeupCallback; + break; + + case HAL_WWDG_MSPINIT_CB_ID: + hwwdg->MspInitCallback = HAL_WWDG_MspInit; + break; + + default: + status = HAL_ERROR; + break; + } + + return status; +} +#endif /* USE_HAL_WWDG_REGISTER_CALLBACKS */ + +/** + * @} + */ + +/** @defgroup WWDG_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Refresh the WWDG. + (+) Handle WWDG interrupt request and associated function callback. + +@endverbatim + * @{ + */ + +/** + * @brief Refresh the WWDG. + * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg) +{ + /* Write to WWDG CR the WWDG Counter value to refresh with */ + WRITE_REG(hwwdg->Instance->CR, (hwwdg->Init.Counter)); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Handle 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 by calling HAL_WWDG_Init function with + * EWIMode set to WWDG_EWI_ENABLE. + * 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 pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg) +{ + /* Check if Early Wakeup Interrupt is enable */ + if (__HAL_WWDG_GET_IT_SOURCE(hwwdg, WWDG_IT_EWI) != RESET) + { + /* Check if WWDG Early Wakeup Interrupt occurred */ + if (__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET) + { + /* Clear the WWDG Early Wakeup flag */ + __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF); + +#if (USE_HAL_WWDG_REGISTER_CALLBACKS == 1) + /* Early Wakeup registered callback */ + hwwdg->EwiCallback(hwwdg); +#else + /* Early Wakeup callback */ + HAL_WWDG_EarlyWakeupCallback(hwwdg); +#endif /* USE_HAL_WWDG_REGISTER_CALLBACKS */ + } + } +} + + +/** + * @brief WWDG Early Wakeup callback. + * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +__weak void HAL_WWDG_EarlyWakeupCallback(WWDG_HandleTypeDef *hwwdg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hwwdg); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_WWDG_EarlyWakeupCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_WWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_xspi.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_xspi.c index 4949f15d1..58dd9d496 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_xspi.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_hal_xspi.c @@ -1,3424 +1,3440 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_hal_xspi.c - * @author MCD Application Team - * @brief XSPI HAL module driver. - This file provides firmware functions to manage the following - functionalities of the OctoSPI/HSPI interface (XSPI). - + Initialization and de-initialization functions - + Hyperbus configuration - + Indirect functional mode management - + Memory-mapped functional mode management - + Auto-polling functional mode management - + Interrupts and flags management - + DMA channel configuration for indirect functional mode - + Errors management and abort functionality - + IO manager configuration - + HIGH-SPEED INTERFACE configuration - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - =============================================================================== - ##### How to use this driver ##### - =============================================================================== - [..] - *** Initialization *** - ====================== - [..] - As prerequisite, fill in the HAL_XSPI_MspInit() : - (+) Enable OctoSPI/HSPI clocks interface with __HAL_RCC_XSPI_CLK_ENABLE(). - (+) Reset OctoSPI/HSPI Peripheral with __HAL_RCC_XSPI_FORCE_RESET() and __HAL_RCC_XSPI_RELEASE_RESET(). - (+) Enable the clocks for the OctoSPI/HSPI GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). - (+) Configure these OctoSPI/HSPI pins in alternate mode using HAL_GPIO_Init(). - (+) If interrupt or DMA mode is used, enable and configure OctoSPI/HSPI global - interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). - (+) If DMA mode is used, enable the clocks for the OctoSPI/HSPI DMA channel - with __HAL_RCC_DMAx_CLK_ENABLE(), configure DMA with HAL_DMA_Init(), - link it with OctoSPI/HSPI handle using __HAL_LINKDMA(), enable and configure - DMA channel global interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). - [..] - Configure the fifo threshold, the memory mode, the memory type, the - device size, the CS high time, the free running clock, the clock mode, - the wrap size, the clock prescaler, the sample shifting, the hold delay - and the CS boundary using the HAL_XSPI_Init() function. - [..] - When using Hyperbus, configure the RW recovery time, the access time, - the write latency and the latency mode using the HAL_XSPI_HyperbusCfg() - function. - - *** Indirect functional mode *** - ================================ - [..] - In regular mode, configure the command sequence using the HAL_XSPI_Command() - or HAL_XSPI_Command_IT() functions : - (+) Instruction phase : the mode used and if present the size, the instruction - opcode and the DTR mode. - (+) Address phase : the mode used and if present the size, the address - value and the DTR mode. - (+) Alternate-bytes phase : the mode used and if present the size, the - alternate bytes values and the DTR mode. - (+) Dummy-cycles phase : the number of dummy cycles (mode used is same as data phase). - (+) Data phase : the mode used and if present the number of bytes and the DTR mode. - (+) Data strobe (DQS) mode : the activation (or not) of this mode - (+) IO selection : to access external memory. - (+) Operation type : always common configuration. - [..] - In Hyperbus mode, configure the command sequence using the HAL_XSPI_HyperbusCmd() - function : - (+) Address space : indicate if the access will be done in register or memory - (+) Address size - (+) Number of data - (+) Data strobe (DQS) mode : the activation (or not) of this mode - [..] - If no data is required for the command (only for regular mode, not for - Hyperbus mode), it is sent directly to the memory : - (+) In polling mode, the output of the function is done when the transfer is complete. - (+) In interrupt mode, HAL_XSPI_CmdCpltCallback() will be called when the transfer is complete. - [..] - For the indirect write mode, use HAL_XSPI_Transmit(), HAL_XSPI_Transmit_DMA() or - HAL_XSPI_Transmit_IT() after the command configuration : - (+) In polling mode, the output of the function is done when the transfer is complete. - (+) In interrupt mode, HAL_XSPI_FifoThresholdCallback() will be called when the fifo threshold - is reached and HAL_XSPI_TxCpltCallback() will be called when the transfer is complete. - (+) In DMA mode, HAL_XSPI_TxHalfCpltCallback() will be called at the half transfer and - HAL_XSPI_TxCpltCallback() will be called when the transfer is complete. - [..] - For the indirect read mode, use HAL_XSPI_Receive(), HAL_XSPI_Receive_DMA() or - HAL_XSPI_Receive_IT() after the command configuration : - (+) In polling mode, the output of the function is done when the transfer is complete. - (+) In interrupt mode, HAL_XSPI_FifoThresholdCallback() will be called when the fifo threshold - is reached and HAL_XSPI_RxCpltCallback() will be called when the transfer is complete. - (+) In DMA mode, HAL_XSPI_RxHalfCpltCallback() will be called at the half transfer and - HAL_XSPI_RxCpltCallback() will be called when the transfer is complete. - - *** Auto-polling functional mode *** - ==================================== - [..] - Configure the command sequence by the same way than the indirect mode - [..] - Configure the auto-polling functional mode using the HAL_XSPI_AutoPolling() - or HAL_XSPI_AutoPolling_IT() functions : - (+) The size of the status bytes, the match value, the mask used, the match mode (OR/AND), - the polling interval and the automatic stop activation. - [..] - After the configuration : - (+) In polling mode, the output of the function is done when the status match is reached. The - automatic stop is activated to avoid an infinite loop. - (+) In interrupt mode, HAL_XSPI_StatusMatchCallback() will be called each time the status match is reached. - - *** Memory-mapped functional mode *** - ===================================== - [..] - Configure the command sequence by the same way than the indirect mode except - for the operation type in regular mode : - (+) Operation type equals to read configuration : the command configuration - applies to read access in memory-mapped mode - (+) Operation type equals to write configuration : the command configuration - applies to write access in memory-mapped mode - (+) Both read and write configuration should be performed before activating - memory-mapped mode - [..] - Configure the memory-mapped functional mode using the HAL_XSPI_MemoryMapped() - functions : - (+) The timeout activation and the timeout period. - [..] - After the configuration, the OctoSPI/HSPI will be used as soon as an access on the AHB is done on - the address range. HAL_XSPI_TimeOutCallback() will be called when the timeout expires. - - *** Errors management and abort functionality *** - ================================================= - [..] - HAL_XSPI_GetError() function gives the error raised during the last operation. - [..] - HAL_XSPI_Abort() and HAL_XSPI_AbortIT() functions aborts any on-going operation and - flushes the fifo : - (+) In polling mode, the output of the function is done when the transfer - complete bit is set and the busy bit cleared. - (+) In interrupt mode, HAL_XSPI_AbortCpltCallback() will be called when - the transfer complete bit is set. - - *** Control functions *** - ========================= - [..] - HAL_XSPI_GetState() function gives the current state of the HAL XSPI driver. - [..] - HAL_XSPI_SetTimeout() function configures the timeout value used in the driver. - [..] - HAL_XSPI_SetFifoThreshold() function configures the threshold on the Fifo of the OctoSPI/HSPI Peripheral. - [..] - HAL_XSPI_SetMemoryType() function configures the type of the external memory. - [..] - HAL_XSPI_SetDeviceSize() function configures the size of the external memory. - [..] - HAL_XSPI_SetClockPrescaler() function configures the clock prescaler of the OctoSPI/HSPI Peripheral. - [..] - HAL_XSPI_GetFifoThreshold() function gives the current of the Fifo's threshold - - *** IO manager configuration functions *** - ========================================== - [..] - HAL_XSPIM_Config() function configures the IO manager for the XSPI instance. - - *** High-speed interface and calibration functions *** - ========================================== - [..] - The purpose of High-speed interface is primary to shift data or data strobe by one quarter of octal - bus clock period, with a correct timing accuracy. DLL must be calibrated versus this clock period. - The calibration process is automatically enabled when one of the three conditions below is met: - (+) The XSPI exits Reset state. - (+) The Prescaler is set. - (+) The configuration of communication is set. - [..] - HAL_XSPI_GetDelayValue() function Get the delay values of the high-speed interface DLLs.. - [..] - HAL_XSPI_SetDelayValue() function Set the delay values of the high-speed interface DLLs.. - - *** Callback registration *** - ============================================= - [..] - The compilation define USE_HAL_XSPI_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - - [..] - Use function HAL_XSPI_RegisterCallback() to register a user callback, - it allows to register following callbacks: - (+) ErrorCallback : callback when error occurs. - (+) AbortCpltCallback : callback when abort is completed. - (+) FifoThresholdCallback : callback when the fifo threshold is reached. - (+) CmdCpltCallback : callback when a command without data is completed. - (+) RxCpltCallback : callback when a reception transfer is completed. - (+) TxCpltCallback : callback when a transmission transfer is completed. - (+) RxHalfCpltCallback : callback when half of the reception transfer is completed. - (+) TxHalfCpltCallback : callback when half of the transmission transfer is completed. - (+) StatusMatchCallback : callback when a status match occurs. - (+) TimeOutCallback : callback when the timeout perioed expires. - (+) MspInitCallback : XSPI MspInit. - (+) MspDeInitCallback : XSPI MspDeInit. - [..] - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - - [..] - Use function HAL_XSPI_UnRegisterCallback() to reset a callback to the default - weak (overridden) function. It allows to reset following callbacks: - (+) ErrorCallback : callback when error occurs. - (+) AbortCpltCallback : callback when abort is completed. - (+) FifoThresholdCallback : callback when the fifo threshold is reached. - (+) CmdCpltCallback : callback when a command without data is completed. - (+) RxCpltCallback : callback when a reception transfer is completed. - (+) TxCpltCallback : callback when a transmission transfer is completed. - (+) RxHalfCpltCallback : callback when half of the reception transfer is completed. - (+) TxHalfCpltCallback : callback when half of the transmission transfer is completed. - (+) StatusMatchCallback : callback when a status match occurs. - (+) TimeOutCallback : callback when the timeout perioed expires. - (+) MspInitCallback : XSPI MspInit. - (+) MspDeInitCallback : XSPI MspDeInit. - [..] - This function) takes as parameters the HAL peripheral handle and the Callback ID. - - [..] - By default, after the HAL_XSPI_Init() and if the state is HAL_XSPI_STATE_RESET - all callbacks are reset to the corresponding legacy weak (overridden) functions. - Exception done for MspInit and MspDeInit callbacks that are respectively - reset to the legacy weak (overridden) functions in the HAL_XSPI_Init() - and HAL_XSPI_DeInit() only when these callbacks are null (not registered beforehand). - If not, MspInit or MspDeInit are not null, the HAL_XSPI_Init() and HAL_XSPI_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) - - [..] - Callbacks can be registered/unregistered in READY state only. - Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered - in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used - during the Init/DeInit. - In that case first register the MspInit/MspDeInit user callbacks - using HAL_XSPI_RegisterCallback() before calling HAL_XSPI_DeInit() - or HAL_XSPI_Init() function. - - [..] - When The compilation define USE_HAL_XSPI_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registering feature is not available - and weak (overridden) callbacks are used. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -#if defined(XSPI) || defined(XSPI1) || defined(XSPI2) - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup XSPI XSPI - * @brief XSPI HAL module driver - * @{ - */ - -#ifdef HAL_XSPI_MODULE_ENABLED - -/** - @cond 0 - */ -/* Private typedef -----------------------------------------------------------*/ - -/* Private define ------------------------------------------------------------*/ -#define XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE ((uint32_t)0x00000000) /*!< Indirect write mode */ -#define XSPI_FUNCTIONAL_MODE_INDIRECT_READ ((uint32_t)XSPI_CR_FMODE_0) /*!< Indirect read mode */ -#define XSPI_FUNCTIONAL_MODE_AUTO_POLLING ((uint32_t)XSPI_CR_FMODE_1) /*!< Automatic polling mode */ -#define XSPI_FUNCTIONAL_MODE_MEMORY_MAPPED ((uint32_t)XSPI_CR_FMODE) /*!< Memory-mapped mode */ - -#define XSPI_CFG_STATE_MASK 0x00000004U -#define XSPI_BUSY_STATE_MASK 0x00000008U - -#define XSPI_NB_INSTANCE 2U -#define XSPI_IOM_NB_PORTS 2U -#define XSPI_IOM_PORT_MASK 0x1U - -/* Private macro -------------------------------------------------------------*/ -#define IS_XSPI_FUNCTIONAL_MODE(MODE) (((MODE) == XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE) || \ - ((MODE) == XSPI_FUNCTIONAL_MODE_INDIRECT_READ) || \ - ((MODE) == XSPI_FUNCTIONAL_MODE_AUTO_POLLING) || \ - ((MODE) == XSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)) - -/* Private variables ---------------------------------------------------------*/ - -/* Private function prototypes -----------------------------------------------*/ -static void XSPI_DMACplt(DMA_HandleTypeDef *hdma); -static void XSPI_DMAHalfCplt(DMA_HandleTypeDef *hdma); -static void XSPI_DMAError(DMA_HandleTypeDef *hdma); -static void XSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef XSPI_WaitFlagStateUntilTimeout(XSPI_HandleTypeDef *hxspi, uint32_t Flag, FlagStatus State, - uint32_t Tickstart, uint32_t Timeout); -static HAL_StatusTypeDef XSPI_ConfigCmd(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *const pCmd); -static void XSPIM_GetConfig(uint8_t instance_nb, XSPIM_CfgTypeDef *const pCfg); -/** - @endcond - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup XSPI_Exported_Functions XSPI Exported Functions - * @{ - */ - -/** @defgroup XSPI_Exported_Functions_Group1 Initialization/de-initialization functions - * @brief Initialization and Configuration functions - * -@verbatim -=============================================================================== - ##### Initialization and Configuration functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to : - (+) Initialize the XSPI. - (+) De-initialize the XSPI. - -@endverbatim - * @{ - */ - -/** - * @brief Initialize the XSPI mode according to the specified parameters - * in the XSPI_InitTypeDef and initialize the associated handle. - * @param hxspi : XSPI handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Init(XSPI_HandleTypeDef *hxspi) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t tickstart = HAL_GetTick(); - - /* Check the XSPI handle allocation */ - if (hxspi == NULL) - { - status = HAL_ERROR; - /* No error code can be set set as the handler is null */ - } - else - { - /* Check the parameters of the initialization structure */ - assert_param(IS_XSPI_MEMORY_MODE(hxspi->Init.MemoryMode)); - assert_param(IS_XSPI_MEMORY_TYPE(hxspi->Init.MemoryType)); - assert_param(IS_XSPI_MEMORY_SIZE(hxspi->Init.MemorySize)); - assert_param(IS_XSPI_CS_HIGH_TIME_CYCLE(hxspi->Init.ChipSelectHighTimeCycle)); - assert_param(IS_XSPI_FREE_RUN_CLK(hxspi->Init.FreeRunningClock)); - assert_param(IS_XSPI_CLOCK_MODE(hxspi->Init.ClockMode)); - assert_param(IS_XSPI_WRAP_SIZE(hxspi->Init.WrapSize)); - assert_param(IS_XSPI_CLK_PRESCALER(hxspi->Init.ClockPrescaler)); - assert_param(IS_XSPI_SAMPLE_SHIFTING(hxspi->Init.SampleShifting)); - assert_param(IS_XSPI_DHQC(hxspi->Init.DelayHoldQuarterCycle)); - assert_param(IS_XSPI_CS_BOUND(hxspi->Init.ChipSelectBoundary)); - assert_param(IS_XSPI_FIFO_THRESHOLD_BYTE(hxspi->Init.FifoThresholdByte)); - assert_param(IS_XSPI_MAXTRAN(hxspi->Init.MaxTran)); - assert_param(IS_XSPI_CSSEL(hxspi->Init.MemorySelect)); - /* Initialize error code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_NONE; - - /* Check if the state is the reset state */ - if (hxspi->State == HAL_XSPI_STATE_RESET) - { -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - /* Reset Callback pointers in HAL_XSPI_STATE_RESET only */ - hxspi->ErrorCallback = HAL_XSPI_ErrorCallback; - hxspi->AbortCpltCallback = HAL_XSPI_AbortCpltCallback; - hxspi->FifoThresholdCallback = HAL_XSPI_FifoThresholdCallback; - hxspi->CmdCpltCallback = HAL_XSPI_CmdCpltCallback; - hxspi->RxCpltCallback = HAL_XSPI_RxCpltCallback; - hxspi->TxCpltCallback = HAL_XSPI_TxCpltCallback; - hxspi->RxHalfCpltCallback = HAL_XSPI_RxHalfCpltCallback; - hxspi->TxHalfCpltCallback = HAL_XSPI_TxHalfCpltCallback; - hxspi->StatusMatchCallback = HAL_XSPI_StatusMatchCallback; - hxspi->TimeOutCallback = HAL_XSPI_TimeOutCallback; - - if (hxspi->MspInitCallback == NULL) - { - hxspi->MspInitCallback = HAL_XSPI_MspInit; - } - - /* Init the low level hardware */ - hxspi->MspInitCallback(hxspi); -#else - /* Initialization of the low level hardware */ - HAL_XSPI_MspInit(hxspi); -#endif /* defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - - /* Configure the default timeout for the XSPI memory access */ - (void)HAL_XSPI_SetTimeout(hxspi, HAL_XSPI_TIMEOUT_DEFAULT_VALUE); - - /* Configure memory type, device size, chip select high time, free running clock, clock mode */ - MODIFY_REG(hxspi->Instance->DCR1, - (XSPI_DCR1_MTYP | XSPI_DCR1_DEVSIZE | XSPI_DCR1_CSHT | XSPI_DCR1_FRCK | XSPI_DCR1_CKMODE), - (hxspi->Init.MemoryType | ((hxspi->Init.MemorySize) << XSPI_DCR1_DEVSIZE_Pos) | - ((hxspi->Init.ChipSelectHighTimeCycle - 1U) << XSPI_DCR1_CSHT_Pos) | hxspi->Init.ClockMode)); - - /* Configure wrap size */ - MODIFY_REG(hxspi->Instance->DCR2, XSPI_DCR2_WRAPSIZE, hxspi->Init.WrapSize); - - /* Configure chip select boundary */ - MODIFY_REG(hxspi->Instance->DCR3, XSPI_DCR3_CSBOUND, (hxspi->Init.ChipSelectBoundary << XSPI_DCR3_CSBOUND_Pos)); - - /* Configure maximum transfer */ - MODIFY_REG(hxspi->Instance->DCR3, XSPI_DCR3_MAXTRAN, \ - (hxspi->Init.MaxTran << XSPI_DCR3_MAXTRAN_Pos)); - - /* Configure refresh */ - hxspi->Instance->DCR4 = hxspi->Init.Refresh; - - /* Configure FIFO threshold */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FTHRES, ((hxspi->Init.FifoThresholdByte - 1U) << XSPI_CR_FTHRES_Pos)); - - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); - - if (status == HAL_OK) - { - /* Configure clock prescaler */ - MODIFY_REG(hxspi->Instance->DCR2, XSPI_DCR2_PRESCALER, - ((hxspi->Init.ClockPrescaler) << XSPI_DCR2_PRESCALER_Pos)); - - if (IS_XSPI_ALL_INSTANCE(hxspi->Instance)) - { - /* The configuration of clock prescaler trigger automatically a calibration process. - So it is necessary to wait the calibration is complete */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); - if (status != HAL_OK) - { - return status; - } - } - /* Configure Dual Memory mode and CS Selection */ - MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_DMM | XSPI_CR_CSSEL), - (hxspi->Init.MemoryMode | hxspi->Init.MemorySelect)); - - /* Configure sample shifting and delay hold quarter cycle */ - MODIFY_REG(hxspi->Instance->TCR, (XSPI_TCR_SSHIFT | XSPI_TCR_DHQC), - (hxspi->Init.SampleShifting | hxspi->Init.DelayHoldQuarterCycle)); - - /* Enable XSPI */ - HAL_XSPI_ENABLE(hxspi); - - /* Enable free running clock if needed : must be done after XSPI enable */ - if (hxspi->Init.FreeRunningClock == HAL_XSPI_FREERUNCLK_ENABLE) - { - SET_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK); - } - - /* Initialize the XSPI state */ - if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) - { - hxspi->State = HAL_XSPI_STATE_HYPERBUS_INIT; - } - else - { - hxspi->State = HAL_XSPI_STATE_READY; - } - } - } - } - return status; -} - -/** - * @brief Initialize the XSPI MSP. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_MspInit(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_XSPI_MspInit can be implemented in the user file - */ -} - -/** - * @brief De-Initialize the XSPI peripheral. - * @param hxspi : XSPI handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_DeInit(XSPI_HandleTypeDef *hxspi) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the XSPI handle allocation */ - if (hxspi == NULL) - { - status = HAL_ERROR; - /* No error code can be set as the handler is null */ - } - else - { - /* Disable XSPI */ - HAL_XSPI_DISABLE(hxspi); - - /* Disable free running clock if needed : must be done after XSPI disable */ - CLEAR_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK); - -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - if (hxspi->MspDeInitCallback == NULL) - { - hxspi->MspDeInitCallback = HAL_XSPI_MspDeInit; - } - - /* De-initialize the low level hardware */ - hxspi->MspDeInitCallback(hxspi); -#else - /* De-initialize the low-level hardware */ - HAL_XSPI_MspDeInit(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - - /* Reset the driver state */ - hxspi->State = HAL_XSPI_STATE_RESET; - } - - return status; -} - -/** - * @brief DeInitialize the XSPI MSP. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_MspDeInit(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_XSPI_MspDeInit can be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup XSPI_Exported_Functions_Group2 Input and Output operation functions - * @brief XSPI Transmit/Receive functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to : - (+) Handle the interrupts. - (+) Handle the command sequence (regular and Hyperbus). - (+) Handle the Hyperbus configuration. - (+) Transmit data in blocking, interrupt or DMA mode. - (+) Receive data in blocking, interrupt or DMA mode. - (+) Manage the auto-polling functional mode. - (+) Manage the memory-mapped functional mode. - -@endverbatim - * @{ - */ - -/** - * @brief Handle XSPI interrupt request. - * @param hxspi : XSPI handle - * @retval None - */ -void HAL_XSPI_IRQHandler(XSPI_HandleTypeDef *hxspi) -{ - __IO uint32_t *data_reg = &hxspi->Instance->DR; - uint32_t flag = hxspi->Instance->SR; - uint32_t itsource = hxspi->Instance->CR; - uint32_t currentstate = hxspi->State; - - /* XSPI fifo threshold interrupt occurred -------------------------------*/ - if (((flag & HAL_XSPI_FLAG_FT) != 0U) && ((itsource & HAL_XSPI_IT_FT) != 0U)) - { - if (currentstate == HAL_XSPI_STATE_BUSY_TX) - { - /* Write a data in the fifo */ - *((__IO uint8_t *)data_reg) = *hxspi->pBuffPtr; - hxspi->pBuffPtr++; - hxspi->XferCount--; - } - else if (currentstate == HAL_XSPI_STATE_BUSY_RX) - { - /* Read a data from the fifo */ - *hxspi->pBuffPtr = *((__IO uint8_t *)data_reg); - hxspi->pBuffPtr++; - hxspi->XferCount--; - } - else - { - /* Nothing to do */ - } - - if (hxspi->XferCount == 0U) - { - /* All data have been received or transmitted for the transfer */ - /* Disable fifo threshold interrupt */ - HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_FT); - } - - /* Fifo threshold callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->FifoThresholdCallback(hxspi); -#else - HAL_XSPI_FifoThresholdCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - /* XSPI transfer complete interrupt occurred ----------------------------*/ - else if (((flag & HAL_XSPI_FLAG_TC) != 0U) && ((itsource & HAL_XSPI_IT_TC) != 0U)) - { - if (currentstate == HAL_XSPI_STATE_BUSY_RX) - { - if ((hxspi->XferCount > 0U) && ((flag & XSPI_SR_FLEVEL) != 0U)) - { - /* Read the last data received in the fifo */ - *hxspi->pBuffPtr = *((__IO uint8_t *)data_reg); - hxspi->pBuffPtr++; - hxspi->XferCount--; - } - else if (hxspi->XferCount == 0U) - { - /* Clear flag */ - hxspi->Instance->FCR = HAL_XSPI_FLAG_TC; - - /* Disable the interrupts */ - HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); - - hxspi->State = HAL_XSPI_STATE_READY; - - /* RX complete callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->RxCpltCallback(hxspi); -#else - HAL_XSPI_RxCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - else - { - /* Nothing to do */ - } - } - else - { - /* Clear flag */ - hxspi->Instance->FCR = HAL_XSPI_FLAG_TC; - - /* Disable the interrupts */ - HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); - - hxspi->State = HAL_XSPI_STATE_READY; - - if (currentstate == HAL_XSPI_STATE_BUSY_TX) - { - /* TX complete callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->TxCpltCallback(hxspi); -#else - HAL_XSPI_TxCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - else if (currentstate == HAL_XSPI_STATE_BUSY_CMD) - { - /* Command complete callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->CmdCpltCallback(hxspi); -#else - HAL_XSPI_CmdCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - else if (currentstate == HAL_XSPI_STATE_ABORT) - { - if (hxspi->ErrorCode == HAL_XSPI_ERROR_NONE) - { - /* Abort called by the user */ - /* Abort complete callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->AbortCpltCallback(hxspi); -#else - HAL_XSPI_AbortCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - else - { - /* Abort due to an error (eg : DMA error) */ - /* Error callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->ErrorCallback(hxspi); -#else - HAL_XSPI_ErrorCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - } - else - { - /* Nothing to do */ - } - } - } - /* XSPI status match interrupt occurred ---------------------------------*/ - else if (((flag & HAL_XSPI_FLAG_SM) != 0U) && ((itsource & HAL_XSPI_IT_SM) != 0U)) - { - /* Clear flag */ - hxspi->Instance->FCR = HAL_XSPI_FLAG_SM; - - /* Check if automatic poll mode stop is activated */ - if ((hxspi->Instance->CR & XSPI_CR_APMS) != 0U) - { - /* Disable the interrupts */ - HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_SM | HAL_XSPI_IT_TE); - - hxspi->State = HAL_XSPI_STATE_READY; - } - - /* Status match callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->StatusMatchCallback(hxspi); -#else - HAL_XSPI_StatusMatchCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - /* XSPI transfer error interrupt occurred -------------------------------*/ - else if (((flag & HAL_XSPI_FLAG_TE) != 0U) && ((itsource & HAL_XSPI_IT_TE) != 0U)) - { - /* Clear flag */ - hxspi->Instance->FCR = HAL_XSPI_FLAG_TE; - - /* Disable all interrupts */ - HAL_XSPI_DISABLE_IT(hxspi, (HAL_XSPI_IT_TO | HAL_XSPI_IT_SM | HAL_XSPI_IT_FT | HAL_XSPI_IT_TC | HAL_XSPI_IT_TE)); - - /* Set error code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_TRANSFER; - - /* Check if the DMA is enabled */ - if ((hxspi->Instance->CR & XSPI_CR_DMAEN) != 0U) - { - /* Disable the DMA transfer on the XSPI side */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - - /* Disable the DMA transmit on the DMA side */ - hxspi->hdmatx->XferAbortCallback = XSPI_DMAAbortCplt; - if (HAL_DMA_Abort_IT(hxspi->hdmatx) != HAL_OK) - { - hxspi->State = HAL_XSPI_STATE_READY; - - /* Error callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->ErrorCallback(hxspi); -#else - HAL_XSPI_ErrorCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - - /* Disable the DMA receive on the DMA side */ - hxspi->hdmarx->XferAbortCallback = XSPI_DMAAbortCplt; - if (HAL_DMA_Abort_IT(hxspi->hdmarx) != HAL_OK) - { - hxspi->State = HAL_XSPI_STATE_READY; - - /* Error callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->ErrorCallback(hxspi); -#else - HAL_XSPI_ErrorCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - } - else - { - hxspi->State = HAL_XSPI_STATE_READY; - - /* Error callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->ErrorCallback(hxspi); -#else - HAL_XSPI_ErrorCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - } - /* XSPI timeout interrupt occurred --------------------------------------*/ - else if (((flag & HAL_XSPI_FLAG_TO) != 0U) && ((itsource & HAL_XSPI_IT_TO) != 0U)) - { - /* Clear flag */ - hxspi->Instance->FCR = HAL_XSPI_FLAG_TO; - - /* Timeout callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->TimeOutCallback(hxspi); -#else - HAL_XSPI_TimeOutCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - else - { - /* Nothing to do */ - } -} - -/** - * @brief Set the command configuration. - * @param hxspi : XSPI handle - * @param pCmd : structure that contains the command configuration information - * @param Timeout : Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Command(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *const pCmd, uint32_t Timeout) -{ - HAL_StatusTypeDef status; - uint32_t state; - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters of the command structure */ - assert_param(IS_XSPI_OPERATION_TYPE(pCmd->OperationType)); - if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM) - { - assert_param(IS_XSPI_IO_SELECT(pCmd->IOSelect)); - } - - assert_param(IS_XSPI_INSTRUCTION_MODE(pCmd->InstructionMode)); - if (pCmd->InstructionMode != HAL_XSPI_INSTRUCTION_NONE) - { - assert_param(IS_XSPI_INSTRUCTION_WIDTH(pCmd->InstructionWidth)); - assert_param(IS_XSPI_INSTRUCTION_DTR_MODE(pCmd->InstructionDTRMode)); - } - - assert_param(IS_XSPI_ADDRESS_MODE(pCmd->AddressMode)); - if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) - { - assert_param(IS_XSPI_ADDRESS_WIDTH(pCmd->AddressWidth)); - assert_param(IS_XSPI_ADDRESS_DTR_MODE(pCmd->AddressDTRMode)); - } - - assert_param(IS_XSPI_ALT_BYTES_MODE(pCmd->AlternateBytesMode)); - if (pCmd->AlternateBytesMode != HAL_XSPI_ALT_BYTES_NONE) - { - assert_param(IS_XSPI_ALT_BYTES_WIDTH(pCmd->AlternateBytesWidth)); - assert_param(IS_XSPI_ALT_BYTES_DTR_MODE(pCmd->AlternateBytesDTRMode)); - } - - assert_param(IS_XSPI_DATA_MODE(hxspi->Init.MemoryType, pCmd->DataMode)); - - if (pCmd->DataMode != HAL_XSPI_DATA_NONE) - { - if (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) - { - assert_param(IS_XSPI_DATA_LENGTH(pCmd->DataLength)); - } - assert_param(IS_XSPI_DATA_DTR_MODE(pCmd->DataDTRMode)); - assert_param(IS_XSPI_DUMMY_CYCLES(pCmd->DummyCycles)); - } - - assert_param(IS_XSPI_DQS_MODE(pCmd->DQSMode)); - - /* Check the state of the driver */ - state = hxspi->State; - if (((state == HAL_XSPI_STATE_READY) && (hxspi->Init.MemoryType != HAL_XSPI_MEMTYPE_HYPERBUS)) || - ((state == HAL_XSPI_STATE_READ_CMD_CFG) && ((pCmd->OperationType == HAL_XSPI_OPTYPE_WRITE_CFG) || - (pCmd->OperationType == HAL_XSPI_OPTYPE_WRAP_CFG))) || - ((state == HAL_XSPI_STATE_WRITE_CMD_CFG) && - ((pCmd->OperationType == HAL_XSPI_OPTYPE_READ_CFG) || - (pCmd->OperationType == HAL_XSPI_OPTYPE_WRAP_CFG)))) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Initialize error code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_NONE; - - /* Configure the registers */ - status = XSPI_ConfigCmd(hxspi, pCmd); - - if (status == HAL_OK) - { - if (pCmd->DataMode == HAL_XSPI_DATA_NONE) - { - /* When there is no data phase, the transfer start as soon as the configuration is done - so wait until TC flag is set to go back in idle state */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, Timeout); - - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); - } - else - { - /* Update the state */ - if (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) - { - hxspi->State = HAL_XSPI_STATE_CMD_CFG; - } - else if (pCmd->OperationType == HAL_XSPI_OPTYPE_READ_CFG) - { - if (hxspi->State == HAL_XSPI_STATE_WRITE_CMD_CFG) - { - hxspi->State = HAL_XSPI_STATE_CMD_CFG; - } - else - { - hxspi->State = HAL_XSPI_STATE_READ_CMD_CFG; - } - } - else if (pCmd->OperationType == HAL_XSPI_OPTYPE_WRITE_CFG) - { - if (hxspi->State == HAL_XSPI_STATE_READ_CMD_CFG) - { - hxspi->State = HAL_XSPI_STATE_CMD_CFG; - } - else - { - hxspi->State = HAL_XSPI_STATE_WRITE_CMD_CFG; - } - } - else - { - /* Wrap configuration, no state change */ - } - } - } - } - else - { - status = HAL_BUSY; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Set the command configuration in interrupt mode. - * @param hxspi : XSPI handle - * @param pCmd : structure that contains the command configuration information - * @note This function is used only in Indirect Read or Write Modes - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Command_IT(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *const pCmd) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters of the command structure */ - assert_param(IS_XSPI_OPERATION_TYPE(pCmd->OperationType)); - - if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM) - { - assert_param(IS_XSPI_IO_SELECT(pCmd->IOSelect)); - } - - assert_param(IS_XSPI_INSTRUCTION_MODE(pCmd->InstructionMode)); - if (pCmd->InstructionMode != HAL_XSPI_INSTRUCTION_NONE) - { - assert_param(IS_XSPI_INSTRUCTION_WIDTH(pCmd->InstructionWidth)); - assert_param(IS_XSPI_INSTRUCTION_DTR_MODE(pCmd->InstructionDTRMode)); - } - - assert_param(IS_XSPI_ADDRESS_MODE(pCmd->AddressMode)); - if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) - { - assert_param(IS_XSPI_ADDRESS_WIDTH(pCmd->AddressWidth)); - assert_param(IS_XSPI_ADDRESS_DTR_MODE(pCmd->AddressDTRMode)); - } - - assert_param(IS_XSPI_ALT_BYTES_MODE(pCmd->AlternateBytesMode)); - if (pCmd->AlternateBytesMode != HAL_XSPI_ALT_BYTES_NONE) - { - assert_param(IS_XSPI_ALT_BYTES_WIDTH(pCmd->AlternateBytesWidth)); - assert_param(IS_XSPI_ALT_BYTES_DTR_MODE(pCmd->AlternateBytesDTRMode)); - } - - assert_param(IS_XSPI_DATA_MODE(hxspi->Init.MemoryType, pCmd->DataMode)); - - if (pCmd->DataMode != HAL_XSPI_DATA_NONE) - { - assert_param(IS_XSPI_DATA_LENGTH(pCmd->DataLength)); - assert_param(IS_XSPI_DATA_DTR_MODE(pCmd->DataDTRMode)); - assert_param(IS_XSPI_DUMMY_CYCLES(pCmd->DummyCycles)); - } - - assert_param(IS_XSPI_DQS_MODE(pCmd->DQSMode)); - - /* Check the state of the driver */ - if ((hxspi->State == HAL_XSPI_STATE_READY) && (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) && - (pCmd->DataMode == HAL_XSPI_DATA_NONE) && (hxspi->Init.MemoryType != HAL_XSPI_MEMTYPE_HYPERBUS)) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); - - if (status == HAL_OK) - { - /* Initialize error code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_NONE; - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); - - /* Configure the registers */ - status = XSPI_ConfigCmd(hxspi, pCmd); - - if (status == HAL_OK) - { - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_BUSY_CMD; - - /* Enable the transfer complete and transfer error interrupts */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_TE); - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Configure the Hyperbus parameters. - * @param hxspi : XSPI handle - * @param pCfg : Pointer to Structure containing the Hyperbus configuration - * @param Timeout : Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_HyperbusCfg(XSPI_HandleTypeDef *hxspi, XSPI_HyperbusCfgTypeDef *const pCfg, - uint32_t Timeout) -{ - HAL_StatusTypeDef status; - uint32_t state; - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters of the hyperbus configuration structure */ - assert_param(IS_XSPI_RW_RECOVERY_TIME_CYCLE(pCfg->RWRecoveryTimeCycle)); - assert_param(IS_XSPI_ACCESS_TIME_CYCLE(pCfg->AccessTimeCycle)); - assert_param(IS_XSPI_WRITE_ZERO_LATENCY(pCfg->WriteZeroLatency)); - assert_param(IS_XSPI_LATENCY_MODE(pCfg->LatencyMode)); - - /* Check the state of the driver */ - state = hxspi->State; - if ((state == HAL_XSPI_STATE_HYPERBUS_INIT) || (state == HAL_XSPI_STATE_READY)) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Configure Hyperbus configuration Latency register */ - WRITE_REG(hxspi->Instance->HLCR, ((pCfg->RWRecoveryTimeCycle << XSPI_HLCR_TRWR_Pos) | - (pCfg->AccessTimeCycle << XSPI_HLCR_TACC_Pos) | - pCfg->WriteZeroLatency | pCfg->LatencyMode)); - - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_READY; - } - else - { - status = HAL_BUSY; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Set the Hyperbus command configuration. - * @param hxspi : XSPI handle - * @param pCmd : Structure containing the Hyperbus command - * @param Timeout : Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_HyperbusCmd(XSPI_HandleTypeDef *hxspi, XSPI_HyperbusCmdTypeDef *const pCmd, - uint32_t Timeout) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters of the hyperbus command structure */ - assert_param(IS_XSPI_ADDRESS_SPACE(pCmd->AddressSpace)); - assert_param(IS_XSPI_ADDRESS_WIDTH(pCmd->AddressWidth)); - assert_param(IS_XSPI_DATA_LENGTH(pCmd->DataLength)); - assert_param(IS_XSPI_DQS_MODE(pCmd->DQSMode)); - assert_param(IS_XSPI_DATA_MODE(hxspi->Init.MemoryType, pCmd->DataMode)); - - /* Check the state of the driver */ - if ((hxspi->State == HAL_XSPI_STATE_READY) && (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS)) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Re-initialize the value of the functional mode */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, 0U); - - /* Configure the address space in the DCR1 register */ - MODIFY_REG(hxspi->Instance->DCR1, XSPI_DCR1_MTYP_0, pCmd->AddressSpace); - - /* Configure the CCR and WCCR registers with the address size and the following configuration : - - DQS signal enabled (used as RWDS) - - DTR mode enabled on address and data */ - /* - address and data on 8 or 16 lines */ - WRITE_REG(hxspi->Instance->CCR, (pCmd->DQSMode | XSPI_CCR_DDTR | pCmd->DataMode | - pCmd->AddressWidth | XSPI_CCR_ADDTR | XSPI_CCR_ADMODE_2)); - WRITE_REG(hxspi->Instance->WCCR, (pCmd->DQSMode | XSPI_WCCR_DDTR | pCmd->DataMode | - pCmd->AddressWidth | XSPI_WCCR_ADDTR | XSPI_WCCR_ADMODE_2)); - - /* Configure the DLR register with the number of data */ - WRITE_REG(hxspi->Instance->DLR, (pCmd->DataLength - 1U)); - - /* Configure the AR register with the address value */ - WRITE_REG(hxspi->Instance->AR, pCmd->Address); - - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_CMD_CFG; - } - else - { - status = HAL_BUSY; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Transmit an amount of data in blocking mode. - * @param hxspi : XSPI handle - * @param pData : pointer to data buffer - * @param Timeout : Timeout duration - * @note This function is used only in Indirect Write Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Transmit(XSPI_HandleTypeDef *hxspi, const uint8_t *pData, uint32_t Timeout) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - __IO uint32_t *data_reg = &hxspi->Instance->DR; - - /* Check the data pointer allocation */ - if (pData == NULL) - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - else - { - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - /* Configure counters and size */ - hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; - hxspi->XferSize = hxspi->XferCount; - hxspi->pBuffPtr = (uint8_t *)pData; - - /* Configure CR register with functional mode as indirect write */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE); - - do - { - /* Wait till fifo threshold flag is set to send data */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_FT, SET, tickstart, Timeout); - - if (status != HAL_OK) - { - break; - } - - *((__IO uint8_t *)data_reg) = *hxspi->pBuffPtr; - hxspi->pBuffPtr++; - hxspi->XferCount--; - } while (hxspi->XferCount > 0U); - - if (status == HAL_OK) - { - /* Wait till transfer complete flag is set to go back in idle state */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Clear transfer complete flag */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); - - hxspi->State = HAL_XSPI_STATE_READY; - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - - return status; -} - -/** - * @brief Receive an amount of data in blocking mode. - * @param hxspi : XSPI handle - * @param pData : pointer to data buffer - * @param Timeout : Timeout duration - * @note This function is used only in Indirect Read Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Receive(XSPI_HandleTypeDef *hxspi, uint8_t *const pData, uint32_t Timeout) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - __IO uint32_t *data_reg = &hxspi->Instance->DR; - uint32_t addr_reg = hxspi->Instance->AR; - uint32_t ir_reg = hxspi->Instance->IR; - - /* Check the data pointer allocation */ - if (pData == NULL) - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - else - { - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - /* Configure counters and size */ - hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; - hxspi->XferSize = hxspi->XferCount; - hxspi->pBuffPtr = pData; - - /* Configure CR register with functional mode as indirect read */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_READ); - - /* Trig the transfer by re-writing address or instruction register */ - if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - WRITE_REG(hxspi->Instance->IR, ir_reg); - } - } - - do - { - /* Wait till fifo threshold or transfer complete flags are set to read received data */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, (HAL_XSPI_FLAG_FT | HAL_XSPI_FLAG_TC), SET, tickstart, Timeout); - - if (status != HAL_OK) - { - break; - } - - *hxspi->pBuffPtr = *((__IO uint8_t *)data_reg); - hxspi->pBuffPtr++; - hxspi->XferCount--; - } while (hxspi->XferCount > 0U); - - if (status == HAL_OK) - { - /* Wait till transfer complete flag is set to go back in idle state */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Clear transfer complete flag */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); - - hxspi->State = HAL_XSPI_STATE_READY; - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - - return status; -} - -/** - * @brief Send an amount of data in non-blocking mode with interrupt. - * @param hxspi : XSPI handle - * @param pData : pointer to data buffer - * @note This function is used only in Indirect Write Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Transmit_IT(XSPI_HandleTypeDef *hxspi, const uint8_t *pData) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Check the data pointer allocation */ - if (pData == NULL) - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - else - { - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - /* Configure counters and size */ - hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; - hxspi->XferSize = hxspi->XferCount; - hxspi->pBuffPtr = (uint8_t *)pData; - - /* Configure CR register with functional mode as indirect write */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE); - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); - - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_BUSY_TX; - - /* Enable the transfer complete, fifo threshold and transfer error interrupts */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - - return status; -} - -/** - * @brief Receive an amount of data in non-blocking mode with interrupt. - * @param hxspi : XSPI handle - * @param pData : pointer to data buffer - * @note This function is used only in Indirect Read Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Receive_IT(XSPI_HandleTypeDef *hxspi, uint8_t *const pData) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t addr_reg = hxspi->Instance->AR; - uint32_t ir_reg = hxspi->Instance->IR; - - /* Check the data pointer allocation */ - if (pData == NULL) - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - else - { - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - /* Configure counters and size */ - hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; - hxspi->XferSize = hxspi->XferCount; - hxspi->pBuffPtr = pData; - - /* Configure CR register with functional mode as indirect read */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_READ); - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); - - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_BUSY_RX; - - /* Enable the transfer complete, fifo threshold and transfer error interrupts */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); - - /* Trig the transfer by re-writing address or instruction register */ - if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - WRITE_REG(hxspi->Instance->IR, ir_reg); - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - - return status; -} - -/** - * @brief Send an amount of data in non-blocking mode with DMA. - * @param hxspi : XSPI handle - * @param pData : pointer to data buffer - * @note This function is used only in Indirect Write Mode - * @note If DMA peripheral access is configured as halfword, the number - * of data and the fifo threshold should be aligned on halfword - * @note If DMA peripheral access is configured as word, the number - * of data and the fifo threshold should be aligned on word - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Transmit_DMA(XSPI_HandleTypeDef *hxspi, const uint8_t *pData) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t data_size = hxspi->Instance->DLR + 1U; - DMA_QListTypeDef *p_queue = {NULL}; - uint32_t data_width = DMA_DEST_DATAWIDTH_BYTE; - - /* Check the data pointer allocation */ - if (pData == NULL) - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - else - { - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - if ((hxspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - p_queue = hxspi->hdmatx->LinkedListQueue; - if ((p_queue != NULL) && (p_queue->Head != NULL)) - { - data_width = p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - } - else - { - /* Set Error Code function status */ - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - - /* Return function status */ - status = HAL_ERROR; - } - } - else - { - data_width = hxspi->hdmatx->Init.DestDataWidth; - } - /* Configure counters and size */ - if (data_width == DMA_DEST_DATAWIDTH_BYTE) - { - hxspi->XferCount = data_size; - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - if (((data_size % 2U) != 0U) || ((hxspi->Init.FifoThresholdByte % 2U) != 0U)) - { - /* The number of data or the fifo threshold is not aligned on halfword - => no transfer possible with DMA peripheral access configured as halfword */ - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - hxspi->XferCount = data_size; - } - } - else if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - if (((data_size % 4U) != 0U) || ((hxspi->Init.FifoThresholdByte % 4U) != 0U)) - { - /* The number of data or the fifo threshold is not aligned on word - => no transfer possible with DMA peripheral access configured as word */ - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - hxspi->XferCount = data_size; - } - } - else - { - /* Nothing to do */ - } - - if (status == HAL_OK) - { - hxspi->XferSize = hxspi->XferCount; - hxspi->pBuffPtr = (uint8_t *)pData; - - /* Configure CR register with functional mode as indirect write */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE); - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); - - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_BUSY_TX; - - /* Set the DMA transfer complete callback */ - hxspi->hdmatx->XferCpltCallback = XSPI_DMACplt; - - /* Set the DMA Half transfer complete callback */ - hxspi->hdmatx->XferHalfCpltCallback = XSPI_DMAHalfCplt; - - /* Set the DMA error callback */ - hxspi->hdmatx->XferErrorCallback = XSPI_DMAError; - - /* Clear the DMA abort callback */ - hxspi->hdmatx->XferAbortCallback = NULL; - - /* Enable the transmit DMA Channel */ - if ((hxspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hxspi->hdmatx->LinkedListQueue != NULL) - { - /* Enable the DMA channel */ - MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET], \ - (DMA_CTR1_SINC | DMA_CTR1_DINC), (DMA_SINC_INCREMENTED | DMA_DINC_FIXED)); - MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET], \ - DMA_CTR2_DREQ, DMA_MEMORY_TO_PERIPH); - /* Set DMA data size*/ - p_queue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hxspi->XferSize; - /* Set DMA source address */ - p_queue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; - /* Set DMA destination address */ - p_queue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hxspi->Instance->DR; - - status = HAL_DMAEx_List_Start_IT(hxspi->hdmatx); - } - else - { - /* Set Error Code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - - hxspi->State = HAL_XSPI_STATE_READY; - - /* Return function status */ - status = HAL_ERROR; - } - } - else - { - if ((hxspi->hdmatx->Init.Direction == DMA_MEMORY_TO_PERIPH) && - (hxspi->hdmatx->Init.SrcInc == DMA_SINC_INCREMENTED) && (hxspi->hdmatx->Init.DestInc == DMA_DINC_FIXED)) - { - status = HAL_DMA_Start_IT(hxspi->hdmatx, (uint32_t)pData, (uint32_t)&hxspi->Instance->DR, hxspi->XferSize); - } - else - { - /* no transmit possible with DMA peripheral, invalid configuration */ - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - } - if (status == HAL_OK) - { - /* Enable the transfer error interrupt */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TE); - - /* Enable the DMA transfer by setting the DMAEN bit */ - SET_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - hxspi->State = HAL_XSPI_STATE_READY; - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - - return status; -} - -/** - * @brief Receive an amount of data in non-blocking mode with DMA. - * @param hxspi : XSPI handle - * @param pData : pointer to data buffer. - * @note This function is used only in Indirect Read Mode - * @note If DMA peripheral access is configured as halfword, the number - * of data and the fifo threshold should be aligned on halfword - * @note If DMA peripheral access is configured as word, the number - * of data and the fifo threshold should be aligned on word - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Receive_DMA(XSPI_HandleTypeDef *hxspi, uint8_t *const pData) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t data_size = hxspi->Instance->DLR + 1U; - uint32_t addr_reg = hxspi->Instance->AR; - uint32_t ir_reg = hxspi->Instance->IR; - DMA_QListTypeDef *p_queue = {NULL}; - uint32_t data_width = DMA_DEST_DATAWIDTH_BYTE; - - /* Check the data pointer allocation */ - if (pData == NULL) - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - else - { - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - if ((hxspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - p_queue = hxspi->hdmarx->LinkedListQueue; - if ((p_queue != NULL) && (p_queue->Head != NULL)) - { - data_width = p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; - } - else - { - /* Set Error Code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - - /* Return function status */ - status = HAL_ERROR; - } - } - else - { - data_width = hxspi->hdmarx->Init.DestDataWidth; - } - - /* Configure counters and size */ - if (data_width == DMA_DEST_DATAWIDTH_BYTE) - { - hxspi->XferCount = data_size; - } - else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) - { - if (((data_size % 2U) != 0U) || ((hxspi->Init.FifoThresholdByte % 2U) != 0U)) - { - /* The number of data or the fifo threshold is not aligned on halfword - => no transfer possible with DMA peripheral access configured as halfword */ - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - hxspi->XferCount = data_size; - } - } - else if (data_width == DMA_DEST_DATAWIDTH_WORD) - { - if (((data_size % 4U) != 0U) || ((hxspi->Init.FifoThresholdByte % 4U) != 0U)) - { - /* The number of data or the fifo threshold is not aligned on word - => no transfer possible with DMA peripheral access configured as word */ - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - else - { - hxspi->XferCount = data_size; - } - } - else - { - /* Nothing to do */ - } - - if (status == HAL_OK) - { - hxspi->XferSize = hxspi->XferCount; - hxspi->pBuffPtr = pData; - - /* Configure CR register with functional mode as indirect read */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_READ); - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); - - /* Update the state */ - hxspi->State = HAL_XSPI_STATE_BUSY_RX; - - /* Set the DMA transfer complete callback */ - hxspi->hdmarx->XferCpltCallback = XSPI_DMACplt; - - /* Set the DMA Half transfer complete callback */ - hxspi->hdmarx->XferHalfCpltCallback = XSPI_DMAHalfCplt; - - /* Set the DMA error callback */ - hxspi->hdmarx->XferErrorCallback = XSPI_DMAError; - - /* Clear the DMA abort callback */ - hxspi->hdmarx->XferAbortCallback = NULL; - - /* Enable the receive DMA Channel */ - if ((hxspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) - { - if (hxspi->hdmarx->LinkedListQueue != NULL) - { - /* Enable the DMA channel */ - MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET], \ - (DMA_CTR1_SINC | DMA_CTR1_DINC), (DMA_SINC_FIXED | DMA_DINC_INCREMENTED)); - MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET], \ - DMA_CTR2_DREQ, DMA_PERIPH_TO_MEMORY); - /* Set DMA data size */ - p_queue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hxspi->XferSize; - /* Set DMA source address */ - p_queue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hxspi->Instance->DR; - /* Set DMA destination address */ - p_queue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; - - status = HAL_DMAEx_List_Start_IT(hxspi->hdmarx); - } - else - { - /* Set Error Code */ - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - - hxspi->State = HAL_XSPI_STATE_READY; - - /* Return function status */ - status = HAL_ERROR; - } - } - else - { - if ((hxspi->hdmarx->Init.Direction == DMA_PERIPH_TO_MEMORY) && (hxspi->hdmarx->Init.SrcInc == DMA_SINC_FIXED) - && (hxspi->hdmarx->Init.DestInc == DMA_DINC_INCREMENTED)) - { - status = HAL_DMA_Start_IT(hxspi->hdmarx, (uint32_t)&hxspi->Instance->DR, (uint32_t)pData, hxspi->XferSize); - } - else - { - /* no receive possible with DMA peripheral, invalid configuration */ - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - status = HAL_ERROR; - } - } - if (status == HAL_OK) - { - /* Enable the transfer error interrupt */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TE); - - /* Trig the transfer by re-writing address or instruction register */ - if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - WRITE_REG(hxspi->Instance->IR, ir_reg); - } - } - - /* Enable the DMA transfer by setting the DMAEN bit */ - SET_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - hxspi->State = HAL_XSPI_STATE_READY; - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - - return status; -} - -/** - * @brief Configure the XSPI Automatic Polling Mode in blocking mode. - * @param hxspi : XSPI handle - * @param pCfg : Pointer to structure that contains the polling configuration information. - * @param Timeout : Timeout duration - * @note This function is used only in Automatic Polling Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_AutoPolling(XSPI_HandleTypeDef *hxspi, XSPI_AutoPollingTypeDef *const pCfg, - uint32_t Timeout) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - uint32_t addr_reg = hxspi->Instance->AR; - uint32_t ir_reg = hxspi->Instance->IR; -#ifdef USE_FULL_ASSERT - uint32_t dlr_reg = hxspi->Instance->DLR; -#endif /* USE_FULL_ASSERT */ - - /* Check the parameters of the autopolling configuration structure */ - assert_param(IS_XSPI_MATCH_MODE(pCfg->MatchMode)); - assert_param(IS_XSPI_AUTOMATIC_STOP(pCfg->AutomaticStop)); - assert_param(IS_XSPI_INTERVAL(pCfg->IntervalTime)); - assert_param(IS_XSPI_STATUS_BYTES_SIZE(dlr_reg + 1U)); - - /* Check the state */ - if ((hxspi->State == HAL_XSPI_STATE_CMD_CFG) && (pCfg->AutomaticStop == HAL_XSPI_AUTOMATIC_STOP_ENABLE)) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Configure registers */ - WRITE_REG(hxspi->Instance->PSMAR, pCfg->MatchValue); - WRITE_REG(hxspi->Instance->PSMKR, pCfg->MatchMask); - WRITE_REG(hxspi->Instance->PIR, pCfg->IntervalTime); - MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_PMM | XSPI_CR_APMS | XSPI_CR_FMODE), - (pCfg->MatchMode | pCfg->AutomaticStop | XSPI_FUNCTIONAL_MODE_AUTO_POLLING)); - - /* Trig the transfer by re-writing address or instruction register */ - if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - WRITE_REG(hxspi->Instance->IR, ir_reg); - } - } - - /* Wait till status match flag is set to go back in idle state */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_SM, SET, tickstart, Timeout); - - if (status == HAL_OK) - { - /* Clear status match flag */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_SM); - - hxspi->State = HAL_XSPI_STATE_READY; - } - } - else - { - status = HAL_BUSY; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Configure the XSPI Automatic Polling Mode in non-blocking mode. - * @param hxspi : XSPI handle - * @param pCfg : Pointer to structure that contains the polling configuration information. - * @note This function is used only in Automatic Polling Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_AutoPolling_IT(XSPI_HandleTypeDef *hxspi, XSPI_AutoPollingTypeDef *const pCfg) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - uint32_t addr_reg = hxspi->Instance->AR; - uint32_t ir_reg = hxspi->Instance->IR; -#ifdef USE_FULL_ASSERT - uint32_t dlr_reg = hxspi->Instance->DLR; -#endif /* USE_FULL_ASSERT */ - - /* Check the parameters of the autopolling configuration structure */ - assert_param(IS_XSPI_MATCH_MODE(pCfg->MatchMode)); - assert_param(IS_XSPI_AUTOMATIC_STOP(pCfg->AutomaticStop)); - assert_param(IS_XSPI_INTERVAL(pCfg->IntervalTime)); - assert_param(IS_XSPI_STATUS_BYTES_SIZE(dlr_reg + 1U)); - - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); - - if (status == HAL_OK) - { - /* Configure registers */ - WRITE_REG(hxspi->Instance->PSMAR, pCfg->MatchValue); - WRITE_REG(hxspi->Instance->PSMKR, pCfg->MatchMask); - WRITE_REG(hxspi->Instance->PIR, pCfg->IntervalTime); - MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_PMM | XSPI_CR_APMS | XSPI_CR_FMODE), - (pCfg->MatchMode | pCfg->AutomaticStop | XSPI_FUNCTIONAL_MODE_AUTO_POLLING)); - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_SM); - - hxspi->State = HAL_XSPI_STATE_BUSY_AUTO_POLLING; - - /* Enable the status match and transfer error interrupts */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_SM | HAL_XSPI_IT_TE); - - /* Trig the transfer by re-writing address or instruction register */ - if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) - { - WRITE_REG(hxspi->Instance->AR, addr_reg); - } - else - { - WRITE_REG(hxspi->Instance->IR, ir_reg); - } - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Configure the Memory Mapped mode. - * @param hxspi : XSPI handle - * @param pCfg : Pointer to structure that contains the memory mapped configuration information. - * @note This function is used only in Memory mapped Mode - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_MemoryMapped(XSPI_HandleTypeDef *hxspi, XSPI_MemoryMappedTypeDef *const pCfg) -{ - HAL_StatusTypeDef status; - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters of the memory-mapped configuration structure */ - assert_param(IS_XSPI_TIMEOUT_ACTIVATION(pCfg->TimeOutActivation)); - - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) - { - /* Wait till busy flag is reset */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); - - if (status == HAL_OK) - { - hxspi->State = HAL_XSPI_STATE_BUSY_MEM_MAPPED; - - if (pCfg->TimeOutActivation == HAL_XSPI_TIMEOUT_COUNTER_ENABLE) - { - assert_param(IS_XSPI_TIMEOUT_PERIOD(pCfg->TimeoutPeriodClock)); - - /* Configure register */ - WRITE_REG(hxspi->Instance->LPTR, pCfg->TimeoutPeriodClock); - - /* Clear flags related to interrupt */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TO); - - /* Enable the timeout interrupt */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TO); - } - - /* Configure CR register with functional mode as memory-mapped */ - MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_TCEN | XSPI_CR_FMODE), - (pCfg->TimeOutActivation | XSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)); - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Transfer Error callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_ErrorCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_XSPI_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief Abort completed callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_AbortCpltCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_XSPI_AbortCpltCallback could be implemented in the user file - */ -} - -/** - * @brief FIFO Threshold callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_FifoThresholdCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_XSPI_FIFOThresholdCallback could be implemented in the user file - */ -} - -/** - * @brief Command completed callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_CmdCpltCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_XSPI_CmdCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_RxCpltCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_XSPI_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Tx Transfer completed callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_TxCpltCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_XSPI_TxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Half Transfer completed callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_RxHalfCpltCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_XSPI_RxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Tx Half Transfer completed callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_TxHalfCpltCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_XSPI_TxHalfCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Status Match callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_StatusMatchCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_XSPI_StatusMatchCallback could be implemented in the user file - */ -} - -/** - * @brief Timeout callback. - * @param hxspi : XSPI handle - * @retval None - */ -__weak void HAL_XSPI_TimeOutCallback(XSPI_HandleTypeDef *hxspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hxspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_XSPI_TimeOutCallback could be implemented in the user file - */ -} - -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) -/** - * @brief Register a User XSPI Callback - * To be used to override the weak predefined callback - * @param hxspi : XSPI handle - * @param CallbackID : ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_XSPI_ERROR_CB_ID XSPI Error Callback ID - * @arg @ref HAL_XSPI_ABORT_CB_ID XSPI Abort Callback ID - * @arg @ref HAL_XSPI_FIFO_THRESHOLD_CB_ID XSPI FIFO Threshold Callback ID - * @arg @ref HAL_XSPI_CMD_CPLT_CB_ID XSPI Command Complete Callback ID - * @arg @ref HAL_XSPI_RX_CPLT_CB_ID XSPI Rx Complete Callback ID - * @arg @ref HAL_XSPI_TX_CPLT_CB_ID XSPI Tx Complete Callback ID - * @arg @ref HAL_XSPI_RX_HALF_CPLT_CB_ID XSPI Rx Half Complete Callback ID - * @arg @ref HAL_XSPI_TX_HALF_CPLT_CB_ID XSPI Tx Half Complete Callback ID - * @arg @ref HAL_XSPI_STATUS_MATCH_CB_ID XSPI Status Match Callback ID - * @arg @ref HAL_XSPI_TIMEOUT_CB_ID XSPI Timeout Callback ID - * @arg @ref HAL_XSPI_MSP_INIT_CB_ID XSPI MspInit callback ID - * @arg @ref HAL_XSPI_MSP_DEINIT_CB_ID XSPI MspDeInit callback ID - * @param pCallback : pointer to the Callback function - * @retval status - */ -HAL_StatusTypeDef HAL_XSPI_RegisterCallback(XSPI_HandleTypeDef *hxspi, HAL_XSPI_CallbackIDTypeDef CallbackID, - pXSPI_CallbackTypeDef pCallback) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) - { - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - return HAL_ERROR; - } - - if (hxspi->State == HAL_XSPI_STATE_READY) - { - switch (CallbackID) - { - case HAL_XSPI_ERROR_CB_ID : - hxspi->ErrorCallback = pCallback; - break; - case HAL_XSPI_ABORT_CB_ID : - hxspi->AbortCpltCallback = pCallback; - break; - case HAL_XSPI_FIFO_THRESHOLD_CB_ID : - hxspi->FifoThresholdCallback = pCallback; - break; - case HAL_XSPI_CMD_CPLT_CB_ID : - hxspi->CmdCpltCallback = pCallback; - break; - case HAL_XSPI_RX_CPLT_CB_ID : - hxspi->RxCpltCallback = pCallback; - break; - case HAL_XSPI_TX_CPLT_CB_ID : - hxspi->TxCpltCallback = pCallback; - break; - case HAL_XSPI_RX_HALF_CPLT_CB_ID : - hxspi->RxHalfCpltCallback = pCallback; - break; - case HAL_XSPI_TX_HALF_CPLT_CB_ID : - hxspi->TxHalfCpltCallback = pCallback; - break; - case HAL_XSPI_STATUS_MATCH_CB_ID : - hxspi->StatusMatchCallback = pCallback; - break; - case HAL_XSPI_TIMEOUT_CB_ID : - hxspi->TimeOutCallback = pCallback; - break; - case HAL_XSPI_MSP_INIT_CB_ID : - hxspi->MspInitCallback = pCallback; - break; - case HAL_XSPI_MSP_DEINIT_CB_ID : - hxspi->MspDeInitCallback = pCallback; - break; - default : - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hxspi->State == HAL_XSPI_STATE_RESET) - { - switch (CallbackID) - { - case HAL_XSPI_MSP_INIT_CB_ID : - hxspi->MspInitCallback = pCallback; - break; - case HAL_XSPI_MSP_DEINIT_CB_ID : - hxspi->MspDeInitCallback = pCallback; - break; - default : - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} - -/** - * @brief Unregister a User XSPI Callback - * XSPI Callback is redirected to the weak predefined callback - * @param hxspi : XSPI handle - * @param CallbackID : ID of the callback to be unregistered - * This parameter can be one of the following values: - * @arg @ref HAL_XSPI_ERROR_CB_ID XSPI Error Callback ID - * @arg @ref HAL_XSPI_ABORT_CB_ID XSPI Abort Callback ID - * @arg @ref HAL_XSPI_FIFO_THRESHOLD_CB_ID XSPI FIFO Threshold Callback ID - * @arg @ref HAL_XSPI_CMD_CPLT_CB_ID XSPI Command Complete Callback ID - * @arg @ref HAL_XSPI_RX_CPLT_CB_ID XSPI Rx Complete Callback ID - * @arg @ref HAL_XSPI_TX_CPLT_CB_ID XSPI Tx Complete Callback ID - * @arg @ref HAL_XSPI_RX_HALF_CPLT_CB_ID XSPI Rx Half Complete Callback ID - * @arg @ref HAL_XSPI_TX_HALF_CPLT_CB_ID XSPI Tx Half Complete Callback ID - * @arg @ref HAL_XSPI_STATUS_MATCH_CB_ID XSPI Status Match Callback ID - * @arg @ref HAL_XSPI_TIMEOUT_CB_ID XSPI Timeout Callback ID - * @arg @ref HAL_XSPI_MSP_INIT_CB_ID XSPI MspInit callback ID - * @arg @ref HAL_XSPI_MSP_DEINIT_CB_ID XSPI MspDeInit callback ID - * @retval status - */ -HAL_StatusTypeDef HAL_XSPI_UnRegisterCallback(XSPI_HandleTypeDef *hxspi, HAL_XSPI_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (hxspi->State == HAL_XSPI_STATE_READY) - { - switch (CallbackID) - { - case HAL_XSPI_ERROR_CB_ID : - hxspi->ErrorCallback = HAL_XSPI_ErrorCallback; - break; - case HAL_XSPI_ABORT_CB_ID : - hxspi->AbortCpltCallback = HAL_XSPI_AbortCpltCallback; - break; - case HAL_XSPI_FIFO_THRESHOLD_CB_ID : - hxspi->FifoThresholdCallback = HAL_XSPI_FifoThresholdCallback; - break; - case HAL_XSPI_CMD_CPLT_CB_ID : - hxspi->CmdCpltCallback = HAL_XSPI_CmdCpltCallback; - break; - case HAL_XSPI_RX_CPLT_CB_ID : - hxspi->RxCpltCallback = HAL_XSPI_RxCpltCallback; - break; - case HAL_XSPI_TX_CPLT_CB_ID : - hxspi->TxCpltCallback = HAL_XSPI_TxCpltCallback; - break; - case HAL_XSPI_RX_HALF_CPLT_CB_ID : - hxspi->RxHalfCpltCallback = HAL_XSPI_RxHalfCpltCallback; - break; - case HAL_XSPI_TX_HALF_CPLT_CB_ID : - hxspi->TxHalfCpltCallback = HAL_XSPI_TxHalfCpltCallback; - break; - case HAL_XSPI_STATUS_MATCH_CB_ID : - hxspi->StatusMatchCallback = HAL_XSPI_StatusMatchCallback; - break; - case HAL_XSPI_TIMEOUT_CB_ID : - hxspi->TimeOutCallback = HAL_XSPI_TimeOutCallback; - break; - case HAL_XSPI_MSP_INIT_CB_ID : - hxspi->MspInitCallback = HAL_XSPI_MspInit; - break; - case HAL_XSPI_MSP_DEINIT_CB_ID : - hxspi->MspDeInitCallback = HAL_XSPI_MspDeInit; - break; - default : - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else if (hxspi->State == HAL_XSPI_STATE_RESET) - { - switch (CallbackID) - { - case HAL_XSPI_MSP_INIT_CB_ID : - hxspi->MspInitCallback = HAL_XSPI_MspInit; - break; - case HAL_XSPI_MSP_DEINIT_CB_ID : - hxspi->MspDeInitCallback = HAL_XSPI_MspDeInit; - break; - default : - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - break; - } - } - else - { - /* Update the error code */ - hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; - /* update return status */ - status = HAL_ERROR; - } - - return status; -} -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - -/** - * @} - */ - -/** @defgroup XSPI_Exported_Functions_Group3 Peripheral Control and State functions - * @brief XSPI control and State functions - * -@verbatim - =============================================================================== - ##### Peripheral Control and State functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to : - (+) Check in run-time the state of the driver. - (+) Check the error code set during last operation. - (+) Abort any operation. - (+) Manage the Fifo threshold. - (+) Configure the timeout duration used in the driver. - -@endverbatim - * @{ - */ - -/** - * @brief Abort the current operation, return to the indirect mode. - * @param hxspi : XSPI handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Abort(XSPI_HandleTypeDef *hxspi) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t state; - uint32_t tickstart = HAL_GetTick(); - - /* Check if the state is in one of the busy or configured states */ - state = hxspi->State; - if (((state & XSPI_BUSY_STATE_MASK) != 0U) || ((state & XSPI_CFG_STATE_MASK) != 0U)) - { - /* Check if the DMA is enabled */ - if ((hxspi->Instance->CR & XSPI_CR_DMAEN) != 0U) - { - /* Disable the DMA transfer on the XSPI side */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - - /* Disable the DMA transmit on the DMA side */ - status = HAL_DMA_Abort(hxspi->hdmatx); - if (status != HAL_OK) - { - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - } - - /* Disable the DMA receive on the DMA side */ - status = HAL_DMA_Abort(hxspi->hdmarx); - if (status != HAL_OK) - { - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - } - } - - if (HAL_XSPI_GET_FLAG(hxspi, HAL_XSPI_FLAG_BUSY) != RESET) - { - /* Perform an abort of the XSPI */ - SET_BIT(hxspi->Instance->CR, XSPI_CR_ABORT); - - /* Wait until the transfer complete flag is set to go back in idle state */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, hxspi->Timeout); - - if (status == HAL_OK) - { - /* Clear transfer complete flag */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); - - /* Wait until the busy flag is reset to go back in idle state */ - status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); - - if (status == HAL_OK) - { - /* Return to indirect mode */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); - - hxspi->State = HAL_XSPI_STATE_READY; - } - } - } - else - { - /* Return to indirect mode */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); - - hxspi->State = HAL_XSPI_STATE_READY; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** - * @brief Abort the current operation, return to the indirect mode. (non-blocking function) - * @param hxspi : XSPI handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_Abort_IT(XSPI_HandleTypeDef *hxspi) -{ - HAL_StatusTypeDef status = HAL_OK; - uint32_t state; - - /* Check if the state is in one of the busy or configured states */ - state = hxspi->State; - if (((state & XSPI_BUSY_STATE_MASK) != 0U) || ((state & XSPI_CFG_STATE_MASK) != 0U)) - { - /* Disable all interrupts */ - HAL_XSPI_DISABLE_IT(hxspi, (HAL_XSPI_IT_TO | HAL_XSPI_IT_SM | HAL_XSPI_IT_FT | HAL_XSPI_IT_TC | HAL_XSPI_IT_TE)); - - hxspi->State = HAL_XSPI_STATE_ABORT; - - /* Check if the DMA is enabled */ - if ((hxspi->Instance->CR & XSPI_CR_DMAEN) != 0U) - { - /* Disable the DMA transfer on the XSPI side */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - - /* Disable the DMA transmit on the DMA side */ - hxspi->hdmatx->XferAbortCallback = XSPI_DMAAbortCplt; - if (HAL_DMA_Abort_IT(hxspi->hdmatx) != HAL_OK) - { - hxspi->State = HAL_XSPI_STATE_READY; - - /* Abort callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->AbortCpltCallback(hxspi); -#else - HAL_XSPI_AbortCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - - /* Disable the DMA receive on the DMA side */ - hxspi->hdmarx->XferAbortCallback = XSPI_DMAAbortCplt; - if (HAL_DMA_Abort_IT(hxspi->hdmarx) != HAL_OK) - { - hxspi->State = HAL_XSPI_STATE_READY; - - /* Abort callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->AbortCpltCallback(hxspi); -#else - HAL_XSPI_AbortCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - } - else - { - if (HAL_XSPI_GET_FLAG(hxspi, HAL_XSPI_FLAG_BUSY) != RESET) - { - /* Clear transfer complete flag */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); - - /* Enable the transfer complete interrupts */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC); - - /* Perform an abort of the XSPI */ - SET_BIT(hxspi->Instance->CR, XSPI_CR_ABORT); - - /* Return to indirect mode */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); - } - else - { - /* Return to indirect mode */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); - - hxspi->State = HAL_XSPI_STATE_READY; - - /* Abort callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->AbortCpltCallback(hxspi); -#else - HAL_XSPI_AbortCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** @brief Set XSPI Fifo threshold. - * @param hxspi : XSPI handle. - * @param Threshold : Threshold of the Fifo. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_SetFifoThreshold(XSPI_HandleTypeDef *hxspi, uint32_t Threshold) -{ - HAL_StatusTypeDef status = HAL_OK; - - assert_param(IS_XSPI_FIFO_THRESHOLD_BYTE(Threshold)); - - /* Check the state */ - if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) - { - /* Synchronize initialization structure with the new fifo threshold value */ - hxspi->Init.FifoThresholdByte = Threshold; - - /* Configure new fifo threshold */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FTHRES, ((hxspi->Init.FifoThresholdByte - 1U) << XSPI_CR_FTHRES_Pos)); - - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** @brief Get XSPI Fifo threshold. - * @param hxspi : XSPI handle. - * @retval Fifo threshold - */ -uint32_t HAL_XSPI_GetFifoThreshold(const XSPI_HandleTypeDef *hxspi) -{ - return ((READ_BIT(hxspi->Instance->CR, XSPI_CR_FTHRES) >> XSPI_CR_FTHRES_Pos) + 1U); -} - -/** @brief Set XSPI Memory Type. - * @param hxspi : XSPI handle. - * @param Type : Memory Type. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_SetMemoryType(XSPI_HandleTypeDef *hxspi, uint32_t Type) -{ - HAL_StatusTypeDef status = HAL_OK; - - assert_param(IS_XSPI_MEMORY_TYPE(Type)); - - /* Check the state */ - if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) - { - /* Synchronize initialization structure with the new memory type value */ - hxspi->Init.MemoryType = Type; - - /* Configure new memory type */ - MODIFY_REG(hxspi->Instance->DCR1, XSPI_DCR1_MTYP, hxspi->Init.MemoryType); - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** @brief Set XSPI Device Size. - * @param hxspi : XSPI handle. - * @param Size : Device Size. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_SetDeviceSize(XSPI_HandleTypeDef *hxspi, uint32_t Size) -{ - HAL_StatusTypeDef status = HAL_OK; - - assert_param(IS_XSPI_MEMORY_SIZE(Size)); - - /* Check the state */ - if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) - { - /* Synchronize initialization structure with the new device size value */ - hxspi->Init.MemorySize = Size; - - /* Configure new device size */ - MODIFY_REG(hxspi->Instance->DCR1, XSPI_DCR1_DEVSIZE, - (hxspi->Init.MemorySize << XSPI_DCR1_DEVSIZE_Pos)); - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** @brief Set XSPI Clock prescaler. - * @param hxspi : XSPI handle. - * @param Prescaler : Clock prescaler. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_SetClockPrescaler(XSPI_HandleTypeDef *hxspi, uint32_t Prescaler) -{ - HAL_StatusTypeDef status = HAL_OK; - assert_param(IS_XSPI_CLK_PRESCALER(Prescaler)); - - /* Check the state */ - if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) - { - /* Synchronize initialization structure with the new clock prescaler value */ - hxspi->Init.ClockPrescaler = Prescaler; - - /* Configure clock prescaler */ - MODIFY_REG(hxspi->Instance->DCR2, XSPI_DCR2_PRESCALER, - ((hxspi->Init.ClockPrescaler) << XSPI_DCR2_PRESCALER_Pos)); - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - - return status; -} - -/** @brief Set XSPI timeout. - * @param hxspi : XSPI handle. - * @param Timeout : Timeout for the memory access. - * @retval HAL state - */ -HAL_StatusTypeDef HAL_XSPI_SetTimeout(XSPI_HandleTypeDef *hxspi, uint32_t Timeout) -{ - hxspi->Timeout = Timeout; - return HAL_OK; -} - -/** - * @brief Return the XSPI error code. - * @param hxspi : XSPI handle - * @retval XSPI Error Code - */ -uint32_t HAL_XSPI_GetError(const XSPI_HandleTypeDef *hxspi) -{ - return hxspi->ErrorCode; -} - -/** - * @brief Return the XSPI handle state. - * @param hxspi : XSPI handle - * @retval HAL state - */ -uint32_t HAL_XSPI_GetState(const XSPI_HandleTypeDef *hxspi) -{ - /* Return XSPI handle state */ - return hxspi->State; -} - -/** - * @} - */ - -/** @defgroup XSPI_Exported_Functions_Group4 IO Manager configuration function - * @brief XSPI IO Manager configuration function - * -@verbatim - =============================================================================== - ##### IO Manager configuration function ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to : - (+) Configure the IO manager. - -@endverbatim - * @{ - */ - -/** - * @brief Configure the XSPI IO manager. - * @param hxspi : XSPI handle - * @param pCfg : Pointer to Configuration of the IO Manager for the instance - * @param Timeout : Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPIM_Config(XSPI_HandleTypeDef *const hxspi, XSPIM_CfgTypeDef *const pCfg, uint32_t Timeout) -{ - HAL_StatusTypeDef status = HAL_OK; - uint8_t index; - uint8_t xspi_enabled = 0U; - - XSPIM_CfgTypeDef IOM_cfg[XSPI_NB_INSTANCE] = {0}; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(Timeout); - - /* Check the parameters of the XSPI IO Manager configuration structure */ - assert_param(IS_XSPIM_NCS_OVR(pCfg->nCSOverride)); - assert_param(IS_XSPIM_IO_PORT(pCfg->IOPort)); - assert_param(IS_XSPIM_REQ2ACKTIME(pCfg->Req2AckTime)); - - /**************** Get current configuration of the instances ****************/ - for (index = 0U; index < XSPI_NB_INSTANCE; index++) - { - XSPIM_GetConfig(index + 1U, &(IOM_cfg[index])); - } - - /********** Disable both XSPI to configure XSPI IO Manager **********/ - if ((XSPI1->CR & XSPI_CR_EN) != 0U) - { - CLEAR_BIT(XSPI1->CR, XSPI_CR_EN); - xspi_enabled |= 0x1U; - } - if ((XSPI2->CR & XSPI_CR_EN) != 0U) - { - CLEAR_BIT(XSPI2->CR, XSPI_CR_EN); - xspi_enabled |= 0x2U; - } - - /***************** Deactivation of previous configuration *****************/ - CLEAR_REG(XSPIM->CR); - - /******************** Activation of new configuration *********************/ - MODIFY_REG(XSPIM->CR, XSPIM_CR_REQ2ACK_TIME, ((pCfg->Req2AckTime - 1U) << XSPIM_CR_REQ2ACK_TIME_Pos)); - - if (hxspi->Instance == XSPI1) - { - IOM_cfg[0].IOPort = pCfg->IOPort ; - if (pCfg->nCSOverride != HAL_XSPI_CSSEL_OVR_DISABLED) - { - MODIFY_REG(XSPIM->CR, (XSPIM_CR_CSSEL_OVR_O1 | XSPIM_CR_CSSEL_OVR_EN), (pCfg->nCSOverride)); - } - else - { - /* Nothing to do */ - } - } - else if (hxspi->Instance == XSPI2) - { - IOM_cfg[1].IOPort = pCfg->IOPort ; - if (pCfg->nCSOverride != HAL_XSPI_CSSEL_OVR_DISABLED) - { - MODIFY_REG(XSPIM->CR, (XSPIM_CR_CSSEL_OVR_O2 | XSPIM_CR_CSSEL_OVR_EN), (pCfg->nCSOverride)); - } - else - { - /* Nothing to do */ - } - } - else - { - return HAL_ERROR; - } - - for (index = 0U; index < (XSPI_NB_INSTANCE - 1U); index++) - { - if ((IOM_cfg[index].IOPort == IOM_cfg[index + 1U].IOPort)) - { - /*Mux*/ - SET_BIT(XSPIM->CR, XSPIM_CR_MUXEN); - } - else - { - /* Nothing to do */ - } - if (IOM_cfg[0].IOPort == HAL_XSPIM_IOPORT_2) - { - /*Mode*/ - SET_BIT(XSPIM->CR, XSPIM_CR_MODE); - } - else - { - /* Nothing to do */ - } - } - - /******* Re-enable both XSPI after configure XSPI IO Manager ********/ - if ((xspi_enabled & 0x1U) != 0U) - { - SET_BIT(XSPI1->CR, XSPI_CR_EN); - } - if ((xspi_enabled & 0x2U) != 0U) - { - SET_BIT(XSPI2->CR, XSPI_CR_EN); - } - - return status; -} - -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup XSPI_Exported_Functions_Group6 High-speed interface and calibration functions - * @brief XSPI high-speed interface and calibration functions - * -@verbatim - =============================================================================== - ##### High-speed interface and calibration functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to : - (+) Get the delay values of the high-speed interface DLLs. - (+) Set a delay value for the high-speed interface DLLs. - -@endverbatim - * @{ - */ - -/** - * @brief Get the delay values of the high-speed interface DLLs. - * @param hxspi : XSPI handle - * @param pCfg : Current delay values corresponding to the DelayValueType field. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_GetDelayValue(XSPI_HandleTypeDef *hxspi, XSPI_HSCalTypeDef *const pCfg) -{ - HAL_StatusTypeDef status = HAL_OK; - __IO uint32_t reg = 0; - - if (IS_XSPI_ALL_INSTANCE(hxspi->Instance)) - { - /* Check the parameter specified in the structure */ - assert_param(IS_XSPI_DELAY_TYPE(pCfg->DelayValueType)); - - switch (pCfg->DelayValueType) - { - case HAL_XSPI_CAL_FULL_CYCLE_DELAY: - reg = hxspi->Instance->CALFCR; - pCfg->MaxCalibration = (reg & XSPI_CALFCR_CALMAX); - break; - case HAL_XSPI_CAL_FEEDBACK_CLK_DELAY: - reg = hxspi->Instance->CALMR; - break; - case HAL_XSPI_CAL_DATA_OUTPUT_DELAY: - reg = hxspi->Instance->CALSOR; - break; - case HAL_XSPI_CAL_DQS_INPUT_DELAY: - reg = hxspi->Instance->CALSIR; - break; - default: - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - break; - } - - if (status == HAL_OK) - { - pCfg->FineCalibrationUnit = (reg & XSPI_CALFCR_FINE); - pCfg->CoarseCalibrationUnit = ((reg & XSPI_CALFCR_COARSE) >> XSPI_CALFCR_COARSE_Pos); - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - - return status; -} - -/** - * @brief Set a delay value for the high-speed interface DLLs. - * @param hxspi : XSPI handle - * @param pCfg : Configuration of delay value specified in DelayValueType field. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_XSPI_SetDelayValue(XSPI_HandleTypeDef *hxspi, XSPI_HSCalTypeDef *const pCfg) -{ - HAL_StatusTypeDef status = HAL_OK; - - if (IS_XSPI_ALL_INSTANCE(hxspi->Instance)) - { - /* Check the parameter specified in the structure */ - assert_param(IS_XSPI_DELAY_TYPE(pCfg->DelayValueType)); - assert_param(IS_XSPI_FINECAL_VALUE(pCfg->FineCalibrationUnit)); - assert_param(IS_XSPI_COARSECAL_VALUE(pCfg->CoarseCalibrationUnit)); - - /* Check if the state isn't in one of the busy states */ - if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) - { - switch (pCfg->DelayValueType) - { - case HAL_XSPI_CAL_FEEDBACK_CLK_DELAY: - MODIFY_REG(hxspi->Instance->CALMR, (XSPI_CALMR_COARSE | XSPI_CALMR_FINE), - (pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << XSPI_CALMR_COARSE_Pos))); - break; - case HAL_XSPI_CAL_DATA_OUTPUT_DELAY: - MODIFY_REG(hxspi->Instance->CALSOR, (XSPI_CALSOR_COARSE | XSPI_CALSOR_FINE), - (pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << XSPI_CALSOR_COARSE_Pos))); - break; - case HAL_XSPI_CAL_DQS_INPUT_DELAY: - MODIFY_REG(hxspi->Instance->CALSIR, (XSPI_CALSIR_COARSE | XSPI_CALSIR_FINE), - (pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << XSPI_CALSIR_COARSE_Pos))); - break; - default: - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - break; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; - } - } - else - { - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - - return status; -} - -/** - * @} - */ - -/** - @cond 0 - */ -/** - * @brief DMA XSPI process complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void XSPI_DMACplt(DMA_HandleTypeDef *hdma) -{ - XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); - hxspi->XferCount = 0; - - /* Disable the DMA transfer on the XSPI side */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - - /* Enable the XSPI transfer complete Interrupt */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC); -} - -/** - * @brief DMA XSPI process half complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void XSPI_DMAHalfCplt(DMA_HandleTypeDef *hdma) -{ - XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); - hxspi->XferCount = (hxspi->XferCount >> 1); - - if (hxspi->State == HAL_XSPI_STATE_BUSY_RX) - { -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->RxHalfCpltCallback(hxspi); -#else - HAL_XSPI_RxHalfCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - else - { -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->TxHalfCpltCallback(hxspi); -#else - HAL_XSPI_TxHalfCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } -} - -/** - * @brief DMA XSPI communication error callback. - * @param hdma : DMA handle - * @retval None - */ -static void XSPI_DMAError(DMA_HandleTypeDef *hdma) -{ - XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); - hxspi->XferCount = 0; - hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; - - /* Disable the DMA transfer on the XSPI side */ - CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); - - /* Abort the XSPI */ - if (HAL_XSPI_Abort_IT(hxspi) != HAL_OK) - { - /* Disable the interrupts */ - HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); - - hxspi->State = HAL_XSPI_STATE_READY; - - /* Error callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->ErrorCallback(hxspi); -#else - HAL_XSPI_ErrorCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } -} - -/** - * @brief DMA XSPI abort complete callback. - * @param hdma : DMA handle - * @retval None - */ -static void XSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma) -{ - XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); - hxspi->XferCount = 0; - - /* Check the state */ - if (hxspi->State == HAL_XSPI_STATE_ABORT) - { - /* DMA abort called by XSPI abort */ - if (HAL_XSPI_GET_FLAG(hxspi, HAL_XSPI_FLAG_BUSY) != RESET) - { - /* Clear transfer complete flag */ - HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); - - /* Enable the transfer complete interrupts */ - HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC); - - /* Perform an abort of the XSPI */ - SET_BIT(hxspi->Instance->CR, XSPI_CR_ABORT); - } - else - { - hxspi->State = HAL_XSPI_STATE_READY; - - /* Abort callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->AbortCpltCallback(hxspi); -#else - HAL_XSPI_AbortCpltCallback(hxspi); -#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } - } - else - { - /* DMA abort called due to a transfer error interrupt */ - hxspi->State = HAL_XSPI_STATE_READY; - - /* Error callback */ -#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) - hxspi->ErrorCallback(hxspi); -#else - HAL_XSPI_ErrorCallback(hxspi); -#endif /* defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ - } -} - -/** - * @brief Wait for a flag state until timeout. - * @param hxspi : XSPI handle - * @param Flag : Flag checked - * @param State : Value of the flag expected - * @param Timeout : Duration of the timeout - * @param Tickstart : Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef XSPI_WaitFlagStateUntilTimeout(XSPI_HandleTypeDef *hxspi, uint32_t Flag, - FlagStatus State, uint32_t Tickstart, uint32_t Timeout) -{ - /* Wait until flag is in expected state */ - while ((HAL_XSPI_GET_FLAG(hxspi, Flag)) != State) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) - { - hxspi->State = HAL_XSPI_STATE_ERROR; - hxspi->ErrorCode |= HAL_XSPI_ERROR_TIMEOUT; - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief Configure the registers for the regular command mode. - * @param hxspi : XSPI handle - * @param pCmd : structure that contains the command configuration information - * @retval HAL status - */ -static HAL_StatusTypeDef XSPI_ConfigCmd(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *pCmd) -{ - HAL_StatusTypeDef status = HAL_OK; - __IO uint32_t *ccr_reg; - __IO uint32_t *tcr_reg; - __IO uint32_t *ir_reg; - __IO uint32_t *abr_reg; - - /* Re-initialize the value of the functional mode */ - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, 0U); - - if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM) - { - assert_param(IS_XSPI_IO_SELECT(pCmd->IOSelect)); - MODIFY_REG(hxspi->Instance->CR, XSPI_CR_MSEL, pCmd->IOSelect); - } - - if (pCmd->OperationType == HAL_XSPI_OPTYPE_WRITE_CFG) - { - ccr_reg = &(hxspi->Instance->WCCR); - tcr_reg = &(hxspi->Instance->WTCR); - ir_reg = &(hxspi->Instance->WIR); - abr_reg = &(hxspi->Instance->WABR); - } - else if (pCmd->OperationType == HAL_XSPI_OPTYPE_WRAP_CFG) - { - ccr_reg = &(hxspi->Instance->WPCCR); - tcr_reg = &(hxspi->Instance->WPTCR); - ir_reg = &(hxspi->Instance->WPIR); - abr_reg = &(hxspi->Instance->WPABR); - } - else - { - ccr_reg = &(hxspi->Instance->CCR); - tcr_reg = &(hxspi->Instance->TCR); - ir_reg = &(hxspi->Instance->IR); - abr_reg = &(hxspi->Instance->ABR); - } - - /* Configure the CCR register with DQS and SIOO modes */ - *ccr_reg = pCmd->DQSMode; - - if (pCmd->AlternateBytesMode != HAL_XSPI_ALT_BYTES_NONE) - { - /* Configure the ABR register with alternate bytes value */ - *abr_reg = pCmd->AlternateBytes; - - /* Configure the CCR register with alternate bytes communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_ABMODE | XSPI_CCR_ABDTR | XSPI_CCR_ABSIZE), - (pCmd->AlternateBytesMode | pCmd->AlternateBytesDTRMode | pCmd->AlternateBytesWidth)); - } - - /* Configure the TCR register with the number of dummy cycles */ - MODIFY_REG((*tcr_reg), XSPI_TCR_DCYC, pCmd->DummyCycles); - - if (pCmd->DataMode != HAL_XSPI_DATA_NONE) - { - if (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) - { - /* Configure the DLR register with the number of data */ - hxspi->Instance->DLR = (pCmd->DataLength - 1U); - } - } - - if (pCmd->InstructionMode != HAL_XSPI_INSTRUCTION_NONE) - { - if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) - { - if (pCmd->DataMode != HAL_XSPI_DATA_NONE) - { - /* ---- Command with instruction, address and data ---- */ - - /* Configure the CCR register with all communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE | - XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE | - XSPI_CCR_DMODE | XSPI_CCR_DDTR), - (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth | - pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth | - pCmd->DataMode | pCmd->DataDTRMode)); - } - else - { - /* ---- Command with instruction and address ---- */ - - /* Configure the CCR register with all communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE | - XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE), - (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth | - pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth)); - - /* The DHQC bit is linked with DDTR bit which should be activated */ - if ((hxspi->Init.DelayHoldQuarterCycle == HAL_XSPI_DHQC_ENABLE) && - (pCmd->InstructionDTRMode == HAL_XSPI_INSTRUCTION_DTR_ENABLE)) - { - MODIFY_REG((*ccr_reg), XSPI_CCR_DDTR, HAL_XSPI_DATA_DTR_ENABLE); - } - } - /* Configure the IR register with the instruction value */ - *ir_reg = pCmd->Instruction; - - /* Configure the AR register with the address value */ - hxspi->Instance->AR = pCmd->Address; - } - else - { - if (pCmd->DataMode != HAL_XSPI_DATA_NONE) - { - /* ---- Command with instruction and data ---- */ - - /* Configure the CCR register with all communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE | - XSPI_CCR_DMODE | XSPI_CCR_DDTR), - (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth | - pCmd->DataMode | pCmd->DataDTRMode)); - } - else - { - /* ---- Command with only instruction ---- */ - - /* Configure the CCR register with all communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE), - (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth)); - - /* The DHQC bit is linked with DDTR bit which should be activated */ - if ((hxspi->Init.DelayHoldQuarterCycle == HAL_XSPI_DHQC_ENABLE) && - (pCmd->InstructionDTRMode == HAL_XSPI_INSTRUCTION_DTR_ENABLE)) - { - MODIFY_REG((*ccr_reg), XSPI_CCR_DDTR, HAL_XSPI_DATA_DTR_ENABLE); - } - } - - /* Configure the IR register with the instruction value */ - *ir_reg = pCmd->Instruction; - - } - } - else - { - if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) - { - if (pCmd->DataMode != HAL_XSPI_DATA_NONE) - { - /* ---- Command with address and data ---- */ - - /* Configure the CCR register with all communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE | - XSPI_CCR_DMODE | XSPI_CCR_DDTR), - (pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth | - pCmd->DataMode | pCmd->DataDTRMode)); - } - else - { - /* ---- Command with only address ---- */ - - /* Configure the CCR register with all communication parameters */ - MODIFY_REG((*ccr_reg), (XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE), - (pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth)); - } - - /* Configure the AR register with the instruction value */ - hxspi->Instance->AR = pCmd->Address; - } - else - { - /* ---- Invalid command configuration (no instruction, no address) ---- */ - status = HAL_ERROR; - hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; - } - } - - return status; -} - -/** - * @brief Get the current IOM configuration for an XSPI instance. - * @param instance_nb : number of the instance - * @param pCfg : configuration of the IO Manager for the instance - * @retval HAL status - */ -static void XSPIM_GetConfig(uint8_t instance_nb, XSPIM_CfgTypeDef *const pCfg) -{ - uint32_t mux; - uint32_t mode; - - if (instance_nb == 1U) - { - if ((XSPIM->CR & XSPIM_CR_MODE) == 0U) - { - pCfg->IOPort = HAL_XSPIM_IOPORT_1; - } - else - { - pCfg->IOPort = HAL_XSPIM_IOPORT_2; - } - - if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_EN) != XSPIM_CR_CSSEL_OVR_EN) - { - pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_DISABLED; - } - else if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_O1) == XSPIM_CR_CSSEL_OVR_O1) - { - pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS2; - } - else - { - pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS1; - } - } - else - { - mux = (XSPIM->CR & XSPIM_CR_MUXEN); - mode = ((XSPIM->CR & XSPIM_CR_MODE) >> XSPIM_CR_MODE_Pos); - if (mux != mode) - { - pCfg->IOPort = HAL_XSPIM_IOPORT_1; - } - else - { - pCfg->IOPort = HAL_XSPIM_IOPORT_2; - } - if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_EN) != XSPIM_CR_CSSEL_OVR_EN) - { - pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_DISABLED; - } - else if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_O2) == XSPIM_CR_CSSEL_OVR_O2) - { - pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS2; - } - else - { - pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS1; - } - } -} -/** - @endcond - */ - -/** - * @} - */ - -#endif /* HAL_XSPI_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* XSPI || XSPI1 || XSPI2 */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_xspi.c + * @author MCD Application Team + * @brief XSPI HAL module driver. + This file provides firmware functions to manage the following + functionalities of the OctoSPI/HSPI interface (XSPI). + + Initialization and de-initialization functions + + Hyperbus configuration + + Indirect functional mode management + + Memory-mapped functional mode management + + Auto-polling functional mode management + + Interrupts and flags management + + DMA channel configuration for indirect functional mode + + Errors management and abort functionality + + IO manager configuration + + HIGH-SPEED INTERFACE configuration + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + *** Initialization *** + ====================== + [..] + As prerequisite, fill in the HAL_XSPI_MspInit() : + (+) Enable OctoSPI/HSPI clocks interface with __HAL_RCC_XSPI_CLK_ENABLE(). + (+) Reset OctoSPI/HSPI Peripheral with __HAL_RCC_XSPI_FORCE_RESET() and __HAL_RCC_XSPI_RELEASE_RESET(). + (+) Enable the clocks for the OctoSPI/HSPI GPIOS with __HAL_RCC_GPIOx_CLK_ENABLE(). + (+) Configure these OctoSPI/HSPI pins in alternate mode using HAL_GPIO_Init(). + (+) If interrupt or DMA mode is used, enable and configure OctoSPI/HSPI global + interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). + (+) If DMA mode is used, enable the clocks for the OctoSPI/HSPI DMA channel + with __HAL_RCC_DMAx_CLK_ENABLE(), configure DMA with HAL_DMA_Init(), + link it with OctoSPI/HSPI handle using __HAL_LINKDMA(), enable and configure + DMA channel global interrupt with HAL_NVIC_SetPriority() and HAL_NVIC_EnableIRQ(). + [..] + Configure the fifo threshold, the memory mode, the memory type, the + device size, the CS high time, the free running clock, the clock mode, + the wrap size, the clock prescaler, the sample shifting, the hold delay + and the CS boundary using the HAL_XSPI_Init() function. + [..] + When using Hyperbus, configure the RW recovery time, the access time, + the write latency and the latency mode using the HAL_XSPI_HyperbusCfg() + function. + + *** Indirect functional mode *** + ================================ + [..] + In regular mode, configure the command sequence using the HAL_XSPI_Command() + or HAL_XSPI_Command_IT() functions : + (+) Instruction phase : the mode used and if present the size, the instruction + opcode and the DTR mode. + (+) Address phase : the mode used and if present the size, the address + value and the DTR mode. + (+) Alternate-bytes phase : the mode used and if present the size, the + alternate bytes values and the DTR mode. + (+) Dummy-cycles phase : the number of dummy cycles (mode used is same as data phase). + (+) Data phase : the mode used and if present the number of bytes and the DTR mode. + (+) Data strobe (DQS) mode : the activation (or not) of this mode + (+) IO selection : to access external memory. + (+) Operation type : always common configuration. + [..] + In Hyperbus mode, configure the command sequence using the HAL_XSPI_HyperbusCmd() + function : + (+) Address space : indicate if the access will be done in register or memory + (+) Address size + (+) Number of data + (+) Data strobe (DQS) mode : the activation (or not) of this mode + [..] + If no data is required for the command (only for regular mode, not for + Hyperbus mode), it is sent directly to the memory : + (+) In polling mode, the output of the function is done when the transfer is complete. + (+) In interrupt mode, HAL_XSPI_CmdCpltCallback() will be called when the transfer is complete. + [..] + For the indirect write mode, use HAL_XSPI_Transmit(), HAL_XSPI_Transmit_DMA() or + HAL_XSPI_Transmit_IT() after the command configuration : + (+) In polling mode, the output of the function is done when the transfer is complete. + (+) In interrupt mode, HAL_XSPI_FifoThresholdCallback() will be called when the fifo threshold + is reached and HAL_XSPI_TxCpltCallback() will be called when the transfer is complete. + (+) In DMA mode, HAL_XSPI_TxHalfCpltCallback() will be called at the half transfer and + HAL_XSPI_TxCpltCallback() will be called when the transfer is complete. + [..] + For the indirect read mode, use HAL_XSPI_Receive(), HAL_XSPI_Receive_DMA() or + HAL_XSPI_Receive_IT() after the command configuration : + (+) In polling mode, the output of the function is done when the transfer is complete. + (+) In interrupt mode, HAL_XSPI_FifoThresholdCallback() will be called when the fifo threshold + is reached and HAL_XSPI_RxCpltCallback() will be called when the transfer is complete. + (+) In DMA mode, HAL_XSPI_RxHalfCpltCallback() will be called at the half transfer and + HAL_XSPI_RxCpltCallback() will be called when the transfer is complete. + + *** Auto-polling functional mode *** + ==================================== + [..] + Configure the command sequence by the same way than the indirect mode + [..] + Configure the auto-polling functional mode using the HAL_XSPI_AutoPolling() + or HAL_XSPI_AutoPolling_IT() functions : + (+) The size of the status bytes, the match value, the mask used, the match mode (OR/AND), + the polling interval and the automatic stop activation. + [..] + After the configuration : + (+) In polling mode, the output of the function is done when the status match is reached. The + automatic stop is activated to avoid an infinite loop. + (+) In interrupt mode, HAL_XSPI_StatusMatchCallback() will be called each time the status match is reached. + + *** Memory-mapped functional mode *** + ===================================== + [..] + Configure the command sequence by the same way than the indirect mode except + for the operation type in regular mode : + (+) Operation type equals to read configuration : the command configuration + applies to read access in memory-mapped mode + (+) Operation type equals to write configuration : the command configuration + applies to write access in memory-mapped mode + (+) Both read and write configuration should be performed before activating + memory-mapped mode + [..] + Configure the memory-mapped functional mode using the HAL_XSPI_MemoryMapped() + functions : + (+) The timeout activation and the timeout period. + [..] + After the configuration, the OctoSPI/HSPI will be used as soon as an access on the AHB is done on + the address range. HAL_XSPI_TimeOutCallback() will be called when the timeout expires. + + *** Errors management and abort functionality *** + ================================================= + [..] + HAL_XSPI_GetError() function gives the error raised during the last operation. + [..] + HAL_XSPI_Abort() and HAL_XSPI_AbortIT() functions aborts any on-going operation and + flushes the fifo : + (+) In polling mode, the output of the function is done when the transfer + complete bit is set and the busy bit cleared. + (+) In interrupt mode, HAL_XSPI_AbortCpltCallback() will be called when + the transfer complete bit is set. + + *** Control functions *** + ========================= + [..] + HAL_XSPI_GetState() function gives the current state of the HAL XSPI driver. + [..] + HAL_XSPI_SetTimeout() function configures the timeout value used in the driver. + [..] + HAL_XSPI_SetFifoThreshold() function configures the threshold on the Fifo of the OctoSPI/HSPI Peripheral. + [..] + HAL_XSPI_SetMemoryType() function configures the type of the external memory. + [..] + HAL_XSPI_SetDeviceSize() function configures the size of the external memory. + [..] + HAL_XSPI_SetClockPrescaler() function configures the clock prescaler of the OctoSPI/HSPI Peripheral. + [..] + HAL_XSPI_GetFifoThreshold() function gives the current of the Fifo's threshold + + *** IO manager configuration functions *** + ========================================== + [..] + HAL_XSPIM_Config() function configures the IO manager for the XSPI instance. + + *** High-speed interface and calibration functions *** + ========================================== + [..] + The purpose of High-speed interface is primary to shift data or data strobe by one quarter of octal + bus clock period, with a correct timing accuracy. DLL must be calibrated versus this clock period. + The calibration process is automatically enabled when one of the three conditions below is met: + (+) The XSPI exits Reset state. + (+) The Prescaler is set. + (+) The configuration of communication is set. + [..] + HAL_XSPI_GetDelayValue() function Get the delay values of the high-speed interface DLLs.. + [..] + HAL_XSPI_SetDelayValue() function Set the delay values of the high-speed interface DLLs.. + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_XSPI_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + [..] + Use function HAL_XSPI_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) FifoThresholdCallback : callback when the fifo threshold is reached. + (+) CmdCpltCallback : callback when a command without data is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxHalfCpltCallback : callback when half of the reception transfer is completed. + (+) TxHalfCpltCallback : callback when half of the transmission transfer is completed. + (+) StatusMatchCallback : callback when a status match occurs. + (+) TimeOutCallback : callback when the timeout perioed expires. + (+) MspInitCallback : XSPI MspInit. + (+) MspDeInitCallback : XSPI MspDeInit. + [..] + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + + [..] + Use function HAL_XSPI_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) ErrorCallback : callback when error occurs. + (+) AbortCpltCallback : callback when abort is completed. + (+) FifoThresholdCallback : callback when the fifo threshold is reached. + (+) CmdCpltCallback : callback when a command without data is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxHalfCpltCallback : callback when half of the reception transfer is completed. + (+) TxHalfCpltCallback : callback when half of the transmission transfer is completed. + (+) StatusMatchCallback : callback when a status match occurs. + (+) TimeOutCallback : callback when the timeout perioed expires. + (+) MspInitCallback : XSPI MspInit. + (+) MspDeInitCallback : XSPI MspDeInit. + [..] + This function) takes as parameters the HAL peripheral handle and the Callback ID. + + [..] + By default, after the HAL_XSPI_Init() and if the state is HAL_XSPI_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_XSPI_Init() + and HAL_XSPI_DeInit() only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_XSPI_Init() and HAL_XSPI_DeInit() + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + [..] + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_XSPI_RegisterCallback() before calling HAL_XSPI_DeInit() + or HAL_XSPI_Init() function. + + [..] + When The compilation define USE_HAL_XSPI_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +#if defined(XSPI) || defined(XSPI1) || defined(XSPI2) + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup XSPI XSPI + * @brief XSPI HAL module driver + * @{ + */ + +#ifdef HAL_XSPI_MODULE_ENABLED + +/** + @cond 0 + */ +/* Private typedef -----------------------------------------------------------*/ + +/* Private define ------------------------------------------------------------*/ +#define XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE ((uint32_t)0x00000000) /*!< Indirect write mode */ +#define XSPI_FUNCTIONAL_MODE_INDIRECT_READ ((uint32_t)XSPI_CR_FMODE_0) /*!< Indirect read mode */ +#define XSPI_FUNCTIONAL_MODE_AUTO_POLLING ((uint32_t)XSPI_CR_FMODE_1) /*!< Automatic polling mode */ +#define XSPI_FUNCTIONAL_MODE_MEMORY_MAPPED ((uint32_t)XSPI_CR_FMODE) /*!< Memory-mapped mode */ + +#define XSPI_CFG_STATE_MASK 0x00000004U +#define XSPI_BUSY_STATE_MASK 0x00000008U + +#define XSPI_NB_INSTANCE 2U +#define XSPI_IOM_NB_PORTS 2U +#define XSPI_IOM_PORT_MASK 0x1U + +/* Private macro -------------------------------------------------------------*/ +#define IS_XSPI_FUNCTIONAL_MODE(MODE) (((MODE) == XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE) || \ + ((MODE) == XSPI_FUNCTIONAL_MODE_INDIRECT_READ) || \ + ((MODE) == XSPI_FUNCTIONAL_MODE_AUTO_POLLING) || \ + ((MODE) == XSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)) + +/* Private variables ---------------------------------------------------------*/ + +/* Private function prototypes -----------------------------------------------*/ +static void XSPI_DMACplt(DMA_HandleTypeDef *hdma); +static void XSPI_DMAHalfCplt(DMA_HandleTypeDef *hdma); +static void XSPI_DMAError(DMA_HandleTypeDef *hdma); +static void XSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef XSPI_WaitFlagStateUntilTimeout(XSPI_HandleTypeDef *hxspi, uint32_t Flag, FlagStatus State, + uint32_t Tickstart, uint32_t Timeout); +static HAL_StatusTypeDef XSPI_ConfigCmd(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *const pCmd); +static void XSPIM_GetConfig(uint8_t instance_nb, XSPIM_CfgTypeDef *const pCfg); +/** + @endcond + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup XSPI_Exported_Functions XSPI Exported Functions + * @{ + */ + +/** @defgroup XSPI_Exported_Functions_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to : + (+) Initialize the XSPI. + (+) De-initialize the XSPI. + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the XSPI mode according to the specified parameters + * in the XSPI_InitTypeDef and initialize the associated handle. + * @param hxspi : XSPI handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Init(XSPI_HandleTypeDef *hxspi) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tickstart = HAL_GetTick(); + + /* Check the XSPI handle allocation */ + if (hxspi == NULL) + { + status = HAL_ERROR; + /* No error code can be set set as the handler is null */ + } + else + { + /* Check the parameters of the initialization structure */ + assert_param(IS_XSPI_MEMORY_MODE(hxspi->Init.MemoryMode)); + assert_param(IS_XSPI_MEMORY_TYPE(hxspi->Init.MemoryType)); + assert_param(IS_XSPI_MEMORY_SIZE(hxspi->Init.MemorySize)); + assert_param(IS_XSPI_CS_HIGH_TIME_CYCLE(hxspi->Init.ChipSelectHighTimeCycle)); + assert_param(IS_XSPI_FREE_RUN_CLK(hxspi->Init.FreeRunningClock)); + assert_param(IS_XSPI_CLOCK_MODE(hxspi->Init.ClockMode)); + assert_param(IS_XSPI_WRAP_SIZE(hxspi->Init.WrapSize)); + assert_param(IS_XSPI_CLK_PRESCALER(hxspi->Init.ClockPrescaler)); + assert_param(IS_XSPI_SAMPLE_SHIFTING(hxspi->Init.SampleShifting)); + assert_param(IS_XSPI_DHQC(hxspi->Init.DelayHoldQuarterCycle)); + assert_param(IS_XSPI_CS_BOUND(hxspi->Init.ChipSelectBoundary)); + assert_param(IS_XSPI_FIFO_THRESHOLD_BYTE(hxspi->Init.FifoThresholdByte)); + assert_param(IS_XSPI_MAXTRAN(hxspi->Init.MaxTran)); + assert_param(IS_XSPI_CSSEL(hxspi->Init.MemorySelect)); + /* Initialize error code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_NONE; + + /* Check if the state is the reset state */ + if (hxspi->State == HAL_XSPI_STATE_RESET) + { +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + /* Reset Callback pointers in HAL_XSPI_STATE_RESET only */ + hxspi->ErrorCallback = HAL_XSPI_ErrorCallback; + hxspi->AbortCpltCallback = HAL_XSPI_AbortCpltCallback; + hxspi->FifoThresholdCallback = HAL_XSPI_FifoThresholdCallback; + hxspi->CmdCpltCallback = HAL_XSPI_CmdCpltCallback; + hxspi->RxCpltCallback = HAL_XSPI_RxCpltCallback; + hxspi->TxCpltCallback = HAL_XSPI_TxCpltCallback; + hxspi->RxHalfCpltCallback = HAL_XSPI_RxHalfCpltCallback; + hxspi->TxHalfCpltCallback = HAL_XSPI_TxHalfCpltCallback; + hxspi->StatusMatchCallback = HAL_XSPI_StatusMatchCallback; + hxspi->TimeOutCallback = HAL_XSPI_TimeOutCallback; + + if (hxspi->MspInitCallback == NULL) + { + hxspi->MspInitCallback = HAL_XSPI_MspInit; + } + + /* Init the low level hardware */ + hxspi->MspInitCallback(hxspi); +#else + /* Initialization of the low level hardware */ + HAL_XSPI_MspInit(hxspi); +#endif /* defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + + /* Configure the default timeout for the XSPI memory access */ + (void)HAL_XSPI_SetTimeout(hxspi, HAL_XSPI_TIMEOUT_DEFAULT_VALUE); + + /* Configure memory type, device size, chip select high time, free running clock, clock mode */ + MODIFY_REG(hxspi->Instance->DCR1, + (XSPI_DCR1_MTYP | XSPI_DCR1_DEVSIZE | XSPI_DCR1_CSHT | XSPI_DCR1_FRCK | XSPI_DCR1_CKMODE), + (hxspi->Init.MemoryType | ((hxspi->Init.MemorySize) << XSPI_DCR1_DEVSIZE_Pos) | + ((hxspi->Init.ChipSelectHighTimeCycle - 1U) << XSPI_DCR1_CSHT_Pos) | hxspi->Init.ClockMode)); + + /* Configure wrap size */ + MODIFY_REG(hxspi->Instance->DCR2, XSPI_DCR2_WRAPSIZE, hxspi->Init.WrapSize); + + /* Configure chip select boundary */ + MODIFY_REG(hxspi->Instance->DCR3, XSPI_DCR3_CSBOUND, (hxspi->Init.ChipSelectBoundary << XSPI_DCR3_CSBOUND_Pos)); + + /* Configure maximum transfer */ + MODIFY_REG(hxspi->Instance->DCR3, XSPI_DCR3_MAXTRAN, \ + (hxspi->Init.MaxTran << XSPI_DCR3_MAXTRAN_Pos)); + + /* Configure refresh */ + hxspi->Instance->DCR4 = hxspi->Init.Refresh; + + /* Configure FIFO threshold */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FTHRES, ((hxspi->Init.FifoThresholdByte - 1U) << XSPI_CR_FTHRES_Pos)); + + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); + + if (status == HAL_OK) + { + /* Configure clock prescaler */ + MODIFY_REG(hxspi->Instance->DCR2, XSPI_DCR2_PRESCALER, + ((hxspi->Init.ClockPrescaler) << XSPI_DCR2_PRESCALER_Pos)); + + if (IS_XSPI_ALL_INSTANCE(hxspi->Instance)) + { + /* The configuration of clock prescaler trigger automatically a calibration process. + So it is necessary to wait the calibration is complete */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); + if (status != HAL_OK) + { + return status; + } + } + /* Configure Dual Memory mode and CS Selection */ + MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_DMM | XSPI_CR_CSSEL), + (hxspi->Init.MemoryMode | hxspi->Init.MemorySelect)); + + /* Configure sample shifting and delay hold quarter cycle */ + MODIFY_REG(hxspi->Instance->TCR, (XSPI_TCR_SSHIFT | XSPI_TCR_DHQC), + (hxspi->Init.SampleShifting | hxspi->Init.DelayHoldQuarterCycle)); + + /* Enable XSPI */ + HAL_XSPI_ENABLE(hxspi); + + /* Enable free running clock if needed : must be done after XSPI enable */ + if (hxspi->Init.FreeRunningClock == HAL_XSPI_FREERUNCLK_ENABLE) + { + SET_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK); + } + + /* Initialize the XSPI state */ + if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) + { + hxspi->State = HAL_XSPI_STATE_HYPERBUS_INIT; + } + else + { + hxspi->State = HAL_XSPI_STATE_READY; + } + } + } + } + return status; +} + +/** + * @brief Initialize the XSPI MSP. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_MspInit(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_XSPI_MspInit can be implemented in the user file + */ +} + +/** + * @brief De-Initialize the XSPI peripheral. + * @param hxspi : XSPI handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_DeInit(XSPI_HandleTypeDef *hxspi) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the XSPI handle allocation */ + if (hxspi == NULL) + { + status = HAL_ERROR; + /* No error code can be set as the handler is null */ + } + else + { + /* Disable XSPI */ + HAL_XSPI_DISABLE(hxspi); + + /* Disable free running clock if needed : must be done after XSPI disable */ + CLEAR_BIT(hxspi->Instance->DCR1, XSPI_DCR1_FRCK); + +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + if (hxspi->MspDeInitCallback == NULL) + { + hxspi->MspDeInitCallback = HAL_XSPI_MspDeInit; + } + + /* De-initialize the low level hardware */ + hxspi->MspDeInitCallback(hxspi); +#else + /* De-initialize the low-level hardware */ + HAL_XSPI_MspDeInit(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + + /* Reset the driver state */ + hxspi->State = HAL_XSPI_STATE_RESET; + } + + return status; +} + +/** + * @brief DeInitialize the XSPI MSP. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_MspDeInit(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_XSPI_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup XSPI_Exported_Functions_Group2 Input and Output operation functions + * @brief XSPI Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to : + (+) Handle the interrupts. + (+) Handle the command sequence (regular and Hyperbus). + (+) Handle the Hyperbus configuration. + (+) Transmit data in blocking, interrupt or DMA mode. + (+) Receive data in blocking, interrupt or DMA mode. + (+) Manage the auto-polling functional mode. + (+) Manage the memory-mapped functional mode. + +@endverbatim + * @{ + */ + +/** + * @brief Handle XSPI interrupt request. + * @param hxspi : XSPI handle + * @retval None + */ +void HAL_XSPI_IRQHandler(XSPI_HandleTypeDef *hxspi) +{ + __IO uint32_t *data_reg = &hxspi->Instance->DR; + uint32_t flag = hxspi->Instance->SR; + uint32_t itsource = hxspi->Instance->CR; + uint32_t currentstate = hxspi->State; + + /* XSPI fifo threshold interrupt occurred -------------------------------*/ + if (((flag & HAL_XSPI_FLAG_FT) != 0U) && ((itsource & HAL_XSPI_IT_FT) != 0U)) + { + if (currentstate == HAL_XSPI_STATE_BUSY_TX) + { + /* Write a data in the fifo */ + *((__IO uint8_t *)data_reg) = *hxspi->pBuffPtr; + hxspi->pBuffPtr++; + hxspi->XferCount--; + } + else if (currentstate == HAL_XSPI_STATE_BUSY_RX) + { + /* Read a data from the fifo */ + *hxspi->pBuffPtr = *((__IO uint8_t *)data_reg); + hxspi->pBuffPtr++; + hxspi->XferCount--; + } + else + { + /* Nothing to do */ + } + + if (hxspi->XferCount == 0U) + { + /* All data have been received or transmitted for the transfer */ + /* Disable fifo threshold interrupt */ + HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_FT); + } + + /* Fifo threshold callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->FifoThresholdCallback(hxspi); +#else + HAL_XSPI_FifoThresholdCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + /* XSPI transfer complete interrupt occurred ----------------------------*/ + else if (((flag & HAL_XSPI_FLAG_TC) != 0U) && ((itsource & HAL_XSPI_IT_TC) != 0U)) + { + if (currentstate == HAL_XSPI_STATE_BUSY_RX) + { + if ((hxspi->XferCount > 0U) && ((flag & XSPI_SR_FLEVEL) != 0U)) + { + /* Read the last data received in the fifo */ + *hxspi->pBuffPtr = *((__IO uint8_t *)data_reg); + hxspi->pBuffPtr++; + hxspi->XferCount--; + } + else if (hxspi->XferCount == 0U) + { + /* Clear flag */ + hxspi->Instance->FCR = HAL_XSPI_FLAG_TC; + + /* Disable the interrupts */ + HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); + + hxspi->State = HAL_XSPI_STATE_READY; + + /* RX complete callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->RxCpltCallback(hxspi); +#else + HAL_XSPI_RxCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + else + { + /* Nothing to do */ + } + } + else + { + /* Clear flag */ + hxspi->Instance->FCR = HAL_XSPI_FLAG_TC; + + /* Disable the interrupts */ + HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); + + hxspi->State = HAL_XSPI_STATE_READY; + + if (currentstate == HAL_XSPI_STATE_BUSY_TX) + { + /* TX complete callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->TxCpltCallback(hxspi); +#else + HAL_XSPI_TxCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + else if (currentstate == HAL_XSPI_STATE_BUSY_CMD) + { + /* Command complete callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->CmdCpltCallback(hxspi); +#else + HAL_XSPI_CmdCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + else if (currentstate == HAL_XSPI_STATE_ABORT) + { + if (hxspi->ErrorCode == HAL_XSPI_ERROR_NONE) + { + /* Abort called by the user */ + /* Abort complete callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->AbortCpltCallback(hxspi); +#else + HAL_XSPI_AbortCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + else + { + /* Abort due to an error (eg : DMA error) */ + /* Error callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->ErrorCallback(hxspi); +#else + HAL_XSPI_ErrorCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + } + else + { + /* Nothing to do */ + } + } + } + /* XSPI status match interrupt occurred ---------------------------------*/ + else if (((flag & HAL_XSPI_FLAG_SM) != 0U) && ((itsource & HAL_XSPI_IT_SM) != 0U)) + { + /* Clear flag */ + hxspi->Instance->FCR = HAL_XSPI_FLAG_SM; + + /* Check if automatic poll mode stop is activated */ + if ((hxspi->Instance->CR & XSPI_CR_APMS) != 0U) + { + /* Disable the interrupts */ + HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_SM | HAL_XSPI_IT_TE); + + hxspi->State = HAL_XSPI_STATE_READY; + } + + /* Status match callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->StatusMatchCallback(hxspi); +#else + HAL_XSPI_StatusMatchCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + /* XSPI transfer error interrupt occurred -------------------------------*/ + else if (((flag & HAL_XSPI_FLAG_TE) != 0U) && ((itsource & HAL_XSPI_IT_TE) != 0U)) + { + /* Clear flag */ + hxspi->Instance->FCR = HAL_XSPI_FLAG_TE; + + /* Disable all interrupts */ + HAL_XSPI_DISABLE_IT(hxspi, (HAL_XSPI_IT_TO | HAL_XSPI_IT_SM | HAL_XSPI_IT_FT | HAL_XSPI_IT_TC | HAL_XSPI_IT_TE)); + + /* Set error code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_TRANSFER; + + /* Check if the DMA is enabled */ + if ((hxspi->Instance->CR & XSPI_CR_DMAEN) != 0U) + { + /* Disable the DMA transfer on the XSPI side */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + + /* Disable the DMA transmit on the DMA side */ + hxspi->hdmatx->XferAbortCallback = XSPI_DMAAbortCplt; + if (HAL_DMA_Abort_IT(hxspi->hdmatx) != HAL_OK) + { + hxspi->State = HAL_XSPI_STATE_READY; + + /* Error callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->ErrorCallback(hxspi); +#else + HAL_XSPI_ErrorCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + + /* Disable the DMA receive on the DMA side */ + hxspi->hdmarx->XferAbortCallback = XSPI_DMAAbortCplt; + if (HAL_DMA_Abort_IT(hxspi->hdmarx) != HAL_OK) + { + hxspi->State = HAL_XSPI_STATE_READY; + + /* Error callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->ErrorCallback(hxspi); +#else + HAL_XSPI_ErrorCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + } + else + { + hxspi->State = HAL_XSPI_STATE_READY; + + /* Error callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->ErrorCallback(hxspi); +#else + HAL_XSPI_ErrorCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + } + /* XSPI timeout interrupt occurred --------------------------------------*/ + else if (((flag & HAL_XSPI_FLAG_TO) != 0U) && ((itsource & HAL_XSPI_IT_TO) != 0U)) + { + /* Clear flag */ + hxspi->Instance->FCR = HAL_XSPI_FLAG_TO; + + /* Timeout callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->TimeOutCallback(hxspi); +#else + HAL_XSPI_TimeOutCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + else + { + /* Nothing to do */ + } +} + +/** + * @brief Set the command configuration. + * @param hxspi : XSPI handle + * @param pCmd : structure that contains the command configuration information + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Command(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *const pCmd, uint32_t Timeout) +{ + HAL_StatusTypeDef status; + uint32_t state; + uint32_t tickstart = HAL_GetTick(); + + /* Check the parameters of the command structure */ + assert_param(IS_XSPI_OPERATION_TYPE(pCmd->OperationType)); + if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM) + { + assert_param(IS_XSPI_IO_SELECT(pCmd->IOSelect)); + } + + assert_param(IS_XSPI_INSTRUCTION_MODE(pCmd->InstructionMode)); + if (pCmd->InstructionMode != HAL_XSPI_INSTRUCTION_NONE) + { + assert_param(IS_XSPI_INSTRUCTION_WIDTH(pCmd->InstructionWidth)); + assert_param(IS_XSPI_INSTRUCTION_DTR_MODE(pCmd->InstructionDTRMode)); + } + + assert_param(IS_XSPI_ADDRESS_MODE(pCmd->AddressMode)); + if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) + { + assert_param(IS_XSPI_ADDRESS_WIDTH(pCmd->AddressWidth)); + assert_param(IS_XSPI_ADDRESS_DTR_MODE(pCmd->AddressDTRMode)); + } + + assert_param(IS_XSPI_ALT_BYTES_MODE(pCmd->AlternateBytesMode)); + if (pCmd->AlternateBytesMode != HAL_XSPI_ALT_BYTES_NONE) + { + assert_param(IS_XSPI_ALT_BYTES_WIDTH(pCmd->AlternateBytesWidth)); + assert_param(IS_XSPI_ALT_BYTES_DTR_MODE(pCmd->AlternateBytesDTRMode)); + } + + assert_param(IS_XSPI_DATA_MODE(hxspi->Init.MemoryType, pCmd->DataMode)); + + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + if (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) + { + assert_param(IS_XSPI_DATA_LENGTH(pCmd->DataLength)); + } + assert_param(IS_XSPI_DATA_DTR_MODE(pCmd->DataDTRMode)); + assert_param(IS_XSPI_DUMMY_CYCLES(pCmd->DummyCycles)); + } + + assert_param(IS_XSPI_DQS_MODE(pCmd->DQSMode)); + + /* Check the state of the driver */ + state = hxspi->State; + if (((state == HAL_XSPI_STATE_READY) && (hxspi->Init.MemoryType != HAL_XSPI_MEMTYPE_HYPERBUS)) || + ((state == HAL_XSPI_STATE_READ_CMD_CFG) && ((pCmd->OperationType == HAL_XSPI_OPTYPE_WRITE_CFG) || + (pCmd->OperationType == HAL_XSPI_OPTYPE_WRAP_CFG))) || + ((state == HAL_XSPI_STATE_WRITE_CMD_CFG) && + ((pCmd->OperationType == HAL_XSPI_OPTYPE_READ_CFG) || + (pCmd->OperationType == HAL_XSPI_OPTYPE_WRAP_CFG)))) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Initialize error code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_NONE; + + /* Configure the registers */ + status = XSPI_ConfigCmd(hxspi, pCmd); + + if (status == HAL_OK) + { + if (pCmd->DataMode == HAL_XSPI_DATA_NONE) + { + /* When there is no data phase, the transfer start as soon as the configuration is done + so wait until TC flag is set to go back in idle state */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, Timeout); + + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); + } + else + { + /* Update the state */ + if (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) + { + hxspi->State = HAL_XSPI_STATE_CMD_CFG; + } + else if (pCmd->OperationType == HAL_XSPI_OPTYPE_READ_CFG) + { + if (hxspi->State == HAL_XSPI_STATE_WRITE_CMD_CFG) + { + hxspi->State = HAL_XSPI_STATE_CMD_CFG; + } + else + { + hxspi->State = HAL_XSPI_STATE_READ_CMD_CFG; + } + } + else if (pCmd->OperationType == HAL_XSPI_OPTYPE_WRITE_CFG) + { + if (hxspi->State == HAL_XSPI_STATE_READ_CMD_CFG) + { + hxspi->State = HAL_XSPI_STATE_CMD_CFG; + } + else + { + hxspi->State = HAL_XSPI_STATE_WRITE_CMD_CFG; + } + } + else + { + /* Wrap configuration, no state change */ + } + } + } + } + else + { + status = HAL_BUSY; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Set the command configuration in interrupt mode. + * @param hxspi : XSPI handle + * @param pCmd : structure that contains the command configuration information + * @note This function is used only in Indirect Read or Write Modes + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Command_IT(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *const pCmd) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + + /* Check the parameters of the command structure */ + assert_param(IS_XSPI_OPERATION_TYPE(pCmd->OperationType)); + + if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM) + { + assert_param(IS_XSPI_IO_SELECT(pCmd->IOSelect)); + } + + assert_param(IS_XSPI_INSTRUCTION_MODE(pCmd->InstructionMode)); + if (pCmd->InstructionMode != HAL_XSPI_INSTRUCTION_NONE) + { + assert_param(IS_XSPI_INSTRUCTION_WIDTH(pCmd->InstructionWidth)); + assert_param(IS_XSPI_INSTRUCTION_DTR_MODE(pCmd->InstructionDTRMode)); + } + + assert_param(IS_XSPI_ADDRESS_MODE(pCmd->AddressMode)); + if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) + { + assert_param(IS_XSPI_ADDRESS_WIDTH(pCmd->AddressWidth)); + assert_param(IS_XSPI_ADDRESS_DTR_MODE(pCmd->AddressDTRMode)); + } + + assert_param(IS_XSPI_ALT_BYTES_MODE(pCmd->AlternateBytesMode)); + if (pCmd->AlternateBytesMode != HAL_XSPI_ALT_BYTES_NONE) + { + assert_param(IS_XSPI_ALT_BYTES_WIDTH(pCmd->AlternateBytesWidth)); + assert_param(IS_XSPI_ALT_BYTES_DTR_MODE(pCmd->AlternateBytesDTRMode)); + } + + assert_param(IS_XSPI_DATA_MODE(hxspi->Init.MemoryType, pCmd->DataMode)); + + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + assert_param(IS_XSPI_DATA_LENGTH(pCmd->DataLength)); + assert_param(IS_XSPI_DATA_DTR_MODE(pCmd->DataDTRMode)); + assert_param(IS_XSPI_DUMMY_CYCLES(pCmd->DummyCycles)); + } + + assert_param(IS_XSPI_DQS_MODE(pCmd->DQSMode)); + + /* Check the state of the driver */ + if ((hxspi->State == HAL_XSPI_STATE_READY) && (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) && + (pCmd->DataMode == HAL_XSPI_DATA_NONE) && (hxspi->Init.MemoryType != HAL_XSPI_MEMTYPE_HYPERBUS)) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); + + if (status == HAL_OK) + { + /* Initialize error code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_NONE; + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); + + /* Configure the registers */ + status = XSPI_ConfigCmd(hxspi, pCmd); + + if (status == HAL_OK) + { + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_BUSY_CMD; + + /* Enable the transfer complete and transfer error interrupts */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_TE); + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Configure the Hyperbus parameters. + * @param hxspi : XSPI handle + * @param pCfg : Pointer to Structure containing the Hyperbus configuration + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_HyperbusCfg(XSPI_HandleTypeDef *hxspi, XSPI_HyperbusCfgTypeDef *const pCfg, + uint32_t Timeout) +{ + HAL_StatusTypeDef status; + uint32_t state; + uint32_t tickstart = HAL_GetTick(); + + /* Check the parameters of the hyperbus configuration structure */ + assert_param(IS_XSPI_RW_RECOVERY_TIME_CYCLE(pCfg->RWRecoveryTimeCycle)); + assert_param(IS_XSPI_ACCESS_TIME_CYCLE(pCfg->AccessTimeCycle)); + assert_param(IS_XSPI_WRITE_ZERO_LATENCY(pCfg->WriteZeroLatency)); + assert_param(IS_XSPI_LATENCY_MODE(pCfg->LatencyMode)); + + /* Check the state of the driver */ + state = hxspi->State; + if ((state == HAL_XSPI_STATE_HYPERBUS_INIT) || (state == HAL_XSPI_STATE_READY)) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Configure Hyperbus configuration Latency register */ + WRITE_REG(hxspi->Instance->HLCR, ((pCfg->RWRecoveryTimeCycle << XSPI_HLCR_TRWR_Pos) | + (pCfg->AccessTimeCycle << XSPI_HLCR_TACC_Pos) | + pCfg->WriteZeroLatency | pCfg->LatencyMode)); + + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_READY; + } + else + { + status = HAL_BUSY; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Set the Hyperbus command configuration. + * @param hxspi : XSPI handle + * @param pCmd : Structure containing the Hyperbus command + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_HyperbusCmd(XSPI_HandleTypeDef *hxspi, XSPI_HyperbusCmdTypeDef *const pCmd, + uint32_t Timeout) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + + /* Check the parameters of the hyperbus command structure */ + assert_param(IS_XSPI_ADDRESS_SPACE(pCmd->AddressSpace)); + assert_param(IS_XSPI_ADDRESS_WIDTH(pCmd->AddressWidth)); + assert_param(IS_XSPI_DATA_LENGTH(pCmd->DataLength)); + assert_param(IS_XSPI_DQS_MODE(pCmd->DQSMode)); + assert_param(IS_XSPI_DATA_MODE(hxspi->Init.MemoryType, pCmd->DataMode)); + + /* Check the state of the driver */ + if ((hxspi->State == HAL_XSPI_STATE_READY) && (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS)) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Re-initialize the value of the functional mode */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, 0U); + + /* Configure the address space in the DCR1 register */ + MODIFY_REG(hxspi->Instance->DCR1, XSPI_DCR1_MTYP_0, pCmd->AddressSpace); + + /* Configure the CCR and WCCR registers with the address size and the following configuration : + - DQS signal enabled (used as RWDS) + - DTR mode enabled on address and data */ + /* - address and data on 8 or 16 lines */ + WRITE_REG(hxspi->Instance->CCR, (pCmd->DQSMode | XSPI_CCR_DDTR | pCmd->DataMode | + pCmd->AddressWidth | XSPI_CCR_ADDTR | XSPI_CCR_ADMODE_2)); + WRITE_REG(hxspi->Instance->WCCR, (pCmd->DQSMode | XSPI_WCCR_DDTR | pCmd->DataMode | + pCmd->AddressWidth | XSPI_WCCR_ADDTR | XSPI_WCCR_ADMODE_2)); + + /* Configure the DLR register with the number of data */ + WRITE_REG(hxspi->Instance->DLR, (pCmd->DataLength - 1U)); + + /* Configure the AR register with the address value */ + WRITE_REG(hxspi->Instance->AR, pCmd->Address); + + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_CMD_CFG; + } + else + { + status = HAL_BUSY; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Transmit an amount of data in blocking mode. + * @param hxspi : XSPI handle + * @param pData : pointer to data buffer + * @param Timeout : Timeout duration + * @note This function is used only in Indirect Write Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Transmit(XSPI_HandleTypeDef *hxspi, const uint8_t *pData, uint32_t Timeout) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + __IO uint32_t *data_reg = &hxspi->Instance->DR; + + /* Check the data pointer allocation */ + if (pData == NULL) + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + else + { + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + /* Configure counters and size */ + hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; + hxspi->XferSize = hxspi->XferCount; + hxspi->pBuffPtr = (uint8_t *)pData; + + /* Configure CR register with functional mode as indirect write */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE); + + do + { + /* Wait till fifo threshold flag is set to send data */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_FT, SET, tickstart, Timeout); + + if (status != HAL_OK) + { + break; + } + + *((__IO uint8_t *)data_reg) = *hxspi->pBuffPtr; + hxspi->pBuffPtr++; + hxspi->XferCount--; + } while (hxspi->XferCount > 0U); + + if (status == HAL_OK) + { + /* Wait till transfer complete flag is set to go back in idle state */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Clear transfer complete flag */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); + + hxspi->State = HAL_XSPI_STATE_READY; + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + + return status; +} + +/** + * @brief Receive an amount of data in blocking mode. + * @param hxspi : XSPI handle + * @param pData : pointer to data buffer + * @param Timeout : Timeout duration + * @note This function is used only in Indirect Read Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Receive(XSPI_HandleTypeDef *hxspi, uint8_t *const pData, uint32_t Timeout) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + __IO uint32_t *data_reg = &hxspi->Instance->DR; + uint32_t addr_reg = hxspi->Instance->AR; + uint32_t ir_reg = hxspi->Instance->IR; + + /* Check the data pointer allocation */ + if (pData == NULL) + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + else + { + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + /* Configure counters and size */ + hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; + hxspi->XferSize = hxspi->XferCount; + hxspi->pBuffPtr = pData; + + /* Configure CR register with functional mode as indirect read */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_READ); + + /* Trig the transfer by re-writing address or instruction register */ + if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + WRITE_REG(hxspi->Instance->IR, ir_reg); + } + } + + do + { + /* Wait till fifo threshold or transfer complete flags are set to read received data */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, (HAL_XSPI_FLAG_FT | HAL_XSPI_FLAG_TC), SET, tickstart, Timeout); + + if (status != HAL_OK) + { + break; + } + + *hxspi->pBuffPtr = *((__IO uint8_t *)data_reg); + hxspi->pBuffPtr++; + hxspi->XferCount--; + } while (hxspi->XferCount > 0U); + + if (status == HAL_OK) + { + /* Wait till transfer complete flag is set to go back in idle state */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Clear transfer complete flag */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); + + hxspi->State = HAL_XSPI_STATE_READY; + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + + return status; +} + +/** + * @brief Send an amount of data in non-blocking mode with interrupt. + * @param hxspi : XSPI handle + * @param pData : pointer to data buffer + * @note This function is used only in Indirect Write Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Transmit_IT(XSPI_HandleTypeDef *hxspi, const uint8_t *pData) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the data pointer allocation */ + if (pData == NULL) + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + else + { + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + /* Configure counters and size */ + hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; + hxspi->XferSize = hxspi->XferCount; + hxspi->pBuffPtr = (uint8_t *)pData; + + /* Configure CR register with functional mode as indirect write */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE); + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); + + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_BUSY_TX; + + /* Enable the transfer complete, fifo threshold and transfer error interrupts */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + + return status; +} + +/** + * @brief Receive an amount of data in non-blocking mode with interrupt. + * @param hxspi : XSPI handle + * @param pData : pointer to data buffer + * @note This function is used only in Indirect Read Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Receive_IT(XSPI_HandleTypeDef *hxspi, uint8_t *const pData) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t addr_reg = hxspi->Instance->AR; + uint32_t ir_reg = hxspi->Instance->IR; + + /* Check the data pointer allocation */ + if (pData == NULL) + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + else + { + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + /* Configure counters and size */ + hxspi->XferCount = READ_REG(hxspi->Instance->DLR) + 1U; + hxspi->XferSize = hxspi->XferCount; + hxspi->pBuffPtr = pData; + + /* Configure CR register with functional mode as indirect read */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_READ); + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); + + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_BUSY_RX; + + /* Enable the transfer complete, fifo threshold and transfer error interrupts */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); + + /* Trig the transfer by re-writing address or instruction register */ + if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + WRITE_REG(hxspi->Instance->IR, ir_reg); + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + + return status; +} + +/** + * @brief Send an amount of data in non-blocking mode with DMA. + * @param hxspi : XSPI handle + * @param pData : pointer to data buffer + * @note This function is used only in Indirect Write Mode + * @note If DMA peripheral access is configured as halfword, the number + * of data and the fifo threshold should be aligned on halfword + * @note If DMA peripheral access is configured as word, the number + * of data and the fifo threshold should be aligned on word + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Transmit_DMA(XSPI_HandleTypeDef *hxspi, const uint8_t *pData) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t data_size = hxspi->Instance->DLR + 1U; + DMA_QListTypeDef *p_queue = {NULL}; + uint32_t data_width = DMA_DEST_DATAWIDTH_BYTE; + + /* Check the data pointer allocation */ + if (pData == NULL) + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + else + { + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + if ((hxspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + p_queue = hxspi->hdmatx->LinkedListQueue; + if ((p_queue != NULL) && (p_queue->Head != NULL)) + { + data_width = p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + } + else + { + /* Set Error Code function status */ + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + + /* Return function status */ + status = HAL_ERROR; + } + } + else + { + data_width = hxspi->hdmatx->Init.DestDataWidth; + } + /* Configure counters and size */ + if (data_width == DMA_DEST_DATAWIDTH_BYTE) + { + hxspi->XferCount = data_size; + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + if (((data_size % 2U) != 0U) || ((hxspi->Init.FifoThresholdByte % 2U) != 0U)) + { + /* The number of data or the fifo threshold is not aligned on halfword + => no transfer possible with DMA peripheral access configured as halfword */ + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + hxspi->XferCount = data_size; + } + } + else if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + if (((data_size % 4U) != 0U) || ((hxspi->Init.FifoThresholdByte % 4U) != 0U)) + { + /* The number of data or the fifo threshold is not aligned on word + => no transfer possible with DMA peripheral access configured as word */ + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + hxspi->XferCount = data_size; + } + } + else + { + /* Nothing to do */ + } + + if (status == HAL_OK) + { + hxspi->XferSize = hxspi->XferCount; + hxspi->pBuffPtr = (uint8_t *)pData; + + /* Configure CR register with functional mode as indirect write */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_WRITE); + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); + + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_BUSY_TX; + + /* Set the DMA transfer complete callback */ + hxspi->hdmatx->XferCpltCallback = XSPI_DMACplt; + + /* Set the DMA Half transfer complete callback */ + hxspi->hdmatx->XferHalfCpltCallback = XSPI_DMAHalfCplt; + + /* Set the DMA error callback */ + hxspi->hdmatx->XferErrorCallback = XSPI_DMAError; + + /* Clear the DMA abort callback */ + hxspi->hdmatx->XferAbortCallback = NULL; + + /* Enable the transmit DMA Channel */ + if ((hxspi->hdmatx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hxspi->hdmatx->LinkedListQueue != NULL) + { + /* Enable the DMA channel */ + MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET], \ + (DMA_CTR1_SINC | DMA_CTR1_DINC), (DMA_SINC_INCREMENTED | DMA_DINC_FIXED)); + MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET], \ + DMA_CTR2_DREQ, DMA_MEMORY_TO_PERIPH); + /* Set DMA data size*/ + p_queue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hxspi->XferSize; + /* Set DMA source address */ + p_queue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)pData; + /* Set DMA destination address */ + p_queue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)&hxspi->Instance->DR; + + status = HAL_DMAEx_List_Start_IT(hxspi->hdmatx); + } + else + { + /* Set Error Code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + + hxspi->State = HAL_XSPI_STATE_READY; + + /* Return function status */ + status = HAL_ERROR; + } + } + else + { + if ((hxspi->hdmatx->Init.Direction == DMA_MEMORY_TO_PERIPH) && + (hxspi->hdmatx->Init.SrcInc == DMA_SINC_INCREMENTED) && (hxspi->hdmatx->Init.DestInc == DMA_DINC_FIXED)) + { + status = HAL_DMA_Start_IT(hxspi->hdmatx, (uint32_t)pData, (uint32_t)&hxspi->Instance->DR, hxspi->XferSize); + } + else + { + /* no transmit possible with DMA peripheral, invalid configuration */ + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + } + if (status == HAL_OK) + { + /* Enable the transfer error interrupt */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TE); + + /* Enable the DMA transfer by setting the DMAEN bit */ + SET_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + hxspi->State = HAL_XSPI_STATE_READY; + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + + return status; +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA. + * @param hxspi : XSPI handle + * @param pData : pointer to data buffer. + * @note This function is used only in Indirect Read Mode + * @note If DMA peripheral access is configured as halfword, the number + * of data and the fifo threshold should be aligned on halfword + * @note If DMA peripheral access is configured as word, the number + * of data and the fifo threshold should be aligned on word + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Receive_DMA(XSPI_HandleTypeDef *hxspi, uint8_t *const pData) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t data_size = hxspi->Instance->DLR + 1U; + uint32_t addr_reg = hxspi->Instance->AR; + uint32_t ir_reg = hxspi->Instance->IR; + DMA_QListTypeDef *p_queue = {NULL}; + uint32_t data_width = DMA_DEST_DATAWIDTH_BYTE; + + /* Check the data pointer allocation */ + if (pData == NULL) + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + else + { + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + if ((hxspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + p_queue = hxspi->hdmarx->LinkedListQueue; + if ((p_queue != NULL) && (p_queue->Head != NULL)) + { + data_width = p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET] & DMA_CTR1_DDW_LOG2; + } + else + { + /* Set Error Code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + + /* Return function status */ + status = HAL_ERROR; + } + } + else + { + data_width = hxspi->hdmarx->Init.DestDataWidth; + } + + /* Configure counters and size */ + if (data_width == DMA_DEST_DATAWIDTH_BYTE) + { + hxspi->XferCount = data_size; + } + else if (data_width == DMA_DEST_DATAWIDTH_HALFWORD) + { + if (((data_size % 2U) != 0U) || ((hxspi->Init.FifoThresholdByte % 2U) != 0U)) + { + /* The number of data or the fifo threshold is not aligned on halfword + => no transfer possible with DMA peripheral access configured as halfword */ + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + hxspi->XferCount = data_size; + } + } + else if (data_width == DMA_DEST_DATAWIDTH_WORD) + { + if (((data_size % 4U) != 0U) || ((hxspi->Init.FifoThresholdByte % 4U) != 0U)) + { + /* The number of data or the fifo threshold is not aligned on word + => no transfer possible with DMA peripheral access configured as word */ + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + else + { + hxspi->XferCount = data_size; + } + } + else + { + /* Nothing to do */ + } + + if (status == HAL_OK) + { + hxspi->XferSize = hxspi->XferCount; + hxspi->pBuffPtr = pData; + + /* Configure CR register with functional mode as indirect read */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, XSPI_FUNCTIONAL_MODE_INDIRECT_READ); + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_TC); + + /* Update the state */ + hxspi->State = HAL_XSPI_STATE_BUSY_RX; + + /* Set the DMA transfer complete callback */ + hxspi->hdmarx->XferCpltCallback = XSPI_DMACplt; + + /* Set the DMA Half transfer complete callback */ + hxspi->hdmarx->XferHalfCpltCallback = XSPI_DMAHalfCplt; + + /* Set the DMA error callback */ + hxspi->hdmarx->XferErrorCallback = XSPI_DMAError; + + /* Clear the DMA abort callback */ + hxspi->hdmarx->XferAbortCallback = NULL; + + /* Enable the receive DMA Channel */ + if ((hxspi->hdmarx->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST) + { + if (hxspi->hdmarx->LinkedListQueue != NULL) + { + /* Enable the DMA channel */ + MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR1_DEFAULT_OFFSET], \ + (DMA_CTR1_SINC | DMA_CTR1_DINC), (DMA_SINC_FIXED | DMA_DINC_INCREMENTED)); + MODIFY_REG(p_queue->Head->LinkRegisters[NODE_CTR2_DEFAULT_OFFSET], \ + DMA_CTR2_DREQ, DMA_PERIPH_TO_MEMORY); + /* Set DMA data size */ + p_queue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = hxspi->XferSize; + /* Set DMA source address */ + p_queue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = (uint32_t)&hxspi->Instance->DR; + /* Set DMA destination address */ + p_queue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData; + + status = HAL_DMAEx_List_Start_IT(hxspi->hdmarx); + } + else + { + /* Set Error Code */ + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + + hxspi->State = HAL_XSPI_STATE_READY; + + /* Return function status */ + status = HAL_ERROR; + } + } + else + { + if ((hxspi->hdmarx->Init.Direction == DMA_PERIPH_TO_MEMORY) && (hxspi->hdmarx->Init.SrcInc == DMA_SINC_FIXED) + && (hxspi->hdmarx->Init.DestInc == DMA_DINC_INCREMENTED)) + { + status = HAL_DMA_Start_IT(hxspi->hdmarx, (uint32_t)&hxspi->Instance->DR, (uint32_t)pData, hxspi->XferSize); + } + else + { + /* no receive possible with DMA peripheral, invalid configuration */ + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + status = HAL_ERROR; + } + } + if (status == HAL_OK) + { + /* Enable the transfer error interrupt */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TE); + + /* Trig the transfer by re-writing address or instruction register */ + if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + WRITE_REG(hxspi->Instance->IR, ir_reg); + } + } + + /* Enable the DMA transfer by setting the DMAEN bit */ + SET_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + hxspi->State = HAL_XSPI_STATE_READY; + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + + return status; +} + +/** + * @brief Configure the XSPI Automatic Polling Mode in blocking mode. + * @param hxspi : XSPI handle + * @param pCfg : Pointer to structure that contains the polling configuration information. + * @param Timeout : Timeout duration + * @note This function is used only in Automatic Polling Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_AutoPolling(XSPI_HandleTypeDef *hxspi, XSPI_AutoPollingTypeDef *const pCfg, + uint32_t Timeout) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + uint32_t addr_reg = hxspi->Instance->AR; + uint32_t ir_reg = hxspi->Instance->IR; +#ifdef USE_FULL_ASSERT + uint32_t dlr_reg = hxspi->Instance->DLR; +#endif /* USE_FULL_ASSERT */ + + /* Check the parameters of the autopolling configuration structure */ + assert_param(IS_XSPI_MATCH_MODE(pCfg->MatchMode)); + assert_param(IS_XSPI_AUTOMATIC_STOP(pCfg->AutomaticStop)); + assert_param(IS_XSPI_INTERVAL(pCfg->IntervalTime)); + assert_param(IS_XSPI_STATUS_BYTES_SIZE(dlr_reg + 1U)); + + /* Check the state */ + if ((hxspi->State == HAL_XSPI_STATE_CMD_CFG) && (pCfg->AutomaticStop == HAL_XSPI_AUTOMATIC_STOP_ENABLE)) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Configure registers */ + WRITE_REG(hxspi->Instance->PSMAR, pCfg->MatchValue); + WRITE_REG(hxspi->Instance->PSMKR, pCfg->MatchMask); + WRITE_REG(hxspi->Instance->PIR, pCfg->IntervalTime); + MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_PMM | XSPI_CR_APMS | XSPI_CR_FMODE), + (pCfg->MatchMode | pCfg->AutomaticStop | XSPI_FUNCTIONAL_MODE_AUTO_POLLING)); + + /* Trig the transfer by re-writing address or instruction register */ + if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + WRITE_REG(hxspi->Instance->IR, ir_reg); + } + } + + /* Wait till status match flag is set to go back in idle state */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_SM, SET, tickstart, Timeout); + + if (status == HAL_OK) + { + /* Clear status match flag */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_SM); + + hxspi->State = HAL_XSPI_STATE_READY; + } + } + else + { + status = HAL_BUSY; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Configure the XSPI Automatic Polling Mode in non-blocking mode. + * @param hxspi : XSPI handle + * @param pCfg : Pointer to structure that contains the polling configuration information. + * @note This function is used only in Automatic Polling Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_AutoPolling_IT(XSPI_HandleTypeDef *hxspi, XSPI_AutoPollingTypeDef *const pCfg) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + uint32_t addr_reg = hxspi->Instance->AR; + uint32_t ir_reg = hxspi->Instance->IR; +#ifdef USE_FULL_ASSERT + uint32_t dlr_reg = hxspi->Instance->DLR; +#endif /* USE_FULL_ASSERT */ + + /* Check the parameters of the autopolling configuration structure */ + assert_param(IS_XSPI_MATCH_MODE(pCfg->MatchMode)); + assert_param(IS_XSPI_AUTOMATIC_STOP(pCfg->AutomaticStop)); + assert_param(IS_XSPI_INTERVAL(pCfg->IntervalTime)); + assert_param(IS_XSPI_STATUS_BYTES_SIZE(dlr_reg + 1U)); + + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); + + if (status == HAL_OK) + { + /* Configure registers */ + WRITE_REG(hxspi->Instance->PSMAR, pCfg->MatchValue); + WRITE_REG(hxspi->Instance->PSMKR, pCfg->MatchMask); + WRITE_REG(hxspi->Instance->PIR, pCfg->IntervalTime); + MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_PMM | XSPI_CR_APMS | XSPI_CR_FMODE), + (pCfg->MatchMode | pCfg->AutomaticStop | XSPI_FUNCTIONAL_MODE_AUTO_POLLING)); + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TE | HAL_XSPI_FLAG_SM); + + hxspi->State = HAL_XSPI_STATE_BUSY_AUTO_POLLING; + + /* Enable the status match and transfer error interrupts */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_SM | HAL_XSPI_IT_TE); + + /* Trig the transfer by re-writing address or instruction register */ + if (hxspi->Init.MemoryType == HAL_XSPI_MEMTYPE_HYPERBUS) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + if (READ_BIT(hxspi->Instance->CCR, XSPI_CCR_ADMODE) != HAL_XSPI_ADDRESS_NONE) + { + WRITE_REG(hxspi->Instance->AR, addr_reg); + } + else + { + WRITE_REG(hxspi->Instance->IR, ir_reg); + } + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Configure the Memory Mapped mode. + * @param hxspi : XSPI handle + * @param pCfg : Pointer to structure that contains the memory mapped configuration information. + * @note This function is used only in Memory mapped Mode + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_MemoryMapped(XSPI_HandleTypeDef *hxspi, XSPI_MemoryMappedTypeDef *const pCfg) +{ + HAL_StatusTypeDef status; + uint32_t tickstart = HAL_GetTick(); + + /* Check the parameters of the memory-mapped configuration structure */ + assert_param(IS_XSPI_TIMEOUT_ACTIVATION(pCfg->TimeOutActivation)); + + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_CMD_CFG) + { + /* Wait till busy flag is reset */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); + + if (status == HAL_OK) + { + hxspi->State = HAL_XSPI_STATE_BUSY_MEM_MAPPED; + + if (pCfg->TimeOutActivation == HAL_XSPI_TIMEOUT_COUNTER_ENABLE) + { + assert_param(IS_XSPI_TIMEOUT_PERIOD(pCfg->TimeoutPeriodClock)); + + /* Configure register */ + WRITE_REG(hxspi->Instance->LPTR, pCfg->TimeoutPeriodClock); + + /* Clear flags related to interrupt */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TO); + + /* Enable the timeout interrupt */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TO); + } + + /* Configure CR register with functional mode as memory-mapped */ + MODIFY_REG(hxspi->Instance->CR, (XSPI_CR_TCEN | XSPI_CR_FMODE), + (pCfg->TimeOutActivation | XSPI_FUNCTIONAL_MODE_MEMORY_MAPPED)); + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Transfer Error callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_ErrorCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_XSPI_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Abort completed callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_AbortCpltCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_XSPI_AbortCpltCallback could be implemented in the user file + */ +} + +/** + * @brief FIFO Threshold callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_FifoThresholdCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_XSPI_FIFOThresholdCallback could be implemented in the user file + */ +} + +/** + * @brief Command completed callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_CmdCpltCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_XSPI_CmdCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_RxCpltCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_XSPI_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Transfer completed callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_TxCpltCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_XSPI_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_RxHalfCpltCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_XSPI_RxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_TxHalfCpltCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_XSPI_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Status Match callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_StatusMatchCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_XSPI_StatusMatchCallback could be implemented in the user file + */ +} + +/** + * @brief Timeout callback. + * @param hxspi : XSPI handle + * @retval None + */ +__weak void HAL_XSPI_TimeOutCallback(XSPI_HandleTypeDef *hxspi) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hxspi); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_XSPI_TimeOutCallback could be implemented in the user file + */ +} + +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User XSPI Callback + * To be used to override the weak predefined callback + * @param hxspi : XSPI handle + * @param CallbackID : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_XSPI_ERROR_CB_ID XSPI Error Callback ID + * @arg @ref HAL_XSPI_ABORT_CB_ID XSPI Abort Callback ID + * @arg @ref HAL_XSPI_FIFO_THRESHOLD_CB_ID XSPI FIFO Threshold Callback ID + * @arg @ref HAL_XSPI_CMD_CPLT_CB_ID XSPI Command Complete Callback ID + * @arg @ref HAL_XSPI_RX_CPLT_CB_ID XSPI Rx Complete Callback ID + * @arg @ref HAL_XSPI_TX_CPLT_CB_ID XSPI Tx Complete Callback ID + * @arg @ref HAL_XSPI_RX_HALF_CPLT_CB_ID XSPI Rx Half Complete Callback ID + * @arg @ref HAL_XSPI_TX_HALF_CPLT_CB_ID XSPI Tx Half Complete Callback ID + * @arg @ref HAL_XSPI_STATUS_MATCH_CB_ID XSPI Status Match Callback ID + * @arg @ref HAL_XSPI_TIMEOUT_CB_ID XSPI Timeout Callback ID + * @arg @ref HAL_XSPI_MSP_INIT_CB_ID XSPI MspInit callback ID + * @arg @ref HAL_XSPI_MSP_DEINIT_CB_ID XSPI MspDeInit callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_XSPI_RegisterCallback(XSPI_HandleTypeDef *hxspi, HAL_XSPI_CallbackIDTypeDef CallbackID, + pXSPI_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hxspi->State == HAL_XSPI_STATE_READY) + { + switch (CallbackID) + { + case HAL_XSPI_ERROR_CB_ID : + hxspi->ErrorCallback = pCallback; + break; + case HAL_XSPI_ABORT_CB_ID : + hxspi->AbortCpltCallback = pCallback; + break; + case HAL_XSPI_FIFO_THRESHOLD_CB_ID : + hxspi->FifoThresholdCallback = pCallback; + break; + case HAL_XSPI_CMD_CPLT_CB_ID : + hxspi->CmdCpltCallback = pCallback; + break; + case HAL_XSPI_RX_CPLT_CB_ID : + hxspi->RxCpltCallback = pCallback; + break; + case HAL_XSPI_TX_CPLT_CB_ID : + hxspi->TxCpltCallback = pCallback; + break; + case HAL_XSPI_RX_HALF_CPLT_CB_ID : + hxspi->RxHalfCpltCallback = pCallback; + break; + case HAL_XSPI_TX_HALF_CPLT_CB_ID : + hxspi->TxHalfCpltCallback = pCallback; + break; + case HAL_XSPI_STATUS_MATCH_CB_ID : + hxspi->StatusMatchCallback = pCallback; + break; + case HAL_XSPI_TIMEOUT_CB_ID : + hxspi->TimeOutCallback = pCallback; + break; + case HAL_XSPI_MSP_INIT_CB_ID : + hxspi->MspInitCallback = pCallback; + break; + case HAL_XSPI_MSP_DEINIT_CB_ID : + hxspi->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hxspi->State == HAL_XSPI_STATE_RESET) + { + switch (CallbackID) + { + case HAL_XSPI_MSP_INIT_CB_ID : + hxspi->MspInitCallback = pCallback; + break; + case HAL_XSPI_MSP_DEINIT_CB_ID : + hxspi->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User XSPI Callback + * XSPI Callback is redirected to the weak predefined callback + * @param hxspi : XSPI handle + * @param CallbackID : ID of the callback to be unregistered + * This parameter can be one of the following values: + * @arg @ref HAL_XSPI_ERROR_CB_ID XSPI Error Callback ID + * @arg @ref HAL_XSPI_ABORT_CB_ID XSPI Abort Callback ID + * @arg @ref HAL_XSPI_FIFO_THRESHOLD_CB_ID XSPI FIFO Threshold Callback ID + * @arg @ref HAL_XSPI_CMD_CPLT_CB_ID XSPI Command Complete Callback ID + * @arg @ref HAL_XSPI_RX_CPLT_CB_ID XSPI Rx Complete Callback ID + * @arg @ref HAL_XSPI_TX_CPLT_CB_ID XSPI Tx Complete Callback ID + * @arg @ref HAL_XSPI_RX_HALF_CPLT_CB_ID XSPI Rx Half Complete Callback ID + * @arg @ref HAL_XSPI_TX_HALF_CPLT_CB_ID XSPI Tx Half Complete Callback ID + * @arg @ref HAL_XSPI_STATUS_MATCH_CB_ID XSPI Status Match Callback ID + * @arg @ref HAL_XSPI_TIMEOUT_CB_ID XSPI Timeout Callback ID + * @arg @ref HAL_XSPI_MSP_INIT_CB_ID XSPI MspInit callback ID + * @arg @ref HAL_XSPI_MSP_DEINIT_CB_ID XSPI MspDeInit callback ID + * @retval status + */ +HAL_StatusTypeDef HAL_XSPI_UnRegisterCallback(XSPI_HandleTypeDef *hxspi, HAL_XSPI_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hxspi->State == HAL_XSPI_STATE_READY) + { + switch (CallbackID) + { + case HAL_XSPI_ERROR_CB_ID : + hxspi->ErrorCallback = HAL_XSPI_ErrorCallback; + break; + case HAL_XSPI_ABORT_CB_ID : + hxspi->AbortCpltCallback = HAL_XSPI_AbortCpltCallback; + break; + case HAL_XSPI_FIFO_THRESHOLD_CB_ID : + hxspi->FifoThresholdCallback = HAL_XSPI_FifoThresholdCallback; + break; + case HAL_XSPI_CMD_CPLT_CB_ID : + hxspi->CmdCpltCallback = HAL_XSPI_CmdCpltCallback; + break; + case HAL_XSPI_RX_CPLT_CB_ID : + hxspi->RxCpltCallback = HAL_XSPI_RxCpltCallback; + break; + case HAL_XSPI_TX_CPLT_CB_ID : + hxspi->TxCpltCallback = HAL_XSPI_TxCpltCallback; + break; + case HAL_XSPI_RX_HALF_CPLT_CB_ID : + hxspi->RxHalfCpltCallback = HAL_XSPI_RxHalfCpltCallback; + break; + case HAL_XSPI_TX_HALF_CPLT_CB_ID : + hxspi->TxHalfCpltCallback = HAL_XSPI_TxHalfCpltCallback; + break; + case HAL_XSPI_STATUS_MATCH_CB_ID : + hxspi->StatusMatchCallback = HAL_XSPI_StatusMatchCallback; + break; + case HAL_XSPI_TIMEOUT_CB_ID : + hxspi->TimeOutCallback = HAL_XSPI_TimeOutCallback; + break; + case HAL_XSPI_MSP_INIT_CB_ID : + hxspi->MspInitCallback = HAL_XSPI_MspInit; + break; + case HAL_XSPI_MSP_DEINIT_CB_ID : + hxspi->MspDeInitCallback = HAL_XSPI_MspDeInit; + break; + default : + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hxspi->State == HAL_XSPI_STATE_RESET) + { + switch (CallbackID) + { + case HAL_XSPI_MSP_INIT_CB_ID : + hxspi->MspInitCallback = HAL_XSPI_MspInit; + break; + case HAL_XSPI_MSP_DEINIT_CB_ID : + hxspi->MspDeInitCallback = HAL_XSPI_MspDeInit; + break; + default : + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + +/** + * @} + */ + +/** @defgroup XSPI_Exported_Functions_Group3 Peripheral Control and State functions + * @brief XSPI control and State functions + * +@verbatim + =============================================================================== + ##### Peripheral Control and State functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to : + (+) Check in run-time the state of the driver. + (+) Check the error code set during last operation. + (+) Abort any operation. + (+) Manage the Fifo threshold. + (+) Configure the timeout duration used in the driver. + +@endverbatim + * @{ + */ + +/** + * @brief Abort the current operation, return to the indirect mode. + * @param hxspi : XSPI handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Abort(XSPI_HandleTypeDef *hxspi) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tickstart = HAL_GetTick(); + + /* Check if the state is not in reset state */ + if (hxspi->State != HAL_XSPI_STATE_RESET) + { + /* Check if the DMA is enabled */ + if ((hxspi->Instance->CR & XSPI_CR_DMAEN) != 0U) + { + /* Disable the DMA transfer on the XSPI side */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + + /* Disable the DMA transmit on the DMA side */ + status = HAL_DMA_Abort(hxspi->hdmatx); + if (status != HAL_OK) + { + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + } + + /* Disable the DMA receive on the DMA side */ + status = HAL_DMA_Abort(hxspi->hdmarx); + if (status != HAL_OK) + { + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + } + } + + if (HAL_XSPI_GET_FLAG(hxspi, HAL_XSPI_FLAG_BUSY) != RESET) + { + /* Perform an abort of the XSPI */ + SET_BIT(hxspi->Instance->CR, XSPI_CR_ABORT); + + /* Wait until the transfer complete flag is set to go back in idle state */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_TC, SET, tickstart, hxspi->Timeout); + + if (status == HAL_OK) + { + /* Clear transfer complete flag */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); + + /* Wait until the busy flag is reset to go back in idle state */ + status = XSPI_WaitFlagStateUntilTimeout(hxspi, HAL_XSPI_FLAG_BUSY, RESET, tickstart, hxspi->Timeout); + + if (status == HAL_OK) + { + /* Return to indirect mode */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); + + hxspi->State = HAL_XSPI_STATE_READY; + } + } + } + else + { + /* Return to indirect mode */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); + + hxspi->State = HAL_XSPI_STATE_READY; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** + * @brief Abort the current operation, return to the indirect mode. (non-blocking function) + * @param hxspi : XSPI handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_Abort_IT(XSPI_HandleTypeDef *hxspi) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check if the state is not in reset state */ + if (hxspi->State != HAL_XSPI_STATE_RESET) + { + /* Disable all interrupts */ + HAL_XSPI_DISABLE_IT(hxspi, (HAL_XSPI_IT_TO | HAL_XSPI_IT_SM | HAL_XSPI_IT_FT | HAL_XSPI_IT_TC | HAL_XSPI_IT_TE)); + + hxspi->State = HAL_XSPI_STATE_ABORT; + + /* Check if the DMA is enabled */ + if ((hxspi->Instance->CR & XSPI_CR_DMAEN) != 0U) + { + /* Disable the DMA transfer on the XSPI side */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + + /* Disable the DMA transmit on the DMA side */ + hxspi->hdmatx->XferAbortCallback = XSPI_DMAAbortCplt; + if (HAL_DMA_Abort_IT(hxspi->hdmatx) != HAL_OK) + { + hxspi->State = HAL_XSPI_STATE_READY; + + /* Abort callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->AbortCpltCallback(hxspi); +#else + HAL_XSPI_AbortCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + + /* Disable the DMA receive on the DMA side */ + hxspi->hdmarx->XferAbortCallback = XSPI_DMAAbortCplt; + if (HAL_DMA_Abort_IT(hxspi->hdmarx) != HAL_OK) + { + hxspi->State = HAL_XSPI_STATE_READY; + + /* Abort callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->AbortCpltCallback(hxspi); +#else + HAL_XSPI_AbortCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + } + else + { + if (HAL_XSPI_GET_FLAG(hxspi, HAL_XSPI_FLAG_BUSY) != RESET) + { + /* Clear transfer complete flag */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); + + /* Enable the transfer complete interrupts */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC); + + /* Perform an abort of the XSPI */ + SET_BIT(hxspi->Instance->CR, XSPI_CR_ABORT); + + /* Return to indirect mode */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); + } + else + { + /* Return to indirect mode */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_FMODE); + + hxspi->State = HAL_XSPI_STATE_READY; + + /* Abort callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->AbortCpltCallback(hxspi); +#else + HAL_XSPI_AbortCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** @brief Set XSPI Fifo threshold. + * @param hxspi : XSPI handle. + * @param Threshold : Threshold of the Fifo. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_SetFifoThreshold(XSPI_HandleTypeDef *hxspi, uint32_t Threshold) +{ + HAL_StatusTypeDef status = HAL_OK; + + assert_param(IS_XSPI_FIFO_THRESHOLD_BYTE(Threshold)); + + /* Check the state */ + if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) + { + /* Synchronize initialization structure with the new fifo threshold value */ + hxspi->Init.FifoThresholdByte = Threshold; + + /* Configure new fifo threshold */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FTHRES, ((hxspi->Init.FifoThresholdByte - 1U) << XSPI_CR_FTHRES_Pos)); + + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** @brief Get XSPI Fifo threshold. + * @param hxspi : XSPI handle. + * @retval Fifo threshold + */ +uint32_t HAL_XSPI_GetFifoThreshold(const XSPI_HandleTypeDef *hxspi) +{ + return ((READ_BIT(hxspi->Instance->CR, XSPI_CR_FTHRES) >> XSPI_CR_FTHRES_Pos) + 1U); +} + +/** @brief Set XSPI Memory Type. + * @param hxspi : XSPI handle. + * @param Type : Memory Type. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_SetMemoryType(XSPI_HandleTypeDef *hxspi, uint32_t Type) +{ + HAL_StatusTypeDef status = HAL_OK; + + assert_param(IS_XSPI_MEMORY_TYPE(Type)); + + /* Check the state */ + if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) + { + /* Synchronize initialization structure with the new memory type value */ + hxspi->Init.MemoryType = Type; + + /* Configure new memory type */ + MODIFY_REG(hxspi->Instance->DCR1, XSPI_DCR1_MTYP, hxspi->Init.MemoryType); + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** @brief Set XSPI Device Size. + * @param hxspi : XSPI handle. + * @param Size : Device Size. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_SetDeviceSize(XSPI_HandleTypeDef *hxspi, uint32_t Size) +{ + HAL_StatusTypeDef status = HAL_OK; + + assert_param(IS_XSPI_MEMORY_SIZE(Size)); + + /* Check the state */ + if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) + { + /* Synchronize initialization structure with the new device size value */ + hxspi->Init.MemorySize = Size; + + /* Configure new device size */ + MODIFY_REG(hxspi->Instance->DCR1, XSPI_DCR1_DEVSIZE, + (hxspi->Init.MemorySize << XSPI_DCR1_DEVSIZE_Pos)); + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** @brief Set XSPI Clock prescaler. + * @param hxspi : XSPI handle. + * @param Prescaler : Clock prescaler. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_SetClockPrescaler(XSPI_HandleTypeDef *hxspi, uint32_t Prescaler) +{ + HAL_StatusTypeDef status = HAL_OK; + assert_param(IS_XSPI_CLK_PRESCALER(Prescaler)); + + /* Check the state */ + if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) + { + /* Synchronize initialization structure with the new clock prescaler value */ + hxspi->Init.ClockPrescaler = Prescaler; + + /* Configure clock prescaler */ + MODIFY_REG(hxspi->Instance->DCR2, XSPI_DCR2_PRESCALER, + ((hxspi->Init.ClockPrescaler) << XSPI_DCR2_PRESCALER_Pos)); + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + + return status; +} + +/** @brief Set XSPI timeout. + * @param hxspi : XSPI handle. + * @param Timeout : Timeout for the memory access. + * @retval HAL state + */ +HAL_StatusTypeDef HAL_XSPI_SetTimeout(XSPI_HandleTypeDef *hxspi, uint32_t Timeout) +{ + hxspi->Timeout = Timeout; + return HAL_OK; +} + +/** + * @brief Return the XSPI error code. + * @param hxspi : XSPI handle + * @retval XSPI Error Code + */ +uint32_t HAL_XSPI_GetError(const XSPI_HandleTypeDef *hxspi) +{ + return hxspi->ErrorCode; +} + +/** + * @brief Return the XSPI handle state. + * @param hxspi : XSPI handle + * @retval HAL state + */ +uint32_t HAL_XSPI_GetState(const XSPI_HandleTypeDef *hxspi) +{ + /* Return XSPI handle state */ + return hxspi->State; +} + +/** + * @} + */ + +/** @defgroup XSPI_Exported_Functions_Group4 IO Manager configuration function + * @brief XSPI IO Manager configuration function + * +@verbatim + =============================================================================== + ##### IO Manager configuration function ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to : + (+) Configure the IO manager. + +@endverbatim + * @{ + */ + +/** + * @brief Configure the XSPI IO manager. + * @param hxspi : XSPI handle + * @param pCfg : Pointer to Configuration of the IO Manager for the instance + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPIM_Config(XSPI_HandleTypeDef *const hxspi, XSPIM_CfgTypeDef *const pCfg, uint32_t Timeout) +{ + HAL_StatusTypeDef status = HAL_OK; + uint8_t index; + uint8_t xspi_enabled = 0U; + + XSPIM_CfgTypeDef IOM_cfg[XSPI_NB_INSTANCE] = {0}; + + /* Prevent unused argument(s) compilation warning */ + UNUSED(Timeout); + + /* Check the parameters of the XSPI IO Manager configuration structure */ + assert_param(IS_XSPIM_NCS_OVR(pCfg->nCSOverride)); + assert_param(IS_XSPIM_IO_PORT(pCfg->IOPort)); + assert_param(IS_XSPIM_REQ2ACKTIME(pCfg->Req2AckTime)); + + /**************** Get current configuration of the instances ****************/ + for (index = 0U; index < XSPI_NB_INSTANCE; index++) + { + XSPIM_GetConfig(index + 1U, &(IOM_cfg[index])); + } + + /********** Disable both XSPI to configure XSPI IO Manager **********/ + if ((XSPI1->CR & XSPI_CR_EN) != 0U) + { + CLEAR_BIT(XSPI1->CR, XSPI_CR_EN); + xspi_enabled |= 0x1U; + } + if ((XSPI2->CR & XSPI_CR_EN) != 0U) + { + CLEAR_BIT(XSPI2->CR, XSPI_CR_EN); + xspi_enabled |= 0x2U; + } + + /***************** Deactivation of previous configuration *****************/ + CLEAR_REG(XSPIM->CR); + + /******************** Activation of new configuration *********************/ + MODIFY_REG(XSPIM->CR, XSPIM_CR_REQ2ACK_TIME, ((pCfg->Req2AckTime - 1U) << XSPIM_CR_REQ2ACK_TIME_Pos)); + + if (hxspi->Instance == XSPI1) + { + IOM_cfg[0].IOPort = pCfg->IOPort ; + if (pCfg->nCSOverride != HAL_XSPI_CSSEL_OVR_DISABLED) + { + MODIFY_REG(XSPIM->CR, (XSPIM_CR_CSSEL_OVR_O1 | XSPIM_CR_CSSEL_OVR_EN), (pCfg->nCSOverride)); + } + else + { + /* Nothing to do */ + } + } + else if (hxspi->Instance == XSPI2) + { + IOM_cfg[1].IOPort = pCfg->IOPort ; + if (pCfg->nCSOverride != HAL_XSPI_CSSEL_OVR_DISABLED) + { + MODIFY_REG(XSPIM->CR, (XSPIM_CR_CSSEL_OVR_O2 | XSPIM_CR_CSSEL_OVR_EN), (pCfg->nCSOverride)); + } + else + { + /* Nothing to do */ + } + } + else + { + hxspi->ErrorCode |= HAL_XSPI_ERROR_INVALID_PARAM; + return HAL_ERROR; + } + + for (index = 0U; index < (XSPI_NB_INSTANCE - 1U); index++) + { + if ((IOM_cfg[index].IOPort == IOM_cfg[index + 1U].IOPort)) + { + /*Mux*/ + SET_BIT(XSPIM->CR, XSPIM_CR_MUXEN); + } + else + { + /* Nothing to do */ + } + if (IOM_cfg[0].IOPort == HAL_XSPIM_IOPORT_2) + { + /*Mode*/ + SET_BIT(XSPIM->CR, XSPIM_CR_MODE); + } + else + { + /* Nothing to do */ + } + } + + /******* Re-enable both XSPI after configure XSPI IO Manager ********/ + if ((xspi_enabled & 0x1U) != 0U) + { + SET_BIT(XSPI1->CR, XSPI_CR_EN); + } + if ((xspi_enabled & 0x2U) != 0U) + { + SET_BIT(XSPI2->CR, XSPI_CR_EN); + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup XSPI_Exported_Functions_Group6 High-speed interface and calibration functions + * @brief XSPI high-speed interface and calibration functions + * +@verbatim + =============================================================================== + ##### High-speed interface and calibration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to : + (+) Get the delay values of the high-speed interface DLLs. + (+) Set a delay value for the high-speed interface DLLs. + +@endverbatim + * @{ + */ + +/** + * @brief Get the delay values of the high-speed interface DLLs. + * @param hxspi : XSPI handle + * @param pCfg : Current delay values corresponding to the DelayValueType field. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_GetDelayValue(XSPI_HandleTypeDef *hxspi, XSPI_HSCalTypeDef *const pCfg) +{ + HAL_StatusTypeDef status = HAL_OK; + __IO uint32_t reg = 0; + + if (IS_XSPI_ALL_INSTANCE(hxspi->Instance)) + { + /* Check the parameter specified in the structure */ + assert_param(IS_XSPI_DELAY_TYPE(pCfg->DelayValueType)); + + switch (pCfg->DelayValueType) + { + case HAL_XSPI_CAL_FULL_CYCLE_DELAY: + reg = hxspi->Instance->CALFCR; + pCfg->MaxCalibration = (reg & XSPI_CALFCR_CALMAX); + break; + case HAL_XSPI_CAL_FEEDBACK_CLK_DELAY: + reg = hxspi->Instance->CALMR; + break; + case HAL_XSPI_CAL_DATA_OUTPUT_DELAY: + reg = hxspi->Instance->CALSOR; + break; + case HAL_XSPI_CAL_DQS_INPUT_DELAY: + reg = hxspi->Instance->CALSIR; + break; + default: + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + break; + } + + if (status == HAL_OK) + { + pCfg->FineCalibrationUnit = (reg & XSPI_CALFCR_FINE); + pCfg->CoarseCalibrationUnit = ((reg & XSPI_CALFCR_COARSE) >> XSPI_CALFCR_COARSE_Pos); + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + + return status; +} + +/** + * @brief Set a delay value for the high-speed interface DLLs. + * @param hxspi : XSPI handle + * @param pCfg : Configuration of delay value specified in DelayValueType field. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_XSPI_SetDelayValue(XSPI_HandleTypeDef *hxspi, XSPI_HSCalTypeDef *const pCfg) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (IS_XSPI_ALL_INSTANCE(hxspi->Instance)) + { + /* Check the parameter specified in the structure */ + assert_param(IS_XSPI_DELAY_TYPE(pCfg->DelayValueType)); + assert_param(IS_XSPI_FINECAL_VALUE(pCfg->FineCalibrationUnit)); + assert_param(IS_XSPI_COARSECAL_VALUE(pCfg->CoarseCalibrationUnit)); + + /* Check if the state isn't in one of the busy states */ + if ((hxspi->State & XSPI_BUSY_STATE_MASK) == 0U) + { + switch (pCfg->DelayValueType) + { + case HAL_XSPI_CAL_FEEDBACK_CLK_DELAY: + MODIFY_REG(hxspi->Instance->CALMR, (XSPI_CALMR_COARSE | XSPI_CALMR_FINE), + (pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << XSPI_CALMR_COARSE_Pos))); + break; + case HAL_XSPI_CAL_DATA_OUTPUT_DELAY: + MODIFY_REG(hxspi->Instance->CALSOR, (XSPI_CALSOR_COARSE | XSPI_CALSOR_FINE), + (pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << XSPI_CALSOR_COARSE_Pos))); + break; + case HAL_XSPI_CAL_DQS_INPUT_DELAY: + MODIFY_REG(hxspi->Instance->CALSIR, (XSPI_CALSIR_COARSE | XSPI_CALSIR_FINE), + (pCfg->FineCalibrationUnit | (pCfg->CoarseCalibrationUnit << XSPI_CALSIR_COARSE_Pos))); + break; + default: + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + break; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_SEQUENCE; + } + } + else + { + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + + return status; +} + +/** + * @} + */ + +/** + @cond 0 + */ +/** + * @brief DMA XSPI process complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void XSPI_DMACplt(DMA_HandleTypeDef *hdma) +{ + XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); + hxspi->XferCount = 0; + + /* Disable the DMA transfer on the XSPI side */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + + /* Enable the XSPI transfer complete Interrupt */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC); +} + +/** + * @brief DMA XSPI process half complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void XSPI_DMAHalfCplt(DMA_HandleTypeDef *hdma) +{ + XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); + hxspi->XferCount = (hxspi->XferCount >> 1); + + if (hxspi->State == HAL_XSPI_STATE_BUSY_RX) + { +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->RxHalfCpltCallback(hxspi); +#else + HAL_XSPI_RxHalfCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + else + { +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->TxHalfCpltCallback(hxspi); +#else + HAL_XSPI_TxHalfCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } +} + +/** + * @brief DMA XSPI communication error callback. + * @param hdma : DMA handle + * @retval None + */ +static void XSPI_DMAError(DMA_HandleTypeDef *hdma) +{ + XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); + hxspi->XferCount = 0; + hxspi->ErrorCode = HAL_XSPI_ERROR_DMA; + + /* Disable the DMA transfer on the XSPI side */ + CLEAR_BIT(hxspi->Instance->CR, XSPI_CR_DMAEN); + + /* Abort the XSPI */ + if (HAL_XSPI_Abort_IT(hxspi) != HAL_OK) + { + /* Disable the interrupts */ + HAL_XSPI_DISABLE_IT(hxspi, HAL_XSPI_IT_TC | HAL_XSPI_IT_FT | HAL_XSPI_IT_TE); + + hxspi->State = HAL_XSPI_STATE_READY; + + /* Error callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->ErrorCallback(hxspi); +#else + HAL_XSPI_ErrorCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } +} + +/** + * @brief DMA XSPI abort complete callback. + * @param hdma : DMA handle + * @retval None + */ +static void XSPI_DMAAbortCplt(DMA_HandleTypeDef *hdma) +{ + XSPI_HandleTypeDef *hxspi = (XSPI_HandleTypeDef *)(hdma->Parent); + hxspi->XferCount = 0; + + /* Check the state */ + if (hxspi->State == HAL_XSPI_STATE_ABORT) + { + /* DMA abort called by XSPI abort */ + if (HAL_XSPI_GET_FLAG(hxspi, HAL_XSPI_FLAG_BUSY) != RESET) + { + /* Clear transfer complete flag */ + HAL_XSPI_CLEAR_FLAG(hxspi, HAL_XSPI_FLAG_TC); + + /* Enable the transfer complete interrupts */ + HAL_XSPI_ENABLE_IT(hxspi, HAL_XSPI_IT_TC); + + /* Perform an abort of the XSPI */ + SET_BIT(hxspi->Instance->CR, XSPI_CR_ABORT); + } + else + { + hxspi->State = HAL_XSPI_STATE_READY; + + /* Abort callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->AbortCpltCallback(hxspi); +#else + HAL_XSPI_AbortCpltCallback(hxspi); +#endif /* (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } + } + else + { + /* DMA abort called due to a transfer error interrupt */ + hxspi->State = HAL_XSPI_STATE_READY; + + /* Error callback */ +#if defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) + hxspi->ErrorCallback(hxspi); +#else + HAL_XSPI_ErrorCallback(hxspi); +#endif /* defined (USE_HAL_XSPI_REGISTER_CALLBACKS) && (USE_HAL_XSPI_REGISTER_CALLBACKS == 1U) */ + } +} + +/** + * @brief Wait for a flag state until timeout. + * @param hxspi : XSPI handle + * @param Flag : Flag checked + * @param State : Value of the flag expected + * @param Timeout : Duration of the timeout + * @param Tickstart : Tick start value + * @retval HAL status + */ +static HAL_StatusTypeDef XSPI_WaitFlagStateUntilTimeout(XSPI_HandleTypeDef *hxspi, uint32_t Flag, + FlagStatus State, uint32_t Tickstart, uint32_t Timeout) +{ + /* Wait until flag is in expected state */ + while ((HAL_XSPI_GET_FLAG(hxspi, Flag)) != State) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) + { + hxspi->State = HAL_XSPI_STATE_READY; + hxspi->ErrorCode |= HAL_XSPI_ERROR_TIMEOUT; + + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + +/** + * @brief Configure the registers for the regular command mode. + * @param hxspi : XSPI handle + * @param pCmd : structure that contains the command configuration information + * @retval HAL status + */ +static HAL_StatusTypeDef XSPI_ConfigCmd(XSPI_HandleTypeDef *hxspi, XSPI_RegularCmdTypeDef *pCmd) +{ + HAL_StatusTypeDef status = HAL_OK; + __IO uint32_t *ccr_reg; + __IO uint32_t *tcr_reg; + __IO uint32_t *ir_reg; + __IO uint32_t *abr_reg; + + /* Re-initialize the value of the functional mode */ + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_FMODE, 0U); + + if (hxspi->Init.MemoryMode == HAL_XSPI_SINGLE_MEM) + { + assert_param(IS_XSPI_IO_SELECT(pCmd->IOSelect)); + MODIFY_REG(hxspi->Instance->CR, XSPI_CR_MSEL, pCmd->IOSelect); + } + + if (pCmd->OperationType == HAL_XSPI_OPTYPE_WRITE_CFG) + { + ccr_reg = &(hxspi->Instance->WCCR); + tcr_reg = &(hxspi->Instance->WTCR); + ir_reg = &(hxspi->Instance->WIR); + abr_reg = &(hxspi->Instance->WABR); + } + else if (pCmd->OperationType == HAL_XSPI_OPTYPE_WRAP_CFG) + { + ccr_reg = &(hxspi->Instance->WPCCR); + tcr_reg = &(hxspi->Instance->WPTCR); + ir_reg = &(hxspi->Instance->WPIR); + abr_reg = &(hxspi->Instance->WPABR); + } + else + { + ccr_reg = &(hxspi->Instance->CCR); + tcr_reg = &(hxspi->Instance->TCR); + ir_reg = &(hxspi->Instance->IR); + abr_reg = &(hxspi->Instance->ABR); + } + + /* Configure the CCR register with DQS and SIOO modes */ + *ccr_reg = pCmd->DQSMode; + + if (pCmd->AlternateBytesMode != HAL_XSPI_ALT_BYTES_NONE) + { + /* Configure the ABR register with alternate bytes value */ + *abr_reg = pCmd->AlternateBytes; + + /* Configure the CCR register with alternate bytes communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_ABMODE | XSPI_CCR_ABDTR | XSPI_CCR_ABSIZE), + (pCmd->AlternateBytesMode | pCmd->AlternateBytesDTRMode | pCmd->AlternateBytesWidth)); + } + + /* Configure the TCR register with the number of dummy cycles */ + MODIFY_REG((*tcr_reg), XSPI_TCR_DCYC, pCmd->DummyCycles); + + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + if (pCmd->OperationType == HAL_XSPI_OPTYPE_COMMON_CFG) + { + /* Configure the DLR register with the number of data */ + hxspi->Instance->DLR = (pCmd->DataLength - 1U); + } + } + + /* Configure SSHIFT register to handle SDR/DTR data transfer */ + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + if (pCmd->DataDTRMode == HAL_XSPI_DATA_DTR_ENABLE) + { + /* Deactivate sample shifting when receiving data in DTR mode (DDTR=1) */ + CLEAR_BIT(hxspi->Instance->TCR, XSPI_TCR_SSHIFT); + } + else if(hxspi->Init.SampleShifting == HAL_XSPI_SAMPLE_SHIFT_HALFCYCLE) + { + /* Configure sample shifting */ + SET_BIT(hxspi->Instance->TCR, XSPI_TCR_SSHIFT); + } + else + { + /* Do nothing */ + } + } + + if (pCmd->InstructionMode != HAL_XSPI_INSTRUCTION_NONE) + { + if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) + { + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + /* ---- Command with instruction, address and data ---- */ + + /* Configure the CCR register with all communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE | + XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE | + XSPI_CCR_DMODE | XSPI_CCR_DDTR), + (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth | + pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth | + pCmd->DataMode | pCmd->DataDTRMode)); + } + else + { + /* ---- Command with instruction and address ---- */ + + /* Configure the CCR register with all communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE | + XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE), + (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth | + pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth)); + + /* The DHQC bit is linked with DDTR bit which should be activated */ + if ((hxspi->Init.DelayHoldQuarterCycle == HAL_XSPI_DHQC_ENABLE) && + (pCmd->InstructionDTRMode == HAL_XSPI_INSTRUCTION_DTR_ENABLE)) + { + MODIFY_REG((*ccr_reg), XSPI_CCR_DDTR, HAL_XSPI_DATA_DTR_ENABLE); + } + } + /* Configure the IR register with the instruction value */ + *ir_reg = pCmd->Instruction; + + /* Configure the AR register with the address value */ + hxspi->Instance->AR = pCmd->Address; + } + else + { + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + /* ---- Command with instruction and data ---- */ + + /* Configure the CCR register with all communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE | + XSPI_CCR_DMODE | XSPI_CCR_DDTR), + (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth | + pCmd->DataMode | pCmd->DataDTRMode)); + } + else + { + /* ---- Command with only instruction ---- */ + + /* Configure the CCR register with all communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_IMODE | XSPI_CCR_IDTR | XSPI_CCR_ISIZE), + (pCmd->InstructionMode | pCmd->InstructionDTRMode | pCmd->InstructionWidth)); + + /* The DHQC bit is linked with DDTR bit which should be activated */ + if ((hxspi->Init.DelayHoldQuarterCycle == HAL_XSPI_DHQC_ENABLE) && + (pCmd->InstructionDTRMode == HAL_XSPI_INSTRUCTION_DTR_ENABLE)) + { + MODIFY_REG((*ccr_reg), XSPI_CCR_DDTR, HAL_XSPI_DATA_DTR_ENABLE); + } + } + + /* Configure the IR register with the instruction value */ + *ir_reg = pCmd->Instruction; + + } + } + else + { + if (pCmd->AddressMode != HAL_XSPI_ADDRESS_NONE) + { + if (pCmd->DataMode != HAL_XSPI_DATA_NONE) + { + /* ---- Command with address and data ---- */ + + /* Configure the CCR register with all communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE | + XSPI_CCR_DMODE | XSPI_CCR_DDTR), + (pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth | + pCmd->DataMode | pCmd->DataDTRMode)); + } + else + { + /* ---- Command with only address ---- */ + + /* Configure the CCR register with all communication parameters */ + MODIFY_REG((*ccr_reg), (XSPI_CCR_ADMODE | XSPI_CCR_ADDTR | XSPI_CCR_ADSIZE), + (pCmd->AddressMode | pCmd->AddressDTRMode | pCmd->AddressWidth)); + } + + /* Configure the AR register with the instruction value */ + hxspi->Instance->AR = pCmd->Address; + } + else + { + /* ---- Invalid command configuration (no instruction, no address) ---- */ + status = HAL_ERROR; + hxspi->ErrorCode = HAL_XSPI_ERROR_INVALID_PARAM; + } + } + + return status; +} + +/** + * @brief Get the current IOM configuration for an XSPI instance. + * @param instance_nb : number of the instance + * @param pCfg : configuration of the IO Manager for the instance + * @retval HAL status + */ +static void XSPIM_GetConfig(uint8_t instance_nb, XSPIM_CfgTypeDef *const pCfg) +{ + uint32_t mux; + uint32_t mode; + + if (instance_nb == 1U) + { + if ((XSPIM->CR & XSPIM_CR_MODE) == 0U) + { + pCfg->IOPort = HAL_XSPIM_IOPORT_1; + } + else + { + pCfg->IOPort = HAL_XSPIM_IOPORT_2; + } + + if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_EN) != XSPIM_CR_CSSEL_OVR_EN) + { + pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_DISABLED; + } + else if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_O1) == XSPIM_CR_CSSEL_OVR_O1) + { + pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS2; + } + else + { + pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS1; + } + } + else + { + mux = (XSPIM->CR & XSPIM_CR_MUXEN); + mode = ((XSPIM->CR & XSPIM_CR_MODE) >> XSPIM_CR_MODE_Pos); + if (mux != mode) + { + pCfg->IOPort = HAL_XSPIM_IOPORT_1; + } + else + { + pCfg->IOPort = HAL_XSPIM_IOPORT_2; + } + if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_EN) != XSPIM_CR_CSSEL_OVR_EN) + { + pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_DISABLED; + } + else if ((XSPIM->CR & XSPIM_CR_CSSEL_OVR_O2) == XSPIM_CR_CSSEL_OVR_O2) + { + pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS2; + } + else + { + pCfg->nCSOverride = HAL_XSPI_CSSEL_OVR_NCS1; + } + } +} +/** + @endcond + */ + +/** + * @} + */ + +#endif /* HAL_XSPI_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* XSPI || XSPI1 || XSPI2 */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_adc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_adc.c index 13408c327..ff334a807 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_adc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_adc.c @@ -1,1067 +1,1067 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_adc.c - * @author MCD Application Team - * @brief ADC LL module driver - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_adc.h" -#include "stm32h7rsxx_ll_bus.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (ADC1) || defined (ADC2) - -/** @addtogroup ADC_LL ADC - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup ADC_LL_Private_Constants - * @{ - */ - -/* Definitions of ADC hardware constraints delays */ -/* Note: Only ADC peripheral HW delays are defined in ADC LL driver driver, */ -/* not timeout values: */ -/* Timeout values for ADC operations are dependent to device clock */ -/* configuration (system clock versus ADC clock), */ -/* and therefore must be defined in user application. */ -/* Refer to @ref ADC_LL_EC_HW_DELAYS for description of ADC timeout */ -/* values definition. */ -/* Note: ADC timeout values are defined here in CPU cycles to be independent */ -/* of device clock setting. */ -/* In user application, ADC timeout values should be defined with */ -/* temporal values, in function of device clock settings. */ -/* Highest ratio CPU clock frequency vs ADC clock frequency: */ -/* - ADC clock from synchronous clock with AHB prescaler 512, */ -/* ADC prescaler 4. */ -/* Ratio max = 512 *4 = 2048 */ -/* - ADC clock from asynchronous clock (PLLP) with prescaler 256. */ -/* Highest CPU clock PLL (PLLR). */ -/* Ratio max = PLLRmax /PPLPmin * 256 = (VCO/2) / (VCO/31) * 256 */ -/* = 3968 */ -/* Unit: CPU cycles. */ -#define ADC_CLOCK_RATIO_VS_CPU_HIGHEST (3968UL) -#define ADC_TIMEOUT_DISABLE_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1UL) -#define ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1UL) - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ - -/** @addtogroup ADC_LL_Private_Macros - * @{ - */ - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* common to several ADC instances. */ -#define IS_LL_ADC_COMMON_CLOCK(__CLOCK__) \ - (((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV1) \ - || ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV2) \ - || ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV4) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV1) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV2) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV4) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV6) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV8) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV10) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV12) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV16) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV32) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV64) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV128) \ - || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV256) \ - ) - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* ADC instance. */ -#define IS_LL_ADC_RESOLUTION(__RESOLUTION__) \ - (((__RESOLUTION__) == LL_ADC_RESOLUTION_12B) \ - || ((__RESOLUTION__) == LL_ADC_RESOLUTION_10B) \ - || ((__RESOLUTION__) == LL_ADC_RESOLUTION_8B) \ - || ((__RESOLUTION__) == LL_ADC_RESOLUTION_6B) \ - ) - -#define IS_LL_ADC_DATA_ALIGN(__DATA_ALIGN__) \ - (((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_RIGHT) \ - || ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_LEFT) \ - ) - -#define IS_LL_ADC_LOW_POWER(__LOW_POWER__) \ - (((__LOW_POWER__) == LL_ADC_LP_MODE_NONE) \ - || ((__LOW_POWER__) == LL_ADC_LP_AUTOWAIT) \ - ) - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* ADC group regular */ -#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ - (((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM12_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM9_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM15_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH4) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM1_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM2_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM3_CH1) \ - ) - -#define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \ - (((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \ - || ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \ - ) - -#define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \ - (((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE) \ - || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_LIMITED) \ - || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \ - ) - -#define IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(__REG_OVR_DATA_BEHAVIOR__) \ - (((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_PRESERVED) \ - || ((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_OVERWRITTEN) \ - ) - -#define IS_LL_ADC_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \ - (((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_DISABLE) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS) \ - ) - -#define IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \ - (((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_DISABLE) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_1RANK) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_2RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_3RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_4RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_5RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_6RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_7RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_8RANKS) \ - ) - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* ADC group injected */ -#define IS_LL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \ - (((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM9_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM9_CH1) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM12_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM1_CH2) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM2_CH2) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM3_CH1) \ - ) - -#define IS_LL_ADC_INJ_TRIG_EXT_EDGE(__INJ_TRIG_EXT_EDGE__) \ - (((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_RISING) \ - || ((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_FALLING) \ - || ((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_RISINGFALLING) \ - ) - -#define IS_LL_ADC_INJ_TRIG_AUTO(__INJ_TRIG_AUTO__) \ - (((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_INDEPENDENT) \ - || ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_FROM_GRP_REGULAR) \ - ) - -#define IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(__INJ_SEQ_SCAN_LENGTH__) \ - (((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_DISABLE) \ - || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS) \ - || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS) \ - || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS) \ - ) - -#define IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(__INJ_SEQ_DISCONT_MODE__) \ - (((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_DISABLE) \ - || ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_1RANK) \ - ) - -#if defined(ADC_MULTIMODE_SUPPORT) -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* multimode. */ -#define IS_LL_ADC_MULTI_MODE(__MULTI_MODE__) \ - (((__MULTI_MODE__) == LL_ADC_MULTI_INDEPENDENT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIMULT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_SIMULT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_ALTERN) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INT_INJ_SIM) \ - ) - -#define IS_LL_ADC_MULTI_DMA_TRANSFER(__MULTI_DMA_TRANSFER__) \ - (((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_EACH_ADC) \ - || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_LIMIT_RES12_10B) \ - || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_LIMIT_RES8_6B) \ - || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_UNLMT_RES12_10B) \ - || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_UNLMT_RES8_6B) \ - ) - -#define IS_LL_ADC_MULTI_TWOSMP_DELAY(__MULTI_TWOSMP_DELAY__) \ - (((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_2CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_3CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_4CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_5CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_6CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_7CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_8CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_9CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_10CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_11CYCLES) \ - || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_12CYCLES) \ - ) - -#define IS_LL_ADC_MULTI_MASTER_SLAVE(__MULTI_MASTER_SLAVE__) \ - (((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER) \ - || ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_SLAVE) \ - || ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER_SLAVE) \ - ) - -#endif /* ADC_MULTIMODE_SUPPORT */ -/** - * @} - */ - - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup ADC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup ADC_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize registers of all ADC instances belonging to - * the same ADC common instance to their default reset values. - * @note This function is performing a hard reset, using high level - * clock source RCC ADC reset. - * Caution: On this STM32 series, if several ADC instances are available - * on the selected device, RCC ADC reset will reset - * all ADC instances belonging to the common ADC instance. - * To de-initialize only 1 ADC instance, use - * function @ref LL_ADC_DeInit(). - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC common registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_ADC_CommonDeInit(const ADC_Common_TypeDef *ADCxy_COMMON) -{ - /* Check the parameters */ - assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); - - /* Prevent unused argument compilation warning */ - (void)(ADCxy_COMMON); - - /* Force reset of ADC clock (core clock) */ - LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_ADC12); - - /* Release reset of ADC clock (core clock) */ - LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_ADC12); - - return SUCCESS; -} - -/** - * @brief Initialize some features of ADC common parameters - * (all ADC instances belonging to the same ADC common instance) - * and multimode (for devices with several ADC instances available). - * @note The setting of ADC common parameters is conditioned to - * ADC instances state: - * All ADC instances belonging to the same ADC common instance - * must be disabled. - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @param pADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC common registers are initialized - * - ERROR: ADC common registers are not initialized - */ -ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, const LL_ADC_CommonInitTypeDef *pADC_CommonInitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); - assert_param(IS_LL_ADC_COMMON_CLOCK(pADC_CommonInitStruct->CommonClock)); - -#if defined(ADC_MULTIMODE_SUPPORT) - assert_param(IS_LL_ADC_MULTI_MODE(pADC_CommonInitStruct->Multimode)); - if (pADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT) - { - assert_param(IS_LL_ADC_MULTI_DMA_TRANSFER(pADC_CommonInitStruct->MultiDMATransfer)); - assert_param(IS_LL_ADC_MULTI_TWOSMP_DELAY(pADC_CommonInitStruct->MultiTwoSamplingDelay)); - } -#endif /* ADC_MULTIMODE_SUPPORT */ - - /* Note: Hardware constraint (refer to description of functions */ - /* "LL_ADC_SetCommonXXX()" and "LL_ADC_SetMultiXXX()"): */ - /* On this STM32 series, setting of these features is conditioned to */ - /* ADC state: */ - /* All ADC instances of the ADC common group must be disabled. */ - if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0UL) - { - /* Configuration of ADC hierarchical scope: */ - /* - common to several ADC */ - /* (all ADC instances belonging to the same ADC common instance) */ - /* - Set ADC clock (conversion clock) */ - /* - multimode (if several ADC instances available on the */ - /* selected device) */ - /* - Set ADC multimode configuration */ - /* - Set ADC multimode DMA transfer */ - /* - Set ADC multimode: delay between 2 sampling phases */ -#if defined(ADC_MULTIMODE_SUPPORT) - if (pADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT) - { - MODIFY_REG(ADCxy_COMMON->CCR, - ADC_CCR_CKMODE - | ADC_CCR_PRESC - | ADC_CCR_DUAL - | ADC_CCR_MDMA - | ADC_CCR_DELAY - , - pADC_CommonInitStruct->CommonClock - | pADC_CommonInitStruct->Multimode - | pADC_CommonInitStruct->MultiDMATransfer - | pADC_CommonInitStruct->MultiTwoSamplingDelay - ); - } - else - { - MODIFY_REG(ADCxy_COMMON->CCR, - ADC_CCR_CKMODE - | ADC_CCR_PRESC - | ADC_CCR_DUAL - | ADC_CCR_MDMA - | ADC_CCR_DELAY - , - pADC_CommonInitStruct->CommonClock - | LL_ADC_MULTI_INDEPENDENT - ); - } -#else - LL_ADC_SetCommonClock(ADCxy_COMMON, pADC_CommonInitStruct->CommonClock); -#endif /* ADC_MULTIMODE_SUPPORT */ - } - else - { - /* Initialization error: One or several ADC instances belonging to */ - /* the same ADC common instance are not disabled. */ - status = ERROR; - } - - return status; -} - -/** - * @brief Set each @ref LL_ADC_CommonInitTypeDef field to default value. - * @param pADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *pADC_CommonInitStruct) -{ - /* Set pADC_CommonInitStruct fields to default values */ - /* Set fields of ADC common */ - /* (all ADC instances belonging to the same ADC common instance) */ - pADC_CommonInitStruct->CommonClock = LL_ADC_CLOCK_SYNC_PCLK_DIV2; - -#if defined(ADC_MULTIMODE_SUPPORT) - /* Set fields of ADC multimode */ - pADC_CommonInitStruct->Multimode = LL_ADC_MULTI_INDEPENDENT; - pADC_CommonInitStruct->MultiDMATransfer = LL_ADC_MULTI_REG_DMA_EACH_ADC; - pADC_CommonInitStruct->MultiTwoSamplingDelay = LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE; -#endif /* ADC_MULTIMODE_SUPPORT */ -} - -/** - * @brief De-initialize registers of the selected ADC instance - * to their default reset values. - * @note To reset all ADC instances quickly (perform a hard reset), - * use function @ref LL_ADC_CommonDeInit(). - * @note If this functions returns error status, it means that ADC instance - * is in an unknown state. - * In this case, perform a hard reset using high level - * clock source RCC ADC reset. - * Caution: On this STM32 series, if several ADC instances are available - * on the selected device, RCC ADC reset will reset - * all ADC instances belonging to the common ADC instance. - * Refer to function @ref LL_ADC_CommonDeInit(). - * @param ADCx ADC instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are de-initialized - * - ERROR: ADC registers are not de-initialized - */ -ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx) -{ - ErrorStatus status = SUCCESS; - - __IO uint32_t timeout_cpu_cycles = 0UL; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); - - /* Disable ADC instance if not already disabled. */ - if (LL_ADC_IsEnabled(ADCx) == 1UL) - { - /* Stop potential ADC conversion on going on ADC group regular. */ - if (LL_ADC_REG_IsConversionOngoing(ADCx) != 0UL) - { - if (LL_ADC_REG_IsStopConversionOngoing(ADCx) == 0UL) - { - LL_ADC_REG_StopConversion(ADCx); - } - } - - /* Stop potential ADC conversion on going on ADC group injected. */ - if (LL_ADC_INJ_IsConversionOngoing(ADCx) != 0UL) - { - if (LL_ADC_INJ_IsStopConversionOngoing(ADCx) == 0UL) - { - LL_ADC_INJ_StopConversion(ADCx); - } - } - - /* Wait for ADC conversions are effectively stopped */ - timeout_cpu_cycles = ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES; - while ((LL_ADC_REG_IsStopConversionOngoing(ADCx) - | LL_ADC_INJ_IsStopConversionOngoing(ADCx)) == 1UL) - { - timeout_cpu_cycles--; - if (timeout_cpu_cycles == 0UL) - { - /* Time-out error */ - status = ERROR; - break; - } - } - - /* Flush group injected contexts queue (register JSQR): */ - /* Note: Bit JQM must be set to empty the contexts queue (otherwise */ - /* contexts queue is maintained with the last active context). */ - LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); - - /* Disable the ADC instance */ - LL_ADC_Disable(ADCx); - - /* Wait for ADC instance is effectively disabled */ - timeout_cpu_cycles = ADC_TIMEOUT_DISABLE_CPU_CYCLES; - while (LL_ADC_IsDisableOngoing(ADCx) == 1UL) - { - timeout_cpu_cycles--; - if (timeout_cpu_cycles == 0UL) - { - /* Time-out error */ - status = ERROR; - break; - } - } - } - - /* Check whether ADC state is compliant with expected state */ - if (READ_BIT(ADCx->CR, - (ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART - | ADC_CR_ADDIS | ADC_CR_ADEN) - ) - == 0UL) - { - /* ========== Reset ADC registers ========== */ - /* Reset register IER */ - CLEAR_BIT(ADCx->IER, - (LL_ADC_IT_ADRDY - | LL_ADC_IT_EOC - | LL_ADC_IT_EOS - | LL_ADC_IT_OVR - | LL_ADC_IT_EOSMP - | LL_ADC_IT_JEOC - | LL_ADC_IT_JEOS - | LL_ADC_IT_JQOVF - | LL_ADC_IT_AWD1 - | LL_ADC_IT_AWD2 - | LL_ADC_IT_AWD3 - ) - ); - - /* Reset register ISR */ - SET_BIT(ADCx->ISR, - (LL_ADC_FLAG_ADRDY - | LL_ADC_FLAG_EOC - | LL_ADC_FLAG_EOS - | LL_ADC_FLAG_OVR - | LL_ADC_FLAG_EOSMP - | LL_ADC_FLAG_JEOC - | LL_ADC_FLAG_JEOS - | LL_ADC_FLAG_JQOVF - | LL_ADC_FLAG_AWD1 - | LL_ADC_FLAG_AWD2 - | LL_ADC_FLAG_AWD3 - ) - ); - - /* Reset register CR */ - /* - Bits ADC_CR_JADSTP, ADC_CR_ADSTP, ADC_CR_JADSTART, ADC_CR_ADSTART, */ - /* ADC_CR_ADCAL, ADC_CR_ADDIS, ADC_CR_ADEN are in */ - /* access mode "read-set": no direct reset applicable. */ - /* - Reset Calibration mode to default setting (single ended). */ - /* - Disable ADC internal voltage regulator. */ - /* - Enable ADC deep power down. */ - /* Note: ADC internal voltage regulator disable and ADC deep power */ - /* down enable are conditioned to ADC state disabled: */ - /* already done above. */ - CLEAR_BIT(ADCx->CR, ADC_CR_ADVREGEN | ADC_CR_ADCALDIF); - SET_BIT(ADCx->CR, ADC_CR_DEEPPWD); - - /* Reset register CFGR */ - MODIFY_REG(ADCx->CFGR, - (ADC_CFGR_AWD1CH | ADC_CFGR_JAUTO | ADC_CFGR_JAWD1EN - | ADC_CFGR_AWD1EN | ADC_CFGR_AWD1SGL | ADC_CFGR_JQM - | ADC_CFGR_JDISCEN | ADC_CFGR_DISCNUM | ADC_CFGR_DISCEN - | ADC_CFGR_AUTDLY | ADC_CFGR_CONT | ADC_CFGR_OVRMOD - | ADC_CFGR_EXTEN | ADC_CFGR_EXTSEL | ADC_CFGR_ALIGN - | ADC_CFGR_RES | ADC_CFGR_DMACFG | ADC_CFGR_DMAEN), - ADC_CFGR_JQDIS - ); - - /* Reset register CFGR2 */ - CLEAR_BIT(ADCx->CFGR2, - (ADC_CFGR2_ROVSM | ADC_CFGR2_TROVS | ADC_CFGR2_OVSS - | ADC_CFGR2_SWTRIG | ADC_CFGR2_BULB | ADC_CFGR2_SMPTRIG - | ADC_CFGR2_OVSR | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE) - ); - - /* Reset register SMPR1 */ - CLEAR_BIT(ADCx->SMPR1, - (ADC_SMPR1_SMP9 | ADC_SMPR1_SMP8 | ADC_SMPR1_SMP7 - | ADC_SMPR1_SMP6 | ADC_SMPR1_SMP5 | ADC_SMPR1_SMP4 - | ADC_SMPR1_SMP3 | ADC_SMPR1_SMP2 | ADC_SMPR1_SMP1) - ); - - /* Reset register SMPR2 */ - CLEAR_BIT(ADCx->SMPR2, - (ADC_SMPR2_SMP18 | ADC_SMPR2_SMP17 | ADC_SMPR2_SMP16 - | ADC_SMPR2_SMP15 | ADC_SMPR2_SMP14 | ADC_SMPR2_SMP13 - | ADC_SMPR2_SMP12 | ADC_SMPR2_SMP11 | ADC_SMPR2_SMP10) - ); - - /* Reset register TR1 */ - MODIFY_REG(ADCx->TR1, ADC_TR1_AWDFILT | ADC_TR1_HT1 | ADC_TR1_LT1, ADC_TR1_HT1); - - /* Reset register TR2 */ - MODIFY_REG(ADCx->TR2, ADC_TR2_HT2 | ADC_TR2_LT2, ADC_TR2_HT2); - - /* Reset register TR3 */ - MODIFY_REG(ADCx->TR3, ADC_TR3_HT3 | ADC_TR3_LT3, ADC_TR3_HT3); - - /* Reset register SQR1 */ - CLEAR_BIT(ADCx->SQR1, - (ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2 - | ADC_SQR1_SQ1 | ADC_SQR1_L) - ); - - /* Reset register SQR2 */ - CLEAR_BIT(ADCx->SQR2, - (ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 - | ADC_SQR2_SQ6 | ADC_SQR2_SQ5) - ); - - /* Reset register SQR3 */ - CLEAR_BIT(ADCx->SQR3, - (ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12 - | ADC_SQR3_SQ11 | ADC_SQR3_SQ10) - ); - - /* Reset register SQR4 */ - CLEAR_BIT(ADCx->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15); - - /* Reset register JSQR */ - CLEAR_BIT(ADCx->JSQR, - (ADC_JSQR_JL - | ADC_JSQR_JEXTSEL | ADC_JSQR_JEXTEN - | ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 - | ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1) - ); - - /* Reset register DR */ - /* Note: bits in access mode read only, no direct reset applicable */ - - /* Reset register OFR1 */ - CLEAR_BIT(ADCx->OFR1, - ADC_OFR1_OFFSET1_EN | ADC_OFR1_OFFSET1_CH | ADC_OFR1_OFFSET1 | ADC_OFR1_SATEN | ADC_OFR1_OFFSETPOS); - /* Reset register OFR2 */ - CLEAR_BIT(ADCx->OFR2, - ADC_OFR2_OFFSET2_EN | ADC_OFR2_OFFSET2_CH | ADC_OFR2_OFFSET2 | ADC_OFR2_SATEN | ADC_OFR2_OFFSETPOS); - /* Reset register OFR3 */ - CLEAR_BIT(ADCx->OFR3, - ADC_OFR3_OFFSET3_EN | ADC_OFR3_OFFSET3_CH | ADC_OFR3_OFFSET3 | ADC_OFR3_SATEN | ADC_OFR3_OFFSETPOS); - /* Reset register OFR4 */ - CLEAR_BIT(ADCx->OFR4, - ADC_OFR4_OFFSET4_EN | ADC_OFR4_OFFSET4_CH | ADC_OFR4_OFFSET4 | ADC_OFR4_SATEN | ADC_OFR4_OFFSETPOS); - - /* Reset registers JDR1, JDR2, JDR3, JDR4 */ - /* Note: bits in access mode read only, no direct reset applicable */ - - /* Reset register AWD2CR */ - CLEAR_BIT(ADCx->AWD2CR, ADC_AWD2CR_AWD2CH); - - /* Reset register AWD3CR */ - CLEAR_BIT(ADCx->AWD3CR, ADC_AWD3CR_AWD3CH); - - /* Reset register DIFSEL */ - CLEAR_BIT(ADCx->DIFSEL, ADC_DIFSEL_DIFSEL); - - /* Reset register CALFACT */ - CLEAR_BIT(ADCx->CALFACT, ADC_CALFACT_CALFACT_D | ADC_CALFACT_CALFACT_S); - } - else - { - /* ADC instance is in an unknown state */ - /* Need to performing a hard reset of ADC instance, using high level */ - /* clock source RCC ADC reset. */ - /* Caution: On this STM32 series, if several ADC instances are available */ - /* on the selected device, RCC ADC reset will reset */ - /* all ADC instances belonging to the common ADC instance. */ - /* Caution: On this STM32 series, if several ADC instances are available */ - /* on the selected device, RCC ADC reset will reset */ - /* all ADC instances belonging to the common ADC instance. */ - status = ERROR; - } - - return status; -} - -/** - * @brief Initialize some features of ADC instance. - * @note These parameters have an impact on ADC scope: ADC instance. - * Affects both group regular and group injected (availability - * of ADC group injected depends on STM32 series). - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Instance . - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 series. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - * @note After using this function, some other features must be configured - * using LL unitary functions. - * The minimum configuration remaining to be done is: - * - Set ADC group regular or group injected sequencer: - * map channel on the selected sequencer rank. - * Refer to function @ref LL_ADC_REG_SetSequencerRanks(). - * - Set ADC channel sampling time - * Refer to function LL_ADC_SetChannelSamplingTime(); - * @param ADCx ADC instance - * @param pADC_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are initialized - * - ERROR: ADC registers are not initialized - */ -ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, const LL_ADC_InitTypeDef *pADC_InitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); - - assert_param(IS_LL_ADC_RESOLUTION(pADC_InitStruct->Resolution)); - assert_param(IS_LL_ADC_DATA_ALIGN(pADC_InitStruct->DataAlignment)); - assert_param(IS_LL_ADC_LOW_POWER(pADC_InitStruct->LowPowerMode)); - - /* Note: Hardware constraint (refer to description of this function): */ - /* ADC instance must be disabled. */ - if (LL_ADC_IsEnabled(ADCx) == 0UL) - { - /* Configuration of ADC hierarchical scope: */ - /* - ADC instance */ - /* - Set ADC data resolution */ - /* - Set ADC conversion data alignment */ - /* - Set ADC low power mode */ - MODIFY_REG(ADCx->CFGR, - ADC_CFGR_RES - | ADC_CFGR_ALIGN - | ADC_CFGR_AUTDLY - , - pADC_InitStruct->Resolution - | pADC_InitStruct->DataAlignment - | pADC_InitStruct->LowPowerMode - ); - - } - else - { - /* Initialization error: ADC instance is not disabled. */ - status = ERROR; - } - - return status; -} - -/** - * @brief Set each @ref LL_ADC_InitTypeDef field to default value. - * @param pADC_InitStruct Pointer to a @ref LL_ADC_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_StructInit(LL_ADC_InitTypeDef *pADC_InitStruct) -{ - /* Set pADC_InitStruct fields to default values */ - /* Set fields of ADC instance */ - pADC_InitStruct->Resolution = LL_ADC_RESOLUTION_12B; - pADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT; - pADC_InitStruct->LowPowerMode = LL_ADC_LP_MODE_NONE; - -} - -/** - * @brief Initialize some features of ADC group regular. - * @note These parameters have an impact on ADC scope: ADC group regular. - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Group_Regular - * (functions with prefix "REG"). - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 series. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - * @note After using this function, other features must be configured - * using LL unitary functions. - * The minimum configuration remaining to be done is: - * - Set ADC group regular or group injected sequencer: - * map channel on the selected sequencer rank. - * Refer to function @ref LL_ADC_REG_SetSequencerRanks(). - * - Set ADC channel sampling time - * Refer to function LL_ADC_SetChannelSamplingTime(); - * @param ADCx ADC instance - * @param pADC_RegInitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are initialized - * - ERROR: ADC registers are not initialized - */ -ErrorStatus LL_ADC_REG_Init(ADC_TypeDef *ADCx, const LL_ADC_REG_InitTypeDef *pADC_RegInitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); - assert_param(IS_LL_ADC_REG_TRIG_SOURCE(pADC_RegInitStruct->TriggerSource)); - assert_param(IS_LL_ADC_REG_SEQ_SCAN_LENGTH(pADC_RegInitStruct->SequencerLength)); - if (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) - { - assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(pADC_RegInitStruct->SequencerDiscont)); - - /* ADC group regular continuous mode and discontinuous mode */ - /* can not be enabled simultenaeously */ - assert_param((pADC_RegInitStruct->ContinuousMode == LL_ADC_REG_CONV_SINGLE) - || (pADC_RegInitStruct->SequencerDiscont == LL_ADC_REG_SEQ_DISCONT_DISABLE)); - } - assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(pADC_RegInitStruct->ContinuousMode)); - assert_param(IS_LL_ADC_REG_DMA_TRANSFER(pADC_RegInitStruct->DMATransfer)); - assert_param(IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(pADC_RegInitStruct->Overrun)); - - /* Note: Hardware constraint (refer to description of this function): */ - /* ADC instance must be disabled. */ - if (LL_ADC_IsEnabled(ADCx) == 0UL) - { - /* Configuration of ADC hierarchical scope: */ - /* - ADC group regular */ - /* - Set ADC group regular trigger source */ - /* - Set ADC group regular sequencer length */ - /* - Set ADC group regular sequencer discontinuous mode */ - /* - Set ADC group regular continuous mode */ - /* - Set ADC group regular conversion data transfer: no transfer or */ - /* transfer by DMA, and DMA requests mode */ - /* - Set ADC group regular overrun behavior */ - /* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */ - /* setting of trigger source to SW start. */ - if (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) - { - MODIFY_REG(ADCx->CFGR, - ADC_CFGR_EXTSEL - | ADC_CFGR_EXTEN - | ADC_CFGR_DISCEN - | ADC_CFGR_DISCNUM - | ADC_CFGR_CONT - | ADC_CFGR_ADFCFG - | ADC_CFGR_DMAEN - | ADC_CFGR_DMACFG - | ADC_CFGR_OVRMOD - , - pADC_RegInitStruct->TriggerSource - | pADC_RegInitStruct->SequencerDiscont - | pADC_RegInitStruct->ContinuousMode - | pADC_RegInitStruct->DMATransfer - | pADC_RegInitStruct->Overrun - ); - } - else - { - MODIFY_REG(ADCx->CFGR, - ADC_CFGR_EXTSEL - | ADC_CFGR_EXTEN - | ADC_CFGR_DISCEN - | ADC_CFGR_DISCNUM - | ADC_CFGR_CONT - | ADC_CFGR_ADFCFG - | ADC_CFGR_DMAEN - | ADC_CFGR_DMACFG - | ADC_CFGR_OVRMOD - , - pADC_RegInitStruct->TriggerSource - | LL_ADC_REG_SEQ_DISCONT_DISABLE - | pADC_RegInitStruct->ContinuousMode - | pADC_RegInitStruct->DMATransfer - | pADC_RegInitStruct->Overrun - ); - } - - /* Set ADC group regular sequencer length and scan direction */ - LL_ADC_REG_SetSequencerLength(ADCx, pADC_RegInitStruct->SequencerLength); - } - else - { - /* Initialization error: ADC instance is not disabled. */ - status = ERROR; - } - return status; -} - -/** - * @brief Set each @ref LL_ADC_REG_InitTypeDef field to default value. - * @param pADC_RegInitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *pADC_RegInitStruct) -{ - /* Set pADC_RegInitStruct fields to default values */ - /* Set fields of ADC group regular */ - /* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */ - /* setting of trigger source to SW start. */ - pADC_RegInitStruct->TriggerSource = LL_ADC_REG_TRIG_SOFTWARE; - pADC_RegInitStruct->SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE; - pADC_RegInitStruct->SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE; - pADC_RegInitStruct->ContinuousMode = LL_ADC_REG_CONV_SINGLE; - pADC_RegInitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE; - pADC_RegInitStruct->Overrun = LL_ADC_REG_OVR_DATA_OVERWRITTEN; -} - -/** - * @brief Initialize some features of ADC group injected. - * @note These parameters have an impact on ADC scope: ADC group injected. - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Group_Regular - * (functions with prefix "INJ"). - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 series. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - * @note After using this function, other features must be configured - * using LL unitary functions. - * The minimum configuration remaining to be done is: - * - Set ADC group injected sequencer: - * map channel on the selected sequencer rank. - * Refer to function @ref LL_ADC_INJ_SetSequencerRanks(). - * - Set ADC channel sampling time - * Refer to function LL_ADC_SetChannelSamplingTime(); - * @note Caution if feature ADC group injected contexts queue is enabled - * (refer to with function @ref LL_ADC_INJ_SetQueueMode() ): - * using successively several times this function will appear as - * having no effect. - * To set several features of ADC group injected, use - * function @ref LL_ADC_INJ_ConfigQueueContext(). - * @param ADCx ADC instance - * @param pADC_InjInitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are initialized - * - ERROR: ADC registers are not initialized - */ -ErrorStatus LL_ADC_INJ_Init(ADC_TypeDef *ADCx, const LL_ADC_INJ_InitTypeDef *pADC_InjInitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); - assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(pADC_InjInitStruct->TriggerSource)); - assert_param(IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(pADC_InjInitStruct->SequencerLength)); - if (pADC_InjInitStruct->SequencerLength != LL_ADC_INJ_SEQ_SCAN_DISABLE) - { - assert_param(IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(pADC_InjInitStruct->SequencerDiscont)); - } - assert_param(IS_LL_ADC_INJ_TRIG_AUTO(pADC_InjInitStruct->TrigAuto)); - - /* Note: Hardware constraint (refer to description of this function): */ - /* ADC instance must be disabled. */ - if (LL_ADC_IsEnabled(ADCx) == 0UL) - { - /* Configuration of ADC hierarchical scope: */ - /* - ADC group injected */ - /* - Set ADC group injected trigger source */ - /* - Set ADC group injected sequencer length */ - /* - Set ADC group injected sequencer discontinuous mode */ - /* - Set ADC group injected conversion trigger: independent or */ - /* from ADC group regular */ - /* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */ - /* setting of trigger source to SW start. */ - if (pADC_InjInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) - { - MODIFY_REG(ADCx->CFGR, - ADC_CFGR_JDISCEN - | ADC_CFGR_JAUTO - , - pADC_InjInitStruct->SequencerDiscont - | pADC_InjInitStruct->TrigAuto - ); - } - else - { - MODIFY_REG(ADCx->CFGR, - ADC_CFGR_JDISCEN - | ADC_CFGR_JAUTO - , - LL_ADC_REG_SEQ_DISCONT_DISABLE - | pADC_InjInitStruct->TrigAuto - ); - } - - MODIFY_REG(ADCx->JSQR, - ADC_JSQR_JEXTSEL - | ADC_JSQR_JEXTEN - | ADC_JSQR_JL - , - pADC_InjInitStruct->TriggerSource - | pADC_InjInitStruct->SequencerLength - ); - } - else - { - /* Initialization error: ADC instance is not disabled. */ - status = ERROR; - } - return status; -} - -/** - * @brief Set each @ref LL_ADC_INJ_InitTypeDef field to default value. - * @param pADC_InjInitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_INJ_StructInit(LL_ADC_INJ_InitTypeDef *pADC_InjInitStruct) -{ - /* Set pADC_InjInitStruct fields to default values */ - /* Set fields of ADC group injected */ - pADC_InjInitStruct->TriggerSource = LL_ADC_INJ_TRIG_SOFTWARE; - pADC_InjInitStruct->SequencerLength = LL_ADC_INJ_SEQ_SCAN_DISABLE; - pADC_InjInitStruct->SequencerDiscont = LL_ADC_INJ_SEQ_DISCONT_DISABLE; - pADC_InjInitStruct->TrigAuto = LL_ADC_INJ_TRIG_INDEPENDENT; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* ADC1 || ADC2 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_adc.c + * @author MCD Application Team + * @brief ADC LL module driver + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_adc.h" +#include "stm32h7rsxx_ll_bus.h" + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (ADC1) || defined (ADC2) + +/** @addtogroup ADC_LL ADC + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup ADC_LL_Private_Constants + * @{ + */ + +/* Definitions of ADC hardware constraints delays */ +/* Note: Only ADC peripheral HW delays are defined in ADC LL driver driver, */ +/* not timeout values: */ +/* Timeout values for ADC operations are dependent to device clock */ +/* configuration (system clock versus ADC clock), */ +/* and therefore must be defined in user application. */ +/* Refer to @ref ADC_LL_EC_HW_DELAYS for description of ADC timeout */ +/* values definition. */ +/* Note: ADC timeout values are defined here in CPU cycles to be independent */ +/* of device clock setting. */ +/* In user application, ADC timeout values should be defined with */ +/* temporal values, in function of device clock settings. */ +/* Highest ratio CPU clock frequency vs ADC clock frequency: */ +/* - ADC clock from synchronous clock with AHB prescaler 512, */ +/* ADC prescaler 4. */ +/* Ratio max = 512 *4 = 2048 */ +/* - ADC clock from asynchronous clock (PLLP) with prescaler 256. */ +/* Highest CPU clock PLL (PLLR). */ +/* Ratio max = PLLRmax /PPLPmin * 256 = (VCO/2) / (VCO/31) * 256 */ +/* = 3968 */ +/* Unit: CPU cycles. */ +#define ADC_CLOCK_RATIO_VS_CPU_HIGHEST (3968UL) +#define ADC_TIMEOUT_DISABLE_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1UL) +#define ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1UL) + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ + +/** @addtogroup ADC_LL_Private_Macros + * @{ + */ + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* common to several ADC instances. */ +#define IS_LL_ADC_COMMON_CLOCK(__CLOCK__) \ + (((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV1) \ + || ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV2) \ + || ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV4) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV1) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV2) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV4) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV6) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV8) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV10) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV12) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV16) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV32) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV64) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV128) \ + || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV256) \ + ) + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* ADC instance. */ +#define IS_LL_ADC_RESOLUTION(__RESOLUTION__) \ + (((__RESOLUTION__) == LL_ADC_RESOLUTION_12B) \ + || ((__RESOLUTION__) == LL_ADC_RESOLUTION_10B) \ + || ((__RESOLUTION__) == LL_ADC_RESOLUTION_8B) \ + || ((__RESOLUTION__) == LL_ADC_RESOLUTION_6B) \ + ) + +#define IS_LL_ADC_DATA_ALIGN(__DATA_ALIGN__) \ + (((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_RIGHT) \ + || ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_LEFT) \ + ) + +#define IS_LL_ADC_LOW_POWER(__LOW_POWER__) \ + (((__LOW_POWER__) == LL_ADC_LP_MODE_NONE) \ + || ((__LOW_POWER__) == LL_ADC_LP_AUTOWAIT) \ + ) + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* ADC group regular */ +#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ + (((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM12_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM9_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_TRGO2) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM15_TRGO) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH4) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM1_CH1) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM2_CH1) \ + || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_LPTIM3_CH1) \ + ) + +#define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \ + (((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \ + || ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \ + ) + +#define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \ + (((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE) \ + || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_LIMITED) \ + || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \ + ) + +#define IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(__REG_OVR_DATA_BEHAVIOR__) \ + (((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_PRESERVED) \ + || ((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_OVERWRITTEN) \ + ) + +#define IS_LL_ADC_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \ + (((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_DISABLE) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS) \ + || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS) \ + ) + +#define IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \ + (((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_DISABLE) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_1RANK) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_2RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_3RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_4RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_5RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_6RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_7RANKS) \ + || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_8RANKS) \ + ) + +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* ADC group injected */ +#define IS_LL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \ + (((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO2) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM9_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM9_CH1) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH3) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH1) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM6_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM12_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM15_TRGO) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM1_CH2) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM2_CH2) \ + || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_LPTIM3_CH1) \ + ) + +#define IS_LL_ADC_INJ_TRIG_EXT_EDGE(__INJ_TRIG_EXT_EDGE__) \ + (((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_RISING) \ + || ((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_FALLING) \ + || ((__INJ_TRIG_EXT_EDGE__) == LL_ADC_INJ_TRIG_EXT_RISINGFALLING) \ + ) + +#define IS_LL_ADC_INJ_TRIG_AUTO(__INJ_TRIG_AUTO__) \ + (((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_INDEPENDENT) \ + || ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_FROM_GRP_REGULAR) \ + ) + +#define IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(__INJ_SEQ_SCAN_LENGTH__) \ + (((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_DISABLE) \ + || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS) \ + || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS) \ + || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS) \ + ) + +#define IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(__INJ_SEQ_DISCONT_MODE__) \ + (((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_DISABLE) \ + || ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_1RANK) \ + ) + +#if defined(ADC_MULTIMODE_SUPPORT) +/* Check of parameters for configuration of ADC hierarchical scope: */ +/* multimode. */ +#define IS_LL_ADC_MULTI_MODE(__MULTI_MODE__) \ + (((__MULTI_MODE__) == LL_ADC_MULTI_INDEPENDENT) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIMULT) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_SIMULT) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_ALTERN) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \ + || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INT_INJ_SIM) \ + ) + +#define IS_LL_ADC_MULTI_DMA_TRANSFER(__MULTI_DMA_TRANSFER__) \ + (((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_EACH_ADC) \ + || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_LIMIT_RES12_10B) \ + || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_LIMIT_RES8_6B) \ + || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_UNLMT_RES12_10B) \ + || ((__MULTI_DMA_TRANSFER__) == LL_ADC_MULTI_REG_DMA_UNLMT_RES8_6B) \ + ) + +#define IS_LL_ADC_MULTI_TWOSMP_DELAY(__MULTI_TWOSMP_DELAY__) \ + (((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_2CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_3CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_4CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_5CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_6CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_7CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_8CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_9CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_10CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_11CYCLES) \ + || ((__MULTI_TWOSMP_DELAY__) == LL_ADC_MULTI_TWOSMP_DELAY_12CYCLES) \ + ) + +#define IS_LL_ADC_MULTI_MASTER_SLAVE(__MULTI_MASTER_SLAVE__) \ + (((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER) \ + || ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_SLAVE) \ + || ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER_SLAVE) \ + ) + +#endif /* ADC_MULTIMODE_SUPPORT */ +/** + * @} + */ + + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup ADC_LL_Exported_Functions + * @{ + */ + +/** @addtogroup ADC_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize registers of all ADC instances belonging to + * the same ADC common instance to their default reset values. + * @note This function is performing a hard reset, using high level + * clock source RCC ADC reset. + * Caution: On this STM32 series, if several ADC instances are available + * on the selected device, RCC ADC reset will reset + * all ADC instances belonging to the common ADC instance. + * To de-initialize only 1 ADC instance, use + * function @ref LL_ADC_DeInit(). + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC common registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_ADC_CommonDeInit(const ADC_Common_TypeDef *ADCxy_COMMON) +{ + /* Check the parameters */ + assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); + + /* Prevent unused argument compilation warning */ + (void)(ADCxy_COMMON); + + /* Force reset of ADC clock (core clock) */ + LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_ADC12); + + /* Release reset of ADC clock (core clock) */ + LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_ADC12); + + return SUCCESS; +} + +/** + * @brief Initialize some features of ADC common parameters + * (all ADC instances belonging to the same ADC common instance) + * and multimode (for devices with several ADC instances available). + * @note The setting of ADC common parameters is conditioned to + * ADC instances state: + * All ADC instances belonging to the same ADC common instance + * must be disabled. + * @param ADCxy_COMMON ADC common instance + * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) + * @param pADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC common registers are initialized + * - ERROR: ADC common registers are not initialized + */ +ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, const LL_ADC_CommonInitTypeDef *pADC_CommonInitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); + assert_param(IS_LL_ADC_COMMON_CLOCK(pADC_CommonInitStruct->CommonClock)); + +#if defined(ADC_MULTIMODE_SUPPORT) + assert_param(IS_LL_ADC_MULTI_MODE(pADC_CommonInitStruct->Multimode)); + if (pADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT) + { + assert_param(IS_LL_ADC_MULTI_DMA_TRANSFER(pADC_CommonInitStruct->MultiDMATransfer)); + assert_param(IS_LL_ADC_MULTI_TWOSMP_DELAY(pADC_CommonInitStruct->MultiTwoSamplingDelay)); + } +#endif /* ADC_MULTIMODE_SUPPORT */ + + /* Note: Hardware constraint (refer to description of functions */ + /* "LL_ADC_SetCommonXXX()" and "LL_ADC_SetMultiXXX()"): */ + /* On this STM32 series, setting of these features is conditioned to */ + /* ADC state: */ + /* All ADC instances of the ADC common group must be disabled. */ + if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - common to several ADC */ + /* (all ADC instances belonging to the same ADC common instance) */ + /* - Set ADC clock (conversion clock) */ + /* - multimode (if several ADC instances available on the */ + /* selected device) */ + /* - Set ADC multimode configuration */ + /* - Set ADC multimode DMA transfer */ + /* - Set ADC multimode: delay between 2 sampling phases */ +#if defined(ADC_MULTIMODE_SUPPORT) + if (pADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT) + { + MODIFY_REG(ADCxy_COMMON->CCR, + ADC_CCR_CKMODE + | ADC_CCR_PRESC + | ADC_CCR_DUAL + | ADC_CCR_MDMA + | ADC_CCR_DELAY + , + pADC_CommonInitStruct->CommonClock + | pADC_CommonInitStruct->Multimode + | pADC_CommonInitStruct->MultiDMATransfer + | pADC_CommonInitStruct->MultiTwoSamplingDelay + ); + } + else + { + MODIFY_REG(ADCxy_COMMON->CCR, + ADC_CCR_CKMODE + | ADC_CCR_PRESC + | ADC_CCR_DUAL + | ADC_CCR_MDMA + | ADC_CCR_DELAY + , + pADC_CommonInitStruct->CommonClock + | LL_ADC_MULTI_INDEPENDENT + ); + } +#else + LL_ADC_SetCommonClock(ADCxy_COMMON, pADC_CommonInitStruct->CommonClock); +#endif /* ADC_MULTIMODE_SUPPORT */ + } + else + { + /* Initialization error: One or several ADC instances belonging to */ + /* the same ADC common instance are not disabled. */ + status = ERROR; + } + + return status; +} + +/** + * @brief Set each @ref LL_ADC_CommonInitTypeDef field to default value. + * @param pADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *pADC_CommonInitStruct) +{ + /* Set pADC_CommonInitStruct fields to default values */ + /* Set fields of ADC common */ + /* (all ADC instances belonging to the same ADC common instance) */ + pADC_CommonInitStruct->CommonClock = LL_ADC_CLOCK_SYNC_PCLK_DIV2; + +#if defined(ADC_MULTIMODE_SUPPORT) + /* Set fields of ADC multimode */ + pADC_CommonInitStruct->Multimode = LL_ADC_MULTI_INDEPENDENT; + pADC_CommonInitStruct->MultiDMATransfer = LL_ADC_MULTI_REG_DMA_EACH_ADC; + pADC_CommonInitStruct->MultiTwoSamplingDelay = LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE; +#endif /* ADC_MULTIMODE_SUPPORT */ +} + +/** + * @brief De-initialize registers of the selected ADC instance + * to their default reset values. + * @note To reset all ADC instances quickly (perform a hard reset), + * use function @ref LL_ADC_CommonDeInit(). + * @note If this functions returns error status, it means that ADC instance + * is in an unknown state. + * In this case, perform a hard reset using high level + * clock source RCC ADC reset. + * Caution: On this STM32 series, if several ADC instances are available + * on the selected device, RCC ADC reset will reset + * all ADC instances belonging to the common ADC instance. + * Refer to function @ref LL_ADC_CommonDeInit(). + * @param ADCx ADC instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are de-initialized + * - ERROR: ADC registers are not de-initialized + */ +ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx) +{ + ErrorStatus status = SUCCESS; + + __IO uint32_t timeout_cpu_cycles = 0UL; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(ADCx)); + + /* Disable ADC instance if not already disabled. */ + if (LL_ADC_IsEnabled(ADCx) == 1UL) + { + /* Stop potential ADC conversion on going on ADC group regular. */ + if (LL_ADC_REG_IsConversionOngoing(ADCx) != 0UL) + { + if (LL_ADC_REG_IsStopConversionOngoing(ADCx) == 0UL) + { + LL_ADC_REG_StopConversion(ADCx); + } + } + + /* Stop potential ADC conversion on going on ADC group injected. */ + if (LL_ADC_INJ_IsConversionOngoing(ADCx) != 0UL) + { + if (LL_ADC_INJ_IsStopConversionOngoing(ADCx) == 0UL) + { + LL_ADC_INJ_StopConversion(ADCx); + } + } + + /* Wait for ADC conversions are effectively stopped */ + timeout_cpu_cycles = ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES; + while ((LL_ADC_REG_IsStopConversionOngoing(ADCx) + | LL_ADC_INJ_IsStopConversionOngoing(ADCx)) == 1UL) + { + timeout_cpu_cycles--; + if (timeout_cpu_cycles == 0UL) + { + /* Time-out error */ + status = ERROR; + break; + } + } + + /* Flush group injected contexts queue (register JSQR): */ + /* Note: Bit JQM must be set to empty the contexts queue (otherwise */ + /* contexts queue is maintained with the last active context). */ + LL_ADC_INJ_SetQueueMode(ADCx, LL_ADC_INJ_QUEUE_2CONTEXTS_END_EMPTY); + + /* Disable the ADC instance */ + LL_ADC_Disable(ADCx); + + /* Wait for ADC instance is effectively disabled */ + timeout_cpu_cycles = ADC_TIMEOUT_DISABLE_CPU_CYCLES; + while (LL_ADC_IsDisableOngoing(ADCx) == 1UL) + { + timeout_cpu_cycles--; + if (timeout_cpu_cycles == 0UL) + { + /* Time-out error */ + status = ERROR; + break; + } + } + } + + /* Check whether ADC state is compliant with expected state */ + if (READ_BIT(ADCx->CR, + (ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART + | ADC_CR_ADDIS | ADC_CR_ADEN) + ) + == 0UL) + { + /* ========== Reset ADC registers ========== */ + /* Reset register IER */ + CLEAR_BIT(ADCx->IER, + (LL_ADC_IT_ADRDY + | LL_ADC_IT_EOC + | LL_ADC_IT_EOS + | LL_ADC_IT_OVR + | LL_ADC_IT_EOSMP + | LL_ADC_IT_JEOC + | LL_ADC_IT_JEOS + | LL_ADC_IT_JQOVF + | LL_ADC_IT_AWD1 + | LL_ADC_IT_AWD2 + | LL_ADC_IT_AWD3 + ) + ); + + /* Reset register ISR */ + SET_BIT(ADCx->ISR, + (LL_ADC_FLAG_ADRDY + | LL_ADC_FLAG_EOC + | LL_ADC_FLAG_EOS + | LL_ADC_FLAG_OVR + | LL_ADC_FLAG_EOSMP + | LL_ADC_FLAG_JEOC + | LL_ADC_FLAG_JEOS + | LL_ADC_FLAG_JQOVF + | LL_ADC_FLAG_AWD1 + | LL_ADC_FLAG_AWD2 + | LL_ADC_FLAG_AWD3 + ) + ); + + /* Reset register CR */ + /* - Bits ADC_CR_JADSTP, ADC_CR_ADSTP, ADC_CR_JADSTART, ADC_CR_ADSTART, */ + /* ADC_CR_ADCAL, ADC_CR_ADDIS, ADC_CR_ADEN are in */ + /* access mode "read-set": no direct reset applicable. */ + /* - Reset Calibration mode to default setting (single ended). */ + /* - Disable ADC internal voltage regulator. */ + /* - Enable ADC deep power down. */ + /* Note: ADC internal voltage regulator disable and ADC deep power */ + /* down enable are conditioned to ADC state disabled: */ + /* already done above. */ + CLEAR_BIT(ADCx->CR, ADC_CR_ADVREGEN | ADC_CR_ADCALDIF); + SET_BIT(ADCx->CR, ADC_CR_DEEPPWD); + + /* Reset register CFGR */ + MODIFY_REG(ADCx->CFGR, + (ADC_CFGR_AWD1CH | ADC_CFGR_JAUTO | ADC_CFGR_JAWD1EN + | ADC_CFGR_AWD1EN | ADC_CFGR_AWD1SGL | ADC_CFGR_JQM + | ADC_CFGR_JDISCEN | ADC_CFGR_DISCNUM | ADC_CFGR_DISCEN + | ADC_CFGR_AUTDLY | ADC_CFGR_CONT | ADC_CFGR_OVRMOD + | ADC_CFGR_EXTEN | ADC_CFGR_EXTSEL | ADC_CFGR_ALIGN + | ADC_CFGR_RES | ADC_CFGR_DMACFG | ADC_CFGR_DMAEN), + ADC_CFGR_JQDIS + ); + + /* Reset register CFGR2 */ + CLEAR_BIT(ADCx->CFGR2, + (ADC_CFGR2_ROVSM | ADC_CFGR2_TROVS | ADC_CFGR2_OVSS + | ADC_CFGR2_SWTRIG | ADC_CFGR2_BULB | ADC_CFGR2_SMPTRIG + | ADC_CFGR2_OVSR | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE) + ); + + /* Reset register SMPR1 */ + CLEAR_BIT(ADCx->SMPR1, + (ADC_SMPR1_SMP9 | ADC_SMPR1_SMP8 | ADC_SMPR1_SMP7 + | ADC_SMPR1_SMP6 | ADC_SMPR1_SMP5 | ADC_SMPR1_SMP4 + | ADC_SMPR1_SMP3 | ADC_SMPR1_SMP2 | ADC_SMPR1_SMP1) + ); + + /* Reset register SMPR2 */ + CLEAR_BIT(ADCx->SMPR2, + (ADC_SMPR2_SMP18 | ADC_SMPR2_SMP17 | ADC_SMPR2_SMP16 + | ADC_SMPR2_SMP15 | ADC_SMPR2_SMP14 | ADC_SMPR2_SMP13 + | ADC_SMPR2_SMP12 | ADC_SMPR2_SMP11 | ADC_SMPR2_SMP10) + ); + + /* Reset register TR1 */ + MODIFY_REG(ADCx->TR1, ADC_TR1_AWDFILT | ADC_TR1_HT1 | ADC_TR1_LT1, ADC_TR1_HT1); + + /* Reset register TR2 */ + MODIFY_REG(ADCx->TR2, ADC_TR2_HT2 | ADC_TR2_LT2, ADC_TR2_HT2); + + /* Reset register TR3 */ + MODIFY_REG(ADCx->TR3, ADC_TR3_HT3 | ADC_TR3_LT3, ADC_TR3_HT3); + + /* Reset register SQR1 */ + CLEAR_BIT(ADCx->SQR1, + (ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2 + | ADC_SQR1_SQ1 | ADC_SQR1_L) + ); + + /* Reset register SQR2 */ + CLEAR_BIT(ADCx->SQR2, + (ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 + | ADC_SQR2_SQ6 | ADC_SQR2_SQ5) + ); + + /* Reset register SQR3 */ + CLEAR_BIT(ADCx->SQR3, + (ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12 + | ADC_SQR3_SQ11 | ADC_SQR3_SQ10) + ); + + /* Reset register SQR4 */ + CLEAR_BIT(ADCx->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15); + + /* Reset register JSQR */ + CLEAR_BIT(ADCx->JSQR, + (ADC_JSQR_JL + | ADC_JSQR_JEXTSEL | ADC_JSQR_JEXTEN + | ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 + | ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1) + ); + + /* Reset register DR */ + /* Note: bits in access mode read only, no direct reset applicable */ + + /* Reset register OFR1 */ + CLEAR_BIT(ADCx->OFR1, + ADC_OFR1_OFFSET1_EN | ADC_OFR1_OFFSET1_CH | ADC_OFR1_OFFSET1 | ADC_OFR1_SATEN | ADC_OFR1_OFFSETPOS); + /* Reset register OFR2 */ + CLEAR_BIT(ADCx->OFR2, + ADC_OFR2_OFFSET2_EN | ADC_OFR2_OFFSET2_CH | ADC_OFR2_OFFSET2 | ADC_OFR2_SATEN | ADC_OFR2_OFFSETPOS); + /* Reset register OFR3 */ + CLEAR_BIT(ADCx->OFR3, + ADC_OFR3_OFFSET3_EN | ADC_OFR3_OFFSET3_CH | ADC_OFR3_OFFSET3 | ADC_OFR3_SATEN | ADC_OFR3_OFFSETPOS); + /* Reset register OFR4 */ + CLEAR_BIT(ADCx->OFR4, + ADC_OFR4_OFFSET4_EN | ADC_OFR4_OFFSET4_CH | ADC_OFR4_OFFSET4 | ADC_OFR4_SATEN | ADC_OFR4_OFFSETPOS); + + /* Reset registers JDR1, JDR2, JDR3, JDR4 */ + /* Note: bits in access mode read only, no direct reset applicable */ + + /* Reset register AWD2CR */ + CLEAR_BIT(ADCx->AWD2CR, ADC_AWD2CR_AWD2CH); + + /* Reset register AWD3CR */ + CLEAR_BIT(ADCx->AWD3CR, ADC_AWD3CR_AWD3CH); + + /* Reset register DIFSEL */ + CLEAR_BIT(ADCx->DIFSEL, ADC_DIFSEL_DIFSEL); + + /* Reset register CALFACT */ + CLEAR_BIT(ADCx->CALFACT, ADC_CALFACT_CALFACT_D | ADC_CALFACT_CALFACT_S); + } + else + { + /* ADC instance is in an unknown state */ + /* Need to performing a hard reset of ADC instance, using high level */ + /* clock source RCC ADC reset. */ + /* Caution: On this STM32 series, if several ADC instances are available */ + /* on the selected device, RCC ADC reset will reset */ + /* all ADC instances belonging to the common ADC instance. */ + /* Caution: On this STM32 series, if several ADC instances are available */ + /* on the selected device, RCC ADC reset will reset */ + /* all ADC instances belonging to the common ADC instance. */ + status = ERROR; + } + + return status; +} + +/** + * @brief Initialize some features of ADC instance. + * @note These parameters have an impact on ADC scope: ADC instance. + * Affects both group regular and group injected (availability + * of ADC group injected depends on STM32 series). + * Refer to corresponding unitary functions into + * @ref ADC_LL_EF_Configuration_ADC_Instance . + * @note The setting of these parameters by function @ref LL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all STM32 series. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + * @note After using this function, some other features must be configured + * using LL unitary functions. + * The minimum configuration remaining to be done is: + * - Set ADC group regular or group injected sequencer: + * map channel on the selected sequencer rank. + * Refer to function @ref LL_ADC_REG_SetSequencerRanks(). + * - Set ADC channel sampling time + * Refer to function LL_ADC_SetChannelSamplingTime(); + * @param ADCx ADC instance + * @param pADC_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are initialized + * - ERROR: ADC registers are not initialized + */ +ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, const LL_ADC_InitTypeDef *pADC_InitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(ADCx)); + + assert_param(IS_LL_ADC_RESOLUTION(pADC_InitStruct->Resolution)); + assert_param(IS_LL_ADC_DATA_ALIGN(pADC_InitStruct->DataAlignment)); + assert_param(IS_LL_ADC_LOW_POWER(pADC_InitStruct->LowPowerMode)); + + /* Note: Hardware constraint (refer to description of this function): */ + /* ADC instance must be disabled. */ + if (LL_ADC_IsEnabled(ADCx) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - ADC instance */ + /* - Set ADC data resolution */ + /* - Set ADC conversion data alignment */ + /* - Set ADC low power mode */ + MODIFY_REG(ADCx->CFGR, + ADC_CFGR_RES + | ADC_CFGR_ALIGN + | ADC_CFGR_AUTDLY + , + pADC_InitStruct->Resolution + | pADC_InitStruct->DataAlignment + | pADC_InitStruct->LowPowerMode + ); + + } + else + { + /* Initialization error: ADC instance is not disabled. */ + status = ERROR; + } + + return status; +} + +/** + * @brief Set each @ref LL_ADC_InitTypeDef field to default value. + * @param pADC_InitStruct Pointer to a @ref LL_ADC_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_ADC_StructInit(LL_ADC_InitTypeDef *pADC_InitStruct) +{ + /* Set pADC_InitStruct fields to default values */ + /* Set fields of ADC instance */ + pADC_InitStruct->Resolution = LL_ADC_RESOLUTION_12B; + pADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT; + pADC_InitStruct->LowPowerMode = LL_ADC_LP_MODE_NONE; + +} + +/** + * @brief Initialize some features of ADC group regular. + * @note These parameters have an impact on ADC scope: ADC group regular. + * Refer to corresponding unitary functions into + * @ref ADC_LL_EF_Configuration_ADC_Group_Regular + * (functions with prefix "REG"). + * @note The setting of these parameters by function @ref LL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all STM32 series. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + * @note After using this function, other features must be configured + * using LL unitary functions. + * The minimum configuration remaining to be done is: + * - Set ADC group regular or group injected sequencer: + * map channel on the selected sequencer rank. + * Refer to function @ref LL_ADC_REG_SetSequencerRanks(). + * - Set ADC channel sampling time + * Refer to function LL_ADC_SetChannelSamplingTime(); + * @param ADCx ADC instance + * @param pADC_RegInitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are initialized + * - ERROR: ADC registers are not initialized + */ +ErrorStatus LL_ADC_REG_Init(ADC_TypeDef *ADCx, const LL_ADC_REG_InitTypeDef *pADC_RegInitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(ADCx)); + assert_param(IS_LL_ADC_REG_TRIG_SOURCE(pADC_RegInitStruct->TriggerSource)); + assert_param(IS_LL_ADC_REG_SEQ_SCAN_LENGTH(pADC_RegInitStruct->SequencerLength)); + if (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) + { + assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(pADC_RegInitStruct->SequencerDiscont)); + + /* ADC group regular continuous mode and discontinuous mode */ + /* can not be enabled simultenaeously */ + assert_param((pADC_RegInitStruct->ContinuousMode == LL_ADC_REG_CONV_SINGLE) + || (pADC_RegInitStruct->SequencerDiscont == LL_ADC_REG_SEQ_DISCONT_DISABLE)); + } + assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(pADC_RegInitStruct->ContinuousMode)); + assert_param(IS_LL_ADC_REG_DMA_TRANSFER(pADC_RegInitStruct->DMATransfer)); + assert_param(IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(pADC_RegInitStruct->Overrun)); + + /* Note: Hardware constraint (refer to description of this function): */ + /* ADC instance must be disabled. */ + if (LL_ADC_IsEnabled(ADCx) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - ADC group regular */ + /* - Set ADC group regular trigger source */ + /* - Set ADC group regular sequencer length */ + /* - Set ADC group regular sequencer discontinuous mode */ + /* - Set ADC group regular continuous mode */ + /* - Set ADC group regular conversion data transfer: no transfer or */ + /* transfer by DMA, and DMA requests mode */ + /* - Set ADC group regular overrun behavior */ + /* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */ + /* setting of trigger source to SW start. */ + if (pADC_RegInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) + { + MODIFY_REG(ADCx->CFGR, + ADC_CFGR_EXTSEL + | ADC_CFGR_EXTEN + | ADC_CFGR_DISCEN + | ADC_CFGR_DISCNUM + | ADC_CFGR_CONT + | ADC_CFGR_ADFCFG + | ADC_CFGR_DMAEN + | ADC_CFGR_DMACFG + | ADC_CFGR_OVRMOD + , + pADC_RegInitStruct->TriggerSource + | pADC_RegInitStruct->SequencerDiscont + | pADC_RegInitStruct->ContinuousMode + | pADC_RegInitStruct->DMATransfer + | pADC_RegInitStruct->Overrun + ); + } + else + { + MODIFY_REG(ADCx->CFGR, + ADC_CFGR_EXTSEL + | ADC_CFGR_EXTEN + | ADC_CFGR_DISCEN + | ADC_CFGR_DISCNUM + | ADC_CFGR_CONT + | ADC_CFGR_ADFCFG + | ADC_CFGR_DMAEN + | ADC_CFGR_DMACFG + | ADC_CFGR_OVRMOD + , + pADC_RegInitStruct->TriggerSource + | LL_ADC_REG_SEQ_DISCONT_DISABLE + | pADC_RegInitStruct->ContinuousMode + | pADC_RegInitStruct->DMATransfer + | pADC_RegInitStruct->Overrun + ); + } + + /* Set ADC group regular sequencer length and scan direction */ + LL_ADC_REG_SetSequencerLength(ADCx, pADC_RegInitStruct->SequencerLength); + } + else + { + /* Initialization error: ADC instance is not disabled. */ + status = ERROR; + } + return status; +} + +/** + * @brief Set each @ref LL_ADC_REG_InitTypeDef field to default value. + * @param pADC_RegInitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *pADC_RegInitStruct) +{ + /* Set pADC_RegInitStruct fields to default values */ + /* Set fields of ADC group regular */ + /* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */ + /* setting of trigger source to SW start. */ + pADC_RegInitStruct->TriggerSource = LL_ADC_REG_TRIG_SOFTWARE; + pADC_RegInitStruct->SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE; + pADC_RegInitStruct->SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE; + pADC_RegInitStruct->ContinuousMode = LL_ADC_REG_CONV_SINGLE; + pADC_RegInitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE; + pADC_RegInitStruct->Overrun = LL_ADC_REG_OVR_DATA_OVERWRITTEN; +} + +/** + * @brief Initialize some features of ADC group injected. + * @note These parameters have an impact on ADC scope: ADC group injected. + * Refer to corresponding unitary functions into + * @ref ADC_LL_EF_Configuration_ADC_Group_Regular + * (functions with prefix "INJ"). + * @note The setting of these parameters by function @ref LL_ADC_Init() + * is conditioned to ADC state: + * ADC instance must be disabled. + * This condition is applied to all ADC features, for efficiency + * and compatibility over all STM32 series. However, the different + * features can be set under different ADC state conditions + * (setting possible with ADC enabled without conversion on going, + * ADC enabled with conversion on going, ...) + * Each feature can be updated afterwards with a unitary function + * and potentially with ADC in a different state than disabled, + * refer to description of each function for setting + * conditioned to ADC state. + * @note After using this function, other features must be configured + * using LL unitary functions. + * The minimum configuration remaining to be done is: + * - Set ADC group injected sequencer: + * map channel on the selected sequencer rank. + * Refer to function @ref LL_ADC_INJ_SetSequencerRanks(). + * - Set ADC channel sampling time + * Refer to function LL_ADC_SetChannelSamplingTime(); + * @note Caution if feature ADC group injected contexts queue is enabled + * (refer to with function @ref LL_ADC_INJ_SetQueueMode() ): + * using successively several times this function will appear as + * having no effect. + * To set several features of ADC group injected, use + * function @ref LL_ADC_INJ_ConfigQueueContext(). + * @param ADCx ADC instance + * @param pADC_InjInitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ADC registers are initialized + * - ERROR: ADC registers are not initialized + */ +ErrorStatus LL_ADC_INJ_Init(ADC_TypeDef *ADCx, const LL_ADC_INJ_InitTypeDef *pADC_InjInitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(ADCx)); + assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(pADC_InjInitStruct->TriggerSource)); + assert_param(IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(pADC_InjInitStruct->SequencerLength)); + if (pADC_InjInitStruct->SequencerLength != LL_ADC_INJ_SEQ_SCAN_DISABLE) + { + assert_param(IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(pADC_InjInitStruct->SequencerDiscont)); + } + assert_param(IS_LL_ADC_INJ_TRIG_AUTO(pADC_InjInitStruct->TrigAuto)); + + /* Note: Hardware constraint (refer to description of this function): */ + /* ADC instance must be disabled. */ + if (LL_ADC_IsEnabled(ADCx) == 0UL) + { + /* Configuration of ADC hierarchical scope: */ + /* - ADC group injected */ + /* - Set ADC group injected trigger source */ + /* - Set ADC group injected sequencer length */ + /* - Set ADC group injected sequencer discontinuous mode */ + /* - Set ADC group injected conversion trigger: independent or */ + /* from ADC group regular */ + /* Note: On this STM32 series, ADC trigger edge is set to value 0x0 by */ + /* setting of trigger source to SW start. */ + if (pADC_InjInitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) + { + MODIFY_REG(ADCx->CFGR, + ADC_CFGR_JDISCEN + | ADC_CFGR_JAUTO + , + pADC_InjInitStruct->SequencerDiscont + | pADC_InjInitStruct->TrigAuto + ); + } + else + { + MODIFY_REG(ADCx->CFGR, + ADC_CFGR_JDISCEN + | ADC_CFGR_JAUTO + , + LL_ADC_REG_SEQ_DISCONT_DISABLE + | pADC_InjInitStruct->TrigAuto + ); + } + + MODIFY_REG(ADCx->JSQR, + ADC_JSQR_JEXTSEL + | ADC_JSQR_JEXTEN + | ADC_JSQR_JL + , + pADC_InjInitStruct->TriggerSource + | pADC_InjInitStruct->SequencerLength + ); + } + else + { + /* Initialization error: ADC instance is not disabled. */ + status = ERROR; + } + return status; +} + +/** + * @brief Set each @ref LL_ADC_INJ_InitTypeDef field to default value. + * @param pADC_InjInitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_ADC_INJ_StructInit(LL_ADC_INJ_InitTypeDef *pADC_InjInitStruct) +{ + /* Set pADC_InjInitStruct fields to default values */ + /* Set fields of ADC group injected */ + pADC_InjInitStruct->TriggerSource = LL_ADC_INJ_TRIG_SOFTWARE; + pADC_InjInitStruct->SequencerLength = LL_ADC_INJ_SEQ_SCAN_DISABLE; + pADC_InjInitStruct->SequencerDiscont = LL_ADC_INJ_SEQ_DISCONT_DISABLE; + pADC_InjInitStruct->TrigAuto = LL_ADC_INJ_TRIG_INDEPENDENT; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* ADC1 || ADC2 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_cordic.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_cordic.c index b6f1b4eca..f671f2fbb 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_cordic.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_cordic.c @@ -1,102 +1,102 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_cordic.c - * @author MCD Application Team - * @brief CORDIC LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_cordic.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined(CORDIC) - -/** @addtogroup CORDIC_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup CORDIC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup CORDIC_LL_EF_Init - * @{ - */ - -/** - * @brief De-Initialize CORDIC peripheral registers to their default reset values. - * @param CORDICx CORDIC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: CORDIC registers are de-initialized - * - ERROR: CORDIC registers are not de-initialized - */ -ErrorStatus LL_CORDIC_DeInit(const CORDIC_TypeDef *CORDICx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_CORDIC_ALL_INSTANCE(CORDICx)); - - if (CORDICx == CORDIC) - { - /* Force CORDIC reset */ - LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_CORDIC); - - /* Release CORDIC reset */ - LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_CORDIC); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined(CORDIC) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_cordic.c + * @author MCD Application Team + * @brief CORDIC LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_cordic.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined(CORDIC) + +/** @addtogroup CORDIC_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CORDIC_LL_Exported_Functions + * @{ + */ + +/** @addtogroup CORDIC_LL_EF_Init + * @{ + */ + +/** + * @brief De-Initialize CORDIC peripheral registers to their default reset values. + * @param CORDICx CORDIC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: CORDIC registers are de-initialized + * - ERROR: CORDIC registers are not de-initialized + */ +ErrorStatus LL_CORDIC_DeInit(const CORDIC_TypeDef *CORDICx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_CORDIC_ALL_INSTANCE(CORDICx)); + + if (CORDICx == CORDIC) + { + /* Force CORDIC reset */ + LL_AHB2_GRP1_ForceReset(LL_AHB2_GRP1_PERIPH_CORDIC); + + /* Release CORDIC reset */ + LL_AHB2_GRP1_ReleaseReset(LL_AHB2_GRP1_PERIPH_CORDIC); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(CORDIC) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_crc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_crc.c index f5f45cca3..b11a4d38c 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_crc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_crc.c @@ -1,103 +1,103 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_crc.c - * @author MCD Application Team - * @brief CRC LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_crc.h" -#include "stm32h7rsxx_ll_bus.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (CRC) - -/** @addtogroup CRC_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup CRC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup CRC_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize CRC registers (Registers restored to their default values). - * @param CRCx CRC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: CRC registers are de-initialized - * - ERROR: CRC registers are not de-initialized - */ -ErrorStatus LL_CRC_DeInit(const CRC_TypeDef *CRCx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_CRC_ALL_INSTANCE(CRCx)); - - if (CRCx == CRC) - { - /* Force CRC reset */ - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_CRC); - - /* Release CRC reset */ - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_CRC); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined (CRC) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_crc.c + * @author MCD Application Team + * @brief CRC LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_crc.h" +#include "stm32h7rsxx_ll_bus.h" + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (CRC) + +/** @addtogroup CRC_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CRC_LL_Exported_Functions + * @{ + */ + +/** @addtogroup CRC_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize CRC registers (Registers restored to their default values). + * @param CRCx CRC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: CRC registers are de-initialized + * - ERROR: CRC registers are not de-initialized + */ +ErrorStatus LL_CRC_DeInit(const CRC_TypeDef *CRCx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_CRC_ALL_INSTANCE(CRCx)); + + if (CRCx == CRC) + { + /* Force CRC reset */ + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_CRC); + + /* Release CRC reset */ + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_CRC); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (CRC) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma.c index 6a3ea567d..e17181964 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma.c @@ -1,1195 +1,1194 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_dma.c - * @author MCD Application Team - * @brief DMA LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### LL DMA driver acronyms ##### - ============================================================================== - [..] Acronyms table : - ========================================= - || Acronym || || - ========================================= - || SRC || Source || - || DEST || Destination || - || ADDR || Address || - || ADDRS || Addresses || - || INC || Increment / Incremented || - || DEC || Decrement / Decremented || - || BLK || Block || - || RPT || Repeat / Repeated || - || TRIG || Trigger || - ========================================= - @endverbatim - ****************************************************************************** - */ - -#if defined (USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_dma.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if (defined (GPDMA1) || defined (HPDMA1)) - -/** @addtogroup DMA_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ - -/** @addtogroup DMA_LL_Private_Macros - * @{ - */ -#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, Channel) ((((INSTANCE) == HPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_0) || \ - ((Channel) == LL_DMA_CHANNEL_1) || \ - ((Channel) == LL_DMA_CHANNEL_2) || \ - ((Channel) == LL_DMA_CHANNEL_3) || \ - ((Channel) == LL_DMA_CHANNEL_4) || \ - ((Channel) == LL_DMA_CHANNEL_5) || \ - ((Channel) == LL_DMA_CHANNEL_6) || \ - ((Channel) == LL_DMA_CHANNEL_7) || \ - ((Channel) == LL_DMA_CHANNEL_8) || \ - ((Channel) == LL_DMA_CHANNEL_9) || \ - ((Channel) == LL_DMA_CHANNEL_10) || \ - ((Channel) == LL_DMA_CHANNEL_11) || \ - ((Channel) == LL_DMA_CHANNEL_12) || \ - ((Channel) == LL_DMA_CHANNEL_13) || \ - ((Channel) == LL_DMA_CHANNEL_14) || \ - ((Channel) == LL_DMA_CHANNEL_15) || \ - ((Channel) == LL_DMA_CHANNEL_ALL))) || \ - (((INSTANCE) == GPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_0) || \ - ((Channel) == LL_DMA_CHANNEL_1) || \ - ((Channel) == LL_DMA_CHANNEL_2) || \ - ((Channel) == LL_DMA_CHANNEL_3) || \ - ((Channel) == LL_DMA_CHANNEL_4) || \ - ((Channel) == LL_DMA_CHANNEL_5) || \ - ((Channel) == LL_DMA_CHANNEL_6) || \ - ((Channel) == LL_DMA_CHANNEL_7) || \ - ((Channel) == LL_DMA_CHANNEL_8) || \ - ((Channel) == LL_DMA_CHANNEL_9) || \ - ((Channel) == LL_DMA_CHANNEL_10) || \ - ((Channel) == LL_DMA_CHANNEL_11) || \ - ((Channel) == LL_DMA_CHANNEL_12) || \ - ((Channel) == LL_DMA_CHANNEL_13) || \ - ((Channel) == LL_DMA_CHANNEL_14) || \ - ((Channel) == LL_DMA_CHANNEL_15) || \ - ((Channel) == LL_DMA_CHANNEL_ALL)))) - -#define IS_LL_HPDMA_CHANNEL_INSTANCE(INSTANCE, Channel) (((INSTANCE) == HPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_0) || \ - ((Channel) == LL_DMA_CHANNEL_1) || \ - ((Channel) == LL_DMA_CHANNEL_2) || \ - ((Channel) == LL_DMA_CHANNEL_3) || \ - ((Channel) == LL_DMA_CHANNEL_4) || \ - ((Channel) == LL_DMA_CHANNEL_5) || \ - ((Channel) == LL_DMA_CHANNEL_6) || \ - ((Channel) == LL_DMA_CHANNEL_7) || \ - ((Channel) == LL_DMA_CHANNEL_8) || \ - ((Channel) == LL_DMA_CHANNEL_9) || \ - ((Channel) == LL_DMA_CHANNEL_10) || \ - ((Channel) == LL_DMA_CHANNEL_11) || \ - ((Channel) == LL_DMA_CHANNEL_12) || \ - ((Channel) == LL_DMA_CHANNEL_13) || \ - ((Channel) == LL_DMA_CHANNEL_14) || \ - ((Channel) == LL_DMA_CHANNEL_15))) - -#define IS_LL_GPDMA_CHANNEL_INSTANCE(INSTANCE, Channel) (((INSTANCE) == GPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_0) || \ - ((Channel) == LL_DMA_CHANNEL_1) || \ - ((Channel) == LL_DMA_CHANNEL_2) || \ - ((Channel) == LL_DMA_CHANNEL_3) || \ - ((Channel) == LL_DMA_CHANNEL_4) || \ - ((Channel) == LL_DMA_CHANNEL_5) || \ - ((Channel) == LL_DMA_CHANNEL_6) || \ - ((Channel) == LL_DMA_CHANNEL_7) || \ - ((Channel) == LL_DMA_CHANNEL_8) || \ - ((Channel) == LL_DMA_CHANNEL_9) || \ - ((Channel) == LL_DMA_CHANNEL_10) || \ - ((Channel) == LL_DMA_CHANNEL_11) || \ - ((Channel) == LL_DMA_CHANNEL_12) || \ - ((Channel) == LL_DMA_CHANNEL_13) || \ - ((Channel) == LL_DMA_CHANNEL_14) || \ - ((Channel) == LL_DMA_CHANNEL_15))) - -#define IS_LL_DMA_2D_CHANNEL_INSTANCE(INSTANCE, Channel) ((((INSTANCE) == HPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_12) || \ - ((Channel) == LL_DMA_CHANNEL_13) || \ - ((Channel) == LL_DMA_CHANNEL_14) || \ - ((Channel) == LL_DMA_CHANNEL_15))) || \ - (((INSTANCE) == GPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_12) || \ - ((Channel) == LL_DMA_CHANNEL_13) || \ - ((Channel) == LL_DMA_CHANNEL_14) || \ - ((Channel) == LL_DMA_CHANNEL_15)))) - -#define IS_LL_DMA_MODE(__VALUE__) (((__VALUE__) == LL_DMA_NORMAL) || \ - ((__VALUE__) == LL_DMA_PFCTRL)) - -#define IS_LL_DMA_PFREQ_INSTANCE(INSTANCE, Channel) ((((INSTANCE) == HPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_15))) || \ - (((INSTANCE) == GPDMA1) && \ - (((Channel) == LL_DMA_CHANNEL_0) || \ - ((Channel) == LL_DMA_CHANNEL_15)))) - -#define IS_LL_DMA_DIRECTION(__VALUE__) (((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_MEMORY) || \ - ((__VALUE__) == LL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \ - ((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_PERIPH)) - -#define IS_LL_DMA_DATA_ALIGNMENT(__VALUE__) (((__VALUE__) == LL_DMA_DATA_ALIGN_ZEROPADD) || \ - ((__VALUE__) == LL_DMA_DATA_ALIGN_SIGNEXTPADD) || \ - ((__VALUE__) == LL_DMA_DATA_PACK_UNPACK)) - -#define IS_LL_DMA_BURST_LENGTH(__VALUE__) (((__VALUE__) > 0U) && ((__VALUE__) <= 64U)) - -#define IS_LL_DMA_SRC_DATA_WIDTH(__VALUE__) (((__VALUE__) == LL_DMA_SRC_DATAWIDTH_BYTE) || \ - ((__VALUE__) == LL_DMA_SRC_DATAWIDTH_HALFWORD) || \ - ((__VALUE__) == LL_DMA_SRC_DATAWIDTH_WORD) || \ - ((__VALUE__) == LL_DMA_SRC_DATAWIDTH_DOUBLEWORD)) - -#define IS_LL_DMA_DEST_DATA_WIDTH(__VALUE__) (((__VALUE__) == LL_DMA_DEST_DATAWIDTH_BYTE) || \ - ((__VALUE__) == LL_DMA_DEST_DATAWIDTH_HALFWORD) || \ - ((__VALUE__) == LL_DMA_DEST_DATAWIDTH_WORD) || \ - ((__VALUE__) == LL_DMA_DEST_DATAWIDTH_DOUBLEWORD)) - -#define IS_LL_DMA_SRC_INCREMENT_MODE(__VALUE__) (((__VALUE__) == LL_DMA_SRC_FIXED) || \ - ((__VALUE__) == LL_DMA_SRC_INCREMENT)) - -#define IS_LL_DMA_DEST_INCREMENT_MODE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_FIXED) || \ - ((__VALUE__) == LL_DMA_DEST_INCREMENT)) - -#define IS_LL_DMA_PRIORITY(__VALUE__) (((__VALUE__) == LL_DMA_LOW_PRIORITY_LOW_WEIGHT) || \ - ((__VALUE__) == LL_DMA_LOW_PRIORITY_MID_WEIGHT) || \ - ((__VALUE__) == LL_DMA_LOW_PRIORITY_HIGH_WEIGHT) || \ - ((__VALUE__) == LL_DMA_HIGH_PRIORITY)) - -#define IS_LL_DMA_BLK_DATALENGTH(__VALUE__) ((__VALUE__) <= 0xFFFFU) - -#define IS_LL_DMA_BLK_REPEATCOUNT(__VALUE__) ((__VALUE__) <= 0x0EFFU) - -#define IS_LL_DMA_TRIGGER_MODE(__VALUE__) (((__VALUE__) == LL_DMA_TRIGM_BLK_TRANSFER) || \ - ((__VALUE__) == LL_DMA_TRIGM_RPT_BLK_TRANSFER) || \ - ((__VALUE__) == LL_DMA_TRIGM_LLI_LINK_TRANSFER) || \ - ((__VALUE__) == LL_DMA_TRIGM_SINGLBURST_TRANSFER )) - -#define IS_LL_DMA_TRIGGER_POLARITY(__VALUE__) (((__VALUE__) == LL_DMA_TRIG_POLARITY_MASKED) || \ - ((__VALUE__) == LL_DMA_TRIG_POLARITY_RISING) || \ - ((__VALUE__) == LL_DMA_TRIG_POLARITY_FALLING)) - -#define IS_LL_DMA_BLKHW_REQUEST(__VALUE__) (((__VALUE__) == LL_DMA_HWREQUEST_SINGLEBURST) || \ - ((__VALUE__) == LL_DMA_HWREQUEST_BLK)) - -#define IS_LL_DMA_TRIGGER_SELECTION(__VALUE__) ((__VALUE__) <= LL_GPDMA1_TRIGGER_TIM15_TRGO) - -#define IS_LL_DMA_REQUEST_SELECTION(__VALUE__) ((__VALUE__) <= LL_GPDMA1_REQUEST_I3C1_RS) - -#define IS_LL_DMA_TRANSFER_EVENT_MODE(__VALUE__) (((__VALUE__) == LL_DMA_TCEM_BLK_TRANSFER) || \ - ((__VALUE__) == LL_DMA_TCEM_RPT_BLK_TRANSFER) || \ - ((__VALUE__) == LL_DMA_TCEM_EACH_LLITEM_TRANSFER) || \ - ((__VALUE__) == LL_DMA_TCEM_LAST_LLITEM_TRANSFER)) - -#define IS_LL_DMA_DEST_WORD_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_WORD_PRESERVE) || \ - ((__VALUE__) == LL_DMA_DEST_WORD_EXCHANGE)) - -#define IS_LL_DMA_DEST_HALFWORD_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_HALFWORD_PRESERVE) || \ - ((__VALUE__) == LL_DMA_DEST_HALFWORD_EXCHANGE)) - -#define IS_LL_DMA_DEST_BYTE_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_BYTE_PRESERVE) || \ - ((__VALUE__) == LL_DMA_DEST_BYTE_EXCHANGE)) - -#define IS_LL_DMA_SRC_BYTE_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_SRC_BYTE_PRESERVE) || \ - ((__VALUE__) == LL_DMA_SRC_BYTE_EXCHANGE)) - -#define IS_LL_DMA_LINK_ALLOCATED_PORT(__VALUE__) (((__VALUE__) == LL_DMA_LINK_ALLOCATED_PORT0) || \ - ((__VALUE__) == LL_DMA_LINK_ALLOCATED_PORT1)) - -#define IS_LL_DMA_SRC_ALLOCATED_PORT(__VALUE__) (((__VALUE__) == LL_DMA_SRC_ALLOCATED_PORT0) || \ - ((__VALUE__) == LL_DMA_SRC_ALLOCATED_PORT1)) - -#define IS_LL_DMA_DEST_ALLOCATED_PORT(__VALUE__) (((__VALUE__) == LL_DMA_DEST_ALLOCATED_PORT0) || \ - ((__VALUE__) == LL_DMA_DEST_ALLOCATED_PORT1)) - -#define IS_LL_DMA_LINK_STEP_MODE(__VALUE__) (((__VALUE__) == LL_DMA_LSM_FULL_EXECUTION) || \ - ((__VALUE__) == LL_DMA_LSM_1LINK_EXECUTION)) - -#define IS_LL_DMA_BURST_SRC_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BURST_SRC_ADDR_INCREMENT) || \ - ((__VALUE__) == LL_DMA_BURST_SRC_ADDR_DECREMENT)) - -#define IS_LL_DMA_BURST_DEST_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BURST_DEST_ADDR_INCREMENT) || \ - ((__VALUE__) == LL_DMA_BURST_DEST_ADDR_DECREMENT)) - -#define IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(__VALUE__) ((__VALUE__) <= 0x1FFFU) - -#define IS_LL_DMA_BLKRPT_SRC_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BLKRPT_SRC_ADDR_INCREMENT) || \ - ((__VALUE__) == LL_DMA_BLKRPT_SRC_ADDR_DECREMENT)) - -#define IS_LL_DMA_BLKRPT_DEST_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BLKRPT_DEST_ADDR_INCREMENT) || \ - ((__VALUE__) == LL_DMA_BLKRPT_DEST_ADDR_DECREMENT)) - -#define IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(__VALUE__) ((__VALUE__) <= 0xFFFFU) - -#define IS_LL_DMA_LINK_BASEADDR(__VALUE__) (((__VALUE__) & 0xFFFFU) == 0U) - -#define IS_LL_DMA_LINK_ADDR_OFFSET(__VALUE__) (((__VALUE__) & 0x03U) == 0U) - -#define IS_LL_DMA_LINK_UPDATE_REGISTERS(__VALUE__) ((((__VALUE__) & 0x01FE0000U) == 0U) && ((__VALUE__) != 0U)) - -#define IS_LL_DMA_LINK_NODETYPE(__VALUE__) (((__VALUE__) == LL_DMA_HPDMA_2D_NODE) || \ - ((__VALUE__) == LL_DMA_HPDMA_LINEAR_NODE) || \ - ((__VALUE__) == LL_DMA_GPDMA_2D_NODE) || \ - ((__VALUE__) == LL_DMA_GPDMA_LINEAR_NODE)) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @addtogroup DMA_LL_Exported_Functions - * @{ - */ - -/** @addtogroup DMA_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the DMA registers to their default reset values. - * @note This API is used for all available DMA channels. - * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use - * helper macros : - * @arg @ref LL_DMA_GET_INSTANCE - * @arg @ref LL_DMA_GET_CHANNEL - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_0 - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @arg @ref LL_DMA_CHANNEL_8 - * @arg @ref LL_DMA_CHANNEL_9 - * @arg @ref LL_DMA_CHANNEL_10 - * @arg @ref LL_DMA_CHANNEL_11 - * @arg @ref LL_DMA_CHANNEL_12 - * @arg @ref LL_DMA_CHANNEL_13 - * @arg @ref LL_DMA_CHANNEL_14 - * @arg @ref LL_DMA_CHANNEL_15 - * @retval An ErrorStatus enumeration value: - * - SUCCESS : DMA registers are de-initialized. - * - ERROR : DMA registers are not de-initialized. - */ -uint32_t LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) -{ - DMA_Channel_TypeDef *tmp; - ErrorStatus status = SUCCESS; - - /* Check the DMA Instance DMAx and Channel parameters */ - assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); - - if (Channel == LL_DMA_CHANNEL_ALL) - { - if (DMAx == GPDMA1) - { - /* Force reset of DMA clock */ - LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_GPDMA1); - - /* Release reset of DMA clock */ - LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_GPDMA1); - } - else - { - /* Force reset of DMA clock */ - LL_AHB5_GRP1_ForceReset(LL_AHB5_GRP1_PERIPH_HPDMA1); - - /* Release reset of DMA clock */ - LL_AHB5_GRP1_ReleaseReset(LL_AHB5_GRP1_PERIPH_HPDMA1); - } - } - else - { - /* Get the DMA Channel Instance */ - tmp = (DMA_Channel_TypeDef *)(LL_DMA_GET_CHANNEL_INSTANCE(DMAx, Channel)); - - /* Suspend DMA channel */ - LL_DMA_SuspendChannel(DMAx, Channel); - - /* Disable the selected Channel */ - LL_DMA_ResetChannel(DMAx, Channel); - - /* Reset DMAx_Channely control register */ - LL_DMA_WriteReg(tmp, CLBAR, 0U); - - /* Reset DMAx_Channely control register */ - LL_DMA_WriteReg(tmp, CCR, 0U); - - /* Reset DMAx_Channely Configuration register */ - LL_DMA_WriteReg(tmp, CTR1, 0U); - - /* Reset DMAx_Channely transfer register 2 */ - LL_DMA_WriteReg(tmp, CTR2, 0U); - - /* Reset DMAx_Channely block number of data register */ - LL_DMA_WriteReg(tmp, CBR1, 0U); - - /* Reset DMAx_Channely source address register */ - LL_DMA_WriteReg(tmp, CSAR, 0U); - - /* Reset DMAx_Channely destination address register */ - LL_DMA_WriteReg(tmp, CDAR, 0U); - - /* Check DMA channel */ - if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) - { - /* Reset DMAx_Channely transfer register 3 */ - LL_DMA_WriteReg(tmp, CTR3, 0U); - - /* Reset DMAx_Channely Block register 2 */ - LL_DMA_WriteReg(tmp, CBR2, 0U); - } - - /* Reset DMAx_Channely Linked list address register */ - LL_DMA_WriteReg(tmp, CLLR, 0U); - - /* Reset DMAx_Channely pending flags */ - LL_DMA_WriteReg(tmp, CFCR, 0x00003F00U); - - /* Reset DMAx_Channely attribute */ - LL_DMA_DisableChannelPrivilege(DMAx, Channel); - - } - - return (uint32_t)status; -} - -/** - * @brief Initialize the DMA registers according to the specified parameters - * in DMA_InitStruct. - * @note This API is used for all available DMA channels. - * @note A software request transfer can be done once programming the direction - * field in memory to memory value. - * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use - * helper macros : - * @arg @ref LL_DMA_GET_INSTANCE - * @arg @ref LL_DMA_GET_CHANNEL - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_0 - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @arg @ref LL_DMA_CHANNEL_8 - * @arg @ref LL_DMA_CHANNEL_9 - * @arg @ref LL_DMA_CHANNEL_10 - * @arg @ref LL_DMA_CHANNEL_11 - * @arg @ref LL_DMA_CHANNEL_12 - * @arg @ref LL_DMA_CHANNEL_13 - * @arg @ref LL_DMA_CHANNEL_14 - * @arg @ref LL_DMA_CHANNEL_15 - * @param DMA_InitStruct pointer to a @ref LL_DMA_InitTypeDef structure. - * @retval An ErrorStatus enumeration value: - * - SUCCESS : DMA registers are initialized. - * - ERROR : Not applicable. - */ -uint32_t LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitTypeDef *DMA_InitStruct) -{ - /* Check the DMA Instance DMAx and Channel parameters*/ - assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); - - /* Check the DMA parameters from DMA_InitStruct */ - assert_param(IS_LL_DMA_DIRECTION(DMA_InitStruct->Direction)); - - /* Check direction */ - if (DMA_InitStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) - { - assert_param(IS_LL_DMA_REQUEST_SELECTION(DMA_InitStruct->Request)); - } - - assert_param(IS_LL_DMA_DATA_ALIGNMENT(DMA_InitStruct->DataAlignment)); - assert_param(IS_LL_DMA_SRC_DATA_WIDTH(DMA_InitStruct->SrcDataWidth)); - assert_param(IS_LL_DMA_DEST_DATA_WIDTH(DMA_InitStruct->DestDataWidth)); - assert_param(IS_LL_DMA_SRC_INCREMENT_MODE(DMA_InitStruct->SrcIncMode)); - assert_param(IS_LL_DMA_DEST_INCREMENT_MODE(DMA_InitStruct->DestIncMode)); - assert_param(IS_LL_DMA_PRIORITY(DMA_InitStruct->Priority)); - assert_param(IS_LL_DMA_BLK_DATALENGTH(DMA_InitStruct->BlkDataLength)); - assert_param(IS_LL_DMA_TRIGGER_POLARITY(DMA_InitStruct->TriggerPolarity)); - assert_param(IS_LL_DMA_BLKHW_REQUEST(DMA_InitStruct->BlkHWRequest)); - assert_param(IS_LL_DMA_TRANSFER_EVENT_MODE(DMA_InitStruct->TransferEventMode)); - assert_param(IS_LL_DMA_LINK_STEP_MODE(DMA_InitStruct->LinkStepMode)); - assert_param(IS_LL_DMA_LINK_BASEADDR(DMA_InitStruct->LinkedListBaseAddr)); - assert_param(IS_LL_DMA_LINK_ADDR_OFFSET(DMA_InitStruct->LinkedListAddrOffset)); - assert_param(IS_LL_DMA_MODE(DMA_InitStruct->Mode)); - if (DMA_InitStruct->Mode == LL_DMA_PFCTRL) - { - assert_param(IS_LL_DMA_PFREQ_INSTANCE(DMAx, Channel)); - } - - /* Check DMA instance */ - if ((IS_LL_HPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U) || (IS_LL_GPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U)) - { - assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitStruct->SrcBurstLength)); - assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitStruct->DestBurstLength)); - assert_param(IS_LL_DMA_DEST_WORD_EXCHANGE(DMA_InitStruct->DestWordExchange)); - assert_param(IS_LL_DMA_DEST_HALFWORD_EXCHANGE(DMA_InitStruct->DestHWordExchange)); - assert_param(IS_LL_DMA_DEST_BYTE_EXCHANGE(DMA_InitStruct->DestByteExchange)); - assert_param(IS_LL_DMA_SRC_BYTE_EXCHANGE(DMA_InitStruct->SrcByteExchange)); - assert_param(IS_LL_DMA_LINK_ALLOCATED_PORT(DMA_InitStruct->LinkAllocatedPort)); - assert_param(IS_LL_DMA_SRC_ALLOCATED_PORT(DMA_InitStruct->SrcAllocatedPort)); - assert_param(IS_LL_DMA_DEST_ALLOCATED_PORT(DMA_InitStruct->DestAllocatedPort)); - } - - /* Check trigger polarity */ - if (DMA_InitStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) - { - assert_param(IS_LL_DMA_TRIGGER_MODE(DMA_InitStruct->TriggerMode)); - assert_param(IS_LL_DMA_TRIGGER_SELECTION(DMA_InitStruct->TriggerSelection)); - } - - /* Check DMA channel */ - if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) - { - assert_param(IS_LL_DMA_BLK_REPEATCOUNT(DMA_InitStruct->BlkRptCount)); - assert_param(IS_LL_DMA_BURST_SRC_ADDR_UPDATE(DMA_InitStruct->SrcAddrUpdateMode)); - assert_param(IS_LL_DMA_BURST_DEST_ADDR_UPDATE(DMA_InitStruct->DestAddrUpdateMode)); - assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitStruct->SrcAddrOffset)); - assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitStruct->DestAddrOffset)); - assert_param(IS_LL_DMA_BLKRPT_SRC_ADDR_UPDATE(DMA_InitStruct->BlkRptSrcAddrUpdateMode)); - assert_param(IS_LL_DMA_BLKRPT_DEST_ADDR_UPDATE(DMA_InitStruct->BlkRptDestAddrUpdateMode)); - assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitStruct->BlkRptSrcAddrOffset)); - assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitStruct->BlkRptDestAddrOffset)); - } - - /*-------------------------- DMAx CLBAR Configuration ------------------------ - * Configure the Transfer linked list address with parameter : - * - LinkedListBaseAdd: DMA_CLBAR_LBA[31:16] bits - */ - LL_DMA_SetLinkedListBaseAddr(DMAx, Channel, DMA_InitStruct->LinkedListBaseAddr); - - /*-------------------------- DMAx CCR Configuration -------------------------- - * Configure the control parameter : - * - LinkAllocatedPort: DMA_CCR_LAP bit - * - LinkStepMode: DMA_CCR_LSM bit - * - Priority: DMA_CCR_PRIO [23:22] bits - */ - LL_DMA_ConfigControl(DMAx, Channel, DMA_InitStruct->Priority | \ - DMA_InitStruct->LinkAllocatedPort | \ - DMA_InitStruct->LinkStepMode); - - /*-------------------------- DMAx CTR1 Configuration ------------------------- - * Configure the Data transfer parameter : - * - DestAllocatedPort: DMA_CTR1_DAP bit - * - DestWordExchange: DMA_CTR1_DWX bit - * - DestHWordExchange: DMA_CTR1_DHX bit - * - DestByteExchange: DMA_CTR1_DBX bit - * - DestIncMode: DMA_CTR1_DINC bit - * - DestDataWidth: DMA_CTR1_DDW_LOG2 [17:16] bits - * - SrcAllocatedPort: DMA_CTR1_SAP bit - * - SrcByteExchange: DMA_CTR1_SBX bit - * - DataAlignment: DMA_CTR1_PAM [12:11] bits - * - SrcIncMode: DMA_CTR1_SINC bit - * - SrcDataWidth: DMA_CTR1_SDW_LOG2 [1:0] bits - * - SrcBurstLength: DMA_CTR1_SBL_1 [9:4] bits - * - DestBurstLength: DMA_CTR1_DBL_1 [25:20] bits - */ - LL_DMA_ConfigTransfer(DMAx, Channel, DMA_InitStruct->DestAllocatedPort | \ - DMA_InitStruct->DestWordExchange | \ - DMA_InitStruct->DestHWordExchange | \ - DMA_InitStruct->DestByteExchange | \ - DMA_InitStruct->DestIncMode | \ - DMA_InitStruct->DestDataWidth | \ - DMA_InitStruct->SrcAllocatedPort | \ - DMA_InitStruct->SrcByteExchange | \ - DMA_InitStruct->DataAlignment | \ - DMA_InitStruct->SrcIncMode | \ - DMA_InitStruct->SrcDataWidth); - /* Check DMA instance */ - if ((IS_LL_HPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U) || (IS_LL_GPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U)) - { - LL_DMA_ConfigBurstLength(DMAx, Channel, DMA_InitStruct->SrcBurstLength, - DMA_InitStruct->DestBurstLength); - } - - /*-------------------------- DMAx CTR2 Configuration ------------------------- - * Configure the channel transfer parameter : - * - TransferEventMode: DMA_CTR2_TCEM [31:30] bits - * - TriggerPolarity: DMA_CTR2_TRIGPOL [25:24] bits - * - TriggerMode: DMA_CTR2_TRIGM [15:14] bits - * - BlkHWRequest: DMA_CTR2_BREQ bit - * - Mode: DMA_CTR2_PFREQ bit - * - Direction: DMA_CTR2_DREQ bit - * - Direction: DMA_CTR2_SWREQ bit - * - TriggerSelection: DMA_CTR2_TRIGSEL [21:16] bits - * - Request: DMA_CTR2_REQSEL [6:0] bits - */ - LL_DMA_ConfigChannelTransfer(DMAx, Channel, DMA_InitStruct->TransferEventMode | \ - DMA_InitStruct->TriggerPolarity | \ - DMA_InitStruct->BlkHWRequest | \ - DMA_InitStruct->Mode | \ - DMA_InitStruct->Direction); - - /* Check direction */ - if (DMA_InitStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) - { - LL_DMA_SetPeriphRequest(DMAx, Channel, DMA_InitStruct->Request); - } - - /* Check trigger polarity */ - if (DMA_InitStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) - { - LL_DMA_SetHWTrigger(DMAx, Channel, DMA_InitStruct->TriggerSelection); - LL_DMA_SetTriggerMode(DMAx, Channel, DMA_InitStruct->TriggerMode); - } - - /*-------------------------- DMAx CBR1 Configuration ------------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - BlkDataLength: DMA_CBR1_BNDT[15:0] bits - * - BlkRptCount: DMA_CBR1_BRC[26:16] bits - * BlkRptCount field is supported only by 2D addressing channels. - * - BlkRptSrcAddrUpdateMode: DMA_CBR1_BRSDEC bit - * BlkRptSrcAddrUpdateMode field is supported only by 2D addressing channels. - * - BlkRptDestAddrUpdateMode: DMA_CBR1_BRDDEC bit - * BlkRptDestAddrUpdateMode field is supported only by 2D addressing channels. - * - SrcAddrUpdateMode: DMA_CBR1_SDEC bit - * SrcAddrUpdateMode field is supported only by 2D addressing channels. - * - DestAddrUpdateMode: DMA_CBR1_DDEC bit - * DestAddrUpdateMode field is supported only by 2D addressing channels. - */ - LL_DMA_SetBlkDataLength(DMAx, Channel, DMA_InitStruct->BlkDataLength); - - /* Check DMA channel */ - if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) - { - LL_DMA_SetBlkRptCount(DMAx, Channel, DMA_InitStruct->BlkRptCount); - LL_DMA_ConfigBlkRptAddrUpdate(DMAx, Channel, DMA_InitStruct->BlkRptSrcAddrUpdateMode | \ - DMA_InitStruct->BlkRptDestAddrUpdateMode | \ - DMA_InitStruct->SrcAddrUpdateMode | \ - DMA_InitStruct->DestAddrUpdateMode); - } - - /*-------------------------- DMAx CSAR and CDAR Configuration ---------------- - * Configure the Transfer source address with parameter : - * - SrcAddress: DMA_CSAR_SA[31:0] bits - * - DestAddress: DMA_CDAR_DA[31:0] bits - */ - LL_DMA_ConfigAddresses(DMAx, Channel, DMA_InitStruct->SrcAddress, DMA_InitStruct->DestAddress); - - /* Check DMA channel */ - if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) - { - /*------------------------ DMAx CTR3 Configuration ------------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - SrcAddrOffset: DMA_CTR3_SAO[28:16] bits - * SrcAddrOffset field is supported only by 2D addressing channels. - * - DestAddrOffset: DMA_CTR3_DAO[12:0] bits - * DestAddrOffset field is supported only by 2D addressing channels. - */ - LL_DMA_ConfigAddrUpdateValue(DMAx, Channel, DMA_InitStruct->SrcAddrOffset, DMA_InitStruct->DestAddrOffset); - - /*------------------------ DMAx CBR2 Configuration ----------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - BlkRptSrcAddrOffset: DMA_CBR2_BRSAO[15:0] bits - * BlkRptSrcAddrOffset field is supported only by 2D addressing channels. - * - BlkRptDestAddrOffset: DMA_CBR2_BRDAO[31:16] bits - * BlkRptDestAddrOffset field is supported only by 2D addressing channels. - */ - LL_DMA_ConfigBlkRptAddrUpdateValue(DMAx, Channel, DMA_InitStruct->BlkRptSrcAddrOffset, - DMA_InitStruct->BlkRptDestAddrOffset); - } - - /*-------------------------- DMAx CLLR Configuration ------------------------- - * Configure the Transfer linked list address with parameter : - * - DestAddrOffset: DMA_CLLR_LA[15:2] bits - */ - LL_DMA_SetLinkedListAddrOffset(DMAx, Channel, DMA_InitStruct->LinkedListAddrOffset); - - return (uint32_t)SUCCESS; -} - -/** - * @brief Set each @ref LL_DMA_InitTypeDef field to default value. - * @param DMA_InitStruct Pointer to a @ref LL_DMA_InitTypeDef structure. - * @retval None. - */ -void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct) -{ - /* Set DMA_InitStruct fields to default values */ - DMA_InitStruct->SrcAddress = 0x00000000U; - DMA_InitStruct->DestAddress = 0x00000000U; - DMA_InitStruct->Direction = LL_DMA_DIRECTION_MEMORY_TO_MEMORY; - DMA_InitStruct->BlkHWRequest = LL_DMA_HWREQUEST_SINGLEBURST; - DMA_InitStruct->DataAlignment = LL_DMA_DATA_ALIGN_ZEROPADD; - DMA_InitStruct->SrcBurstLength = 1U; - DMA_InitStruct->DestBurstLength = 1U; - DMA_InitStruct->SrcDataWidth = LL_DMA_SRC_DATAWIDTH_BYTE; - DMA_InitStruct->DestDataWidth = LL_DMA_DEST_DATAWIDTH_BYTE; - DMA_InitStruct->SrcIncMode = LL_DMA_SRC_FIXED; - DMA_InitStruct->DestIncMode = LL_DMA_DEST_FIXED; - DMA_InitStruct->Priority = LL_DMA_LOW_PRIORITY_LOW_WEIGHT; - DMA_InitStruct->BlkDataLength = 0x00000000U; - DMA_InitStruct->Mode = LL_DMA_NORMAL; - DMA_InitStruct->BlkRptCount = 0x00000000U; - DMA_InitStruct->TriggerMode = LL_DMA_TRIGM_BLK_TRANSFER; - DMA_InitStruct->TriggerPolarity = LL_DMA_TRIG_POLARITY_MASKED; - DMA_InitStruct->TriggerSelection = 0x00000000U; - DMA_InitStruct->Request = 0x00000000U; - DMA_InitStruct->TransferEventMode = LL_DMA_TCEM_BLK_TRANSFER; - DMA_InitStruct->DestWordExchange = LL_DMA_DEST_WORD_PRESERVE; - DMA_InitStruct->DestHWordExchange = LL_DMA_DEST_HALFWORD_PRESERVE; - DMA_InitStruct->DestByteExchange = LL_DMA_DEST_BYTE_PRESERVE; - DMA_InitStruct->SrcByteExchange = LL_DMA_SRC_BYTE_PRESERVE; - DMA_InitStruct->SrcAllocatedPort = LL_DMA_SRC_ALLOCATED_PORT0; - DMA_InitStruct->DestAllocatedPort = LL_DMA_DEST_ALLOCATED_PORT0; - DMA_InitStruct->LinkAllocatedPort = LL_DMA_LINK_ALLOCATED_PORT0; - DMA_InitStruct->LinkStepMode = LL_DMA_LSM_FULL_EXECUTION; - DMA_InitStruct->SrcAddrUpdateMode = LL_DMA_BURST_SRC_ADDR_INCREMENT; - DMA_InitStruct->DestAddrUpdateMode = LL_DMA_BURST_DEST_ADDR_INCREMENT; - DMA_InitStruct->SrcAddrOffset = 0x00000000U; - DMA_InitStruct->DestAddrOffset = 0x00000000U; - DMA_InitStruct->BlkRptSrcAddrUpdateMode = LL_DMA_BLKRPT_SRC_ADDR_INCREMENT; - DMA_InitStruct->BlkRptDestAddrUpdateMode = LL_DMA_BLKRPT_DEST_ADDR_INCREMENT; - DMA_InitStruct->BlkRptSrcAddrOffset = 0x00000000U; - DMA_InitStruct->BlkRptDestAddrOffset = 0x00000000U; - DMA_InitStruct->LinkedListBaseAddr = 0x00000000U; - DMA_InitStruct->LinkedListAddrOffset = 0x00000000U; -} - -/** - * @brief Set each @ref LL_DMA_InitLinkedListTypeDef field to default value. - * @param DMA_InitLinkedListStruct Pointer to - * a @ref LL_DMA_InitLinkedListTypeDef structure. - * @retval None. - */ -void LL_DMA_ListStructInit(LL_DMA_InitLinkedListTypeDef *DMA_InitLinkedListStruct) -{ - /* Set LL_DMA_InitLinkedListTypeDef fields to default values */ - DMA_InitLinkedListStruct->Priority = LL_DMA_LOW_PRIORITY_LOW_WEIGHT; - DMA_InitLinkedListStruct->LinkStepMode = LL_DMA_LSM_FULL_EXECUTION; - DMA_InitLinkedListStruct->TransferEventMode = LL_DMA_TCEM_LAST_LLITEM_TRANSFER; - DMA_InitLinkedListStruct->LinkAllocatedPort = LL_DMA_LINK_ALLOCATED_PORT0; -} - -/** - * @brief De-initialize the DMA linked list. - * @note This API is used for all available DMA channels. - * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use - * helper macros : - * @arg @ref LL_DMA_GET_INSTANCE - * @arg @ref LL_DMA_GET_CHANNEL - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_0 - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @arg @ref LL_DMA_CHANNEL_8 - * @arg @ref LL_DMA_CHANNEL_9 - * @arg @ref LL_DMA_CHANNEL_10 - * @arg @ref LL_DMA_CHANNEL_11 - * @arg @ref LL_DMA_CHANNEL_12 - * @arg @ref LL_DMA_CHANNEL_13 - * @arg @ref LL_DMA_CHANNEL_14 - * @arg @ref LL_DMA_CHANNEL_15 - * @retval An ErrorStatus enumeration value: - * - SUCCESS : DMA registers are de-initialized. - * - ERROR : DMA registers are not de-initialized. - */ -uint32_t LL_DMA_List_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return LL_DMA_DeInit(DMAx, Channel); -} - -/** - * @brief Initialize the DMA linked list according to the specified parameters - * in LL_DMA_InitLinkedListTypeDef. - * @note This API is used for all available DMA channels. - * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use - * helper macros : - * @arg @ref LL_DMA_GET_INSTANCE - * @arg @ref LL_DMA_GET_CHANNEL - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_0 - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @arg @ref LL_DMA_CHANNEL_8 - * @arg @ref LL_DMA_CHANNEL_9 - * @arg @ref LL_DMA_CHANNEL_10 - * @arg @ref LL_DMA_CHANNEL_11 - * @arg @ref LL_DMA_CHANNEL_12 - * @arg @ref LL_DMA_CHANNEL_13 - * @arg @ref LL_DMA_CHANNEL_14 - * @arg @ref LL_DMA_CHANNEL_15 - * @param DMA_InitLinkedListStruct pointer to - * a @ref LL_DMA_InitLinkedListTypeDef structure. - * @retval An ErrorStatus enumeration value: - * - SUCCESS : DMA registers are initialized. - * - ERROR : Not applicable. - */ -uint32_t LL_DMA_List_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitLinkedListTypeDef *DMA_InitLinkedListStruct) -{ - /* Check the DMA Instance DMAx and Channel parameters*/ - assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); - - /* Check the DMA parameters from DMA_InitLinkedListStruct */ - assert_param(IS_LL_DMA_PRIORITY(DMA_InitLinkedListStruct->Priority)); - assert_param(IS_LL_DMA_LINK_STEP_MODE(DMA_InitLinkedListStruct->LinkStepMode)); - assert_param(IS_LL_DMA_TRANSFER_EVENT_MODE(DMA_InitLinkedListStruct->TransferEventMode)); - /* Check DMA instance */ - if ((IS_LL_HPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U) || (IS_LL_GPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U)) - { - assert_param(IS_LL_DMA_LINK_ALLOCATED_PORT(DMA_InitLinkedListStruct->LinkAllocatedPort)); - } - - /*-------------------------- DMAx CCR Configuration -------------------------- - * Configure the control parameter : - * - LinkAllocatedPort: DMA_CCR_LAP bit - * LinkAllocatedPort field is supported only by GPDMA channels. - * - LinkStepMode: DMA_CCR_LSM bit - * - Priority: DMA_CCR_PRIO [23:22] bits - */ - LL_DMA_ConfigControl(DMAx, Channel, DMA_InitLinkedListStruct->Priority | \ - DMA_InitLinkedListStruct->LinkAllocatedPort | \ - DMA_InitLinkedListStruct->LinkStepMode); - - /*-------------------------- DMAx CTR2 Configuration ------------------------- - * Configure the channel transfer parameter : - * - TransferEventMode: DMA_CTR2_TCEM [31:30] bits - */ - LL_DMA_SetTransferEventMode(DMAx, Channel, DMA_InitLinkedListStruct->TransferEventMode); - - return (uint32_t)SUCCESS; -} - -/** - * @brief Set each @ref LL_DMA_InitNodeTypeDef field to default value. - * @param DMA_InitNodeStruct Pointer to a @ref LL_DMA_InitNodeTypeDef - * structure. - * @retval None. - */ -void LL_DMA_NodeStructInit(LL_DMA_InitNodeTypeDef *DMA_InitNodeStruct) -{ - /* Set DMA_InitNodeStruct fields to default values */ - DMA_InitNodeStruct->DestAllocatedPort = LL_DMA_DEST_ALLOCATED_PORT0; - DMA_InitNodeStruct->DestWordExchange = LL_DMA_DEST_WORD_PRESERVE; - DMA_InitNodeStruct->DestHWordExchange = LL_DMA_DEST_HALFWORD_PRESERVE; - DMA_InitNodeStruct->DestByteExchange = LL_DMA_DEST_BYTE_PRESERVE; - DMA_InitNodeStruct->DestBurstLength = 1U; - DMA_InitNodeStruct->DestIncMode = LL_DMA_DEST_FIXED; - DMA_InitNodeStruct->DestDataWidth = LL_DMA_DEST_DATAWIDTH_BYTE; - DMA_InitNodeStruct->SrcAllocatedPort = LL_DMA_SRC_ALLOCATED_PORT0; - DMA_InitNodeStruct->SrcByteExchange = LL_DMA_SRC_BYTE_PRESERVE; - DMA_InitNodeStruct->DataAlignment = LL_DMA_DATA_ALIGN_ZEROPADD; - DMA_InitNodeStruct->SrcBurstLength = 1U; - DMA_InitNodeStruct->SrcIncMode = LL_DMA_SRC_FIXED; - DMA_InitNodeStruct->SrcDataWidth = LL_DMA_SRC_DATAWIDTH_BYTE; - DMA_InitNodeStruct->TransferEventMode = LL_DMA_TCEM_BLK_TRANSFER; - DMA_InitNodeStruct->TriggerPolarity = LL_DMA_TRIG_POLARITY_MASKED; - DMA_InitNodeStruct->TriggerSelection = 0x00000000U; - DMA_InitNodeStruct->TriggerMode = LL_DMA_TRIGM_BLK_TRANSFER; - DMA_InitNodeStruct->BlkHWRequest = LL_DMA_HWREQUEST_SINGLEBURST; - DMA_InitNodeStruct->Direction = LL_DMA_DIRECTION_MEMORY_TO_MEMORY; - DMA_InitNodeStruct->Request = 0x00000000U; - DMA_InitNodeStruct->Mode = LL_DMA_NORMAL; - DMA_InitNodeStruct->BlkRptDestAddrUpdateMode = LL_DMA_BLKRPT_DEST_ADDR_INCREMENT; - DMA_InitNodeStruct->BlkRptSrcAddrUpdateMode = LL_DMA_BLKRPT_SRC_ADDR_INCREMENT; - DMA_InitNodeStruct->DestAddrUpdateMode = LL_DMA_BURST_DEST_ADDR_INCREMENT; - DMA_InitNodeStruct->SrcAddrUpdateMode = LL_DMA_BURST_SRC_ADDR_INCREMENT; - DMA_InitNodeStruct->BlkRptCount = 0x00000000U; - DMA_InitNodeStruct->BlkDataLength = 0x00000000U; - DMA_InitNodeStruct->SrcAddress = 0x00000000U; - DMA_InitNodeStruct->DestAddress = 0x00000000U; - DMA_InitNodeStruct->DestAddrOffset = 0x00000000U; - DMA_InitNodeStruct->SrcAddrOffset = 0x00000000U; - DMA_InitNodeStruct->BlkRptDestAddrOffset = 0x00000000U; - DMA_InitNodeStruct->BlkRptSrcAddrOffset = 0x00000000U; - DMA_InitNodeStruct->UpdateRegisters = (LL_DMA_UPDATE_CTR1 | LL_DMA_UPDATE_CTR2 | \ - LL_DMA_UPDATE_CBR1 | LL_DMA_UPDATE_CSAR | \ - LL_DMA_UPDATE_CDAR | LL_DMA_UPDATE_CTR3 | \ - LL_DMA_UPDATE_CBR2 | LL_DMA_UPDATE_CLLR); - DMA_InitNodeStruct->NodeType = LL_DMA_GPDMA_LINEAR_NODE; -} - -/** - * @brief Initializes DMA linked list node according to the specified - * parameters in the DMA_InitNodeStruct. - * @param DMA_InitNodeStruct Pointer to a LL_DMA_InitNodeTypeDef structure - * that contains linked list node - * registers configurations. - * @param pNode Pointer to linked list node to fill according to - * LL_DMA_LinkNodeTypeDef parameters. - * @retval None - */ -uint32_t LL_DMA_CreateLinkNode(const LL_DMA_InitNodeTypeDef *DMA_InitNodeStruct, LL_DMA_LinkNodeTypeDef *pNode) -{ - uint32_t reg_counter = 0U; - - /* Check the DMA Node type */ - assert_param(IS_LL_DMA_LINK_NODETYPE(DMA_InitNodeStruct->NodeType)); - - /* Check the DMA parameters from DMA_InitNodeStruct */ - assert_param(IS_LL_DMA_DIRECTION(DMA_InitNodeStruct->Direction)); - - /* Check direction */ - if (DMA_InitNodeStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) - { - assert_param(IS_LL_DMA_REQUEST_SELECTION(DMA_InitNodeStruct->Request)); - } - - assert_param(IS_LL_DMA_DATA_ALIGNMENT(DMA_InitNodeStruct->DataAlignment)); - assert_param(IS_LL_DMA_SRC_DATA_WIDTH(DMA_InitNodeStruct->SrcDataWidth)); - assert_param(IS_LL_DMA_DEST_DATA_WIDTH(DMA_InitNodeStruct->DestDataWidth)); - assert_param(IS_LL_DMA_SRC_INCREMENT_MODE(DMA_InitNodeStruct->SrcIncMode)); - assert_param(IS_LL_DMA_DEST_INCREMENT_MODE(DMA_InitNodeStruct->DestIncMode)); - assert_param(IS_LL_DMA_BLK_DATALENGTH(DMA_InitNodeStruct->BlkDataLength)); - assert_param(IS_LL_DMA_TRIGGER_POLARITY(DMA_InitNodeStruct->TriggerPolarity)); - assert_param(IS_LL_DMA_BLKHW_REQUEST(DMA_InitNodeStruct->BlkHWRequest)); - assert_param(IS_LL_DMA_TRANSFER_EVENT_MODE(DMA_InitNodeStruct->TransferEventMode)); - assert_param(IS_LL_DMA_LINK_UPDATE_REGISTERS(DMA_InitNodeStruct->UpdateRegisters)); - assert_param(IS_LL_DMA_MODE(DMA_InitNodeStruct->Mode)); - - /* Check trigger polarity */ - if (DMA_InitNodeStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) - { - assert_param(IS_LL_DMA_TRIGGER_MODE(DMA_InitNodeStruct->TriggerMode)); - assert_param(IS_LL_DMA_TRIGGER_SELECTION(DMA_InitNodeStruct->TriggerSelection)); - } - - /* Check node type */ - if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_LINEAR_NODE) || \ - (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_LINEAR_NODE)) - { - assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitNodeStruct->SrcBurstLength)); - assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitNodeStruct->DestBurstLength)); - assert_param(IS_LL_DMA_DEST_WORD_EXCHANGE(DMA_InitNodeStruct->DestWordExchange)); - assert_param(IS_LL_DMA_DEST_HALFWORD_EXCHANGE(DMA_InitNodeStruct->DestHWordExchange)); - assert_param(IS_LL_DMA_DEST_BYTE_EXCHANGE(DMA_InitNodeStruct->DestByteExchange)); - assert_param(IS_LL_DMA_SRC_BYTE_EXCHANGE(DMA_InitNodeStruct->SrcByteExchange)); - assert_param(IS_LL_DMA_SRC_ALLOCATED_PORT(DMA_InitNodeStruct->SrcAllocatedPort)); - assert_param(IS_LL_DMA_DEST_ALLOCATED_PORT(DMA_InitNodeStruct->DestAllocatedPort)); - } - - /* Check DMA channel */ - if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || \ - (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) - { - assert_param(IS_LL_DMA_BLK_REPEATCOUNT(DMA_InitNodeStruct->BlkRptCount)); - assert_param(IS_LL_DMA_BURST_SRC_ADDR_UPDATE(DMA_InitNodeStruct->SrcAddrUpdateMode)); - assert_param(IS_LL_DMA_BURST_DEST_ADDR_UPDATE(DMA_InitNodeStruct->DestAddrUpdateMode)); - assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->SrcAddrOffset)); - assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->DestAddrOffset)); - assert_param(IS_LL_DMA_BLKRPT_SRC_ADDR_UPDATE(DMA_InitNodeStruct->BlkRptSrcAddrUpdateMode)); - assert_param(IS_LL_DMA_BLKRPT_DEST_ADDR_UPDATE(DMA_InitNodeStruct->BlkRptDestAddrUpdateMode)); - assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->BlkRptSrcAddrOffset)); - assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->BlkRptDestAddrOffset)); - } - - /* Check if CTR1 register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CTR1) == LL_DMA_UPDATE_CTR1) - { - /*-------------------------- DMAx CTR1 Configuration ----------------------- - * Configure the Data transfer parameter : - * - DestAllocatedPort: DMA_CTR1_DAP bit - * - DestWordExchange: DMA_CTR1_DWX bit - * - DestHWordExchange: DMA_CTR1_DHX bit - * - DestByteExchange: DMA_CTR1_DBX bit - * - DestIncMode: DMA_CTR1_DINC bit - * - DestDataWidth: DMA_CTR1_DDW_LOG2 [17:16] bits - * - SrcAllocatedPort: DMA_CTR1_SAP bit - * - SrcByteExchange: DMA_CTR1_SBX bit - * - DataAlignment: DMA_CTR1_PAM [12:11] bits - * - SrcIncMode: DMA_CTR1_SINC bit - * - SrcDataWidth: DMA_CTR1_SDW_LOG2 [1:0] bits - * - SrcBurstLength: DMA_CTR1_SBL_1 [9:4] bits - * - DestBurstLength: DMA_CTR1_DBL_1 [25:20] bits - */ - - pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->DestIncMode | \ - DMA_InitNodeStruct->DestDataWidth | \ - DMA_InitNodeStruct->DataAlignment | \ - DMA_InitNodeStruct->SrcIncMode | \ - DMA_InitNodeStruct->SrcDataWidth); - - /* Update CTR1 register fields */ - pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->DestAllocatedPort | \ - DMA_InitNodeStruct->DestWordExchange | \ - DMA_InitNodeStruct->DestHWordExchange | \ - DMA_InitNodeStruct->DestByteExchange | \ - ((DMA_InitNodeStruct->DestBurstLength - 1U) << DMA_CTR1_DBL_1_Pos) | \ - DMA_InitNodeStruct->SrcAllocatedPort | \ - DMA_InitNodeStruct->SrcByteExchange | \ - ((DMA_InitNodeStruct->SrcBurstLength - 1U) << DMA_CTR1_SBL_1_Pos)); - - /* Increment counter for the next register */ - reg_counter++; - } - - - /* Check if CTR2 register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CTR2) == LL_DMA_UPDATE_CTR2) - { - /*-------------------------- DMAx CTR2 Configuration ----------------------- - * Configure the channel transfer parameter : - * - TransferEventMode: DMA_CTR2_TCEM [31:30] bits - * - TriggerPolarity: DMA_CTR2_TRIGPOL [25:24] bits - * - TriggerMode: DMA_CTR2_TRIGM [15:14] bits - * - Mode: DMA_CTR2_PFREQ bit - * - BlkHWRequest: DMA_CTR2_BREQ bit - * - Direction: DMA_CTR2_DREQ bit - * - Direction: DMA_CTR2_SWREQ bit - * - TriggerSelection: DMA_CTR2_TRIGSEL [21:16] bits - * - Request: DMA_CTR2_REQSEL [6:0] bits - */ - pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->TransferEventMode | \ - DMA_InitNodeStruct->TriggerPolarity | \ - DMA_InitNodeStruct->BlkHWRequest | \ - DMA_InitNodeStruct->Mode | \ - DMA_InitNodeStruct->Direction); - - /* Check direction */ - if (DMA_InitNodeStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) - { - pNode->LinkRegisters[reg_counter] |= DMA_InitNodeStruct->Request & DMA_CTR2_REQSEL; - } - - /* Check trigger polarity */ - if (DMA_InitNodeStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) - { - pNode->LinkRegisters[reg_counter] |= (((DMA_InitNodeStruct->TriggerSelection << DMA_CTR2_TRIGSEL_Pos) & \ - DMA_CTR2_TRIGSEL) | DMA_InitNodeStruct->TriggerMode); - } - - - /* Increment counter for the next register */ - reg_counter++; - } - - /* Check if CBR1 register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CBR1) == LL_DMA_UPDATE_CBR1) - { - /*-------------------------- DMAx CBR1 Configuration ----------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - BlkDataLength: DMA_CBR1_BNDT[15:0] bits - * - BlkRptCount: DMA_CBR1_BRC[26:16] bits - * BlkRptCount field is supported only by 2D addressing channels. - * - BlkRptSrcAddrUpdateMode: DMA_CBR1_BRSDEC bit - * BlkRptSrcAddrUpdateMode field is supported only by 2D addressing channels. - * - BlkRptDestAddrUpdateMode: DMA_CBR1_BRDDEC bit - * BlkRptDestAddrUpdateMode field is supported only by 2D addressing channels. - * - SrcAddrUpdateMode: DMA_CBR1_SDEC bit - * SrcAddrUpdateMode field is supported only by 2D addressing channels. - * - DestAddrUpdateMode: DMA_CBR1_DDEC bit - * DestAddrUpdateMode field is supported only by 2D addressing channels. - */ - pNode->LinkRegisters[reg_counter] = DMA_InitNodeStruct->BlkDataLength; - - /* Update CBR1 register fields for 2D addressing channels */ - if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || \ - (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) - { - pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->BlkRptDestAddrUpdateMode | \ - DMA_InitNodeStruct->BlkRptSrcAddrUpdateMode | \ - DMA_InitNodeStruct->DestAddrUpdateMode | \ - DMA_InitNodeStruct->SrcAddrUpdateMode | \ - ((DMA_InitNodeStruct->BlkRptCount << DMA_CBR1_BRC_Pos) & DMA_CBR1_BRC)); - } - - /* Increment counter for the next register */ - reg_counter++; - } - - /* Check if CSAR register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CSAR) == LL_DMA_UPDATE_CSAR) - { - /*-------------------------- DMAx CSAR Configuration ----------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - SrcAddress: DMA_CSAR_SA[31:0] bits - */ - pNode->LinkRegisters[reg_counter] = DMA_InitNodeStruct->SrcAddress; - - /* Increment counter for the next register */ - reg_counter++; - } - - - /* Check if CDAR register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CDAR) == LL_DMA_UPDATE_CDAR) - { - /*-------------------------- DMAx CDAR Configuration ----------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - DestAddress: DMA_CDAR_DA[31:0] bits - */ - pNode->LinkRegisters[reg_counter] = DMA_InitNodeStruct->DestAddress; - - /* Increment counter for the next register */ - reg_counter++; - } - - - /* Update CTR3 register fields for 2D addressing channels */ - if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) - { - /* Check if CTR3 register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CTR3) == LL_DMA_UPDATE_CTR3) - { - /*-------------------------- DMAx CTR3 Configuration --------------------- - * Configure the Block counters and update mode with parameter : - * - DestAddressOffset: DMA_CTR3_DAO[12:0] bits - * DestAddressOffset field is supported only by 2D addressing channels. - * - SrcAddressOffset: DMA_CTR3_SAO[12:0] bits - * SrcAddressOffset field is supported only by 2D addressing channels. - */ - pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->SrcAddrOffset | \ - ((DMA_InitNodeStruct->DestAddrOffset << DMA_CTR3_DAO_Pos) & DMA_CTR3_DAO)); - - /* Increment counter for the next register */ - reg_counter++; - } - } - - - /* Update CBR2 register fields for 2D addressing channels */ - if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) - { - /* Check if CBR2 register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CBR2) == LL_DMA_UPDATE_CBR2) - { - /*-------------------------- DMAx CBR2 Configuration --------------------- - * Configure the Block counters and update mode with parameter : - * - BlkRptDestAddrOffset: DMA_CBR2_BRDAO[31:16] bits - * BlkRptDestAddrOffset field is supported only by 2D addressing channels. - * - BlkRptSrcAddrOffset: DMA_CBR2_BRSAO[15:0] bits - * BlkRptSrcAddrOffset field is supported only by 2D addressing channels. - */ - pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->BlkRptSrcAddrOffset | \ - ((DMA_InitNodeStruct->BlkRptDestAddrOffset << DMA_CBR2_BRDAO_Pos) & \ - DMA_CBR2_BRDAO)); - - /* Increment counter for the next register */ - reg_counter++; - } - } - - /* Check if CLLR register update is enabled */ - if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CLLR) == LL_DMA_UPDATE_CLLR) - { - /*-------------------------- DMAx CLLR Configuration ----------------------- - * Configure the Transfer Block counters and update mode with parameter : - * - UpdateRegisters DMA_CLLR_UT1 bit - * - UpdateRegisters DMA_CLLR_UT2 bit - * - UpdateRegisters DMA_CLLR_UB1 bit - * - UpdateRegisters DMA_CLLR_USA bit - * - UpdateRegisters DMA_CLLR_UDA bit - * - UpdateRegisters DMA_CLLR_UT3 bit - * DMA_CLLR_UT3 bit is discarded for linear addressing channels. - * - UpdateRegisters DMA_CLLR_UB2 bit - * DMA_CLLR_UB2 bit is discarded for linear addressing channels. - * - UpdateRegisters DMA_CLLR_ULL bit - */ - pNode->LinkRegisters[reg_counter] = ((DMA_InitNodeStruct->UpdateRegisters & (DMA_CLLR_UT1 | DMA_CLLR_UT2 | \ - DMA_CLLR_UB1 | DMA_CLLR_USA | \ - DMA_CLLR_UDA | DMA_CLLR_ULL))); - - /* Update CLLR register fields for 2D addressing channels */ - if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || \ - (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) - { - pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->UpdateRegisters & (DMA_CLLR_UT3 | DMA_CLLR_UB2)); - } - } - - return (uint32_t)SUCCESS; -} - -/** - * @brief Connect Linked list Nodes. - * @param pPrevLinkNode Pointer to previous linked list node to be connected to new Linked list node. - * @param PrevNodeCLLRIdx Offset of Previous Node CLLR register. - * This parameter can be a value of @ref DMA_LL_EC_CLLR_OFFSET. - * @param pNewLinkNode Pointer to new Linked list. - * @param NewNodeCLLRIdx Offset of New Node CLLR register. - * This parameter can be a value of @ref DMA_LL_EC_CLLR_OFFSET. - * @retval None - */ -void LL_DMA_ConnectLinkNode(LL_DMA_LinkNodeTypeDef *pPrevLinkNode, uint32_t PrevNodeCLLRIdx, - LL_DMA_LinkNodeTypeDef *pNewLinkNode, uint32_t NewNodeCLLRIdx) -{ - pPrevLinkNode->LinkRegisters[PrevNodeCLLRIdx] = (((uint32_t)pNewLinkNode & DMA_CLLR_LA) | \ - (pNewLinkNode->LinkRegisters[NewNodeCLLRIdx] & (DMA_CLLR_UT1 | \ - DMA_CLLR_UT2 | DMA_CLLR_UB1 | DMA_CLLR_USA | DMA_CLLR_UDA | \ - DMA_CLLR_UT3 | DMA_CLLR_UB2 | DMA_CLLR_ULL))); -} - -/** - * @brief Disconnect the next linked list node. - * @param pLinkNode Pointer to linked list node to be disconnected from the next one. - * @param LinkNodeCLLRIdx Offset of Link Node CLLR register. - * @retval None. - */ -void LL_DMA_DisconnectNextLinkNode(LL_DMA_LinkNodeTypeDef *pLinkNode, uint32_t LinkNodeCLLRIdx) -{ - pLinkNode->LinkRegisters[LinkNodeCLLRIdx] = 0; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* GPDMA1 || HPDMA1 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_dma.c + * @author MCD Application Team + * @brief DMA LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### LL DMA driver acronyms ##### + ============================================================================== + [..] Acronyms table : + ========================================= + || Acronym || || + ========================================= + || SRC || Source || + || DEST || Destination || + || ADDR || Address || + || ADDRS || Addresses || + || INC || Increment / Incremented || + || DEC || Decrement / Decremented || + || BLK || Block || + || RPT || Repeat / Repeated || + || TRIG || Trigger || + ========================================= + @endverbatim + ****************************************************************************** + */ + +#if defined (USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_dma.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if (defined (GPDMA1) || defined (HPDMA1)) + +/** @addtogroup DMA_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +/** @addtogroup DMA_LL_Private_Macros + * @{ + */ +#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, Channel) ((((INSTANCE) == HPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_0) || \ + ((Channel) == LL_DMA_CHANNEL_1) || \ + ((Channel) == LL_DMA_CHANNEL_2) || \ + ((Channel) == LL_DMA_CHANNEL_3) || \ + ((Channel) == LL_DMA_CHANNEL_4) || \ + ((Channel) == LL_DMA_CHANNEL_5) || \ + ((Channel) == LL_DMA_CHANNEL_6) || \ + ((Channel) == LL_DMA_CHANNEL_7) || \ + ((Channel) == LL_DMA_CHANNEL_8) || \ + ((Channel) == LL_DMA_CHANNEL_9) || \ + ((Channel) == LL_DMA_CHANNEL_10) || \ + ((Channel) == LL_DMA_CHANNEL_11) || \ + ((Channel) == LL_DMA_CHANNEL_12) || \ + ((Channel) == LL_DMA_CHANNEL_13) || \ + ((Channel) == LL_DMA_CHANNEL_14) || \ + ((Channel) == LL_DMA_CHANNEL_15) || \ + ((Channel) == LL_DMA_CHANNEL_ALL))) || \ + (((INSTANCE) == GPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_0) || \ + ((Channel) == LL_DMA_CHANNEL_1) || \ + ((Channel) == LL_DMA_CHANNEL_2) || \ + ((Channel) == LL_DMA_CHANNEL_3) || \ + ((Channel) == LL_DMA_CHANNEL_4) || \ + ((Channel) == LL_DMA_CHANNEL_5) || \ + ((Channel) == LL_DMA_CHANNEL_6) || \ + ((Channel) == LL_DMA_CHANNEL_7) || \ + ((Channel) == LL_DMA_CHANNEL_8) || \ + ((Channel) == LL_DMA_CHANNEL_9) || \ + ((Channel) == LL_DMA_CHANNEL_10) || \ + ((Channel) == LL_DMA_CHANNEL_11) || \ + ((Channel) == LL_DMA_CHANNEL_12) || \ + ((Channel) == LL_DMA_CHANNEL_13) || \ + ((Channel) == LL_DMA_CHANNEL_14) || \ + ((Channel) == LL_DMA_CHANNEL_15) || \ + ((Channel) == LL_DMA_CHANNEL_ALL)))) + +#define IS_LL_HPDMA_CHANNEL_INSTANCE(INSTANCE, Channel) (((INSTANCE) == HPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_0) || \ + ((Channel) == LL_DMA_CHANNEL_1) || \ + ((Channel) == LL_DMA_CHANNEL_2) || \ + ((Channel) == LL_DMA_CHANNEL_3) || \ + ((Channel) == LL_DMA_CHANNEL_4) || \ + ((Channel) == LL_DMA_CHANNEL_5) || \ + ((Channel) == LL_DMA_CHANNEL_6) || \ + ((Channel) == LL_DMA_CHANNEL_7) || \ + ((Channel) == LL_DMA_CHANNEL_8) || \ + ((Channel) == LL_DMA_CHANNEL_9) || \ + ((Channel) == LL_DMA_CHANNEL_10) || \ + ((Channel) == LL_DMA_CHANNEL_11) || \ + ((Channel) == LL_DMA_CHANNEL_12) || \ + ((Channel) == LL_DMA_CHANNEL_13) || \ + ((Channel) == LL_DMA_CHANNEL_14) || \ + ((Channel) == LL_DMA_CHANNEL_15))) + +#define IS_LL_GPDMA_CHANNEL_INSTANCE(INSTANCE, Channel) (((INSTANCE) == GPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_0) || \ + ((Channel) == LL_DMA_CHANNEL_1) || \ + ((Channel) == LL_DMA_CHANNEL_2) || \ + ((Channel) == LL_DMA_CHANNEL_3) || \ + ((Channel) == LL_DMA_CHANNEL_4) || \ + ((Channel) == LL_DMA_CHANNEL_5) || \ + ((Channel) == LL_DMA_CHANNEL_6) || \ + ((Channel) == LL_DMA_CHANNEL_7) || \ + ((Channel) == LL_DMA_CHANNEL_8) || \ + ((Channel) == LL_DMA_CHANNEL_9) || \ + ((Channel) == LL_DMA_CHANNEL_10) || \ + ((Channel) == LL_DMA_CHANNEL_11) || \ + ((Channel) == LL_DMA_CHANNEL_12) || \ + ((Channel) == LL_DMA_CHANNEL_13) || \ + ((Channel) == LL_DMA_CHANNEL_14) || \ + ((Channel) == LL_DMA_CHANNEL_15))) + +#define IS_LL_DMA_2D_CHANNEL_INSTANCE(INSTANCE, Channel) ((((INSTANCE) == HPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_12) || \ + ((Channel) == LL_DMA_CHANNEL_13) || \ + ((Channel) == LL_DMA_CHANNEL_14) || \ + ((Channel) == LL_DMA_CHANNEL_15))) || \ + (((INSTANCE) == GPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_12) || \ + ((Channel) == LL_DMA_CHANNEL_13) || \ + ((Channel) == LL_DMA_CHANNEL_14) || \ + ((Channel) == LL_DMA_CHANNEL_15)))) + +#define IS_LL_DMA_MODE(__VALUE__) (((__VALUE__) == LL_DMA_NORMAL) || \ + ((__VALUE__) == LL_DMA_PFCTRL)) + +#define IS_LL_DMA_PFREQ_INSTANCE(INSTANCE, Channel) ((((INSTANCE) == HPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_15))) || \ + (((INSTANCE) == GPDMA1) && \ + (((Channel) == LL_DMA_CHANNEL_0) || \ + ((Channel) == LL_DMA_CHANNEL_15)))) + +#define IS_LL_DMA_DIRECTION(__VALUE__) (((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_MEMORY) || \ + ((__VALUE__) == LL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \ + ((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_PERIPH)) + +#define IS_LL_DMA_DATA_ALIGNMENT(__VALUE__) (((__VALUE__) == LL_DMA_DATA_ALIGN_ZEROPADD) || \ + ((__VALUE__) == LL_DMA_DATA_ALIGN_SIGNEXTPADD) || \ + ((__VALUE__) == LL_DMA_DATA_PACK_UNPACK)) + +#define IS_LL_DMA_BURST_LENGTH(__VALUE__) (((__VALUE__) > 0U) && ((__VALUE__) <= 64U)) + +#define IS_LL_DMA_SRC_DATA_WIDTH(__VALUE__) (((__VALUE__) == LL_DMA_SRC_DATAWIDTH_BYTE) || \ + ((__VALUE__) == LL_DMA_SRC_DATAWIDTH_HALFWORD) || \ + ((__VALUE__) == LL_DMA_SRC_DATAWIDTH_WORD) || \ + ((__VALUE__) == LL_DMA_SRC_DATAWIDTH_DOUBLEWORD)) + +#define IS_LL_DMA_DEST_DATA_WIDTH(__VALUE__) (((__VALUE__) == LL_DMA_DEST_DATAWIDTH_BYTE) || \ + ((__VALUE__) == LL_DMA_DEST_DATAWIDTH_HALFWORD) || \ + ((__VALUE__) == LL_DMA_DEST_DATAWIDTH_WORD) || \ + ((__VALUE__) == LL_DMA_DEST_DATAWIDTH_DOUBLEWORD)) + +#define IS_LL_DMA_SRC_INCREMENT_MODE(__VALUE__) (((__VALUE__) == LL_DMA_SRC_FIXED) || \ + ((__VALUE__) == LL_DMA_SRC_INCREMENT)) + +#define IS_LL_DMA_DEST_INCREMENT_MODE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_FIXED) || \ + ((__VALUE__) == LL_DMA_DEST_INCREMENT)) + +#define IS_LL_DMA_PRIORITY(__VALUE__) (((__VALUE__) == LL_DMA_LOW_PRIORITY_LOW_WEIGHT) || \ + ((__VALUE__) == LL_DMA_LOW_PRIORITY_MID_WEIGHT) || \ + ((__VALUE__) == LL_DMA_LOW_PRIORITY_HIGH_WEIGHT) || \ + ((__VALUE__) == LL_DMA_HIGH_PRIORITY)) + +#define IS_LL_DMA_BLK_DATALENGTH(__VALUE__) ((__VALUE__) <= 0xFFFFU) + +#define IS_LL_DMA_BLK_REPEATCOUNT(__VALUE__) ((__VALUE__) <= 0x0EFFU) + +#define IS_LL_DMA_TRIGGER_MODE(__VALUE__) (((__VALUE__) == LL_DMA_TRIGM_BLK_TRANSFER) || \ + ((__VALUE__) == LL_DMA_TRIGM_RPT_BLK_TRANSFER) || \ + ((__VALUE__) == LL_DMA_TRIGM_LLI_LINK_TRANSFER) || \ + ((__VALUE__) == LL_DMA_TRIGM_SINGLBURST_TRANSFER )) + +#define IS_LL_DMA_TRIGGER_POLARITY(__VALUE__) (((__VALUE__) == LL_DMA_TRIG_POLARITY_MASKED) || \ + ((__VALUE__) == LL_DMA_TRIG_POLARITY_RISING) || \ + ((__VALUE__) == LL_DMA_TRIG_POLARITY_FALLING)) + +#define IS_LL_DMA_BLKHW_REQUEST(__VALUE__) (((__VALUE__) == LL_DMA_HWREQUEST_SINGLEBURST) || \ + ((__VALUE__) == LL_DMA_HWREQUEST_BLK)) + +#define IS_LL_DMA_TRIGGER_SELECTION(__VALUE__) ((__VALUE__) <= LL_GPDMA1_TRIGGER_TIM15_TRGO) + +#define IS_LL_DMA_REQUEST_SELECTION(__VALUE__) ((__VALUE__) <= LL_GPDMA1_REQUEST_I3C1_RS) + +#define IS_LL_DMA_TRANSFER_EVENT_MODE(__VALUE__) (((__VALUE__) == LL_DMA_TCEM_BLK_TRANSFER) || \ + ((__VALUE__) == LL_DMA_TCEM_RPT_BLK_TRANSFER) || \ + ((__VALUE__) == LL_DMA_TCEM_EACH_LLITEM_TRANSFER) || \ + ((__VALUE__) == LL_DMA_TCEM_LAST_LLITEM_TRANSFER)) + +#define IS_LL_DMA_DEST_WORD_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_WORD_PRESERVE) || \ + ((__VALUE__) == LL_DMA_DEST_WORD_EXCHANGE)) + +#define IS_LL_DMA_DEST_HALFWORD_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_HALFWORD_PRESERVE) || \ + ((__VALUE__) == LL_DMA_DEST_HALFWORD_EXCHANGE)) + +#define IS_LL_DMA_DEST_BYTE_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_DEST_BYTE_PRESERVE) || \ + ((__VALUE__) == LL_DMA_DEST_BYTE_EXCHANGE)) + +#define IS_LL_DMA_SRC_BYTE_EXCHANGE(__VALUE__) (((__VALUE__) == LL_DMA_SRC_BYTE_PRESERVE) || \ + ((__VALUE__) == LL_DMA_SRC_BYTE_EXCHANGE)) + +#define IS_LL_DMA_LINK_ALLOCATED_PORT(__VALUE__) (((__VALUE__) == LL_DMA_LINK_ALLOCATED_PORT0) || \ + ((__VALUE__) == LL_DMA_LINK_ALLOCATED_PORT1)) + +#define IS_LL_DMA_SRC_ALLOCATED_PORT(__VALUE__) (((__VALUE__) == LL_DMA_SRC_ALLOCATED_PORT0) || \ + ((__VALUE__) == LL_DMA_SRC_ALLOCATED_PORT1)) + +#define IS_LL_DMA_DEST_ALLOCATED_PORT(__VALUE__) (((__VALUE__) == LL_DMA_DEST_ALLOCATED_PORT0) || \ + ((__VALUE__) == LL_DMA_DEST_ALLOCATED_PORT1)) + +#define IS_LL_DMA_LINK_STEP_MODE(__VALUE__) (((__VALUE__) == LL_DMA_LSM_FULL_EXECUTION) || \ + ((__VALUE__) == LL_DMA_LSM_1LINK_EXECUTION)) + +#define IS_LL_DMA_BURST_SRC_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BURST_SRC_ADDR_INCREMENT) || \ + ((__VALUE__) == LL_DMA_BURST_SRC_ADDR_DECREMENT)) + +#define IS_LL_DMA_BURST_DEST_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BURST_DEST_ADDR_INCREMENT) || \ + ((__VALUE__) == LL_DMA_BURST_DEST_ADDR_DECREMENT)) + +#define IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(__VALUE__) ((__VALUE__) <= 0x1FFFU) + +#define IS_LL_DMA_BLKRPT_SRC_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BLKRPT_SRC_ADDR_INCREMENT) || \ + ((__VALUE__) == LL_DMA_BLKRPT_SRC_ADDR_DECREMENT)) + +#define IS_LL_DMA_BLKRPT_DEST_ADDR_UPDATE(__VALUE__) (((__VALUE__) == LL_DMA_BLKRPT_DEST_ADDR_INCREMENT) || \ + ((__VALUE__) == LL_DMA_BLKRPT_DEST_ADDR_DECREMENT)) + +#define IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(__VALUE__) ((__VALUE__) <= 0xFFFFU) + +#define IS_LL_DMA_LINK_BASEADDR(__VALUE__) (((__VALUE__) & 0xFFFFU) == 0U) + +#define IS_LL_DMA_LINK_ADDR_OFFSET(__VALUE__) (((__VALUE__) & 0x03U) == 0U) + +#define IS_LL_DMA_LINK_UPDATE_REGISTERS(__VALUE__) ((((__VALUE__) & 0x01FE0000U) == 0U) && ((__VALUE__) != 0U)) + +#define IS_LL_DMA_LINK_NODETYPE(__VALUE__) (((__VALUE__) == LL_DMA_HPDMA_2D_NODE) || \ + ((__VALUE__) == LL_DMA_HPDMA_LINEAR_NODE) || \ + ((__VALUE__) == LL_DMA_GPDMA_2D_NODE) || \ + ((__VALUE__) == LL_DMA_GPDMA_LINEAR_NODE)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup DMA_LL_Exported_Functions + * @{ + */ + +/** @addtogroup DMA_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the DMA registers to their default reset values. + * @note This API is used for all available DMA channels. + * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use + * helper macros : + * @arg @ref LL_DMA_GET_INSTANCE + * @arg @ref LL_DMA_GET_CHANNEL + * @param DMAx DMAx Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref LL_DMA_CHANNEL_0 + * @arg @ref LL_DMA_CHANNEL_1 + * @arg @ref LL_DMA_CHANNEL_2 + * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 + * @arg @ref LL_DMA_CHANNEL_5 + * @arg @ref LL_DMA_CHANNEL_6 + * @arg @ref LL_DMA_CHANNEL_7 + * @arg @ref LL_DMA_CHANNEL_8 + * @arg @ref LL_DMA_CHANNEL_9 + * @arg @ref LL_DMA_CHANNEL_10 + * @arg @ref LL_DMA_CHANNEL_11 + * @arg @ref LL_DMA_CHANNEL_12 + * @arg @ref LL_DMA_CHANNEL_13 + * @arg @ref LL_DMA_CHANNEL_14 + * @arg @ref LL_DMA_CHANNEL_15 + * @retval An ErrorStatus enumeration value: + * - SUCCESS : DMA registers are de-initialized. + * - ERROR : DMA registers are not de-initialized. + */ +uint32_t LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) +{ + DMA_Channel_TypeDef *tmp; + ErrorStatus status = SUCCESS; + + /* Check the DMA Instance DMAx and Channel parameters */ + assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); + + if (Channel == LL_DMA_CHANNEL_ALL) + { + if (DMAx == GPDMA1) + { + /* Force reset of DMA clock */ + LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_GPDMA1); + + /* Release reset of DMA clock */ + LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_GPDMA1); + } + else + { + /* Force reset of DMA clock */ + LL_AHB5_GRP1_ForceReset(LL_AHB5_GRP1_PERIPH_HPDMA1); + + /* Release reset of DMA clock */ + LL_AHB5_GRP1_ReleaseReset(LL_AHB5_GRP1_PERIPH_HPDMA1); + } + } + else + { + /* Get the DMA Channel Instance */ + tmp = (DMA_Channel_TypeDef *)(LL_DMA_GET_CHANNEL_INSTANCE(DMAx, Channel)); + + /* Suspend DMA channel */ + LL_DMA_SuspendChannel(DMAx, Channel); + + /* Disable the selected Channel */ + LL_DMA_ResetChannel(DMAx, Channel); + + /* Reset DMAx_Channely control register */ + LL_DMA_WriteReg(tmp, CLBAR, 0U); + + /* Reset DMAx_Channely control register */ + LL_DMA_WriteReg(tmp, CCR, 0U); + + /* Reset DMAx_Channely Configuration register */ + LL_DMA_WriteReg(tmp, CTR1, 0U); + + /* Reset DMAx_Channely transfer register 2 */ + LL_DMA_WriteReg(tmp, CTR2, 0U); + + /* Reset DMAx_Channely block number of data register */ + LL_DMA_WriteReg(tmp, CBR1, 0U); + + /* Reset DMAx_Channely source address register */ + LL_DMA_WriteReg(tmp, CSAR, 0U); + + /* Reset DMAx_Channely destination address register */ + LL_DMA_WriteReg(tmp, CDAR, 0U); + + /* Check DMA channel */ + if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) + { + /* Reset DMAx_Channely transfer register 3 */ + LL_DMA_WriteReg(tmp, CTR3, 0U); + + /* Reset DMAx_Channely Block register 2 */ + LL_DMA_WriteReg(tmp, CBR2, 0U); + } + + /* Reset DMAx_Channely Linked list address register */ + LL_DMA_WriteReg(tmp, CLLR, 0U); + + /* Reset DMAx_Channely pending flags */ + LL_DMA_WriteReg(tmp, CFCR, 0x00003F00U); + + /* Reset DMAx_Channely attribute */ + LL_DMA_DisableChannelPrivilege(DMAx, Channel); + + } + + return (uint32_t)status; +} + +/** + * @brief Initialize the DMA registers according to the specified parameters + * in DMA_InitStruct. + * @note This API is used for all available DMA channels. + * @note A software request transfer can be done once programming the direction + * field in memory to memory value. + * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use + * helper macros : + * @arg @ref LL_DMA_GET_INSTANCE + * @arg @ref LL_DMA_GET_CHANNEL + * @param DMAx DMAx Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref LL_DMA_CHANNEL_0 + * @arg @ref LL_DMA_CHANNEL_1 + * @arg @ref LL_DMA_CHANNEL_2 + * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 + * @arg @ref LL_DMA_CHANNEL_5 + * @arg @ref LL_DMA_CHANNEL_6 + * @arg @ref LL_DMA_CHANNEL_7 + * @arg @ref LL_DMA_CHANNEL_8 + * @arg @ref LL_DMA_CHANNEL_9 + * @arg @ref LL_DMA_CHANNEL_10 + * @arg @ref LL_DMA_CHANNEL_11 + * @arg @ref LL_DMA_CHANNEL_12 + * @arg @ref LL_DMA_CHANNEL_13 + * @arg @ref LL_DMA_CHANNEL_14 + * @arg @ref LL_DMA_CHANNEL_15 + * @param DMA_InitStruct pointer to a @ref LL_DMA_InitTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS : DMA registers are initialized. + * - ERROR : Not applicable. + */ +uint32_t LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitTypeDef *DMA_InitStruct) +{ + /* Check the DMA Instance DMAx and Channel parameters*/ + assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); + + /* Check the DMA parameters from DMA_InitStruct */ + assert_param(IS_LL_DMA_DIRECTION(DMA_InitStruct->Direction)); + + /* Check direction */ + if (DMA_InitStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) + { + assert_param(IS_LL_DMA_REQUEST_SELECTION(DMA_InitStruct->Request)); + } + + assert_param(IS_LL_DMA_DATA_ALIGNMENT(DMA_InitStruct->DataAlignment)); + assert_param(IS_LL_DMA_SRC_DATA_WIDTH(DMA_InitStruct->SrcDataWidth)); + assert_param(IS_LL_DMA_DEST_DATA_WIDTH(DMA_InitStruct->DestDataWidth)); + assert_param(IS_LL_DMA_SRC_INCREMENT_MODE(DMA_InitStruct->SrcIncMode)); + assert_param(IS_LL_DMA_DEST_INCREMENT_MODE(DMA_InitStruct->DestIncMode)); + assert_param(IS_LL_DMA_PRIORITY(DMA_InitStruct->Priority)); + assert_param(IS_LL_DMA_BLK_DATALENGTH(DMA_InitStruct->BlkDataLength)); + assert_param(IS_LL_DMA_TRIGGER_POLARITY(DMA_InitStruct->TriggerPolarity)); + assert_param(IS_LL_DMA_BLKHW_REQUEST(DMA_InitStruct->BlkHWRequest)); + assert_param(IS_LL_DMA_TRANSFER_EVENT_MODE(DMA_InitStruct->TransferEventMode)); + assert_param(IS_LL_DMA_LINK_STEP_MODE(DMA_InitStruct->LinkStepMode)); + assert_param(IS_LL_DMA_LINK_BASEADDR(DMA_InitStruct->LinkedListBaseAddr)); + assert_param(IS_LL_DMA_LINK_ADDR_OFFSET(DMA_InitStruct->LinkedListAddrOffset)); + assert_param(IS_LL_DMA_MODE(DMA_InitStruct->Mode)); + if (DMA_InitStruct->Mode == LL_DMA_PFCTRL) + { + assert_param(IS_LL_DMA_PFREQ_INSTANCE(DMAx, Channel)); + } + + /* Check DMA instance */ + if ((IS_LL_HPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U) || (IS_LL_GPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U)) + { + assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitStruct->SrcBurstLength)); + assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitStruct->DestBurstLength)); + assert_param(IS_LL_DMA_DEST_WORD_EXCHANGE(DMA_InitStruct->DestWordExchange)); + assert_param(IS_LL_DMA_DEST_HALFWORD_EXCHANGE(DMA_InitStruct->DestHWordExchange)); + assert_param(IS_LL_DMA_DEST_BYTE_EXCHANGE(DMA_InitStruct->DestByteExchange)); + assert_param(IS_LL_DMA_SRC_BYTE_EXCHANGE(DMA_InitStruct->SrcByteExchange)); + assert_param(IS_LL_DMA_LINK_ALLOCATED_PORT(DMA_InitStruct->LinkAllocatedPort)); + assert_param(IS_LL_DMA_SRC_ALLOCATED_PORT(DMA_InitStruct->SrcAllocatedPort)); + assert_param(IS_LL_DMA_DEST_ALLOCATED_PORT(DMA_InitStruct->DestAllocatedPort)); + } + + /* Check trigger polarity */ + if (DMA_InitStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) + { + assert_param(IS_LL_DMA_TRIGGER_MODE(DMA_InitStruct->TriggerMode)); + assert_param(IS_LL_DMA_TRIGGER_SELECTION(DMA_InitStruct->TriggerSelection)); + } + + /* Check DMA channel */ + if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) + { + assert_param(IS_LL_DMA_BLK_REPEATCOUNT(DMA_InitStruct->BlkRptCount)); + assert_param(IS_LL_DMA_BURST_SRC_ADDR_UPDATE(DMA_InitStruct->SrcAddrUpdateMode)); + assert_param(IS_LL_DMA_BURST_DEST_ADDR_UPDATE(DMA_InitStruct->DestAddrUpdateMode)); + assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitStruct->SrcAddrOffset)); + assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitStruct->DestAddrOffset)); + assert_param(IS_LL_DMA_BLKRPT_SRC_ADDR_UPDATE(DMA_InitStruct->BlkRptSrcAddrUpdateMode)); + assert_param(IS_LL_DMA_BLKRPT_DEST_ADDR_UPDATE(DMA_InitStruct->BlkRptDestAddrUpdateMode)); + assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitStruct->BlkRptSrcAddrOffset)); + assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitStruct->BlkRptDestAddrOffset)); + } + + /*-------------------------- DMAx CLBAR Configuration ------------------------ + * Configure the Transfer linked list address with parameter : + * - LinkedListBaseAdd: DMA_CLBAR_LBA[31:16] bits + */ + LL_DMA_SetLinkedListBaseAddr(DMAx, Channel, DMA_InitStruct->LinkedListBaseAddr); + + /*-------------------------- DMAx CCR Configuration -------------------------- + * Configure the control parameter : + * - LinkAllocatedPort: DMA_CCR_LAP bit + * - LinkStepMode: DMA_CCR_LSM bit + * - Priority: DMA_CCR_PRIO [23:22] bits + */ + LL_DMA_ConfigControl(DMAx, Channel, DMA_InitStruct->Priority | \ + DMA_InitStruct->LinkAllocatedPort | \ + DMA_InitStruct->LinkStepMode); + + /*-------------------------- DMAx CTR1 Configuration ------------------------- + * Configure the Data transfer parameter : + * - DestAllocatedPort: DMA_CTR1_DAP bit + * - DestWordExchange: DMA_CTR1_DWX bit + * - DestHWordExchange: DMA_CTR1_DHX bit + * - DestByteExchange: DMA_CTR1_DBX bit + * - DestIncMode: DMA_CTR1_DINC bit + * - DestDataWidth: DMA_CTR1_DDW_LOG2 [17:16] bits + * - SrcAllocatedPort: DMA_CTR1_SAP bit + * - SrcByteExchange: DMA_CTR1_SBX bit + * - DataAlignment: DMA_CTR1_PAM [12:11] bits + * - SrcIncMode: DMA_CTR1_SINC bit + * - SrcDataWidth: DMA_CTR1_SDW_LOG2 [1:0] bits + * - SrcBurstLength: DMA_CTR1_SBL_1 [9:4] bits + * - DestBurstLength: DMA_CTR1_DBL_1 [25:20] bits + */ + LL_DMA_ConfigTransfer(DMAx, Channel, DMA_InitStruct->DestAllocatedPort | \ + DMA_InitStruct->DestWordExchange | \ + DMA_InitStruct->DestHWordExchange | \ + DMA_InitStruct->DestByteExchange | \ + DMA_InitStruct->DestIncMode | \ + DMA_InitStruct->DestDataWidth | \ + DMA_InitStruct->SrcAllocatedPort | \ + DMA_InitStruct->SrcByteExchange | \ + DMA_InitStruct->DataAlignment | \ + DMA_InitStruct->SrcIncMode | \ + DMA_InitStruct->SrcDataWidth); + /* Check DMA instance */ + if ((IS_LL_HPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U) || (IS_LL_GPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U)) + { + LL_DMA_ConfigBurstLength(DMAx, Channel, DMA_InitStruct->SrcBurstLength, + DMA_InitStruct->DestBurstLength); + } + + /*-------------------------- DMAx CTR2 Configuration ------------------------- + * Configure the channel transfer parameter : + * - TransferEventMode: DMA_CTR2_TCEM [31:30] bits + * - TriggerPolarity: DMA_CTR2_TRIGPOL [25:24] bits + * - TriggerMode: DMA_CTR2_TRIGM [15:14] bits + * - BlkHWRequest: DMA_CTR2_BREQ bit + * - Mode: DMA_CTR2_PFREQ bit + * - Direction: DMA_CTR2_DREQ bit + * - Direction: DMA_CTR2_SWREQ bit + * - TriggerSelection: DMA_CTR2_TRIGSEL [21:16] bits + * - Request: DMA_CTR2_REQSEL [6:0] bits + */ + LL_DMA_ConfigChannelTransfer(DMAx, Channel, DMA_InitStruct->TransferEventMode | \ + DMA_InitStruct->TriggerPolarity | \ + DMA_InitStruct->BlkHWRequest | \ + DMA_InitStruct->Mode | \ + DMA_InitStruct->Direction); + + /* Check direction */ + if (DMA_InitStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) + { + LL_DMA_SetPeriphRequest(DMAx, Channel, DMA_InitStruct->Request); + } + + /* Check trigger polarity */ + if (DMA_InitStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) + { + LL_DMA_SetHWTrigger(DMAx, Channel, DMA_InitStruct->TriggerSelection); + LL_DMA_SetTriggerMode(DMAx, Channel, DMA_InitStruct->TriggerMode); + } + + /*-------------------------- DMAx CBR1 Configuration ------------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - BlkDataLength: DMA_CBR1_BNDT[15:0] bits + * - BlkRptCount: DMA_CBR1_BRC[26:16] bits + * BlkRptCount field is supported only by 2D addressing channels. + * - BlkRptSrcAddrUpdateMode: DMA_CBR1_BRSDEC bit + * BlkRptSrcAddrUpdateMode field is supported only by 2D addressing channels. + * - BlkRptDestAddrUpdateMode: DMA_CBR1_BRDDEC bit + * BlkRptDestAddrUpdateMode field is supported only by 2D addressing channels. + * - SrcAddrUpdateMode: DMA_CBR1_SDEC bit + * SrcAddrUpdateMode field is supported only by 2D addressing channels. + * - DestAddrUpdateMode: DMA_CBR1_DDEC bit + * DestAddrUpdateMode field is supported only by 2D addressing channels. + */ + LL_DMA_SetBlkDataLength(DMAx, Channel, DMA_InitStruct->BlkDataLength); + + /* Check DMA channel */ + if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) + { + LL_DMA_SetBlkRptCount(DMAx, Channel, DMA_InitStruct->BlkRptCount); + LL_DMA_ConfigBlkRptAddrUpdate(DMAx, Channel, DMA_InitStruct->BlkRptSrcAddrUpdateMode | \ + DMA_InitStruct->BlkRptDestAddrUpdateMode | \ + DMA_InitStruct->SrcAddrUpdateMode | \ + DMA_InitStruct->DestAddrUpdateMode); + } + + /*-------------------------- DMAx CSAR and CDAR Configuration ---------------- + * Configure the Transfer source address with parameter : + * - SrcAddress: DMA_CSAR_SA[31:0] bits + * - DestAddress: DMA_CDAR_DA[31:0] bits + */ + LL_DMA_ConfigAddresses(DMAx, Channel, DMA_InitStruct->SrcAddress, DMA_InitStruct->DestAddress); + + /* Check DMA channel */ + if (IS_LL_DMA_2D_CHANNEL_INSTANCE(DMAx, Channel) != 0U) + { + /*------------------------ DMAx CTR3 Configuration ------------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - SrcAddrOffset: DMA_CTR3_SAO[28:16] bits + * SrcAddrOffset field is supported only by 2D addressing channels. + * - DestAddrOffset: DMA_CTR3_DAO[12:0] bits + * DestAddrOffset field is supported only by 2D addressing channels. + */ + LL_DMA_ConfigAddrUpdateValue(DMAx, Channel, DMA_InitStruct->SrcAddrOffset, DMA_InitStruct->DestAddrOffset); + + /*------------------------ DMAx CBR2 Configuration ----------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - BlkRptSrcAddrOffset: DMA_CBR2_BRSAO[15:0] bits + * BlkRptSrcAddrOffset field is supported only by 2D addressing channels. + * - BlkRptDestAddrOffset: DMA_CBR2_BRDAO[31:16] bits + * BlkRptDestAddrOffset field is supported only by 2D addressing channels. + */ + LL_DMA_ConfigBlkRptAddrUpdateValue(DMAx, Channel, DMA_InitStruct->BlkRptSrcAddrOffset, + DMA_InitStruct->BlkRptDestAddrOffset); + } + + /*-------------------------- DMAx CLLR Configuration ------------------------- + * Configure the Transfer linked list address with parameter : + * - DestAddrOffset: DMA_CLLR_LA[15:2] bits + */ + LL_DMA_SetLinkedListAddrOffset(DMAx, Channel, DMA_InitStruct->LinkedListAddrOffset); + + return (uint32_t)SUCCESS; +} + +/** + * @brief Set each @ref LL_DMA_InitTypeDef field to default value. + * @param DMA_InitStruct Pointer to a @ref LL_DMA_InitTypeDef structure. + * @retval None. + */ +void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct) +{ + /* Set DMA_InitStruct fields to default values */ + DMA_InitStruct->SrcAddress = 0x00000000U; + DMA_InitStruct->DestAddress = 0x00000000U; + DMA_InitStruct->Direction = LL_DMA_DIRECTION_MEMORY_TO_MEMORY; + DMA_InitStruct->BlkHWRequest = LL_DMA_HWREQUEST_SINGLEBURST; + DMA_InitStruct->DataAlignment = LL_DMA_DATA_ALIGN_ZEROPADD; + DMA_InitStruct->SrcBurstLength = 1U; + DMA_InitStruct->DestBurstLength = 1U; + DMA_InitStruct->SrcDataWidth = LL_DMA_SRC_DATAWIDTH_BYTE; + DMA_InitStruct->DestDataWidth = LL_DMA_DEST_DATAWIDTH_BYTE; + DMA_InitStruct->SrcIncMode = LL_DMA_SRC_FIXED; + DMA_InitStruct->DestIncMode = LL_DMA_DEST_FIXED; + DMA_InitStruct->Priority = LL_DMA_LOW_PRIORITY_LOW_WEIGHT; + DMA_InitStruct->BlkDataLength = 0x00000000U; + DMA_InitStruct->Mode = LL_DMA_NORMAL; + DMA_InitStruct->BlkRptCount = 0x00000000U; + DMA_InitStruct->TriggerMode = LL_DMA_TRIGM_BLK_TRANSFER; + DMA_InitStruct->TriggerPolarity = LL_DMA_TRIG_POLARITY_MASKED; + DMA_InitStruct->TriggerSelection = 0x00000000U; + DMA_InitStruct->Request = 0x00000000U; + DMA_InitStruct->TransferEventMode = LL_DMA_TCEM_BLK_TRANSFER; + DMA_InitStruct->DestWordExchange = LL_DMA_DEST_WORD_PRESERVE; + DMA_InitStruct->DestHWordExchange = LL_DMA_DEST_HALFWORD_PRESERVE; + DMA_InitStruct->DestByteExchange = LL_DMA_DEST_BYTE_PRESERVE; + DMA_InitStruct->SrcByteExchange = LL_DMA_SRC_BYTE_PRESERVE; + DMA_InitStruct->SrcAllocatedPort = LL_DMA_SRC_ALLOCATED_PORT0; + DMA_InitStruct->DestAllocatedPort = LL_DMA_DEST_ALLOCATED_PORT0; + DMA_InitStruct->LinkAllocatedPort = LL_DMA_LINK_ALLOCATED_PORT0; + DMA_InitStruct->LinkStepMode = LL_DMA_LSM_FULL_EXECUTION; + DMA_InitStruct->SrcAddrUpdateMode = LL_DMA_BURST_SRC_ADDR_INCREMENT; + DMA_InitStruct->DestAddrUpdateMode = LL_DMA_BURST_DEST_ADDR_INCREMENT; + DMA_InitStruct->SrcAddrOffset = 0x00000000U; + DMA_InitStruct->DestAddrOffset = 0x00000000U; + DMA_InitStruct->BlkRptSrcAddrUpdateMode = LL_DMA_BLKRPT_SRC_ADDR_INCREMENT; + DMA_InitStruct->BlkRptDestAddrUpdateMode = LL_DMA_BLKRPT_DEST_ADDR_INCREMENT; + DMA_InitStruct->BlkRptSrcAddrOffset = 0x00000000U; + DMA_InitStruct->BlkRptDestAddrOffset = 0x00000000U; + DMA_InitStruct->LinkedListBaseAddr = 0x00000000U; + DMA_InitStruct->LinkedListAddrOffset = 0x00000000U; +} + +/** + * @brief Set each @ref LL_DMA_InitLinkedListTypeDef field to default value. + * @param DMA_InitLinkedListStruct Pointer to + * a @ref LL_DMA_InitLinkedListTypeDef structure. + * @retval None. + */ +void LL_DMA_ListStructInit(LL_DMA_InitLinkedListTypeDef *DMA_InitLinkedListStruct) +{ + /* Set LL_DMA_InitLinkedListTypeDef fields to default values */ + DMA_InitLinkedListStruct->Priority = LL_DMA_LOW_PRIORITY_LOW_WEIGHT; + DMA_InitLinkedListStruct->LinkStepMode = LL_DMA_LSM_FULL_EXECUTION; + DMA_InitLinkedListStruct->TransferEventMode = LL_DMA_TCEM_LAST_LLITEM_TRANSFER; + DMA_InitLinkedListStruct->LinkAllocatedPort = LL_DMA_LINK_ALLOCATED_PORT0; +} + +/** + * @brief De-initialize the DMA linked list. + * @note This API is used for all available DMA channels. + * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use + * helper macros : + * @arg @ref LL_DMA_GET_INSTANCE + * @arg @ref LL_DMA_GET_CHANNEL + * @param DMAx DMAx Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref LL_DMA_CHANNEL_0 + * @arg @ref LL_DMA_CHANNEL_1 + * @arg @ref LL_DMA_CHANNEL_2 + * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 + * @arg @ref LL_DMA_CHANNEL_5 + * @arg @ref LL_DMA_CHANNEL_6 + * @arg @ref LL_DMA_CHANNEL_7 + * @arg @ref LL_DMA_CHANNEL_8 + * @arg @ref LL_DMA_CHANNEL_9 + * @arg @ref LL_DMA_CHANNEL_10 + * @arg @ref LL_DMA_CHANNEL_11 + * @arg @ref LL_DMA_CHANNEL_12 + * @arg @ref LL_DMA_CHANNEL_13 + * @arg @ref LL_DMA_CHANNEL_14 + * @arg @ref LL_DMA_CHANNEL_15 + * @retval An ErrorStatus enumeration value: + * - SUCCESS : DMA registers are de-initialized. + * - ERROR : DMA registers are not de-initialized. + */ +uint32_t LL_DMA_List_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) +{ + return LL_DMA_DeInit(DMAx, Channel); +} + +/** + * @brief Initialize the DMA linked list according to the specified parameters + * in LL_DMA_InitLinkedListTypeDef. + * @note This API is used for all available DMA channels. + * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use + * helper macros : + * @arg @ref LL_DMA_GET_INSTANCE + * @arg @ref LL_DMA_GET_CHANNEL + * @param DMAx DMAx Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref LL_DMA_CHANNEL_0 + * @arg @ref LL_DMA_CHANNEL_1 + * @arg @ref LL_DMA_CHANNEL_2 + * @arg @ref LL_DMA_CHANNEL_3 + * @arg @ref LL_DMA_CHANNEL_4 + * @arg @ref LL_DMA_CHANNEL_5 + * @arg @ref LL_DMA_CHANNEL_6 + * @arg @ref LL_DMA_CHANNEL_7 + * @arg @ref LL_DMA_CHANNEL_8 + * @arg @ref LL_DMA_CHANNEL_9 + * @arg @ref LL_DMA_CHANNEL_10 + * @arg @ref LL_DMA_CHANNEL_11 + * @arg @ref LL_DMA_CHANNEL_12 + * @arg @ref LL_DMA_CHANNEL_13 + * @arg @ref LL_DMA_CHANNEL_14 + * @arg @ref LL_DMA_CHANNEL_15 + * @param DMA_InitLinkedListStruct pointer to + * a @ref LL_DMA_InitLinkedListTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS : DMA registers are initialized. + * - ERROR : Not applicable. + */ +uint32_t LL_DMA_List_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitLinkedListTypeDef *DMA_InitLinkedListStruct) +{ + /* Check the DMA Instance DMAx and Channel parameters*/ + assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); + + /* Check the DMA parameters from DMA_InitLinkedListStruct */ + assert_param(IS_LL_DMA_PRIORITY(DMA_InitLinkedListStruct->Priority)); + assert_param(IS_LL_DMA_LINK_STEP_MODE(DMA_InitLinkedListStruct->LinkStepMode)); + assert_param(IS_LL_DMA_TRANSFER_EVENT_MODE(DMA_InitLinkedListStruct->TransferEventMode)); + /* Check DMA instance */ + if ((IS_LL_HPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U) || (IS_LL_GPDMA_CHANNEL_INSTANCE(DMAx, Channel) != 0U)) + { + assert_param(IS_LL_DMA_LINK_ALLOCATED_PORT(DMA_InitLinkedListStruct->LinkAllocatedPort)); + } + + /*-------------------------- DMAx CCR Configuration -------------------------- + * Configure the control parameter : + * - LinkAllocatedPort: DMA_CCR_LAP bit + * LinkAllocatedPort field is supported only by GPDMA channels. + * - LinkStepMode: DMA_CCR_LSM bit + * - Priority: DMA_CCR_PRIO [23:22] bits + */ + LL_DMA_ConfigControl(DMAx, Channel, DMA_InitLinkedListStruct->Priority | \ + DMA_InitLinkedListStruct->LinkAllocatedPort | \ + DMA_InitLinkedListStruct->LinkStepMode); + + /*-------------------------- DMAx CTR2 Configuration ------------------------- + * Configure the channel transfer parameter : + * - TransferEventMode: DMA_CTR2_TCEM [31:30] bits + */ + LL_DMA_SetTransferEventMode(DMAx, Channel, DMA_InitLinkedListStruct->TransferEventMode); + + return (uint32_t)SUCCESS; +} + +/** + * @brief Set each @ref LL_DMA_InitNodeTypeDef field to default value. + * @param DMA_InitNodeStruct Pointer to a @ref LL_DMA_InitNodeTypeDef + * structure. + * @retval None. + */ +void LL_DMA_NodeStructInit(LL_DMA_InitNodeTypeDef *DMA_InitNodeStruct) +{ + /* Set DMA_InitNodeStruct fields to default values */ + DMA_InitNodeStruct->DestAllocatedPort = LL_DMA_DEST_ALLOCATED_PORT0; + DMA_InitNodeStruct->DestWordExchange = LL_DMA_DEST_WORD_PRESERVE; + DMA_InitNodeStruct->DestHWordExchange = LL_DMA_DEST_HALFWORD_PRESERVE; + DMA_InitNodeStruct->DestByteExchange = LL_DMA_DEST_BYTE_PRESERVE; + DMA_InitNodeStruct->DestBurstLength = 1U; + DMA_InitNodeStruct->DestIncMode = LL_DMA_DEST_FIXED; + DMA_InitNodeStruct->DestDataWidth = LL_DMA_DEST_DATAWIDTH_BYTE; + DMA_InitNodeStruct->SrcAllocatedPort = LL_DMA_SRC_ALLOCATED_PORT0; + DMA_InitNodeStruct->SrcByteExchange = LL_DMA_SRC_BYTE_PRESERVE; + DMA_InitNodeStruct->DataAlignment = LL_DMA_DATA_ALIGN_ZEROPADD; + DMA_InitNodeStruct->SrcBurstLength = 1U; + DMA_InitNodeStruct->SrcIncMode = LL_DMA_SRC_FIXED; + DMA_InitNodeStruct->SrcDataWidth = LL_DMA_SRC_DATAWIDTH_BYTE; + DMA_InitNodeStruct->TransferEventMode = LL_DMA_TCEM_BLK_TRANSFER; + DMA_InitNodeStruct->TriggerPolarity = LL_DMA_TRIG_POLARITY_MASKED; + DMA_InitNodeStruct->TriggerSelection = 0x00000000U; + DMA_InitNodeStruct->TriggerMode = LL_DMA_TRIGM_BLK_TRANSFER; + DMA_InitNodeStruct->BlkHWRequest = LL_DMA_HWREQUEST_SINGLEBURST; + DMA_InitNodeStruct->Direction = LL_DMA_DIRECTION_MEMORY_TO_MEMORY; + DMA_InitNodeStruct->Request = 0x00000000U; + DMA_InitNodeStruct->Mode = LL_DMA_NORMAL; + DMA_InitNodeStruct->BlkRptDestAddrUpdateMode = LL_DMA_BLKRPT_DEST_ADDR_INCREMENT; + DMA_InitNodeStruct->BlkRptSrcAddrUpdateMode = LL_DMA_BLKRPT_SRC_ADDR_INCREMENT; + DMA_InitNodeStruct->DestAddrUpdateMode = LL_DMA_BURST_DEST_ADDR_INCREMENT; + DMA_InitNodeStruct->SrcAddrUpdateMode = LL_DMA_BURST_SRC_ADDR_INCREMENT; + DMA_InitNodeStruct->BlkRptCount = 0x00000000U; + DMA_InitNodeStruct->BlkDataLength = 0x00000000U; + DMA_InitNodeStruct->SrcAddress = 0x00000000U; + DMA_InitNodeStruct->DestAddress = 0x00000000U; + DMA_InitNodeStruct->DestAddrOffset = 0x00000000U; + DMA_InitNodeStruct->SrcAddrOffset = 0x00000000U; + DMA_InitNodeStruct->BlkRptDestAddrOffset = 0x00000000U; + DMA_InitNodeStruct->BlkRptSrcAddrOffset = 0x00000000U; + DMA_InitNodeStruct->UpdateRegisters = (LL_DMA_UPDATE_CTR1 | LL_DMA_UPDATE_CTR2 | \ + LL_DMA_UPDATE_CBR1 | LL_DMA_UPDATE_CSAR | \ + LL_DMA_UPDATE_CDAR | LL_DMA_UPDATE_CTR3 | \ + LL_DMA_UPDATE_CBR2 | LL_DMA_UPDATE_CLLR); + DMA_InitNodeStruct->NodeType = LL_DMA_GPDMA_LINEAR_NODE; +} + +/** + * @brief Initializes DMA linked list node according to the specified + * parameters in the DMA_InitNodeStruct. + * @param DMA_InitNodeStruct Pointer to a LL_DMA_InitNodeTypeDef structure + * that contains linked list node + * registers configurations. + * @param pNode Pointer to linked list node to fill according to + * LL_DMA_LinkNodeTypeDef parameters. + * @retval None + */ +uint32_t LL_DMA_CreateLinkNode(const LL_DMA_InitNodeTypeDef *DMA_InitNodeStruct, LL_DMA_LinkNodeTypeDef *pNode) +{ + uint32_t reg_counter = 0U; + + /* Check the DMA Node type */ + assert_param(IS_LL_DMA_LINK_NODETYPE(DMA_InitNodeStruct->NodeType)); + + /* Check the DMA parameters from DMA_InitNodeStruct */ + assert_param(IS_LL_DMA_DIRECTION(DMA_InitNodeStruct->Direction)); + + /* Check direction */ + if (DMA_InitNodeStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) + { + assert_param(IS_LL_DMA_REQUEST_SELECTION(DMA_InitNodeStruct->Request)); + } + + assert_param(IS_LL_DMA_DATA_ALIGNMENT(DMA_InitNodeStruct->DataAlignment)); + assert_param(IS_LL_DMA_SRC_DATA_WIDTH(DMA_InitNodeStruct->SrcDataWidth)); + assert_param(IS_LL_DMA_DEST_DATA_WIDTH(DMA_InitNodeStruct->DestDataWidth)); + assert_param(IS_LL_DMA_SRC_INCREMENT_MODE(DMA_InitNodeStruct->SrcIncMode)); + assert_param(IS_LL_DMA_DEST_INCREMENT_MODE(DMA_InitNodeStruct->DestIncMode)); + assert_param(IS_LL_DMA_BLK_DATALENGTH(DMA_InitNodeStruct->BlkDataLength)); + assert_param(IS_LL_DMA_TRIGGER_POLARITY(DMA_InitNodeStruct->TriggerPolarity)); + assert_param(IS_LL_DMA_BLKHW_REQUEST(DMA_InitNodeStruct->BlkHWRequest)); + assert_param(IS_LL_DMA_TRANSFER_EVENT_MODE(DMA_InitNodeStruct->TransferEventMode)); + assert_param(IS_LL_DMA_LINK_UPDATE_REGISTERS(DMA_InitNodeStruct->UpdateRegisters)); + assert_param(IS_LL_DMA_MODE(DMA_InitNodeStruct->Mode)); + + /* Check trigger polarity */ + if (DMA_InitNodeStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) + { + assert_param(IS_LL_DMA_TRIGGER_MODE(DMA_InitNodeStruct->TriggerMode)); + assert_param(IS_LL_DMA_TRIGGER_SELECTION(DMA_InitNodeStruct->TriggerSelection)); + } + + /* Check node type */ + if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_LINEAR_NODE) || \ + (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_LINEAR_NODE)) + { + assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitNodeStruct->SrcBurstLength)); + assert_param(IS_LL_DMA_BURST_LENGTH(DMA_InitNodeStruct->DestBurstLength)); + assert_param(IS_LL_DMA_DEST_WORD_EXCHANGE(DMA_InitNodeStruct->DestWordExchange)); + assert_param(IS_LL_DMA_DEST_HALFWORD_EXCHANGE(DMA_InitNodeStruct->DestHWordExchange)); + assert_param(IS_LL_DMA_DEST_BYTE_EXCHANGE(DMA_InitNodeStruct->DestByteExchange)); + assert_param(IS_LL_DMA_SRC_BYTE_EXCHANGE(DMA_InitNodeStruct->SrcByteExchange)); + assert_param(IS_LL_DMA_SRC_ALLOCATED_PORT(DMA_InitNodeStruct->SrcAllocatedPort)); + assert_param(IS_LL_DMA_DEST_ALLOCATED_PORT(DMA_InitNodeStruct->DestAllocatedPort)); + } + + /* Check DMA channel */ + if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || \ + (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) + { + assert_param(IS_LL_DMA_BLK_REPEATCOUNT(DMA_InitNodeStruct->BlkRptCount)); + assert_param(IS_LL_DMA_BURST_SRC_ADDR_UPDATE(DMA_InitNodeStruct->SrcAddrUpdateMode)); + assert_param(IS_LL_DMA_BURST_DEST_ADDR_UPDATE(DMA_InitNodeStruct->DestAddrUpdateMode)); + assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->SrcAddrOffset)); + assert_param(IS_LL_DMA_BURST_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->DestAddrOffset)); + assert_param(IS_LL_DMA_BLKRPT_SRC_ADDR_UPDATE(DMA_InitNodeStruct->BlkRptSrcAddrUpdateMode)); + assert_param(IS_LL_DMA_BLKRPT_DEST_ADDR_UPDATE(DMA_InitNodeStruct->BlkRptDestAddrUpdateMode)); + assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->BlkRptSrcAddrOffset)); + assert_param(IS_LL_DMA_BLKRPT_ADDR_UPDATE_VALUE(DMA_InitNodeStruct->BlkRptDestAddrOffset)); + } + + /* Check if CTR1 register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CTR1) == LL_DMA_UPDATE_CTR1) + { + /*-------------------------- DMAx CTR1 Configuration ----------------------- + * Configure the Data transfer parameter : + * - DestAllocatedPort: DMA_CTR1_DAP bit + * - DestWordExchange: DMA_CTR1_DWX bit + * - DestHWordExchange: DMA_CTR1_DHX bit + * - DestByteExchange: DMA_CTR1_DBX bit + * - DestIncMode: DMA_CTR1_DINC bit + * - DestDataWidth: DMA_CTR1_DDW_LOG2 [17:16] bits + * - SrcAllocatedPort: DMA_CTR1_SAP bit + * - SrcByteExchange: DMA_CTR1_SBX bit + * - DataAlignment: DMA_CTR1_PAM [12:11] bits + * - SrcIncMode: DMA_CTR1_SINC bit + * - SrcDataWidth: DMA_CTR1_SDW_LOG2 [1:0] bits + * - SrcBurstLength: DMA_CTR1_SBL_1 [9:4] bits + * - DestBurstLength: DMA_CTR1_DBL_1 [25:20] bits + */ + + pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->DestIncMode | \ + DMA_InitNodeStruct->DestDataWidth | \ + DMA_InitNodeStruct->DataAlignment | \ + DMA_InitNodeStruct->SrcIncMode | \ + DMA_InitNodeStruct->SrcDataWidth); + + /* Update CTR1 register fields */ + pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->DestAllocatedPort | \ + DMA_InitNodeStruct->DestWordExchange | \ + DMA_InitNodeStruct->DestHWordExchange | \ + DMA_InitNodeStruct->DestByteExchange | \ + ((DMA_InitNodeStruct->DestBurstLength - 1U) << DMA_CTR1_DBL_1_Pos) | \ + DMA_InitNodeStruct->SrcAllocatedPort | \ + DMA_InitNodeStruct->SrcByteExchange | \ + ((DMA_InitNodeStruct->SrcBurstLength - 1U) << DMA_CTR1_SBL_1_Pos)); + + /* Increment counter for the next register */ + reg_counter++; + } + + + /* Check if CTR2 register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CTR2) == LL_DMA_UPDATE_CTR2) + { + /*-------------------------- DMAx CTR2 Configuration ----------------------- + * Configure the channel transfer parameter : + * - TransferEventMode: DMA_CTR2_TCEM [31:30] bits + * - TriggerPolarity: DMA_CTR2_TRIGPOL [25:24] bits + * - TriggerMode: DMA_CTR2_TRIGM [15:14] bits + * - Mode: DMA_CTR2_PFREQ bit + * - BlkHWRequest: DMA_CTR2_BREQ bit + * - Direction: DMA_CTR2_DREQ bit + * - Direction: DMA_CTR2_SWREQ bit + * - TriggerSelection: DMA_CTR2_TRIGSEL [21:16] bits + * - Request: DMA_CTR2_REQSEL [6:0] bits + */ + pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->TransferEventMode | \ + DMA_InitNodeStruct->TriggerPolarity | \ + DMA_InitNodeStruct->BlkHWRequest | \ + DMA_InitNodeStruct->Mode | \ + DMA_InitNodeStruct->Direction); + + /* Check direction */ + if (DMA_InitNodeStruct->Direction != LL_DMA_DIRECTION_MEMORY_TO_MEMORY) + { + pNode->LinkRegisters[reg_counter] |= DMA_InitNodeStruct->Request & DMA_CTR2_REQSEL; + } + + /* Check trigger polarity */ + if (DMA_InitNodeStruct->TriggerPolarity != LL_DMA_TRIG_POLARITY_MASKED) + { + pNode->LinkRegisters[reg_counter] |= (((DMA_InitNodeStruct->TriggerSelection << DMA_CTR2_TRIGSEL_Pos) & \ + DMA_CTR2_TRIGSEL) | DMA_InitNodeStruct->TriggerMode); + } + + + /* Increment counter for the next register */ + reg_counter++; + } + + /* Check if CBR1 register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CBR1) == LL_DMA_UPDATE_CBR1) + { + /*-------------------------- DMAx CBR1 Configuration ----------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - BlkDataLength: DMA_CBR1_BNDT[15:0] bits + * - BlkRptCount: DMA_CBR1_BRC[26:16] bits + * BlkRptCount field is supported only by 2D addressing channels. + * - BlkRptSrcAddrUpdateMode: DMA_CBR1_BRSDEC bit + * BlkRptSrcAddrUpdateMode field is supported only by 2D addressing channels. + * - BlkRptDestAddrUpdateMode: DMA_CBR1_BRDDEC bit + * BlkRptDestAddrUpdateMode field is supported only by 2D addressing channels. + * - SrcAddrUpdateMode: DMA_CBR1_SDEC bit + * SrcAddrUpdateMode field is supported only by 2D addressing channels. + * - DestAddrUpdateMode: DMA_CBR1_DDEC bit + * DestAddrUpdateMode field is supported only by 2D addressing channels. + */ + pNode->LinkRegisters[reg_counter] = DMA_InitNodeStruct->BlkDataLength; + + /* Update CBR1 register fields for 2D addressing channels */ + if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || \ + (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) + { + pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->BlkRptDestAddrUpdateMode | \ + DMA_InitNodeStruct->BlkRptSrcAddrUpdateMode | \ + DMA_InitNodeStruct->DestAddrUpdateMode | \ + DMA_InitNodeStruct->SrcAddrUpdateMode | \ + ((DMA_InitNodeStruct->BlkRptCount << DMA_CBR1_BRC_Pos) & DMA_CBR1_BRC)); + } + + /* Increment counter for the next register */ + reg_counter++; + } + + /* Check if CSAR register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CSAR) == LL_DMA_UPDATE_CSAR) + { + /*-------------------------- DMAx CSAR Configuration ----------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - SrcAddress: DMA_CSAR_SA[31:0] bits + */ + pNode->LinkRegisters[reg_counter] = DMA_InitNodeStruct->SrcAddress; + + /* Increment counter for the next register */ + reg_counter++; + } + + + /* Check if CDAR register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CDAR) == LL_DMA_UPDATE_CDAR) + { + /*-------------------------- DMAx CDAR Configuration ----------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - DestAddress: DMA_CDAR_DA[31:0] bits + */ + pNode->LinkRegisters[reg_counter] = DMA_InitNodeStruct->DestAddress; + + /* Increment counter for the next register */ + reg_counter++; + } + + + /* Update CTR3 register fields for 2D addressing channels */ + if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) + { + /* Check if CTR3 register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CTR3) == LL_DMA_UPDATE_CTR3) + { + /*-------------------------- DMAx CTR3 Configuration --------------------- + * Configure the Block counters and update mode with parameter : + * - DestAddressOffset: DMA_CTR3_DAO[12:0] bits + * DestAddressOffset field is supported only by 2D addressing channels. + * - SrcAddressOffset: DMA_CTR3_SAO[12:0] bits + * SrcAddressOffset field is supported only by 2D addressing channels. + */ + pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->SrcAddrOffset | \ + ((DMA_InitNodeStruct->DestAddrOffset << DMA_CTR3_DAO_Pos) & DMA_CTR3_DAO)); + + /* Increment counter for the next register */ + reg_counter++; + } + } + + + /* Update CBR2 register fields for 2D addressing channels */ + if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) + { + /* Check if CBR2 register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CBR2) == LL_DMA_UPDATE_CBR2) + { + /*-------------------------- DMAx CBR2 Configuration --------------------- + * Configure the Block counters and update mode with parameter : + * - BlkRptDestAddrOffset: DMA_CBR2_BRDAO[31:16] bits + * BlkRptDestAddrOffset field is supported only by 2D addressing channels. + * - BlkRptSrcAddrOffset: DMA_CBR2_BRSAO[15:0] bits + * BlkRptSrcAddrOffset field is supported only by 2D addressing channels. + */ + pNode->LinkRegisters[reg_counter] = (DMA_InitNodeStruct->BlkRptSrcAddrOffset | \ + ((DMA_InitNodeStruct->BlkRptDestAddrOffset << DMA_CBR2_BRDAO_Pos) & \ + DMA_CBR2_BRDAO)); + + /* Increment counter for the next register */ + reg_counter++; + } + } + + /* Check if CLLR register update is enabled */ + if ((DMA_InitNodeStruct->UpdateRegisters & LL_DMA_UPDATE_CLLR) == LL_DMA_UPDATE_CLLR) + { + /*-------------------------- DMAx CLLR Configuration ----------------------- + * Configure the Transfer Block counters and update mode with parameter : + * - UpdateRegisters DMA_CLLR_UT1 bit + * - UpdateRegisters DMA_CLLR_UT2 bit + * - UpdateRegisters DMA_CLLR_UB1 bit + * - UpdateRegisters DMA_CLLR_USA bit + * - UpdateRegisters DMA_CLLR_UDA bit + * - UpdateRegisters DMA_CLLR_UT3 bit + * DMA_CLLR_UT3 bit is discarded for linear addressing channels. + * - UpdateRegisters DMA_CLLR_UB2 bit + * DMA_CLLR_UB2 bit is discarded for linear addressing channels. + * - UpdateRegisters DMA_CLLR_ULL bit + */ + pNode->LinkRegisters[reg_counter] = ((DMA_InitNodeStruct->UpdateRegisters & (DMA_CLLR_UT1 | DMA_CLLR_UT2 | \ + DMA_CLLR_UB1 | DMA_CLLR_USA | \ + DMA_CLLR_UDA | DMA_CLLR_ULL))); + + /* Update CLLR register fields for 2D addressing channels */ + if ((DMA_InitNodeStruct->NodeType == LL_DMA_HPDMA_2D_NODE) || \ + (DMA_InitNodeStruct->NodeType == LL_DMA_GPDMA_2D_NODE)) + { + pNode->LinkRegisters[reg_counter] |= (DMA_InitNodeStruct->UpdateRegisters & (DMA_CLLR_UT3 | DMA_CLLR_UB2)); + } + } + + return (uint32_t)SUCCESS; +} + +/** + * @brief Connect Linked list Nodes. + * @param pPrevLinkNode Pointer to previous linked list node to be connected to new Linked list node. + * @param PrevNodeCLLRIdx Offset of Previous Node CLLR register. + * This parameter can be a value of @ref DMA_LL_EC_CLLR_OFFSET. + * @param pNewLinkNode Pointer to new Linked list. + * @param NewNodeCLLRIdx Offset of New Node CLLR register. + * This parameter can be a value of @ref DMA_LL_EC_CLLR_OFFSET. + * @retval None + */ +void LL_DMA_ConnectLinkNode(LL_DMA_LinkNodeTypeDef *pPrevLinkNode, uint32_t PrevNodeCLLRIdx, + LL_DMA_LinkNodeTypeDef *pNewLinkNode, uint32_t NewNodeCLLRIdx) +{ + pPrevLinkNode->LinkRegisters[PrevNodeCLLRIdx] = (((uint32_t)pNewLinkNode & DMA_CLLR_LA) | \ + (pNewLinkNode->LinkRegisters[NewNodeCLLRIdx] & (DMA_CLLR_UT1 | \ + DMA_CLLR_UT2 | DMA_CLLR_UB1 | DMA_CLLR_USA | DMA_CLLR_UDA | \ + DMA_CLLR_UT3 | DMA_CLLR_UB2 | DMA_CLLR_ULL))); +} + +/** + * @brief Disconnect the next linked list node. + * @param pLinkNode Pointer to linked list node to be disconnected from the next one. + * @param LinkNodeCLLRIdx Offset of Link Node CLLR register. + * @retval None. + */ +void LL_DMA_DisconnectNextLinkNode(LL_DMA_LinkNodeTypeDef *pLinkNode, uint32_t LinkNodeCLLRIdx) +{ + pLinkNode->LinkRegisters[LinkNodeCLLRIdx] = 0; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* GPDMA1 || HPDMA1 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma2d.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma2d.c index b33606b3b..51f4fe032 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma2d.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_dma2d.c @@ -1,633 +1,633 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_dma2d.c - * @author MCD Application Team - * @brief DMA2D LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_dma2d.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (DMA2D) - -/** @addtogroup DMA2D_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup DMA2D_LL_Private_Constants DMA2D Private Constants - * @{ - */ -#define LL_DMA2D_COLOR 0xFFU /*!< Maximum output color setting */ -#define LL_DMA2D_NUMBEROFLINES DMA2D_NLR_NL /*!< Maximum number of lines */ -#define LL_DMA2D_NUMBEROFPIXELS (DMA2D_NLR_PL >> DMA2D_NLR_PL_Pos) /*!< Maximum number of pixels per lines */ -#define LL_DMA2D_OFFSET_MAX 0x3FFFU /*!< Maximum output line offset expressed in pixels */ -#define LL_DMA2D_CLUTSIZE_MAX 0xFFU /*!< Maximum CLUT size */ -/** - * @} - */ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup DMA2D_LL_Private_Macros - * @{ - */ -#define IS_LL_DMA2D_MODE(MODE) (((MODE) == LL_DMA2D_MODE_M2M) || \ - ((MODE) == LL_DMA2D_MODE_M2M_PFC) || \ - ((MODE) == LL_DMA2D_MODE_M2M_BLEND) || \ - ((MODE) == LL_DMA2D_MODE_M2M_BLEND_FIXED_COLOR_FG) || \ - ((MODE) == LL_DMA2D_MODE_M2M_BLEND_FIXED_COLOR_BG) || \ - ((MODE) == LL_DMA2D_MODE_R2M)) - -#define IS_LL_DMA2D_OCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB8888) || \ - ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB888) || \ - ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB565) || \ - ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB1555) || \ - ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB4444)) - -#define IS_LL_DMA2D_GREEN(GREEN) ((GREEN) <= LL_DMA2D_COLOR) -#define IS_LL_DMA2D_RED(RED) ((RED) <= LL_DMA2D_COLOR) -#define IS_LL_DMA2D_BLUE(BLUE) ((BLUE) <= LL_DMA2D_COLOR) -#define IS_LL_DMA2D_ALPHA(ALPHA) ((ALPHA) <= LL_DMA2D_COLOR) - -#define IS_LL_DMA2D_OFFSET_MODE(MODE) (((MODE) == LL_DMA2D_LINE_OFFSET_PIXELS) || \ - ((MODE) == LL_DMA2D_LINE_OFFSET_BYTES)) - -#define IS_LL_DMA2D_OFFSET(OFFSET) ((OFFSET) <= LL_DMA2D_OFFSET_MAX) - -#define IS_LL_DMA2D_LINE(LINES) ((LINES) <= LL_DMA2D_NUMBEROFLINES) -#define IS_LL_DMA2D_PIXEL(PIXELS) ((PIXELS) <= LL_DMA2D_NUMBEROFPIXELS) - -#define IS_LL_DMA2D_SWAP_MODE(MODE) (((MODE) == LL_DMA2D_SWAP_MODE_REGULAR) || \ - ((MODE) == LL_DMA2D_SWAP_MODE_TWO_BY_TWO)) - -#define IS_LL_DMA2D_ALPHAINV(ALPHA) (((ALPHA) == LL_DMA2D_ALPHA_REGULAR) || \ - ((ALPHA) == LL_DMA2D_ALPHA_INVERTED)) - -#define IS_LL_DMA2D_RBSWAP(RBSWAP) (((RBSWAP) == LL_DMA2D_RB_MODE_REGULAR) || \ - ((RBSWAP) == LL_DMA2D_RB_MODE_SWAP)) - -#define IS_LL_DMA2D_LCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB8888) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB888) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB565) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB1555) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB4444) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L8) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL44) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL88) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L4) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A8) || \ - ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A4)) - -#define IS_LL_DMA2D_CLUTCMODE(CLUTCMODE) (((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_ARGB8888) || \ - ((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_RGB888)) - -#define IS_LL_DMA2D_CLUTSIZE(SIZE) ((SIZE) <= LL_DMA2D_CLUTSIZE_MAX) - -#define IS_LL_DMA2D_ALPHAMODE(MODE) (((MODE) == LL_DMA2D_ALPHA_MODE_NO_MODIF) || \ - ((MODE) == LL_DMA2D_ALPHA_MODE_REPLACE) || \ - ((MODE) == LL_DMA2D_ALPHA_MODE_COMBINE)) - -#define IS_LL_DMA2D_CHROMA_SUB_SAMPLING(CSS) (((CSS) == LL_DMA2D_CSS_444) || \ - ((CSS) == LL_DMA2D_CSS_422) || \ - ((CSS) == LL_DMA2D_CSS_420)) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup DMA2D_LL_Exported_Functions - * @{ - */ - -/** @addtogroup DMA2D_LL_EF_Init_Functions Initialization and De-initialization Functions - * @{ - */ - -/** - * @brief De-initialize DMA2D registers (registers restored to their default values). - * @param DMA2Dx DMA2D Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: DMA2D registers are de-initialized - * - ERROR: DMA2D registers are not de-initialized - */ -ErrorStatus LL_DMA2D_DeInit(const DMA2D_TypeDef *DMA2Dx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - - if (DMA2Dx == DMA2D) - { - /* Force reset of DMA2D clock */ - LL_AHB5_GRP1_ForceReset(LL_AHB5_GRP1_PERIPH_DMA2D); - - /* Release reset of DMA2D clock */ - LL_AHB5_GRP1_ReleaseReset(LL_AHB5_GRP1_PERIPH_DMA2D); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Initialize DMA2D registers according to the specified parameters in DMA2D_InitStruct. - * @note DMA2D transfers must be disabled to set initialization bits in configuration registers, - * otherwise ERROR result is returned. - * @param DMA2Dx DMA2D Instance - * @param DMA2D_InitStruct pointer to a LL_DMA2D_InitTypeDef structure - * that contains the configuration information for the specified DMA2D peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: DMA2D registers are initialized according to DMA2D_InitStruct content - * - ERROR: Issue occurred during DMA2D registers initialization - */ -ErrorStatus LL_DMA2D_Init(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_InitTypeDef *DMA2D_InitStruct) -{ - ErrorStatus status = ERROR; - LL_DMA2D_ColorTypeDef dma2d_colorstruct; - uint32_t tmp; - uint32_t tmp1; - uint32_t tmp2; - uint32_t regMask; - uint32_t regValue; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - assert_param(IS_LL_DMA2D_MODE(DMA2D_InitStruct->Mode)); - assert_param(IS_LL_DMA2D_OCMODE(DMA2D_InitStruct->ColorMode)); - assert_param(IS_LL_DMA2D_LINE(DMA2D_InitStruct->NbrOfLines)); - assert_param(IS_LL_DMA2D_PIXEL(DMA2D_InitStruct->NbrOfPixelsPerLines)); - assert_param(IS_LL_DMA2D_GREEN(DMA2D_InitStruct->OutputGreen)); - assert_param(IS_LL_DMA2D_RED(DMA2D_InitStruct->OutputRed)); - assert_param(IS_LL_DMA2D_BLUE(DMA2D_InitStruct->OutputBlue)); - assert_param(IS_LL_DMA2D_ALPHA(DMA2D_InitStruct->OutputAlpha)); - assert_param(IS_LL_DMA2D_SWAP_MODE(DMA2D_InitStruct->OutputSwapMode)); - assert_param(IS_LL_DMA2D_OFFSET_MODE(DMA2D_InitStruct->LineOffsetMode)); - assert_param(IS_LL_DMA2D_OFFSET(DMA2D_InitStruct->LineOffset)); - assert_param(IS_LL_DMA2D_ALPHAINV(DMA2D_InitStruct->AlphaInversionMode)); - assert_param(IS_LL_DMA2D_RBSWAP(DMA2D_InitStruct->RBSwapMode)); - - /* DMA2D transfers must be disabled to configure bits in initialization registers */ - tmp = LL_DMA2D_IsTransferOngoing(DMA2Dx); - tmp1 = LL_DMA2D_FGND_IsEnabledCLUTLoad(DMA2Dx); - tmp2 = LL_DMA2D_BGND_IsEnabledCLUTLoad(DMA2Dx); - if ((tmp == 0U) && (tmp1 == 0U) && (tmp2 == 0U)) - { - /* DMA2D CR register configuration -------------------------------------------*/ - MODIFY_REG(DMA2Dx->CR, (DMA2D_CR_MODE | DMA2D_CR_LOM), \ - (DMA2D_InitStruct->Mode | DMA2D_InitStruct->LineOffsetMode)); - - /* DMA2D OPFCCR register configuration ---------------------------------------*/ - regMask = DMA2D_OPFCCR_CM; - regValue = DMA2D_InitStruct->ColorMode; - - regMask |= DMA2D_OPFCCR_SB; - regValue |= DMA2D_InitStruct->OutputSwapMode; - - regMask |= (DMA2D_OPFCCR_RBS | DMA2D_OPFCCR_AI); - regValue |= (DMA2D_InitStruct->AlphaInversionMode | DMA2D_InitStruct->RBSwapMode); - - - MODIFY_REG(DMA2Dx->OPFCCR, regMask, regValue); - - /* DMA2D OOR register configuration ------------------------------------------*/ - LL_DMA2D_SetLineOffset(DMA2Dx, DMA2D_InitStruct->LineOffset); - - /* DMA2D NLR register configuration ------------------------------------------*/ - LL_DMA2D_ConfigSize(DMA2Dx, DMA2D_InitStruct->NbrOfLines, DMA2D_InitStruct->NbrOfPixelsPerLines); - - /* DMA2D OMAR register configuration ------------------------------------------*/ - LL_DMA2D_SetOutputMemAddr(DMA2Dx, DMA2D_InitStruct->OutputMemoryAddress); - - /* DMA2D OCOLR register configuration ------------------------------------------*/ - dma2d_colorstruct.ColorMode = DMA2D_InitStruct->ColorMode; - dma2d_colorstruct.OutputBlue = DMA2D_InitStruct->OutputBlue; - dma2d_colorstruct.OutputGreen = DMA2D_InitStruct->OutputGreen; - dma2d_colorstruct.OutputRed = DMA2D_InitStruct->OutputRed; - dma2d_colorstruct.OutputAlpha = DMA2D_InitStruct->OutputAlpha; - LL_DMA2D_ConfigOutputColor(DMA2Dx, &dma2d_colorstruct); - - status = SUCCESS; - } - /* If DMA2D transfers are not disabled, return ERROR */ - - return (status); -} - -/** - * @brief Set each @ref LL_DMA2D_InitTypeDef field to default value. - * @param DMA2D_InitStruct pointer to a @ref LL_DMA2D_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_DMA2D_StructInit(LL_DMA2D_InitTypeDef *DMA2D_InitStruct) -{ - /* Set DMA2D_InitStruct fields to default values */ - DMA2D_InitStruct->Mode = LL_DMA2D_MODE_M2M; - DMA2D_InitStruct->ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB8888; - DMA2D_InitStruct->NbrOfLines = 0x0U; - DMA2D_InitStruct->NbrOfPixelsPerLines = 0x0U; - DMA2D_InitStruct->LineOffsetMode = LL_DMA2D_LINE_OFFSET_PIXELS; - DMA2D_InitStruct->LineOffset = 0x0U; - DMA2D_InitStruct->OutputBlue = 0x0U; - DMA2D_InitStruct->OutputGreen = 0x0U; - DMA2D_InitStruct->OutputRed = 0x0U; - DMA2D_InitStruct->OutputAlpha = 0x0U; - DMA2D_InitStruct->OutputMemoryAddress = 0x0U; - DMA2D_InitStruct->OutputSwapMode = LL_DMA2D_SWAP_MODE_REGULAR; - DMA2D_InitStruct->AlphaInversionMode = LL_DMA2D_ALPHA_REGULAR; - DMA2D_InitStruct->RBSwapMode = LL_DMA2D_RB_MODE_REGULAR; -} - -/** - * @brief Configure the foreground or background according to the specified parameters - * in the LL_DMA2D_LayerCfgTypeDef structure. - * @param DMA2Dx DMA2D Instance - * @param DMA2D_LayerCfg pointer to a LL_DMA2D_LayerCfgTypeDef structure that contains - * the configuration information for the specified layer. - * @param LayerIdx DMA2D Layer index. - * This parameter can be one of the following values: - * 0(background) / 1(foreground) - * @retval None - */ -void LL_DMA2D_ConfigLayer(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg, uint32_t LayerIdx) -{ - /* Check the parameters */ - assert_param(IS_LL_DMA2D_OFFSET(DMA2D_LayerCfg->LineOffset)); - assert_param(IS_LL_DMA2D_LCMODE(DMA2D_LayerCfg->ColorMode)); - assert_param(IS_LL_DMA2D_CLUTCMODE(DMA2D_LayerCfg->CLUTColorMode)); - assert_param(IS_LL_DMA2D_CLUTSIZE(DMA2D_LayerCfg->CLUTSize)); - assert_param(IS_LL_DMA2D_ALPHAMODE(DMA2D_LayerCfg->AlphaMode)); - assert_param(IS_LL_DMA2D_GREEN(DMA2D_LayerCfg->Green)); - assert_param(IS_LL_DMA2D_RED(DMA2D_LayerCfg->Red)); - assert_param(IS_LL_DMA2D_BLUE(DMA2D_LayerCfg->Blue)); - assert_param(IS_LL_DMA2D_ALPHA(DMA2D_LayerCfg->Alpha)); - assert_param(IS_LL_DMA2D_ALPHAINV(DMA2D_LayerCfg->AlphaInversionMode)); - assert_param(IS_LL_DMA2D_RBSWAP(DMA2D_LayerCfg->RBSwapMode)); - assert_param(IS_LL_DMA2D_CHROMA_SUB_SAMPLING(DMA2D_LayerCfg->ChromaSubSampling)); - - - if (LayerIdx == 0U) - { - /* Configure the background memory address */ - LL_DMA2D_BGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress); - - /* Configure the background line offset */ - LL_DMA2D_BGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset); - - /* Configure the background Alpha value, Alpha mode, RB swap, Alpha inversion - CLUT size, CLUT Color mode and Color mode */ - MODIFY_REG(DMA2Dx->BGPFCCR, \ - (DMA2D_BGPFCCR_ALPHA | DMA2D_BGPFCCR_RBS | DMA2D_BGPFCCR_AI | DMA2D_BGPFCCR_AM | \ - DMA2D_BGPFCCR_CS | DMA2D_BGPFCCR_CCM | DMA2D_BGPFCCR_CM), \ - ((DMA2D_LayerCfg->Alpha << DMA2D_BGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->RBSwapMode | \ - DMA2D_LayerCfg->AlphaInversionMode | DMA2D_LayerCfg->AlphaMode | \ - (DMA2D_LayerCfg->CLUTSize << DMA2D_BGPFCCR_CS_Pos) | DMA2D_LayerCfg->CLUTColorMode | \ - DMA2D_LayerCfg->ColorMode)); - - /* Configure the background color */ - LL_DMA2D_BGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue); - - /* Configure the background CLUT memory address */ - LL_DMA2D_BGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress); - } - else - { - /* Configure the foreground memory address */ - LL_DMA2D_FGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress); - - /* Configure the foreground line offset */ - LL_DMA2D_FGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset); - - /* Configure the foreground Alpha value, Alpha mode, RB swap, Alpha inversion - CLUT size, CLUT Color mode and Color mode */ - MODIFY_REG(DMA2Dx->FGPFCCR, \ - (DMA2D_FGPFCCR_ALPHA | DMA2D_FGPFCCR_RBS | DMA2D_FGPFCCR_AI | DMA2D_FGPFCCR_CSS | DMA2D_FGPFCCR_AM | \ - DMA2D_FGPFCCR_CS | DMA2D_FGPFCCR_CCM | DMA2D_FGPFCCR_CM), \ - ((DMA2D_LayerCfg->Alpha << DMA2D_FGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->RBSwapMode | \ - DMA2D_LayerCfg->AlphaInversionMode | DMA2D_LayerCfg->ChromaSubSampling | \ - DMA2D_LayerCfg->AlphaMode | (DMA2D_LayerCfg->CLUTSize << DMA2D_FGPFCCR_CS_Pos) | \ - DMA2D_LayerCfg->CLUTColorMode | DMA2D_LayerCfg->ColorMode)); - - /* Configure the foreground color */ - LL_DMA2D_FGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue); - - /* Configure the foreground CLUT memory address */ - LL_DMA2D_FGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress); - } -} - -/** - * @brief Set each @ref LL_DMA2D_LayerCfgTypeDef field to default value. - * @param DMA2D_LayerCfg pointer to a @ref LL_DMA2D_LayerCfgTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_DMA2D_LayerCfgStructInit(LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg) -{ - /* Set DMA2D_LayerCfg fields to default values */ - DMA2D_LayerCfg->MemoryAddress = 0x0U; - DMA2D_LayerCfg->ColorMode = LL_DMA2D_INPUT_MODE_ARGB8888; - DMA2D_LayerCfg->LineOffset = 0x0U; - DMA2D_LayerCfg->CLUTColorMode = LL_DMA2D_CLUT_COLOR_MODE_ARGB8888; - DMA2D_LayerCfg->CLUTSize = 0x0U; - DMA2D_LayerCfg->AlphaMode = LL_DMA2D_ALPHA_MODE_NO_MODIF; - DMA2D_LayerCfg->Alpha = 0x0U; - DMA2D_LayerCfg->Blue = 0x0U; - DMA2D_LayerCfg->Green = 0x0U; - DMA2D_LayerCfg->Red = 0x0U; - DMA2D_LayerCfg->CLUTMemoryAddress = 0x0U; - DMA2D_LayerCfg->AlphaInversionMode = LL_DMA2D_ALPHA_REGULAR; - DMA2D_LayerCfg->RBSwapMode = LL_DMA2D_RB_MODE_REGULAR; - DMA2D_LayerCfg->ChromaSubSampling = LL_DMA2D_CSS_444; -} - -/** - * @brief Initialize DMA2D output color register according to the specified parameters - * in DMA2D_ColorStruct. - * @param DMA2Dx DMA2D Instance - * @param DMA2D_ColorStruct pointer to a LL_DMA2D_ColorTypeDef structure that contains - * the color configuration information for the specified DMA2D peripheral. - * @retval None - */ -void LL_DMA2D_ConfigOutputColor(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_ColorTypeDef *DMA2D_ColorStruct) -{ - uint32_t outgreen; - uint32_t outred; - uint32_t outalpha; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - assert_param(IS_LL_DMA2D_OCMODE(DMA2D_ColorStruct->ColorMode)); - assert_param(IS_LL_DMA2D_GREEN(DMA2D_ColorStruct->OutputGreen)); - assert_param(IS_LL_DMA2D_RED(DMA2D_ColorStruct->OutputRed)); - assert_param(IS_LL_DMA2D_BLUE(DMA2D_ColorStruct->OutputBlue)); - assert_param(IS_LL_DMA2D_ALPHA(DMA2D_ColorStruct->OutputAlpha)); - - /* DMA2D OCOLR register configuration ------------------------------------------*/ - if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) - { - outgreen = DMA2D_ColorStruct->OutputGreen << 8U; - outred = DMA2D_ColorStruct->OutputRed << 16U; - outalpha = DMA2D_ColorStruct->OutputAlpha << 24U; - } - else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) - { - outgreen = DMA2D_ColorStruct->OutputGreen << 8U; - outred = DMA2D_ColorStruct->OutputRed << 16U; - outalpha = 0x00000000U; - } - else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) - { - outgreen = DMA2D_ColorStruct->OutputGreen << 5U; - outred = DMA2D_ColorStruct->OutputRed << 11U; - outalpha = 0x00000000U; - } - else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) - { - outgreen = DMA2D_ColorStruct->OutputGreen << 5U; - outred = DMA2D_ColorStruct->OutputRed << 10U; - outalpha = DMA2D_ColorStruct->OutputAlpha << 15U; - } - else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ - { - outgreen = DMA2D_ColorStruct->OutputGreen << 4U; - outred = DMA2D_ColorStruct->OutputRed << 8U; - outalpha = DMA2D_ColorStruct->OutputAlpha << 12U; - } - LL_DMA2D_SetOutputColor(DMA2Dx, (outgreen | outred | DMA2D_ColorStruct->OutputBlue | outalpha)); -} - -/** - * @brief Return DMA2D output Blue color. - * @param DMA2Dx DMA2D Instance. - * @param ColorMode This parameter can be one of the following values: - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 - * @retval Output Blue color value between Min_Data=0 and Max_Data=0xFF - */ -uint32_t LL_DMA2D_GetOutputBlueColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) -{ - uint32_t color; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); - - /* DMA2D OCOLR register reading ------------------------------------------*/ - if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU)); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU)); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU)); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU)); - } - else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFU)); - } - - return color; -} - -/** - * @brief Return DMA2D output Green color. - * @param DMA2Dx DMA2D Instance. - * @param ColorMode This parameter can be one of the following values: - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 - * @retval Output Green color value between Min_Data=0 and Max_Data=0xFF - */ -uint32_t LL_DMA2D_GetOutputGreenColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) -{ - uint32_t color; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); - - /* DMA2D OCOLR register reading ------------------------------------------*/ - if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7E0U) >> 5U); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x3E0U) >> 5U); - } - else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF0U) >> 4U); - } - - return color; -} - -/** - * @brief Return DMA2D output Red color. - * @param DMA2Dx DMA2D Instance. - * @param ColorMode This parameter can be one of the following values: - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 - * @retval Output Red color value between Min_Data=0 and Max_Data=0xFF - */ -uint32_t LL_DMA2D_GetOutputRedColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) -{ - uint32_t color; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); - - /* DMA2D OCOLR register reading ------------------------------------------*/ - if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF800U) >> 11U); - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7C00U) >> 10U); - } - else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF00U) >> 8U); - } - - return color; -} - -/** - * @brief Return DMA2D output Alpha color. - * @param DMA2Dx DMA2D Instance. - * @param ColorMode This parameter can be one of the following values: - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 - * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 - * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 - * @retval Output Alpha color value between Min_Data=0 and Max_Data=0xFF - */ -uint32_t LL_DMA2D_GetOutputAlphaColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) -{ - uint32_t color; - - /* Check the parameters */ - assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); - assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); - - /* DMA2D OCOLR register reading ------------------------------------------*/ - if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF000000U) >> 24U); - } - else if ((ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) || (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)) - { - color = 0x0U; - } - else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x8000U) >> 15U); - } - else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ - { - color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF000U) >> 12U); - } - - return color; -} - -/** - * @brief Configure DMA2D transfer size. - * @param DMA2Dx DMA2D Instance - * @param NbrOfLines Value between Min_Data=0 and Max_Data=0xFFFF - * @param NbrOfPixelsPerLines Value between Min_Data=0 and Max_Data=0x3FFF - * @retval None - */ -void LL_DMA2D_ConfigSize(DMA2D_TypeDef *DMA2Dx, uint32_t NbrOfLines, uint32_t NbrOfPixelsPerLines) -{ - MODIFY_REG(DMA2Dx->NLR, (DMA2D_NLR_PL | DMA2D_NLR_NL), \ - ((NbrOfPixelsPerLines << DMA2D_NLR_PL_Pos) | NbrOfLines)); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined (DMA2D) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_dma2d.c + * @author MCD Application Team + * @brief DMA2D LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_dma2d.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (DMA2D) + +/** @addtogroup DMA2D_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup DMA2D_LL_Private_Constants DMA2D Private Constants + * @{ + */ +#define LL_DMA2D_COLOR 0xFFU /*!< Maximum output color setting */ +#define LL_DMA2D_NUMBEROFLINES DMA2D_NLR_NL /*!< Maximum number of lines */ +#define LL_DMA2D_NUMBEROFPIXELS (DMA2D_NLR_PL >> DMA2D_NLR_PL_Pos) /*!< Maximum number of pixels per lines */ +#define LL_DMA2D_OFFSET_MAX 0x3FFFU /*!< Maximum output line offset expressed in pixels */ +#define LL_DMA2D_CLUTSIZE_MAX 0xFFU /*!< Maximum CLUT size */ +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup DMA2D_LL_Private_Macros + * @{ + */ +#define IS_LL_DMA2D_MODE(MODE) (((MODE) == LL_DMA2D_MODE_M2M) || \ + ((MODE) == LL_DMA2D_MODE_M2M_PFC) || \ + ((MODE) == LL_DMA2D_MODE_M2M_BLEND) || \ + ((MODE) == LL_DMA2D_MODE_M2M_BLEND_FIXED_COLOR_FG) || \ + ((MODE) == LL_DMA2D_MODE_M2M_BLEND_FIXED_COLOR_BG) || \ + ((MODE) == LL_DMA2D_MODE_R2M)) + +#define IS_LL_DMA2D_OCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB8888) || \ + ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB888) || \ + ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB565) || \ + ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB1555) || \ + ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB4444)) + +#define IS_LL_DMA2D_GREEN(GREEN) ((GREEN) <= LL_DMA2D_COLOR) +#define IS_LL_DMA2D_RED(RED) ((RED) <= LL_DMA2D_COLOR) +#define IS_LL_DMA2D_BLUE(BLUE) ((BLUE) <= LL_DMA2D_COLOR) +#define IS_LL_DMA2D_ALPHA(ALPHA) ((ALPHA) <= LL_DMA2D_COLOR) + +#define IS_LL_DMA2D_OFFSET_MODE(MODE) (((MODE) == LL_DMA2D_LINE_OFFSET_PIXELS) || \ + ((MODE) == LL_DMA2D_LINE_OFFSET_BYTES)) + +#define IS_LL_DMA2D_OFFSET(OFFSET) ((OFFSET) <= LL_DMA2D_OFFSET_MAX) + +#define IS_LL_DMA2D_LINE(LINES) ((LINES) <= LL_DMA2D_NUMBEROFLINES) +#define IS_LL_DMA2D_PIXEL(PIXELS) ((PIXELS) <= LL_DMA2D_NUMBEROFPIXELS) + +#define IS_LL_DMA2D_SWAP_MODE(MODE) (((MODE) == LL_DMA2D_SWAP_MODE_REGULAR) || \ + ((MODE) == LL_DMA2D_SWAP_MODE_TWO_BY_TWO)) + +#define IS_LL_DMA2D_ALPHAINV(ALPHA) (((ALPHA) == LL_DMA2D_ALPHA_REGULAR) || \ + ((ALPHA) == LL_DMA2D_ALPHA_INVERTED)) + +#define IS_LL_DMA2D_RBSWAP(RBSWAP) (((RBSWAP) == LL_DMA2D_RB_MODE_REGULAR) || \ + ((RBSWAP) == LL_DMA2D_RB_MODE_SWAP)) + +#define IS_LL_DMA2D_LCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB8888) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB888) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB565) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB1555) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB4444) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L8) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL44) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL88) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L4) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A8) || \ + ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A4)) + +#define IS_LL_DMA2D_CLUTCMODE(CLUTCMODE) (((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_ARGB8888) || \ + ((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_RGB888)) + +#define IS_LL_DMA2D_CLUTSIZE(SIZE) ((SIZE) <= LL_DMA2D_CLUTSIZE_MAX) + +#define IS_LL_DMA2D_ALPHAMODE(MODE) (((MODE) == LL_DMA2D_ALPHA_MODE_NO_MODIF) || \ + ((MODE) == LL_DMA2D_ALPHA_MODE_REPLACE) || \ + ((MODE) == LL_DMA2D_ALPHA_MODE_COMBINE)) + +#define IS_LL_DMA2D_CHROMA_SUB_SAMPLING(CSS) (((CSS) == LL_DMA2D_CSS_444) || \ + ((CSS) == LL_DMA2D_CSS_422) || \ + ((CSS) == LL_DMA2D_CSS_420)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup DMA2D_LL_Exported_Functions + * @{ + */ + +/** @addtogroup DMA2D_LL_EF_Init_Functions Initialization and De-initialization Functions + * @{ + */ + +/** + * @brief De-initialize DMA2D registers (registers restored to their default values). + * @param DMA2Dx DMA2D Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: DMA2D registers are de-initialized + * - ERROR: DMA2D registers are not de-initialized + */ +ErrorStatus LL_DMA2D_DeInit(const DMA2D_TypeDef *DMA2Dx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + + if (DMA2Dx == DMA2D) + { + /* Force reset of DMA2D clock */ + LL_AHB5_GRP1_ForceReset(LL_AHB5_GRP1_PERIPH_DMA2D); + + /* Release reset of DMA2D clock */ + LL_AHB5_GRP1_ReleaseReset(LL_AHB5_GRP1_PERIPH_DMA2D); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize DMA2D registers according to the specified parameters in DMA2D_InitStruct. + * @note DMA2D transfers must be disabled to set initialization bits in configuration registers, + * otherwise ERROR result is returned. + * @param DMA2Dx DMA2D Instance + * @param DMA2D_InitStruct pointer to a LL_DMA2D_InitTypeDef structure + * that contains the configuration information for the specified DMA2D peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: DMA2D registers are initialized according to DMA2D_InitStruct content + * - ERROR: Issue occurred during DMA2D registers initialization + */ +ErrorStatus LL_DMA2D_Init(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_InitTypeDef *DMA2D_InitStruct) +{ + ErrorStatus status = ERROR; + LL_DMA2D_ColorTypeDef dma2d_colorstruct; + uint32_t tmp; + uint32_t tmp1; + uint32_t tmp2; + uint32_t regMask; + uint32_t regValue; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + assert_param(IS_LL_DMA2D_MODE(DMA2D_InitStruct->Mode)); + assert_param(IS_LL_DMA2D_OCMODE(DMA2D_InitStruct->ColorMode)); + assert_param(IS_LL_DMA2D_LINE(DMA2D_InitStruct->NbrOfLines)); + assert_param(IS_LL_DMA2D_PIXEL(DMA2D_InitStruct->NbrOfPixelsPerLines)); + assert_param(IS_LL_DMA2D_GREEN(DMA2D_InitStruct->OutputGreen)); + assert_param(IS_LL_DMA2D_RED(DMA2D_InitStruct->OutputRed)); + assert_param(IS_LL_DMA2D_BLUE(DMA2D_InitStruct->OutputBlue)); + assert_param(IS_LL_DMA2D_ALPHA(DMA2D_InitStruct->OutputAlpha)); + assert_param(IS_LL_DMA2D_SWAP_MODE(DMA2D_InitStruct->OutputSwapMode)); + assert_param(IS_LL_DMA2D_OFFSET_MODE(DMA2D_InitStruct->LineOffsetMode)); + assert_param(IS_LL_DMA2D_OFFSET(DMA2D_InitStruct->LineOffset)); + assert_param(IS_LL_DMA2D_ALPHAINV(DMA2D_InitStruct->AlphaInversionMode)); + assert_param(IS_LL_DMA2D_RBSWAP(DMA2D_InitStruct->RBSwapMode)); + + /* DMA2D transfers must be disabled to configure bits in initialization registers */ + tmp = LL_DMA2D_IsTransferOngoing(DMA2Dx); + tmp1 = LL_DMA2D_FGND_IsEnabledCLUTLoad(DMA2Dx); + tmp2 = LL_DMA2D_BGND_IsEnabledCLUTLoad(DMA2Dx); + if ((tmp == 0U) && (tmp1 == 0U) && (tmp2 == 0U)) + { + /* DMA2D CR register configuration -------------------------------------------*/ + MODIFY_REG(DMA2Dx->CR, (DMA2D_CR_MODE | DMA2D_CR_LOM), \ + (DMA2D_InitStruct->Mode | DMA2D_InitStruct->LineOffsetMode)); + + /* DMA2D OPFCCR register configuration ---------------------------------------*/ + regMask = DMA2D_OPFCCR_CM; + regValue = DMA2D_InitStruct->ColorMode; + + regMask |= DMA2D_OPFCCR_SB; + regValue |= DMA2D_InitStruct->OutputSwapMode; + + regMask |= (DMA2D_OPFCCR_RBS | DMA2D_OPFCCR_AI); + regValue |= (DMA2D_InitStruct->AlphaInversionMode | DMA2D_InitStruct->RBSwapMode); + + + MODIFY_REG(DMA2Dx->OPFCCR, regMask, regValue); + + /* DMA2D OOR register configuration ------------------------------------------*/ + LL_DMA2D_SetLineOffset(DMA2Dx, DMA2D_InitStruct->LineOffset); + + /* DMA2D NLR register configuration ------------------------------------------*/ + LL_DMA2D_ConfigSize(DMA2Dx, DMA2D_InitStruct->NbrOfLines, DMA2D_InitStruct->NbrOfPixelsPerLines); + + /* DMA2D OMAR register configuration ------------------------------------------*/ + LL_DMA2D_SetOutputMemAddr(DMA2Dx, DMA2D_InitStruct->OutputMemoryAddress); + + /* DMA2D OCOLR register configuration ------------------------------------------*/ + dma2d_colorstruct.ColorMode = DMA2D_InitStruct->ColorMode; + dma2d_colorstruct.OutputBlue = DMA2D_InitStruct->OutputBlue; + dma2d_colorstruct.OutputGreen = DMA2D_InitStruct->OutputGreen; + dma2d_colorstruct.OutputRed = DMA2D_InitStruct->OutputRed; + dma2d_colorstruct.OutputAlpha = DMA2D_InitStruct->OutputAlpha; + LL_DMA2D_ConfigOutputColor(DMA2Dx, &dma2d_colorstruct); + + status = SUCCESS; + } + /* If DMA2D transfers are not disabled, return ERROR */ + + return (status); +} + +/** + * @brief Set each @ref LL_DMA2D_InitTypeDef field to default value. + * @param DMA2D_InitStruct pointer to a @ref LL_DMA2D_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_DMA2D_StructInit(LL_DMA2D_InitTypeDef *DMA2D_InitStruct) +{ + /* Set DMA2D_InitStruct fields to default values */ + DMA2D_InitStruct->Mode = LL_DMA2D_MODE_M2M; + DMA2D_InitStruct->ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB8888; + DMA2D_InitStruct->NbrOfLines = 0x0U; + DMA2D_InitStruct->NbrOfPixelsPerLines = 0x0U; + DMA2D_InitStruct->LineOffsetMode = LL_DMA2D_LINE_OFFSET_PIXELS; + DMA2D_InitStruct->LineOffset = 0x0U; + DMA2D_InitStruct->OutputBlue = 0x0U; + DMA2D_InitStruct->OutputGreen = 0x0U; + DMA2D_InitStruct->OutputRed = 0x0U; + DMA2D_InitStruct->OutputAlpha = 0x0U; + DMA2D_InitStruct->OutputMemoryAddress = 0x0U; + DMA2D_InitStruct->OutputSwapMode = LL_DMA2D_SWAP_MODE_REGULAR; + DMA2D_InitStruct->AlphaInversionMode = LL_DMA2D_ALPHA_REGULAR; + DMA2D_InitStruct->RBSwapMode = LL_DMA2D_RB_MODE_REGULAR; +} + +/** + * @brief Configure the foreground or background according to the specified parameters + * in the LL_DMA2D_LayerCfgTypeDef structure. + * @param DMA2Dx DMA2D Instance + * @param DMA2D_LayerCfg pointer to a LL_DMA2D_LayerCfgTypeDef structure that contains + * the configuration information for the specified layer. + * @param LayerIdx DMA2D Layer index. + * This parameter can be one of the following values: + * 0(background) / 1(foreground) + * @retval None + */ +void LL_DMA2D_ConfigLayer(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg, uint32_t LayerIdx) +{ + /* Check the parameters */ + assert_param(IS_LL_DMA2D_OFFSET(DMA2D_LayerCfg->LineOffset)); + assert_param(IS_LL_DMA2D_LCMODE(DMA2D_LayerCfg->ColorMode)); + assert_param(IS_LL_DMA2D_CLUTCMODE(DMA2D_LayerCfg->CLUTColorMode)); + assert_param(IS_LL_DMA2D_CLUTSIZE(DMA2D_LayerCfg->CLUTSize)); + assert_param(IS_LL_DMA2D_ALPHAMODE(DMA2D_LayerCfg->AlphaMode)); + assert_param(IS_LL_DMA2D_GREEN(DMA2D_LayerCfg->Green)); + assert_param(IS_LL_DMA2D_RED(DMA2D_LayerCfg->Red)); + assert_param(IS_LL_DMA2D_BLUE(DMA2D_LayerCfg->Blue)); + assert_param(IS_LL_DMA2D_ALPHA(DMA2D_LayerCfg->Alpha)); + assert_param(IS_LL_DMA2D_ALPHAINV(DMA2D_LayerCfg->AlphaInversionMode)); + assert_param(IS_LL_DMA2D_RBSWAP(DMA2D_LayerCfg->RBSwapMode)); + assert_param(IS_LL_DMA2D_CHROMA_SUB_SAMPLING(DMA2D_LayerCfg->ChromaSubSampling)); + + + if (LayerIdx == 0U) + { + /* Configure the background memory address */ + LL_DMA2D_BGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress); + + /* Configure the background line offset */ + LL_DMA2D_BGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset); + + /* Configure the background Alpha value, Alpha mode, RB swap, Alpha inversion + CLUT size, CLUT Color mode and Color mode */ + MODIFY_REG(DMA2Dx->BGPFCCR, \ + (DMA2D_BGPFCCR_ALPHA | DMA2D_BGPFCCR_RBS | DMA2D_BGPFCCR_AI | DMA2D_BGPFCCR_AM | \ + DMA2D_BGPFCCR_CS | DMA2D_BGPFCCR_CCM | DMA2D_BGPFCCR_CM), \ + ((DMA2D_LayerCfg->Alpha << DMA2D_BGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->RBSwapMode | \ + DMA2D_LayerCfg->AlphaInversionMode | DMA2D_LayerCfg->AlphaMode | \ + (DMA2D_LayerCfg->CLUTSize << DMA2D_BGPFCCR_CS_Pos) | DMA2D_LayerCfg->CLUTColorMode | \ + DMA2D_LayerCfg->ColorMode)); + + /* Configure the background color */ + LL_DMA2D_BGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue); + + /* Configure the background CLUT memory address */ + LL_DMA2D_BGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress); + } + else + { + /* Configure the foreground memory address */ + LL_DMA2D_FGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress); + + /* Configure the foreground line offset */ + LL_DMA2D_FGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset); + + /* Configure the foreground Alpha value, Alpha mode, RB swap, Alpha inversion + CLUT size, CLUT Color mode and Color mode */ + MODIFY_REG(DMA2Dx->FGPFCCR, \ + (DMA2D_FGPFCCR_ALPHA | DMA2D_FGPFCCR_RBS | DMA2D_FGPFCCR_AI | DMA2D_FGPFCCR_CSS | DMA2D_FGPFCCR_AM | \ + DMA2D_FGPFCCR_CS | DMA2D_FGPFCCR_CCM | DMA2D_FGPFCCR_CM), \ + ((DMA2D_LayerCfg->Alpha << DMA2D_FGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->RBSwapMode | \ + DMA2D_LayerCfg->AlphaInversionMode | DMA2D_LayerCfg->ChromaSubSampling | \ + DMA2D_LayerCfg->AlphaMode | (DMA2D_LayerCfg->CLUTSize << DMA2D_FGPFCCR_CS_Pos) | \ + DMA2D_LayerCfg->CLUTColorMode | DMA2D_LayerCfg->ColorMode)); + + /* Configure the foreground color */ + LL_DMA2D_FGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue); + + /* Configure the foreground CLUT memory address */ + LL_DMA2D_FGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress); + } +} + +/** + * @brief Set each @ref LL_DMA2D_LayerCfgTypeDef field to default value. + * @param DMA2D_LayerCfg pointer to a @ref LL_DMA2D_LayerCfgTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_DMA2D_LayerCfgStructInit(LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg) +{ + /* Set DMA2D_LayerCfg fields to default values */ + DMA2D_LayerCfg->MemoryAddress = 0x0U; + DMA2D_LayerCfg->ColorMode = LL_DMA2D_INPUT_MODE_ARGB8888; + DMA2D_LayerCfg->LineOffset = 0x0U; + DMA2D_LayerCfg->CLUTColorMode = LL_DMA2D_CLUT_COLOR_MODE_ARGB8888; + DMA2D_LayerCfg->CLUTSize = 0x0U; + DMA2D_LayerCfg->AlphaMode = LL_DMA2D_ALPHA_MODE_NO_MODIF; + DMA2D_LayerCfg->Alpha = 0x0U; + DMA2D_LayerCfg->Blue = 0x0U; + DMA2D_LayerCfg->Green = 0x0U; + DMA2D_LayerCfg->Red = 0x0U; + DMA2D_LayerCfg->CLUTMemoryAddress = 0x0U; + DMA2D_LayerCfg->AlphaInversionMode = LL_DMA2D_ALPHA_REGULAR; + DMA2D_LayerCfg->RBSwapMode = LL_DMA2D_RB_MODE_REGULAR; + DMA2D_LayerCfg->ChromaSubSampling = LL_DMA2D_CSS_444; +} + +/** + * @brief Initialize DMA2D output color register according to the specified parameters + * in DMA2D_ColorStruct. + * @param DMA2Dx DMA2D Instance + * @param DMA2D_ColorStruct pointer to a LL_DMA2D_ColorTypeDef structure that contains + * the color configuration information for the specified DMA2D peripheral. + * @retval None + */ +void LL_DMA2D_ConfigOutputColor(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_ColorTypeDef *DMA2D_ColorStruct) +{ + uint32_t outgreen; + uint32_t outred; + uint32_t outalpha; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + assert_param(IS_LL_DMA2D_OCMODE(DMA2D_ColorStruct->ColorMode)); + assert_param(IS_LL_DMA2D_GREEN(DMA2D_ColorStruct->OutputGreen)); + assert_param(IS_LL_DMA2D_RED(DMA2D_ColorStruct->OutputRed)); + assert_param(IS_LL_DMA2D_BLUE(DMA2D_ColorStruct->OutputBlue)); + assert_param(IS_LL_DMA2D_ALPHA(DMA2D_ColorStruct->OutputAlpha)); + + /* DMA2D OCOLR register configuration ------------------------------------------*/ + if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) + { + outgreen = DMA2D_ColorStruct->OutputGreen << 8U; + outred = DMA2D_ColorStruct->OutputRed << 16U; + outalpha = DMA2D_ColorStruct->OutputAlpha << 24U; + } + else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) + { + outgreen = DMA2D_ColorStruct->OutputGreen << 8U; + outred = DMA2D_ColorStruct->OutputRed << 16U; + outalpha = 0x00000000U; + } + else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) + { + outgreen = DMA2D_ColorStruct->OutputGreen << 5U; + outred = DMA2D_ColorStruct->OutputRed << 11U; + outalpha = 0x00000000U; + } + else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) + { + outgreen = DMA2D_ColorStruct->OutputGreen << 5U; + outred = DMA2D_ColorStruct->OutputRed << 10U; + outalpha = DMA2D_ColorStruct->OutputAlpha << 15U; + } + else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ + { + outgreen = DMA2D_ColorStruct->OutputGreen << 4U; + outred = DMA2D_ColorStruct->OutputRed << 8U; + outalpha = DMA2D_ColorStruct->OutputAlpha << 12U; + } + LL_DMA2D_SetOutputColor(DMA2Dx, (outgreen | outred | DMA2D_ColorStruct->OutputBlue | outalpha)); +} + +/** + * @brief Return DMA2D output Blue color. + * @param DMA2Dx DMA2D Instance. + * @param ColorMode This parameter can be one of the following values: + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 + * @retval Output Blue color value between Min_Data=0 and Max_Data=0xFF + */ +uint32_t LL_DMA2D_GetOutputBlueColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) +{ + uint32_t color; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); + + /* DMA2D OCOLR register reading ------------------------------------------*/ + if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU)); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU)); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU)); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU)); + } + else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFU)); + } + + return color; +} + +/** + * @brief Return DMA2D output Green color. + * @param DMA2Dx DMA2D Instance. + * @param ColorMode This parameter can be one of the following values: + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 + * @retval Output Green color value between Min_Data=0 and Max_Data=0xFF + */ +uint32_t LL_DMA2D_GetOutputGreenColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) +{ + uint32_t color; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); + + /* DMA2D OCOLR register reading ------------------------------------------*/ + if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7E0U) >> 5U); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x3E0U) >> 5U); + } + else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF0U) >> 4U); + } + + return color; +} + +/** + * @brief Return DMA2D output Red color. + * @param DMA2Dx DMA2D Instance. + * @param ColorMode This parameter can be one of the following values: + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 + * @retval Output Red color value between Min_Data=0 and Max_Data=0xFF + */ +uint32_t LL_DMA2D_GetOutputRedColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) +{ + uint32_t color; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); + + /* DMA2D OCOLR register reading ------------------------------------------*/ + if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF800U) >> 11U); + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7C00U) >> 10U); + } + else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF00U) >> 8U); + } + + return color; +} + +/** + * @brief Return DMA2D output Alpha color. + * @param DMA2Dx DMA2D Instance. + * @param ColorMode This parameter can be one of the following values: + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 + * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 + * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 + * @retval Output Alpha color value between Min_Data=0 and Max_Data=0xFF + */ +uint32_t LL_DMA2D_GetOutputAlphaColor(const DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) +{ + uint32_t color; + + /* Check the parameters */ + assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); + assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); + + /* DMA2D OCOLR register reading ------------------------------------------*/ + if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF000000U) >> 24U); + } + else if ((ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) || (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)) + { + color = 0x0U; + } + else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x8000U) >> 15U); + } + else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ + { + color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF000U) >> 12U); + } + + return color; +} + +/** + * @brief Configure DMA2D transfer size. + * @param DMA2Dx DMA2D Instance + * @param NbrOfLines Value between Min_Data=0 and Max_Data=0xFFFF + * @param NbrOfPixelsPerLines Value between Min_Data=0 and Max_Data=0x3FFF + * @retval None + */ +void LL_DMA2D_ConfigSize(DMA2D_TypeDef *DMA2Dx, uint32_t NbrOfLines, uint32_t NbrOfPixelsPerLines) +{ + MODIFY_REG(DMA2Dx->NLR, (DMA2D_NLR_PL | DMA2D_NLR_NL), \ + ((NbrOfPixelsPerLines << DMA2D_NLR_PL_Pos) | NbrOfLines)); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (DMA2D) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_exti.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_exti.c index 5f2856dfa..ab2b768bc 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_exti.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_exti.c @@ -1,321 +1,320 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_exti.c - * @author MCD Application Team - * @brief EXTI LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_exti.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (EXTI) - -/** @defgroup EXTI_LL EXTI - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup EXTI_LL_Private_Macros - * @{ - */ - -#define IS_LL_EXTI_LINE_0_31(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_0_31) == 0x00000000U) -#define IS_LL_EXTI_LINE_32_63(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_32_63) == 0x00000000U) -#define IS_LL_EXTI_LINE_64_95(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_64_95) == 0x00000000U) - -#define IS_LL_EXTI_MODE(__VALUE__) (((__VALUE__) == LL_EXTI_MODE_IT) \ - || ((__VALUE__) == LL_EXTI_MODE_EVENT) \ - || ((__VALUE__) == LL_EXTI_MODE_IT_EVENT)) - - -#define IS_LL_EXTI_TRIGGER(__VALUE__) (((__VALUE__) == LL_EXTI_TRIGGER_NONE) \ - || ((__VALUE__) == LL_EXTI_TRIGGER_RISING) \ - || ((__VALUE__) == LL_EXTI_TRIGGER_FALLING) \ - || ((__VALUE__) == LL_EXTI_TRIGGER_RISING_FALLING)) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup EXTI_LL_Exported_Functions - * @{ - */ - -/** @addtogroup EXTI_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the EXTI registers to their default reset values. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: EXTI registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_EXTI_DeInit(void) -{ - /* Interrupt mask register set to default reset values */ - LL_EXTI_WriteReg(IMR1, 0xFFC00000U); - /* Event mask register set to default reset values */ - LL_EXTI_WriteReg(EMR1, 0x00000000U); - /* Rising Trigger selection register set to default reset values */ - LL_EXTI_WriteReg(RTSR1, 0x00000000U); - /* Falling Trigger selection register set to default reset values */ - LL_EXTI_WriteReg(FTSR1, 0x00000000U); - /* Pending register clear */ - LL_EXTI_WriteReg(PR1, 0x003FFFFFU); - - /* Interrupt mask register 2 set to default reset values */ - LL_EXTI_WriteReg(IMR2, 0xFFB5BFFBU); - /* Event mask register 2 set to default reset values */ - LL_EXTI_WriteReg(EMR2, 0x00000000U); - /* Rising Trigger selection register 2 set to default reset values */ - LL_EXTI_WriteReg(RTSR2, 0x00000000U); - /* Falling Trigger selection register 2 set to default reset values */ - LL_EXTI_WriteReg(FTSR2, 0x00000000U); - /* Pending register 2 clear */ - LL_EXTI_WriteReg(PR2, 0x004A4004U); - - /* Interrupt mask register 3 set to default reset values */ - LL_EXTI_WriteReg(IMR3, 0x00003FFFU); - /* Event mask register 3 set to default reset values */ - LL_EXTI_WriteReg(EMR3, 0x00000000U); - - return SUCCESS; -} - -/** - * @brief Initialize the EXTI registers according to the specified parameters in EXTI_InitStruct. - * @param EXTI_InitStruct pointer to a @ref LL_EXTI_InitTypeDef structure. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: EXTI registers are initialized - * - ERROR: not applicable - */ -ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) -{ - ErrorStatus status = SUCCESS; - /* Check the parameters */ - assert_param(IS_LL_EXTI_LINE_0_31(EXTI_InitStruct->Line_0_31)); - assert_param(IS_LL_EXTI_LINE_32_63(EXTI_InitStruct->Line_32_63)); - assert_param(IS_LL_EXTI_LINE_64_95(EXTI_InitStruct->Line_64_95)); - assert_param(IS_FUNCTIONAL_STATE(EXTI_InitStruct->LineCommand)); - assert_param(IS_LL_EXTI_MODE(EXTI_InitStruct->Mode)); - - /* ENABLE LineCommand */ - if (EXTI_InitStruct->LineCommand != DISABLE) - { - assert_param(IS_LL_EXTI_TRIGGER(EXTI_InitStruct->Trigger)); - - /* Configure EXTI Lines in range from 0 to 31 */ - if (EXTI_InitStruct->Line_0_31 != LL_EXTI_LINE_NONE) - { - switch (EXTI_InitStruct->Mode) - { - case LL_EXTI_MODE_IT: - /* First Disable Event on provided Lines */ - LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31); - /* Then Enable IT on provided Lines */ - LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31); - break; - case LL_EXTI_MODE_EVENT: - /* First Disable IT on provided Lines */ - LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31); - /* Then Enable Event on provided Lines */ - LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31); - break; - case LL_EXTI_MODE_IT_EVENT: - /* Directly Enable IT & Event on provided Lines */ - LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31); - LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31); - break; - default: - status = ERROR; - break; - } - if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) - { - switch (EXTI_InitStruct->Trigger) - { - case LL_EXTI_TRIGGER_RISING: - /* First Disable Falling Trigger on provided Lines */ - LL_EXTI_DisableFallingTrig_0_31(EXTI_InitStruct->Line_0_31); - /* Then Enable Rising Trigger on provided Lines */ - LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31); - break; - case LL_EXTI_TRIGGER_FALLING: - /* First Disable Rising Trigger on provided Lines */ - LL_EXTI_DisableRisingTrig_0_31(EXTI_InitStruct->Line_0_31); - /* Then Enable Falling Trigger on provided Lines */ - LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31); - break; - case LL_EXTI_TRIGGER_RISING_FALLING: - LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31); - LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31); - break; - default: - status = ERROR; - break; - } - } - } - /* Configure EXTI Lines in range from 32 to 63 */ - if (EXTI_InitStruct->Line_32_63 != LL_EXTI_LINE_NONE) - { - switch (EXTI_InitStruct->Mode) - { - case LL_EXTI_MODE_IT: - /* First Disable Event on provided Lines */ - LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63); - /* Then Enable IT on provided Lines */ - LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63); - break; - case LL_EXTI_MODE_EVENT: - /* First Disable IT on provided Lines */ - LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63); - /* Then Enable Event on provided Lines */ - LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63); - break; - case LL_EXTI_MODE_IT_EVENT: - /* Directly Enable IT & Event on provided Lines */ - LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63); - LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63); - break; - default: - status = ERROR; - break; - } - if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) - { - switch (EXTI_InitStruct->Trigger) - { - case LL_EXTI_TRIGGER_RISING: - /* First Disable Falling Trigger on provided Lines */ - LL_EXTI_DisableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); - /* Then Enable IT on provided Lines */ - LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); - break; - case LL_EXTI_TRIGGER_FALLING: - /* First Disable Rising Trigger on provided Lines */ - LL_EXTI_DisableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); - /* Then Enable Falling Trigger on provided Lines */ - LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); - break; - case LL_EXTI_TRIGGER_RISING_FALLING: - LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); - LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); - break; - default: - status = ERROR; - break; - } - } - } - /* Configure EXTI Lines in range from 64 to 95 */ - if (EXTI_InitStruct->Line_64_95 != LL_EXTI_LINE_NONE) - { - switch (EXTI_InitStruct->Mode) - { - case LL_EXTI_MODE_IT: - /* First Disable Event on provided Lines */ - LL_EXTI_DisableEvent_64_95(EXTI_InitStruct->Line_64_95); - /* Then Enable IT on provided Lines */ - LL_EXTI_EnableIT_64_95(EXTI_InitStruct->Line_64_95); - break; - case LL_EXTI_MODE_EVENT: - /* First Disable IT on provided Lines */ - LL_EXTI_DisableIT_64_95(EXTI_InitStruct->Line_64_95); - /* Then Enable Event on provided Lines */ - LL_EXTI_EnableEvent_64_95(EXTI_InitStruct->Line_64_95); - break; - case LL_EXTI_MODE_IT_EVENT: - /* Directly Enable IT & Event on provided Lines */ - LL_EXTI_EnableIT_64_95(EXTI_InitStruct->Line_64_95); - LL_EXTI_EnableEvent_64_95(EXTI_InitStruct->Line_64_95); - break; - default: - status = ERROR; - break; - } - if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) - { - status = ERROR; - } - } - } - /* DISABLE LineCommand */ - else - { - /* De-configure EXTI Lines in range from 0 to 31 */ - LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31); - LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31); - /* De-configure EXTI Lines in range from 32 to 63 */ - LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63); - LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63); - /* De-configure EXTI Lines in range from 64 to 95 */ - LL_EXTI_DisableIT_64_95(EXTI_InitStruct->Line_64_95); - LL_EXTI_DisableEvent_64_95(EXTI_InitStruct->Line_64_95); - } - return status; -} - -/** - * @brief Set each @ref LL_EXTI_InitTypeDef field to default value. - * @param EXTI_InitStruct Pointer to a @ref LL_EXTI_InitTypeDef structure. - * @retval None - */ -void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct) -{ - EXTI_InitStruct->Line_0_31 = LL_EXTI_LINE_NONE; - EXTI_InitStruct->Line_32_63 = LL_EXTI_LINE_NONE; - EXTI_InitStruct->Line_64_95 = LL_EXTI_LINE_NONE; - EXTI_InitStruct->LineCommand = DISABLE; - EXTI_InitStruct->Mode = LL_EXTI_MODE_IT; - EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined (EXTI) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_exti.c + * @author MCD Application Team + * @brief EXTI LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_exti.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (EXTI) + +/** @defgroup EXTI_LL EXTI + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup EXTI_LL_Private_Macros + * @{ + */ + +#define IS_LL_EXTI_LINE_0_31(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_0_31) == 0x00000000U) +#define IS_LL_EXTI_LINE_32_63(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_32_63) == 0x00000000U) +#define IS_LL_EXTI_LINE_64_95(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_64_95) == 0x00000000U) + +#define IS_LL_EXTI_MODE(__VALUE__) (((__VALUE__) == LL_EXTI_MODE_IT) \ + || ((__VALUE__) == LL_EXTI_MODE_EVENT) \ + || ((__VALUE__) == LL_EXTI_MODE_IT_EVENT)) + + +#define IS_LL_EXTI_TRIGGER(__VALUE__) (((__VALUE__) == LL_EXTI_TRIGGER_NONE) \ + || ((__VALUE__) == LL_EXTI_TRIGGER_RISING) \ + || ((__VALUE__) == LL_EXTI_TRIGGER_FALLING) \ + || ((__VALUE__) == LL_EXTI_TRIGGER_RISING_FALLING)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup EXTI_LL_Exported_Functions + * @{ + */ + +/** @addtogroup EXTI_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the EXTI registers to their default reset values. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: EXTI registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_EXTI_DeInit(void) +{ + /* Interrupt mask register set to default reset values */ + LL_EXTI_WriteReg(IMR1, 0xFFC00000U); + /* Event mask register set to default reset values */ + LL_EXTI_WriteReg(EMR1, 0x00000000U); + /* Rising Trigger selection register set to default reset values */ + LL_EXTI_WriteReg(RTSR1, 0x00000000U); + /* Falling Trigger selection register set to default reset values */ + LL_EXTI_WriteReg(FTSR1, 0x00000000U); + /* Pending register clear */ + LL_EXTI_WriteReg(PR1, 0x003FFFFFU); + + /* Interrupt mask register 2 set to default reset values */ + LL_EXTI_WriteReg(IMR2, 0xFFB5BFFBU); + /* Event mask register 2 set to default reset values */ + LL_EXTI_WriteReg(EMR2, 0x00000000U); + /* Rising Trigger selection register 2 set to default reset values */ + LL_EXTI_WriteReg(RTSR2, 0x00000000U); + /* Falling Trigger selection register 2 set to default reset values */ + LL_EXTI_WriteReg(FTSR2, 0x00000000U); + /* Pending register 2 clear */ + LL_EXTI_WriteReg(PR2, 0x004A4004U); + + /* Interrupt mask register 3 set to default reset values */ + LL_EXTI_WriteReg(IMR3, 0x00003FFFU); + /* Event mask register 3 set to default reset values */ + LL_EXTI_WriteReg(EMR3, 0x00000000U); + + return SUCCESS; +} + +/** + * @brief Initialize the EXTI registers according to the specified parameters in EXTI_InitStruct. + * @param EXTI_InitStruct pointer to a @ref LL_EXTI_InitTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: EXTI registers are initialized + * - ERROR: not applicable + */ +ErrorStatus LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct) +{ + ErrorStatus status = SUCCESS; + /* Check the parameters */ + assert_param(IS_LL_EXTI_LINE_0_31(EXTI_InitStruct->Line_0_31)); + assert_param(IS_LL_EXTI_LINE_32_63(EXTI_InitStruct->Line_32_63)); + assert_param(IS_LL_EXTI_LINE_64_95(EXTI_InitStruct->Line_64_95)); + assert_param(IS_FUNCTIONAL_STATE(EXTI_InitStruct->LineCommand)); + assert_param(IS_LL_EXTI_MODE(EXTI_InitStruct->Mode)); + + /* ENABLE LineCommand */ + if (EXTI_InitStruct->LineCommand != DISABLE) + { + assert_param(IS_LL_EXTI_TRIGGER(EXTI_InitStruct->Trigger)); + + /* Configure EXTI Lines in range from 0 to 31 */ + if (EXTI_InitStruct->Line_0_31 != LL_EXTI_LINE_NONE) + { + switch (EXTI_InitStruct->Mode) + { + case LL_EXTI_MODE_IT: + /* First Disable Event on provided Lines */ + LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31); + /* Then Enable IT on provided Lines */ + LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31); + break; + case LL_EXTI_MODE_EVENT: + /* First Disable IT on provided Lines */ + LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31); + /* Then Enable Event on provided Lines */ + LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31); + break; + case LL_EXTI_MODE_IT_EVENT: + /* Directly Enable IT & Event on provided Lines */ + LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31); + LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31); + break; + default: + status = ERROR; + break; + } + if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) + { + switch (EXTI_InitStruct->Trigger) + { + case LL_EXTI_TRIGGER_RISING: + /* First Disable Falling Trigger on provided Lines */ + LL_EXTI_DisableFallingTrig_0_31(EXTI_InitStruct->Line_0_31); + /* Then Enable Rising Trigger on provided Lines */ + LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31); + break; + case LL_EXTI_TRIGGER_FALLING: + /* First Disable Rising Trigger on provided Lines */ + LL_EXTI_DisableRisingTrig_0_31(EXTI_InitStruct->Line_0_31); + /* Then Enable Falling Trigger on provided Lines */ + LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31); + break; + case LL_EXTI_TRIGGER_RISING_FALLING: + LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31); + LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31); + break; + default: + status = ERROR; + break; + } + } + } + /* Configure EXTI Lines in range from 32 to 63 */ + if (EXTI_InitStruct->Line_32_63 != LL_EXTI_LINE_NONE) + { + switch (EXTI_InitStruct->Mode) + { + case LL_EXTI_MODE_IT: + /* First Disable Event on provided Lines */ + LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable IT on provided Lines */ + LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_MODE_EVENT: + /* First Disable IT on provided Lines */ + LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable Event on provided Lines */ + LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_MODE_IT_EVENT: + /* Directly Enable IT & Event on provided Lines */ + LL_EXTI_EnableIT_32_63(EXTI_InitStruct->Line_32_63); + LL_EXTI_EnableEvent_32_63(EXTI_InitStruct->Line_32_63); + break; + default: + status = ERROR; + break; + } + if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) + { + switch (EXTI_InitStruct->Trigger) + { + case LL_EXTI_TRIGGER_RISING: + /* First Disable Falling Trigger on provided Lines */ + LL_EXTI_DisableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable IT on provided Lines */ + LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_TRIGGER_FALLING: + /* First Disable Rising Trigger on provided Lines */ + LL_EXTI_DisableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); + /* Then Enable Falling Trigger on provided Lines */ + LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); + break; + case LL_EXTI_TRIGGER_RISING_FALLING: + LL_EXTI_EnableRisingTrig_32_63(EXTI_InitStruct->Line_32_63); + LL_EXTI_EnableFallingTrig_32_63(EXTI_InitStruct->Line_32_63); + break; + default: + status = ERROR; + break; + } + } + } + /* Configure EXTI Lines in range from 64 to 95 */ + if (EXTI_InitStruct->Line_64_95 != LL_EXTI_LINE_NONE) + { + switch (EXTI_InitStruct->Mode) + { + case LL_EXTI_MODE_IT: + /* First Disable Event on provided Lines */ + LL_EXTI_DisableEvent_64_95(EXTI_InitStruct->Line_64_95); + /* Then Enable IT on provided Lines */ + LL_EXTI_EnableIT_64_95(EXTI_InitStruct->Line_64_95); + break; + case LL_EXTI_MODE_EVENT: + /* First Disable IT on provided Lines */ + LL_EXTI_DisableIT_64_95(EXTI_InitStruct->Line_64_95); + /* Then Enable Event on provided Lines */ + LL_EXTI_EnableEvent_64_95(EXTI_InitStruct->Line_64_95); + break; + case LL_EXTI_MODE_IT_EVENT: + /* Directly Enable IT & Event on provided Lines */ + LL_EXTI_EnableIT_64_95(EXTI_InitStruct->Line_64_95); + LL_EXTI_EnableEvent_64_95(EXTI_InitStruct->Line_64_95); + break; + default: + status = ERROR; + break; + } + if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE) + { + status = ERROR; + } + } + } + /* DISABLE LineCommand */ + else + { + /* De-configure EXTI Lines in range from 0 to 31 */ + LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31); + LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31); + /* De-configure EXTI Lines in range from 32 to 63 */ + LL_EXTI_DisableIT_32_63(EXTI_InitStruct->Line_32_63); + LL_EXTI_DisableEvent_32_63(EXTI_InitStruct->Line_32_63); + /* De-configure EXTI Lines in range from 64 to 95 */ + LL_EXTI_DisableIT_64_95(EXTI_InitStruct->Line_64_95); + LL_EXTI_DisableEvent_64_95(EXTI_InitStruct->Line_64_95); + } + return status; +} + +/** + * @brief Set each @ref LL_EXTI_InitTypeDef field to default value. + * @param EXTI_InitStruct Pointer to a @ref LL_EXTI_InitTypeDef structure. + * @retval None + */ +void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct) +{ + EXTI_InitStruct->Line_0_31 = LL_EXTI_LINE_NONE; + EXTI_InitStruct->Line_32_63 = LL_EXTI_LINE_NONE; + EXTI_InitStruct->Line_64_95 = LL_EXTI_LINE_NONE; + EXTI_InitStruct->LineCommand = DISABLE; + EXTI_InitStruct->Mode = LL_EXTI_MODE_IT; + EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (EXTI) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_fmc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_fmc.c index 384fcb380..3c4534169 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_fmc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_fmc.c @@ -1,1107 +1,1106 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_fmc.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### FMC peripheral features ##### - ============================================================================== - [..] The Flexible memory controller (FMC) includes following memory controllers: - (+) The NOR/PSRAM memory controller - (+) The NAND memory controller - (+) The Synchronous DRAM (SDRAM) controller - - [..] The FMC functional block makes the interface with synchronous and asynchronous static - memories and SDRAM memories. 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) - (++) 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 - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ -#if defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) || defined(HAL_SDRAM_MODULE_ENABLED)\ - || defined(HAL_SRAM_MODULE_ENABLED) - -/** @defgroup FMC_LL FMC Low Layer - * @brief FMC driver modules - * @{ - */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ - -/** @defgroup FMC_LL_Private_Constants FMC Low Layer Private Constants - * @{ - */ - -/* ----------------------- FMC registers bit mask --------------------------- */ - -/* --- BCR Register ---*/ -/* BCR register clear mask */ - -/* --- BTR Register ---*/ -/* BTR register clear mask */ -#define BTR_CLEAR_MASK ((uint32_t)(FMC_BTRx_ADDSET | FMC_BTRx_ADDHLD |\ - FMC_BTRx_DATAST | FMC_BTRx_BUSTURN |\ - FMC_BTRx_CLKDIV | FMC_BTRx_DATLAT |\ - FMC_BTRx_ACCMOD)) - -/* --- BWTR Register ---*/ -/* BWTR register clear mask */ -#if defined(FMC_BWTRx_BUSTURN) -#define BWTR_CLEAR_MASK ((uint32_t)(FMC_BWTRx_ADDSET | FMC_BWTRx_ADDHLD |\ - FMC_BWTRx_DATAST | FMC_BWTRx_BUSTURN |\ - FMC_BWTRx_ACCMOD)) -#else -#define BWTR_CLEAR_MASK ((uint32_t)(FMC_BWTRx_ADDSET | FMC_BWTRx_ADDHLD |\ - FMC_BWTRx_DATAST | FMC_BWTRx_ACCMOD)) -#endif /* FMC_BWTRx_BUSTURN */ - -/* --- PCR Register ---*/ -/* PCR register clear mask */ -#define PCR_CLEAR_MASK ((uint32_t)(FMC_PCR_PWAITEN | FMC_PCR_PBKEN | \ - FMC_PCR_PWID | FMC_PCR_ECCEN | \ - FMC_PCR_TCLR | FMC_PCR_TAR | \ - FMC_PCR_ECCPS)) -/* --- PMEM Register ---*/ -/* PMEM register clear mask */ -#define PMEM_CLEAR_MASK ((uint32_t)(FMC_PMEM_MEMSET | FMC_PMEM_MEMWAIT |\ - FMC_PMEM_MEMHOLD | FMC_PMEM_MEMHIZ)) - -/* --- PATT Register ---*/ -/* PATT register clear mask */ -#define PATT_CLEAR_MASK ((uint32_t)(FMC_PATT_ATTSET | FMC_PATT_ATTWAIT |\ - FMC_PATT_ATTHOLD | FMC_PATT_ATTHIZ)) - - -/* --- SDCR Register ---*/ -/* SDCR register clear mask */ -#define SDCR_CLEAR_MASK ((uint32_t)(FMC_SDCRx_NC | FMC_SDCRx_NR | \ - FMC_SDCRx_MWID | FMC_SDCRx_NB | \ - FMC_SDCRx_CAS | FMC_SDCRx_WP | \ - FMC_SDCRx_SDCLK | FMC_SDCRx_RBURST | \ - FMC_SDCRx_RPIPE)) - -/* --- SDTR Register ---*/ -/* SDTR register clear mask */ -#define SDTR_CLEAR_MASK ((uint32_t)(FMC_SDTRx_TMRD | FMC_SDTRx_TXSR | \ - FMC_SDTRx_TRAS | FMC_SDTRx_TRC | \ - FMC_SDTRx_TWR | FMC_SDTRx_TRP | \ - FMC_SDTRx_TRCD)) - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup FMC_LL_Exported_Functions FMC Low Layer Exported Functions - * @{ - */ - - -/** @defgroup FMC_LL_Exported_Functions_NORSRAM FMC Low Layer NOR SRAM Exported 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 FMC_LL_NORSRAM_Exported_Functions_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 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 flashaccess; - uint32_t btcr_reg; - uint32_t mask; - - /* 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_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)); - assert_param(IS_FMC_WRITE_FIFO(Init->WriteFifo)); - assert_param(IS_FMC_PAGESIZE(Init->PageSize)); - - /* Disable NORSRAM Device */ - __FMC_NORSRAM_DISABLE(Device, Init->NSBank); - - /* Set NORSRAM device control parameters */ - if (Init->MemoryType == FMC_MEMORY_TYPE_NOR) - { - flashaccess = FMC_NORSRAM_FLASH_ACCESS_ENABLE; - } - else - { - flashaccess = FMC_NORSRAM_FLASH_ACCESS_DISABLE; - } - - btcr_reg = (flashaccess | \ - Init->DataAddressMux | \ - Init->MemoryType | \ - Init->MemoryDataWidth | \ - Init->BurstAccessMode | \ - Init->WaitSignalPolarity | \ - Init->WaitSignalActive | \ - Init->WriteOperation | \ - Init->WaitSignal | \ - Init->ExtendedMode | \ - Init->AsynchronousWait | \ - Init->WriteBurst); - - btcr_reg |= Init->ContinuousClock; - btcr_reg |= Init->WriteFifo; - btcr_reg |= Init->PageSize; - - mask = (FMC_BCRx_MBKEN | - FMC_BCRx_MUXEN | - FMC_BCRx_MTYP | - FMC_BCRx_MWID | - FMC_BCRx_FACCEN | - FMC_BCRx_BURSTEN | - FMC_BCRx_WAITPOL | - FMC_BCRx_WAITCFG | - FMC_BCRx_WREN | - FMC_BCRx_WAITEN | - FMC_BCRx_EXTMOD | - FMC_BCRx_ASYNCWAIT | - FMC_BCRx_CBURSTRW); - - mask |= FMC_BCR1_CCLKEN; - mask |= FMC_BCR1_WFDIS; - mask |= FMC_BCRx_CPSIZE; - - MODIFY_REG(Device->BTCR[Init->NSBank], mask, btcr_reg); - - /* Configure synchronous mode when Continuous clock is enabled for bank2..4 */ - if ((Init->ContinuousClock == FMC_CONTINUOUS_CLOCK_SYNC_ASYNC) && (Init->NSBank != FMC_NORSRAM_BANK1)) - { - MODIFY_REG(Device->BTCR[FMC_NORSRAM_BANK1], FMC_BCR1_CCLKEN, Init->ContinuousClock); - } - - if (Init->NSBank != FMC_NORSRAM_BANK1) - { - /* Configure Write FIFO mode when Write Fifo is enabled for bank2..4 */ - SET_BIT(Device->BTCR[FMC_NORSRAM_BANK1], (uint32_t)(Init->WriteFifo)); - } - - 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] = 0x000030DBU; - } - /* FMC_NORSRAM_BANK2, FMC_NORSRAM_BANK3 or FMC_NORSRAM_BANK4 */ - else - { - Device->BTCR[Bank] = 0x000030D2U; - } - - Device->BTCR[Bank + 1U] = 0x0FFFFFFFU; - ExDevice->BWTR[Bank] = 0x0FFFFFFFU; - - 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; - - /* 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 */ - Device->BTCR[Bank + 1U] = - (Timing->AddressSetupTime << FMC_BTRx_ADDSET_Pos) | - (Timing->AddressHoldTime << FMC_BTRx_ADDHLD_Pos) | - (Timing->DataSetupTime << FMC_BTRx_DATAST_Pos) | - (Timing->BusTurnAroundDuration << FMC_BTRx_BUSTURN_Pos) | - ((Timing->CLKDivision - 1U) << FMC_BTRx_CLKDIV_Pos) | - ((Timing->DataLatency - 2U) << FMC_BTRx_DATLAT_Pos) | - Timing->AccessMode; - - /* 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 + 1U] & ~((0x0FU) << FMC_BTRx_CLKDIV_Pos)); - tmpr |= (uint32_t)(((Timing->CLKDivision) - 1U) << FMC_BTRx_CLKDIV_Pos); - MODIFY_REG(Device->BTCR[FMC_NORSRAM_BANK1 + 1U], FMC_BTRx_CLKDIV, 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 - * @param ExtendedMode FMC Extended Mode - * This parameter can be one of the following values: - * @arg FMC_EXTENDED_MODE_DISABLE - * @arg FMC_EXTENDED_MODE_ENABLE - * @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)); -#if defined(FMC_BWTRx_BUSTURN) - assert_param(IS_FMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration)); -#endif /* FMC_BWTRx_BUSTURN */ - assert_param(IS_FMC_ACCESS_MODE(Timing->AccessMode)); - assert_param(IS_FMC_NORSRAM_BANK(Bank)); - - /* Set NORSRAM device timing register for write configuration, if extended mode is used */ -#if defined(FMC_BWTRx_BUSTURN) - MODIFY_REG(Device->BWTR[Bank], BWTR_CLEAR_MASK, (Timing->AddressSetupTime | - ((Timing->AddressHoldTime) << FMC_BWTRx_ADDHLD_Pos) | - ((Timing->DataSetupTime) << FMC_BWTRx_DATAST_Pos) | - Timing->AccessMode | - ((Timing->BusTurnAroundDuration) << FMC_BWTRx_BUSTURN_Pos))); -#else /* FMC_BWTRx_BUSTURN */ - MODIFY_REG(Device->BWTR[Bank], BWTR_CLEAR_MASK, (Timing->AddressSetupTime | - ((Timing->AddressHoldTime) << FMC_BWTRx_ADDHLD_Pos) | - ((Timing->DataSetupTime) << FMC_BWTRx_DATAST_Pos) | - Timing->AccessMode)); -#endif /* FMC_BWTRx_BUSTURN */ - } - else - { - Device->BWTR[Bank] = 0x0FFFFFFFU; - } - - return HAL_OK; -} -/** - * @} - */ - -/** @addtogroup FMC_LL_NORSRAM_Private_Functions_Group2 - * @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 */ - SET_BIT(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 */ - CLEAR_BIT(Device->BTCR[Bank], FMC_WRITE_OPERATION_ENABLE); - - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - - -/** @defgroup FMC_LL_Exported_Functions_NAND FMC Low Layer NAND Exported Functions - * @brief NAND 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 FMC_LL_NAND_Exported_Functions_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 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) -{ - /* 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)); - - /* NAND bank 3 registers configuration */ - MODIFY_REG(Device->PCR, PCR_CLEAR_MASK, (Init->Waitfeature | - FMC_PCR_MEMORY_TYPE_NAND | - Init->MemoryDataWidth | - Init->EccComputation | - Init->ECCPageSize | - ((Init->TCLRSetupTime) << FMC_PCR_TCLR_Pos) | - ((Init->TARSetupTime) << FMC_PCR_TAR_Pos))); - - 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) -{ - /* 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)); - - /* Prevent unused argument(s) compilation warning if no assert_param check */ - UNUSED(Bank); - - /* NAND bank 3 registers configuration */ - Device->PMEM =(Timing->SetupTime | - ((Timing->WaitSetupTime) << FMC_PMEM_MEMWAIT_Pos) | - ((Timing->HoldSetupTime )<< FMC_PMEM_MEMHOLD_Pos) | - ((Timing->HiZSetupTime) << FMC_PMEM_MEMHIZ_Pos)); - - 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) -{ - /* 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)); - - /* Prevent unused argument(s) compilation warning if no assert_param check */ - UNUSED(Bank); - - /* NAND bank 3 registers configuration */ - Device->PATT =(Timing->SetupTime | - ((Timing->WaitSetupTime) << FMC_PATT_ATTWAIT_Pos) | - ((Timing->HoldSetupTime) << FMC_PATT_ATTHOLD_Pos) | - ((Timing->HiZSetupTime) << FMC_PATT_ATTHIZ_Pos)); - - 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 */ - /* Prevent unused argument(s) compilation warning if no assert_param check */ - UNUSED(Bank); - - /* Set the FMC_NAND_BANK3 registers to their reset values */ - WRITE_REG(Device->PCR, 0x00000018U); - WRITE_REG(Device->SR, 0x00000040U); - WRITE_REG(Device->PMEM, 0xFCFCFCFCU); - WRITE_REG(Device->PATT, 0xFCFCFCFCU); - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup HAL_FMC_NAND_Group2 Peripheral 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 */ - /* Prevent unused argument(s) compilation warning if no assert_param check */ - UNUSED(Bank); - - SET_BIT(Device->PCR, FMC_PCR_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 */ - /* Prevent unused argument(s) compilation warning if no assert_param check */ - UNUSED(Bank); - - CLEAR_BIT(Device->PCR, FMC_PCR_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 tickstart; - - /* Check the parameters */ - assert_param(IS_FMC_NAND_DEVICE(Device)); - assert_param(IS_FMC_NAND_BANK(Bank)); - - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Wait until FIFO is empty */ - while (__FMC_NAND_GET_FLAG(Device, Bank, FMC_FLAG_FEMPT) == RESET) - { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) - { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) - { - return HAL_TIMEOUT; - } - } - } - - /* Prevent unused argument(s) compilation warning if no assert_param check */ - UNUSED(Bank); - - /* Get the ECCR register value */ - *ECCval = (uint32_t)Device->ECCR; - - return HAL_OK; -} - -/** - * @} - */ - - - -/** @defgroup FMC_LL_SDRAM - * @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 - * @{ - */ - -/** @addtogroup FMC_LL_SDRAM_Private_Functions_Group1 - * @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) -{ - /* 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_BANK1) - { - MODIFY_REG(Device->SDCR[FMC_SDRAM_BANK1], - SDCR_CLEAR_MASK, - (Init->ColumnBitsNumber | - Init->RowBitsNumber | - Init->MemoryDataWidth | - Init->InternalBankNumber | - Init->CASLatency | - Init->WriteProtection | - Init->SDClockPeriod | - Init->ReadBurst | - Init->ReadPipeDelay)); - } - else /* FMC_Bank2_SDRAM */ - { - MODIFY_REG(Device->SDCR[FMC_SDRAM_BANK1], - FMC_SDCRx_SDCLK | - FMC_SDCRx_RBURST | - FMC_SDCRx_RPIPE, - (Init->SDClockPeriod | - Init->ReadBurst | - Init->ReadPipeDelay)); - - MODIFY_REG(Device->SDCR[FMC_SDRAM_BANK2], - SDCR_CLEAR_MASK, - (Init->ColumnBitsNumber | - Init->RowBitsNumber | - Init->MemoryDataWidth | - Init->InternalBankNumber | - Init->CASLatency | - Init->WriteProtection)); - } - - 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) -{ - /* 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_BANK1) - { - MODIFY_REG(Device->SDTR[FMC_SDRAM_BANK1], - SDTR_CLEAR_MASK, - (((Timing->LoadToActiveDelay) - 1U) | - (((Timing->ExitSelfRefreshDelay) - 1U) << FMC_SDTRx_TXSR_Pos) | - (((Timing->SelfRefreshTime) - 1U) << FMC_SDTRx_TRAS_Pos) | - (((Timing->RowCycleDelay) - 1U) << FMC_SDTRx_TRC_Pos) | - (((Timing->WriteRecoveryTime) - 1U) << FMC_SDTRx_TWR_Pos) | - (((Timing->RPDelay) - 1U) << FMC_SDTRx_TRP_Pos) | - (((Timing->RCDDelay) - 1U) << FMC_SDTRx_TRCD_Pos))); - } - else /* FMC_Bank2_SDRAM */ - { - MODIFY_REG(Device->SDTR[FMC_SDRAM_BANK1], - FMC_SDTRx_TRC | - FMC_SDTRx_TRP, - (((Timing->RowCycleDelay) - 1U) << FMC_SDTRx_TRC_Pos) | - (((Timing->RPDelay) - 1U) << FMC_SDTRx_TRP_Pos)); - - MODIFY_REG(Device->SDTR[FMC_SDRAM_BANK2], - SDTR_CLEAR_MASK, - (((Timing->LoadToActiveDelay) - 1U) | - (((Timing->ExitSelfRefreshDelay) - 1U) << FMC_SDTRx_TXSR_Pos) | - (((Timing->SelfRefreshTime) - 1U) << FMC_SDTRx_TRAS_Pos) | - (((Timing->WriteRecoveryTime) - 1U) << FMC_SDTRx_TWR_Pos) | - (((Timing->RCDDelay) - 1U) << FMC_SDTRx_TRCD_Pos))); - } - - 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] = 0x000002D0U; - Device->SDTR[Bank] = 0x0FFFFFFFU; - Device->SDCMR = 0x00000000U; - Device->SDRTR = 0x00000000U; - Device->SDSR = 0x00000000U; - - return HAL_OK; -} - -/** - * @} - */ - -/** @addtogroup FMC_LL_SDRAMPrivate_Functions_Group2 - * @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 */ - SET_BIT(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 */ - CLEAR_BIT(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) -{ - /* 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 */ - MODIFY_REG(Device->SDCMR, (FMC_SDCMR_MODE | FMC_SDCMR_CTB2 | FMC_SDCMR_CTB1 | FMC_SDCMR_NRFS | FMC_SDCMR_MRD), - ((Command->CommandMode) | (Command->CommandTarget) | - (((Command->AutoRefreshNumber) - 1U) << FMC_SDCMR_NRFS_Pos) | - ((Command->ModeRegisterDefinition) << FMC_SDCMR_MRD_Pos))); - /* Prevent unused argument(s) compilation warning */ - UNUSED(Timeout); - 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 */ - MODIFY_REG(Device->SDRTR, FMC_SDRTR_COUNT, (RefreshRate << FMC_SDRTR_COUNT_Pos)); - - 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 */ - MODIFY_REG(Device->SDCMR, FMC_SDCMR_NRFS, ((AutoRefreshNumber - 1U) << FMC_SDCMR_NRFS_Pos)); - - 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(const FMC_SDRAM_TypeDef *Device, uint32_t Bank) -{ - uint32_t tmpreg; - - /* 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) >> 2U); - } - - /* Return the mode status */ - return tmpreg; -} - -/** - * @} - */ - -/** - * @} - */ - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* HAL_NOR_MODULE_ENABLED */ -/** - * @} - */ -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_fmc.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### FMC peripheral features ##### + ============================================================================== + [..] The Flexible memory controller (FMC) includes following memory controllers: + (+) The NOR/PSRAM memory controller + (+) The NAND memory controller + (+) The Synchronous DRAM (SDRAM) controller + + [..] The FMC functional block makes the interface with synchronous and asynchronous static + memories and SDRAM memories. 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) + (++) 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 + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ +#if defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) || defined(HAL_SDRAM_MODULE_ENABLED)\ + || defined(HAL_SRAM_MODULE_ENABLED) + +/** @defgroup FMC_LL FMC Low Layer + * @brief FMC driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + +/** @defgroup FMC_LL_Private_Constants FMC Low Layer Private Constants + * @{ + */ + +/* ----------------------- FMC registers bit mask --------------------------- */ + +/* --- BCR Register ---*/ +/* BCR register clear mask */ + +/* --- BTR Register ---*/ +/* BTR register clear mask */ +#define BTR_CLEAR_MASK ((uint32_t)(FMC_BTRx_ADDSET | FMC_BTRx_ADDHLD |\ + FMC_BTRx_DATAST | FMC_BTRx_BUSTURN |\ + FMC_BTRx_CLKDIV | FMC_BTRx_DATLAT |\ + FMC_BTRx_ACCMOD)) + +/* --- BWTR Register ---*/ +/* BWTR register clear mask */ +#if defined(FMC_BWTRx_BUSTURN) +#define BWTR_CLEAR_MASK ((uint32_t)(FMC_BWTRx_ADDSET | FMC_BWTRx_ADDHLD |\ + FMC_BWTRx_DATAST | FMC_BWTRx_BUSTURN |\ + FMC_BWTRx_ACCMOD)) +#else +#define BWTR_CLEAR_MASK ((uint32_t)(FMC_BWTRx_ADDSET | FMC_BWTRx_ADDHLD |\ + FMC_BWTRx_DATAST | FMC_BWTRx_ACCMOD)) +#endif /* FMC_BWTRx_BUSTURN */ + +/* --- PCR Register ---*/ +/* PCR register clear mask */ +#define PCR_CLEAR_MASK ((uint32_t)(FMC_PCR_PWAITEN | FMC_PCR_PBKEN | \ + FMC_PCR_PWID | FMC_PCR_ECCEN | \ + FMC_PCR_TCLR | FMC_PCR_TAR | \ + FMC_PCR_ECCPS)) +/* --- PMEM Register ---*/ +/* PMEM register clear mask */ +#define PMEM_CLEAR_MASK ((uint32_t)(FMC_PMEM_MEMSET | FMC_PMEM_MEMWAIT |\ + FMC_PMEM_MEMHOLD | FMC_PMEM_MEMHIZ)) + +/* --- PATT Register ---*/ +/* PATT register clear mask */ +#define PATT_CLEAR_MASK ((uint32_t)(FMC_PATT_ATTSET | FMC_PATT_ATTWAIT |\ + FMC_PATT_ATTHOLD | FMC_PATT_ATTHIZ)) + + +/* --- SDCR Register ---*/ +/* SDCR register clear mask */ +#define SDCR_CLEAR_MASK ((uint32_t)(FMC_SDCRx_NC | FMC_SDCRx_NR | \ + FMC_SDCRx_MWID | FMC_SDCRx_NB | \ + FMC_SDCRx_CAS | FMC_SDCRx_WP | \ + FMC_SDCRx_SDCLK | FMC_SDCRx_RBURST | \ + FMC_SDCRx_RPIPE)) + +/* --- SDTR Register ---*/ +/* SDTR register clear mask */ +#define SDTR_CLEAR_MASK ((uint32_t)(FMC_SDTRx_TMRD | FMC_SDTRx_TXSR | \ + FMC_SDTRx_TRAS | FMC_SDTRx_TRC | \ + FMC_SDTRx_TWR | FMC_SDTRx_TRP | \ + FMC_SDTRx_TRCD)) + +/** + * @} + */ + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup FMC_LL_Exported_Functions FMC Low Layer Exported Functions + * @{ + */ + + +/** @defgroup FMC_LL_Exported_Functions_NORSRAM FMC Low Layer NOR SRAM Exported 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 FMC_LL_NORSRAM_Exported_Functions_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 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, + const FMC_NORSRAM_InitTypeDef *Init) +{ + uint32_t flashaccess; + uint32_t btcr_reg; + uint32_t mask; + + /* 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_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)); + assert_param(IS_FMC_WRITE_FIFO(Init->WriteFifo)); + assert_param(IS_FMC_PAGESIZE(Init->PageSize)); + + /* Disable NORSRAM Device */ + __FMC_NORSRAM_DISABLE(Device, Init->NSBank); + + /* Set NORSRAM device control parameters */ + if (Init->MemoryType == FMC_MEMORY_TYPE_NOR) + { + flashaccess = FMC_NORSRAM_FLASH_ACCESS_ENABLE; + } + else + { + flashaccess = FMC_NORSRAM_FLASH_ACCESS_DISABLE; + } + + btcr_reg = (flashaccess | \ + Init->DataAddressMux | \ + Init->MemoryType | \ + Init->MemoryDataWidth | \ + Init->BurstAccessMode | \ + Init->WaitSignalPolarity | \ + Init->WaitSignalActive | \ + Init->WriteOperation | \ + Init->WaitSignal | \ + Init->ExtendedMode | \ + Init->AsynchronousWait | \ + Init->WriteBurst); + + btcr_reg |= Init->ContinuousClock; + btcr_reg |= Init->WriteFifo; + btcr_reg |= Init->PageSize; + + mask = (FMC_BCRx_MBKEN | + FMC_BCRx_MUXEN | + FMC_BCRx_MTYP | + FMC_BCRx_MWID | + FMC_BCRx_FACCEN | + FMC_BCRx_BURSTEN | + FMC_BCRx_WAITPOL | + FMC_BCRx_WAITCFG | + FMC_BCRx_WREN | + FMC_BCRx_WAITEN | + FMC_BCRx_EXTMOD | + FMC_BCRx_ASYNCWAIT | + FMC_BCRx_CBURSTRW); + + mask |= FMC_BCR1_CCLKEN; + mask |= FMC_BCR1_WFDIS; + mask |= FMC_BCRx_CPSIZE; + + MODIFY_REG(Device->BTCR[Init->NSBank], mask, btcr_reg); + + /* Configure synchronous mode when Continuous clock is enabled for bank2..4 */ + if ((Init->ContinuousClock == FMC_CONTINUOUS_CLOCK_SYNC_ASYNC) && (Init->NSBank != FMC_NORSRAM_BANK1)) + { + MODIFY_REG(Device->BTCR[FMC_NORSRAM_BANK1], FMC_BCR1_CCLKEN, Init->ContinuousClock); + } + + if (Init->NSBank != FMC_NORSRAM_BANK1) + { + /* Configure Write FIFO mode when Write Fifo is enabled for bank2..4 */ + SET_BIT(Device->BTCR[FMC_NORSRAM_BANK1], (uint32_t)(Init->WriteFifo)); + } + + 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] = 0x000030DBU; + } + /* FMC_NORSRAM_BANK2, FMC_NORSRAM_BANK3 or FMC_NORSRAM_BANK4 */ + else + { + Device->BTCR[Bank] = 0x000030D2U; + } + + Device->BTCR[Bank + 1U] = 0x0FFFFFFFU; + ExDevice->BWTR[Bank] = 0x0FFFFFFFU; + + 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, + const FMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank) +{ + uint32_t tmpr; + + /* 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 */ + Device->BTCR[Bank + 1U] = + (Timing->AddressSetupTime << FMC_BTRx_ADDSET_Pos) | + (Timing->AddressHoldTime << FMC_BTRx_ADDHLD_Pos) | + (Timing->DataSetupTime << FMC_BTRx_DATAST_Pos) | + (Timing->BusTurnAroundDuration << FMC_BTRx_BUSTURN_Pos) | + ((Timing->CLKDivision - 1U) << FMC_BTRx_CLKDIV_Pos) | + ((Timing->DataLatency - 2U) << FMC_BTRx_DATLAT_Pos) | + Timing->AccessMode; + + /* 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 + 1U] & ~((0x0FU) << FMC_BTRx_CLKDIV_Pos)); + tmpr |= (uint32_t)(((Timing->CLKDivision) - 1U) << FMC_BTRx_CLKDIV_Pos); + MODIFY_REG(Device->BTCR[FMC_NORSRAM_BANK1 + 1U], FMC_BTRx_CLKDIV, 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 + * @param ExtendedMode FMC Extended Mode + * This parameter can be one of the following values: + * @arg FMC_EXTENDED_MODE_DISABLE + * @arg FMC_EXTENDED_MODE_ENABLE + * @retval HAL status + */ +HAL_StatusTypeDef FMC_NORSRAM_Extended_Timing_Init(FMC_NORSRAM_EXTENDED_TypeDef *Device, + const 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)); +#if defined(FMC_BWTRx_BUSTURN) + assert_param(IS_FMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration)); +#endif /* FMC_BWTRx_BUSTURN */ + assert_param(IS_FMC_ACCESS_MODE(Timing->AccessMode)); + assert_param(IS_FMC_NORSRAM_BANK(Bank)); + + /* Set NORSRAM device timing register for write configuration, if extended mode is used */ +#if defined(FMC_BWTRx_BUSTURN) + MODIFY_REG(Device->BWTR[Bank], BWTR_CLEAR_MASK, (Timing->AddressSetupTime | + ((Timing->AddressHoldTime) << FMC_BWTRx_ADDHLD_Pos) | + ((Timing->DataSetupTime) << FMC_BWTRx_DATAST_Pos) | + Timing->AccessMode | + ((Timing->BusTurnAroundDuration) << FMC_BWTRx_BUSTURN_Pos))); +#else /* FMC_BWTRx_BUSTURN */ + MODIFY_REG(Device->BWTR[Bank], BWTR_CLEAR_MASK, (Timing->AddressSetupTime | + ((Timing->AddressHoldTime) << FMC_BWTRx_ADDHLD_Pos) | + ((Timing->DataSetupTime) << FMC_BWTRx_DATAST_Pos) | + Timing->AccessMode)); +#endif /* FMC_BWTRx_BUSTURN */ + } + else + { + Device->BWTR[Bank] = 0x0FFFFFFFU; + } + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup FMC_LL_NORSRAM_Private_Functions_Group2 + * @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 */ + SET_BIT(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 */ + CLEAR_BIT(Device->BTCR[Bank], FMC_WRITE_OPERATION_ENABLE); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + + +/** @defgroup FMC_LL_Exported_Functions_NAND FMC Low Layer NAND Exported Functions + * @brief NAND 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 FMC_LL_NAND_Exported_Functions_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 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, const FMC_NAND_InitTypeDef *Init) +{ + /* 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)); + + /* NAND bank 3 registers configuration */ + MODIFY_REG(Device->PCR, PCR_CLEAR_MASK, (Init->Waitfeature | + FMC_PCR_MEMORY_TYPE_NAND | + Init->MemoryDataWidth | + Init->EccComputation | + Init->ECCPageSize | + ((Init->TCLRSetupTime) << FMC_PCR_TCLR_Pos) | + ((Init->TARSetupTime) << FMC_PCR_TAR_Pos))); + + 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, + const FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) +{ + /* 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)); + + /* Prevent unused argument(s) compilation warning if no assert_param check */ + UNUSED(Bank); + + /* NAND bank 3 registers configuration */ + Device->PMEM = (Timing->SetupTime | + ((Timing->WaitSetupTime) << FMC_PMEM_MEMWAIT_Pos) | + ((Timing->HoldSetupTime) << FMC_PMEM_MEMHOLD_Pos) | + ((Timing->HiZSetupTime) << FMC_PMEM_MEMHIZ_Pos)); + + 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, + const FMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank) +{ + /* 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)); + + /* Prevent unused argument(s) compilation warning if no assert_param check */ + UNUSED(Bank); + + /* NAND bank 3 registers configuration */ + Device->PATT = (Timing->SetupTime | + ((Timing->WaitSetupTime) << FMC_PATT_ATTWAIT_Pos) | + ((Timing->HoldSetupTime) << FMC_PATT_ATTHOLD_Pos) | + ((Timing->HiZSetupTime) << FMC_PATT_ATTHIZ_Pos)); + + 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 */ + /* Prevent unused argument(s) compilation warning if no assert_param check */ + UNUSED(Bank); + + /* Set the FMC_NAND_BANK3 registers to their reset values */ + WRITE_REG(Device->PCR, 0x00000018U); + WRITE_REG(Device->SR, 0x00000040U); + WRITE_REG(Device->PMEM, 0xFCFCFCFCU); + WRITE_REG(Device->PATT, 0xFCFCFCFCU); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_FMC_NAND_Group2 Peripheral 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 */ + /* Prevent unused argument(s) compilation warning if no assert_param check */ + UNUSED(Bank); + + SET_BIT(Device->PCR, FMC_PCR_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 */ + /* Prevent unused argument(s) compilation warning if no assert_param check */ + UNUSED(Bank); + + CLEAR_BIT(Device->PCR, FMC_PCR_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(const FMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, + uint32_t Timeout) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_FMC_NAND_DEVICE(Device)); + assert_param(IS_FMC_NAND_BANK(Bank)); + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until FIFO is empty */ + while (__FMC_NAND_GET_FLAG(Device, Bank, FMC_FLAG_FEMPT) == RESET) + { + /* Check for the Timeout */ + if (Timeout != HAL_MAX_DELAY) + { + if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) + { + return HAL_TIMEOUT; + } + } + } + + /* Prevent unused argument(s) compilation warning if no assert_param check */ + UNUSED(Bank); + + /* Get the ECCR register value */ + *ECCval = (uint32_t)Device->ECCR; + + return HAL_OK; +} + +/** + * @} + */ + + +/** @defgroup FMC_LL_SDRAM + * @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 + * @{ + */ + +/** @addtogroup FMC_LL_SDRAM_Private_Functions_Group1 + * @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, const FMC_SDRAM_InitTypeDef *Init) +{ + /* 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_BANK1) + { + MODIFY_REG(Device->SDCR[FMC_SDRAM_BANK1], + SDCR_CLEAR_MASK, + (Init->ColumnBitsNumber | + Init->RowBitsNumber | + Init->MemoryDataWidth | + Init->InternalBankNumber | + Init->CASLatency | + Init->WriteProtection | + Init->SDClockPeriod | + Init->ReadBurst | + Init->ReadPipeDelay)); + } + else /* FMC_Bank2_SDRAM */ + { + MODIFY_REG(Device->SDCR[FMC_SDRAM_BANK1], + FMC_SDCRx_SDCLK | + FMC_SDCRx_RBURST | + FMC_SDCRx_RPIPE, + (Init->SDClockPeriod | + Init->ReadBurst | + Init->ReadPipeDelay)); + + MODIFY_REG(Device->SDCR[FMC_SDRAM_BANK2], + SDCR_CLEAR_MASK, + (Init->ColumnBitsNumber | + Init->RowBitsNumber | + Init->MemoryDataWidth | + Init->InternalBankNumber | + Init->CASLatency | + Init->WriteProtection)); + } + + 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, + const FMC_SDRAM_TimingTypeDef *Timing, uint32_t Bank) +{ + /* 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_BANK1) + { + MODIFY_REG(Device->SDTR[FMC_SDRAM_BANK1], + SDTR_CLEAR_MASK, + (((Timing->LoadToActiveDelay) - 1U) | + (((Timing->ExitSelfRefreshDelay) - 1U) << FMC_SDTRx_TXSR_Pos) | + (((Timing->SelfRefreshTime) - 1U) << FMC_SDTRx_TRAS_Pos) | + (((Timing->RowCycleDelay) - 1U) << FMC_SDTRx_TRC_Pos) | + (((Timing->WriteRecoveryTime) - 1U) << FMC_SDTRx_TWR_Pos) | + (((Timing->RPDelay) - 1U) << FMC_SDTRx_TRP_Pos) | + (((Timing->RCDDelay) - 1U) << FMC_SDTRx_TRCD_Pos))); + } + else /* FMC_Bank2_SDRAM */ + { + MODIFY_REG(Device->SDTR[FMC_SDRAM_BANK1], + FMC_SDTRx_TRC | + FMC_SDTRx_TRP, + (((Timing->RowCycleDelay) - 1U) << FMC_SDTRx_TRC_Pos) | + (((Timing->RPDelay) - 1U) << FMC_SDTRx_TRP_Pos)); + + MODIFY_REG(Device->SDTR[FMC_SDRAM_BANK2], + SDTR_CLEAR_MASK, + (((Timing->LoadToActiveDelay) - 1U) | + (((Timing->ExitSelfRefreshDelay) - 1U) << FMC_SDTRx_TXSR_Pos) | + (((Timing->SelfRefreshTime) - 1U) << FMC_SDTRx_TRAS_Pos) | + (((Timing->WriteRecoveryTime) - 1U) << FMC_SDTRx_TWR_Pos) | + (((Timing->RCDDelay) - 1U) << FMC_SDTRx_TRCD_Pos))); + } + + 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] = 0x000002D0U; + Device->SDTR[Bank] = 0x0FFFFFFFU; + Device->SDCMR = 0x00000000U; + Device->SDRTR = 0x00000000U; + Device->SDSR = 0x00000000U; + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup FMC_LL_SDRAMPrivate_Functions_Group2 + * @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 */ + SET_BIT(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 */ + CLEAR_BIT(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, + const FMC_SDRAM_CommandTypeDef *Command, uint32_t Timeout) +{ + /* 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 */ + MODIFY_REG(Device->SDCMR, (FMC_SDCMR_MODE | FMC_SDCMR_CTB2 | FMC_SDCMR_CTB1 | FMC_SDCMR_NRFS | FMC_SDCMR_MRD), + ((Command->CommandMode) | (Command->CommandTarget) | + (((Command->AutoRefreshNumber) - 1U) << FMC_SDCMR_NRFS_Pos) | + ((Command->ModeRegisterDefinition) << FMC_SDCMR_MRD_Pos))); + /* Prevent unused argument(s) compilation warning */ + UNUSED(Timeout); + 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 */ + MODIFY_REG(Device->SDRTR, FMC_SDRTR_COUNT, (RefreshRate << FMC_SDRTR_COUNT_Pos)); + + 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 */ + MODIFY_REG(Device->SDCMR, FMC_SDCMR_NRFS, ((AutoRefreshNumber - 1U) << FMC_SDCMR_NRFS_Pos)); + + 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(const FMC_SDRAM_TypeDef *Device, uint32_t Bank) +{ + uint32_t tmpreg; + + /* 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) >> 2U); + } + + /* Return the mode status */ + return tmpreg; +} + +/** + * @} + */ + +/** + * @} + */ + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_NOR_MODULE_ENABLED */ +/** + * @} + */ +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_gpio.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_gpio.c index b3a6b0e60..4b6c87bef 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_gpio.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_gpio.c @@ -1,299 +1,298 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_gpio.c - * @author MCD Application Team - * @brief GPIO LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_gpio.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ -#if defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || \ - defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || \ - defined (GPIOM) || defined (GPION) || defined (GPIOO) || defined (GPIOP) - -/** @addtogroup GPIO_LL - * @{ - */ -/** MISRA C:2012 deviation rule has been granted for following rules: - * Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of - * range of the shift operator in following API : - * LL_GPIO_Init - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup GPIO_LL_Private_Macros - * @{ - */ -#define IS_LL_GPIO_PIN(__VALUE__) (((0x00u) < (__VALUE__)) && ((__VALUE__) <= (LL_GPIO_PIN_ALL))) - -#define IS_LL_GPIO_MODE(__VALUE__) (((__VALUE__) == LL_GPIO_MODE_INPUT) ||\ - ((__VALUE__) == LL_GPIO_MODE_OUTPUT) ||\ - ((__VALUE__) == LL_GPIO_MODE_ALTERNATE) ||\ - ((__VALUE__) == LL_GPIO_MODE_ANALOG)) - -#define IS_LL_GPIO_OUTPUT_TYPE(__VALUE__) (((__VALUE__) == LL_GPIO_OUTPUT_PUSHPULL) ||\ - ((__VALUE__) == LL_GPIO_OUTPUT_OPENDRAIN)) - -#define IS_LL_GPIO_SPEED(__VALUE__) (((__VALUE__) == LL_GPIO_SPEED_FREQ_LOW) ||\ - ((__VALUE__) == LL_GPIO_SPEED_FREQ_MEDIUM) ||\ - ((__VALUE__) == LL_GPIO_SPEED_FREQ_HIGH) ||\ - ((__VALUE__) == LL_GPIO_SPEED_FREQ_VERY_HIGH)) - -#define IS_LL_GPIO_PULL(__VALUE__) (((__VALUE__) == LL_GPIO_PULL_NO) ||\ - ((__VALUE__) == LL_GPIO_PULL_UP) ||\ - ((__VALUE__) == LL_GPIO_PULL_DOWN)) - -#define IS_LL_GPIO_ALTERNATE(__VALUE__) (((__VALUE__) == LL_GPIO_AF_0 ) ||\ - ((__VALUE__) == LL_GPIO_AF_1 ) ||\ - ((__VALUE__) == LL_GPIO_AF_2 ) ||\ - ((__VALUE__) == LL_GPIO_AF_3 ) ||\ - ((__VALUE__) == LL_GPIO_AF_4 ) ||\ - ((__VALUE__) == LL_GPIO_AF_5 ) ||\ - ((__VALUE__) == LL_GPIO_AF_6 ) ||\ - ((__VALUE__) == LL_GPIO_AF_7 ) ||\ - ((__VALUE__) == LL_GPIO_AF_8 ) ||\ - ((__VALUE__) == LL_GPIO_AF_9 ) ||\ - ((__VALUE__) == LL_GPIO_AF_10 ) ||\ - ((__VALUE__) == LL_GPIO_AF_11 ) ||\ - ((__VALUE__) == LL_GPIO_AF_12 ) ||\ - ((__VALUE__) == LL_GPIO_AF_13 ) ||\ - ((__VALUE__) == LL_GPIO_AF_14 ) ||\ - ((__VALUE__) == LL_GPIO_AF_15 )) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup GPIO_LL_Exported_Functions - * @{ - */ - -/** @addtogroup GPIO_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize GPIO registers (Registers restored to their default values). - * @param GPIOx GPIO Port - * @retval An ErrorStatus enumeration value: - * - SUCCESS: GPIO registers are de-initialized - * - ERROR: Wrong GPIO Port - */ -ErrorStatus LL_GPIO_DeInit(const GPIO_TypeDef *GPIOx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); - - /* Force and Release reset on clock of GPIOx Port */ - if (GPIOx == GPIOA) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOA); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOA); - } - else if (GPIOx == GPIOB) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOB); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOB); - } - else if (GPIOx == GPIOC) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOC); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOC); - } - else if (GPIOx == GPIOD) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOD); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOD); - } - else if (GPIOx == GPIOE) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOE); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOE); - } - else if (GPIOx == GPIOF) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOF); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOF); - } - else if (GPIOx == GPIOG) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOG); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOG); - } - else if (GPIOx == GPIOH) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOH); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOH); - } - else if (GPIOx == GPIOM) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOM); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOM); - } - else if (GPIOx == GPION) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPION); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPION); - } - else if (GPIOx == GPIOO) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOO); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOO); - } - else if (GPIOx == GPIOP) - { - LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOP); - LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOP); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Initialize GPIO registers according to the specified parameters in GPIO_InitStruct. - * @param GPIOx GPIO Port - * @param GPIO_InitStruct pointer to a @ref LL_GPIO_InitTypeDef structure - * that contains the configuration information for the specified GPIO peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: GPIO registers are initialized according to GPIO_InitStruct content - * - ERROR: Not applicable - */ -ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, const LL_GPIO_InitTypeDef *GPIO_InitStruct) -{ - uint32_t pinpos; - uint32_t currentpin; - - /* Check the parameters */ - assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); - assert_param(IS_LL_GPIO_PIN(GPIO_InitStruct->Pin)); - assert_param(IS_LL_GPIO_MODE(GPIO_InitStruct->Mode)); - assert_param(IS_LL_GPIO_PULL(GPIO_InitStruct->Pull)); - - /* ------------------------- Configure the port pins ---------------- */ - /* Initialize pinpos on first pin set */ - pinpos = POSITION_VAL(GPIO_InitStruct->Pin); - - /* Configure the port pins */ - while (((GPIO_InitStruct->Pin) >> pinpos) != 0x00u) - { - /* Get current io position */ - currentpin = (GPIO_InitStruct->Pin) & (0x00000001uL << pinpos); - - if (currentpin != 0x00u) - { - if ((GPIO_InitStruct->Mode == LL_GPIO_MODE_OUTPUT) || (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE)) - { - /* Check Speed mode parameters */ - assert_param(IS_LL_GPIO_SPEED(GPIO_InitStruct->Speed)); - - /* Speed mode configuration */ - LL_GPIO_SetPinSpeed(GPIOx, currentpin, GPIO_InitStruct->Speed); - - /* Check Output mode parameters */ - assert_param(IS_LL_GPIO_OUTPUT_TYPE(GPIO_InitStruct->OutputType)); - - /* Output mode configuration*/ - LL_GPIO_SetPinOutputType(GPIOx, currentpin, GPIO_InitStruct->OutputType); - } - - /* Pull-up Pull down resistor configuration*/ - LL_GPIO_SetPinPull(GPIOx, currentpin, GPIO_InitStruct->Pull); - - if (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE) - { - /* Check Alternate parameter */ - assert_param(IS_LL_GPIO_ALTERNATE(GPIO_InitStruct->Alternate)); - - /* Alternate function configuration */ - if (currentpin < LL_GPIO_PIN_8) - { - LL_GPIO_SetAFPin_0_7(GPIOx, currentpin, GPIO_InitStruct->Alternate); - } - else - { - LL_GPIO_SetAFPin_8_15(GPIOx, currentpin, GPIO_InitStruct->Alternate); - } - } - - /* Pin Mode configuration */ - LL_GPIO_SetPinMode(GPIOx, currentpin, GPIO_InitStruct->Mode); - } - pinpos++; - } - - return (SUCCESS); -} - -/** - * @brief Set each @ref LL_GPIO_InitTypeDef field to default value. - * @param GPIO_InitStruct pointer to a @ref LL_GPIO_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ - -void LL_GPIO_StructInit(LL_GPIO_InitTypeDef *GPIO_InitStruct) -{ - /* Reset GPIO init structure parameters values */ - GPIO_InitStruct->Pin = LL_GPIO_PIN_ALL; - GPIO_InitStruct->Mode = LL_GPIO_MODE_ANALOG; - GPIO_InitStruct->Speed = LL_GPIO_SPEED_FREQ_LOW; - GPIO_InitStruct->OutputType = LL_GPIO_OUTPUT_PUSHPULL; - GPIO_InitStruct->Pull = LL_GPIO_PULL_NO; - GPIO_InitStruct->Alternate = LL_GPIO_AF_0; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || */ -/* defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || */ -/* defined (GPIOM) || defined (GPION) || defined (GPIOO) || defined (GPIOP) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_gpio.c + * @author MCD Application Team + * @brief GPIO LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_gpio.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ +#if defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || \ + defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || \ + defined (GPIOM) || defined (GPION) || defined (GPIOO) || defined (GPIOP) + +/** @addtogroup GPIO_LL + * @{ + */ +/** MISRA C:2012 deviation rule has been granted for following rules: + * Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of + * range of the shift operator in following API : + * LL_GPIO_Init + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup GPIO_LL_Private_Macros + * @{ + */ +#define IS_LL_GPIO_PIN(__VALUE__) (((0x00u) < (__VALUE__)) && ((__VALUE__) <= (LL_GPIO_PIN_ALL))) + +#define IS_LL_GPIO_MODE(__VALUE__) (((__VALUE__) == LL_GPIO_MODE_INPUT) ||\ + ((__VALUE__) == LL_GPIO_MODE_OUTPUT) ||\ + ((__VALUE__) == LL_GPIO_MODE_ALTERNATE) ||\ + ((__VALUE__) == LL_GPIO_MODE_ANALOG)) + +#define IS_LL_GPIO_OUTPUT_TYPE(__VALUE__) (((__VALUE__) == LL_GPIO_OUTPUT_PUSHPULL) ||\ + ((__VALUE__) == LL_GPIO_OUTPUT_OPENDRAIN)) + +#define IS_LL_GPIO_SPEED(__VALUE__) (((__VALUE__) == LL_GPIO_SPEED_FREQ_LOW) ||\ + ((__VALUE__) == LL_GPIO_SPEED_FREQ_MEDIUM) ||\ + ((__VALUE__) == LL_GPIO_SPEED_FREQ_HIGH) ||\ + ((__VALUE__) == LL_GPIO_SPEED_FREQ_VERY_HIGH)) + +#define IS_LL_GPIO_PULL(__VALUE__) (((__VALUE__) == LL_GPIO_PULL_NO) ||\ + ((__VALUE__) == LL_GPIO_PULL_UP) ||\ + ((__VALUE__) == LL_GPIO_PULL_DOWN)) + +#define IS_LL_GPIO_ALTERNATE(__VALUE__) (((__VALUE__) == LL_GPIO_AF_0 ) ||\ + ((__VALUE__) == LL_GPIO_AF_1 ) ||\ + ((__VALUE__) == LL_GPIO_AF_2 ) ||\ + ((__VALUE__) == LL_GPIO_AF_3 ) ||\ + ((__VALUE__) == LL_GPIO_AF_4 ) ||\ + ((__VALUE__) == LL_GPIO_AF_5 ) ||\ + ((__VALUE__) == LL_GPIO_AF_6 ) ||\ + ((__VALUE__) == LL_GPIO_AF_7 ) ||\ + ((__VALUE__) == LL_GPIO_AF_8 ) ||\ + ((__VALUE__) == LL_GPIO_AF_9 ) ||\ + ((__VALUE__) == LL_GPIO_AF_10 ) ||\ + ((__VALUE__) == LL_GPIO_AF_11 ) ||\ + ((__VALUE__) == LL_GPIO_AF_12 ) ||\ + ((__VALUE__) == LL_GPIO_AF_13 ) ||\ + ((__VALUE__) == LL_GPIO_AF_14 ) ||\ + ((__VALUE__) == LL_GPIO_AF_15 )) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup GPIO_LL_Exported_Functions + * @{ + */ + +/** @addtogroup GPIO_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize GPIO registers (Registers restored to their default values). + * @param GPIOx GPIO Port + * @retval An ErrorStatus enumeration value: + * - SUCCESS: GPIO registers are de-initialized + * - ERROR: Wrong GPIO Port + */ +ErrorStatus LL_GPIO_DeInit(const GPIO_TypeDef *GPIOx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); + + /* Force and Release reset on clock of GPIOx Port */ + if (GPIOx == GPIOA) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOA); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOA); + } + else if (GPIOx == GPIOB) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOB); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOB); + } + else if (GPIOx == GPIOC) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOC); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOC); + } + else if (GPIOx == GPIOD) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOD); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOD); + } + else if (GPIOx == GPIOE) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOE); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOE); + } + else if (GPIOx == GPIOF) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOF); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOF); + } + else if (GPIOx == GPIOG) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOG); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOG); + } + else if (GPIOx == GPIOH) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOH); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOH); + } + else if (GPIOx == GPIOM) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOM); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOM); + } + else if (GPIOx == GPION) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPION); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPION); + } + else if (GPIOx == GPIOO) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOO); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOO); + } + else if (GPIOx == GPIOP) + { + LL_AHB4_GRP1_ForceReset(LL_AHB4_GRP1_PERIPH_GPIOP); + LL_AHB4_GRP1_ReleaseReset(LL_AHB4_GRP1_PERIPH_GPIOP); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize GPIO registers according to the specified parameters in GPIO_InitStruct. + * @param GPIOx GPIO Port + * @param GPIO_InitStruct pointer to a @ref LL_GPIO_InitTypeDef structure + * that contains the configuration information for the specified GPIO peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: GPIO registers are initialized according to GPIO_InitStruct content + * - ERROR: Not applicable + */ +ErrorStatus LL_GPIO_Init(GPIO_TypeDef *GPIOx, const LL_GPIO_InitTypeDef *GPIO_InitStruct) +{ + uint32_t pinpos; + uint32_t currentpin; + + /* Check the parameters */ + assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); + assert_param(IS_LL_GPIO_PIN(GPIO_InitStruct->Pin)); + assert_param(IS_LL_GPIO_MODE(GPIO_InitStruct->Mode)); + assert_param(IS_LL_GPIO_PULL(GPIO_InitStruct->Pull)); + + /* ------------------------- Configure the port pins ---------------- */ + /* Initialize pinpos on first pin set */ + pinpos = POSITION_VAL(GPIO_InitStruct->Pin); + + /* Configure the port pins */ + while (((GPIO_InitStruct->Pin) >> pinpos) != 0x00u) + { + /* Get current io position */ + currentpin = (GPIO_InitStruct->Pin) & (0x00000001uL << pinpos); + + if (currentpin != 0x00u) + { + if ((GPIO_InitStruct->Mode == LL_GPIO_MODE_OUTPUT) || (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE)) + { + /* Check Speed mode parameters */ + assert_param(IS_LL_GPIO_SPEED(GPIO_InitStruct->Speed)); + + /* Speed mode configuration */ + LL_GPIO_SetPinSpeed(GPIOx, currentpin, GPIO_InitStruct->Speed); + + /* Check Output mode parameters */ + assert_param(IS_LL_GPIO_OUTPUT_TYPE(GPIO_InitStruct->OutputType)); + + /* Output mode configuration*/ + LL_GPIO_SetPinOutputType(GPIOx, currentpin, GPIO_InitStruct->OutputType); + } + + /* Pull-up Pull down resistor configuration*/ + LL_GPIO_SetPinPull(GPIOx, currentpin, GPIO_InitStruct->Pull); + + if (GPIO_InitStruct->Mode == LL_GPIO_MODE_ALTERNATE) + { + /* Check Alternate parameter */ + assert_param(IS_LL_GPIO_ALTERNATE(GPIO_InitStruct->Alternate)); + + /* Alternate function configuration */ + if (currentpin < LL_GPIO_PIN_8) + { + LL_GPIO_SetAFPin_0_7(GPIOx, currentpin, GPIO_InitStruct->Alternate); + } + else + { + LL_GPIO_SetAFPin_8_15(GPIOx, currentpin, GPIO_InitStruct->Alternate); + } + } + + /* Pin Mode configuration */ + LL_GPIO_SetPinMode(GPIOx, currentpin, GPIO_InitStruct->Mode); + } + pinpos++; + } + + return (SUCCESS); +} + +/** + * @brief Set each @ref LL_GPIO_InitTypeDef field to default value. + * @param GPIO_InitStruct pointer to a @ref LL_GPIO_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ + +void LL_GPIO_StructInit(LL_GPIO_InitTypeDef *GPIO_InitStruct) +{ + /* Reset GPIO init structure parameters values */ + GPIO_InitStruct->Pin = LL_GPIO_PIN_ALL; + GPIO_InitStruct->Mode = LL_GPIO_MODE_ANALOG; + GPIO_InitStruct->Speed = LL_GPIO_SPEED_FREQ_LOW; + GPIO_InitStruct->OutputType = LL_GPIO_OUTPUT_PUSHPULL; + GPIO_InitStruct->Pull = LL_GPIO_PULL_NO; + GPIO_InitStruct->Alternate = LL_GPIO_AF_0; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (GPIOA) || defined (GPIOB) || defined (GPIOC) || defined (GPIOD) || */ +/* defined (GPIOE) || defined (GPIOF) || defined (GPIOG) || defined (GPIOH) || */ +/* defined (GPIOM) || defined (GPION) || defined (GPIOO) || defined (GPIOP) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i2c.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i2c.c index 808e7d0db..7dcc7376e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i2c.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i2c.c @@ -1,232 +1,232 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_i2c.c - * @author MCD Application Team - * @brief I2C LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_i2c.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (I2C1) || defined (I2C2) || defined (I2C3) - -/** @defgroup I2C_LL I2C - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup I2C_LL_Private_Macros - * @{ - */ - -#define IS_LL_I2C_PERIPHERAL_MODE(__VALUE__) (((__VALUE__) == LL_I2C_MODE_I2C) || \ - ((__VALUE__) == LL_I2C_MODE_SMBUS_HOST) || \ - ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE) || \ - ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE_ARP)) - -#define IS_LL_I2C_ANALOG_FILTER(__VALUE__) (((__VALUE__) == LL_I2C_ANALOGFILTER_ENABLE) || \ - ((__VALUE__) == LL_I2C_ANALOGFILTER_DISABLE)) - -#define IS_LL_I2C_DIGITAL_FILTER(__VALUE__) ((__VALUE__) <= 0x0000000FU) - -#define IS_LL_I2C_OWN_ADDRESS1(__VALUE__) ((__VALUE__) <= 0x000003FFU) - -#define IS_LL_I2C_TYPE_ACKNOWLEDGE(__VALUE__) (((__VALUE__) == LL_I2C_ACK) || \ - ((__VALUE__) == LL_I2C_NACK)) - -#define IS_LL_I2C_OWN_ADDRSIZE(__VALUE__) (((__VALUE__) == LL_I2C_OWNADDRESS1_7BIT) || \ - ((__VALUE__) == LL_I2C_OWNADDRESS1_10BIT)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I2C_LL_Exported_Functions - * @{ - */ - -/** @addtogroup I2C_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the I2C registers to their default reset values. - * @param I2Cx I2C Instance. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: I2C registers are de-initialized - * - ERROR: I2C registers are not de-initialized - */ -ErrorStatus LL_I2C_DeInit(const I2C_TypeDef *I2Cx) -{ - ErrorStatus status = SUCCESS; - - /* Check the I2C Instance I2Cx */ - assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); - - if (I2Cx == I2C1) - { - /* Force reset of I2C clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1); - - /* Release reset of I2C clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1); - } - else if (I2Cx == I2C2) - { - /* Force reset of I2C clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C2); - - /* Release reset of I2C clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2); - - } - else if (I2Cx == I2C3) - { - /* Force reset of I2C clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C3); - - /* Release reset of I2C clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C3); - } - else - { - status = ERROR; - } - - return status; -} - -/** - * @brief Initialize the I2C registers according to the specified parameters in I2C_InitStruct. - * @param I2Cx I2C Instance. - * @param I2C_InitStruct pointer to a @ref LL_I2C_InitTypeDef structure. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: I2C registers are initialized - * - ERROR: Not applicable - */ -ErrorStatus LL_I2C_Init(I2C_TypeDef *I2Cx, const LL_I2C_InitTypeDef *I2C_InitStruct) -{ - /* Check the I2C Instance I2Cx */ - assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); - - /* Check the I2C parameters from I2C_InitStruct */ - assert_param(IS_LL_I2C_PERIPHERAL_MODE(I2C_InitStruct->PeripheralMode)); - assert_param(IS_LL_I2C_ANALOG_FILTER(I2C_InitStruct->AnalogFilter)); - assert_param(IS_LL_I2C_DIGITAL_FILTER(I2C_InitStruct->DigitalFilter)); - assert_param(IS_LL_I2C_OWN_ADDRESS1(I2C_InitStruct->OwnAddress1)); - assert_param(IS_LL_I2C_TYPE_ACKNOWLEDGE(I2C_InitStruct->TypeAcknowledge)); - assert_param(IS_LL_I2C_OWN_ADDRSIZE(I2C_InitStruct->OwnAddrSize)); - - /* Disable the selected I2Cx Peripheral */ - LL_I2C_Disable(I2Cx); - - /*---------------------------- I2Cx CR1 Configuration ------------------------ - * Configure the analog and digital noise filters with parameters : - * - AnalogFilter: I2C_CR1_ANFOFF bit - * - DigitalFilter: I2C_CR1_DNF[3:0] bits - */ - LL_I2C_ConfigFilters(I2Cx, I2C_InitStruct->AnalogFilter, I2C_InitStruct->DigitalFilter); - - /*---------------------------- I2Cx TIMINGR Configuration -------------------- - * Configure the SDA setup, hold time and the SCL high, low period with parameter : - * - Timing: I2C_TIMINGR_PRESC[3:0], I2C_TIMINGR_SCLDEL[3:0], I2C_TIMINGR_SDADEL[3:0], - * I2C_TIMINGR_SCLH[7:0] and I2C_TIMINGR_SCLL[7:0] bits - */ - LL_I2C_SetTiming(I2Cx, I2C_InitStruct->Timing); - - /* Enable the selected I2Cx Peripheral */ - LL_I2C_Enable(I2Cx); - - /*---------------------------- I2Cx OAR1 Configuration ----------------------- - * Disable, Configure and Enable I2Cx device own address 1 with parameters : - * - OwnAddress1: I2C_OAR1_OA1[9:0] bits - * - OwnAddrSize: I2C_OAR1_OA1MODE bit - */ - LL_I2C_DisableOwnAddress1(I2Cx); - LL_I2C_SetOwnAddress1(I2Cx, I2C_InitStruct->OwnAddress1, I2C_InitStruct->OwnAddrSize); - - /* OwnAdress1 == 0 is reserved for General Call address */ - if (I2C_InitStruct->OwnAddress1 != 0U) - { - LL_I2C_EnableOwnAddress1(I2Cx); - } - - /*---------------------------- I2Cx MODE Configuration ----------------------- - * Configure I2Cx peripheral mode with parameter : - * - PeripheralMode: I2C_CR1_SMBDEN and I2C_CR1_SMBHEN bits - */ - LL_I2C_SetMode(I2Cx, I2C_InitStruct->PeripheralMode); - - /*---------------------------- I2Cx CR2 Configuration ------------------------ - * Configure the ACKnowledge or Non ACKnowledge condition - * after the address receive match code or next received byte with parameter : - * - TypeAcknowledge: I2C_CR2_NACK bit - */ - LL_I2C_AcknowledgeNextData(I2Cx, I2C_InitStruct->TypeAcknowledge); - - return SUCCESS; -} - -/** - * @brief Set each @ref LL_I2C_InitTypeDef field to default value. - * @param I2C_InitStruct Pointer to a @ref LL_I2C_InitTypeDef structure. - * @retval None - */ -void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct) -{ - /* Set I2C_InitStruct fields to default values */ - I2C_InitStruct->PeripheralMode = LL_I2C_MODE_I2C; - I2C_InitStruct->Timing = 0U; - I2C_InitStruct->AnalogFilter = LL_I2C_ANALOGFILTER_ENABLE; - I2C_InitStruct->DigitalFilter = 0U; - I2C_InitStruct->OwnAddress1 = 0U; - I2C_InitStruct->TypeAcknowledge = LL_I2C_NACK; - I2C_InitStruct->OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* I2C1 || I2C2 || I2C3 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_i2c.c + * @author MCD Application Team + * @brief I2C LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_i2c.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (I2C1) || defined (I2C2) || defined (I2C3) + +/** @defgroup I2C_LL I2C + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup I2C_LL_Private_Macros + * @{ + */ + +#define IS_LL_I2C_PERIPHERAL_MODE(__VALUE__) (((__VALUE__) == LL_I2C_MODE_I2C) || \ + ((__VALUE__) == LL_I2C_MODE_SMBUS_HOST) || \ + ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE) || \ + ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE_ARP)) + +#define IS_LL_I2C_ANALOG_FILTER(__VALUE__) (((__VALUE__) == LL_I2C_ANALOGFILTER_ENABLE) || \ + ((__VALUE__) == LL_I2C_ANALOGFILTER_DISABLE)) + +#define IS_LL_I2C_DIGITAL_FILTER(__VALUE__) ((__VALUE__) <= 0x0000000FU) + +#define IS_LL_I2C_OWN_ADDRESS1(__VALUE__) ((__VALUE__) <= 0x000003FFU) + +#define IS_LL_I2C_TYPE_ACKNOWLEDGE(__VALUE__) (((__VALUE__) == LL_I2C_ACK) || \ + ((__VALUE__) == LL_I2C_NACK)) + +#define IS_LL_I2C_OWN_ADDRSIZE(__VALUE__) (((__VALUE__) == LL_I2C_OWNADDRESS1_7BIT) || \ + ((__VALUE__) == LL_I2C_OWNADDRESS1_10BIT)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2C_LL_Exported_Functions + * @{ + */ + +/** @addtogroup I2C_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the I2C registers to their default reset values. + * @param I2Cx I2C Instance. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: I2C registers are de-initialized + * - ERROR: I2C registers are not de-initialized + */ +ErrorStatus LL_I2C_DeInit(const I2C_TypeDef *I2Cx) +{ + ErrorStatus status = SUCCESS; + + /* Check the I2C Instance I2Cx */ + assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); + + if (I2Cx == I2C1) + { + /* Force reset of I2C clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1); + + /* Release reset of I2C clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1); + } + else if (I2Cx == I2C2) + { + /* Force reset of I2C clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C2); + + /* Release reset of I2C clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2); + + } + else if (I2Cx == I2C3) + { + /* Force reset of I2C clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C3); + + /* Release reset of I2C clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C3); + } + else + { + status = ERROR; + } + + return status; +} + +/** + * @brief Initialize the I2C registers according to the specified parameters in I2C_InitStruct. + * @param I2Cx I2C Instance. + * @param I2C_InitStruct pointer to a @ref LL_I2C_InitTypeDef structure. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: I2C registers are initialized + * - ERROR: Not applicable + */ +ErrorStatus LL_I2C_Init(I2C_TypeDef *I2Cx, const LL_I2C_InitTypeDef *I2C_InitStruct) +{ + /* Check the I2C Instance I2Cx */ + assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); + + /* Check the I2C parameters from I2C_InitStruct */ + assert_param(IS_LL_I2C_PERIPHERAL_MODE(I2C_InitStruct->PeripheralMode)); + assert_param(IS_LL_I2C_ANALOG_FILTER(I2C_InitStruct->AnalogFilter)); + assert_param(IS_LL_I2C_DIGITAL_FILTER(I2C_InitStruct->DigitalFilter)); + assert_param(IS_LL_I2C_OWN_ADDRESS1(I2C_InitStruct->OwnAddress1)); + assert_param(IS_LL_I2C_TYPE_ACKNOWLEDGE(I2C_InitStruct->TypeAcknowledge)); + assert_param(IS_LL_I2C_OWN_ADDRSIZE(I2C_InitStruct->OwnAddrSize)); + + /* Disable the selected I2Cx Peripheral */ + LL_I2C_Disable(I2Cx); + + /*---------------------------- I2Cx CR1 Configuration ------------------------ + * Configure the analog and digital noise filters with parameters : + * - AnalogFilter: I2C_CR1_ANFOFF bit + * - DigitalFilter: I2C_CR1_DNF[3:0] bits + */ + LL_I2C_ConfigFilters(I2Cx, I2C_InitStruct->AnalogFilter, I2C_InitStruct->DigitalFilter); + + /*---------------------------- I2Cx TIMINGR Configuration -------------------- + * Configure the SDA setup, hold time and the SCL high, low period with parameter : + * - Timing: I2C_TIMINGR_PRESC[3:0], I2C_TIMINGR_SCLDEL[3:0], I2C_TIMINGR_SDADEL[3:0], + * I2C_TIMINGR_SCLH[7:0] and I2C_TIMINGR_SCLL[7:0] bits + */ + LL_I2C_SetTiming(I2Cx, I2C_InitStruct->Timing); + + /* Enable the selected I2Cx Peripheral */ + LL_I2C_Enable(I2Cx); + + /*---------------------------- I2Cx OAR1 Configuration ----------------------- + * Disable, Configure and Enable I2Cx device own address 1 with parameters : + * - OwnAddress1: I2C_OAR1_OA1[9:0] bits + * - OwnAddrSize: I2C_OAR1_OA1MODE bit + */ + LL_I2C_DisableOwnAddress1(I2Cx); + LL_I2C_SetOwnAddress1(I2Cx, I2C_InitStruct->OwnAddress1, I2C_InitStruct->OwnAddrSize); + + /* OwnAdress1 == 0 is reserved for General Call address */ + if (I2C_InitStruct->OwnAddress1 != 0U) + { + LL_I2C_EnableOwnAddress1(I2Cx); + } + + /*---------------------------- I2Cx MODE Configuration ----------------------- + * Configure I2Cx peripheral mode with parameter : + * - PeripheralMode: I2C_CR1_SMBDEN and I2C_CR1_SMBHEN bits + */ + LL_I2C_SetMode(I2Cx, I2C_InitStruct->PeripheralMode); + + /*---------------------------- I2Cx CR2 Configuration ------------------------ + * Configure the ACKnowledge or Non ACKnowledge condition + * after the address receive match code or next received byte with parameter : + * - TypeAcknowledge: I2C_CR2_NACK bit + */ + LL_I2C_AcknowledgeNextData(I2Cx, I2C_InitStruct->TypeAcknowledge); + + return SUCCESS; +} + +/** + * @brief Set each @ref LL_I2C_InitTypeDef field to default value. + * @param I2C_InitStruct Pointer to a @ref LL_I2C_InitTypeDef structure. + * @retval None + */ +void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct) +{ + /* Set I2C_InitStruct fields to default values */ + I2C_InitStruct->PeripheralMode = LL_I2C_MODE_I2C; + I2C_InitStruct->Timing = 0U; + I2C_InitStruct->AnalogFilter = LL_I2C_ANALOGFILTER_ENABLE; + I2C_InitStruct->DigitalFilter = 0U; + I2C_InitStruct->OwnAddress1 = 0U; + I2C_InitStruct->TypeAcknowledge = LL_I2C_NACK; + I2C_InitStruct->OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* I2C1 || I2C2 || I2C3 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i3c.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i3c.c index bcea19132..de45c2fac 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i3c.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_i3c.c @@ -1,197 +1,197 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_i3c.c - * @author MCD Application Team - * @brief I3C LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_i3c.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (I3C1) - -/** @defgroup I3C_LL I3C - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup I3C_LL_Private_Macros - * @{ - */ -#define IS_LL_I3C_SDAHOLDTIME_VALUE(VALUE) (((VALUE) == LL_I3C_SDA_HOLD_TIME_0_5) || \ - ((VALUE) == LL_I3C_SDA_HOLD_TIME_1_5)) - -#define IS_LL_I3C_WAITTIME_VALUE(VALUE) (((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_0) || \ - ((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_1) || \ - ((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_2) || \ - ((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_3)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I3C_LL_Exported_Functions - * @{ - */ - -/** @addtogroup I3C_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the I3C registers to their default reset values. - * @param I3Cx I3C Instance. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: I3C registers are de-initialized - * - ERROR: I3C registers are not de-initialized - */ -ErrorStatus LL_I3C_DeInit(const I3C_TypeDef *I3Cx) -{ - ErrorStatus status = SUCCESS; - - /* Check the I3C Instance I3Cx */ - assert_param(IS_I3C_ALL_INSTANCE(I3Cx)); - - /* Prevent unused argument(s) compilation warning */ - UNUSED(I3Cx); - - /* Force reset of I3C clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I3C1); - - /* Release reset of I3C clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I3C1); - - return status; -} - -/** - * @brief Initialize the I3C registers according to the specified parameters in I3C_InitStruct. - * @param I3Cx I3C Instance. - * @param I3C_InitStruct pointer to a @ref LL_I3C_InitTypeDef structure. - * @param Mode I3C peripheral mode. - * This parameter can be a value of @ref I3C_LL_EC_MODE. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: I3C registers are initialized - * - ERROR: Not applicable - */ -ErrorStatus LL_I3C_Init(I3C_TypeDef *I3Cx, LL_I3C_InitTypeDef *I3C_InitStruct, uint32_t Mode) -{ - uint32_t waveform_value; - uint32_t timing_value; - - /* Check the I3C Instance I3Cx */ - assert_param(IS_I3C_ALL_INSTANCE(I3Cx)); - - /* Disable the selected I3C peripheral */ - LL_I3C_Disable(I3Cx); - - /* Check on the I3C mode: initialization depends on the mode */ - if (Mode == LL_I3C_MODE_CONTROLLER) - { - /* Check the parameters */ - assert_param(IS_LL_I3C_SDAHOLDTIME_VALUE(I3C_InitStruct->CtrlBusCharacteristic.SDAHoldTime)); - assert_param(IS_LL_I3C_WAITTIME_VALUE(I3C_InitStruct->CtrlBusCharacteristic.WaitTime)); - - /* Set Controller mode */ - LL_I3C_SetMode(I3Cx, LL_I3C_MODE_CONTROLLER); - - /*------------------ SCL signal waveform configuration : I3C timing register 0 (I3C_TIMINGR0) ------------------- */ - /* Set the controller SCL waveform */ - waveform_value = - ((uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.SCLPPLowDuration) | - ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.SCLI3CHighDuration << I3C_TIMINGR0_SCLH_I3C_Pos) | - ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.SCLODLowDuration << I3C_TIMINGR0_SCLL_OD_Pos) | - ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.SCLI2CHighDuration << I3C_TIMINGR0_SCLH_I2C_Pos)); - - LL_I3C_ConfigClockWaveForm(I3Cx, waveform_value); - - /*------------------- Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------- */ - /* Set SDA hold time, activity state, bus free duration and bus available duration */ - timing_value = ((uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.SDAHoldTime) | - (uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.WaitTime) | - ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.BusFreeDuration << I3C_TIMINGR1_FREE_Pos) | - (uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.BusIdleDuration)); - - LL_I3C_SetCtrlBusCharacteristic(I3Cx, timing_value); - } - else - { - /* Set target mode */ - LL_I3C_SetMode(I3Cx, LL_I3C_MODE_TARGET); - - /*------------------- Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------- */ - /* Set the number of kernel clocks cycles for the bus available condition time */ - LL_I3C_SetTgtBusCharacteristic(I3Cx, I3C_InitStruct->TgtBusCharacteristic.BusAvailableDuration); - } - - /* Enable the selected I3C peripheral */ - LL_I3C_Enable(I3Cx); - - return SUCCESS; -} - -/** - * @brief Set each @ref LL_I3C_InitTypeDef field to default value. - * @param I3C_InitStruct Pointer to a @ref LL_I3C_InitTypeDef structure. - * @retval None - */ -void LL_I3C_StructInit(LL_I3C_InitTypeDef *I3C_InitStruct) -{ - /* Set I3C_InitStruct fields to default values */ - I3C_InitStruct->CtrlBusCharacteristic.SDAHoldTime = LL_I3C_SDA_HOLD_TIME_0_5; - I3C_InitStruct->CtrlBusCharacteristic.WaitTime = LL_I3C_OWN_ACTIVITY_STATE_0; - I3C_InitStruct->CtrlBusCharacteristic.SCLPPLowDuration = 0U; - I3C_InitStruct->CtrlBusCharacteristic.SCLI3CHighDuration = 0U; - I3C_InitStruct->CtrlBusCharacteristic.SCLODLowDuration = 0U; - I3C_InitStruct->CtrlBusCharacteristic.SCLI2CHighDuration = 0U; - I3C_InitStruct->CtrlBusCharacteristic.BusFreeDuration = 0U; - I3C_InitStruct->CtrlBusCharacteristic.BusIdleDuration = 0U; - I3C_InitStruct->TgtBusCharacteristic.BusAvailableDuration = 0U; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* I3C1 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_i3c.c + * @author MCD Application Team + * @brief I3C LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_i3c.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (I3C1) + +/** @defgroup I3C_LL I3C + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup I3C_LL_Private_Macros + * @{ + */ +#define IS_LL_I3C_SDAHOLDTIME_VALUE(VALUE) (((VALUE) == LL_I3C_SDA_HOLD_TIME_0_5) || \ + ((VALUE) == LL_I3C_SDA_HOLD_TIME_1_5)) + +#define IS_LL_I3C_WAITTIME_VALUE(VALUE) (((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_0) || \ + ((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_1) || \ + ((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_2) || \ + ((VALUE) == LL_I3C_OWN_ACTIVITY_STATE_3)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I3C_LL_Exported_Functions + * @{ + */ + +/** @addtogroup I3C_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the I3C registers to their default reset values. + * @param I3Cx I3C Instance. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: I3C registers are de-initialized + * - ERROR: I3C registers are not de-initialized + */ +ErrorStatus LL_I3C_DeInit(const I3C_TypeDef *I3Cx) +{ + ErrorStatus status = SUCCESS; + + /* Check the I3C Instance I3Cx */ + assert_param(IS_I3C_ALL_INSTANCE(I3Cx)); + + /* Prevent unused argument(s) compilation warning */ + UNUSED(I3Cx); + + /* Force reset of I3C clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I3C1); + + /* Release reset of I3C clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I3C1); + + return status; +} + +/** + * @brief Initialize the I3C registers according to the specified parameters in I3C_InitStruct. + * @param I3Cx I3C Instance. + * @param I3C_InitStruct pointer to a @ref LL_I3C_InitTypeDef structure. + * @param Mode I3C peripheral mode. + * This parameter can be a value of @ref I3C_LL_EC_MODE. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: I3C registers are initialized + * - ERROR: Not applicable + */ +ErrorStatus LL_I3C_Init(I3C_TypeDef *I3Cx, LL_I3C_InitTypeDef *I3C_InitStruct, uint32_t Mode) +{ + uint32_t waveform_value; + uint32_t timing_value; + + /* Check the I3C Instance I3Cx */ + assert_param(IS_I3C_ALL_INSTANCE(I3Cx)); + + /* Disable the selected I3C peripheral */ + LL_I3C_Disable(I3Cx); + + /* Check on the I3C mode: initialization depends on the mode */ + if (Mode == LL_I3C_MODE_CONTROLLER) + { + /* Check the parameters */ + assert_param(IS_LL_I3C_SDAHOLDTIME_VALUE(I3C_InitStruct->CtrlBusCharacteristic.SDAHoldTime)); + assert_param(IS_LL_I3C_WAITTIME_VALUE(I3C_InitStruct->CtrlBusCharacteristic.WaitTime)); + + /* Set Controller mode */ + LL_I3C_SetMode(I3Cx, LL_I3C_MODE_CONTROLLER); + + /*------------------ SCL signal waveform configuration : I3C timing register 0 (I3C_TIMINGR0) ------------------- */ + /* Set the controller SCL waveform */ + waveform_value = + ((uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.SCLPPLowDuration) | + ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.SCLI3CHighDuration << I3C_TIMINGR0_SCLH_I3C_Pos) | + ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.SCLODLowDuration << I3C_TIMINGR0_SCLL_OD_Pos) | + ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.SCLI2CHighDuration << I3C_TIMINGR0_SCLH_I2C_Pos)); + + LL_I3C_ConfigClockWaveForm(I3Cx, waveform_value); + + /*------------------- Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------- */ + /* Set SDA hold time, activity state, bus free duration and bus available duration */ + timing_value = ((uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.SDAHoldTime) | + (uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.WaitTime) | + ((uint32_t)I3C_InitStruct->CtrlBusCharacteristic.BusFreeDuration << I3C_TIMINGR1_FREE_Pos) | + (uint32_t)(I3C_InitStruct->CtrlBusCharacteristic.BusIdleDuration)); + + LL_I3C_SetCtrlBusCharacteristic(I3Cx, timing_value); + } + else + { + /* Set target mode */ + LL_I3C_SetMode(I3Cx, LL_I3C_MODE_TARGET); + + /*------------------- Timing configuration : I3C timing register 1 (I3C_TIMINGR1) ------------------------------- */ + /* Set the number of kernel clocks cycles for the bus available condition time */ + LL_I3C_SetTgtBusCharacteristic(I3Cx, I3C_InitStruct->TgtBusCharacteristic.BusAvailableDuration); + } + + /* Enable the selected I3C peripheral */ + LL_I3C_Enable(I3Cx); + + return SUCCESS; +} + +/** + * @brief Set each @ref LL_I3C_InitTypeDef field to default value. + * @param I3C_InitStruct Pointer to a @ref LL_I3C_InitTypeDef structure. + * @retval None + */ +void LL_I3C_StructInit(LL_I3C_InitTypeDef *I3C_InitStruct) +{ + /* Set I3C_InitStruct fields to default values */ + I3C_InitStruct->CtrlBusCharacteristic.SDAHoldTime = LL_I3C_SDA_HOLD_TIME_0_5; + I3C_InitStruct->CtrlBusCharacteristic.WaitTime = LL_I3C_OWN_ACTIVITY_STATE_0; + I3C_InitStruct->CtrlBusCharacteristic.SCLPPLowDuration = 0U; + I3C_InitStruct->CtrlBusCharacteristic.SCLI3CHighDuration = 0U; + I3C_InitStruct->CtrlBusCharacteristic.SCLODLowDuration = 0U; + I3C_InitStruct->CtrlBusCharacteristic.SCLI2CHighDuration = 0U; + I3C_InitStruct->CtrlBusCharacteristic.BusFreeDuration = 0U; + I3C_InitStruct->CtrlBusCharacteristic.BusIdleDuration = 0U; + I3C_InitStruct->TgtBusCharacteristic.BusAvailableDuration = 0U; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* I3C1 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lptim.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lptim.c index 4d4ca05cc..b22135cad 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lptim.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lptim.c @@ -1,206 +1,206 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_lptim.c - * @author MCD Application Team - * @brief LPTIM LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_lptim.h" -#include "stm32h7rsxx_ll_bus.h" -#include "stm32h7rsxx_ll_rcc.h" - - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (LPTIM1) || defined (LPTIM2) || defined (LPTIM3) || defined (LPTIM4) || defined (LPTIM5) - -/** @addtogroup LPTIM_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup LPTIM_LL_Private_Macros - * @{ - */ -#define IS_LL_LPTIM_CLOCK_SOURCE(__VALUE__) (((__VALUE__) == LL_LPTIM_CLK_SOURCE_INTERNAL) \ - || ((__VALUE__) == LL_LPTIM_CLK_SOURCE_EXTERNAL)) - -#define IS_LL_LPTIM_CLOCK_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPTIM_PRESCALER_DIV1) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV2) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV4) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV8) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV16) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV32) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV64) \ - || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV128)) - -#define IS_LL_LPTIM_WAVEFORM(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_PWM) \ - || ((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_SETONCE)) - -/** - * @} - */ - - -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup LPTIM_Private_Functions LPTIM Private Functions - * @{ - */ -/** - * @} - */ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup LPTIM_LL_Exported_Functions - * @{ - */ - -/** @addtogroup LPTIM_LL_EF_Init - * @{ - */ - -/** - * @brief Set LPTIMx registers to their reset values. - * @param LPTIMx LP Timer instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: LPTIMx registers are de-initialized - * - ERROR: invalid LPTIMx instance - */ -ErrorStatus LL_LPTIM_DeInit(const LPTIM_TypeDef *LPTIMx) -{ - ErrorStatus result = SUCCESS; - - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(LPTIMx)); - - if (LPTIMx == LPTIM1) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_LPTIM1); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM1); - } - else if (LPTIMx == LPTIM2) - { - LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM2); - LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM2); - } - else if (LPTIMx == LPTIM3) - { - LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM3); - LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM3); - } - else if (LPTIMx == LPTIM4) - { - LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM4); - LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM4); - } - else if (LPTIMx == LPTIM5) - { - LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM5); - LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM5); - } - else - { - result = ERROR; - } - - return result; -} - -/** - * @brief Set each fields of the LPTIM_InitStruct structure to its default - * value. - * @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure - * @retval None - */ -void LL_LPTIM_StructInit(LL_LPTIM_InitTypeDef *LPTIM_InitStruct) -{ - /* Set the default configuration */ - LPTIM_InitStruct->ClockSource = LL_LPTIM_CLK_SOURCE_INTERNAL; - LPTIM_InitStruct->Prescaler = LL_LPTIM_PRESCALER_DIV1; - LPTIM_InitStruct->Waveform = LL_LPTIM_OUTPUT_WAVEFORM_PWM; -} - -/** - * @brief Configure the LPTIMx peripheral according to the specified parameters. - * @note LL_LPTIM_Init can only be called when the LPTIM instance is disabled. - * @note LPTIMx can be disabled using unitary function @ref LL_LPTIM_Disable(). - * @param LPTIMx LP Timer Instance - * @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: LPTIMx instance has been initialized - * - ERROR: LPTIMx instance hasn't been initialized - */ -ErrorStatus LL_LPTIM_Init(LPTIM_TypeDef *LPTIMx, const LL_LPTIM_InitTypeDef *LPTIM_InitStruct) -{ - ErrorStatus result = SUCCESS; - /* Check the parameters */ - assert_param(IS_LPTIM_INSTANCE(LPTIMx)); - assert_param(IS_LL_LPTIM_CLOCK_SOURCE(LPTIM_InitStruct->ClockSource)); - assert_param(IS_LL_LPTIM_CLOCK_PRESCALER(LPTIM_InitStruct->Prescaler)); - assert_param(IS_LL_LPTIM_WAVEFORM(LPTIM_InitStruct->Waveform)); - - /* The LPTIMx_CFGR register must only be modified when the LPTIM is disabled - (ENABLE bit is reset to 0). - */ - if (LL_LPTIM_IsEnabled(LPTIMx) == 1UL) - { - result = ERROR; - } - else - { - /* Set CKSEL bitfield according to ClockSource value */ - /* Set PRESC bitfield according to Prescaler value */ - /* Set WAVE bitfield according to Waveform value */ - MODIFY_REG(LPTIMx->CFGR, - (LPTIM_CFGR_CKSEL | LPTIM_CFGR_PRESC | LPTIM_CFGR_WAVE), - LPTIM_InitStruct->ClockSource | \ - LPTIM_InitStruct->Prescaler | \ - LPTIM_InitStruct->Waveform); - } - - return result; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* LPTIM1 || LPTIM2 || LPTIM3 || LPTIM4 || LPTIM5 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_lptim.c + * @author MCD Application Team + * @brief LPTIM LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_lptim.h" +#include "stm32h7rsxx_ll_bus.h" +#include "stm32h7rsxx_ll_rcc.h" + + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (LPTIM1) || defined (LPTIM2) || defined (LPTIM3) || defined (LPTIM4) || defined (LPTIM5) + +/** @addtogroup LPTIM_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup LPTIM_LL_Private_Macros + * @{ + */ +#define IS_LL_LPTIM_CLOCK_SOURCE(__VALUE__) (((__VALUE__) == LL_LPTIM_CLK_SOURCE_INTERNAL) \ + || ((__VALUE__) == LL_LPTIM_CLK_SOURCE_EXTERNAL)) + +#define IS_LL_LPTIM_CLOCK_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPTIM_PRESCALER_DIV1) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV2) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV4) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV8) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV16) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV32) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV64) \ + || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV128)) + +#define IS_LL_LPTIM_WAVEFORM(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_PWM) \ + || ((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_SETONCE)) + +/** + * @} + */ + + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup LPTIM_Private_Functions LPTIM Private Functions + * @{ + */ +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup LPTIM_LL_Exported_Functions + * @{ + */ + +/** @addtogroup LPTIM_LL_EF_Init + * @{ + */ + +/** + * @brief Set LPTIMx registers to their reset values. + * @param LPTIMx LP Timer instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: LPTIMx registers are de-initialized + * - ERROR: invalid LPTIMx instance + */ +ErrorStatus LL_LPTIM_DeInit(const LPTIM_TypeDef *LPTIMx) +{ + ErrorStatus result = SUCCESS; + + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(LPTIMx)); + + if (LPTIMx == LPTIM1) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_LPTIM1); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM1); + } + else if (LPTIMx == LPTIM2) + { + LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM2); + LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM2); + } + else if (LPTIMx == LPTIM3) + { + LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM3); + LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM3); + } + else if (LPTIMx == LPTIM4) + { + LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM4); + LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM4); + } + else if (LPTIMx == LPTIM5) + { + LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPTIM5); + LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPTIM5); + } + else + { + result = ERROR; + } + + return result; +} + +/** + * @brief Set each fields of the LPTIM_InitStruct structure to its default + * value. + * @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure + * @retval None + */ +void LL_LPTIM_StructInit(LL_LPTIM_InitTypeDef *LPTIM_InitStruct) +{ + /* Set the default configuration */ + LPTIM_InitStruct->ClockSource = LL_LPTIM_CLK_SOURCE_INTERNAL; + LPTIM_InitStruct->Prescaler = LL_LPTIM_PRESCALER_DIV1; + LPTIM_InitStruct->Waveform = LL_LPTIM_OUTPUT_WAVEFORM_PWM; +} + +/** + * @brief Configure the LPTIMx peripheral according to the specified parameters. + * @note LL_LPTIM_Init can only be called when the LPTIM instance is disabled. + * @note LPTIMx can be disabled using unitary function @ref LL_LPTIM_Disable(). + * @param LPTIMx LP Timer Instance + * @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: LPTIMx instance has been initialized + * - ERROR: LPTIMx instance hasn't been initialized + */ +ErrorStatus LL_LPTIM_Init(LPTIM_TypeDef *LPTIMx, const LL_LPTIM_InitTypeDef *LPTIM_InitStruct) +{ + ErrorStatus result = SUCCESS; + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(LPTIMx)); + assert_param(IS_LL_LPTIM_CLOCK_SOURCE(LPTIM_InitStruct->ClockSource)); + assert_param(IS_LL_LPTIM_CLOCK_PRESCALER(LPTIM_InitStruct->Prescaler)); + assert_param(IS_LL_LPTIM_WAVEFORM(LPTIM_InitStruct->Waveform)); + + /* The LPTIMx_CFGR register must only be modified when the LPTIM is disabled + (ENABLE bit is reset to 0). + */ + if (LL_LPTIM_IsEnabled(LPTIMx) == 1UL) + { + result = ERROR; + } + else + { + /* Set CKSEL bitfield according to ClockSource value */ + /* Set PRESC bitfield according to Prescaler value */ + /* Set WAVE bitfield according to Waveform value */ + MODIFY_REG(LPTIMx->CFGR, + (LPTIM_CFGR_CKSEL | LPTIM_CFGR_PRESC | LPTIM_CFGR_WAVE), + LPTIM_InitStruct->ClockSource | \ + LPTIM_InitStruct->Prescaler | \ + LPTIM_InitStruct->Waveform); + } + + return result; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* LPTIM1 || LPTIM2 || LPTIM3 || LPTIM4 || LPTIM5 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lpuart.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lpuart.c index 8e0626937..22faa2ca5 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lpuart.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_lpuart.c @@ -1,285 +1,285 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_lpuart.c - * @author MCD Application Team - * @brief LPUART LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_lpuart.h" -#include "stm32h7rsxx_ll_rcc.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (LPUART1) - -/** @addtogroup LPUART_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup LPUART_LL_Private_Constants - * @{ - */ - -/* Definition of default baudrate value used for LPUART initialisation */ -#define LPUART_DEFAULT_BAUDRATE (9600U) - -/** - * @} - */ - - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup LPUART_LL_Private_Macros - * @{ - */ - -/* Check of parameters for configuration of LPUART registers */ - -#define IS_LL_LPUART_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPUART_PRESCALER_DIV1) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV2) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV4) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV6) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV8) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV10) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV12) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV16) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV32) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV64) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV128) \ - || ((__VALUE__) == LL_LPUART_PRESCALER_DIV256)) - -/* __BAUDRATE__ Depending on constraints applicable for LPUART BRR register */ -/* value : */ -/* - fck must be in the range [3 x baudrate, 4096 x baudrate] */ -/* - LPUART_BRR register value should be >= 0x300 */ -/* - LPUART_BRR register value should be <= 0xFFFFF (20 bits) */ -/* Baudrate specified by the user should belong to [8, 41600000].*/ -#define IS_LL_LPUART_BAUDRATE(__BAUDRATE__) (((__BAUDRATE__) <= 41600000U) && ((__BAUDRATE__) >= 8U)) - -/* __VALUE__ BRR content must be greater than or equal to 0x300. */ -#define IS_LL_LPUART_BRR_MIN(__VALUE__) ((__VALUE__) >= 0x300U) - -/* __VALUE__ BRR content must be lower than or equal to 0xFFFFF. */ -#define IS_LL_LPUART_BRR_MAX(__VALUE__) ((__VALUE__) <= 0x000FFFFFU) - -#define IS_LL_LPUART_DIRECTION(__VALUE__) (((__VALUE__) == LL_LPUART_DIRECTION_NONE) \ - || ((__VALUE__) == LL_LPUART_DIRECTION_RX) \ - || ((__VALUE__) == LL_LPUART_DIRECTION_TX) \ - || ((__VALUE__) == LL_LPUART_DIRECTION_TX_RX)) - -#define IS_LL_LPUART_PARITY(__VALUE__) (((__VALUE__) == LL_LPUART_PARITY_NONE) \ - || ((__VALUE__) == LL_LPUART_PARITY_EVEN) \ - || ((__VALUE__) == LL_LPUART_PARITY_ODD)) - -#define IS_LL_LPUART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_LPUART_DATAWIDTH_7B) \ - || ((__VALUE__) == LL_LPUART_DATAWIDTH_8B) \ - || ((__VALUE__) == LL_LPUART_DATAWIDTH_9B)) - -#define IS_LL_LPUART_STOPBITS(__VALUE__) (((__VALUE__) == LL_LPUART_STOPBITS_1) \ - || ((__VALUE__) == LL_LPUART_STOPBITS_2)) - -#define IS_LL_LPUART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_LPUART_HWCONTROL_NONE) \ - || ((__VALUE__) == LL_LPUART_HWCONTROL_RTS) \ - || ((__VALUE__) == LL_LPUART_HWCONTROL_CTS) \ - || ((__VALUE__) == LL_LPUART_HWCONTROL_RTS_CTS)) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup LPUART_LL_Exported_Functions - * @{ - */ - -/** @addtogroup LPUART_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize LPUART registers (Registers restored to their default values). - * @param LPUARTx LPUART Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: LPUART registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_LPUART_DeInit(const USART_TypeDef *LPUARTx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_LPUART_INSTANCE(LPUARTx)); - - if (LPUARTx == LPUART1) - { - /* Force reset of LPUART peripheral */ - LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPUART1); - - /* Release reset of LPUART peripheral */ - LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPUART1); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Initialize LPUART registers according to the specified - * parameters in LPUART_InitStruct. - * @note As some bits in LPUART configuration registers can only be written when - * the LPUART is disabled (USART_CR1_UE bit =0), - * LPUART Peripheral should be in disabled state prior calling this function. - * Otherwise, ERROR result will be returned. - * @note Baud rate value stored in LPUART_InitStruct BaudRate field, should be valid (different from 0). - * @param LPUARTx LPUART Instance - * @param LPUART_InitStruct pointer to a @ref LL_LPUART_InitTypeDef structure - * that contains the configuration information for the specified LPUART peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: LPUART registers are initialized according to LPUART_InitStruct content - * - ERROR: Problem occurred during LPUART Registers initialization - */ -ErrorStatus LL_LPUART_Init(USART_TypeDef *LPUARTx, const LL_LPUART_InitTypeDef *LPUART_InitStruct) -{ - ErrorStatus status = ERROR; - uint32_t periphclk; - - /* Check the parameters */ - assert_param(IS_LPUART_INSTANCE(LPUARTx)); - assert_param(IS_LL_LPUART_PRESCALER(LPUART_InitStruct->PrescalerValue)); - assert_param(IS_LL_LPUART_BAUDRATE(LPUART_InitStruct->BaudRate)); - assert_param(IS_LL_LPUART_DATAWIDTH(LPUART_InitStruct->DataWidth)); - assert_param(IS_LL_LPUART_STOPBITS(LPUART_InitStruct->StopBits)); - assert_param(IS_LL_LPUART_PARITY(LPUART_InitStruct->Parity)); - assert_param(IS_LL_LPUART_DIRECTION(LPUART_InitStruct->TransferDirection)); - assert_param(IS_LL_LPUART_HWCONTROL(LPUART_InitStruct->HardwareFlowControl)); - - /* LPUART needs to be in disabled state, in order to be able to configure some bits in - CRx registers. Otherwise (LPUART not in Disabled state) => return ERROR */ - if (LL_LPUART_IsEnabled(LPUARTx) == 0U) - { - /*---------------------------- LPUART CR1 Configuration ----------------------- - * Configure LPUARTx CR1 (LPUART Word Length, Parity and Transfer Direction bits) with parameters: - * - DataWidth: USART_CR1_M bits according to LPUART_InitStruct->DataWidth value - * - Parity: USART_CR1_PCE, USART_CR1_PS bits according to LPUART_InitStruct->Parity value - * - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to LPUART_InitStruct->TransferDirection value - */ - MODIFY_REG(LPUARTx->CR1, - (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE), - (LPUART_InitStruct->DataWidth | LPUART_InitStruct->Parity | LPUART_InitStruct->TransferDirection)); - - /*---------------------------- LPUART CR2 Configuration ----------------------- - * Configure LPUARTx CR2 (Stop bits) with parameters: - * - Stop Bits: USART_CR2_STOP bits according to LPUART_InitStruct->StopBits value. - */ - LL_LPUART_SetStopBitsLength(LPUARTx, LPUART_InitStruct->StopBits); - - /*---------------------------- LPUART CR3 Configuration ----------------------- - * Configure LPUARTx CR3 (Hardware Flow Control) with parameters: - * - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according - * to LPUART_InitStruct->HardwareFlowControl value. - */ - LL_LPUART_SetHWFlowCtrl(LPUARTx, LPUART_InitStruct->HardwareFlowControl); - - /*---------------------------- LPUART BRR Configuration ----------------------- - * Retrieve Clock frequency used for LPUART Peripheral - */ - periphclk = LL_RCC_GetLPUARTClockFreq(LL_RCC_LPUART1_CLKSOURCE); - - /* Configure the LPUART Baud Rate : - - prescaler value is required - - valid baud rate value (different from 0) is required - - Peripheral clock as returned by RCC service, should be valid (different from 0). - */ - if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO) - && (LPUART_InitStruct->BaudRate != 0U)) - { - status = SUCCESS; - LL_LPUART_SetBaudRate(LPUARTx, - periphclk, - LPUART_InitStruct->PrescalerValue, - LPUART_InitStruct->BaudRate); - - /* Check BRR is greater than or equal to 0x300 */ - assert_param(IS_LL_LPUART_BRR_MIN(LPUARTx->BRR)); - - /* Check BRR is lower than or equal to 0xFFFFF */ - assert_param(IS_LL_LPUART_BRR_MAX(LPUARTx->BRR)); - } - - /*---------------------------- LPUART PRESC Configuration ----------------------- - * Configure LPUARTx PRESC (Prescaler) with parameters: - * - PrescalerValue: LPUART_PRESC_PRESCALER bits according to LPUART_InitStruct->PrescalerValue value. - */ - LL_LPUART_SetPrescaler(LPUARTx, LPUART_InitStruct->PrescalerValue); - } - - return (status); -} - -/** - * @brief Set each @ref LL_LPUART_InitTypeDef field to default value. - * @param LPUART_InitStruct pointer to a @ref LL_LPUART_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ - -void LL_LPUART_StructInit(LL_LPUART_InitTypeDef *LPUART_InitStruct) -{ - /* Set LPUART_InitStruct fields to default values */ - LPUART_InitStruct->PrescalerValue = LL_LPUART_PRESCALER_DIV1; - LPUART_InitStruct->BaudRate = LPUART_DEFAULT_BAUDRATE; - LPUART_InitStruct->DataWidth = LL_LPUART_DATAWIDTH_8B; - LPUART_InitStruct->StopBits = LL_LPUART_STOPBITS_1; - LPUART_InitStruct->Parity = LL_LPUART_PARITY_NONE ; - LPUART_InitStruct->TransferDirection = LL_LPUART_DIRECTION_TX_RX; - LPUART_InitStruct->HardwareFlowControl = LL_LPUART_HWCONTROL_NONE; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* LPUART1 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_lpuart.c + * @author MCD Application Team + * @brief LPUART LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_lpuart.h" +#include "stm32h7rsxx_ll_rcc.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (LPUART1) + +/** @addtogroup LPUART_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup LPUART_LL_Private_Constants + * @{ + */ + +/* Definition of default baudrate value used for LPUART initialisation */ +#define LPUART_DEFAULT_BAUDRATE (9600U) + +/** + * @} + */ + + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup LPUART_LL_Private_Macros + * @{ + */ + +/* Check of parameters for configuration of LPUART registers */ + +#define IS_LL_LPUART_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPUART_PRESCALER_DIV1) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV2) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV4) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV6) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV8) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV10) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV12) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV16) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV32) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV64) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV128) \ + || ((__VALUE__) == LL_LPUART_PRESCALER_DIV256)) + +/* __BAUDRATE__ Depending on constraints applicable for LPUART BRR register */ +/* value : */ +/* - fck must be in the range [3 x baudrate, 4096 x baudrate] */ +/* - LPUART_BRR register value should be >= 0x300 */ +/* - LPUART_BRR register value should be <= 0xFFFFF (20 bits) */ +/* Baudrate specified by the user should belong to [8, 41600000].*/ +#define IS_LL_LPUART_BAUDRATE(__BAUDRATE__) (((__BAUDRATE__) <= 41600000U) && ((__BAUDRATE__) >= 8U)) + +/* __VALUE__ BRR content must be greater than or equal to 0x300. */ +#define IS_LL_LPUART_BRR_MIN(__VALUE__) ((__VALUE__) >= 0x300U) + +/* __VALUE__ BRR content must be lower than or equal to 0xFFFFF. */ +#define IS_LL_LPUART_BRR_MAX(__VALUE__) ((__VALUE__) <= 0x000FFFFFU) + +#define IS_LL_LPUART_DIRECTION(__VALUE__) (((__VALUE__) == LL_LPUART_DIRECTION_NONE) \ + || ((__VALUE__) == LL_LPUART_DIRECTION_RX) \ + || ((__VALUE__) == LL_LPUART_DIRECTION_TX) \ + || ((__VALUE__) == LL_LPUART_DIRECTION_TX_RX)) + +#define IS_LL_LPUART_PARITY(__VALUE__) (((__VALUE__) == LL_LPUART_PARITY_NONE) \ + || ((__VALUE__) == LL_LPUART_PARITY_EVEN) \ + || ((__VALUE__) == LL_LPUART_PARITY_ODD)) + +#define IS_LL_LPUART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_LPUART_DATAWIDTH_7B) \ + || ((__VALUE__) == LL_LPUART_DATAWIDTH_8B) \ + || ((__VALUE__) == LL_LPUART_DATAWIDTH_9B)) + +#define IS_LL_LPUART_STOPBITS(__VALUE__) (((__VALUE__) == LL_LPUART_STOPBITS_1) \ + || ((__VALUE__) == LL_LPUART_STOPBITS_2)) + +#define IS_LL_LPUART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_LPUART_HWCONTROL_NONE) \ + || ((__VALUE__) == LL_LPUART_HWCONTROL_RTS) \ + || ((__VALUE__) == LL_LPUART_HWCONTROL_CTS) \ + || ((__VALUE__) == LL_LPUART_HWCONTROL_RTS_CTS)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup LPUART_LL_Exported_Functions + * @{ + */ + +/** @addtogroup LPUART_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize LPUART registers (Registers restored to their default values). + * @param LPUARTx LPUART Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: LPUART registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_LPUART_DeInit(const USART_TypeDef *LPUARTx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_LPUART_INSTANCE(LPUARTx)); + + if (LPUARTx == LPUART1) + { + /* Force reset of LPUART peripheral */ + LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_LPUART1); + + /* Release reset of LPUART peripheral */ + LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_LPUART1); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize LPUART registers according to the specified + * parameters in LPUART_InitStruct. + * @note As some bits in LPUART configuration registers can only be written when + * the LPUART is disabled (USART_CR1_UE bit =0), + * LPUART Peripheral should be in disabled state prior calling this function. + * Otherwise, ERROR result will be returned. + * @note Baud rate value stored in LPUART_InitStruct BaudRate field, should be valid (different from 0). + * @param LPUARTx LPUART Instance + * @param LPUART_InitStruct pointer to a @ref LL_LPUART_InitTypeDef structure + * that contains the configuration information for the specified LPUART peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: LPUART registers are initialized according to LPUART_InitStruct content + * - ERROR: Problem occurred during LPUART Registers initialization + */ +ErrorStatus LL_LPUART_Init(USART_TypeDef *LPUARTx, const LL_LPUART_InitTypeDef *LPUART_InitStruct) +{ + ErrorStatus status = ERROR; + uint32_t periphclk; + + /* Check the parameters */ + assert_param(IS_LPUART_INSTANCE(LPUARTx)); + assert_param(IS_LL_LPUART_PRESCALER(LPUART_InitStruct->PrescalerValue)); + assert_param(IS_LL_LPUART_BAUDRATE(LPUART_InitStruct->BaudRate)); + assert_param(IS_LL_LPUART_DATAWIDTH(LPUART_InitStruct->DataWidth)); + assert_param(IS_LL_LPUART_STOPBITS(LPUART_InitStruct->StopBits)); + assert_param(IS_LL_LPUART_PARITY(LPUART_InitStruct->Parity)); + assert_param(IS_LL_LPUART_DIRECTION(LPUART_InitStruct->TransferDirection)); + assert_param(IS_LL_LPUART_HWCONTROL(LPUART_InitStruct->HardwareFlowControl)); + + /* LPUART needs to be in disabled state, in order to be able to configure some bits in + CRx registers. Otherwise (LPUART not in Disabled state) => return ERROR */ + if (LL_LPUART_IsEnabled(LPUARTx) == 0U) + { + /*---------------------------- LPUART CR1 Configuration ----------------------- + * Configure LPUARTx CR1 (LPUART Word Length, Parity and Transfer Direction bits) with parameters: + * - DataWidth: USART_CR1_M bits according to LPUART_InitStruct->DataWidth value + * - Parity: USART_CR1_PCE, USART_CR1_PS bits according to LPUART_InitStruct->Parity value + * - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to LPUART_InitStruct->TransferDirection value + */ + MODIFY_REG(LPUARTx->CR1, + (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE), + (LPUART_InitStruct->DataWidth | LPUART_InitStruct->Parity | LPUART_InitStruct->TransferDirection)); + + /*---------------------------- LPUART CR2 Configuration ----------------------- + * Configure LPUARTx CR2 (Stop bits) with parameters: + * - Stop Bits: USART_CR2_STOP bits according to LPUART_InitStruct->StopBits value. + */ + LL_LPUART_SetStopBitsLength(LPUARTx, LPUART_InitStruct->StopBits); + + /*---------------------------- LPUART CR3 Configuration ----------------------- + * Configure LPUARTx CR3 (Hardware Flow Control) with parameters: + * - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according + * to LPUART_InitStruct->HardwareFlowControl value. + */ + LL_LPUART_SetHWFlowCtrl(LPUARTx, LPUART_InitStruct->HardwareFlowControl); + + /*---------------------------- LPUART BRR Configuration ----------------------- + * Retrieve Clock frequency used for LPUART Peripheral + */ + periphclk = LL_RCC_GetLPUARTClockFreq(LL_RCC_LPUART1_CLKSOURCE); + + /* Configure the LPUART Baud Rate : + - prescaler value is required + - valid baud rate value (different from 0) is required + - Peripheral clock as returned by RCC service, should be valid (different from 0). + */ + if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO) + && (LPUART_InitStruct->BaudRate != 0U)) + { + status = SUCCESS; + LL_LPUART_SetBaudRate(LPUARTx, + periphclk, + LPUART_InitStruct->PrescalerValue, + LPUART_InitStruct->BaudRate); + + /* Check BRR is greater than or equal to 0x300 */ + assert_param(IS_LL_LPUART_BRR_MIN(LPUARTx->BRR)); + + /* Check BRR is lower than or equal to 0xFFFFF */ + assert_param(IS_LL_LPUART_BRR_MAX(LPUARTx->BRR)); + } + + /*---------------------------- LPUART PRESC Configuration ----------------------- + * Configure LPUARTx PRESC (Prescaler) with parameters: + * - PrescalerValue: LPUART_PRESC_PRESCALER bits according to LPUART_InitStruct->PrescalerValue value. + */ + LL_LPUART_SetPrescaler(LPUARTx, LPUART_InitStruct->PrescalerValue); + } + + return (status); +} + +/** + * @brief Set each @ref LL_LPUART_InitTypeDef field to default value. + * @param LPUART_InitStruct pointer to a @ref LL_LPUART_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ + +void LL_LPUART_StructInit(LL_LPUART_InitTypeDef *LPUART_InitStruct) +{ + /* Set LPUART_InitStruct fields to default values */ + LPUART_InitStruct->PrescalerValue = LL_LPUART_PRESCALER_DIV1; + LPUART_InitStruct->BaudRate = LPUART_DEFAULT_BAUDRATE; + LPUART_InitStruct->DataWidth = LL_LPUART_DATAWIDTH_8B; + LPUART_InitStruct->StopBits = LL_LPUART_STOPBITS_1; + LPUART_InitStruct->Parity = LL_LPUART_PARITY_NONE ; + LPUART_InitStruct->TransferDirection = LL_LPUART_DIRECTION_TX_RX; + LPUART_InitStruct->HardwareFlowControl = LL_LPUART_HWCONTROL_NONE; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* LPUART1 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pka.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pka.c index f13701c68..36e99c0a0 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pka.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pka.c @@ -1,163 +1,163 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_pka.c - * @author MCD Application Team - * @brief PKA LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_pka.h" -#include "stm32h7rsxx_ll_bus.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined(PKA) - -/** @addtogroup PKA_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup PKA_LL_Private_Macros PKA Private Constants - * @{ - */ -#define IS_LL_PKA_MODE(__VALUE__) (((__VALUE__)== LL_PKA_MODE_MODULAR_EXP) ||\ - ((__VALUE__) == LL_PKA_MODE_MONTGOMERY_PARAM) ||\ - ((__VALUE__) == LL_PKA_MODE_MODULAR_EXP_FAST) ||\ - ((__VALUE__) == LL_PKA_MODE_MODULAR_EXP_PROTECT) ||\ - ((__VALUE__) == LL_PKA_MODE_ECC_MUL) ||\ - ((__VALUE__) == LL_PKA_MODE_ECC_COMPLETE_ADD) ||\ - ((__VALUE__) == LL_PKA_MODE_ECDSA_SIGNATURE) ||\ - ((__VALUE__) == LL_PKA_MODE_ECDSA_VERIFICATION) ||\ - ((__VALUE__) == LL_PKA_MODE_POINT_CHECK) ||\ - ((__VALUE__) == LL_PKA_MODE_RSA_CRT_EXP) ||\ - ((__VALUE__) == LL_PKA_MODE_MODULAR_INV) ||\ - ((__VALUE__) == LL_PKA_MODE_ARITHMETIC_ADD) ||\ - ((__VALUE__) == LL_PKA_MODE_ARITHMETIC_SUB) ||\ - ((__VALUE__) == LL_PKA_MODE_ARITHMETIC_MUL) ||\ - ((__VALUE__) == LL_PKA_MODE_COMPARISON) ||\ - ((__VALUE__) == LL_PKA_MODE_MODULAR_REDUC) ||\ - ((__VALUE__) == LL_PKA_MODE_MODULAR_ADD) ||\ - ((__VALUE__) == LL_PKA_MODE_MODULAR_SUB) ||\ - ((__VALUE__) == LL_PKA_MODE_MONTGOMERY_MUL) ||\ - ((__VALUE__) == LL_PKA_MODE_DOUBLE_BASE_LADDER) ||\ - ((__VALUE__) == LL_PKA_MODE_ECC_PROJECTIVE_AFF)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup PKA_LL_Exported_Functions - * @{ - */ - -/** @addtogroup PKA_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize PKA registers (Registers restored to their default values). - * @param PKAx PKA Instance. - * @retval ErrorStatus - * - SUCCESS: PKA registers are de-initialized - * - ERROR: PKA registers are not de-initialized - */ -ErrorStatus LL_PKA_DeInit(const PKA_TypeDef *PKAx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_PKA_ALL_INSTANCE(PKAx)); - - if (PKAx == PKA) - { - /* Force PKA reset */ - LL_AHB3_GRP1_ForceReset(LL_AHB3_GRP1_PERIPH_PKA); - - /* Release PKA reset */ - LL_AHB3_GRP1_ReleaseReset(LL_AHB3_GRP1_PERIPH_PKA); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Initialize PKA registers according to the specified parameters in PKA_InitStruct. - * @param PKAx PKA Instance. - * @param PKA_InitStruct pointer to a @ref LL_PKA_InitTypeDef structure - * that contains the configuration information for the specified PKA peripheral. - * @retval ErrorStatus - * - SUCCESS: PKA registers are initialized according to PKA_InitStruct content - * - ERROR: Not applicable - */ -ErrorStatus LL_PKA_Init(PKA_TypeDef *PKAx, LL_PKA_InitTypeDef *PKA_InitStruct) -{ - assert_param(IS_PKA_ALL_INSTANCE(PKAx)); - assert_param(IS_LL_PKA_MODE(PKA_InitStruct->Mode)); - - LL_PKA_Config(PKAx, PKA_InitStruct->Mode); - - return (SUCCESS); -} - -/** - * @brief Set each @ref LL_PKA_InitTypeDef field to default value. - * @param PKA_InitStruct pointer to a @ref LL_PKA_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ - -void LL_PKA_StructInit(LL_PKA_InitTypeDef *PKA_InitStruct) -{ - /* Reset PKA init structure parameters values */ - PKA_InitStruct->Mode = LL_PKA_MODE_MODULAR_EXP; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined (PKA) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_pka.c + * @author MCD Application Team + * @brief PKA LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_pka.h" +#include "stm32h7rsxx_ll_bus.h" + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined(PKA) + +/** @addtogroup PKA_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup PKA_LL_Private_Macros PKA Private Constants + * @{ + */ +#define IS_LL_PKA_MODE(__VALUE__) (((__VALUE__)== LL_PKA_MODE_MODULAR_EXP) ||\ + ((__VALUE__) == LL_PKA_MODE_MONTGOMERY_PARAM) ||\ + ((__VALUE__) == LL_PKA_MODE_MODULAR_EXP_FAST) ||\ + ((__VALUE__) == LL_PKA_MODE_MODULAR_EXP_PROTECT) ||\ + ((__VALUE__) == LL_PKA_MODE_ECC_MUL) ||\ + ((__VALUE__) == LL_PKA_MODE_ECC_COMPLETE_ADD) ||\ + ((__VALUE__) == LL_PKA_MODE_ECDSA_SIGNATURE) ||\ + ((__VALUE__) == LL_PKA_MODE_ECDSA_VERIFICATION) ||\ + ((__VALUE__) == LL_PKA_MODE_POINT_CHECK) ||\ + ((__VALUE__) == LL_PKA_MODE_RSA_CRT_EXP) ||\ + ((__VALUE__) == LL_PKA_MODE_MODULAR_INV) ||\ + ((__VALUE__) == LL_PKA_MODE_ARITHMETIC_ADD) ||\ + ((__VALUE__) == LL_PKA_MODE_ARITHMETIC_SUB) ||\ + ((__VALUE__) == LL_PKA_MODE_ARITHMETIC_MUL) ||\ + ((__VALUE__) == LL_PKA_MODE_COMPARISON) ||\ + ((__VALUE__) == LL_PKA_MODE_MODULAR_REDUC) ||\ + ((__VALUE__) == LL_PKA_MODE_MODULAR_ADD) ||\ + ((__VALUE__) == LL_PKA_MODE_MODULAR_SUB) ||\ + ((__VALUE__) == LL_PKA_MODE_MONTGOMERY_MUL) ||\ + ((__VALUE__) == LL_PKA_MODE_DOUBLE_BASE_LADDER) ||\ + ((__VALUE__) == LL_PKA_MODE_ECC_PROJECTIVE_AFF)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PKA_LL_Exported_Functions + * @{ + */ + +/** @addtogroup PKA_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize PKA registers (Registers restored to their default values). + * @param PKAx PKA Instance. + * @retval ErrorStatus + * - SUCCESS: PKA registers are de-initialized + * - ERROR: PKA registers are not de-initialized + */ +ErrorStatus LL_PKA_DeInit(const PKA_TypeDef *PKAx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_PKA_ALL_INSTANCE(PKAx)); + + if (PKAx == PKA) + { + /* Force PKA reset */ + LL_AHB3_GRP1_ForceReset(LL_AHB3_GRP1_PERIPH_PKA); + + /* Release PKA reset */ + LL_AHB3_GRP1_ReleaseReset(LL_AHB3_GRP1_PERIPH_PKA); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize PKA registers according to the specified parameters in PKA_InitStruct. + * @param PKAx PKA Instance. + * @param PKA_InitStruct pointer to a @ref LL_PKA_InitTypeDef structure + * that contains the configuration information for the specified PKA peripheral. + * @retval ErrorStatus + * - SUCCESS: PKA registers are initialized according to PKA_InitStruct content + * - ERROR: Not applicable + */ +ErrorStatus LL_PKA_Init(PKA_TypeDef *PKAx, LL_PKA_InitTypeDef *PKA_InitStruct) +{ + assert_param(IS_PKA_ALL_INSTANCE(PKAx)); + assert_param(IS_LL_PKA_MODE(PKA_InitStruct->Mode)); + + LL_PKA_Config(PKAx, PKA_InitStruct->Mode); + + return (SUCCESS); +} + +/** + * @brief Set each @ref LL_PKA_InitTypeDef field to default value. + * @param PKA_InitStruct pointer to a @ref LL_PKA_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ + +void LL_PKA_StructInit(LL_PKA_InitTypeDef *PKA_InitStruct) +{ + /* Reset PKA init structure parameters values */ + PKA_InitStruct->Mode = LL_PKA_MODE_MODULAR_EXP; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined (PKA) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pwr.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pwr.c index 12e283549..ae7c56e10 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pwr.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_pwr.c @@ -1,83 +1,82 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_pwr.c - * @author MCD Application Team - * @brief PWR LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -#if defined (USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_pwr.h" - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (PWR) - -/** @defgroup PWR_LL PWR - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup PWR_LL_Exported_Functions - * @{ - */ - -/** @addtogroup PWR_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the PWR registers to their default reset values. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: PWR registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_PWR_DeInit(void) -{ - /* Clear PWR low power flags */ - LL_PWR_ClearFlag_STOP_SB(); - - /* Clear PWR wake up flags */ - LL_PWR_ClearFlag_WU(); - - return SUCCESS; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* defined (PWR) */ -/** - * @} - */ - -#endif /* defined (USE_FULL_LL_DRIVER) */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_pwr.c + * @author MCD Application Team + * @brief PWR LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +#if defined (USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_pwr.h" + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (PWR) + +/** @defgroup PWR_LL PWR + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup PWR_LL_Exported_Functions + * @{ + */ + +/** @addtogroup PWR_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the PWR registers to their default reset values. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: PWR registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_PWR_DeInit(void) +{ + /* Clear PWR low power flags */ + LL_PWR_ClearFlag_STOP_SB(); + + /* Clear PWR wake up flags */ + LL_PWR_ClearFlag_WU(); + + return SUCCESS; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (PWR) */ +/** + * @} + */ + +#endif /* defined (USE_FULL_LL_DRIVER) */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_rtc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_rtc.c index ae75f7ffa..8ec75f36a 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_rtc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_rtc.c @@ -1,850 +1,849 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_rtc.c - * @author MCD Application Team - * @brief RTC LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_rtc.h" -#include "stm32h7rsxx_ll_cortex.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined(RTC) - -/** @addtogroup RTC_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup RTC_LL_Private_Constants - * @{ - */ -/* Default values used for prescaler */ -#define RTC_ASYNCH_PRESC_DEFAULT ((uint32_t) 0x0000007FU) -#define RTC_SYNCH_PRESC_DEFAULT ((uint32_t) 0x000000FFU) - -/* Values used for timeout */ -#define RTC_INITMODE_TIMEOUT ((uint32_t) 1000U) /* 1s when tick set to 1ms */ -#define RTC_SYNCHRO_TIMEOUT ((uint32_t) 1000U) /* 1s when tick set to 1ms */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup RTC_LL_Private_Macros - * @{ - */ - -#define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \ - || ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM)) - -#define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU) - -#define IS_LL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU) - -#define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \ - || ((__VALUE__) == LL_RTC_FORMAT_BCD)) - -#define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \ - || ((__VALUE__) == LL_RTC_TIME_FORMAT_PM)) - -#define IS_LL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U)) -#define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) -#define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) -#define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) - -#define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \ - || ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \ - || ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \ - || ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \ - || ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \ - || ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \ - || ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY)) - -#define IS_LL_RTC_DAY(__DAY__) (((__DAY__) >= (uint32_t)1U) && ((__DAY__) <= (uint32_t)31U)) - -#define IS_LL_RTC_MONTH(__MONTH__) (((__MONTH__) >= 1U) && ((__MONTH__) <= 12U)) - -#define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U) - -#define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \ - || ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \ - || ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \ - || ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \ - || ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \ - || ((__VALUE__) == LL_RTC_ALMA_MASK_ALL)) - -#define IS_LL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMB_MASK_NONE) \ - || ((__VALUE__) == LL_RTC_ALMB_MASK_DATEWEEKDAY) \ - || ((__VALUE__) == LL_RTC_ALMB_MASK_HOURS) \ - || ((__VALUE__) == LL_RTC_ALMB_MASK_MINUTES) \ - || ((__VALUE__) == LL_RTC_ALMB_MASK_SECONDS) \ - || ((__VALUE__) == LL_RTC_ALMB_MASK_ALL)) - - -#define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \ - ((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY)) - -#define IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \ - ((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY)) - - -/** - * @} - */ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup RTC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup RTC_LL_EF_Init - * @{ - */ - -/** - * @brief De-Initializes the RTC registers to their default reset values. - * @note This function does not reset the RTC Clock source and RTC Backup Data - * registers. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC registers are de-initialized - * - ERROR: RTC registers are not de-initialized - */ -ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx) -{ - ErrorStatus status = ERROR; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Set Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - WRITE_REG(RTCx->TR, 0U); - WRITE_REG(RTCx->DR, (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); - WRITE_REG(RTCx->CR, 0U); - WRITE_REG(RTCx->WUTR, RTC_WUTR_WUT); - WRITE_REG(RTCx->PRER, (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT)); - WRITE_REG(RTCx->ALRMAR, 0U); - WRITE_REG(RTCx->ALRMBR, 0U); - WRITE_REG(RTCx->SHIFTR, 0U); - WRITE_REG(RTCx->CALR, 0U); - WRITE_REG(RTCx->ALRMASSR, 0U); - WRITE_REG(RTCx->ALRMBSSR, 0U); - WRITE_REG(RTCx->PRIVCFGR, 0U); - - /* Clear some bits of RTC_ICSR and exit Initialization mode */ - CLEAR_BIT(RTCx->ICSR, RTC_ICSR_BCDU_Msk | RTC_ICSR_BIN_Msk | RTC_ICSR_INIT); - - /* Wait till the RTC RSF flag is set */ - status = LL_RTC_WaitForSynchro(RTCx); - } - - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - /* DeInitialization of the TAMP registers */ - WRITE_REG(TAMP->CR1, 0U); - WRITE_REG(TAMP->CR2, 0U); - WRITE_REG(TAMP->CR3, 0U); - WRITE_REG(TAMP->CFGR, 0U); - WRITE_REG(TAMP->PRIVCFGR, 0U); - WRITE_REG(TAMP->FLTCR, 0U); - WRITE_REG(TAMP->ATCR1, 0x00070000U); - WRITE_REG(TAMP->ATCR2, 0U); - WRITE_REG(TAMP->IER, 0U); - WRITE_REG(TAMP->SCR, 0xFFFFFFFFU); - - return status; -} - -/** - * @brief Initializes the RTC registers according to the specified parameters - * in RTC_InitStruct. - * @param RTCx RTC Instance - * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains - * the configuration information for the RTC peripheral. - * @note The RTC Prescaler register is write protected and can be written in - * initialization mode only. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC registers are initialized - * - ERROR: RTC registers are not initialized - */ -ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat)); - assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); - assert_param(IS_LL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler)); - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Set Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - /* Set Hour Format */ - LL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat); - - /* Configure Synchronous and Asynchronous prescaler factor */ - LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler); - LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); - - /* Exit Initialization mode */ - LL_RTC_DisableInitMode(RTCx); - - status = SUCCESS; - } - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - return status; -} - -/** - * @brief Set each @ref LL_RTC_InitTypeDef field to default value. - * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct) -{ - /* Set RTC_InitStruct fields to default values */ - RTC_InitStruct->HourFormat = LL_RTC_HOURFORMAT_24HOUR; - RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; - RTC_InitStruct->SynchPrescaler = RTC_SYNCH_PRESC_DEFAULT; -} - -/** - * @brief Set the RTC current time. - * @param RTCx RTC Instance - * @param RTC_Format This parameter can be one of the following values: - * @arg @ref LL_RTC_FORMAT_BIN - * @arg @ref LL_RTC_FORMAT_BCD - * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains - * the time configuration information for the RTC. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC Time register is configured - * - ERROR: RTC Time register is not configured - */ -ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_FORMAT(RTC_Format)); - - if (RTC_Format == LL_RTC_FORMAT_BIN) - { - if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) - { - assert_param(IS_LL_RTC_HOUR12(RTC_TimeStruct->Hours)); - assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); - } - else - { - RTC_TimeStruct->TimeFormat = 0x00U; - assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours)); - } - assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes)); - assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds)); - } - else - { - if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) - { - assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); - assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); - } - else - { - RTC_TimeStruct->TimeFormat = 0U; - assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); - } - assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); - assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); - } - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Set Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - /* Check the input parameters format */ - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours, - RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds); - } - else - { - LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours), - __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes), - __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds)); - } - - /* Exit Initialization mode */ - LL_RTC_DisableInitMode(RTCx); - - /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ - if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) - { - status = LL_RTC_WaitForSynchro(RTCx); - } - else - { - status = SUCCESS; - } - } - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - return status; -} - -/** - * @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). - * @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct) -{ - /* Time = 00h:00min:00sec */ - RTC_TimeStruct->TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24; - RTC_TimeStruct->Hours = 0U; - RTC_TimeStruct->Minutes = 0U; - RTC_TimeStruct->Seconds = 0U; -} - -/** - * @brief Set the RTC current date. - * @param RTCx RTC Instance - * @param RTC_Format This parameter can be one of the following values: - * @arg @ref LL_RTC_FORMAT_BIN - * @arg @ref LL_RTC_FORMAT_BCD - * @param RTC_DateStruct: pointer to a RTC_DateTypeDef structure that contains - * the date configuration information for the RTC. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC Day register is configured - * - ERROR: RTC Day register is not configured - */ -ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_FORMAT(RTC_Format)); - - if ((RTC_Format == LL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U)) - { - RTC_DateStruct->Month = (uint8_t)((uint32_t) RTC_DateStruct->Month & (uint32_t)~(0x10U)) + 0x0AU; - } - if (RTC_Format == LL_RTC_FORMAT_BIN) - { - assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year)); - assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month)); - assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day)); - } - else - { - assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year))); - assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month))); - assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day))); - } - assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay)); - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Set Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - /* Check the input parameters format */ - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, - RTC_DateStruct->Year); - } - else - { - LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day), - __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), - __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); - } - - /* Exit Initialization mode */ - LL_RTC_DisableInitMode(RTCx); - - /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ - if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) - { - status = LL_RTC_WaitForSynchro(RTCx); - } - else - { - status = SUCCESS; - } - } - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - return status; -} - -/** - * @brief Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00) - * @param RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct) -{ - /* Monday, January 01 xx00 */ - RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY; - RTC_DateStruct->Day = 1U; - RTC_DateStruct->Month = LL_RTC_MONTH_JANUARY; - RTC_DateStruct->Year = 0U; -} - -/** - * @brief Set the RTC Alarm A. - * @note The Alarm register can only be written when the corresponding Alarm - * is disabled (Use @ref LL_RTC_ALMA_Disable function). - * @param RTCx RTC Instance - * @param RTC_Format This parameter can be one of the following values: - * @arg @ref LL_RTC_FORMAT_BIN - * @arg @ref LL_RTC_FORMAT_BCD - * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that - * contains the alarm configuration parameters. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ALARMA registers are configured - * - ERROR: ALARMA registers are not configured - */ -ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) -{ - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_FORMAT(RTC_Format)); - assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask)); - assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); - - if (RTC_Format == LL_RTC_FORMAT_BIN) - { - if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) - { - assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); - assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); - } - else - { - RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; - assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); - } - assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); - assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); - - if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) - { - assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); - } - else - { - assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); - } - } - else - { - if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) - { - assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); - assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); - } - else - { - RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; - assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); - } - - assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); - assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); - - if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) - { - assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); - } - else - { - assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); - } - } - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Select weekday selection */ - if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) - { - /* Set the date for ALARM */ - LL_RTC_ALMA_DisableWeekday(RTCx); - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - LL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); - } - else - { - LL_RTC_ALMA_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); - } - } - else - { - /* Set the week day for ALARM */ - LL_RTC_ALMA_EnableWeekday(RTCx); - LL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); - } - - /* Configure the Alarm register */ - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, - RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); - } - else - { - LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, - __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), - __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), - __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); - } - /* Set ALARM mask */ - LL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); - - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - return SUCCESS; -} - -/** - * @brief Set the RTC Alarm B. - * @note The Alarm register can only be written when the corresponding Alarm - * is disabled (@ref LL_RTC_ALMB_Disable function). - * @param RTCx RTC Instance - * @param RTC_Format This parameter can be one of the following values: - * @arg @ref LL_RTC_FORMAT_BIN - * @arg @ref LL_RTC_FORMAT_BCD - * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that - * contains the alarm configuration parameters. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ALARMB registers are configured - * - ERROR: ALARMB registers are not configured - */ -ErrorStatus LL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) -{ - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_FORMAT(RTC_Format)); - assert_param(IS_LL_RTC_ALMB_MASK(RTC_AlarmStruct->AlarmMask)); - assert_param(IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); - - if (RTC_Format == LL_RTC_FORMAT_BIN) - { - if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) - { - assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); - assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); - } - else - { - RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; - assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); - } - assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); - assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); - - if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) - { - assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); - } - else - { - assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); - } - } - else - { - if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) - { - assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); - assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); - } - else - { - RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; - assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); - } - - assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); - assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); - - if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) - { - assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); - } - else - { - assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); - } - } - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Select weekday selection */ - if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) - { - /* Set the date for ALARM */ - LL_RTC_ALMB_DisableWeekday(RTCx); - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - LL_RTC_ALMB_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); - } - else - { - LL_RTC_ALMB_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); - } - } - else - { - /* Set the week day for ALARM */ - LL_RTC_ALMB_EnableWeekday(RTCx); - LL_RTC_ALMB_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); - } - - /* Configure the Alarm register */ - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, - RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); - } - else - { - LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, - __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), - __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), - __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); - } - /* Set ALARM mask */ - LL_RTC_ALMB_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); - - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - return SUCCESS; -} - -/** - * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / - * Day = 1st day of the month/Mask = all fields are masked). - * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) -{ - /* Alarm Time Settings : Time = 00h:00mn:00sec */ - RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMA_TIME_FORMAT_AM; - RTC_AlarmStruct->AlarmTime.Hours = 0U; - RTC_AlarmStruct->AlarmTime.Minutes = 0U; - RTC_AlarmStruct->AlarmTime.Seconds = 0U; - - /* Alarm Day Settings : Day = 1st day of the month */ - RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE; - RTC_AlarmStruct->AlarmDateWeekDay = 1U; - - /* Alarm Masks Settings : Mask = all fields are not masked */ - RTC_AlarmStruct->AlarmMask = LL_RTC_ALMA_MASK_NONE; -} - -/** - * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / - * Day = 1st day of the month/Mask = all fields are masked). - * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_ALMB_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) -{ - /* Alarm Time Settings : Time = 00h:00mn:00sec */ - RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMB_TIME_FORMAT_AM; - RTC_AlarmStruct->AlarmTime.Hours = 0U; - RTC_AlarmStruct->AlarmTime.Minutes = 0U; - RTC_AlarmStruct->AlarmTime.Seconds = 0U; - - /* Alarm Day Settings : Day = 1st day of the month */ - RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMB_DATEWEEKDAYSEL_DATE; - RTC_AlarmStruct->AlarmDateWeekDay = 1U; - - /* Alarm Masks Settings : Mask = all fields are not masked */ - RTC_AlarmStruct->AlarmMask = LL_RTC_ALMB_MASK_NONE; -} - -/** - * @brief Enters the RTC Initialization mode. - * @note The RTC Initialization mode is write protected, use the - * @ref LL_RTC_DisableWriteProtection before calling this function. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC is in Init mode - * - ERROR: RTC is not in Init mode - */ -ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx) -{ - __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; - ErrorStatus status = SUCCESS; - uint32_t tmp; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Check if the Initialization mode is set */ - if (LL_RTC_IsActiveFlag_INIT(RTCx) == 0U) - { - /* Set the Initialization mode */ - LL_RTC_EnableInitMode(RTCx); - - /* Wait till RTC is in INIT state and if Time out is reached exit */ - tmp = LL_RTC_IsActiveFlag_INIT(RTCx); - while ((timeout != 0U) && (tmp != 1U)) - { - if (LL_SYSTICK_IsActiveCounterFlag() == 1U) - { - timeout --; - } - tmp = LL_RTC_IsActiveFlag_INIT(RTCx); - if (timeout == 0U) - { - status = ERROR; - } - } - } - return status; -} - -/** - * @brief Exit the RTC Initialization mode. - * @note When the initialization sequence is complete, the calendar restarts - * counting after 4 RTCCLK cycles. - * @note The RTC Initialization mode is write protected, use the - * @ref LL_RTC_DisableWriteProtection before calling this function. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC exited from in Init mode - * - ERROR: Not applicable - */ -ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx) -{ - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Disable initialization mode */ - LL_RTC_DisableInitMode(RTCx); - - return SUCCESS; -} - -/** - * @brief Waits until the RTC Time and Day registers (RTC_TR and RTC_DR) are - * synchronized with RTC APB clock. - * @note The RTC Resynchronization mode is write protected, use the - * @ref LL_RTC_DisableWriteProtection 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 RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC registers are synchronised - * - ERROR: RTC registers are not synchronised - */ -ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) -{ - __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; - uint32_t tmp; - ErrorStatus status = SUCCESS; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Clear RSF flag */ - LL_RTC_ClearFlag_RS(RTCx); - - /* Wait the registers to be synchronised */ - tmp = LL_RTC_IsActiveFlag_RS(RTCx); - while ((timeout != 0U) && (tmp != 1U)) - { - if (LL_SYSTICK_IsActiveCounterFlag() == 1U) - { - timeout--; - } - tmp = LL_RTC_IsActiveFlag_RS(RTCx); - } - - if (timeout == 0U) - { - status = ERROR; - } - - return status; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined(RTC) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_rtc.c + * @author MCD Application Team + * @brief RTC LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_rtc.h" +#include "stm32h7rsxx_ll_cortex.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined(RTC) + +/** @addtogroup RTC_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup RTC_LL_Private_Constants + * @{ + */ +/* Default values used for prescaler */ +#define RTC_ASYNCH_PRESC_DEFAULT ((uint32_t) 0x0000007FU) +#define RTC_SYNCH_PRESC_DEFAULT ((uint32_t) 0x000000FFU) + +/* Values used for timeout */ +#define RTC_INITMODE_TIMEOUT ((uint32_t) 1000U) /* 1s when tick set to 1ms */ +#define RTC_SYNCHRO_TIMEOUT ((uint32_t) 1000U) /* 1s when tick set to 1ms */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup RTC_LL_Private_Macros + * @{ + */ + +#define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \ + || ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM)) + +#define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU) + +#define IS_LL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU) + +#define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \ + || ((__VALUE__) == LL_RTC_FORMAT_BCD)) + +#define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \ + || ((__VALUE__) == LL_RTC_TIME_FORMAT_PM)) + +#define IS_LL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U)) +#define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) +#define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) +#define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) + +#define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \ + || ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \ + || ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \ + || ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \ + || ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \ + || ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \ + || ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY)) + +#define IS_LL_RTC_DAY(__DAY__) (((__DAY__) >= (uint32_t)1U) && ((__DAY__) <= (uint32_t)31U)) + +#define IS_LL_RTC_MONTH(__MONTH__) (((__MONTH__) >= 1U) && ((__MONTH__) <= 12U)) + +#define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U) + +#define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \ + || ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \ + || ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \ + || ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \ + || ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \ + || ((__VALUE__) == LL_RTC_ALMA_MASK_ALL)) + +#define IS_LL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMB_MASK_NONE) \ + || ((__VALUE__) == LL_RTC_ALMB_MASK_DATEWEEKDAY) \ + || ((__VALUE__) == LL_RTC_ALMB_MASK_HOURS) \ + || ((__VALUE__) == LL_RTC_ALMB_MASK_MINUTES) \ + || ((__VALUE__) == LL_RTC_ALMB_MASK_SECONDS) \ + || ((__VALUE__) == LL_RTC_ALMB_MASK_ALL)) + + +#define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \ + ((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY)) + +#define IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \ + ((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY)) + + +/** + * @} + */ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup RTC_LL_Exported_Functions + * @{ + */ + +/** @addtogroup RTC_LL_EF_Init + * @{ + */ + +/** + * @brief De-Initializes the RTC registers to their default reset values. + * @note This function does not reset the RTC Clock source and RTC Backup Data + * registers. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC registers are de-initialized + * - ERROR: RTC registers are not de-initialized + */ +ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx) +{ + ErrorStatus status = ERROR; + + /* Check the parameter */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Disable the write protection for RTC registers */ + LL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (LL_RTC_EnterInitMode(RTCx) != ERROR) + { + WRITE_REG(RTCx->TR, 0U); + WRITE_REG(RTCx->DR, (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); + WRITE_REG(RTCx->CR, 0U); + WRITE_REG(RTCx->WUTR, RTC_WUTR_WUT); + WRITE_REG(RTCx->PRER, (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT)); + WRITE_REG(RTCx->ALRMAR, 0U); + WRITE_REG(RTCx->ALRMBR, 0U); + WRITE_REG(RTCx->SHIFTR, 0U); + WRITE_REG(RTCx->CALR, 0U); + WRITE_REG(RTCx->ALRMASSR, 0U); + WRITE_REG(RTCx->ALRMBSSR, 0U); + WRITE_REG(RTCx->PRIVCFGR, 0U); + + /* Clear some bits of RTC_ICSR and exit Initialization mode */ + CLEAR_BIT(RTCx->ICSR, RTC_ICSR_BCDU_Msk | RTC_ICSR_BIN_Msk | RTC_ICSR_INIT); + + /* Wait till the RTC RSF flag is set */ + status = LL_RTC_WaitForSynchro(RTCx); + } + + /* Enable the write protection for RTC registers */ + LL_RTC_EnableWriteProtection(RTCx); + + /* DeInitialization of the TAMP registers */ + WRITE_REG(TAMP->CR1, 0U); + WRITE_REG(TAMP->CR2, 0U); + WRITE_REG(TAMP->CR3, 0U); + WRITE_REG(TAMP->CFGR, 0U); + WRITE_REG(TAMP->PRIVCFGR, 0U); + WRITE_REG(TAMP->FLTCR, 0U); + WRITE_REG(TAMP->ATCR1, 0x00070000U); + WRITE_REG(TAMP->ATCR2, 0U); + WRITE_REG(TAMP->IER, 0U); + WRITE_REG(TAMP->SCR, 0xFFFFFFFFU); + + return status; +} + +/** + * @brief Initializes the RTC registers according to the specified parameters + * in RTC_InitStruct. + * @param RTCx RTC Instance + * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains + * the configuration information for the RTC peripheral. + * @note The RTC Prescaler register is write protected and can be written in + * initialization mode only. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC registers are initialized + * - ERROR: RTC registers are not initialized + */ +ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + assert_param(IS_LL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat)); + assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); + assert_param(IS_LL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler)); + + /* Disable the write protection for RTC registers */ + LL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (LL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Set Hour Format */ + LL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat); + + /* Configure Synchronous and Asynchronous prescaler factor */ + LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler); + LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); + + /* Exit Initialization mode */ + LL_RTC_DisableInitMode(RTCx); + + status = SUCCESS; + } + /* Enable the write protection for RTC registers */ + LL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Set each @ref LL_RTC_InitTypeDef field to default value. + * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized. + * @retval None + */ +void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct) +{ + /* Set RTC_InitStruct fields to default values */ + RTC_InitStruct->HourFormat = LL_RTC_HOURFORMAT_24HOUR; + RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; + RTC_InitStruct->SynchPrescaler = RTC_SYNCH_PRESC_DEFAULT; +} + +/** + * @brief Set the RTC current time. + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref LL_RTC_FORMAT_BIN + * @arg @ref LL_RTC_FORMAT_BCD + * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains + * the time configuration information for the RTC. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC Time register is configured + * - ERROR: RTC Time register is not configured + */ +ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + assert_param(IS_LL_RTC_FORMAT(RTC_Format)); + + if (RTC_Format == LL_RTC_FORMAT_BIN) + { + if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) + { + assert_param(IS_LL_RTC_HOUR12(RTC_TimeStruct->Hours)); + assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); + } + else + { + RTC_TimeStruct->TimeFormat = 0x00U; + assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours)); + } + assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes)); + assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds)); + } + else + { + if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) + { + assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); + assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); + } + else + { + RTC_TimeStruct->TimeFormat = 0U; + assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); + } + assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); + assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); + } + + /* Disable the write protection for RTC registers */ + LL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (LL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Check the input parameters format */ + if (RTC_Format != LL_RTC_FORMAT_BIN) + { + LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours, + RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds); + } + else + { + LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours), + __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes), + __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds)); + } + + /* Exit Initialization mode */ + LL_RTC_DisableInitMode(RTCx); + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) + { + status = LL_RTC_WaitForSynchro(RTCx); + } + else + { + status = SUCCESS; + } + } + /* Enable the write protection for RTC registers */ + LL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). + * @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized. + * @retval None + */ +void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct) +{ + /* Time = 00h:00min:00sec */ + RTC_TimeStruct->TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24; + RTC_TimeStruct->Hours = 0U; + RTC_TimeStruct->Minutes = 0U; + RTC_TimeStruct->Seconds = 0U; +} + +/** + * @brief Set the RTC current date. + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref LL_RTC_FORMAT_BIN + * @arg @ref LL_RTC_FORMAT_BCD + * @param RTC_DateStruct: pointer to a RTC_DateTypeDef structure that contains + * the date configuration information for the RTC. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC Day register is configured + * - ERROR: RTC Day register is not configured + */ +ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + assert_param(IS_LL_RTC_FORMAT(RTC_Format)); + + if ((RTC_Format == LL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U)) + { + RTC_DateStruct->Month = (uint8_t)((uint32_t) RTC_DateStruct->Month & (uint32_t)~(0x10U)) + 0x0AU; + } + if (RTC_Format == LL_RTC_FORMAT_BIN) + { + assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year)); + assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month)); + assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day)); + } + else + { + assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year))); + assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month))); + assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day))); + } + assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay)); + + /* Disable the write protection for RTC registers */ + LL_RTC_DisableWriteProtection(RTCx); + + /* Set Initialization mode */ + if (LL_RTC_EnterInitMode(RTCx) != ERROR) + { + /* Check the input parameters format */ + if (RTC_Format != LL_RTC_FORMAT_BIN) + { + LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, + RTC_DateStruct->Year); + } + else + { + LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day), + __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), + __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); + } + + /* Exit Initialization mode */ + LL_RTC_DisableInitMode(RTCx); + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) + { + status = LL_RTC_WaitForSynchro(RTCx); + } + else + { + status = SUCCESS; + } + } + /* Enable the write protection for RTC registers */ + LL_RTC_EnableWriteProtection(RTCx); + + return status; +} + +/** + * @brief Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00) + * @param RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized. + * @retval None + */ +void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct) +{ + /* Monday, January 01 xx00 */ + RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY; + RTC_DateStruct->Day = 1U; + RTC_DateStruct->Month = LL_RTC_MONTH_JANUARY; + RTC_DateStruct->Year = 0U; +} + +/** + * @brief Set the RTC Alarm A. + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (Use @ref LL_RTC_ALMA_Disable function). + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref LL_RTC_FORMAT_BIN + * @arg @ref LL_RTC_FORMAT_BCD + * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that + * contains the alarm configuration parameters. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ALARMA registers are configured + * - ERROR: ALARMA registers are not configured + */ +ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + assert_param(IS_LL_RTC_FORMAT(RTC_Format)); + assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask)); + assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); + + if (RTC_Format == LL_RTC_FORMAT_BIN) + { + if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) + { + assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); + assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); + } + assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); + assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) + { + assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + else + { + assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) + { + assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + } + + assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); + assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) + { + assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + else + { + assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + } + + /* Disable the write protection for RTC registers */ + LL_RTC_DisableWriteProtection(RTCx); + + /* Select weekday selection */ + if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) + { + /* Set the date for ALARM */ + LL_RTC_ALMA_DisableWeekday(RTCx); + if (RTC_Format != LL_RTC_FORMAT_BIN) + { + LL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + else + { + LL_RTC_ALMA_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + /* Set the week day for ALARM */ + LL_RTC_ALMA_EnableWeekday(RTCx); + LL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + + /* Configure the Alarm register */ + if (RTC_Format != LL_RTC_FORMAT_BIN) + { + LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, + RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); + } + else + { + LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, + __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), + __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), + __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); + } + /* Set ALARM mask */ + LL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); + + /* Enable the write protection for RTC registers */ + LL_RTC_EnableWriteProtection(RTCx); + + return SUCCESS; +} + +/** + * @brief Set the RTC Alarm B. + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (@ref LL_RTC_ALMB_Disable function). + * @param RTCx RTC Instance + * @param RTC_Format This parameter can be one of the following values: + * @arg @ref LL_RTC_FORMAT_BIN + * @arg @ref LL_RTC_FORMAT_BCD + * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that + * contains the alarm configuration parameters. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ALARMB registers are configured + * - ERROR: ALARMB registers are not configured + */ +ErrorStatus LL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + assert_param(IS_LL_RTC_FORMAT(RTC_Format)); + assert_param(IS_LL_RTC_ALMB_MASK(RTC_AlarmStruct->AlarmMask)); + assert_param(IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); + + if (RTC_Format == LL_RTC_FORMAT_BIN) + { + if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) + { + assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); + assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); + } + assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); + assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) + { + assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + else + { + assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) + { + assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); + } + else + { + RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; + assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); + } + + assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); + assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); + + if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) + { + assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + else + { + assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); + } + } + + /* Disable the write protection for RTC registers */ + LL_RTC_DisableWriteProtection(RTCx); + + /* Select weekday selection */ + if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) + { + /* Set the date for ALARM */ + LL_RTC_ALMB_DisableWeekday(RTCx); + if (RTC_Format != LL_RTC_FORMAT_BIN) + { + LL_RTC_ALMB_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + else + { + LL_RTC_ALMB_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); + } + } + else + { + /* Set the week day for ALARM */ + LL_RTC_ALMB_EnableWeekday(RTCx); + LL_RTC_ALMB_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); + } + + /* Configure the Alarm register */ + if (RTC_Format != LL_RTC_FORMAT_BIN) + { + LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, + RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); + } + else + { + LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, + __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), + __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), + __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); + } + /* Set ALARM mask */ + LL_RTC_ALMB_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); + + /* Enable the write protection for RTC registers */ + LL_RTC_EnableWriteProtection(RTCx); + + return SUCCESS; +} + +/** + * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / + * Day = 1st day of the month/Mask = all fields are masked). + * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. + * @retval None + */ +void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Alarm Time Settings : Time = 00h:00mn:00sec */ + RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMA_TIME_FORMAT_AM; + RTC_AlarmStruct->AlarmTime.Hours = 0U; + RTC_AlarmStruct->AlarmTime.Minutes = 0U; + RTC_AlarmStruct->AlarmTime.Seconds = 0U; + + /* Alarm Day Settings : Day = 1st day of the month */ + RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE; + RTC_AlarmStruct->AlarmDateWeekDay = 1U; + + /* Alarm Masks Settings : Mask = all fields are not masked */ + RTC_AlarmStruct->AlarmMask = LL_RTC_ALMA_MASK_NONE; +} + +/** + * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / + * Day = 1st day of the month/Mask = all fields are masked). + * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. + * @retval None + */ +void LL_RTC_ALMB_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) +{ + /* Alarm Time Settings : Time = 00h:00mn:00sec */ + RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMB_TIME_FORMAT_AM; + RTC_AlarmStruct->AlarmTime.Hours = 0U; + RTC_AlarmStruct->AlarmTime.Minutes = 0U; + RTC_AlarmStruct->AlarmTime.Seconds = 0U; + + /* Alarm Day Settings : Day = 1st day of the month */ + RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMB_DATEWEEKDAYSEL_DATE; + RTC_AlarmStruct->AlarmDateWeekDay = 1U; + + /* Alarm Masks Settings : Mask = all fields are not masked */ + RTC_AlarmStruct->AlarmMask = LL_RTC_ALMB_MASK_NONE; +} + +/** + * @brief Enters the RTC Initialization mode. + * @note The RTC Initialization mode is write protected, use the + * @ref LL_RTC_DisableWriteProtection before calling this function. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC is in Init mode + * - ERROR: RTC is not in Init mode + */ +ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx) +{ + __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; + ErrorStatus status = SUCCESS; + uint32_t tmp; + + /* Check the parameter */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Check if the Initialization mode is set */ + if (LL_RTC_IsActiveFlag_INIT(RTCx) == 0U) + { + /* Set the Initialization mode */ + LL_RTC_EnableInitMode(RTCx); + + /* Wait till RTC is in INIT state and if Time out is reached exit */ + tmp = LL_RTC_IsActiveFlag_INIT(RTCx); + while ((timeout != 0U) && (tmp != 1U)) + { + if (LL_SYSTICK_IsActiveCounterFlag() == 1U) + { + timeout --; + } + tmp = LL_RTC_IsActiveFlag_INIT(RTCx); + if (timeout == 0U) + { + status = ERROR; + } + } + } + return status; +} + +/** + * @brief Exit the RTC Initialization mode. + * @note When the initialization sequence is complete, the calendar restarts + * counting after 4 RTCCLK cycles. + * @note The RTC Initialization mode is write protected, use the + * @ref LL_RTC_DisableWriteProtection before calling this function. + * @param RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC exited from in Init mode + * - ERROR: Not applicable + */ +ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx) +{ + /* Check the parameter */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Disable initialization mode */ + LL_RTC_DisableInitMode(RTCx); + + return SUCCESS; +} + +/** + * @brief Waits until the RTC Time and Day registers (RTC_TR and RTC_DR) are + * synchronized with RTC APB clock. + * @note The RTC Resynchronization mode is write protected, use the + * @ref LL_RTC_DisableWriteProtection 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 RTCx RTC Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: RTC registers are synchronised + * - ERROR: RTC registers are not synchronised + */ +ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) +{ + __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; + uint32_t tmp; + ErrorStatus status = SUCCESS; + + /* Check the parameter */ + assert_param(IS_RTC_ALL_INSTANCE(RTCx)); + + /* Clear RSF flag */ + LL_RTC_ClearFlag_RS(RTCx); + + /* Wait the registers to be synchronised */ + tmp = LL_RTC_IsActiveFlag_RS(RTCx); + while ((timeout != 0U) && (tmp != 1U)) + { + if (LL_SYSTICK_IsActiveCounterFlag() == 1U) + { + timeout--; + } + tmp = LL_RTC_IsActiveFlag_RS(RTCx); + } + + if (timeout == 0U) + { + status = ERROR; + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(RTC) */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_sdmmc.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_sdmmc.c index 4b1850872..28a3e1d55 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_sdmmc.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_sdmmc.c @@ -1,1907 +1,1907 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_sdmmc.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### SDMMC peripheral features ##### - ============================================================================== - [..] The SD/SDMMC MMC card host interface (SDMMC) provides an interface between the AHB - peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDMMC cards and CE-ATA - devices. - - [..] The SDMMC features include the following: - (+) Full compliance with MultiMediaCard System Specification Version 4.51. Card support - for three different databus modes: 1-bit (default), 4-bit and 8-bit. - (+) Full compatibility with previous versions of MultiMediaCards (backward compatibility). - (+) Full compliance with SD memory card specifications version 4.1. - (SDR104 SDMMC_CK speed limited to maximum allowed IO speed, SPI mode and - UHS-II mode not supported). - (+) Full compliance with SDIO card specification version 4.0. Card support - for two different databus modes: 1-bit (default) and 4-bit. - (SDR104 SDMMC_CK speed limited to maximum allowed IO speed, SPI mode and - UHS-II mode not supported). - (+) Data transfer up to 208 Mbyte/s for the 8 bit mode. (depending maximum allowed IO speed). - (+) 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 SDMMC peripheral. - According to the device used (SD card/ MMC card / SDMMC card ...), a set of APIs - is used in the device's driver to perform SDMMC 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 SDMMC clock is coming from output of PLL1_Q or PLL2_R. - Before start working with SDMMC peripheral make sure that the PLL is well configured. - The SDMMC peripheral uses two clock signals: - (++) PLL1_Q bus clock (default after reset) - (++) PLL2_R bus clock - - (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDMMC - peripheral. - - (+) Enable the Power ON State using the SDMMC_PowerState_ON(SDMMCx) - function and disable it using the function SDMMC_PowerState_OFF(SDMMCx). - - (+) Enable/Disable the peripheral interrupts using the macros __SDMMC_ENABLE_IT(hSDMMC, IT) - and __SDMMC_DISABLE_IT(hSDMMC, IT) if you need to use interrupt mode. - - (+) When using the DMA mode - (++) Configure the IDMA mode (Single buffer or double) - (++) Configure the buffer address - (++) Configure Data Path State Machine - - (+) To control the CPSM (Command Path State Machine) and send - commands to the card use the SDMMC_SendCommand(SDMMCx), - SDMMC_GetCommandResponse() and SDMMC_GetResponse() functions. First, user has - to fill the command structure (pointer to SDMMC_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 SDMMC_CMDRESP - register using the SDMMC_GetCommandResponse(). - The SDMMC responses registers (SDMMC_RESP1 to SDMMC_RESP2), use the - SDMMC_GetResponse() function. - - (+) To control the DPSM (Data Path State Machine) and send/receive - data to/from the card use the SDMMC_DataConfig(), SDMMC_GetDataCounter(), - SDMMC_ReadFIFO(), SDMMC_WriteFIFO() and SDMMC_GetFIFOCount() functions. - - *** Read Operations *** - ======================= - [..] - (#) First, user has to fill the data structure (pointer to - SDMMC_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 SDMMC) - (++) Data Transfer mode - (++) DPSM Status (Enable or Disable) - - (#) Configure the SDMMC 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 SDMMC flags/interrupts to check the transfer status. - - *** Write Operations *** - ======================== - [..] - (#) First, user has to fill the data structure (pointer to - SDMMC_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 SDMMC resources to send the data to the card according to - selected transfer mode. - - (#) Send the selected Write command. - - (#) Use the SDMMC flags/interrupts to check the transfer status. - - *** Command management operations *** - ===================================== - [..] - (#) The commands used for Read/Write/Erase operations are managed in - separate functions. - Each function allows to send the needed command with the related argument, - then check the response. - By the same approach, you could implement a command and check the response. - - @endverbatim - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_HAL_Driver - * @{ - */ - -/** @defgroup SDMMC_LL SDMMC Low Layer - * @brief Low layer module for SD - * @{ - */ - -#if defined (SDMMC1) || defined (SDMMC2) -#if defined (HAL_SD_MODULE_ENABLED) || defined (HAL_MMC_MODULE_ENABLED) - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -static uint32_t SDMMC_GetCmdError(SDMMC_TypeDef *SDMMCx); - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup SDMMC_LL_Exported_Functions SDMMC Low Layer Exported Functions - * @{ - */ - -/** @defgroup HAL_SDMMC_LL_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 SDMMC according to the specified - * parameters in the SDMMC_InitTypeDef and create the associated handle. - * @param SDMMCx: Pointer to SDMMC register base - * @param Init: SDMMC initialization structure - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_Init(SDMMC_TypeDef *SDMMCx, SDMMC_InitTypeDef Init) -{ - uint32_t tmpreg = 0; - - /* Check the parameters */ - assert_param(IS_SDMMC_ALL_INSTANCE(SDMMCx)); - assert_param(IS_SDMMC_CLOCK_EDGE(Init.ClockEdge)); - assert_param(IS_SDMMC_CLOCK_POWER_SAVE(Init.ClockPowerSave)); - assert_param(IS_SDMMC_BUS_WIDE(Init.BusWide)); - assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(Init.HardwareFlowControl)); - assert_param(IS_SDMMC_CLKDIV(Init.ClockDiv)); - - /* Set SDMMC configuration parameters */ - tmpreg |= (Init.ClockEdge | \ - Init.ClockPowerSave | \ - Init.BusWide | \ - Init.HardwareFlowControl | \ - Init.ClockDiv - ); - - /* Write to SDMMC CLKCR */ - MODIFY_REG(SDMMCx->CLKCR, CLKCR_CLEAR_MASK, tmpreg); - - return HAL_OK; -} - - -/** - * @} - */ - -/** @defgroup HAL_SDMMC_LL_Group2 IO operation functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### I/O operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the SDMMC data - transfers. - -@endverbatim - * @{ - */ - -/** - * @brief Read data (word) from Rx FIFO in blocking mode (polling) - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_ReadFIFO(const SDMMC_TypeDef *SDMMCx) -{ - /* Read data from Rx FIFO */ - return (SDMMCx->FIFO); -} - -/** - * @brief Write data (word) to Tx FIFO in blocking mode (polling) - * @param SDMMCx: Pointer to SDMMC register base - * @param pWriteData: pointer to data to write - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_WriteFIFO(SDMMC_TypeDef *SDMMCx, uint32_t *pWriteData) -{ - /* Write data to FIFO */ - SDMMCx->FIFO = *pWriteData; - - return HAL_OK; -} - -/** - * @} - */ - -/** @defgroup HAL_SDMMC_LL_Group3 Peripheral Control functions - * @brief management functions - * -@verbatim - =============================================================================== - ##### Peripheral Control functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to control the SDMMC data - transfers. - -@endverbatim - * @{ - */ - -/** - * @brief Set SDMMC Power state to ON. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_PowerState_ON(SDMMC_TypeDef *SDMMCx) -{ - /* Set power state to ON */ - SDMMCx->POWER |= SDMMC_POWER_PWRCTRL; - - return HAL_OK; -} - -/** - * @brief Set SDMMC Power state to Power-Cycle. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_PowerState_Cycle(SDMMC_TypeDef *SDMMCx) -{ - /* Set power state to Power Cycle*/ - SDMMCx->POWER |= SDMMC_POWER_PWRCTRL_1; - - return HAL_OK; -} - -/** - * @brief Set SDMMC Power state to OFF. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_PowerState_OFF(SDMMC_TypeDef *SDMMCx) -{ - /* Set power state to OFF */ - SDMMCx->POWER &= ~(SDMMC_POWER_PWRCTRL); - - return HAL_OK; -} - -/** - * @brief Get SDMMC Power state. - * @param SDMMCx: Pointer to SDMMC 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 SDMMC_GetPowerState(const SDMMC_TypeDef *SDMMCx) -{ - return (SDMMCx->POWER & SDMMC_POWER_PWRCTRL); -} - -/** - * @brief Configure the SDMMC command path according to the specified parameters in - * SDMMC_CmdInitTypeDef structure and send the command - * @param SDMMCx: Pointer to SDMMC register base - * @param Command: pointer to a SDMMC_CmdInitTypeDef structure that contains - * the configuration information for the SDMMC command - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_SendCommand(SDMMC_TypeDef *SDMMCx, SDMMC_CmdInitTypeDef *Command) -{ - uint32_t tmpreg = 0; - - /* Check the parameters */ - assert_param(IS_SDMMC_CMD_INDEX(Command->CmdIndex)); - assert_param(IS_SDMMC_RESPONSE(Command->Response)); - assert_param(IS_SDMMC_WAIT(Command->WaitForInterrupt)); - assert_param(IS_SDMMC_CPSM(Command->CPSM)); - - /* Set the SDMMC Argument value */ - SDMMCx->ARG = Command->Argument; - - /* Set SDMMC command parameters */ - tmpreg |= (uint32_t)(Command->CmdIndex | \ - Command->Response | \ - Command->WaitForInterrupt | \ - Command->CPSM); - - /* Write to SDMMC CMD register */ - MODIFY_REG(SDMMCx->CMD, CMD_CLEAR_MASK, tmpreg); - - return HAL_OK; -} - -/** - * @brief Return the command index of last command for which response received - * @param SDMMCx: Pointer to SDMMC register base - * @retval Command index of the last command response received - */ -uint8_t SDMMC_GetCommandResponse(const SDMMC_TypeDef *SDMMCx) -{ - return (uint8_t)(SDMMCx->RESPCMD); -} - - -/** - * @brief Return the response received from the card for the last command - * @param SDMMCx: Pointer to SDMMC register base - * @param Response: Specifies the SDMMC response register. - * This parameter can be one of the following values: - * @arg SDMMC_RESP1: Response Register 1 - * @arg SDMMC_RESP2: Response Register 2 - * @arg SDMMC_RESP3: Response Register 3 - * @arg SDMMC_RESP4: Response Register 4 - * @retval The Corresponding response register value - */ -uint32_t SDMMC_GetResponse(const SDMMC_TypeDef *SDMMCx, uint32_t Response) -{ - uint32_t tmp; - - /* Check the parameters */ - assert_param(IS_SDMMC_RESP(Response)); - - /* Get the response */ - tmp = (uint32_t)(&(SDMMCx->RESP1)) + Response; - - return (*(__IO uint32_t *) tmp); -} - -/** - * @brief Configure the SDMMC data path according to the specified - * parameters in the SDMMC_DataInitTypeDef. - * @param SDMMCx: Pointer to SDMMC register base - * @param Data : pointer to a SDMMC_DataInitTypeDef structure - * that contains the configuration information for the SDMMC data. - * @retval HAL status - */ -HAL_StatusTypeDef SDMMC_ConfigData(SDMMC_TypeDef *SDMMCx, SDMMC_DataInitTypeDef *Data) -{ - uint32_t tmpreg = 0; - - /* Check the parameters */ - assert_param(IS_SDMMC_DATA_LENGTH(Data->DataLength)); - assert_param(IS_SDMMC_BLOCK_SIZE(Data->DataBlockSize)); - assert_param(IS_SDMMC_TRANSFER_DIR(Data->TransferDir)); - assert_param(IS_SDMMC_TRANSFER_MODE(Data->TransferMode)); - assert_param(IS_SDMMC_DPSM(Data->DPSM)); - - /* Set the SDMMC Data TimeOut value */ - SDMMCx->DTIMER = Data->DataTimeOut; - - /* Set the SDMMC DataLength value */ - SDMMCx->DLEN = Data->DataLength; - - /* Set the SDMMC data configuration parameters */ - tmpreg |= (uint32_t)(Data->DataBlockSize | \ - Data->TransferDir | \ - Data->TransferMode | \ - Data->DPSM); - - /* Write to SDMMC DCTRL */ - MODIFY_REG(SDMMCx->DCTRL, DCTRL_CLEAR_MASK, tmpreg); - - return HAL_OK; - -} - -/** - * @brief Returns number of remaining data bytes to be transferred. - * @param SDMMCx: Pointer to SDMMC register base - * @retval Number of remaining data bytes to be transferred - */ -uint32_t SDMMC_GetDataCounter(const SDMMC_TypeDef *SDMMCx) -{ - return (SDMMCx->DCOUNT); -} - -/** - * @brief Get the FIFO data - * @param SDMMCx: Pointer to SDMMC register base - * @retval Data received - */ -uint32_t SDMMC_GetFIFOCount(const SDMMC_TypeDef *SDMMCx) -{ - return (SDMMCx->FIFO); -} - -/** - * @brief Sets one of the two options of inserting read wait interval. - * @param SDMMCx: Pointer to SDMMC register base - * @param SDMMC_ReadWaitMode: SDMMC Read Wait operation mode. - * This parameter can be: - * @arg SDMMC_READ_WAIT_MODE_CLK: Read Wait control by stopping SDMMCCLK - * @arg SDMMC_READ_WAIT_MODE_DATA2: Read Wait control using SDMMC_DATA2 - * @retval None - */ -HAL_StatusTypeDef SDMMC_SetSDMMCReadWaitMode(SDMMC_TypeDef *SDMMCx, uint32_t SDMMC_ReadWaitMode) -{ - /* Check the parameters */ - assert_param(IS_SDMMC_READWAIT_MODE(SDMMC_ReadWaitMode)); - - /* Set SDMMC read wait mode */ - MODIFY_REG(SDMMCx->DCTRL, SDMMC_DCTRL_RWMOD, SDMMC_ReadWaitMode); - - return HAL_OK; -} - -/** - * @} - */ - - -/** @defgroup HAL_SDMMC_LL_Group4 Command management functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### Commands management functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the needed commands. - -@endverbatim - * @{ - */ - -/** - * @brief Send the Data Block Length command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdBlockLength(SDMMC_TypeDef *SDMMCx, uint32_t BlockSize) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)BlockSize; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_BLOCKLEN; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SET_BLOCKLEN, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Data Block number command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdBlockCount(SDMMC_TypeDef *SDMMCx, uint32_t BlockCount) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)BlockCount; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_BLOCK_COUNT; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SET_BLOCK_COUNT, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Read Single Block command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdReadSingleBlock(SDMMC_TypeDef *SDMMCx, uint32_t ReadAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_SINGLE_BLOCK; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_READ_SINGLE_BLOCK, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Read Multi Block command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdReadMultiBlock(SDMMC_TypeDef *SDMMCx, uint32_t ReadAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_MULT_BLOCK; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_READ_MULT_BLOCK, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Write Single Block command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdWriteSingleBlock(SDMMC_TypeDef *SDMMCx, uint32_t WriteAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_SINGLE_BLOCK; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_WRITE_SINGLE_BLOCK, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Write Multi Block command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdWriteMultiBlock(SDMMC_TypeDef *SDMMCx, uint32_t WriteAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_MULT_BLOCK; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_WRITE_MULT_BLOCK, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Start Address Erase command for SD and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSDEraseStartAdd(SDMMC_TypeDef *SDMMCx, uint32_t StartAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)StartAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_START; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_ERASE_GRP_START, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the End Address Erase command for SD and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSDEraseEndAdd(SDMMC_TypeDef *SDMMCx, uint32_t EndAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)EndAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_END; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_ERASE_GRP_END, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Start Address Erase command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdEraseStartAdd(SDMMC_TypeDef *SDMMCx, uint32_t StartAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)StartAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_START; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_ERASE_GRP_START, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the End Address Erase command and check the response - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdEraseEndAdd(SDMMC_TypeDef *SDMMCx, uint32_t EndAdd) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)EndAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_END; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_ERASE_GRP_END, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Erase command and check the response - * @param SDMMCx Pointer to SDMMC register base - * @param EraseType Type of erase to be performed - * @retval HAL status - */ -uint32_t SDMMC_CmdErase(SDMMC_TypeDef *SDMMCx, uint32_t EraseType) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = EraseType; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_ERASE, SDMMC_MAXERASETIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Stop Transfer command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdStopTransfer(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD12 STOP_TRANSMISSION */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_STOP_TRANSMISSION; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - - __SDMMC_CMDSTOP_ENABLE(SDMMCx); - __SDMMC_CMDTRANS_DISABLE(SDMMCx); - - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_STOP_TRANSMISSION, SDMMC_STOPTRANSFERTIMEOUT); - - __SDMMC_CMDSTOP_DISABLE(SDMMCx); - - /* Ignore Address Out Of Range Error, Not relevant at end of memory */ - if (errorstate == SDMMC_ERROR_ADDR_OUT_OF_RANGE) - { - errorstate = SDMMC_ERROR_NONE; - } - - return errorstate; -} - -/** - * @brief Send the Select Deselect command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param addr: Address of the card to be selected - * @retval HAL status - */ -uint32_t SDMMC_CmdSelDesel(SDMMC_TypeDef *SDMMCx, uint32_t Addr) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD7 SDMMC_SEL_DESEL_CARD */ - sdmmc_cmdinit.Argument = (uint32_t)Addr; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEL_DESEL_CARD; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SEL_DESEL_CARD, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Go Idle State command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdGoIdleState(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_GO_IDLE_STATE; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_NO; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdError(SDMMCx); - - return errorstate; -} - -/** - * @brief Send the Operating Condition command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdOperCond(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* 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 */ - sdmmc_cmdinit.Argument = SDMMC_CHECK_PATTERN; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp7(SDMMCx); - - return errorstate; -} - -/** - * @brief Send the Application command to verify that that the next command - * is an application specific com-mand rather than a standard command - * and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param Argument: Command Argument - * @retval HAL status - */ -uint32_t SDMMC_CmdAppCommand(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = (uint32_t)Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_CMD; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - /* If there is a HAL_ERROR, it is a MMC card, else - it is a SD card: SD card 2.0 (voltage range mismatch) - or SD card 1.x */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_APP_CMD, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the command asking the accessed card to send its operating - * condition register (OCR) - * @param SDMMCx: Pointer to SDMMC register base - * @param Argument: Command Argument - * @retval HAL status - */ -uint32_t SDMMC_CmdAppOperCommand(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_OP_COND; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp3(SDMMCx); - - return errorstate; -} - -/** - * @brief Send the Bus Width command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param BusWidth: BusWidth - * @retval HAL status - */ -uint32_t SDMMC_CmdBusWidth(SDMMC_TypeDef *SDMMCx, uint32_t BusWidth) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = (uint32_t)BusWidth; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_SD_SET_BUSWIDTH; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_APP_SD_SET_BUSWIDTH, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Send SCR command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSendSCR(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD51 SD_APP_SEND_SCR */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_SEND_SCR; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_APP_SEND_SCR, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Send CID command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSendCID(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD2 ALL_SEND_CID */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ALL_SEND_CID; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_LONG; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp2(SDMMCx); - - return errorstate; -} - -/** - * @brief Send the Send CSD command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param Argument: Command Argument - * @retval HAL status - */ -uint32_t SDMMC_CmdSendCSD(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD9 SEND_CSD */ - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_CSD; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_LONG; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp2(SDMMCx); - - return errorstate; -} - -/** - * @brief Send the Send CSD command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param pRCA: Card RCA - * @retval HAL status - */ -uint32_t SDMMC_CmdSetRelAdd(SDMMC_TypeDef *SDMMCx, uint16_t *pRCA) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD3 SD_CMD_SET_REL_ADDR */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp6(SDMMCx, SDMMC_CMD_SET_REL_ADDR, pRCA); - - return errorstate; -} - -/** - * @brief Send the Set Relative Address command to MMC card (not SD card). - * @param SDMMCx Pointer to SDMMC register base - * @param RCA Card RCA - * @retval HAL status - */ -uint32_t SDMMC_CmdSetRelAddMmc(SDMMC_TypeDef *SDMMCx, uint16_t RCA) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD3 SD_CMD_SET_REL_ADDR */ - sdmmc_cmdinit.Argument = ((uint32_t)RCA << 16U); - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SET_REL_ADDR, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Sleep command to MMC card (not SD card). - * @param SDMMCx Pointer to SDMMC register base - * @param Argument Argument of the command (RCA and Sleep/Awake) - * @retval HAL status - */ -uint32_t SDMMC_CmdSleepMmc(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD5 SDMMC_CMD_MMC_SLEEP_AWAKE */ - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_MMC_SLEEP_AWAKE; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_MMC_SLEEP_AWAKE, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Status command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param Argument: Command Argument - * @retval HAL status - */ -uint32_t SDMMC_CmdSendStatus(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_STATUS; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SEND_STATUS, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Status register command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdStatusRegister(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_STATUS; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_APP_STATUS, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Sends host capacity support information and activates the card's - * initialization process. Send SDMMC_CMD_SEND_OP_COND command - * @param SDMMCx: Pointer to SDMMC register base - * @parame Argument: Argument used for the command - * @retval HAL status - */ -uint32_t SDMMC_CmdOpCondition(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_OP_COND; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp3(SDMMCx); - - return errorstate; -} - -/** - * @brief Checks switchable function and switch card function. SDMMC_CMD_HS_SWITCH command - * @param SDMMCx: Pointer to SDMMC register base - * @parame Argument: Argument used for the command - * @retval HAL status - */ -uint32_t SDMMC_CmdSwitch(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD6 to activate SDR50 Mode and Power Limit 1.44W */ - /* CMD Response: R1 */ - sdmmc_cmdinit.Argument = Argument; /* SDMMC_SDR25_SWITCH_PATTERN*/ - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SWITCH; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_HS_SWITCH, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the command asking the accessed card to send its operating - * condition register (OCR) - * @param None - * @retval HAL status - */ -uint32_t SDMMC_CmdVoltageSwitch(SDMMC_TypeDef *SDMMCx) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - sdmmc_cmdinit.Argument = 0x00000000; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_VOLTAGE_SWITCH; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_VOLTAGE_SWITCH, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Send EXT_CSD command and check the response. - * @param SDMMCx: Pointer to SDMMC register base - * @param Argument: Command Argument - * @retval HAL status - */ -uint32_t SDMMC_CmdSendEXTCSD(SDMMC_TypeDef *SDMMCx, uint32_t Argument) -{ - SDMMC_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate; - - /* Send CMD9 SEND_CSD */ - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; - sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; - sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; - (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_HS_SEND_EXT_CSD, SDMMC_CMDTIMEOUT); - - return errorstate; -} - -/** - * @} - */ - - -/** @defgroup HAL_SDMMC_LL_Group5 Responses management functions - * @brief Responses functions - * -@verbatim - =============================================================================== - ##### Responses management functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the needed responses. - -@endverbatim - * @{ - */ -/** - * @brief Checks for error conditions for R1 response. - * @param hsd: SD handle - * @param SD_CMD: The sent command index - * @retval SD Card error state - */ -uint32_t SDMMC_GetCmdResp1(SDMMC_TypeDef *SDMMCx, uint8_t SD_CMD, uint32_t Timeout) -{ - uint32_t response_r1; - uint32_t sta_reg; - - /* 8 is the number of required instructions cycles for the below loop statement. - The Timeout is expressed in ms */ - uint32_t count = Timeout * (SystemCoreClock / 8U / 1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - sta_reg = SDMMCx->STA; - } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT | - SDMMC_FLAG_BUSYD0END)) == 0U) || ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); - - if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - else - { - /* Nothing to do */ - } - - /* Clear all the static flags */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); - - /* Check response received is of desired command */ - if (SDMMC_GetCommandResponse(SDMMCx) != SD_CMD) - { - return SDMMC_ERROR_CMD_CRC_FAIL; - } - - /* We have received response, retrieve it for analysis */ - response_r1 = SDMMC_GetResponse(SDMMCx, SDMMC_RESP1); - - if ((response_r1 & SDMMC_OCR_ERRORBITS) == SDMMC_ALLZERO) - { - return SDMMC_ERROR_NONE; - } - else if ((response_r1 & SDMMC_OCR_ADDR_OUT_OF_RANGE) == SDMMC_OCR_ADDR_OUT_OF_RANGE) - { - return SDMMC_ERROR_ADDR_OUT_OF_RANGE; - } - else if ((response_r1 & SDMMC_OCR_ADDR_MISALIGNED) == SDMMC_OCR_ADDR_MISALIGNED) - { - return SDMMC_ERROR_ADDR_MISALIGNED; - } - else if ((response_r1 & SDMMC_OCR_BLOCK_LEN_ERR) == SDMMC_OCR_BLOCK_LEN_ERR) - { - return SDMMC_ERROR_BLOCK_LEN_ERR; - } - else if ((response_r1 & SDMMC_OCR_ERASE_SEQ_ERR) == SDMMC_OCR_ERASE_SEQ_ERR) - { - return SDMMC_ERROR_ERASE_SEQ_ERR; - } - else if ((response_r1 & SDMMC_OCR_BAD_ERASE_PARAM) == SDMMC_OCR_BAD_ERASE_PARAM) - { - return SDMMC_ERROR_BAD_ERASE_PARAM; - } - else if ((response_r1 & SDMMC_OCR_WRITE_PROT_VIOLATION) == SDMMC_OCR_WRITE_PROT_VIOLATION) - { - return SDMMC_ERROR_WRITE_PROT_VIOLATION; - } - else if ((response_r1 & SDMMC_OCR_LOCK_UNLOCK_FAILED) == SDMMC_OCR_LOCK_UNLOCK_FAILED) - { - return SDMMC_ERROR_LOCK_UNLOCK_FAILED; - } - else if ((response_r1 & SDMMC_OCR_COM_CRC_FAILED) == SDMMC_OCR_COM_CRC_FAILED) - { - return SDMMC_ERROR_COM_CRC_FAILED; - } - else if ((response_r1 & SDMMC_OCR_ILLEGAL_CMD) == SDMMC_OCR_ILLEGAL_CMD) - { - return SDMMC_ERROR_ILLEGAL_CMD; - } - else if ((response_r1 & SDMMC_OCR_CARD_ECC_FAILED) == SDMMC_OCR_CARD_ECC_FAILED) - { - return SDMMC_ERROR_CARD_ECC_FAILED; - } - else if ((response_r1 & SDMMC_OCR_CC_ERROR) == SDMMC_OCR_CC_ERROR) - { - return SDMMC_ERROR_CC_ERR; - } - else if ((response_r1 & SDMMC_OCR_STREAM_READ_UNDERRUN) == SDMMC_OCR_STREAM_READ_UNDERRUN) - { - return SDMMC_ERROR_STREAM_READ_UNDERRUN; - } - else if ((response_r1 & SDMMC_OCR_STREAM_WRITE_OVERRUN) == SDMMC_OCR_STREAM_WRITE_OVERRUN) - { - return SDMMC_ERROR_STREAM_WRITE_OVERRUN; - } - else if ((response_r1 & SDMMC_OCR_CID_CSD_OVERWRITE) == SDMMC_OCR_CID_CSD_OVERWRITE) - { - return SDMMC_ERROR_CID_CSD_OVERWRITE; - } - else if ((response_r1 & SDMMC_OCR_WP_ERASE_SKIP) == SDMMC_OCR_WP_ERASE_SKIP) - { - return SDMMC_ERROR_WP_ERASE_SKIP; - } - else if ((response_r1 & SDMMC_OCR_CARD_ECC_DISABLED) == SDMMC_OCR_CARD_ECC_DISABLED) - { - return SDMMC_ERROR_CARD_ECC_DISABLED; - } - else if ((response_r1 & SDMMC_OCR_ERASE_RESET) == SDMMC_OCR_ERASE_RESET) - { - return SDMMC_ERROR_ERASE_RESET; - } - else if ((response_r1 & SDMMC_OCR_AKE_SEQ_ERROR) == SDMMC_OCR_AKE_SEQ_ERROR) - { - return SDMMC_ERROR_AKE_SEQ_ERR; - } - else - { - return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } -} - -/** - * @brief Checks for error conditions for R2 (CID or CSD) response. - * @param hsd: SD handle - * @retval SD Card error state - */ -uint32_t SDMMC_GetCmdResp2(SDMMC_TypeDef *SDMMCx) -{ - uint32_t sta_reg; - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - sta_reg = SDMMCx->STA; - } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || - ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); - - if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - else - { - /* No error flag set */ - /* Clear all the static flags */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); - } - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Checks for error conditions for R3 (OCR) response. - * @param hsd: SD handle - * @retval SD Card error state - */ -uint32_t SDMMC_GetCmdResp3(SDMMC_TypeDef *SDMMCx) -{ - uint32_t sta_reg; - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - sta_reg = SDMMCx->STA; - } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || - ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); - - if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else - { - /* Clear all the static flags */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); - } - - return SDMMC_ERROR_NONE; -} - -/** - * @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 - */ -uint32_t SDMMC_GetCmdResp6(SDMMC_TypeDef *SDMMCx, uint8_t SD_CMD, uint16_t *pRCA) -{ - uint32_t response_r1; - uint32_t sta_reg; - - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - sta_reg = SDMMCx->STA; - } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || - ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); - - if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) - { - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - else - { - /* Nothing to do */ - } - - /* Check response received is of desired command */ - if (SDMMC_GetCommandResponse(SDMMCx) != SD_CMD) - { - return SDMMC_ERROR_CMD_CRC_FAIL; - } - - /* Clear all the static flags */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); - - /* We have received response, retrieve it. */ - response_r1 = SDMMC_GetResponse(SDMMCx, SDMMC_RESP1); - - if ((response_r1 & (SDMMC_R6_GENERAL_UNKNOWN_ERROR | SDMMC_R6_ILLEGAL_CMD | - SDMMC_R6_COM_CRC_FAILED)) == SDMMC_ALLZERO) - { - *pRCA = (uint16_t)(response_r1 >> 16); - - return SDMMC_ERROR_NONE; - } - else if ((response_r1 & SDMMC_R6_ILLEGAL_CMD) == SDMMC_R6_ILLEGAL_CMD) - { - return SDMMC_ERROR_ILLEGAL_CMD; - } - else if ((response_r1 & SDMMC_R6_COM_CRC_FAILED) == SDMMC_R6_COM_CRC_FAILED) - { - return SDMMC_ERROR_COM_CRC_FAILED; - } - else - { - return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } -} - -/** - * @brief Checks for error conditions for R7 response. - * @param hsd: SD handle - * @retval SD Card error state - */ -uint32_t SDMMC_GetCmdResp7(SDMMC_TypeDef *SDMMCx) -{ - uint32_t sta_reg; - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - sta_reg = SDMMCx->STA; - } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || - ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); - - if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) - { - /* Card is not SD V2.0 compliant */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - - else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) - { - /* Card is not SD V2.0 compliant */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - else - { - /* Nothing to do */ - } - - if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CMDREND)) - { - /* Card is SD V2.0 compliant */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CMDREND); - } - - return SDMMC_ERROR_NONE; - -} - -/** - * @} - */ - - -/** @defgroup HAL_SDMMC_LL_Group6 Linked List functions - * @brief Linked List management functions - * -@verbatim - =============================================================================== - ##### Linked List management functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the needed functions. - -@endverbatim - * @{ - */ - -/** - * @brief Build new Linked List node. - * @param pNode: Pointer to new node to add. - * @param pNodeConf: Pointer to configuration parameters for new node to add. - * @retval Error status - */ -uint32_t SDMMC_DMALinkedList_BuildNode(SDMMC_DMALinkNodeTypeDef *pNode, SDMMC_DMALinkNodeConfTypeDef *pNodeConf) -{ - - if ((pNode == NULL) || (pNodeConf == NULL)) - { - return SDMMC_ERROR_INVALID_PARAMETER; - } - /* Configure the Link Node registers*/ - pNode->IDMABASER = pNodeConf->BufferAddress; - pNode->IDMABSIZE = pNodeConf->BufferSize; - pNode->IDMALAR = SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ABR; - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Insert new Linked List node. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @param pPrevNode: Pointer to previous node . - * @param pNewNode: Pointer to new node to add. - * @retval Error status - */ -uint32_t SDMMC_DMALinkedList_InsertNode(SDMMC_DMALinkedListTypeDef *pLinkedList, SDMMC_DMALinkNodeTypeDef *pPrevNode, - SDMMC_DMALinkNodeTypeDef *pNode) -{ - uint32_t link_list_offset; - uint32_t node_address = (uint32_t) pNode; - - /* First Node */ - if (pLinkedList->NodesCounter == 0U) - { - - pLinkedList->pHeadNode = pNode; - pLinkedList->pTailNode = pNode; - pLinkedList->NodesCounter = 1U; - - } - else if (pPrevNode == pLinkedList->pTailNode) - { - if (pNode <= pLinkedList->pHeadNode) - { - /* Node Address should greater than Head Node Address*/ - return SDMMC_ERROR_INVALID_PARAMETER; - } - - /*Last Node, no next node */ - MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_ULA, 0U); - - /*link Prev node with new one */ - MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_ULA, SDMMC_IDMALAR_ULA); - MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_IDMALA, (node_address - (uint32_t)pLinkedList->pHeadNode)); - - pLinkedList->NodesCounter ++; - pLinkedList->pTailNode = pNode; - - } - else - { - - if (pNode <= pLinkedList->pHeadNode) - { - /* Node Address should greater than Head Node Address*/ - return SDMMC_ERROR_INVALID_PARAMETER; - } - - /*link New node with Next one */ - link_list_offset = pNode->IDMALAR; - MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_IDMALA, link_list_offset); - - /*link Prev node with new one */ - MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_ULA, SDMMC_IDMALAR_ULA); - MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_IDMALA, (node_address - (uint32_t)pLinkedList->pHeadNode)); - - pLinkedList->NodesCounter ++; - - } - return SDMMC_ERROR_NONE; -} - -/** - * @brief Remove node from the Linked List. - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @param pNode: Pointer to new node to add. - * @retval Error status - */ -uint32_t SDMMC_DMALinkedList_RemoveNode(SDMMC_DMALinkedListTypeDef *pLinkedList, SDMMC_DMALinkNodeTypeDef *pNode) -{ - uint32_t count = 0U; - uint32_t linked_list_offset; - SDMMC_DMALinkNodeTypeDef *prev_node = NULL; - SDMMC_DMALinkNodeTypeDef *curr_node ; - - /* First Node */ - if (pLinkedList->NodesCounter == 0U) - { - - return SDMMC_ERROR_INVALID_PARAMETER; - } - else - { - curr_node = pLinkedList->pHeadNode; - while ((curr_node != pNode) && (count <= pLinkedList->NodesCounter)) - { - prev_node = curr_node; - curr_node = (SDMMC_DMALinkNodeTypeDef *)((prev_node->IDMALAR & SDMMC_IDMALAR_IDMALA) + - (uint32_t)pLinkedList->pHeadNode); - count++; - } - - if ((count == 0U) || (count > pLinkedList->NodesCounter)) - { - /* Node not found in the linked list */ - return SDMMC_ERROR_INVALID_PARAMETER; - } - - pLinkedList->NodesCounter--; - - if (pLinkedList->NodesCounter == 0U) - { - pLinkedList->pHeadNode = 0U; - pLinkedList->pTailNode = 0U; - } - else - { - /*link prev node with next one */ - linked_list_offset = curr_node->IDMALAR; - MODIFY_REG(prev_node->IDMALAR, SDMMC_IDMALAR_IDMALA, linked_list_offset); - /* Configure the new Link Node registers*/ - pNode->IDMALAR |= linked_list_offset; - - pLinkedList->pTailNode = prev_node; - } - } - return SDMMC_ERROR_NONE; -} - -/** - * @brief Lock Linked List Node - * @param pNode: Pointer to node to lock. - * @retval Error status - - */ -uint32_t SDMMC_DMALinkedList_LockNode(SDMMC_DMALinkNodeTypeDef *pNode) -{ - - if (pNode == NULL) - { - return SDMMC_ERROR_INVALID_PARAMETER; - } - - MODIFY_REG(pNode->IDMALAR, SDMMC_IDMALAR_ABR, 0U); - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Unlock Linked List Node - * @param pNode: Pointer to node to unlock. - * @retval Error status - - */ -uint32_t SDMMC_DMALinkedList_UnlockNode(SDMMC_DMALinkNodeTypeDef *pNode) -{ - - if (pNode == NULL) - { - return SDMMC_ERROR_INVALID_PARAMETER; - } - - MODIFY_REG(pNode->IDMALAR, SDMMC_IDMALAR_ABR, SDMMC_IDMALAR_ABR); - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Enable Linked List circular mode - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @retval Error status - - */ -uint32_t SDMMC_DMALinkedList_EnableCircularMode(SDMMC_DMALinkedListTypeDef *pLinkedList) -{ - - if (pLinkedList == NULL) - { - return SDMMC_ERROR_INVALID_PARAMETER; - } - - MODIFY_REG(pLinkedList->pTailNode->IDMALAR, SDMMC_IDMALAR_ULA | SDMMC_IDMALAR_IDMALA, SDMMC_IDMALAR_ULA); - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Disable DMA Linked List Circular mode - * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes - * @retval Error status - */ -uint32_t SDMMC_DMALinkedList_DisableCircularMode(SDMMC_DMALinkedListTypeDef *pLinkedList) -{ - - if (pLinkedList == NULL) - { - return SDMMC_ERROR_INVALID_PARAMETER; - } - - MODIFY_REG(pLinkedList->pTailNode->IDMALAR, SDMMC_IDMALAR_ULA, 0U); - - return SDMMC_ERROR_NONE; -} - -/** - * @} - */ - - -/* Private function ----------------------------------------------------------*/ -/** @addtogroup SD_Private_Functions - * @{ - */ - -/** - * @brief Checks for error conditions for CMD0. - * @param hsd: SD handle - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdError(SDMMC_TypeDef *SDMMCx) -{ - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - } while (!__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CMDSENT)); - - /* Clear all the static flags */ - __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); - - return SDMMC_ERROR_NONE; -} - -/** - * @} - */ - -#endif /* HAL_SD_MODULE_ENABLED || HAL_MMC_MODULE_ENABLED */ -#endif /* SDMMC1 || SDMMC2 */ -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_sdmmc.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### SDMMC peripheral features ##### + ============================================================================== + [..] The SD/SDMMC MMC card host interface (SDMMC) provides an interface between the AHB + peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDMMC cards and CE-ATA + devices. + + [..] The SDMMC features include the following: + (+) Full compliance with MultiMediaCard System Specification Version 4.51. Card support + for three different databus modes: 1-bit (default), 4-bit and 8-bit. + (+) Full compatibility with previous versions of MultiMediaCards (backward compatibility). + (+) Full compliance with SD memory card specifications version 4.1. + (SDR104 SDMMC_CK speed limited to maximum allowed IO speed, SPI mode and + UHS-II mode not supported). + (+) Full compliance with SDIO card specification version 4.0. Card support + for two different databus modes: 1-bit (default) and 4-bit. + (SDR104 SDMMC_CK speed limited to maximum allowed IO speed, SPI mode and + UHS-II mode not supported). + (+) Data transfer up to 208 Mbyte/s for the 8 bit mode. (depending maximum allowed IO speed). + (+) 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 SDMMC peripheral. + According to the device used (SD card/ MMC card / SDMMC card ...), a set of APIs + is used in the device's driver to perform SDMMC 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 SDMMC clock is coming from output of PLL1_Q or PLL2_R. + Before start working with SDMMC peripheral make sure that the PLL is well configured. + The SDMMC peripheral uses two clock signals: + (++) PLL1_Q bus clock (default after reset) + (++) PLL2_R bus clock + + (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDMMC + peripheral. + + (+) Enable the Power ON State using the SDMMC_PowerState_ON(SDMMCx) + function and disable it using the function SDMMC_PowerState_OFF(SDMMCx). + + (+) Enable/Disable the peripheral interrupts using the macros __SDMMC_ENABLE_IT(hSDMMC, IT) + and __SDMMC_DISABLE_IT(hSDMMC, IT) if you need to use interrupt mode. + + (+) When using the DMA mode + (++) Configure the IDMA mode (Single buffer or double) + (++) Configure the buffer address + (++) Configure Data Path State Machine + + (+) To control the CPSM (Command Path State Machine) and send + commands to the card use the SDMMC_SendCommand(SDMMCx), + SDMMC_GetCommandResponse() and SDMMC_GetResponse() functions. First, user has + to fill the command structure (pointer to SDMMC_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 SDMMC_CMDRESP + register using the SDMMC_GetCommandResponse(). + The SDMMC responses registers (SDMMC_RESP1 to SDMMC_RESP2), use the + SDMMC_GetResponse() function. + + (+) To control the DPSM (Data Path State Machine) and send/receive + data to/from the card use the SDMMC_DataConfig(), SDMMC_GetDataCounter(), + SDMMC_ReadFIFO(), SDMMC_WriteFIFO() and SDMMC_GetFIFOCount() functions. + + *** Read Operations *** + ======================= + [..] + (#) First, user has to fill the data structure (pointer to + SDMMC_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 SDMMC) + (++) Data Transfer mode + (++) DPSM Status (Enable or Disable) + + (#) Configure the SDMMC 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 SDMMC flags/interrupts to check the transfer status. + + *** Write Operations *** + ======================== + [..] + (#) First, user has to fill the data structure (pointer to + SDMMC_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 SDMMC resources to send the data to the card according to + selected transfer mode. + + (#) Send the selected Write command. + + (#) Use the SDMMC flags/interrupts to check the transfer status. + + *** Command management operations *** + ===================================== + [..] + (#) The commands used for Read/Write/Erase operations are managed in + separate functions. + Each function allows to send the needed command with the related argument, + then check the response. + By the same approach, you could implement a command and check the response. + + @endverbatim + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_HAL_Driver + * @{ + */ + +/** @defgroup SDMMC_LL SDMMC Low Layer + * @brief Low layer module for SD + * @{ + */ + +#if defined (SDMMC1) || defined (SDMMC2) +#if defined (HAL_SD_MODULE_ENABLED) || defined (HAL_MMC_MODULE_ENABLED) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static uint32_t SDMMC_GetCmdError(SDMMC_TypeDef *SDMMCx); + +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SDMMC_LL_Exported_Functions SDMMC Low Layer Exported Functions + * @{ + */ + +/** @defgroup HAL_SDMMC_LL_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 SDMMC according to the specified + * parameters in the SDMMC_InitTypeDef and create the associated handle. + * @param SDMMCx: Pointer to SDMMC register base + * @param Init: SDMMC initialization structure + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_Init(SDMMC_TypeDef *SDMMCx, SDMMC_InitTypeDef Init) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(SDMMCx)); + assert_param(IS_SDMMC_CLOCK_EDGE(Init.ClockEdge)); + assert_param(IS_SDMMC_CLOCK_POWER_SAVE(Init.ClockPowerSave)); + assert_param(IS_SDMMC_BUS_WIDE(Init.BusWide)); + assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(Init.HardwareFlowControl)); + assert_param(IS_SDMMC_CLKDIV(Init.ClockDiv)); + + /* Set SDMMC configuration parameters */ + tmpreg |= (Init.ClockEdge | \ + Init.ClockPowerSave | \ + Init.BusWide | \ + Init.HardwareFlowControl | \ + Init.ClockDiv + ); + + /* Write to SDMMC CLKCR */ + MODIFY_REG(SDMMCx->CLKCR, CLKCR_CLEAR_MASK, tmpreg); + + return HAL_OK; +} + + +/** + * @} + */ + +/** @defgroup HAL_SDMMC_LL_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SDMMC data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Read data (word) from Rx FIFO in blocking mode (polling) + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_ReadFIFO(const SDMMC_TypeDef *SDMMCx) +{ + /* Read data from Rx FIFO */ + return (SDMMCx->FIFO); +} + +/** + * @brief Write data (word) to Tx FIFO in blocking mode (polling) + * @param SDMMCx: Pointer to SDMMC register base + * @param pWriteData: pointer to data to write + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_WriteFIFO(SDMMC_TypeDef *SDMMCx, uint32_t *pWriteData) +{ + /* Write data to FIFO */ + SDMMCx->FIFO = *pWriteData; + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_SDMMC_LL_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SDMMC data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Set SDMMC Power state to ON. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_PowerState_ON(SDMMC_TypeDef *SDMMCx) +{ + /* Set power state to ON */ + SDMMCx->POWER |= SDMMC_POWER_PWRCTRL; + + return HAL_OK; +} + +/** + * @brief Set SDMMC Power state to Power-Cycle. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_PowerState_Cycle(SDMMC_TypeDef *SDMMCx) +{ + /* Set power state to Power Cycle*/ + SDMMCx->POWER |= SDMMC_POWER_PWRCTRL_1; + + return HAL_OK; +} + +/** + * @brief Set SDMMC Power state to OFF. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_PowerState_OFF(SDMMC_TypeDef *SDMMCx) +{ + /* Set power state to OFF */ + SDMMCx->POWER &= ~(SDMMC_POWER_PWRCTRL); + + return HAL_OK; +} + +/** + * @brief Get SDMMC Power state. + * @param SDMMCx: Pointer to SDMMC 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 SDMMC_GetPowerState(const SDMMC_TypeDef *SDMMCx) +{ + return (SDMMCx->POWER & SDMMC_POWER_PWRCTRL); +} + +/** + * @brief Configure the SDMMC command path according to the specified parameters in + * SDMMC_CmdInitTypeDef structure and send the command + * @param SDMMCx: Pointer to SDMMC register base + * @param Command: pointer to a SDMMC_CmdInitTypeDef structure that contains + * the configuration information for the SDMMC command + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_SendCommand(SDMMC_TypeDef *SDMMCx, SDMMC_CmdInitTypeDef *Command) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_CMD_INDEX(Command->CmdIndex)); + assert_param(IS_SDMMC_RESPONSE(Command->Response)); + assert_param(IS_SDMMC_WAIT(Command->WaitForInterrupt)); + assert_param(IS_SDMMC_CPSM(Command->CPSM)); + + /* Set the SDMMC Argument value */ + SDMMCx->ARG = Command->Argument; + + /* Set SDMMC command parameters */ + tmpreg |= (uint32_t)(Command->CmdIndex | \ + Command->Response | \ + Command->WaitForInterrupt | \ + Command->CPSM); + + /* Write to SDMMC CMD register */ + MODIFY_REG(SDMMCx->CMD, CMD_CLEAR_MASK, tmpreg); + + return HAL_OK; +} + +/** + * @brief Return the command index of last command for which response received + * @param SDMMCx: Pointer to SDMMC register base + * @retval Command index of the last command response received + */ +uint8_t SDMMC_GetCommandResponse(const SDMMC_TypeDef *SDMMCx) +{ + return (uint8_t)(SDMMCx->RESPCMD); +} + + +/** + * @brief Return the response received from the card for the last command + * @param SDMMCx: Pointer to SDMMC register base + * @param Response: Specifies the SDMMC response register. + * This parameter can be one of the following values: + * @arg SDMMC_RESP1: Response Register 1 + * @arg SDMMC_RESP2: Response Register 2 + * @arg SDMMC_RESP3: Response Register 3 + * @arg SDMMC_RESP4: Response Register 4 + * @retval The Corresponding response register value + */ +uint32_t SDMMC_GetResponse(const SDMMC_TypeDef *SDMMCx, uint32_t Response) +{ + uint32_t tmp; + + /* Check the parameters */ + assert_param(IS_SDMMC_RESP(Response)); + + /* Get the response */ + tmp = (uint32_t)(&(SDMMCx->RESP1)) + Response; + + return (*(__IO uint32_t *) tmp); +} + +/** + * @brief Configure the SDMMC data path according to the specified + * parameters in the SDMMC_DataInitTypeDef. + * @param SDMMCx: Pointer to SDMMC register base + * @param Data : pointer to a SDMMC_DataInitTypeDef structure + * that contains the configuration information for the SDMMC data. + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_ConfigData(SDMMC_TypeDef *SDMMCx, SDMMC_DataInitTypeDef *Data) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_DATA_LENGTH(Data->DataLength)); + assert_param(IS_SDMMC_BLOCK_SIZE(Data->DataBlockSize)); + assert_param(IS_SDMMC_TRANSFER_DIR(Data->TransferDir)); + assert_param(IS_SDMMC_TRANSFER_MODE(Data->TransferMode)); + assert_param(IS_SDMMC_DPSM(Data->DPSM)); + + /* Set the SDMMC Data TimeOut value */ + SDMMCx->DTIMER = Data->DataTimeOut; + + /* Set the SDMMC DataLength value */ + SDMMCx->DLEN = Data->DataLength; + + /* Set the SDMMC data configuration parameters */ + tmpreg |= (uint32_t)(Data->DataBlockSize | \ + Data->TransferDir | \ + Data->TransferMode | \ + Data->DPSM); + + /* Write to SDMMC DCTRL */ + MODIFY_REG(SDMMCx->DCTRL, DCTRL_CLEAR_MASK, tmpreg); + + return HAL_OK; + +} + +/** + * @brief Returns number of remaining data bytes to be transferred. + * @param SDMMCx: Pointer to SDMMC register base + * @retval Number of remaining data bytes to be transferred + */ +uint32_t SDMMC_GetDataCounter(const SDMMC_TypeDef *SDMMCx) +{ + return (SDMMCx->DCOUNT); +} + +/** + * @brief Get the FIFO data + * @param SDMMCx: Pointer to SDMMC register base + * @retval Data received + */ +uint32_t SDMMC_GetFIFOCount(const SDMMC_TypeDef *SDMMCx) +{ + return (SDMMCx->FIFO); +} + +/** + * @brief Sets one of the two options of inserting read wait interval. + * @param SDMMCx: Pointer to SDMMC register base + * @param SDMMC_ReadWaitMode: SDMMC Read Wait operation mode. + * This parameter can be: + * @arg SDMMC_READ_WAIT_MODE_CLK: Read Wait control by stopping SDMMCCLK + * @arg SDMMC_READ_WAIT_MODE_DATA2: Read Wait control using SDMMC_DATA2 + * @retval None + */ +HAL_StatusTypeDef SDMMC_SetSDMMCReadWaitMode(SDMMC_TypeDef *SDMMCx, uint32_t SDMMC_ReadWaitMode) +{ + /* Check the parameters */ + assert_param(IS_SDMMC_READWAIT_MODE(SDMMC_ReadWaitMode)); + + /* Set SDMMC read wait mode */ + MODIFY_REG(SDMMCx->DCTRL, SDMMC_DCTRL_RWMOD, SDMMC_ReadWaitMode); + + return HAL_OK; +} + +/** + * @} + */ + + +/** @defgroup HAL_SDMMC_LL_Group4 Command management functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### Commands management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed commands. + +@endverbatim + * @{ + */ + +/** + * @brief Send the Data Block Length command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdBlockLength(SDMMC_TypeDef *SDMMCx, uint32_t BlockSize) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)BlockSize; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_BLOCKLEN; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SET_BLOCKLEN, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Data Block number command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdBlockCount(SDMMC_TypeDef *SDMMCx, uint32_t BlockCount) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)BlockCount; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_BLOCK_COUNT; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SET_BLOCK_COUNT, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Read Single Block command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdReadSingleBlock(SDMMC_TypeDef *SDMMCx, uint32_t ReadAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_SINGLE_BLOCK; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_READ_SINGLE_BLOCK, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Read Multi Block command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdReadMultiBlock(SDMMC_TypeDef *SDMMCx, uint32_t ReadAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_MULT_BLOCK; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_READ_MULT_BLOCK, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Write Single Block command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdWriteSingleBlock(SDMMC_TypeDef *SDMMCx, uint32_t WriteAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_SINGLE_BLOCK; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_WRITE_SINGLE_BLOCK, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Write Multi Block command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdWriteMultiBlock(SDMMC_TypeDef *SDMMCx, uint32_t WriteAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_MULT_BLOCK; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_WRITE_MULT_BLOCK, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Start Address Erase command for SD and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdSDEraseStartAdd(SDMMC_TypeDef *SDMMCx, uint32_t StartAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)StartAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_START; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_ERASE_GRP_START, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the End Address Erase command for SD and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdSDEraseEndAdd(SDMMC_TypeDef *SDMMCx, uint32_t EndAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)EndAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_END; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_ERASE_GRP_END, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Start Address Erase command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdEraseStartAdd(SDMMC_TypeDef *SDMMCx, uint32_t StartAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)StartAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_START; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_ERASE_GRP_START, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the End Address Erase command and check the response + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdEraseEndAdd(SDMMC_TypeDef *SDMMCx, uint32_t EndAdd) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = (uint32_t)EndAdd; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_END; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_ERASE_GRP_END, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Erase command and check the response + * @param SDMMCx Pointer to SDMMC register base + * @param EraseType Type of erase to be performed + * @retval HAL status + */ +uint32_t SDMMC_CmdErase(SDMMC_TypeDef *SDMMCx, uint32_t EraseType) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Set Block Size for Card */ + sdmmc_cmdinit.Argument = EraseType; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_ERASE, SDMMC_MAXERASETIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Stop Transfer command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdStopTransfer(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD12 STOP_TRANSMISSION */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_STOP_TRANSMISSION; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + + __SDMMC_CMDSTOP_ENABLE(SDMMCx); + __SDMMC_CMDTRANS_DISABLE(SDMMCx); + + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_STOP_TRANSMISSION, SDMMC_STOPTRANSFERTIMEOUT); + + __SDMMC_CMDSTOP_DISABLE(SDMMCx); + + /* Ignore Address Out Of Range Error, Not relevant at end of memory */ + if (errorstate == SDMMC_ERROR_ADDR_OUT_OF_RANGE) + { + errorstate = SDMMC_ERROR_NONE; + } + + return errorstate; +} + +/** + * @brief Send the Select Deselect command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param addr: Address of the card to be selected + * @retval HAL status + */ +uint32_t SDMMC_CmdSelDesel(SDMMC_TypeDef *SDMMCx, uint32_t Addr) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD7 SDMMC_SEL_DESEL_CARD */ + sdmmc_cmdinit.Argument = (uint32_t)Addr; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEL_DESEL_CARD; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SEL_DESEL_CARD, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Go Idle State command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdGoIdleState(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_GO_IDLE_STATE; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_NO; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdError(SDMMCx); + + return errorstate; +} + +/** + * @brief Send the Operating Condition command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdOperCond(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* 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 */ + sdmmc_cmdinit.Argument = SDMMC_CHECK_PATTERN; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp7(SDMMCx); + + return errorstate; +} + +/** + * @brief Send the Application command to verify that that the next command + * is an application specific com-mand rather than a standard command + * and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: Command Argument + * @retval HAL status + */ +uint32_t SDMMC_CmdAppCommand(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = (uint32_t)Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_CMD; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + /* If there is a HAL_ERROR, it is a MMC card, else + it is a SD card: SD card 2.0 (voltage range mismatch) + or SD card 1.x */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_APP_CMD, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the command asking the accessed card to send its operating + * condition register (OCR) + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: Command Argument + * @retval HAL status + */ +uint32_t SDMMC_CmdAppOperCommand(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_OP_COND; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp3(SDMMCx); + + return errorstate; +} + +/** + * @brief Send the Bus Width command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param BusWidth: BusWidth + * @retval HAL status + */ +uint32_t SDMMC_CmdBusWidth(SDMMC_TypeDef *SDMMCx, uint32_t BusWidth) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = (uint32_t)BusWidth; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_SD_SET_BUSWIDTH; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_APP_SD_SET_BUSWIDTH, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Send SCR command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdSendSCR(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD51 SD_APP_SEND_SCR */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_SEND_SCR; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_APP_SEND_SCR, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Send CID command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdSendCID(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD2 ALL_SEND_CID */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ALL_SEND_CID; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_LONG; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp2(SDMMCx); + + return errorstate; +} + +/** + * @brief Send the Send CSD command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: Command Argument + * @retval HAL status + */ +uint32_t SDMMC_CmdSendCSD(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD9 SEND_CSD */ + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_CSD; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_LONG; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp2(SDMMCx); + + return errorstate; +} + +/** + * @brief Send the Send CSD command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param pRCA: Card RCA + * @retval HAL status + */ +uint32_t SDMMC_CmdSetRelAdd(SDMMC_TypeDef *SDMMCx, uint16_t *pRCA) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD3 SD_CMD_SET_REL_ADDR */ + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp6(SDMMCx, SDMMC_CMD_SET_REL_ADDR, pRCA); + + return errorstate; +} + +/** + * @brief Send the Set Relative Address command to MMC card (not SD card). + * @param SDMMCx Pointer to SDMMC register base + * @param RCA Card RCA + * @retval HAL status + */ +uint32_t SDMMC_CmdSetRelAddMmc(SDMMC_TypeDef *SDMMCx, uint16_t RCA) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD3 SD_CMD_SET_REL_ADDR */ + sdmmc_cmdinit.Argument = ((uint32_t)RCA << 16U); + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SET_REL_ADDR, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Sleep command to MMC card (not SD card). + * @param SDMMCx Pointer to SDMMC register base + * @param Argument Argument of the command (RCA and Sleep/Awake) + * @retval HAL status + */ +uint32_t SDMMC_CmdSleepMmc(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD5 SDMMC_CMD_MMC_SLEEP_AWAKE */ + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_MMC_SLEEP_AWAKE; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_MMC_SLEEP_AWAKE, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Status command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: Command Argument + * @retval HAL status + */ +uint32_t SDMMC_CmdSendStatus(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_STATUS; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SEND_STATUS, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Status register command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_CmdStatusRegister(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = 0U; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_STATUS; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_SD_APP_STATUS, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Sends host capacity support information and activates the card's + * initialization process. Send SDMMC_CMD_SEND_OP_COND command + * @param SDMMCx: Pointer to SDMMC register base + * @parame Argument: Argument used for the command + * @retval HAL status + */ +uint32_t SDMMC_CmdOpCondition(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_OP_COND; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp3(SDMMCx); + + return errorstate; +} + +/** + * @brief Checks switchable function and switch card function. SDMMC_CMD_HS_SWITCH command + * @param SDMMCx: Pointer to SDMMC register base + * @parame Argument: Argument used for the command + * @retval HAL status + */ +uint32_t SDMMC_CmdSwitch(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD6 to activate SDR50 Mode and Power Limit 1.44W */ + /* CMD Response: R1 */ + sdmmc_cmdinit.Argument = Argument; /* SDMMC_SDR25_SWITCH_PATTERN*/ + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SWITCH; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_HS_SWITCH, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the command asking the accessed card to send its operating + * condition register (OCR) + * @param None + * @retval HAL status + */ +uint32_t SDMMC_CmdVoltageSwitch(SDMMC_TypeDef *SDMMCx) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = 0x00000000; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_VOLTAGE_SWITCH; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_VOLTAGE_SWITCH, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @brief Send the Send EXT_CSD command and check the response. + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: Command Argument + * @retval HAL status + */ +uint32_t SDMMC_CmdSendEXTCSD(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + /* Send CMD9 SEND_CSD */ + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp1(SDMMCx, SDMMC_CMD_HS_SEND_EXT_CSD, SDMMC_CMDTIMEOUT); + + return errorstate; +} + +/** + * @} + */ + + +/** @defgroup HAL_SDMMC_LL_Group5 Responses management functions + * @brief Responses functions + * +@verbatim + =============================================================================== + ##### Responses management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed responses. + +@endverbatim + * @{ + */ +/** + * @brief Checks for error conditions for R1 response. + * @param hsd: SD handle + * @param SD_CMD: The sent command index + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp1(SDMMC_TypeDef *SDMMCx, uint8_t SD_CMD, uint32_t Timeout) +{ + uint32_t response_r1; + uint32_t sta_reg; + + /* 8 is the number of required instructions cycles for the below loop statement. + The Timeout is expressed in ms */ + uint32_t count = Timeout * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT | + SDMMC_FLAG_BUSYD0END)) == 0U) || ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + + /* Check response received is of desired command */ + if (SDMMC_GetCommandResponse(SDMMCx) != SD_CMD) + { + return SDMMC_ERROR_CMD_CRC_FAIL; + } + + /* We have received response, retrieve it for analysis */ + response_r1 = SDMMC_GetResponse(SDMMCx, SDMMC_RESP1); + + if ((response_r1 & SDMMC_OCR_ERRORBITS) == SDMMC_ALLZERO) + { + return SDMMC_ERROR_NONE; + } + else if ((response_r1 & SDMMC_OCR_ADDR_OUT_OF_RANGE) == SDMMC_OCR_ADDR_OUT_OF_RANGE) + { + return SDMMC_ERROR_ADDR_OUT_OF_RANGE; + } + else if ((response_r1 & SDMMC_OCR_ADDR_MISALIGNED) == SDMMC_OCR_ADDR_MISALIGNED) + { + return SDMMC_ERROR_ADDR_MISALIGNED; + } + else if ((response_r1 & SDMMC_OCR_BLOCK_LEN_ERR) == SDMMC_OCR_BLOCK_LEN_ERR) + { + return SDMMC_ERROR_BLOCK_LEN_ERR; + } + else if ((response_r1 & SDMMC_OCR_ERASE_SEQ_ERR) == SDMMC_OCR_ERASE_SEQ_ERR) + { + return SDMMC_ERROR_ERASE_SEQ_ERR; + } + else if ((response_r1 & SDMMC_OCR_BAD_ERASE_PARAM) == SDMMC_OCR_BAD_ERASE_PARAM) + { + return SDMMC_ERROR_BAD_ERASE_PARAM; + } + else if ((response_r1 & SDMMC_OCR_WRITE_PROT_VIOLATION) == SDMMC_OCR_WRITE_PROT_VIOLATION) + { + return SDMMC_ERROR_WRITE_PROT_VIOLATION; + } + else if ((response_r1 & SDMMC_OCR_LOCK_UNLOCK_FAILED) == SDMMC_OCR_LOCK_UNLOCK_FAILED) + { + return SDMMC_ERROR_LOCK_UNLOCK_FAILED; + } + else if ((response_r1 & SDMMC_OCR_COM_CRC_FAILED) == SDMMC_OCR_COM_CRC_FAILED) + { + return SDMMC_ERROR_COM_CRC_FAILED; + } + else if ((response_r1 & SDMMC_OCR_ILLEGAL_CMD) == SDMMC_OCR_ILLEGAL_CMD) + { + return SDMMC_ERROR_ILLEGAL_CMD; + } + else if ((response_r1 & SDMMC_OCR_CARD_ECC_FAILED) == SDMMC_OCR_CARD_ECC_FAILED) + { + return SDMMC_ERROR_CARD_ECC_FAILED; + } + else if ((response_r1 & SDMMC_OCR_CC_ERROR) == SDMMC_OCR_CC_ERROR) + { + return SDMMC_ERROR_CC_ERR; + } + else if ((response_r1 & SDMMC_OCR_STREAM_READ_UNDERRUN) == SDMMC_OCR_STREAM_READ_UNDERRUN) + { + return SDMMC_ERROR_STREAM_READ_UNDERRUN; + } + else if ((response_r1 & SDMMC_OCR_STREAM_WRITE_OVERRUN) == SDMMC_OCR_STREAM_WRITE_OVERRUN) + { + return SDMMC_ERROR_STREAM_WRITE_OVERRUN; + } + else if ((response_r1 & SDMMC_OCR_CID_CSD_OVERWRITE) == SDMMC_OCR_CID_CSD_OVERWRITE) + { + return SDMMC_ERROR_CID_CSD_OVERWRITE; + } + else if ((response_r1 & SDMMC_OCR_WP_ERASE_SKIP) == SDMMC_OCR_WP_ERASE_SKIP) + { + return SDMMC_ERROR_WP_ERASE_SKIP; + } + else if ((response_r1 & SDMMC_OCR_CARD_ECC_DISABLED) == SDMMC_OCR_CARD_ECC_DISABLED) + { + return SDMMC_ERROR_CARD_ECC_DISABLED; + } + else if ((response_r1 & SDMMC_OCR_ERASE_RESET) == SDMMC_OCR_ERASE_RESET) + { + return SDMMC_ERROR_ERASE_RESET; + } + else if ((response_r1 & SDMMC_OCR_AKE_SEQ_ERROR) == SDMMC_OCR_AKE_SEQ_ERROR) + { + return SDMMC_ERROR_AKE_SEQ_ERR; + } + else + { + return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } +} + +/** + * @brief Checks for error conditions for R2 (CID or CSD) response. + * @param hsd: SD handle + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp2(SDMMC_TypeDef *SDMMCx) +{ + uint32_t sta_reg; + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* No error flag set */ + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + } + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Checks for error conditions for R3 (OCR) response. + * @param hsd: SD handle + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp3(SDMMC_TypeDef *SDMMCx) +{ + uint32_t sta_reg; + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else + { + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + } + + return SDMMC_ERROR_NONE; +} + +/** + * @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 + */ +uint32_t SDMMC_GetCmdResp6(SDMMC_TypeDef *SDMMCx, uint8_t SD_CMD, uint16_t *pRCA) +{ + uint32_t response_r1; + uint32_t sta_reg; + + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + /* Check response received is of desired command */ + if (SDMMC_GetCommandResponse(SDMMCx) != SD_CMD) + { + return SDMMC_ERROR_CMD_CRC_FAIL; + } + + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + + /* We have received response, retrieve it. */ + response_r1 = SDMMC_GetResponse(SDMMCx, SDMMC_RESP1); + + if ((response_r1 & (SDMMC_R6_GENERAL_UNKNOWN_ERROR | SDMMC_R6_ILLEGAL_CMD | + SDMMC_R6_COM_CRC_FAILED)) == SDMMC_ALLZERO) + { + *pRCA = (uint16_t)(response_r1 >> 16); + + return SDMMC_ERROR_NONE; + } + else if ((response_r1 & SDMMC_R6_ILLEGAL_CMD) == SDMMC_R6_ILLEGAL_CMD) + { + return SDMMC_ERROR_ILLEGAL_CMD; + } + else if ((response_r1 & SDMMC_R6_COM_CRC_FAILED) == SDMMC_R6_COM_CRC_FAILED) + { + return SDMMC_ERROR_COM_CRC_FAILED; + } + else + { + return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } +} + +/** + * @brief Checks for error conditions for R7 response. + * @param hsd: SD handle + * @retval SD Card error state + */ +uint32_t SDMMC_GetCmdResp7(SDMMC_TypeDef *SDMMCx) +{ + uint32_t sta_reg; + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + /* Card is not SD V2.0 compliant */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + + else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) + { + /* Card is not SD V2.0 compliant */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CMDREND)) + { + /* Card is SD V2.0 compliant */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CMDREND); + } + + return SDMMC_ERROR_NONE; + +} + +/** + * @} + */ + + +/** @defgroup HAL_SDMMC_LL_Group6 Linked List functions + * @brief Linked List management functions + * +@verbatim + =============================================================================== + ##### Linked List management functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the needed functions. + +@endverbatim + * @{ + */ + +/** + * @brief Build new Linked List node. + * @param pNode: Pointer to new node to add. + * @param pNodeConf: Pointer to configuration parameters for new node to add. + * @retval Error status + */ +uint32_t SDMMC_DMALinkedList_BuildNode(SDMMC_DMALinkNodeTypeDef *pNode, SDMMC_DMALinkNodeConfTypeDef *pNodeConf) +{ + + if ((pNode == NULL) || (pNodeConf == NULL)) + { + return SDMMC_ERROR_INVALID_PARAMETER; + } + /* Configure the Link Node registers*/ + pNode->IDMABASER = pNodeConf->BufferAddress; + pNode->IDMABSIZE = pNodeConf->BufferSize; + pNode->IDMALAR = SDMMC_IDMALAR_ULS | SDMMC_IDMALAR_ABR; + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Insert new Linked List node. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @param pPrevNode: Pointer to previous node . + * @param pNewNode: Pointer to new node to add. + * @retval Error status + */ +uint32_t SDMMC_DMALinkedList_InsertNode(SDMMC_DMALinkedListTypeDef *pLinkedList, SDMMC_DMALinkNodeTypeDef *pPrevNode, + SDMMC_DMALinkNodeTypeDef *pNode) +{ + uint32_t link_list_offset; + uint32_t node_address = (uint32_t) pNode; + + /* First Node */ + if (pLinkedList->NodesCounter == 0U) + { + + pLinkedList->pHeadNode = pNode; + pLinkedList->pTailNode = pNode; + pLinkedList->NodesCounter = 1U; + + } + else if (pPrevNode == pLinkedList->pTailNode) + { + if (pNode <= pLinkedList->pHeadNode) + { + /* Node Address should greater than Head Node Address*/ + return SDMMC_ERROR_INVALID_PARAMETER; + } + + /*Last Node, no next node */ + MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_ULA, 0U); + + /*link Prev node with new one */ + MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_ULA, SDMMC_IDMALAR_ULA); + MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_IDMALA, (node_address - (uint32_t)pLinkedList->pHeadNode)); + + pLinkedList->NodesCounter ++; + pLinkedList->pTailNode = pNode; + + } + else + { + + if (pNode <= pLinkedList->pHeadNode) + { + /* Node Address should greater than Head Node Address*/ + return SDMMC_ERROR_INVALID_PARAMETER; + } + + /*link New node with Next one */ + link_list_offset = pNode->IDMALAR; + MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_IDMALA, link_list_offset); + + /*link Prev node with new one */ + MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_ULA, SDMMC_IDMALAR_ULA); + MODIFY_REG(pPrevNode->IDMALAR, SDMMC_IDMALAR_IDMALA, (node_address - (uint32_t)pLinkedList->pHeadNode)); + + pLinkedList->NodesCounter ++; + + } + return SDMMC_ERROR_NONE; +} + +/** + * @brief Remove node from the Linked List. + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @param pNode: Pointer to new node to add. + * @retval Error status + */ +uint32_t SDMMC_DMALinkedList_RemoveNode(SDMMC_DMALinkedListTypeDef *pLinkedList, SDMMC_DMALinkNodeTypeDef *pNode) +{ + uint32_t count = 0U; + uint32_t linked_list_offset; + SDMMC_DMALinkNodeTypeDef *prev_node = NULL; + SDMMC_DMALinkNodeTypeDef *curr_node ; + + /* First Node */ + if (pLinkedList->NodesCounter == 0U) + { + + return SDMMC_ERROR_INVALID_PARAMETER; + } + else + { + curr_node = pLinkedList->pHeadNode; + while ((curr_node != pNode) && (count <= pLinkedList->NodesCounter)) + { + prev_node = curr_node; + curr_node = (SDMMC_DMALinkNodeTypeDef *)((prev_node->IDMALAR & SDMMC_IDMALAR_IDMALA) + + (uint32_t)pLinkedList->pHeadNode); + count++; + } + + if ((count == 0U) || (count > pLinkedList->NodesCounter)) + { + /* Node not found in the linked list */ + return SDMMC_ERROR_INVALID_PARAMETER; + } + + pLinkedList->NodesCounter--; + + if (pLinkedList->NodesCounter == 0U) + { + pLinkedList->pHeadNode = 0U; + pLinkedList->pTailNode = 0U; + } + else + { + /*link prev node with next one */ + linked_list_offset = curr_node->IDMALAR; + MODIFY_REG(prev_node->IDMALAR, SDMMC_IDMALAR_IDMALA, linked_list_offset); + /* Configure the new Link Node registers*/ + pNode->IDMALAR |= linked_list_offset; + + pLinkedList->pTailNode = prev_node; + } + } + return SDMMC_ERROR_NONE; +} + +/** + * @brief Lock Linked List Node + * @param pNode: Pointer to node to lock. + * @retval Error status + + */ +uint32_t SDMMC_DMALinkedList_LockNode(SDMMC_DMALinkNodeTypeDef *pNode) +{ + + if (pNode == NULL) + { + return SDMMC_ERROR_INVALID_PARAMETER; + } + + MODIFY_REG(pNode->IDMALAR, SDMMC_IDMALAR_ABR, 0U); + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Unlock Linked List Node + * @param pNode: Pointer to node to unlock. + * @retval Error status + + */ +uint32_t SDMMC_DMALinkedList_UnlockNode(SDMMC_DMALinkNodeTypeDef *pNode) +{ + + if (pNode == NULL) + { + return SDMMC_ERROR_INVALID_PARAMETER; + } + + MODIFY_REG(pNode->IDMALAR, SDMMC_IDMALAR_ABR, SDMMC_IDMALAR_ABR); + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Enable Linked List circular mode + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @retval Error status + + */ +uint32_t SDMMC_DMALinkedList_EnableCircularMode(SDMMC_DMALinkedListTypeDef *pLinkedList) +{ + + if (pLinkedList == NULL) + { + return SDMMC_ERROR_INVALID_PARAMETER; + } + + MODIFY_REG(pLinkedList->pTailNode->IDMALAR, SDMMC_IDMALAR_ULA | SDMMC_IDMALAR_IDMALA, SDMMC_IDMALAR_ULA); + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Disable DMA Linked List Circular mode + * @param pLinkedList: Pointer to the linkedlist that contains transfer nodes + * @retval Error status + */ +uint32_t SDMMC_DMALinkedList_DisableCircularMode(SDMMC_DMALinkedListTypeDef *pLinkedList) +{ + + if (pLinkedList == NULL) + { + return SDMMC_ERROR_INVALID_PARAMETER; + } + + MODIFY_REG(pLinkedList->pTailNode->IDMALAR, SDMMC_IDMALAR_ULA, 0U); + + return SDMMC_ERROR_NONE; +} + +/** + * @} + */ + + +/* Private function ----------------------------------------------------------*/ +/** @addtogroup SD_Private_Functions + * @{ + */ + +/** + * @brief Checks for error conditions for CMD0. + * @param hsd: SD handle + * @retval SD Card error state + */ +static uint32_t SDMMC_GetCmdError(SDMMC_TypeDef *SDMMCx) +{ + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + + } while (!__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CMDSENT)); + + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + + return SDMMC_ERROR_NONE; +} + +/** + * @} + */ + +#endif /* HAL_SD_MODULE_ENABLED || HAL_MMC_MODULE_ENABLED */ +#endif /* SDMMC1 || SDMMC2 */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_spi.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_spi.c index 954ec8a40..a9318fad7 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_spi.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_spi.c @@ -1,751 +1,751 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_spi.c - * @author MCD Application Team - * @brief SPI LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_spi.h" -#include "stm32h7rsxx_ll_bus.h" -#include "stm32h7rsxx_ll_rcc.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6) - -/** @addtogroup SPI_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup SPI_LL_Private_Macros - * @{ - */ - -#define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) || \ - ((__VALUE__) == LL_SPI_MODE_SLAVE)) - -#define IS_LL_SPI_SS_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_SS_IDLENESS_00CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_01CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_02CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_03CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_04CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_05CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_06CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_07CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_08CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_09CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_10CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_11CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_12CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_13CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_14CYCLE) || \ - ((__VALUE__) == LL_SPI_SS_IDLENESS_15CYCLE)) - -#define IS_LL_SPI_ID_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_ID_IDLENESS_00CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_01CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_02CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_03CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_04CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_05CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_06CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_07CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_08CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_09CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_10CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_11CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_12CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_13CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_14CYCLE) || \ - ((__VALUE__) == LL_SPI_ID_IDLENESS_15CYCLE)) - -#define IS_LL_SPI_TXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ZERO_PATTERN) || \ - ((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ONES_PATTERN)) - -#define IS_LL_SPI_RXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ZERO_PATTERN) || \ - ((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ONES_PATTERN)) - -#define IS_LL_SPI_UDR_CONFIG_REGISTER(__VALUE__) (((__VALUE__) == LL_SPI_UDR_CONFIG_REGISTER_PATTERN) || \ - ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_RECEIVED) || \ - ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_TRANSMITTED)) - -#define IS_LL_SPI_UDR_DETECT_BEGIN_DATA(__VALUE__) (((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_DATA_FRAME) || \ - ((__VALUE__) == LL_SPI_UDR_DETECT_END_DATA_FRAME) || \ - ((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_ACTIVE_NSS)) - -#define IS_LL_SPI_PROTOCOL(__VALUE__) (((__VALUE__) == LL_SPI_PROTOCOL_MOTOROLA) || \ - ((__VALUE__) == LL_SPI_PROTOCOL_TI)) - -#define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) || \ - ((__VALUE__) == LL_SPI_PHASE_2EDGE)) - -#define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) || \ - ((__VALUE__) == LL_SPI_POLARITY_HIGH)) - -#define IS_LL_SPI_BAUDRATEPRESCALER(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_BYPASS) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) || \ - ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256)) - -#define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) || \ - ((__VALUE__) == LL_SPI_MSB_FIRST)) - -#define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) || \ - ((__VALUE__) == LL_SPI_SIMPLEX_TX) || \ - ((__VALUE__) == LL_SPI_SIMPLEX_RX) || \ - ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) || \ - ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX)) - -#define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_4BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_5BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_6BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_7BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_9BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_10BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_11BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_12BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_13BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_14BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_15BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_17BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_18BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_19BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_20BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_21BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_22BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_23BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_24BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_25BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_26BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_27BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_28BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_29BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_30BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_31BIT) || \ - ((__VALUE__) == LL_SPI_DATAWIDTH_32BIT)) - -#define IS_LL_SPI_FIFO_TH(__VALUE__) (((__VALUE__) == LL_SPI_FIFO_TH_01DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_02DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_03DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_04DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_05DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_06DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_07DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_08DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_09DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_10DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_11DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_12DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_13DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_14DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_15DATA) || \ - ((__VALUE__) == LL_SPI_FIFO_TH_16DATA)) - -#define IS_LL_SPI_CRC(__VALUE__) (((__VALUE__) == LL_SPI_CRC_4BIT) || \ - ((__VALUE__) == LL_SPI_CRC_5BIT) || \ - ((__VALUE__) == LL_SPI_CRC_6BIT) || \ - ((__VALUE__) == LL_SPI_CRC_7BIT) || \ - ((__VALUE__) == LL_SPI_CRC_8BIT) || \ - ((__VALUE__) == LL_SPI_CRC_9BIT) || \ - ((__VALUE__) == LL_SPI_CRC_10BIT) || \ - ((__VALUE__) == LL_SPI_CRC_11BIT) || \ - ((__VALUE__) == LL_SPI_CRC_12BIT) || \ - ((__VALUE__) == LL_SPI_CRC_13BIT) || \ - ((__VALUE__) == LL_SPI_CRC_14BIT) || \ - ((__VALUE__) == LL_SPI_CRC_15BIT) || \ - ((__VALUE__) == LL_SPI_CRC_16BIT) || \ - ((__VALUE__) == LL_SPI_CRC_17BIT) || \ - ((__VALUE__) == LL_SPI_CRC_18BIT) || \ - ((__VALUE__) == LL_SPI_CRC_19BIT) || \ - ((__VALUE__) == LL_SPI_CRC_20BIT) || \ - ((__VALUE__) == LL_SPI_CRC_21BIT) || \ - ((__VALUE__) == LL_SPI_CRC_22BIT) || \ - ((__VALUE__) == LL_SPI_CRC_23BIT) || \ - ((__VALUE__) == LL_SPI_CRC_24BIT) || \ - ((__VALUE__) == LL_SPI_CRC_25BIT) || \ - ((__VALUE__) == LL_SPI_CRC_26BIT) || \ - ((__VALUE__) == LL_SPI_CRC_27BIT) || \ - ((__VALUE__) == LL_SPI_CRC_28BIT) || \ - ((__VALUE__) == LL_SPI_CRC_29BIT) || \ - ((__VALUE__) == LL_SPI_CRC_30BIT) || \ - ((__VALUE__) == LL_SPI_CRC_31BIT) || \ - ((__VALUE__) == LL_SPI_CRC_32BIT)) - -#define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) || \ - ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) || \ - ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT)) - -#define IS_LL_SPI_RX_FIFO(__VALUE__) (((__VALUE__) == LL_SPI_RX_FIFO_0PACKET) || \ - ((__VALUE__) == LL_SPI_RX_FIFO_1PACKET) || \ - ((__VALUE__) == LL_SPI_RX_FIFO_2PACKET) || \ - ((__VALUE__) == LL_SPI_RX_FIFO_3PACKET)) - -#define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) || \ - ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE)) - -#define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1UL) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup SPI_LL_Exported_Functions - * @{ - */ - -/** @addtogroup SPI_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the SPI registers to their default reset values. - * @param SPIx SPI Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: SPI registers are de-initialized - * - ERROR: SPI registers are not de-initialized - */ -ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_SPI_ALL_INSTANCE(SPIx)); - -#if defined(SPI1) - if (SPIx == SPI1) - { - /* Force reset of SPI clock */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1); - - /* Release reset of SPI clock */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1); - - /* Update the return status */ - status = SUCCESS; - } -#endif /* SPI1 */ -#if defined(SPI2) - if (SPIx == SPI2) - { - /* Force reset of SPI clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2); - - /* Release reset of SPI clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2); - - /* Update the return status */ - status = SUCCESS; - } -#endif /* SPI2 */ -#if defined(SPI3) - if (SPIx == SPI3) - { - /* Force reset of SPI clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3); - - /* Release reset of SPI clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3); - - /* Update the return status */ - status = SUCCESS; - } -#endif /* SPI3 */ -#if defined(SPI4) - if (SPIx == SPI4) - { - /* Force reset of SPI clock */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI4); - - /* Release reset of SPI clock */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI4); - - /* Update the return status */ - status = SUCCESS; - } -#endif /* SPI4 */ -#if defined(SPI5) - if (SPIx == SPI5) - { - /* Force reset of SPI clock */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI5); - - /* Release reset of SPI clock */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI5); - - /* Update the return status */ - status = SUCCESS; - } -#endif /* SPI5 */ -#if defined(SPI6) - if (SPIx == SPI6) - { - /* Force reset of SPI clock */ - LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_SPI6); - - /* Release reset of SPI clock */ - LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_SPI6); - - /* Update the return status */ - status = SUCCESS; - } -#endif /* SPI6 */ - - return status; -} - -/** - * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. - * @note As some bits in SPI configuration registers can only be written when the SPI is disabled - * (SPI_CR1_SPE bit =0), SPI IP should be in disabled state prior calling this function. - * Otherwise, ERROR result will be returned. - * @param SPIx SPI Instance - * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure - * @retval An ErrorStatus enumeration value. (Return always SUCCESS) - */ -ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct) -{ - ErrorStatus status = ERROR; - uint32_t tmp_nss; - uint32_t tmp_mode; - uint32_t tmp_nss_polarity; - - /* Check the SPI Instance SPIx*/ - assert_param(IS_SPI_ALL_INSTANCE(SPIx)); - - /* Check the SPI parameters from SPI_InitStruct*/ - assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection)); - assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode)); - assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth)); - assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity)); - assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase)); - assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS)); - assert_param(IS_LL_SPI_BAUDRATEPRESCALER(SPI_InitStruct->BaudRate)); - assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder)); - assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation)); - - /* Check the SPI instance is not enabled */ - if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL) - { - /*---------------------------- SPIx CFG1 Configuration ------------------------ - * Configure SPIx CFG1 with parameters: - * - Master Baud Rate : SPI_CFG1_MBR[2:0] bits & SPI_CFG1_BPASS bit - * - CRC Computation Enable : SPI_CFG1_CRCEN bit - * - Length of data frame : SPI_CFG1_DSIZE[4:0] bits - */ - MODIFY_REG(SPIx->CFG1, SPI_CFG1_BPASS | SPI_CFG1_MBR | SPI_CFG1_CRCEN | SPI_CFG1_DSIZE, - SPI_InitStruct->BaudRate | SPI_InitStruct->CRCCalculation | SPI_InitStruct->DataWidth); - - tmp_nss = SPI_InitStruct->NSS; - tmp_mode = SPI_InitStruct->Mode; - tmp_nss_polarity = LL_SPI_GetNSSPolarity(SPIx); - - /* Checks to setup Internal SS signal level and avoid a MODF Error */ - if ((tmp_nss == LL_SPI_NSS_SOFT) && (((tmp_nss_polarity == LL_SPI_NSS_POLARITY_LOW) && \ - (tmp_mode == LL_SPI_MODE_MASTER)) || \ - ((tmp_nss_polarity == LL_SPI_NSS_POLARITY_HIGH) && \ - (tmp_mode == LL_SPI_MODE_SLAVE)))) - { - LL_SPI_SetInternalSSLevel(SPIx, LL_SPI_SS_LEVEL_HIGH); - } - - /*---------------------------- SPIx CFG2 Configuration ------------------------ - * Configure SPIx CFG2 with parameters: - * - NSS management : SPI_CFG2_SSM, SPI_CFG2_SSOE bits - * - ClockPolarity : SPI_CFG2_CPOL bit - * - ClockPhase : SPI_CFG2_CPHA bit - * - BitOrder : SPI_CFG2_LSBFRST bit - * - Master/Slave Mode : SPI_CFG2_MASTER bit - * - SPI Mode : SPI_CFG2_COMM[1:0] bits - */ - MODIFY_REG(SPIx->CFG2, SPI_CFG2_SSM | SPI_CFG2_SSOE | - SPI_CFG2_CPOL | SPI_CFG2_CPHA | - SPI_CFG2_LSBFRST | SPI_CFG2_MASTER | SPI_CFG2_COMM, - SPI_InitStruct->NSS | SPI_InitStruct->ClockPolarity | - SPI_InitStruct->ClockPhase | SPI_InitStruct->BitOrder | - SPI_InitStruct->Mode | (SPI_InitStruct->TransferDirection & SPI_CFG2_COMM)); - - /*---------------------------- SPIx CR1 Configuration ------------------------ - * Configure SPIx CR1 with parameter: - * - Half Duplex Direction : SPI_CR1_HDDIR bit - */ - MODIFY_REG(SPIx->CR1, SPI_CR1_HDDIR, SPI_InitStruct->TransferDirection & SPI_CR1_HDDIR); - - /*---------------------------- SPIx CRCPOLY Configuration ---------------------- - * Configure SPIx CRCPOLY with parameter: - * - CRCPoly : CRCPOLY[31:0] bits - */ - if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE) - { - assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly)); - LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly); - } - - /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ - CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD); - - status = SUCCESS; - } - - return status; -} - -/** - * @brief Set each @ref LL_SPI_InitTypeDef field to default value. - * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) -{ - /* Set SPI_InitStruct fields to default values */ - SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX; - SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE; - SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT; - SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW; - SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE; - SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT; - SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2; - SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST; - SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE; - SPI_InitStruct->CRCPoly = 7UL; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -/** @addtogroup I2S_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup I2S_LL_Private_Constants I2S Private Constants - * @{ - */ -/* I2S registers Masks */ -#define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \ - SPI_I2SCFGR_DATFMT | SPI_I2SCFGR_CKPOL | \ - SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_MCKOE | \ - SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD ) - -/** - * @} - */ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup I2S_LL_Private_Macros I2S Private Macros - * @{ - */ - -#define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) || \ - ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) || \ - ((__VALUE__) == LL_I2S_DATAFORMAT_24B) || \ - ((__VALUE__) == LL_I2S_DATAFORMAT_24B_LEFT_ALIGNED) || \ - ((__VALUE__) == LL_I2S_DATAFORMAT_32B)) - -#define IS_LL_I2S_CHANNEL_LENGTH_TYPE (__VALUE__) (((__VALUE__) == LL_I2S_SLAVE_VARIABLE_CH_LENGTH) || \ - ((__VALUE__) == LL_I2S_SLAVE_FIXED_CH_LENGTH)) - -#define IS_LL_I2S_CKPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) || \ - ((__VALUE__) == LL_I2S_POLARITY_HIGH)) - -#define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) || \ - ((__VALUE__) == LL_I2S_STANDARD_MSB) || \ - ((__VALUE__) == LL_I2S_STANDARD_LSB) || \ - ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) || \ - ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG)) - -#define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) || \ - ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) || \ - ((__VALUE__) == LL_I2S_MODE_SLAVE_FULL_DUPLEX) || \ - ((__VALUE__) == LL_I2S_MODE_MASTER_TX) || \ - ((__VALUE__) == LL_I2S_MODE_MASTER_RX) || \ - ((__VALUE__) == LL_I2S_MODE_MASTER_FULL_DUPLEX)) - -#define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) || \ - ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE)) - -#define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) && \ - ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) || \ - ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT)) - -#define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) <= 0xFFUL) - -#define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) || \ - ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD)) - -#define IS_LL_I2S_FIFO_TH (__VALUE__) (((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_01DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_02DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_03DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_04DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_05DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_06DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_07DATA) || \ - ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_08DATA)) - -#define IS_LL_I2S_BIT_ORDER(__VALUE__) (((__VALUE__) == LL_I2S_LSB_FIRST) || \ - ((__VALUE__) == LL_I2S_MSB_FIRST)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I2S_LL_Exported_Functions - * @{ - */ - -/** @addtogroup I2S_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the SPI/I2S registers to their default reset values. - * @param SPIx SPI Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: SPI registers are de-initialized - * - ERROR: SPI registers are not de-initialized - */ -ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx) -{ - return LL_SPI_DeInit(SPIx); -} - -/** - * @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct. - * @note As some bits in I2S configuration registers can only be written when the SPI is disabled - * (SPI_CR1_SPE bit =0), SPI IP should be in disabled state prior calling this function. - * Otherwise, ERROR result will be returned. - * @note I2S (SPI) source clock must be ready before calling this function. Otherwise will results - * in wrong programming. - * @param SPIx SPI Instance - * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: SPI registers are Initialized - * - ERROR: SPI registers are not Initialized - */ -ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct) -{ - uint32_t i2sdiv = 0UL; - uint32_t i2sodd = 0UL; - uint32_t packetlength = 1UL; - uint32_t ispcm = 0UL; - uint32_t tmp; - uint32_t sourceclock; - - ErrorStatus status = ERROR; - - /* Check the I2S parameters */ - assert_param(IS_I2S_ALL_INSTANCE(SPIx)); - assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode)); - assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard)); - assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); - assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput)); - assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq)); - assert_param(IS_LL_I2S_CKPOL(I2S_InitStruct->ClockPolarity)); - - /* Check that SPE bit is set to 0 in order to be sure that SPI/I2S block is disabled. - * In this case, it is useless to check if the I2SMOD bit is set to 0 because - * this bit I2SMOD only serves to select the desired mode. - */ - if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL) - { - /*---------------------------- SPIx I2SCFGR Configuration -------------------- - * Configure SPIx I2SCFGR with parameters: - * - Mode : SPI_I2SCFGR_I2SCFG[2:0] bits - * - Standard : SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits - * - DataFormat : SPI_I2SCFGR_CHLEN, SPI_I2SCFGR_DATFMT and SPI_I2SCFGR_DATLEN[1:0] bits - * - ClockPolarity : SPI_I2SCFGR_CKPOL bit - * - MCLKOutput : SPI_I2SPR_MCKOE bit - * - I2S mode : SPI_I2SCFGR_I2SMOD bit - */ - - /* Write to SPIx I2SCFGR */ - MODIFY_REG(SPIx->I2SCFGR, - I2S_I2SCFGR_CLEAR_MASK, - I2S_InitStruct->Mode | I2S_InitStruct->Standard | - I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | - I2S_InitStruct->MCLKOutput | SPI_I2SCFGR_I2SMOD); - - /*---------------------------- SPIx I2SCFGR Configuration ---------------------- - * Configure SPIx I2SCFGR with parameters: - * - AudioFreq : SPI_I2SCFGR_I2SDIV[7:0] and SPI_I2SCFGR_ODD bits - */ - - /* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv) - * else, default values are used: i2sodd = 0U, i2sdiv = 0U. - */ - if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT) - { - /* Check the frame length (For the Prescaler computing) - * Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U). - */ - if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B) - { - /* Packet length is 32 bits */ - packetlength = 2UL; - } - - /* Check if PCM standard is used */ - if ((I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_SHORT) || - (I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_LONG)) - { - ispcm = 1UL; - } - - /* Get the I2S (SPI) source clock value */ - if (SPIx == SPI1) - { - sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI1_CLKSOURCE); - } - else if ((SPIx == SPI2) || (SPIx == SPI3)) - { - sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI23_CLKSOURCE); - } - else /* SPI6 */ - { - sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI6_CLKSOURCE); - } - - /* Compute the Real divider depending on the MCLK output state with a fixed point */ - if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE) - { - /* MCLK output is enabled */ - tmp = (((sourceclock / (256UL >> ispcm)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL; - } - else - { - /* MCLK output is disabled */ - tmp = (((sourceclock / ((32UL >> ispcm) * packetlength)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL; - } - - /* Remove the fixed point */ - tmp = tmp / 16UL; - - /* Check the parity of the divider */ - i2sodd = tmp & 0x1UL; - - /* Compute the i2sdiv prescaler */ - i2sdiv = tmp / 2UL; - } - - /* Test if the obtain values are forbidden or out of range */ - if (((i2sodd == 1UL) && (i2sdiv == 1UL)) || (i2sdiv > 0xFFUL)) - { - /* Set the default values */ - i2sdiv = 0UL; - i2sodd = 0UL; - } - - /* Write to SPIx I2SCFGR register the computed value */ - MODIFY_REG(SPIx->I2SCFGR, - SPI_I2SCFGR_ODD | SPI_I2SCFGR_I2SDIV, - (i2sodd << SPI_I2SCFGR_ODD_Pos) | (i2sdiv << SPI_I2SCFGR_I2SDIV_Pos)); - - status = SUCCESS; - } - - return status; -} - -/** - * @brief Set each @ref LL_I2S_InitTypeDef field to default value. - * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct) -{ - /*--------------- Reset I2S init structure parameters values -----------------*/ - I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX; - I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS; - I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B; - I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE; - I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT; - I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW; -} - -/** - * @brief Set linear and parity prescaler. - * @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n - * Check Audio frequency table and formulas inside Reference Manual (SPI/I2S). - * @param SPIx SPI Instance - * @param PrescalerLinear Value between Min_Data=0x00 and Max_Data=0xFF - * @note PrescalerLinear '1' is not authorized with parity LL_I2S_PRESCALER_PARITY_ODD - * @param PrescalerParity This parameter can be one of the following values: - * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN - * @arg @ref LL_I2S_PRESCALER_PARITY_ODD - * @retval None - */ -void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity) -{ - /* Check the I2S parameters */ - assert_param(IS_I2S_ALL_INSTANCE(SPIx)); - assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear)); - assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity)); - - /* Write to SPIx I2SPR */ - MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SDIV | SPI_I2SCFGR_ODD, (PrescalerLinear << SPI_I2SCFGR_I2SDIV_Pos) | - (PrescalerParity << SPI_I2SCFGR_ODD_Pos)); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6) */ - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_spi.c + * @author MCD Application Team + * @brief SPI LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_spi.h" +#include "stm32h7rsxx_ll_bus.h" +#include "stm32h7rsxx_ll_rcc.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6) + +/** @addtogroup SPI_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup SPI_LL_Private_Macros + * @{ + */ + +#define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) || \ + ((__VALUE__) == LL_SPI_MODE_SLAVE)) + +#define IS_LL_SPI_SS_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_SS_IDLENESS_00CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_01CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_02CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_03CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_04CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_05CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_06CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_07CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_08CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_09CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_10CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_11CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_12CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_13CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_14CYCLE) || \ + ((__VALUE__) == LL_SPI_SS_IDLENESS_15CYCLE)) + +#define IS_LL_SPI_ID_IDLENESS(__VALUE__) (((__VALUE__) == LL_SPI_ID_IDLENESS_00CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_01CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_02CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_03CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_04CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_05CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_06CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_07CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_08CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_09CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_10CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_11CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_12CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_13CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_14CYCLE) || \ + ((__VALUE__) == LL_SPI_ID_IDLENESS_15CYCLE)) + +#define IS_LL_SPI_TXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ZERO_PATTERN) || \ + ((__VALUE__) == LL_SPI_TXCRCINIT_ALL_ONES_PATTERN)) + +#define IS_LL_SPI_RXCRCINIT_PATTERN(__VALUE__) (((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ZERO_PATTERN) || \ + ((__VALUE__) == LL_SPI_RXCRCINIT_ALL_ONES_PATTERN)) + +#define IS_LL_SPI_UDR_CONFIG_REGISTER(__VALUE__) (((__VALUE__) == LL_SPI_UDR_CONFIG_REGISTER_PATTERN) || \ + ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_RECEIVED) || \ + ((__VALUE__) == LL_SPI_UDR_CONFIG_LAST_TRANSMITTED)) + +#define IS_LL_SPI_UDR_DETECT_BEGIN_DATA(__VALUE__) (((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_DATA_FRAME) || \ + ((__VALUE__) == LL_SPI_UDR_DETECT_END_DATA_FRAME) || \ + ((__VALUE__) == LL_SPI_UDR_DETECT_BEGIN_ACTIVE_NSS)) + +#define IS_LL_SPI_PROTOCOL(__VALUE__) (((__VALUE__) == LL_SPI_PROTOCOL_MOTOROLA) || \ + ((__VALUE__) == LL_SPI_PROTOCOL_TI)) + +#define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) || \ + ((__VALUE__) == LL_SPI_PHASE_2EDGE)) + +#define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) || \ + ((__VALUE__) == LL_SPI_POLARITY_HIGH)) + +#define IS_LL_SPI_BAUDRATEPRESCALER(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_BYPASS) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) || \ + ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256)) + +#define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) || \ + ((__VALUE__) == LL_SPI_MSB_FIRST)) + +#define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) || \ + ((__VALUE__) == LL_SPI_SIMPLEX_TX) || \ + ((__VALUE__) == LL_SPI_SIMPLEX_RX) || \ + ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) || \ + ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX)) + +#define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_4BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_5BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_6BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_7BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_9BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_10BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_11BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_12BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_13BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_14BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_15BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_17BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_18BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_19BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_20BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_21BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_22BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_23BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_24BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_25BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_26BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_27BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_28BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_29BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_30BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_31BIT) || \ + ((__VALUE__) == LL_SPI_DATAWIDTH_32BIT)) + +#define IS_LL_SPI_FIFO_TH(__VALUE__) (((__VALUE__) == LL_SPI_FIFO_TH_01DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_02DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_03DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_04DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_05DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_06DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_07DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_08DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_09DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_10DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_11DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_12DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_13DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_14DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_15DATA) || \ + ((__VALUE__) == LL_SPI_FIFO_TH_16DATA)) + +#define IS_LL_SPI_CRC(__VALUE__) (((__VALUE__) == LL_SPI_CRC_4BIT) || \ + ((__VALUE__) == LL_SPI_CRC_5BIT) || \ + ((__VALUE__) == LL_SPI_CRC_6BIT) || \ + ((__VALUE__) == LL_SPI_CRC_7BIT) || \ + ((__VALUE__) == LL_SPI_CRC_8BIT) || \ + ((__VALUE__) == LL_SPI_CRC_9BIT) || \ + ((__VALUE__) == LL_SPI_CRC_10BIT) || \ + ((__VALUE__) == LL_SPI_CRC_11BIT) || \ + ((__VALUE__) == LL_SPI_CRC_12BIT) || \ + ((__VALUE__) == LL_SPI_CRC_13BIT) || \ + ((__VALUE__) == LL_SPI_CRC_14BIT) || \ + ((__VALUE__) == LL_SPI_CRC_15BIT) || \ + ((__VALUE__) == LL_SPI_CRC_16BIT) || \ + ((__VALUE__) == LL_SPI_CRC_17BIT) || \ + ((__VALUE__) == LL_SPI_CRC_18BIT) || \ + ((__VALUE__) == LL_SPI_CRC_19BIT) || \ + ((__VALUE__) == LL_SPI_CRC_20BIT) || \ + ((__VALUE__) == LL_SPI_CRC_21BIT) || \ + ((__VALUE__) == LL_SPI_CRC_22BIT) || \ + ((__VALUE__) == LL_SPI_CRC_23BIT) || \ + ((__VALUE__) == LL_SPI_CRC_24BIT) || \ + ((__VALUE__) == LL_SPI_CRC_25BIT) || \ + ((__VALUE__) == LL_SPI_CRC_26BIT) || \ + ((__VALUE__) == LL_SPI_CRC_27BIT) || \ + ((__VALUE__) == LL_SPI_CRC_28BIT) || \ + ((__VALUE__) == LL_SPI_CRC_29BIT) || \ + ((__VALUE__) == LL_SPI_CRC_30BIT) || \ + ((__VALUE__) == LL_SPI_CRC_31BIT) || \ + ((__VALUE__) == LL_SPI_CRC_32BIT)) + +#define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) || \ + ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) || \ + ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT)) + +#define IS_LL_SPI_RX_FIFO(__VALUE__) (((__VALUE__) == LL_SPI_RX_FIFO_0PACKET) || \ + ((__VALUE__) == LL_SPI_RX_FIFO_1PACKET) || \ + ((__VALUE__) == LL_SPI_RX_FIFO_2PACKET) || \ + ((__VALUE__) == LL_SPI_RX_FIFO_3PACKET)) + +#define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) || \ + ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE)) + +#define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1UL) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SPI_LL_Exported_Functions + * @{ + */ + +/** @addtogroup SPI_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the SPI registers to their default reset values. + * @param SPIx SPI Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: SPI registers are de-initialized + * - ERROR: SPI registers are not de-initialized + */ +ErrorStatus LL_SPI_DeInit(const SPI_TypeDef *SPIx) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + assert_param(IS_SPI_ALL_INSTANCE(SPIx)); + +#if defined(SPI1) + if (SPIx == SPI1) + { + /* Force reset of SPI clock */ + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1); + + /* Release reset of SPI clock */ + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1); + + /* Update the return status */ + status = SUCCESS; + } +#endif /* SPI1 */ +#if defined(SPI2) + if (SPIx == SPI2) + { + /* Force reset of SPI clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2); + + /* Release reset of SPI clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2); + + /* Update the return status */ + status = SUCCESS; + } +#endif /* SPI2 */ +#if defined(SPI3) + if (SPIx == SPI3) + { + /* Force reset of SPI clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3); + + /* Release reset of SPI clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3); + + /* Update the return status */ + status = SUCCESS; + } +#endif /* SPI3 */ +#if defined(SPI4) + if (SPIx == SPI4) + { + /* Force reset of SPI clock */ + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI4); + + /* Release reset of SPI clock */ + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI4); + + /* Update the return status */ + status = SUCCESS; + } +#endif /* SPI4 */ +#if defined(SPI5) + if (SPIx == SPI5) + { + /* Force reset of SPI clock */ + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI5); + + /* Release reset of SPI clock */ + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI5); + + /* Update the return status */ + status = SUCCESS; + } +#endif /* SPI5 */ +#if defined(SPI6) + if (SPIx == SPI6) + { + /* Force reset of SPI clock */ + LL_APB4_GRP1_ForceReset(LL_APB4_GRP1_PERIPH_SPI6); + + /* Release reset of SPI clock */ + LL_APB4_GRP1_ReleaseReset(LL_APB4_GRP1_PERIPH_SPI6); + + /* Update the return status */ + status = SUCCESS; + } +#endif /* SPI6 */ + + return status; +} + +/** + * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. + * @note As some bits in SPI configuration registers can only be written when the SPI is disabled + * (SPI_CR1_SPE bit =0), SPI IP should be in disabled state prior calling this function. + * Otherwise, ERROR result will be returned. + * @param SPIx SPI Instance + * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure + * @retval An ErrorStatus enumeration value. (Return always SUCCESS) + */ +ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct) +{ + ErrorStatus status = ERROR; + uint32_t tmp_nss; + uint32_t tmp_mode; + uint32_t tmp_nss_polarity; + + /* Check the SPI Instance SPIx*/ + assert_param(IS_SPI_ALL_INSTANCE(SPIx)); + + /* Check the SPI parameters from SPI_InitStruct*/ + assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection)); + assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode)); + assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth)); + assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity)); + assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase)); + assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS)); + assert_param(IS_LL_SPI_BAUDRATEPRESCALER(SPI_InitStruct->BaudRate)); + assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder)); + assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation)); + + /* Check the SPI instance is not enabled */ + if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL) + { + /*---------------------------- SPIx CFG1 Configuration ------------------------ + * Configure SPIx CFG1 with parameters: + * - Master Baud Rate : SPI_CFG1_MBR[2:0] bits & SPI_CFG1_BPASS bit + * - CRC Computation Enable : SPI_CFG1_CRCEN bit + * - Length of data frame : SPI_CFG1_DSIZE[4:0] bits + */ + MODIFY_REG(SPIx->CFG1, SPI_CFG1_BPASS | SPI_CFG1_MBR | SPI_CFG1_CRCEN | SPI_CFG1_DSIZE, + SPI_InitStruct->BaudRate | SPI_InitStruct->CRCCalculation | SPI_InitStruct->DataWidth); + + tmp_nss = SPI_InitStruct->NSS; + tmp_mode = SPI_InitStruct->Mode; + tmp_nss_polarity = LL_SPI_GetNSSPolarity(SPIx); + + /* Checks to setup Internal SS signal level and avoid a MODF Error */ + if ((tmp_nss == LL_SPI_NSS_SOFT) && (((tmp_nss_polarity == LL_SPI_NSS_POLARITY_LOW) && \ + (tmp_mode == LL_SPI_MODE_MASTER)) || \ + ((tmp_nss_polarity == LL_SPI_NSS_POLARITY_HIGH) && \ + (tmp_mode == LL_SPI_MODE_SLAVE)))) + { + LL_SPI_SetInternalSSLevel(SPIx, LL_SPI_SS_LEVEL_HIGH); + } + + /*---------------------------- SPIx CFG2 Configuration ------------------------ + * Configure SPIx CFG2 with parameters: + * - NSS management : SPI_CFG2_SSM, SPI_CFG2_SSOE bits + * - ClockPolarity : SPI_CFG2_CPOL bit + * - ClockPhase : SPI_CFG2_CPHA bit + * - BitOrder : SPI_CFG2_LSBFRST bit + * - Master/Slave Mode : SPI_CFG2_MASTER bit + * - SPI Mode : SPI_CFG2_COMM[1:0] bits + */ + MODIFY_REG(SPIx->CFG2, SPI_CFG2_SSM | SPI_CFG2_SSOE | + SPI_CFG2_CPOL | SPI_CFG2_CPHA | + SPI_CFG2_LSBFRST | SPI_CFG2_MASTER | SPI_CFG2_COMM, + SPI_InitStruct->NSS | SPI_InitStruct->ClockPolarity | + SPI_InitStruct->ClockPhase | SPI_InitStruct->BitOrder | + SPI_InitStruct->Mode | (SPI_InitStruct->TransferDirection & SPI_CFG2_COMM)); + + /*---------------------------- SPIx CR1 Configuration ------------------------ + * Configure SPIx CR1 with parameter: + * - Half Duplex Direction : SPI_CR1_HDDIR bit + */ + MODIFY_REG(SPIx->CR1, SPI_CR1_HDDIR, SPI_InitStruct->TransferDirection & SPI_CR1_HDDIR); + + /*---------------------------- SPIx CRCPOLY Configuration ---------------------- + * Configure SPIx CRCPOLY with parameter: + * - CRCPoly : CRCPOLY[31:0] bits + */ + if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE) + { + assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly)); + LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly); + } + + /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ + CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD); + + status = SUCCESS; + } + + return status; +} + +/** + * @brief Set each @ref LL_SPI_InitTypeDef field to default value. + * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) +{ + /* Set SPI_InitStruct fields to default values */ + SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX; + SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE; + SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT; + SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW; + SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE; + SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT; + SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2; + SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST; + SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE; + SPI_InitStruct->CRCPoly = 7UL; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +/** @addtogroup I2S_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @defgroup I2S_LL_Private_Constants I2S Private Constants + * @{ + */ +/* I2S registers Masks */ +#define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \ + SPI_I2SCFGR_DATFMT | SPI_I2SCFGR_CKPOL | \ + SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_MCKOE | \ + SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD ) + +/** + * @} + */ +/* Private macros ------------------------------------------------------------*/ +/** @defgroup I2S_LL_Private_Macros I2S Private Macros + * @{ + */ + +#define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) || \ + ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) || \ + ((__VALUE__) == LL_I2S_DATAFORMAT_24B) || \ + ((__VALUE__) == LL_I2S_DATAFORMAT_24B_LEFT_ALIGNED) || \ + ((__VALUE__) == LL_I2S_DATAFORMAT_32B)) + +#define IS_LL_I2S_CHANNEL_LENGTH_TYPE (__VALUE__) (((__VALUE__) == LL_I2S_SLAVE_VARIABLE_CH_LENGTH) || \ + ((__VALUE__) == LL_I2S_SLAVE_FIXED_CH_LENGTH)) + +#define IS_LL_I2S_CKPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) || \ + ((__VALUE__) == LL_I2S_POLARITY_HIGH)) + +#define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) || \ + ((__VALUE__) == LL_I2S_STANDARD_MSB) || \ + ((__VALUE__) == LL_I2S_STANDARD_LSB) || \ + ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) || \ + ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG)) + +#define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) || \ + ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) || \ + ((__VALUE__) == LL_I2S_MODE_SLAVE_FULL_DUPLEX) || \ + ((__VALUE__) == LL_I2S_MODE_MASTER_TX) || \ + ((__VALUE__) == LL_I2S_MODE_MASTER_RX) || \ + ((__VALUE__) == LL_I2S_MODE_MASTER_FULL_DUPLEX)) + +#define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) || \ + ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE)) + +#define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) && \ + ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) || \ + ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT)) + +#define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) <= 0xFFUL) + +#define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) || \ + ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD)) + +#define IS_LL_I2S_FIFO_TH (__VALUE__) (((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_01DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_02DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_03DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_04DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_05DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_06DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_07DATA) || \ + ((__VALUE__) == LL_I2S_LL_I2S_FIFO_TH_08DATA)) + +#define IS_LL_I2S_BIT_ORDER(__VALUE__) (((__VALUE__) == LL_I2S_LSB_FIRST) || \ + ((__VALUE__) == LL_I2S_MSB_FIRST)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup I2S_LL_Exported_Functions + * @{ + */ + +/** @addtogroup I2S_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the SPI/I2S registers to their default reset values. + * @param SPIx SPI Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: SPI registers are de-initialized + * - ERROR: SPI registers are not de-initialized + */ +ErrorStatus LL_I2S_DeInit(const SPI_TypeDef *SPIx) +{ + return LL_SPI_DeInit(SPIx); +} + +/** + * @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct. + * @note As some bits in I2S configuration registers can only be written when the SPI is disabled + * (SPI_CR1_SPE bit =0), SPI IP should be in disabled state prior calling this function. + * Otherwise, ERROR result will be returned. + * @note I2S (SPI) source clock must be ready before calling this function. Otherwise will results + * in wrong programming. + * @param SPIx SPI Instance + * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: SPI registers are Initialized + * - ERROR: SPI registers are not Initialized + */ +ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct) +{ + uint32_t i2sdiv = 0UL; + uint32_t i2sodd = 0UL; + uint32_t packetlength = 1UL; + uint32_t ispcm = 0UL; + uint32_t tmp; + uint32_t sourceclock; + + ErrorStatus status = ERROR; + + /* Check the I2S parameters */ + assert_param(IS_I2S_ALL_INSTANCE(SPIx)); + assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode)); + assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard)); + assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); + assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput)); + assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq)); + assert_param(IS_LL_I2S_CKPOL(I2S_InitStruct->ClockPolarity)); + + /* Check that SPE bit is set to 0 in order to be sure that SPI/I2S block is disabled. + * In this case, it is useless to check if the I2SMOD bit is set to 0 because + * this bit I2SMOD only serves to select the desired mode. + */ + if (LL_SPI_IsEnabled(SPIx) == 0x00000000UL) + { + /*---------------------------- SPIx I2SCFGR Configuration -------------------- + * Configure SPIx I2SCFGR with parameters: + * - Mode : SPI_I2SCFGR_I2SCFG[2:0] bits + * - Standard : SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits + * - DataFormat : SPI_I2SCFGR_CHLEN, SPI_I2SCFGR_DATFMT and SPI_I2SCFGR_DATLEN[1:0] bits + * - ClockPolarity : SPI_I2SCFGR_CKPOL bit + * - MCLKOutput : SPI_I2SPR_MCKOE bit + * - I2S mode : SPI_I2SCFGR_I2SMOD bit + */ + + /* Write to SPIx I2SCFGR */ + MODIFY_REG(SPIx->I2SCFGR, + I2S_I2SCFGR_CLEAR_MASK, + I2S_InitStruct->Mode | I2S_InitStruct->Standard | + I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | + I2S_InitStruct->MCLKOutput | SPI_I2SCFGR_I2SMOD); + + /*---------------------------- SPIx I2SCFGR Configuration ---------------------- + * Configure SPIx I2SCFGR with parameters: + * - AudioFreq : SPI_I2SCFGR_I2SDIV[7:0] and SPI_I2SCFGR_ODD bits + */ + + /* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv) + * else, default values are used: i2sodd = 0U, i2sdiv = 0U. + */ + if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT) + { + /* Check the frame length (For the Prescaler computing) + * Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U). + */ + if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B) + { + /* Packet length is 32 bits */ + packetlength = 2UL; + } + + /* Check if PCM standard is used */ + if ((I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_SHORT) || + (I2S_InitStruct->Standard == LL_I2S_STANDARD_PCM_LONG)) + { + ispcm = 1UL; + } + + /* Get the I2S (SPI) source clock value */ + if (SPIx == SPI1) + { + sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI1_CLKSOURCE); + } + else if ((SPIx == SPI2) || (SPIx == SPI3)) + { + sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI23_CLKSOURCE); + } + else /* SPI6 */ + { + sourceclock = LL_RCC_GetSPIClockFreq(LL_RCC_SPI6_CLKSOURCE); + } + + /* Compute the Real divider depending on the MCLK output state with a fixed point */ + if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE) + { + /* MCLK output is enabled */ + tmp = (((sourceclock / (256UL >> ispcm)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL; + } + else + { + /* MCLK output is disabled */ + tmp = (((sourceclock / ((32UL >> ispcm) * packetlength)) * 16UL) / I2S_InitStruct->AudioFreq) + 8UL; + } + + /* Remove the fixed point */ + tmp = tmp / 16UL; + + /* Check the parity of the divider */ + i2sodd = tmp & 0x1UL; + + /* Compute the i2sdiv prescaler */ + i2sdiv = tmp / 2UL; + } + + /* Test if the obtain values are forbidden or out of range */ + if (((i2sodd == 1UL) && (i2sdiv == 1UL)) || (i2sdiv > 0xFFUL)) + { + /* Set the default values */ + i2sdiv = 0UL; + i2sodd = 0UL; + } + + /* Write to SPIx I2SCFGR register the computed value */ + MODIFY_REG(SPIx->I2SCFGR, + SPI_I2SCFGR_ODD | SPI_I2SCFGR_I2SDIV, + (i2sodd << SPI_I2SCFGR_ODD_Pos) | (i2sdiv << SPI_I2SCFGR_I2SDIV_Pos)); + + status = SUCCESS; + } + + return status; +} + +/** + * @brief Set each @ref LL_I2S_InitTypeDef field to default value. + * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct) +{ + /*--------------- Reset I2S init structure parameters values -----------------*/ + I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX; + I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS; + I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B; + I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE; + I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT; + I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW; +} + +/** + * @brief Set linear and parity prescaler. + * @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n + * Check Audio frequency table and formulas inside Reference Manual (SPI/I2S). + * @param SPIx SPI Instance + * @param PrescalerLinear Value between Min_Data=0x00 and Max_Data=0xFF + * @note PrescalerLinear '1' is not authorized with parity LL_I2S_PRESCALER_PARITY_ODD + * @param PrescalerParity This parameter can be one of the following values: + * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN + * @arg @ref LL_I2S_PRESCALER_PARITY_ODD + * @retval None + */ +void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity) +{ + /* Check the I2S parameters */ + assert_param(IS_I2S_ALL_INSTANCE(SPIx)); + assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear)); + assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity)); + + /* Write to SPIx I2SPR */ + MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SDIV | SPI_I2SCFGR_ODD, (PrescalerLinear << SPI_I2SCFGR_I2SDIV_Pos) | + (PrescalerParity << SPI_I2SCFGR_ODD_Pos)); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(SPI1) || defined(SPI2) || defined(SPI3) || defined(SPI4) || defined(SPI5) || defined(SPI6) */ + +/** + * @} + */ +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_tim.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_tim.c index e543cd01e..de2ee4d7e 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_tim.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_tim.c @@ -1,1388 +1,1387 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_tim.c - * @author MCD Application Team - * @brief TIM LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_tim.h" -#include "stm32h7rsxx_ll_bus.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined (TIM1) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM6) || defined (TIM7) || defined (TIM9) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM15) || defined (TIM16) || defined (TIM17) - -/** @addtogroup TIM_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup TIM_LL_Private_Macros - * @{ - */ -#define IS_LL_TIM_COUNTERMODE(__VALUE__) (((__VALUE__) == LL_TIM_COUNTERMODE_UP) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_DOWN) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_DOWN) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP_DOWN)) - -#define IS_LL_TIM_CLOCKDIVISION(__VALUE__) (((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV1) \ - || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV2) \ - || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV4)) - -#define IS_LL_TIM_OCMODE(__VALUE__) (((__VALUE__) == LL_TIM_OCMODE_FROZEN) \ - || ((__VALUE__) == LL_TIM_OCMODE_ACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_INACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_TOGGLE) \ - || ((__VALUE__) == LL_TIM_OCMODE_FORCED_INACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_FORCED_ACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_PWM1) \ - || ((__VALUE__) == LL_TIM_OCMODE_PWM2) \ - || ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM1) \ - || ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM2) \ - || ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM1) \ - || ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM2) \ - || ((__VALUE__) == LL_TIM_OCMODE_ASYMMETRIC_PWM1) \ - || ((__VALUE__) == LL_TIM_OCMODE_ASYMMETRIC_PWM2) \ - || ((__VALUE__) == LL_TIM_OCMODE_PULSE_ON_COMPARE) \ - || ((__VALUE__) == LL_TIM_OCMODE_DIRECTION_OUTPUT)) - -#define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \ - || ((__VALUE__) == LL_TIM_OCSTATE_ENABLE)) - -#define IS_LL_TIM_OCPOLARITY(__VALUE__) (((__VALUE__) == LL_TIM_OCPOLARITY_HIGH) \ - || ((__VALUE__) == LL_TIM_OCPOLARITY_LOW)) - -#define IS_LL_TIM_OCIDLESTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCIDLESTATE_LOW) \ - || ((__VALUE__) == LL_TIM_OCIDLESTATE_HIGH)) - -#define IS_LL_TIM_ACTIVEINPUT(__VALUE__) (((__VALUE__) == LL_TIM_ACTIVEINPUT_DIRECTTI) \ - || ((__VALUE__) == LL_TIM_ACTIVEINPUT_INDIRECTTI) \ - || ((__VALUE__) == LL_TIM_ACTIVEINPUT_TRC)) - -#define IS_LL_TIM_ICPSC(__VALUE__) (((__VALUE__) == LL_TIM_ICPSC_DIV1) \ - || ((__VALUE__) == LL_TIM_ICPSC_DIV2) \ - || ((__VALUE__) == LL_TIM_ICPSC_DIV4) \ - || ((__VALUE__) == LL_TIM_ICPSC_DIV8)) - -#define IS_LL_TIM_IC_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_IC_FILTER_FDIV1) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N2) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N4) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N5) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N5) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N8)) - -#define IS_LL_TIM_IC_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ - || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING) \ - || ((__VALUE__) == LL_TIM_IC_POLARITY_BOTHEDGE)) - -#define IS_LL_TIM_ENCODERMODE(__VALUE__) (((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI1) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI2) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_X4_TI12) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X2) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X1) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_DIRECTIONALCLOCK_X2) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_DIRECTIONALCLOCK_X1_TI12) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_X1_TI1) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_X1_TI2)) - -#define IS_LL_TIM_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ - || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) - -#define IS_LL_TIM_OSSR_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSR_DISABLE) \ - || ((__VALUE__) == LL_TIM_OSSR_ENABLE)) - -#define IS_LL_TIM_OSSI_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSI_DISABLE) \ - || ((__VALUE__) == LL_TIM_OSSI_ENABLE)) - -#define IS_LL_TIM_LOCK_LEVEL(__VALUE__) (((__VALUE__) == LL_TIM_LOCKLEVEL_OFF) \ - || ((__VALUE__) == LL_TIM_LOCKLEVEL_1) \ - || ((__VALUE__) == LL_TIM_LOCKLEVEL_2) \ - || ((__VALUE__) == LL_TIM_LOCKLEVEL_3)) - -#define IS_LL_TIM_BREAK_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_DISABLE) \ - || ((__VALUE__) == LL_TIM_BREAK_ENABLE)) - -#define IS_LL_TIM_BREAK_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_POLARITY_LOW) \ - || ((__VALUE__) == LL_TIM_BREAK_POLARITY_HIGH)) - -#define IS_LL_TIM_BREAK_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N2) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N4) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N8) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV2_N6) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV2_N8) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV4_N6) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV4_N8) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV8_N6) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV8_N8) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N5) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N6) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N8) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N5) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N6) \ - || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N8)) - -#define IS_LL_TIM_BREAK_AFMODE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_AFMODE_INPUT) \ - || ((__VALUE__) == LL_TIM_BREAK_AFMODE_BIDIRECTIONAL)) - -#define IS_LL_TIM_BREAK2_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_DISABLE) \ - || ((__VALUE__) == LL_TIM_BREAK2_ENABLE)) - -#define IS_LL_TIM_BREAK2_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_POLARITY_LOW) \ - || ((__VALUE__) == LL_TIM_BREAK2_POLARITY_HIGH)) - -#define IS_LL_TIM_BREAK2_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N2) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N4) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N8) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV2_N6) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV2_N8) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV4_N6) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV4_N8) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV8_N6) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV8_N8) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N5) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N6) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N8) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N5) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N6) \ - || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N8)) - -#define IS_LL_TIM_BREAK2_AFMODE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_AFMODE_INPUT) \ - || ((__VALUE__) == LL_TIM_BREAK2_AFMODE_BIDIRECTIONAL)) - -#define IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_DISABLE) \ - || ((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_ENABLE)) -/** - * @} - */ - - -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup TIM_LL_Private_Functions TIM Private Functions - * @{ - */ -static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC5Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC6Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus IC1Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -static ErrorStatus IC2Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -static ErrorStatus IC3Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -static ErrorStatus IC4Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup TIM_LL_Exported_Functions - * @{ - */ - -/** @addtogroup TIM_LL_EF_Init - * @{ - */ - -/** - * @brief Set TIMx registers to their reset values. - * @param TIMx Timer instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: invalid TIMx instance - */ -ErrorStatus LL_TIM_DeInit(const TIM_TypeDef *TIMx) -{ - ErrorStatus result = SUCCESS; - - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(TIMx)); - - if (TIMx == TIM1) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM1); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM1); - } - else if (TIMx == TIM2) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM2); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM2); - } - else if (TIMx == TIM3) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM3); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM3); - } - else if (TIMx == TIM4) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM4); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM4); - } - else if (TIMx == TIM5) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5); - } - else if (TIMx == TIM6) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM6); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM6); - } - else if (TIMx == TIM7) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM7); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM7); - } - else if (TIMx == TIM9) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM9); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM9); - } - else if (TIMx == TIM12) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM12); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM12); - } - else if (TIMx == TIM13) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM13); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM13); - } - else if (TIMx == TIM14) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM14); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM14); - } - else if (TIMx == TIM15) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM15); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM15); - } - else if (TIMx == TIM16) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM16); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM16); - } - else if (TIMx == TIM17) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM17); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM17); - } - else - { - result = ERROR; - } - - return result; -} - -/** - * @brief Set the fields of the time base unit configuration data structure - * to their default values. - * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (time base unit configuration data structure) - * @retval None - */ -void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct) -{ - /* Set the default configuration */ - TIM_InitStruct->Prescaler = (uint16_t)0x0000; - TIM_InitStruct->CounterMode = LL_TIM_COUNTERMODE_UP; - TIM_InitStruct->Autoreload = 0xFFFFFFFFU; - TIM_InitStruct->ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; - TIM_InitStruct->RepetitionCounter = 0x00000000U; -} - -/** - * @brief Configure the TIMx time base unit. - * @param TIMx Timer Instance - * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure - * (TIMx time base unit configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, const LL_TIM_InitTypeDef *TIM_InitStruct) -{ - uint32_t tmpcr1; - - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_COUNTERMODE(TIM_InitStruct->CounterMode)); - assert_param(IS_LL_TIM_CLOCKDIVISION(TIM_InitStruct->ClockDivision)); - - tmpcr1 = LL_TIM_ReadReg(TIMx, CR1); - - if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) - { - /* Select the Counter Mode */ - MODIFY_REG(tmpcr1, (TIM_CR1_DIR | TIM_CR1_CMS), TIM_InitStruct->CounterMode); - } - - if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) - { - /* Set the clock division */ - MODIFY_REG(tmpcr1, TIM_CR1_CKD, TIM_InitStruct->ClockDivision); - } - - /* Write to TIMx CR1 */ - LL_TIM_WriteReg(TIMx, CR1, tmpcr1); - - /* Set the Autoreload value */ - LL_TIM_SetAutoReload(TIMx, TIM_InitStruct->Autoreload); - - /* Set the Prescaler value */ - LL_TIM_SetPrescaler(TIMx, TIM_InitStruct->Prescaler); - - if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) - { - /* Set the Repetition Counter value */ - LL_TIM_SetRepetitionCounter(TIMx, TIM_InitStruct->RepetitionCounter); - } - - /* Generate an update event to reload the Prescaler - and the repetition counter value (if applicable) immediately */ - LL_TIM_GenerateEvent_UPDATE(TIMx); - - return SUCCESS; -} - -/** - * @brief Set the fields of the TIMx output channel configuration data - * structure to their default values. - * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure - * (the output channel configuration data structure) - * @retval None - */ -void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) -{ - /* Set the default configuration */ - TIM_OC_InitStruct->OCMode = LL_TIM_OCMODE_FROZEN; - TIM_OC_InitStruct->OCState = LL_TIM_OCSTATE_DISABLE; - TIM_OC_InitStruct->OCNState = LL_TIM_OCSTATE_DISABLE; - TIM_OC_InitStruct->CompareValue = 0x00000000U; - TIM_OC_InitStruct->OCPolarity = LL_TIM_OCPOLARITY_HIGH; - TIM_OC_InitStruct->OCNPolarity = LL_TIM_OCPOLARITY_HIGH; - TIM_OC_InitStruct->OCIdleState = LL_TIM_OCIDLESTATE_LOW; - TIM_OC_InitStruct->OCNIdleState = LL_TIM_OCIDLESTATE_LOW; -} - -/** - * @brief Configure the TIMx output channel. - * @param TIMx Timer Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @arg @ref LL_TIM_CHANNEL_CH5 - * @arg @ref LL_TIM_CHANNEL_CH6 - * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (TIMx output channel configuration - * data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx output channel is initialized - * - ERROR: TIMx output channel is not initialized - */ -ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, const LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) -{ - ErrorStatus result = ERROR; - - switch (Channel) - { - case LL_TIM_CHANNEL_CH1: - result = OC1Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH2: - result = OC2Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH3: - result = OC3Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH4: - result = OC4Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH5: - result = OC5Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH6: - result = OC6Config(TIMx, TIM_OC_InitStruct); - break; - default: - break; - } - - return result; -} - -/** - * @brief Set the fields of the TIMx input channel configuration data - * structure to their default values. - * @param TIM_ICInitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (the input channel configuration - * data structure) - * @retval None - */ -void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Set the default configuration */ - TIM_ICInitStruct->ICPolarity = LL_TIM_IC_POLARITY_RISING; - TIM_ICInitStruct->ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; - TIM_ICInitStruct->ICPrescaler = LL_TIM_ICPSC_DIV1; - TIM_ICInitStruct->ICFilter = LL_TIM_IC_FILTER_FDIV1; -} - -/** - * @brief Configure the TIMx input channel. - * @param TIMx Timer Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param TIM_IC_InitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (TIMx input channel configuration data - * structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx output channel is initialized - * - ERROR: TIMx output channel is not initialized - */ -ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, const LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct) -{ - ErrorStatus result = ERROR; - - switch (Channel) - { - case LL_TIM_CHANNEL_CH1: - result = IC1Config(TIMx, TIM_IC_InitStruct); - break; - case LL_TIM_CHANNEL_CH2: - result = IC2Config(TIMx, TIM_IC_InitStruct); - break; - case LL_TIM_CHANNEL_CH3: - result = IC3Config(TIMx, TIM_IC_InitStruct); - break; - case LL_TIM_CHANNEL_CH4: - result = IC4Config(TIMx, TIM_IC_InitStruct); - break; - default: - break; - } - - return result; -} - -/** - * @brief Fills each TIM_EncoderInitStruct field with its default value - * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (encoder interface - * configuration data structure) - * @retval None - */ -void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) -{ - /* Set the default configuration */ - TIM_EncoderInitStruct->EncoderMode = LL_TIM_ENCODERMODE_X2_TI1; - TIM_EncoderInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; - TIM_EncoderInitStruct->IC1ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; - TIM_EncoderInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; - TIM_EncoderInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; - TIM_EncoderInitStruct->IC2Polarity = LL_TIM_IC_POLARITY_RISING; - TIM_EncoderInitStruct->IC2ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; - TIM_EncoderInitStruct->IC2Prescaler = LL_TIM_ICPSC_DIV1; - TIM_EncoderInitStruct->IC2Filter = LL_TIM_IC_FILTER_FDIV1; -} - -/** - * @brief Configure the encoder interface of the timer instance. - * @param TIMx Timer Instance - * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (TIMx encoder interface - * configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, const LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) -{ - uint32_t tmpccmr1; - uint32_t tmpccer; - - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_ENCODERMODE(TIM_EncoderInitStruct->EncoderMode)); - assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC1Polarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC1ActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC1Prescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC1Filter)); - assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC2Polarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC2ActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC2Prescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC2Filter)); - - /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ - TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Configure TI1 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1ActiveInput >> 16U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Filter >> 16U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Prescaler >> 16U); - - /* Configure TI2 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2ActiveInput >> 8U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Filter >> 8U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Prescaler >> 8U); - - /* Set TI1 and TI2 polarity and enable TI1 and TI2 */ - tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC1Polarity); - tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC2Polarity << 4U); - tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Set encoder mode */ - LL_TIM_SetEncoderMode(TIMx, TIM_EncoderInitStruct->EncoderMode); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Set the fields of the TIMx Hall sensor interface configuration data - * structure to their default values. - * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (HALL sensor interface - * configuration data structure) - * @retval None - */ -void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) -{ - /* Set the default configuration */ - TIM_HallSensorInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; - TIM_HallSensorInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; - TIM_HallSensorInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; - TIM_HallSensorInitStruct->CommutationDelay = 0U; -} - -/** - * @brief Configure the Hall sensor interface of the timer instance. - * @note TIMx CH1, CH2 and CH3 inputs connected through a XOR - * to the TI1 input channel - * @note TIMx slave mode controller is configured in reset mode. - Selected internal trigger is TI1F_ED. - * @note Channel 1 is configured as input, IC1 is mapped on TRC. - * @note Captured value stored in TIMx_CCR1 correspond to the time elapsed - * between 2 changes on the inputs. It gives information about motor speed. - * @note Channel 2 is configured in output PWM 2 mode. - * @note Compare value stored in TIMx_CCR2 corresponds to the commutation delay. - * @note OC2REF is selected as trigger output on TRGO. - * @note LL_TIM_IC_POLARITY_BOTHEDGE must not be used for TI1 when it is used - * when TIMx operates in Hall sensor interface mode. - * @param TIMx Timer Instance - * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (TIMx HALL sensor - * interface configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, const LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) -{ - uint32_t tmpcr2; - uint32_t tmpccmr1; - uint32_t tmpccer; - uint32_t tmpsmcr; - - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_HallSensorInitStruct->IC1Polarity)); - assert_param(IS_LL_TIM_ICPSC(TIM_HallSensorInitStruct->IC1Prescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_HallSensorInitStruct->IC1Filter)); - - /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ - TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx SMCR register value */ - tmpsmcr = LL_TIM_ReadReg(TIMx, SMCR); - - /* Connect TIMx_CH1, CH2 and CH3 pins to the TI1 input */ - tmpcr2 |= TIM_CR2_TI1S; - - /* OC2REF signal is used as trigger output (TRGO) */ - tmpcr2 |= LL_TIM_TRGO_OC2REF; - - /* Configure the slave mode controller */ - tmpsmcr &= (uint32_t)~(TIM_SMCR_TS | TIM_SMCR_SMS); - tmpsmcr |= LL_TIM_TS_TI1F_ED; - tmpsmcr |= LL_TIM_SLAVEMODE_RESET; - - /* Configure input channel 1 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); - tmpccmr1 |= (uint32_t)(LL_TIM_ACTIVEINPUT_TRC >> 16U); - tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Filter >> 16U); - tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Prescaler >> 16U); - - /* Configure input channel 2 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_OC2M | TIM_CCMR1_OC2FE | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2CE); - tmpccmr1 |= (uint32_t)(LL_TIM_OCMODE_PWM2 << 8U); - - /* Set Channel 1 polarity and enable Channel 1 and Channel2 */ - tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= (uint32_t)(TIM_HallSensorInitStruct->IC1Polarity); - tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx SMCR */ - LL_TIM_WriteReg(TIMx, SMCR, tmpsmcr); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - /* Write to TIMx CCR2 */ - LL_TIM_OC_SetCompareCH2(TIMx, TIM_HallSensorInitStruct->CommutationDelay); - - return SUCCESS; -} - -/** - * @brief Set the fields of the Break and Dead Time configuration data structure - * to their default values. - * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration - * data structure) - * @retval None - */ -void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) -{ - /* Set the default configuration */ - TIM_BDTRInitStruct->OSSRState = LL_TIM_OSSR_DISABLE; - TIM_BDTRInitStruct->OSSIState = LL_TIM_OSSI_DISABLE; - TIM_BDTRInitStruct->LockLevel = LL_TIM_LOCKLEVEL_OFF; - TIM_BDTRInitStruct->DeadTime = (uint8_t)0x00; - TIM_BDTRInitStruct->BreakState = LL_TIM_BREAK_DISABLE; - TIM_BDTRInitStruct->BreakPolarity = LL_TIM_BREAK_POLARITY_LOW; - TIM_BDTRInitStruct->BreakFilter = LL_TIM_BREAK_FILTER_FDIV1; - TIM_BDTRInitStruct->BreakAFMode = LL_TIM_BREAK_AFMODE_INPUT; - TIM_BDTRInitStruct->Break2State = LL_TIM_BREAK2_DISABLE; - TIM_BDTRInitStruct->Break2Polarity = LL_TIM_BREAK2_POLARITY_LOW; - TIM_BDTRInitStruct->Break2Filter = LL_TIM_BREAK2_FILTER_FDIV1; - TIM_BDTRInitStruct->Break2AFMode = LL_TIM_BREAK2_AFMODE_INPUT; - TIM_BDTRInitStruct->AutomaticOutput = LL_TIM_AUTOMATICOUTPUT_DISABLE; -} - -/** - * @brief Configure the Break and Dead Time feature of the timer instance. - * @note As the bits BK2P, BK2E, BK2F[3:0], BKF[3:0], AOE, BKP, BKE, OSSI, OSSR - * and DTG[7:0] can be write-locked depending on the LOCK configuration, it - * can be necessary to configure all of them during the first write access to - * the TIMx_BDTR register. - * @note Macro IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @note Macro IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a second break input. - * @param TIMx Timer Instance - * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration - * data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Break and Dead Time is initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, const LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) -{ - uint32_t tmpbdtr = 0; - - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OSSR_STATE(TIM_BDTRInitStruct->OSSRState)); - assert_param(IS_LL_TIM_OSSI_STATE(TIM_BDTRInitStruct->OSSIState)); - assert_param(IS_LL_TIM_LOCK_LEVEL(TIM_BDTRInitStruct->LockLevel)); - assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState)); - assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity)); - assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput)); - assert_param(IS_LL_TIM_BREAK_FILTER(TIM_BDTRInitStruct->BreakFilter)); - assert_param(IS_LL_TIM_BREAK_AFMODE(TIM_BDTRInitStruct->BreakAFMode)); - - /* 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 */ - - /* Set the BDTR bits */ - MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, TIM_BDTRInitStruct->DeadTime); - MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, TIM_BDTRInitStruct->LockLevel); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, TIM_BDTRInitStruct->OSSIState); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, TIM_BDTRInitStruct->OSSRState); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity); - MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, TIM_BDTRInitStruct->BreakFilter); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, TIM_BDTRInitStruct->BreakAFMode); - - if (IS_TIM_BKIN2_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_BREAK2_STATE(TIM_BDTRInitStruct->Break2State)); - assert_param(IS_LL_TIM_BREAK2_POLARITY(TIM_BDTRInitStruct->Break2Polarity)); - assert_param(IS_LL_TIM_BREAK2_FILTER(TIM_BDTRInitStruct->Break2Filter)); - assert_param(IS_LL_TIM_BREAK2_AFMODE(TIM_BDTRInitStruct->Break2AFMode)); - - /* Set the BREAK2 input related BDTR bit-fields */ - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (TIM_BDTRInitStruct->Break2Filter)); - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, TIM_BDTRInitStruct->Break2State); - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, TIM_BDTRInitStruct->Break2Polarity); - MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, TIM_BDTRInitStruct->Break2AFMode); - } - - /* Set TIMx_BDTR */ - LL_TIM_WriteReg(TIMx, BDTR, tmpbdtr); - - return SUCCESS; -} -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup TIM_LL_Private_Functions TIM Private Functions - * @brief Private functions - * @{ - */ -/** - * @brief Configure the TIMx output channel 1. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 1 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr1; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Check the parameters */ - assert_param(IS_TIM_CC1_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - - /* Disable the Channel 1: Reset the CC1E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC1S); - - /* Set the Output Compare Mode */ - MODIFY_REG(tmpccmr1, TIM_CCMR1_OC1M, TIM_OCInitStruct->OCMode); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC1P, TIM_OCInitStruct->OCPolarity); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC1E, TIM_OCInitStruct->OCState); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC1NE, TIM_OCInitStruct->OCNState << 2U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS1, TIM_OCInitStruct->OCIdleState); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS1N, TIM_OCInitStruct->OCNIdleState << 1U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH1(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 2. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 2 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr1; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Check the parameters */ - assert_param(IS_TIM_CC2_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - - /* Disable the Channel 2: Reset the CC2E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC2S); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr1, TIM_CCMR1_OC2M, TIM_OCInitStruct->OCMode << 8U); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC2P, TIM_OCInitStruct->OCPolarity << 4U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC2E, TIM_OCInitStruct->OCState << 4U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC2NE, TIM_OCInitStruct->OCNState << 6U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS2, TIM_OCInitStruct->OCIdleState << 2U); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS2N, TIM_OCInitStruct->OCNIdleState << 3U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH2(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 3. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 3 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr2; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Check the parameters */ - assert_param(IS_TIM_CC3_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - - /* Disable the Channel 3: Reset the CC3E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR2 register value */ - tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC3S); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr2, TIM_CCMR2_OC3M, TIM_OCInitStruct->OCMode); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC3P, TIM_OCInitStruct->OCPolarity << 8U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC3E, TIM_OCInitStruct->OCState << 8U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC3NE, TIM_OCInitStruct->OCNState << 10U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS3, TIM_OCInitStruct->OCIdleState << 4U); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS3N, TIM_OCInitStruct->OCNIdleState << 5U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR2 */ - LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH3(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 4. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 4 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr2; - uint32_t tmpccer; - uint32_t tmpcr2; - - /* Check the parameters */ - assert_param(IS_TIM_CC4_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - - /* Disable the Channel 4: Reset the CC4E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR2 register value */ - tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC4S); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr2, TIM_CCMR2_OC4M, TIM_OCInitStruct->OCMode << 8U); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC4P, TIM_OCInitStruct->OCPolarity << 12U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC4E, TIM_OCInitStruct->OCState << 12U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC4NP, TIM_OCInitStruct->OCNPolarity << 14U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC4NE, TIM_OCInitStruct->OCNState << 14U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS4, TIM_OCInitStruct->OCIdleState << 6U); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS4N, TIM_OCInitStruct->OCNIdleState << 7U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR2 */ - LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH4(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 5. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 5 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC5Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr3; - uint32_t tmpccer; - - /* Check the parameters */ - assert_param(IS_TIM_CC5_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - - /* Disable the Channel 5: Reset the CC5E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC5E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CCMR3 register value */ - tmpccmr3 = LL_TIM_ReadReg(TIMx, CCMR3); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr3, TIM_CCMR3_OC5M, TIM_OCInitStruct->OCMode); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC5P, TIM_OCInitStruct->OCPolarity << 16U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC5E, TIM_OCInitStruct->OCState << 16U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - - /* Set the Output Idle state */ - MODIFY_REG(TIMx->CR2, TIM_CR2_OIS5, TIM_OCInitStruct->OCIdleState << 8U); - - } - - /* Write to TIMx CCMR3 */ - LL_TIM_WriteReg(TIMx, CCMR3, tmpccmr3); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH5(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 6. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 6 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC6Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr3; - uint32_t tmpccer; - - /* Check the parameters */ - assert_param(IS_TIM_CC6_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - - /* Disable the Channel 5: Reset the CC6E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC6E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CCMR3 register value */ - tmpccmr3 = LL_TIM_ReadReg(TIMx, CCMR3); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr3, TIM_CCMR3_OC6M, TIM_OCInitStruct->OCMode << 8U); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC6P, TIM_OCInitStruct->OCPolarity << 20U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC6E, TIM_OCInitStruct->OCState << 20U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - - /* Set the Output Idle state */ - MODIFY_REG(TIMx->CR2, TIM_CR2_OIS6, TIM_OCInitStruct->OCIdleState << 10U); - } - - /* Write to TIMx CCMR3 */ - LL_TIM_WriteReg(TIMx, CCMR3, tmpccmr3); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH6(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 1. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 1 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC1Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC1_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 1: Reset the CC1E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC1E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR1, - (TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); - - /* Select the Polarity and set the CC1E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC1P | TIM_CCER_CC1NP), - (TIM_ICInitStruct->ICPolarity | TIM_CCER_CC1E)); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 2. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 2 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC2Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC2_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 2: Reset the CC2E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC2E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR1, - (TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); - - /* Select the Polarity and set the CC2E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC2P | TIM_CCER_CC2NP), - ((TIM_ICInitStruct->ICPolarity << 4U) | TIM_CCER_CC2E)); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 3. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 3 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC3Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC3_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 3: Reset the CC3E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC3E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR2, - (TIM_CCMR2_CC3S | TIM_CCMR2_IC3F | TIM_CCMR2_IC3PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); - - /* Select the Polarity and set the CC3E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC3P | TIM_CCER_CC3NP), - ((TIM_ICInitStruct->ICPolarity << 8U) | TIM_CCER_CC3E)); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 4. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 4 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC4Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC4_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 4: Reset the CC4E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC4E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR2, - (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); - - /* Select the Polarity and set the CC4E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC4P | TIM_CCER_CC4NP), - ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); - - return SUCCESS; -} - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* TIM1 || TIM2 || TIM3 || TIM4 || TIM5 || TIM6 || TIM7 || TIM9 || TIM12 || TIM13 || TIM14 || TIM15 || TIM16 || TIM17 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_tim.c + * @author MCD Application Team + * @brief TIM LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_tim.h" +#include "stm32h7rsxx_ll_bus.h" + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined (TIM1) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM6) || defined (TIM7) || defined (TIM9) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM15) || defined (TIM16) || defined (TIM17) + +/** @addtogroup TIM_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup TIM_LL_Private_Macros + * @{ + */ +#define IS_LL_TIM_COUNTERMODE(__VALUE__) (((__VALUE__) == LL_TIM_COUNTERMODE_UP) \ + || ((__VALUE__) == LL_TIM_COUNTERMODE_DOWN) \ + || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP) \ + || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_DOWN) \ + || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP_DOWN)) + +#define IS_LL_TIM_CLOCKDIVISION(__VALUE__) (((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV1) \ + || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV2) \ + || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV4)) + +#define IS_LL_TIM_OCMODE(__VALUE__) (((__VALUE__) == LL_TIM_OCMODE_FROZEN) \ + || ((__VALUE__) == LL_TIM_OCMODE_ACTIVE) \ + || ((__VALUE__) == LL_TIM_OCMODE_INACTIVE) \ + || ((__VALUE__) == LL_TIM_OCMODE_TOGGLE) \ + || ((__VALUE__) == LL_TIM_OCMODE_FORCED_INACTIVE) \ + || ((__VALUE__) == LL_TIM_OCMODE_FORCED_ACTIVE) \ + || ((__VALUE__) == LL_TIM_OCMODE_PWM1) \ + || ((__VALUE__) == LL_TIM_OCMODE_PWM2) \ + || ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM1) \ + || ((__VALUE__) == LL_TIM_OCMODE_RETRIG_OPM2) \ + || ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM1) \ + || ((__VALUE__) == LL_TIM_OCMODE_COMBINED_PWM2) \ + || ((__VALUE__) == LL_TIM_OCMODE_ASYMMETRIC_PWM1) \ + || ((__VALUE__) == LL_TIM_OCMODE_ASYMMETRIC_PWM2) \ + || ((__VALUE__) == LL_TIM_OCMODE_PULSE_ON_COMPARE) \ + || ((__VALUE__) == LL_TIM_OCMODE_DIRECTION_OUTPUT)) + +#define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \ + || ((__VALUE__) == LL_TIM_OCSTATE_ENABLE)) + +#define IS_LL_TIM_OCPOLARITY(__VALUE__) (((__VALUE__) == LL_TIM_OCPOLARITY_HIGH) \ + || ((__VALUE__) == LL_TIM_OCPOLARITY_LOW)) + +#define IS_LL_TIM_OCIDLESTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCIDLESTATE_LOW) \ + || ((__VALUE__) == LL_TIM_OCIDLESTATE_HIGH)) + +#define IS_LL_TIM_ACTIVEINPUT(__VALUE__) (((__VALUE__) == LL_TIM_ACTIVEINPUT_DIRECTTI) \ + || ((__VALUE__) == LL_TIM_ACTIVEINPUT_INDIRECTTI) \ + || ((__VALUE__) == LL_TIM_ACTIVEINPUT_TRC)) + +#define IS_LL_TIM_ICPSC(__VALUE__) (((__VALUE__) == LL_TIM_ICPSC_DIV1) \ + || ((__VALUE__) == LL_TIM_ICPSC_DIV2) \ + || ((__VALUE__) == LL_TIM_ICPSC_DIV4) \ + || ((__VALUE__) == LL_TIM_ICPSC_DIV8)) + +#define IS_LL_TIM_IC_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_IC_FILTER_FDIV1) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N2) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N4) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N8) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N6) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N8) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N6) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N8) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N6) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N8) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N5) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N6) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N8) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N5) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N6) \ + || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N8)) + +#define IS_LL_TIM_IC_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ + || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING) \ + || ((__VALUE__) == LL_TIM_IC_POLARITY_BOTHEDGE)) + +#define IS_LL_TIM_ENCODERMODE(__VALUE__) (((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI1) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI2) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_X4_TI12) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X2) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_CLOCKPLUSDIRECTION_X1) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_DIRECTIONALCLOCK_X2) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_DIRECTIONALCLOCK_X1_TI12) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_X1_TI1) \ + || ((__VALUE__) == LL_TIM_ENCODERMODE_X1_TI2)) + +#define IS_LL_TIM_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ + || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) + +#define IS_LL_TIM_OSSR_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSR_DISABLE) \ + || ((__VALUE__) == LL_TIM_OSSR_ENABLE)) + +#define IS_LL_TIM_OSSI_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSI_DISABLE) \ + || ((__VALUE__) == LL_TIM_OSSI_ENABLE)) + +#define IS_LL_TIM_LOCK_LEVEL(__VALUE__) (((__VALUE__) == LL_TIM_LOCKLEVEL_OFF) \ + || ((__VALUE__) == LL_TIM_LOCKLEVEL_1) \ + || ((__VALUE__) == LL_TIM_LOCKLEVEL_2) \ + || ((__VALUE__) == LL_TIM_LOCKLEVEL_3)) + +#define IS_LL_TIM_BREAK_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_DISABLE) \ + || ((__VALUE__) == LL_TIM_BREAK_ENABLE)) + +#define IS_LL_TIM_BREAK_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_POLARITY_LOW) \ + || ((__VALUE__) == LL_TIM_BREAK_POLARITY_HIGH)) + +#define IS_LL_TIM_BREAK_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N2) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N4) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV1_N8) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV2_N6) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV2_N8) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV4_N6) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV4_N8) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV8_N6) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV8_N8) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N5) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N6) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV16_N8) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N5) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N6) \ + || ((__VALUE__) == LL_TIM_BREAK_FILTER_FDIV32_N8)) + +#define IS_LL_TIM_BREAK_AFMODE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_AFMODE_INPUT) \ + || ((__VALUE__) == LL_TIM_BREAK_AFMODE_BIDIRECTIONAL)) + +#define IS_LL_TIM_BREAK2_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_DISABLE) \ + || ((__VALUE__) == LL_TIM_BREAK2_ENABLE)) + +#define IS_LL_TIM_BREAK2_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_POLARITY_LOW) \ + || ((__VALUE__) == LL_TIM_BREAK2_POLARITY_HIGH)) + +#define IS_LL_TIM_BREAK2_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N2) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N4) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV1_N8) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV2_N6) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV2_N8) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV4_N6) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV4_N8) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV8_N6) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV8_N8) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N5) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N6) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV16_N8) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N5) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N6) \ + || ((__VALUE__) == LL_TIM_BREAK2_FILTER_FDIV32_N8)) + +#define IS_LL_TIM_BREAK2_AFMODE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK2_AFMODE_INPUT) \ + || ((__VALUE__) == LL_TIM_BREAK2_AFMODE_BIDIRECTIONAL)) + +#define IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_DISABLE) \ + || ((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_ENABLE)) +/** + * @} + */ + + +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup TIM_LL_Private_Functions TIM Private Functions + * @{ + */ +static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); +static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); +static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); +static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); +static ErrorStatus OC5Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); +static ErrorStatus OC6Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); +static ErrorStatus IC1Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); +static ErrorStatus IC2Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); +static ErrorStatus IC3Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); +static ErrorStatus IC4Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup TIM_LL_Exported_Functions + * @{ + */ + +/** @addtogroup TIM_LL_EF_Init + * @{ + */ + +/** + * @brief Set TIMx registers to their reset values. + * @param TIMx Timer instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: invalid TIMx instance + */ +ErrorStatus LL_TIM_DeInit(const TIM_TypeDef *TIMx) +{ + ErrorStatus result = SUCCESS; + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(TIMx)); + + if (TIMx == TIM1) + { + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM1); + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM1); + } + else if (TIMx == TIM2) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM2); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM2); + } + else if (TIMx == TIM3) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM3); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM3); + } + else if (TIMx == TIM4) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM4); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM4); + } + else if (TIMx == TIM5) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5); + } + else if (TIMx == TIM6) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM6); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM6); + } + else if (TIMx == TIM7) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM7); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM7); + } + else if (TIMx == TIM9) + { + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM9); + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM9); + } + else if (TIMx == TIM12) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM12); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM12); + } + else if (TIMx == TIM13) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM13); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM13); + } + else if (TIMx == TIM14) + { + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM14); + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM14); + } + else if (TIMx == TIM15) + { + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM15); + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM15); + } + else if (TIMx == TIM16) + { + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM16); + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM16); + } + else if (TIMx == TIM17) + { + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM17); + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM17); + } + else + { + result = ERROR; + } + + return result; +} + +/** + * @brief Set the fields of the time base unit configuration data structure + * to their default values. + * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (time base unit configuration data structure) + * @retval None + */ +void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct) +{ + /* Set the default configuration */ + TIM_InitStruct->Prescaler = (uint16_t)0x0000; + TIM_InitStruct->CounterMode = LL_TIM_COUNTERMODE_UP; + TIM_InitStruct->Autoreload = 0xFFFFFFFFU; + TIM_InitStruct->ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; + TIM_InitStruct->RepetitionCounter = 0x00000000U; +} + +/** + * @brief Configure the TIMx time base unit. + * @param TIMx Timer Instance + * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure + * (TIMx time base unit configuration data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, const LL_TIM_InitTypeDef *TIM_InitStruct) +{ + uint32_t tmpcr1; + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_COUNTERMODE(TIM_InitStruct->CounterMode)); + assert_param(IS_LL_TIM_CLOCKDIVISION(TIM_InitStruct->ClockDivision)); + + tmpcr1 = LL_TIM_ReadReg(TIMx, CR1); + + if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) + { + /* Select the Counter Mode */ + MODIFY_REG(tmpcr1, (TIM_CR1_DIR | TIM_CR1_CMS), TIM_InitStruct->CounterMode); + } + + if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) + { + /* Set the clock division */ + MODIFY_REG(tmpcr1, TIM_CR1_CKD, TIM_InitStruct->ClockDivision); + } + + /* Write to TIMx CR1 */ + LL_TIM_WriteReg(TIMx, CR1, tmpcr1); + + /* Set the Autoreload value */ + LL_TIM_SetAutoReload(TIMx, TIM_InitStruct->Autoreload); + + /* Set the Prescaler value */ + LL_TIM_SetPrescaler(TIMx, TIM_InitStruct->Prescaler); + + if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) + { + /* Set the Repetition Counter value */ + LL_TIM_SetRepetitionCounter(TIMx, TIM_InitStruct->RepetitionCounter); + } + + /* Generate an update event to reload the Prescaler + and the repetition counter value (if applicable) immediately */ + LL_TIM_GenerateEvent_UPDATE(TIMx); + + return SUCCESS; +} + +/** + * @brief Set the fields of the TIMx output channel configuration data + * structure to their default values. + * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure + * (the output channel configuration data structure) + * @retval None + */ +void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) +{ + /* Set the default configuration */ + TIM_OC_InitStruct->OCMode = LL_TIM_OCMODE_FROZEN; + TIM_OC_InitStruct->OCState = LL_TIM_OCSTATE_DISABLE; + TIM_OC_InitStruct->OCNState = LL_TIM_OCSTATE_DISABLE; + TIM_OC_InitStruct->CompareValue = 0x00000000U; + TIM_OC_InitStruct->OCPolarity = LL_TIM_OCPOLARITY_HIGH; + TIM_OC_InitStruct->OCNPolarity = LL_TIM_OCPOLARITY_HIGH; + TIM_OC_InitStruct->OCIdleState = LL_TIM_OCIDLESTATE_LOW; + TIM_OC_InitStruct->OCNIdleState = LL_TIM_OCIDLESTATE_LOW; +} + +/** + * @brief Configure the TIMx output channel. + * @param TIMx Timer Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref LL_TIM_CHANNEL_CH1 + * @arg @ref LL_TIM_CHANNEL_CH2 + * @arg @ref LL_TIM_CHANNEL_CH3 + * @arg @ref LL_TIM_CHANNEL_CH4 + * @arg @ref LL_TIM_CHANNEL_CH5 + * @arg @ref LL_TIM_CHANNEL_CH6 + * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (TIMx output channel configuration + * data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx output channel is initialized + * - ERROR: TIMx output channel is not initialized + */ +ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, const LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) +{ + ErrorStatus result = ERROR; + + switch (Channel) + { + case LL_TIM_CHANNEL_CH1: + result = OC1Config(TIMx, TIM_OC_InitStruct); + break; + case LL_TIM_CHANNEL_CH2: + result = OC2Config(TIMx, TIM_OC_InitStruct); + break; + case LL_TIM_CHANNEL_CH3: + result = OC3Config(TIMx, TIM_OC_InitStruct); + break; + case LL_TIM_CHANNEL_CH4: + result = OC4Config(TIMx, TIM_OC_InitStruct); + break; + case LL_TIM_CHANNEL_CH5: + result = OC5Config(TIMx, TIM_OC_InitStruct); + break; + case LL_TIM_CHANNEL_CH6: + result = OC6Config(TIMx, TIM_OC_InitStruct); + break; + default: + break; + } + + return result; +} + +/** + * @brief Set the fields of the TIMx input channel configuration data + * structure to their default values. + * @param TIM_ICInitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (the input channel configuration + * data structure) + * @retval None + */ +void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) +{ + /* Set the default configuration */ + TIM_ICInitStruct->ICPolarity = LL_TIM_IC_POLARITY_RISING; + TIM_ICInitStruct->ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; + TIM_ICInitStruct->ICPrescaler = LL_TIM_ICPSC_DIV1; + TIM_ICInitStruct->ICFilter = LL_TIM_IC_FILTER_FDIV1; +} + +/** + * @brief Configure the TIMx input channel. + * @param TIMx Timer Instance + * @param Channel This parameter can be one of the following values: + * @arg @ref LL_TIM_CHANNEL_CH1 + * @arg @ref LL_TIM_CHANNEL_CH2 + * @arg @ref LL_TIM_CHANNEL_CH3 + * @arg @ref LL_TIM_CHANNEL_CH4 + * @param TIM_IC_InitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (TIMx input channel configuration data + * structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx output channel is initialized + * - ERROR: TIMx output channel is not initialized + */ +ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, const LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct) +{ + ErrorStatus result = ERROR; + + switch (Channel) + { + case LL_TIM_CHANNEL_CH1: + result = IC1Config(TIMx, TIM_IC_InitStruct); + break; + case LL_TIM_CHANNEL_CH2: + result = IC2Config(TIMx, TIM_IC_InitStruct); + break; + case LL_TIM_CHANNEL_CH3: + result = IC3Config(TIMx, TIM_IC_InitStruct); + break; + case LL_TIM_CHANNEL_CH4: + result = IC4Config(TIMx, TIM_IC_InitStruct); + break; + default: + break; + } + + return result; +} + +/** + * @brief Fills each TIM_EncoderInitStruct field with its default value + * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (encoder interface + * configuration data structure) + * @retval None + */ +void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) +{ + /* Set the default configuration */ + TIM_EncoderInitStruct->EncoderMode = LL_TIM_ENCODERMODE_X2_TI1; + TIM_EncoderInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; + TIM_EncoderInitStruct->IC1ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; + TIM_EncoderInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; + TIM_EncoderInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; + TIM_EncoderInitStruct->IC2Polarity = LL_TIM_IC_POLARITY_RISING; + TIM_EncoderInitStruct->IC2ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; + TIM_EncoderInitStruct->IC2Prescaler = LL_TIM_ICPSC_DIV1; + TIM_EncoderInitStruct->IC2Filter = LL_TIM_IC_FILTER_FDIV1; +} + +/** + * @brief Configure the encoder interface of the timer instance. + * @param TIMx Timer Instance + * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (TIMx encoder interface + * configuration data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, const LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + + /* Check the parameters */ + assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_ENCODERMODE(TIM_EncoderInitStruct->EncoderMode)); + assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC1Polarity)); + assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC1ActiveInput)); + assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC1Prescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC1Filter)); + assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC2Polarity)); + assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC2ActiveInput)); + assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC2Prescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC2Filter)); + + /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ + TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); + + /* Get the TIMx CCMR1 register value */ + tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Configure TI1 */ + tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); + tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1ActiveInput >> 16U); + tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Filter >> 16U); + tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Prescaler >> 16U); + + /* Configure TI2 */ + tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC); + tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2ActiveInput >> 8U); + tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Filter >> 8U); + tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Prescaler >> 8U); + + /* Set TI1 and TI2 polarity and enable TI1 and TI2 */ + tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); + tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC1Polarity); + tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC2Polarity << 4U); + tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); + + /* Set encoder mode */ + LL_TIM_SetEncoderMode(TIMx, TIM_EncoderInitStruct->EncoderMode); + + /* Write to TIMx CCMR1 */ + LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Set the fields of the TIMx Hall sensor interface configuration data + * structure to their default values. + * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (HALL sensor interface + * configuration data structure) + * @retval None + */ +void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) +{ + /* Set the default configuration */ + TIM_HallSensorInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; + TIM_HallSensorInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; + TIM_HallSensorInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; + TIM_HallSensorInitStruct->CommutationDelay = 0U; +} + +/** + * @brief Configure the Hall sensor interface of the timer instance. + * @note TIMx CH1, CH2 and CH3 inputs connected through a XOR + * to the TI1 input channel + * @note TIMx slave mode controller is configured in reset mode. + Selected internal trigger is TI1F_ED. + * @note Channel 1 is configured as input, IC1 is mapped on TRC. + * @note Captured value stored in TIMx_CCR1 correspond to the time elapsed + * between 2 changes on the inputs. It gives information about motor speed. + * @note Channel 2 is configured in output PWM 2 mode. + * @note Compare value stored in TIMx_CCR2 corresponds to the commutation delay. + * @note OC2REF is selected as trigger output on TRGO. + * @note LL_TIM_IC_POLARITY_BOTHEDGE must not be used for TI1 when it is used + * when TIMx operates in Hall sensor interface mode. + * @param TIMx Timer Instance + * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (TIMx HALL sensor + * interface configuration data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, const LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) +{ + uint32_t tmpcr2; + uint32_t tmpccmr1; + uint32_t tmpccer; + uint32_t tmpsmcr; + + /* Check the parameters */ + assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_HallSensorInitStruct->IC1Polarity)); + assert_param(IS_LL_TIM_ICPSC(TIM_HallSensorInitStruct->IC1Prescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_HallSensorInitStruct->IC1Filter)); + + /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ + TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); + + /* Get the TIMx CR2 register value */ + tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); + + /* Get the TIMx CCMR1 register value */ + tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx SMCR register value */ + tmpsmcr = LL_TIM_ReadReg(TIMx, SMCR); + + /* Connect TIMx_CH1, CH2 and CH3 pins to the TI1 input */ + tmpcr2 |= TIM_CR2_TI1S; + + /* OC2REF signal is used as trigger output (TRGO) */ + tmpcr2 |= LL_TIM_TRGO_OC2REF; + + /* Configure the slave mode controller */ + tmpsmcr &= (uint32_t)~(TIM_SMCR_TS | TIM_SMCR_SMS); + tmpsmcr |= LL_TIM_TS_TI1F_ED; + tmpsmcr |= LL_TIM_SLAVEMODE_RESET; + + /* Configure input channel 1 */ + tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); + tmpccmr1 |= (uint32_t)(LL_TIM_ACTIVEINPUT_TRC >> 16U); + tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Filter >> 16U); + tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Prescaler >> 16U); + + /* Configure input channel 2 */ + tmpccmr1 &= (uint32_t)~(TIM_CCMR1_OC2M | TIM_CCMR1_OC2FE | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2CE); + tmpccmr1 |= (uint32_t)(LL_TIM_OCMODE_PWM2 << 8U); + + /* Set Channel 1 polarity and enable Channel 1 and Channel2 */ + tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); + tmpccer |= (uint32_t)(TIM_HallSensorInitStruct->IC1Polarity); + tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); + + /* Write to TIMx CR2 */ + LL_TIM_WriteReg(TIMx, CR2, tmpcr2); + + /* Write to TIMx SMCR */ + LL_TIM_WriteReg(TIMx, SMCR, tmpsmcr); + + /* Write to TIMx CCMR1 */ + LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + /* Write to TIMx CCR2 */ + LL_TIM_OC_SetCompareCH2(TIMx, TIM_HallSensorInitStruct->CommutationDelay); + + return SUCCESS; +} + +/** + * @brief Set the fields of the Break and Dead Time configuration data structure + * to their default values. + * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration + * data structure) + * @retval None + */ +void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) +{ + /* Set the default configuration */ + TIM_BDTRInitStruct->OSSRState = LL_TIM_OSSR_DISABLE; + TIM_BDTRInitStruct->OSSIState = LL_TIM_OSSI_DISABLE; + TIM_BDTRInitStruct->LockLevel = LL_TIM_LOCKLEVEL_OFF; + TIM_BDTRInitStruct->DeadTime = (uint8_t)0x00; + TIM_BDTRInitStruct->BreakState = LL_TIM_BREAK_DISABLE; + TIM_BDTRInitStruct->BreakPolarity = LL_TIM_BREAK_POLARITY_LOW; + TIM_BDTRInitStruct->BreakFilter = LL_TIM_BREAK_FILTER_FDIV1; + TIM_BDTRInitStruct->BreakAFMode = LL_TIM_BREAK_AFMODE_INPUT; + TIM_BDTRInitStruct->Break2State = LL_TIM_BREAK2_DISABLE; + TIM_BDTRInitStruct->Break2Polarity = LL_TIM_BREAK2_POLARITY_LOW; + TIM_BDTRInitStruct->Break2Filter = LL_TIM_BREAK2_FILTER_FDIV1; + TIM_BDTRInitStruct->Break2AFMode = LL_TIM_BREAK2_AFMODE_INPUT; + TIM_BDTRInitStruct->AutomaticOutput = LL_TIM_AUTOMATICOUTPUT_DISABLE; +} + +/** + * @brief Configure the Break and Dead Time feature of the timer instance. + * @note As the bits BK2P, BK2E, BK2F[3:0], BKF[3:0], AOE, BKP, BKE, OSSI, OSSR + * and DTG[7:0] can be write-locked depending on the LOCK configuration, it + * can be necessary to configure all of them during the first write access to + * the TIMx_BDTR register. + * @note Macro IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not + * a timer instance provides a break input. + * @note Macro IS_TIM_BKIN2_INSTANCE(TIMx) can be used to check whether or not + * a timer instance provides a second break input. + * @param TIMx Timer Instance + * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration + * data structure) + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Break and Dead Time is initialized + * - ERROR: not applicable + */ +ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, const LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) +{ + uint32_t tmpbdtr = 0; + + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OSSR_STATE(TIM_BDTRInitStruct->OSSRState)); + assert_param(IS_LL_TIM_OSSI_STATE(TIM_BDTRInitStruct->OSSIState)); + assert_param(IS_LL_TIM_LOCK_LEVEL(TIM_BDTRInitStruct->LockLevel)); + assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState)); + assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity)); + assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput)); + assert_param(IS_LL_TIM_BREAK_FILTER(TIM_BDTRInitStruct->BreakFilter)); + assert_param(IS_LL_TIM_BREAK_AFMODE(TIM_BDTRInitStruct->BreakAFMode)); + + /* 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 */ + + /* Set the BDTR bits */ + MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, TIM_BDTRInitStruct->DeadTime); + MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, TIM_BDTRInitStruct->LockLevel); + MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, TIM_BDTRInitStruct->OSSIState); + MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, TIM_BDTRInitStruct->OSSRState); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity); + MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKF, TIM_BDTRInitStruct->BreakFilter); + MODIFY_REG(tmpbdtr, TIM_BDTR_BKBID, TIM_BDTRInitStruct->BreakAFMode); + + if (IS_TIM_BKIN2_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_BREAK2_STATE(TIM_BDTRInitStruct->Break2State)); + assert_param(IS_LL_TIM_BREAK2_POLARITY(TIM_BDTRInitStruct->Break2Polarity)); + assert_param(IS_LL_TIM_BREAK2_FILTER(TIM_BDTRInitStruct->Break2Filter)); + assert_param(IS_LL_TIM_BREAK2_AFMODE(TIM_BDTRInitStruct->Break2AFMode)); + + /* Set the BREAK2 input related BDTR bit-fields */ + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2F, (TIM_BDTRInitStruct->Break2Filter)); + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2E, TIM_BDTRInitStruct->Break2State); + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2P, TIM_BDTRInitStruct->Break2Polarity); + MODIFY_REG(tmpbdtr, TIM_BDTR_BK2BID, TIM_BDTRInitStruct->Break2AFMode); + } + + /* Set TIMx_BDTR */ + LL_TIM_WriteReg(TIMx, BDTR, tmpbdtr); + + return SUCCESS; +} +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup TIM_LL_Private_Functions TIM Private Functions + * @brief Private functions + * @{ + */ +/** + * @brief Configure the TIMx output channel 1. + * @param TIMx Timer Instance + * @param TIM_OCInitStruct pointer to the the TIMx output channel 1 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC1Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); + + /* Disable the Channel 1: Reset the CC1E Bit */ + CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx CR2 register value */ + tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); + + /* Get the TIMx CCMR1 register value */ + tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC1S); + + /* Set the Output Compare Mode */ + MODIFY_REG(tmpccmr1, TIM_CCMR1_OC1M, TIM_OCInitStruct->OCMode); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC1P, TIM_OCInitStruct->OCPolarity); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC1E, TIM_OCInitStruct->OCState); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC1NE, TIM_OCInitStruct->OCNState << 2U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS1, TIM_OCInitStruct->OCIdleState); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS1N, TIM_OCInitStruct->OCNIdleState << 1U); + } + + /* Write to TIMx CR2 */ + LL_TIM_WriteReg(TIMx, CR2, tmpcr2); + + /* Write to TIMx CCMR1 */ + LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); + + /* Set the Capture Compare Register value */ + LL_TIM_OC_SetCompareCH1(TIMx, TIM_OCInitStruct->CompareValue); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx output channel 2. + * @param TIMx Timer Instance + * @param TIM_OCInitStruct pointer to the the TIMx output channel 2 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC2Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) +{ + uint32_t tmpccmr1; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); + + /* Disable the Channel 2: Reset the CC2E Bit */ + CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx CR2 register value */ + tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); + + /* Get the TIMx CCMR1 register value */ + tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC2S); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr1, TIM_CCMR1_OC2M, TIM_OCInitStruct->OCMode << 8U); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC2P, TIM_OCInitStruct->OCPolarity << 4U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC2E, TIM_OCInitStruct->OCState << 4U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC2NE, TIM_OCInitStruct->OCNState << 6U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS2, TIM_OCInitStruct->OCIdleState << 2U); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS2N, TIM_OCInitStruct->OCNIdleState << 3U); + } + + /* Write to TIMx CR2 */ + LL_TIM_WriteReg(TIMx, CR2, tmpcr2); + + /* Write to TIMx CCMR1 */ + LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); + + /* Set the Capture Compare Register value */ + LL_TIM_OC_SetCompareCH2(TIMx, TIM_OCInitStruct->CompareValue); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx output channel 3. + * @param TIMx Timer Instance + * @param TIM_OCInitStruct pointer to the the TIMx output channel 3 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC3Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + assert_param(IS_TIM_CC3_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); + + /* Disable the Channel 3: Reset the CC3E Bit */ + CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx CR2 register value */ + tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); + + /* Get the TIMx CCMR2 register value */ + tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC3S); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr2, TIM_CCMR2_OC3M, TIM_OCInitStruct->OCMode); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC3P, TIM_OCInitStruct->OCPolarity << 8U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC3E, TIM_OCInitStruct->OCState << 8U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC3NE, TIM_OCInitStruct->OCNState << 10U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS3, TIM_OCInitStruct->OCIdleState << 4U); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS3N, TIM_OCInitStruct->OCNIdleState << 5U); + } + + /* Write to TIMx CR2 */ + LL_TIM_WriteReg(TIMx, CR2, tmpcr2); + + /* Write to TIMx CCMR2 */ + LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); + + /* Set the Capture Compare Register value */ + LL_TIM_OC_SetCompareCH3(TIMx, TIM_OCInitStruct->CompareValue); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx output channel 4. + * @param TIMx Timer Instance + * @param TIM_OCInitStruct pointer to the the TIMx output channel 4 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC4Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) +{ + uint32_t tmpccmr2; + uint32_t tmpccer; + uint32_t tmpcr2; + + /* Check the parameters */ + assert_param(IS_TIM_CC4_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); + + /* Disable the Channel 4: Reset the CC4E Bit */ + CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx CR2 register value */ + tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); + + /* Get the TIMx CCMR2 register value */ + tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); + + /* Reset Capture/Compare selection Bits */ + CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC4S); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr2, TIM_CCMR2_OC4M, TIM_OCInitStruct->OCMode << 8U); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC4P, TIM_OCInitStruct->OCPolarity << 12U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC4E, TIM_OCInitStruct->OCState << 12U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); + + /* Set the complementary output Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC4NP, TIM_OCInitStruct->OCNPolarity << 14U); + + /* Set the complementary output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC4NE, TIM_OCInitStruct->OCNState << 14U); + + /* Set the Output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS4, TIM_OCInitStruct->OCIdleState << 6U); + + /* Set the complementary output Idle state */ + MODIFY_REG(tmpcr2, TIM_CR2_OIS4N, TIM_OCInitStruct->OCNIdleState << 7U); + } + + /* Write to TIMx CR2 */ + LL_TIM_WriteReg(TIMx, CR2, tmpcr2); + + /* Write to TIMx CCMR2 */ + LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); + + /* Set the Capture Compare Register value */ + LL_TIM_OC_SetCompareCH4(TIMx, TIM_OCInitStruct->CompareValue); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx output channel 5. + * @param TIMx Timer Instance + * @param TIM_OCInitStruct pointer to the the TIMx output channel 5 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC5Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) +{ + uint32_t tmpccmr3; + uint32_t tmpccer; + + /* Check the parameters */ + assert_param(IS_TIM_CC5_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + + /* Disable the Channel 5: Reset the CC5E Bit */ + CLEAR_BIT(TIMx->CCER, TIM_CCER_CC5E); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx CCMR3 register value */ + tmpccmr3 = LL_TIM_ReadReg(TIMx, CCMR3); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr3, TIM_CCMR3_OC5M, TIM_OCInitStruct->OCMode); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC5P, TIM_OCInitStruct->OCPolarity << 16U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC5E, TIM_OCInitStruct->OCState << 16U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + + /* Set the Output Idle state */ + MODIFY_REG(TIMx->CR2, TIM_CR2_OIS5, TIM_OCInitStruct->OCIdleState << 8U); + + } + + /* Write to TIMx CCMR3 */ + LL_TIM_WriteReg(TIMx, CCMR3, tmpccmr3); + + /* Set the Capture Compare Register value */ + LL_TIM_OC_SetCompareCH5(TIMx, TIM_OCInitStruct->CompareValue); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx output channel 6. + * @param TIMx Timer Instance + * @param TIM_OCInitStruct pointer to the the TIMx output channel 6 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus OC6Config(TIM_TypeDef *TIMx, const LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) +{ + uint32_t tmpccmr3; + uint32_t tmpccer; + + /* Check the parameters */ + assert_param(IS_TIM_CC6_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); + assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); + assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); + + /* Disable the Channel 5: Reset the CC6E Bit */ + CLEAR_BIT(TIMx->CCER, TIM_CCER_CC6E); + + /* Get the TIMx CCER register value */ + tmpccer = LL_TIM_ReadReg(TIMx, CCER); + + /* Get the TIMx CCMR3 register value */ + tmpccmr3 = LL_TIM_ReadReg(TIMx, CCMR3); + + /* Select the Output Compare Mode */ + MODIFY_REG(tmpccmr3, TIM_CCMR3_OC6M, TIM_OCInitStruct->OCMode << 8U); + + /* Set the Output Compare Polarity */ + MODIFY_REG(tmpccer, TIM_CCER_CC6P, TIM_OCInitStruct->OCPolarity << 20U); + + /* Set the Output State */ + MODIFY_REG(tmpccer, TIM_CCER_CC6E, TIM_OCInitStruct->OCState << 20U); + + if (IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); + assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); + + /* Set the Output Idle state */ + MODIFY_REG(TIMx->CR2, TIM_CR2_OIS6, TIM_OCInitStruct->OCIdleState << 10U); + } + + /* Write to TIMx CCMR3 */ + LL_TIM_WriteReg(TIMx, CCMR3, tmpccmr3); + + /* Set the Capture Compare Register value */ + LL_TIM_OC_SetCompareCH6(TIMx, TIM_OCInitStruct->CompareValue); + + /* Write to TIMx CCER */ + LL_TIM_WriteReg(TIMx, CCER, tmpccer); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx input channel 1. + * @param TIMx Timer Instance + * @param TIM_ICInitStruct pointer to the the TIMx input channel 1 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC1Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); + assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); + assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); + + /* Disable the Channel 1: Reset the CC1E Bit */ + TIMx->CCER &= (uint32_t)~TIM_CCER_CC1E; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TIMx->CCMR1, + (TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC), + (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); + + /* Select the Polarity and set the CC1E Bit */ + MODIFY_REG(TIMx->CCER, + (TIM_CCER_CC1P | TIM_CCER_CC1NP), + (TIM_ICInitStruct->ICPolarity | TIM_CCER_CC1E)); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx input channel 2. + * @param TIMx Timer Instance + * @param TIM_ICInitStruct pointer to the the TIMx input channel 2 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC2Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); + assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); + assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= (uint32_t)~TIM_CCER_CC2E; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TIMx->CCMR1, + (TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC), + (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); + + /* Select the Polarity and set the CC2E Bit */ + MODIFY_REG(TIMx->CCER, + (TIM_CCER_CC2P | TIM_CCER_CC2NP), + ((TIM_ICInitStruct->ICPolarity << 4U) | TIM_CCER_CC2E)); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx input channel 3. + * @param TIMx Timer Instance + * @param TIM_ICInitStruct pointer to the the TIMx input channel 3 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC3Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC3_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); + assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); + assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); + + /* Disable the Channel 3: Reset the CC3E Bit */ + TIMx->CCER &= (uint32_t)~TIM_CCER_CC3E; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TIMx->CCMR2, + (TIM_CCMR2_CC3S | TIM_CCMR2_IC3F | TIM_CCMR2_IC3PSC), + (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); + + /* Select the Polarity and set the CC3E Bit */ + MODIFY_REG(TIMx->CCER, + (TIM_CCER_CC3P | TIM_CCER_CC3NP), + ((TIM_ICInitStruct->ICPolarity << 8U) | TIM_CCER_CC3E)); + + return SUCCESS; +} + +/** + * @brief Configure the TIMx input channel 4. + * @param TIMx Timer Instance + * @param TIM_ICInitStruct pointer to the the TIMx input channel 4 configuration data structure + * @retval An ErrorStatus enumeration value: + * - SUCCESS: TIMx registers are de-initialized + * - ERROR: not applicable + */ +static ErrorStatus IC4Config(TIM_TypeDef *TIMx, const LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC4_INSTANCE(TIMx)); + assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); + assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); + assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); + assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); + + /* Disable the Channel 4: Reset the CC4E Bit */ + TIMx->CCER &= (uint32_t)~TIM_CCER_CC4E; + + /* Select the Input and set the filter and the prescaler value */ + MODIFY_REG(TIMx->CCMR2, + (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), + (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); + + /* Select the Polarity and set the CC4E Bit */ + MODIFY_REG(TIMx->CCER, + (TIM_CCER_CC4P | TIM_CCER_CC4NP), + ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); + + return SUCCESS; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* TIM1 || TIM2 || TIM3 || TIM4 || TIM5 || TIM6 || TIM7 || TIM9 || TIM12 || TIM13 || TIM14 || TIM15 || TIM16 || TIM17 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_ucpd.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_ucpd.c index 00185e672..8bf687b86 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_ucpd.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_ucpd.c @@ -1,169 +1,168 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_ucpd.c - * @author MCD Application Team - * @brief UCPD LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_ucpd.h" -#include "stm32h7rsxx_ll_bus.h" -#include "stm32h7rsxx_ll_rcc.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ -#if defined (UCPD1) -/** @addtogroup UCPD_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup UCPD_LL_Private_Constants UCPD Private Constants - * @{ - */ - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup UCPD_LL_Private_Macros UCPD Private Macros - * @{ - */ - - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup UCPD_LL_Exported_Functions - * @{ - */ - -/** @addtogroup UCPD_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the UCPD registers to their default reset values. - * @param UCPDx ucpd Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ucpd registers are de-initialized - * - ERROR: ucpd registers are not de-initialized - */ -ErrorStatus LL_UCPD_DeInit(UCPD_TypeDef *UCPDx) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); - - LL_UCPD_Disable(UCPDx); - - if (UCPD1 == UCPDx) - { - /* Force reset of ucpd clock */ - LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_UCPD1); - - /* Release reset of ucpd clock */ - LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_UCPD1); - - /* Disable ucpd clock */ - LL_APB1_GRP2_DisableClock(LL_APB1_GRP2_PERIPH_UCPD1); - - status = SUCCESS; - } - - return status; -} - -/** - * @brief Initialize the ucpd registers according to the specified parameters in UCPD_InitStruct. - * @note As some bits in ucpd configuration registers can only be written when the ucpd is disabled - * (ucpd_CR1_SPE bit =0), UCPD peripheral should be in disabled state prior calling this function. - * Otherwise, ERROR result will be returned. - * @param UCPDx UCPD Instance - * @param UCPD_InitStruct pointer to a @ref LL_UCPD_InitTypeDef structure that contains - * the configuration information for the UCPD peripheral. - * @retval An ErrorStatus enumeration value. (Return always SUCCESS) - */ -ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, const LL_UCPD_InitTypeDef *UCPD_InitStruct) -{ - /* Check the ucpd Instance UCPDx*/ - assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); - - if (UCPD1 == UCPDx) - { - LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_UCPD1); - } - - - LL_UCPD_Disable(UCPDx); - - /*---------------------------- UCPDx CFG1 Configuration ------------------------*/ - MODIFY_REG(UCPDx->CFG1, - UCPD_CFG1_PSC_UCPDCLK | UCPD_CFG1_TRANSWIN | UCPD_CFG1_IFRGAP | UCPD_CFG1_HBITCLKDIV, - UCPD_InitStruct->psc_ucpdclk | (UCPD_InitStruct->transwin << UCPD_CFG1_TRANSWIN_Pos) | - (UCPD_InitStruct->IfrGap << UCPD_CFG1_IFRGAP_Pos) | UCPD_InitStruct->HbitClockDiv); - - return SUCCESS; -} - -/** - * @brief Set each @ref LL_UCPD_InitTypeDef field to default value. - * @param UCPD_InitStruct pointer to a @ref LL_UCPD_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_UCPD_StructInit(LL_UCPD_InitTypeDef *UCPD_InitStruct) -{ - /* Set UCPD_InitStruct fields to default values */ - UCPD_InitStruct->psc_ucpdclk = LL_UCPD_PSC_DIV2; - UCPD_InitStruct->transwin = 0x7; /* Divide by 8 */ - UCPD_InitStruct->IfrGap = 0x10; /* Divide by 17 */ - UCPD_InitStruct->HbitClockDiv = 0x0D; /* Divide by 14 to produce HBITCLK */ -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* defined (UCPD1) */ -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_ucpd.c + * @author MCD Application Team + * @brief UCPD LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_ucpd.h" +#include "stm32h7rsxx_ll_bus.h" +#include "stm32h7rsxx_ll_rcc.h" + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ +#if defined (UCPD1) +/** @addtogroup UCPD_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup UCPD_LL_Private_Constants UCPD Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @defgroup UCPD_LL_Private_Macros UCPD Private Macros + * @{ + */ + + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup UCPD_LL_Exported_Functions + * @{ + */ + +/** @addtogroup UCPD_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize the UCPD registers to their default reset values. + * @param UCPDx ucpd Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: ucpd registers are de-initialized + * - ERROR: ucpd registers are not de-initialized + */ +ErrorStatus LL_UCPD_DeInit(UCPD_TypeDef *UCPDx) +{ + ErrorStatus status = ERROR; + + /* Check the parameters */ + assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); + + LL_UCPD_Disable(UCPDx); + + if (UCPD1 == UCPDx) + { + /* Force reset of ucpd clock */ + LL_APB1_GRP2_ForceReset(LL_APB1_GRP2_PERIPH_UCPD1); + + /* Release reset of ucpd clock */ + LL_APB1_GRP2_ReleaseReset(LL_APB1_GRP2_PERIPH_UCPD1); + + /* Disable ucpd clock */ + LL_APB1_GRP2_DisableClock(LL_APB1_GRP2_PERIPH_UCPD1); + + status = SUCCESS; + } + + return status; +} + +/** + * @brief Initialize the ucpd registers according to the specified parameters in UCPD_InitStruct. + * @note As some bits in ucpd configuration registers can only be written when the ucpd is disabled + * (ucpd_CR1_SPE bit =0), UCPD peripheral should be in disabled state prior calling this function. + * Otherwise, ERROR result will be returned. + * @param UCPDx UCPD Instance + * @param UCPD_InitStruct pointer to a @ref LL_UCPD_InitTypeDef structure that contains + * the configuration information for the UCPD peripheral. + * @retval An ErrorStatus enumeration value. (Return always SUCCESS) + */ +ErrorStatus LL_UCPD_Init(UCPD_TypeDef *UCPDx, const LL_UCPD_InitTypeDef *UCPD_InitStruct) +{ + /* Check the ucpd Instance UCPDx*/ + assert_param(IS_UCPD_ALL_INSTANCE(UCPDx)); + + if (UCPD1 == UCPDx) + { + LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_UCPD1); + } + + + LL_UCPD_Disable(UCPDx); + + /*---------------------------- UCPDx CFG1 Configuration ------------------------*/ + MODIFY_REG(UCPDx->CFG1, + UCPD_CFG1_PSC_UCPDCLK | UCPD_CFG1_TRANSWIN | UCPD_CFG1_IFRGAP | UCPD_CFG1_HBITCLKDIV, + UCPD_InitStruct->psc_ucpdclk | (UCPD_InitStruct->transwin << UCPD_CFG1_TRANSWIN_Pos) | + (UCPD_InitStruct->IfrGap << UCPD_CFG1_IFRGAP_Pos) | UCPD_InitStruct->HbitClockDiv); + + return SUCCESS; +} + +/** + * @brief Set each @ref LL_UCPD_InitTypeDef field to default value. + * @param UCPD_InitStruct pointer to a @ref LL_UCPD_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_UCPD_StructInit(LL_UCPD_InitTypeDef *UCPD_InitStruct) +{ + /* Set UCPD_InitStruct fields to default values */ + UCPD_InitStruct->psc_ucpdclk = LL_UCPD_PSC_DIV2; + UCPD_InitStruct->transwin = 0x7; /* Divide by 8 */ + UCPD_InitStruct->IfrGap = 0x10; /* Divide by 17 */ + UCPD_InitStruct->HbitClockDiv = 0x0D; /* Divide by 14 to produce HBITCLK */ +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (UCPD1) */ +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usart.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usart.c index aea3b7d29..9cf4e6563 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usart.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usart.c @@ -1,451 +1,449 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_usart.c - * @author MCD Application Team - * @brief USART LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_usart.h" -#include "stm32h7rsxx_ll_rcc.h" -#include "stm32h7rsxx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -#if defined(USART1) || defined(USART2) || defined(USART3) || defined(UART4) || defined(UART5) \ - || defined(UART7) || defined(UART8) - -/** @addtogroup USART_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup USART_LL_Private_Constants - * @{ - */ - -/* Definition of default baudrate value used for USART initialisation */ -#define USART_DEFAULT_BAUDRATE (9600U) - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup USART_LL_Private_Macros - * @{ - */ - -#define IS_LL_USART_PRESCALER(__VALUE__) (((__VALUE__) == LL_USART_PRESCALER_DIV1) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV2) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV4) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV6) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV8) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV10) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV12) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV16) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV32) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV64) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV128) \ - || ((__VALUE__) == LL_USART_PRESCALER_DIV256)) - -/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available - * divided by the smallest oversampling used on the USART (i.e. 8) */ -#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 12500000U) - -/* __VALUE__ In case of oversampling by 16 and 8, BRR content must be greater than or equal to 16d. */ -#define IS_LL_USART_BRR_MIN(__VALUE__) ((__VALUE__) >= 16U) - -#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \ - || ((__VALUE__) == LL_USART_DIRECTION_RX) \ - || ((__VALUE__) == LL_USART_DIRECTION_TX) \ - || ((__VALUE__) == LL_USART_DIRECTION_TX_RX)) - -#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \ - || ((__VALUE__) == LL_USART_PARITY_EVEN) \ - || ((__VALUE__) == LL_USART_PARITY_ODD)) - -#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \ - || ((__VALUE__) == LL_USART_DATAWIDTH_8B) \ - || ((__VALUE__) == LL_USART_DATAWIDTH_9B)) - -#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \ - || ((__VALUE__) == LL_USART_OVERSAMPLING_8)) - -#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \ - || ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT)) - -#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \ - || ((__VALUE__) == LL_USART_PHASE_2EDGE)) - -#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \ - || ((__VALUE__) == LL_USART_POLARITY_HIGH)) - -#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \ - || ((__VALUE__) == LL_USART_CLOCK_ENABLE)) - -#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \ - || ((__VALUE__) == LL_USART_STOPBITS_1) \ - || ((__VALUE__) == LL_USART_STOPBITS_1_5) \ - || ((__VALUE__) == LL_USART_STOPBITS_2)) - -#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \ - || ((__VALUE__) == LL_USART_HWCONTROL_RTS) \ - || ((__VALUE__) == LL_USART_HWCONTROL_CTS) \ - || ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS)) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup USART_LL_Exported_Functions - * @{ - */ - -/** @addtogroup USART_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize USART registers (Registers restored to their default values). - * @param USARTx USART Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: USART registers are de-initialized - * - ERROR: USART registers are not de-initialized - */ -ErrorStatus LL_USART_DeInit(const USART_TypeDef *USARTx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_UART_INSTANCE(USARTx)); - - if (USARTx == USART1) - { - /* Force reset of USART clock */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1); - - /* Release reset of USART clock */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1); - } - else if (USARTx == USART2) - { - /* Force reset of USART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2); - - /* Release reset of USART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2); - } - else if (USARTx == USART3) - { - /* Force reset of USART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3); - - /* Release reset of USART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3); - } - else if (USARTx == UART4) - { - /* Force reset of UART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART4); - - /* Release reset of UART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART4); - } - else if (USARTx == UART5) - { - /* Force reset of UART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART5); - - /* Release reset of UART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART5); - } - else if (USARTx == UART7) - { - /* Force reset of UART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART7); - - /* Release reset of UART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART7); - } - else if (USARTx == UART8) - { - /* Force reset of UART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART8); - - /* Release reset of UART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART8); - } - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Initialize USART registers according to the specified - * parameters in USART_InitStruct. - * @note As some bits in USART configuration registers can only be written when - * the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling - * this function. Otherwise, ERROR result will be returned. - * @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0). - * @param USARTx USART Instance - * @param USART_InitStruct pointer to a LL_USART_InitTypeDef structure - * that contains the configuration information for the specified USART peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: USART registers are initialized according to USART_InitStruct content - * - ERROR: Problem occurred during USART Registers initialization - */ -ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, const LL_USART_InitTypeDef *USART_InitStruct) -{ - ErrorStatus status = ERROR; - uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO; - - /* Check the parameters */ - assert_param(IS_UART_INSTANCE(USARTx)); - assert_param(IS_LL_USART_PRESCALER(USART_InitStruct->PrescalerValue)); - assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate)); - assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth)); - assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits)); - assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity)); - assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection)); - assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl)); - assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling)); - - /* USART needs to be in disabled state, in order to be able to configure some bits in - CRx registers */ - if (LL_USART_IsEnabled(USARTx) == 0U) - { - /*---------------------------- USART CR1 Configuration --------------------- - * Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters: - * - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value - * - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value - * - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value - * - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value. - */ - MODIFY_REG(USARTx->CR1, - (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | - USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8), - (USART_InitStruct->DataWidth | USART_InitStruct->Parity | - USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling)); - - /*---------------------------- USART CR2 Configuration --------------------- - * Configure USARTx CR2 (Stop bits) with parameters: - * - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value. - * - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit(). - */ - LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits); - - /*---------------------------- USART CR3 Configuration --------------------- - * Configure USARTx CR3 (Hardware Flow Control) with parameters: - * - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to - * USART_InitStruct->HardwareFlowControl value. - */ - LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl); - - /*---------------------------- USART BRR Configuration --------------------- - * Retrieve Clock frequency used for USART Peripheral - */ - if (USARTx == USART1) - { - periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE); - } - else if (USARTx == USART2) - { - periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART234578_CLKSOURCE); - } - else if (USARTx == USART3) - { - periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART234578_CLKSOURCE); - } - else if (USARTx == UART4) - { - periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); - } - else if (USARTx == UART5) - { - periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); - } - else if (USARTx == UART7) - { - periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); - } - else if (USARTx == UART8) - { - periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); - } - else - { - /* Nothing to do, as error code is already assigned to ERROR value */ - } - - /* Configure the USART Baud Rate : - - prescaler value is required - - valid baud rate value (different from 0) is required - - Peripheral clock as returned by RCC service, should be valid (different from 0). - */ - if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO) - && (USART_InitStruct->BaudRate != 0U)) - { - status = SUCCESS; - LL_USART_SetBaudRate(USARTx, - periphclk, - USART_InitStruct->PrescalerValue, - USART_InitStruct->OverSampling, - USART_InitStruct->BaudRate); - - /* Check BRR is greater than or equal to 16d */ - assert_param(IS_LL_USART_BRR_MIN(USARTx->BRR)); - } - - /*---------------------------- USART PRESC Configuration ----------------------- - * Configure USARTx PRESC (Prescaler) with parameters: - * - PrescalerValue: USART_PRESC_PRESCALER bits according to USART_InitStruct->PrescalerValue value. - */ - LL_USART_SetPrescaler(USARTx, USART_InitStruct->PrescalerValue); - } - /* Endif (=> USART not in Disabled state => return ERROR) */ - - return (status); -} - -/** - * @brief Set each @ref LL_USART_InitTypeDef field to default value. - * @param USART_InitStruct pointer to a @ref LL_USART_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ - -void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct) -{ - /* Set USART_InitStruct fields to default values */ - USART_InitStruct->PrescalerValue = LL_USART_PRESCALER_DIV1; - USART_InitStruct->BaudRate = USART_DEFAULT_BAUDRATE; - USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B; - USART_InitStruct->StopBits = LL_USART_STOPBITS_1; - USART_InitStruct->Parity = LL_USART_PARITY_NONE ; - USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX; - USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE; - USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16; -} - -/** - * @brief Initialize USART Clock related settings according to the - * specified parameters in the USART_ClockInitStruct. - * @note As some bits in USART configuration registers can only be written when - * the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling - * this function. Otherwise, ERROR result will be returned. - * @param USARTx USART Instance - * @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure - * that contains the Clock configuration information for the specified USART peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: USART registers related to Clock settings are initialized according - * to USART_ClockInitStruct content - * - ERROR: Problem occurred during USART Registers initialization - */ -ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, const LL_USART_ClockInitTypeDef *USART_ClockInitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check USART Instance and Clock signal output parameters */ - assert_param(IS_UART_INSTANCE(USARTx)); - assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput)); - - /* USART needs to be in disabled state, in order to be able to configure some bits in - CRx registers */ - if (LL_USART_IsEnabled(USARTx) == 0U) - { - /* Ensure USART instance is USART capable */ - assert_param(IS_USART_INSTANCE(USARTx)); - - /* Check clock related parameters */ - assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity)); - assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase)); - assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse)); - - /*---------------------------- USART CR2 Configuration ----------------------- - * Configure USARTx CR2 (Clock signal related bits) with parameters: - * - Clock Output: USART_CR2_CLKEN bit according to USART_ClockInitStruct->ClockOutput value - * - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value - * - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value - * - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value. - */ - MODIFY_REG(USARTx->CR2, - USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL, - USART_ClockInitStruct->ClockOutput | USART_ClockInitStruct->ClockPolarity | - USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse); - } - /* Else (USART not in Disabled state => return ERROR */ - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value. - * @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct) -{ - /* Set LL_USART_ClockInitStruct fields with default values */ - USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE; - USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = - LL_USART_CLOCK_DISABLE */ - USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = - LL_USART_CLOCK_DISABLE */ - USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = - LL_USART_CLOCK_DISABLE */ -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* USART1 || USART2 || USART3 || UART4 || UART5 || UART7 || UART8 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - - +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_usart.c + * @author MCD Application Team + * @brief USART LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +#if defined(USE_FULL_LL_DRIVER) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_usart.h" +#include "stm32h7rsxx_ll_rcc.h" +#include "stm32h7rsxx_ll_bus.h" +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +#if defined(USART1) || defined(USART2) || defined(USART3) || defined(UART4) || defined(UART5) \ + || defined(UART7) || defined(UART8) + +/** @addtogroup USART_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup USART_LL_Private_Constants + * @{ + */ + +/* Definition of default baudrate value used for USART initialisation */ +#define USART_DEFAULT_BAUDRATE (9600U) + +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup USART_LL_Private_Macros + * @{ + */ + +#define IS_LL_USART_PRESCALER(__VALUE__) (((__VALUE__) == LL_USART_PRESCALER_DIV1) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV2) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV4) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV6) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV8) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV10) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV12) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV16) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV32) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV64) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV128) \ + || ((__VALUE__) == LL_USART_PRESCALER_DIV256)) + +/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available + * divided by the smallest oversampling used on the USART (i.e. 8) */ +#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 12500000U) + +/* __VALUE__ In case of oversampling by 16 and 8, BRR content must be greater than or equal to 16d. */ +#define IS_LL_USART_BRR_MIN(__VALUE__) ((__VALUE__) >= 16U) + +#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \ + || ((__VALUE__) == LL_USART_DIRECTION_RX) \ + || ((__VALUE__) == LL_USART_DIRECTION_TX) \ + || ((__VALUE__) == LL_USART_DIRECTION_TX_RX)) + +#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \ + || ((__VALUE__) == LL_USART_PARITY_EVEN) \ + || ((__VALUE__) == LL_USART_PARITY_ODD)) + +#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_7B) \ + || ((__VALUE__) == LL_USART_DATAWIDTH_8B) \ + || ((__VALUE__) == LL_USART_DATAWIDTH_9B)) + +#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \ + || ((__VALUE__) == LL_USART_OVERSAMPLING_8)) + +#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \ + || ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT)) + +#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \ + || ((__VALUE__) == LL_USART_PHASE_2EDGE)) + +#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \ + || ((__VALUE__) == LL_USART_POLARITY_HIGH)) + +#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \ + || ((__VALUE__) == LL_USART_CLOCK_ENABLE)) + +#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \ + || ((__VALUE__) == LL_USART_STOPBITS_1) \ + || ((__VALUE__) == LL_USART_STOPBITS_1_5) \ + || ((__VALUE__) == LL_USART_STOPBITS_2)) + +#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \ + || ((__VALUE__) == LL_USART_HWCONTROL_RTS) \ + || ((__VALUE__) == LL_USART_HWCONTROL_CTS) \ + || ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS)) + +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup USART_LL_Exported_Functions + * @{ + */ + +/** @addtogroup USART_LL_EF_Init + * @{ + */ + +/** + * @brief De-initialize USART registers (Registers restored to their default values). + * @param USARTx USART Instance + * @retval An ErrorStatus enumeration value: + * - SUCCESS: USART registers are de-initialized + * - ERROR: USART registers are not de-initialized + */ +ErrorStatus LL_USART_DeInit(const USART_TypeDef *USARTx) +{ + ErrorStatus status = SUCCESS; + + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(USARTx)); + + if (USARTx == USART1) + { + /* Force reset of USART clock */ + LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1); + + /* Release reset of USART clock */ + LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1); + } + else if (USARTx == USART2) + { + /* Force reset of USART clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2); + + /* Release reset of USART clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2); + } + else if (USARTx == USART3) + { + /* Force reset of USART clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3); + + /* Release reset of USART clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3); + } + else if (USARTx == UART4) + { + /* Force reset of UART clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART4); + + /* Release reset of UART clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART4); + } + else if (USARTx == UART5) + { + /* Force reset of UART clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART5); + + /* Release reset of UART clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART5); + } + else if (USARTx == UART7) + { + /* Force reset of UART clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART7); + + /* Release reset of UART clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART7); + } + else if (USARTx == UART8) + { + /* Force reset of UART clock */ + LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART8); + + /* Release reset of UART clock */ + LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART8); + } + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Initialize USART registers according to the specified + * parameters in USART_InitStruct. + * @note As some bits in USART configuration registers can only be written when + * the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling + * this function. Otherwise, ERROR result will be returned. + * @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0). + * @param USARTx USART Instance + * @param USART_InitStruct pointer to a LL_USART_InitTypeDef structure + * that contains the configuration information for the specified USART peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: USART registers are initialized according to USART_InitStruct content + * - ERROR: Problem occurred during USART Registers initialization + */ +ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, const LL_USART_InitTypeDef *USART_InitStruct) +{ + ErrorStatus status = ERROR; + uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO; + + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(USARTx)); + assert_param(IS_LL_USART_PRESCALER(USART_InitStruct->PrescalerValue)); + assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate)); + assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth)); + assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits)); + assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity)); + assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection)); + assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl)); + assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling)); + + /* USART needs to be in disabled state, in order to be able to configure some bits in + CRx registers */ + if (LL_USART_IsEnabled(USARTx) == 0U) + { + /*---------------------------- USART CR1 Configuration --------------------- + * Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters: + * - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value + * - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value + * - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value + * - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value. + */ + MODIFY_REG(USARTx->CR1, + (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | + USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8), + (USART_InitStruct->DataWidth | USART_InitStruct->Parity | + USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling)); + + /*---------------------------- USART CR2 Configuration --------------------- + * Configure USARTx CR2 (Stop bits) with parameters: + * - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value. + * - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit(). + */ + LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits); + + /*---------------------------- USART CR3 Configuration --------------------- + * Configure USARTx CR3 (Hardware Flow Control) with parameters: + * - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to + * USART_InitStruct->HardwareFlowControl value. + */ + LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl); + + /*---------------------------- USART BRR Configuration --------------------- + * Retrieve Clock frequency used for USART Peripheral + */ + if (USARTx == USART1) + { + periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE); + } + else if (USARTx == USART2) + { + periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART234578_CLKSOURCE); + } + else if (USARTx == USART3) + { + periphclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART234578_CLKSOURCE); + } + else if (USARTx == UART4) + { + periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); + } + else if (USARTx == UART5) + { + periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); + } + else if (USARTx == UART7) + { + periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); + } + else if (USARTx == UART8) + { + periphclk = LL_RCC_GetUARTClockFreq(LL_RCC_USART234578_CLKSOURCE); + } + else + { + /* Nothing to do, as error code is already assigned to ERROR value */ + } + + /* Configure the USART Baud Rate : + - prescaler value is required + - valid baud rate value (different from 0) is required + - Peripheral clock as returned by RCC service, should be valid (different from 0). + */ + if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO) + && (USART_InitStruct->BaudRate != 0U)) + { + status = SUCCESS; + LL_USART_SetBaudRate(USARTx, + periphclk, + USART_InitStruct->PrescalerValue, + USART_InitStruct->OverSampling, + USART_InitStruct->BaudRate); + + /* Check BRR is greater than or equal to 16d */ + assert_param(IS_LL_USART_BRR_MIN(USARTx->BRR)); + } + + /*---------------------------- USART PRESC Configuration ----------------------- + * Configure USARTx PRESC (Prescaler) with parameters: + * - PrescalerValue: USART_PRESC_PRESCALER bits according to USART_InitStruct->PrescalerValue value. + */ + LL_USART_SetPrescaler(USARTx, USART_InitStruct->PrescalerValue); + } + /* Endif (=> USART not in Disabled state => return ERROR) */ + + return (status); +} + +/** + * @brief Set each @ref LL_USART_InitTypeDef field to default value. + * @param USART_InitStruct pointer to a @ref LL_USART_InitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ + +void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct) +{ + /* Set USART_InitStruct fields to default values */ + USART_InitStruct->PrescalerValue = LL_USART_PRESCALER_DIV1; + USART_InitStruct->BaudRate = USART_DEFAULT_BAUDRATE; + USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B; + USART_InitStruct->StopBits = LL_USART_STOPBITS_1; + USART_InitStruct->Parity = LL_USART_PARITY_NONE ; + USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX; + USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE; + USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16; +} + +/** + * @brief Initialize USART Clock related settings according to the + * specified parameters in the USART_ClockInitStruct. + * @note As some bits in USART configuration registers can only be written when + * the USART is disabled (USART_CR1_UE bit =0), USART Peripheral should be in disabled state prior calling + * this function. Otherwise, ERROR result will be returned. + * @param USARTx USART Instance + * @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure + * that contains the Clock configuration information for the specified USART peripheral. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: USART registers related to Clock settings are initialized according + * to USART_ClockInitStruct content + * - ERROR: Problem occurred during USART Registers initialization + */ +ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, const LL_USART_ClockInitTypeDef *USART_ClockInitStruct) +{ + ErrorStatus status = SUCCESS; + + /* Check USART Instance and Clock signal output parameters */ + assert_param(IS_UART_INSTANCE(USARTx)); + assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput)); + + /* USART needs to be in disabled state, in order to be able to configure some bits in + CRx registers */ + if (LL_USART_IsEnabled(USARTx) == 0U) + { + /* Ensure USART instance is USART capable */ + assert_param(IS_USART_INSTANCE(USARTx)); + + /* Check clock related parameters */ + assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity)); + assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase)); + assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse)); + + /*---------------------------- USART CR2 Configuration ----------------------- + * Configure USARTx CR2 (Clock signal related bits) with parameters: + * - Clock Output: USART_CR2_CLKEN bit according to USART_ClockInitStruct->ClockOutput value + * - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value + * - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value + * - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value. + */ + MODIFY_REG(USARTx->CR2, + USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL, + USART_ClockInitStruct->ClockOutput | USART_ClockInitStruct->ClockPolarity | + USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse); + } + /* Else (USART not in Disabled state => return ERROR */ + else + { + status = ERROR; + } + + return (status); +} + +/** + * @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value. + * @param USART_ClockInitStruct pointer to a @ref LL_USART_ClockInitTypeDef structure + * whose fields will be set to default values. + * @retval None + */ +void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct) +{ + /* Set LL_USART_ClockInitStruct fields with default values */ + USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE; + USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = + LL_USART_CLOCK_DISABLE */ + USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = + LL_USART_CLOCK_DISABLE */ + USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = + LL_USART_CLOCK_DISABLE */ +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* USART1 || USART2 || USART3 || UART4 || UART5 || UART7 || UART8 */ + +/** + * @} + */ + +#endif /* USE_FULL_LL_DRIVER */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usb.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usb.c index 972e062a8..9c7ad5e3b 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usb.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_usb.c @@ -1,2316 +1,2316 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_usb.c - * @author MCD Application Team - * @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 - * - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - (#) Fill parameters of Init structure in USB_CfgTypeDef structure. - - (#) Call USB_CoreInit() API to initialize the USB Core peripheral. - - (#) The upper HAL HCD/PCD driver will call the right routines for its internal processes. - - @endverbatim - - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_hal.h" - -/** @addtogroup STM32H7RSxx_LL_USB_DRIVER - * @{ - */ - -#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -#if defined (USB_OTG_FS) || defined (USB_OTG_HS) -static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx); - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup USB_LL_Exported_Functions USB Low Layer Exported Functions - * @{ - */ - -/** @defgroup USB_LL_Exported_Functions_Group1 Initialization/de-initialization functions - * @brief Initialization and Configuration functions - * -@verbatim - =============================================================================== - ##### Initialization/de-initialization functions ##### - =============================================================================== - -@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) -{ - HAL_StatusTypeDef ret; -#if defined (USB_OTG_HS) - if (USBx == USB_OTG_HS) - { - if (cfg.phy_itface == USB_OTG_HS_EMBEDDED_PHY) - { - /* Init The UTMI Interface */ - USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_TSDPS); - } - - /* Reset after a PHY select */ - ret = USB_CoreReset(USBx); - - if (cfg.dma_enable == 1U) - { - USBx->GAHBCFG |= USB_OTG_GAHBCFG_HBSTLEN_2; - USBx->GAHBCFG |= USB_OTG_GAHBCFG_DMAEN; - } - } - else -#endif /* defined (USB_OTG_HS) */ - { - /* Select FS Embedded PHY */ - USBx->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL; - - /* Reset after a PHY select */ - ret = USB_CoreReset(USBx); - - if (cfg.battery_charging_enable == 0U) - { - /* Activate the USB Transceiver */ - USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN; - } - else - { - /* Deactivate the USB Transceiver */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); - } - } - - return ret; -} - - -/** - * @brief Set the USB turnaround time - * @param USBx USB Instance - * @param hclk: AHB clock frequency - * @retval USB turnaround time In PHY Clocks number - */ -HAL_StatusTypeDef USB_SetTurnaroundTime(USB_OTG_GlobalTypeDef *USBx, - uint32_t hclk, uint8_t speed) -{ - uint32_t UsbTrd; - - /* The USBTRD is configured according to the tables below, depending on AHB frequency - used by application. In the low AHB frequency range it is used to stretch enough the USB response - time to IN tokens, the USB turnaround time, so to compensate for the longer AHB read access - latency to the Data FIFO */ - if (speed == USBD_FS_SPEED) - { - if ((hclk >= 14200000U) && (hclk < 15000000U)) - { - /* hclk Clock Range between 14.2-15 MHz */ - UsbTrd = 0xFU; - } - else if ((hclk >= 15000000U) && (hclk < 16000000U)) - { - /* hclk Clock Range between 15-16 MHz */ - UsbTrd = 0xEU; - } - else if ((hclk >= 16000000U) && (hclk < 17200000U)) - { - /* hclk Clock Range between 16-17.2 MHz */ - UsbTrd = 0xDU; - } - else if ((hclk >= 17200000U) && (hclk < 18500000U)) - { - /* hclk Clock Range between 17.2-18.5 MHz */ - UsbTrd = 0xCU; - } - else if ((hclk >= 18500000U) && (hclk < 20000000U)) - { - /* hclk Clock Range between 18.5-20 MHz */ - UsbTrd = 0xBU; - } - else if ((hclk >= 20000000U) && (hclk < 21800000U)) - { - /* hclk Clock Range between 20-21.8 MHz */ - UsbTrd = 0xAU; - } - else if ((hclk >= 21800000U) && (hclk < 24000000U)) - { - /* hclk Clock Range between 21.8-24 MHz */ - UsbTrd = 0x9U; - } - else if ((hclk >= 24000000U) && (hclk < 27700000U)) - { - /* hclk Clock Range between 24-27.7 MHz */ - UsbTrd = 0x8U; - } - else if ((hclk >= 27700000U) && (hclk < 32000000U)) - { - /* hclk Clock Range between 27.7-32 MHz */ - UsbTrd = 0x7U; - } - else /* if(hclk >= 32000000) */ - { - /* hclk Clock Range between 32-200 MHz */ - UsbTrd = 0x6U; - } - } - else if (speed == USBD_HS_SPEED) - { - UsbTrd = USBD_HS_TRDT_VALUE; - } - else - { - UsbTrd = USBD_DEFAULT_TRDT_VALUE; - } - - USBx->GUSBCFG &= ~USB_OTG_GUSBCFG_TRDT; - USBx->GUSBCFG |= (uint32_t)((UsbTrd << 10) & USB_OTG_GUSBCFG_TRDT); - - 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 these values: - * @arg USB_DEVICE_MODE Peripheral mode - * @arg USB_HOST_MODE Host mode - * @retval HAL status - */ -HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTypeDef mode) -{ - uint32_t ms = 0U; - - USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FHMOD | USB_OTG_GUSBCFG_FDMOD); - - if (mode == USB_HOST_MODE) - { - USBx->GUSBCFG |= USB_OTG_GUSBCFG_FHMOD; - - do - { - HAL_Delay(10U); - ms += 10U; - } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); - } - else if (mode == USB_DEVICE_MODE) - { - USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD; - - do - { - HAL_Delay(10U); - ms += 10U; - } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); - } - else - { - return HAL_ERROR; - } - - if (ms == HAL_USB_CURRENT_MODE_MAX_DELAY_MS) - { - return HAL_ERROR; - } - - 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) -{ - HAL_StatusTypeDef ret = HAL_OK; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t i; - - for (i = 0U; i < 15U; i++) - { - USBx->DIEPTXF[i] = 0U; - } - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - /* Disable USB PHY pulldown resistors */ - USBx->GCCFG &= ~USB_OTG_GCCFG_PULLDOWNEN; - } - - /* VBUS Sensing setup */ - if (cfg.vbus_sensing_enable == 0U) - { - USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS; - - /* Deactivate VBUS Sensing B */ - USBx->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - - /* B-peripheral session valid override enable */ - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - USBx->GCCFG |= USB_OTG_GCCFG_VBVALEXTOEN; - USBx->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; - } - else - { - USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; - USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; - } - } - else - { - /* B-peripheral session valid override disable */ - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - USBx->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN; - USBx->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL; - } - else - { - USBx->GOTGCTL &= ~USB_OTG_GOTGCTL_BVALOEN; - USBx->GOTGCTL &= ~USB_OTG_GOTGCTL_BVALOVAL; - } - - /* Enable HW VBUS sensing */ - USBx->GCCFG |= USB_OTG_GCCFG_VBDEN; - } - - /* Restart the Phy Clock */ - USBx_PCGCCTL = 0U; - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - if (cfg.speed == USBD_HS_SPEED) - { - /* Set Core speed to High speed mode */ - (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH); - } - else - { - /* Set Core speed to Full speed mode */ - (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH_IN_FULL); - } - } - else - { - /* Set Core speed to Full speed mode */ - (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_FULL); - } - - /* Flush the FIFOs */ - if (USB_FlushTxFifo(USBx, 0x10U) != HAL_OK) /* all Tx FIFOs */ - { - ret = HAL_ERROR; - } - - if (USB_FlushRxFifo(USBx) != HAL_OK) - { - ret = HAL_ERROR; - } - - /* Clear all pending Device Interrupts */ - USBx_DEVICE->DIEPMSK = 0U; - USBx_DEVICE->DOEPMSK = 0U; - USBx_DEVICE->DAINTMSK = 0U; - - for (i = 0U; i < cfg.dev_endpoints; i++) - { - if ((USBx_INEP(i)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) - { - if (i == 0U) - { - USBx_INEP(i)->DIEPCTL = USB_OTG_DIEPCTL_SNAK; - } - else - { - USBx_INEP(i)->DIEPCTL = USB_OTG_DIEPCTL_EPDIS | USB_OTG_DIEPCTL_SNAK; - } - } - else - { - USBx_INEP(i)->DIEPCTL = 0U; - } - - USBx_INEP(i)->DIEPTSIZ = 0U; - USBx_INEP(i)->DIEPINT = 0xFB7FU; - } - - for (i = 0U; i < cfg.dev_endpoints; i++) - { - if ((USBx_OUTEP(i)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) - { - if (i == 0U) - { - USBx_OUTEP(i)->DOEPCTL = USB_OTG_DOEPCTL_SNAK; - } - else - { - USBx_OUTEP(i)->DOEPCTL = USB_OTG_DOEPCTL_EPDIS | USB_OTG_DOEPCTL_SNAK; - } - } - else - { - USBx_OUTEP(i)->DOEPCTL = 0U; - } - - USBx_OUTEP(i)->DOEPTSIZ = 0U; - USBx_OUTEP(i)->DOEPINT = 0xFB7FU; - } - - USBx_DEVICE->DIEPMSK &= ~(USB_OTG_DIEPMSK_TXFURM); - - /* Disable all interrupts. */ - USBx->GINTMSK = 0U; - - /* Clear any pending interrupts */ - USBx->GINTSTS = 0xBFFFFFFFU; - - /* Enable the common interrupts */ - if (cfg.dma_enable == 0U) - { - 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 != 0U) - { - USBx->GINTMSK |= USB_OTG_GINTMSK_SOFM; - } - - if (cfg.vbus_sensing_enable == 1U) - { - USBx->GINTMSK |= (USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_OTGINT); - } - - return ret; -} - -/** - * @brief USB_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) -{ - __IO uint32_t count = 0U; - - /* Wait for AHB master IDLE state. */ - do - { - count++; - - if (count > HAL_USB_TIMEOUT) - { - return HAL_TIMEOUT; - } - } while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); - - /* Flush TX Fifo */ - count = 0U; - USBx->GRSTCTL = (USB_OTG_GRSTCTL_TXFFLSH | (num << 6)); - - do - { - count++; - - if (count > HAL_USB_TIMEOUT) - { - 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) -{ - __IO uint32_t count = 0U; - - /* Wait for AHB master IDLE state. */ - do - { - count++; - - if (count > HAL_USB_TIMEOUT) - { - return HAL_TIMEOUT; - } - } while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); - - /* Flush RX Fifo */ - count = 0U; - USBx->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH; - - do - { - count++; - - if (count > HAL_USB_TIMEOUT) - { - 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 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 - * @retval Hal status - */ -HAL_StatusTypeDef USB_SetDevSpeed(const USB_OTG_GlobalTypeDef *USBx, uint8_t speed) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - 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 these values: - * @arg USBD_HS_SPEED: High speed mode - * @arg USBD_FS_SPEED: Full speed mode - */ -uint8_t USB_GetDevSpeed(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint8_t speed; - uint32_t DevEnumSpeed = USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD; - - if (DevEnumSpeed == DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ) - { - speed = USBD_HS_SPEED; - } - else if ((DevEnumSpeed == DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ) || - (DevEnumSpeed == DSTS_ENUMSPD_FS_PHY_48MHZ)) - { - speed = USBD_FS_SPEED; - } - else - { - speed = 0xFU; - } - - 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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - - if (ep->is_in == 1U) - { - USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK)); - - if ((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_USBAEP) == 0U) - { - USBx_INEP(epnum)->DIEPCTL |= (ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ) | - ((uint32_t)ep->type << 18) | (epnum << 22) | - USB_OTG_DIEPCTL_SD0PID_SEVNFRM | - USB_OTG_DIEPCTL_USBAEP; - } - } - else - { - USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16); - - if (((USBx_OUTEP(epnum)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0U) - { - USBx_OUTEP(epnum)->DOEPCTL |= (ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ) | - ((uint32_t)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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - - /* Read DEPCTLn register */ - if (ep->is_in == 1U) - { - if (((USBx_INEP(epnum)->DIEPCTL) & USB_OTG_DIEPCTL_USBAEP) == 0U) - { - USBx_INEP(epnum)->DIEPCTL |= (ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ) | - ((uint32_t)ep->type << 18) | (epnum << 22) | - USB_OTG_DIEPCTL_SD0PID_SEVNFRM | - USB_OTG_DIEPCTL_USBAEP; - } - - USBx_DEVICE->DEACHMSK |= USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK)); - } - else - { - if (((USBx_OUTEP(epnum)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0U) - { - USBx_OUTEP(epnum)->DOEPCTL |= (ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ) | - ((uint32_t)ep->type << 18) | (epnum << 22) | - USB_OTG_DOEPCTL_USBAEP; - } - - USBx_DEVICE->DEACHMSK |= USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - - /* Read DEPCTLn register */ - if (ep->is_in == 1U) - { - if ((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SNAK; - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_EPDIS; - } - - USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); - USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); - USBx_INEP(epnum)->DIEPCTL &= ~(USB_OTG_DIEPCTL_USBAEP | - USB_OTG_DIEPCTL_MPSIZ | - USB_OTG_DIEPCTL_TXFNUM | - USB_OTG_DIEPCTL_SD0PID_SEVNFRM | - USB_OTG_DIEPCTL_EPTYP); - } - else - { - if ((USBx_OUTEP(epnum)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) - { - USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; - USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_EPDIS; - } - - USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); - USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); - USBx_OUTEP(epnum)->DOEPCTL &= ~(USB_OTG_DOEPCTL_USBAEP | - USB_OTG_DOEPCTL_MPSIZ | - USB_OTG_DOEPCTL_SD0PID_SEVNFRM | - USB_OTG_DOEPCTL_EPTYP); - } - - 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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - - /* Read DEPCTLn register */ - if (ep->is_in == 1U) - { - if ((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SNAK; - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_EPDIS; - } - - USBx_INEP(epnum)->DIEPCTL &= ~ USB_OTG_DIEPCTL_USBAEP; - USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); - } - else - { - if ((USBx_OUTEP(epnum)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) - { - USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; - USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_EPDIS; - } - - USBx_OUTEP(epnum)->DOEPCTL &= ~USB_OTG_DOEPCTL_USBAEP; - USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 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 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) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - uint16_t pktcnt; - - /* IN endpoint */ - if (ep->is_in == 1U) - { - /* Zero Length Packet? */ - if (ep->xfer_len == 0U) - { - USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT); - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1U << 19)); - USBx_INEP(epnum)->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(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ); - USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT); - - if (epnum == 0U) - { - if (ep->xfer_len > ep->maxpacket) - { - ep->xfer_len = ep->maxpacket; - } - - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1U << 19)); - } - else - { - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & - (((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket) << 19)); - } - - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len); - - if (ep->type == EP_TYPE_ISOC) - { - USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_MULCNT); - USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_MULCNT & (1U << 29)); - } - } - - if (dma == 1U) - { - if ((uint32_t)ep->dma_addr != 0U) - { - USBx_INEP(epnum)->DIEPDMA = (uint32_t)(ep->dma_addr); - } - - if (ep->type == EP_TYPE_ISOC) - { - if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SODDFRM; - } - else - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; - } - } - - /* EP enable, IN data in FIFO */ - USBx_INEP(epnum)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA); - } - else - { - /* EP enable, IN data in FIFO */ - USBx_INEP(epnum)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA); - - if (ep->type != EP_TYPE_ISOC) - { - /* Enable the Tx FIFO Empty Interrupt for this EP */ - if (ep->xfer_len > 0U) - { - USBx_DEVICE->DIEPEMPMSK |= 1UL << (ep->num & EP_ADDR_MSK); - } - } - else - { - if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SODDFRM; - } - else - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; - } - - (void)USB_WritePacket(USBx, ep->xfer_buff, ep->num, (uint16_t)ep->xfer_len, dma); - } - } - } - else /* OUT endpoint */ - { - /* Program the transfer size and packet count as follows: - * pktcnt = N - * xfersize = N * maxpacket - */ - USBx_OUTEP(epnum)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_XFRSIZ); - USBx_OUTEP(epnum)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_PKTCNT); - - if (epnum == 0U) - { - if (ep->xfer_len > 0U) - { - ep->xfer_len = ep->maxpacket; - } - - /* Store transfer size, for EP0 this is equal to endpoint max packet size */ - ep->xfer_size = ep->maxpacket; - - USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & ep->xfer_size); - USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1U << 19)); - } - else - { - if (ep->xfer_len == 0U) - { - USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & ep->maxpacket); - USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1U << 19)); - } - else - { - pktcnt = (uint16_t)((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket); - ep->xfer_size = ep->maxpacket * pktcnt; - - USBx_OUTEP(epnum)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_PKTCNT & ((uint32_t)pktcnt << 19); - USBx_OUTEP(epnum)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_XFRSIZ & ep->xfer_size; - } - } - - if (dma == 1U) - { - if ((uint32_t)ep->xfer_buff != 0U) - { - USBx_OUTEP(epnum)->DOEPDMA = (uint32_t)(ep->xfer_buff); - } - } - - if (ep->type == EP_TYPE_ISOC) - { - if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) - { - USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SODDFRM; - } - else - { - USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM; - } - } - /* EP enable */ - USBx_OUTEP(epnum)->DOEPCTL |= (USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA); - } - - return HAL_OK; -} - - -/** - * @brief USB_EPStoptXfer Stop transfer on an EP - * @param USBx usb device instance - * @param ep pointer to endpoint structure - * @retval HAL status - */ -HAL_StatusTypeDef USB_EPStopXfer(const USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) -{ - __IO uint32_t count = 0U; - HAL_StatusTypeDef ret = HAL_OK; - uint32_t USBx_BASE = (uint32_t)USBx; - - /* IN endpoint */ - if (ep->is_in == 1U) - { - /* EP enable, IN data in FIFO */ - if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) - { - USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_SNAK); - USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_EPDIS); - - do - { - count++; - - if (count > 10000U) - { - ret = HAL_ERROR; - break; - } - } while (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA); - } - } - else /* OUT endpoint */ - { - if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) - { - USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_SNAK); - USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_EPDIS); - - do - { - count++; - - if (count > 10000U) - { - ret = HAL_ERROR; - break; - } - } while (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA); - } - } - - return ret; -} - - -/** - * @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 these values: - * 0 : DMA feature not used - * 1 : DMA feature used - * @retval HAL status - */ -HAL_StatusTypeDef USB_WritePacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *src, - uint8_t ch_ep_num, uint16_t len, uint8_t dma) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint8_t *pSrc = src; - uint32_t count32b; - uint32_t i; - - if (dma == 0U) - { - count32b = ((uint32_t)len + 3U) / 4U; - for (i = 0U; i < count32b; i++) - { - USBx_DFIFO((uint32_t)ch_ep_num) = __UNALIGNED_UINT32_READ(pSrc); - pSrc++; - pSrc++; - pSrc++; - pSrc++; - } - } - - return HAL_OK; -} - -/** - * @brief USB_ReadPacket : read a packet from the RX FIFO - * @param USBx Selected device - * @param dest source pointer - * @param len Number of bytes to read - * @retval pointer to destination buffer - */ -void *USB_ReadPacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint8_t *pDest = dest; - uint32_t pData; - uint32_t i; - uint32_t count32b = (uint32_t)len >> 2U; - uint16_t remaining_bytes = len % 4U; - - for (i = 0U; i < count32b; i++) - { - __UNALIGNED_UINT32_WRITE(pDest, USBx_DFIFO(0U)); - pDest++; - pDest++; - pDest++; - pDest++; - } - - /* When Number of data is not word aligned, read the remaining byte */ - if (remaining_bytes != 0U) - { - i = 0U; - __UNALIGNED_UINT32_WRITE(&pData, USBx_DFIFO(0U)); - - do - { - *(uint8_t *)pDest = (uint8_t)(pData >> (8U * (uint8_t)(i))); - i++; - pDest++; - remaining_bytes--; - } while (remaining_bytes != 0U); - } - - return ((void *)pDest); -} - -/** - * @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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - - if (ep->is_in == 1U) - { - if (((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == 0U) && (epnum != 0U)) - { - USBx_INEP(epnum)->DIEPCTL &= ~(USB_OTG_DIEPCTL_EPDIS); - } - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_STALL; - } - else - { - if (((USBx_OUTEP(epnum)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == 0U) && (epnum != 0U)) - { - USBx_OUTEP(epnum)->DOEPCTL &= ~(USB_OTG_DOEPCTL_EPDIS); - } - USBx_OUTEP(epnum)->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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t epnum = (uint32_t)ep->num; - - if (ep->is_in == 1U) - { - USBx_INEP(epnum)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL; - if ((ep->type == EP_TYPE_INTR) || (ep->type == EP_TYPE_BULK)) - { - USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; /* DATA0 */ - } - } - else - { - USBx_OUTEP(epnum)->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL; - if ((ep->type == EP_TYPE_INTR) || (ep->type == EP_TYPE_BULK)) - { - USBx_OUTEP(epnum)->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) -{ - HAL_StatusTypeDef ret; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t i; - - /* Clear Pending interrupt */ - for (i = 0U; i < 15U; i++) - { - USBx_INEP(i)->DIEPINT = 0xFB7FU; - USBx_OUTEP(i)->DOEPINT = 0xFB7FU; - } - - /* Clear interrupt masks */ - USBx_DEVICE->DIEPMSK = 0U; - USBx_DEVICE->DOEPMSK = 0U; - USBx_DEVICE->DAINTMSK = 0U; - - /* Flush the FIFO */ - ret = USB_FlushRxFifo(USBx); - if (ret != HAL_OK) - { - return ret; - } - - ret = USB_FlushTxFifo(USBx, 0x10U); - if (ret != HAL_OK) - { - return ret; - } - - return ret; -} - -/** - * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t address) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - USBx_DEVICE->DCFG &= ~(USB_OTG_DCFG_DAD); - USBx_DEVICE->DCFG |= ((uint32_t)address << 4) & USB_OTG_DCFG_DAD; - - return HAL_OK; -} - -/** - * @brief USB_DevConnect : Connect the USB device by enabling Rpu - * @param USBx Selected device - * @retval HAL status - */ -HAL_StatusTypeDef USB_DevConnect(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - /* In case phy is stopped, ensure to ungate and restore the phy CLK */ - USBx_PCGCCTL &= ~(USB_OTG_PCGCCTL_STOPCLK | USB_OTG_PCGCCTL_GATECLK); - - USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_SDIS; - - return HAL_OK; -} - -/** - * @brief USB_DevDisconnect : Disconnect the USB device by disabling Rpu - * @param USBx Selected device - * @retval HAL status - */ -HAL_StatusTypeDef USB_DevDisconnect(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - /* In case phy is stopped, ensure to ungate and restore the phy CLK */ - USBx_PCGCCTL &= ~(USB_OTG_PCGCCTL_STOPCLK | USB_OTG_PCGCCTL_GATECLK); - - USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS; - - return HAL_OK; -} - -/** - * @brief USB_ReadInterrupts: return the global USB interrupt status - * @param USBx Selected device - * @retval USB Global Interrupt status - */ -uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef const *USBx) -{ - uint32_t tmpreg; - - tmpreg = USBx->GINTSTS; - tmpreg &= USBx->GINTMSK; - - return tmpreg; -} - -/** - * @brief USB_ReadChInterrupts: return USB channel interrupt status - * @param USBx Selected device - * @param chnum Channel number - * @retval USB Channel Interrupt status - */ -uint32_t USB_ReadChInterrupts(const USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - - tmpreg = USBx_HC(chnum)->HCINT; - tmpreg &= USBx_HC(chnum)->HCINTMSK; - - return tmpreg; -} - -/** - * @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status - * @param USBx Selected device - * @retval USB Device OUT EP interrupt status - */ -uint32_t USB_ReadDevAllOutEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - - tmpreg = USBx_DEVICE->DAINT; - tmpreg &= USBx_DEVICE->DAINTMSK; - - return ((tmpreg & 0xffff0000U) >> 16); -} - -/** - * @brief USB_ReadDevAllInEpInterrupt: return the USB device IN endpoints interrupt status - * @param USBx Selected device - * @retval USB Device IN EP interrupt status - */ -uint32_t USB_ReadDevAllInEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - - tmpreg = USBx_DEVICE->DAINT; - tmpreg &= USBx_DEVICE->DAINTMSK; - - return ((tmpreg & 0xFFFFU)); -} - -/** - * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - - tmpreg = USBx_OUTEP((uint32_t)epnum)->DOEPINT; - tmpreg &= USBx_DEVICE->DOEPMSK; - - return tmpreg; -} - -/** - * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t tmpreg; - uint32_t msk; - uint32_t emp; - - msk = USBx_DEVICE->DIEPMSK; - emp = USBx_DEVICE->DIEPEMPMSK; - msk |= ((emp >> (epnum & EP_ADDR_MSK)) & 0x1U) << 7; - tmpreg = USBx_INEP((uint32_t)epnum)->DIEPINT & msk; - - return tmpreg; -} - -/** - * @brief USB_ClearInterrupts: clear a USB interrupt - * @param USBx Selected device - * @param 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 these values: - * 0 : Host - * 1 : Device - */ -uint32_t USB_GetMode(const USB_OTG_GlobalTypeDef *USBx) -{ - return ((USBx->GINTSTS) & 0x1U); -} - -/** - * @brief Activate EP0 for Setup transactions - * @param USBx Selected device - * @retval HAL status - */ -HAL_StatusTypeDef USB_ActivateSetup(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - /* Set the MPS of the IN EP0 to 64 bytes */ - USBx_INEP(0U)->DIEPCTL &= ~USB_OTG_DIEPCTL_MPSIZ; - - 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 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(const USB_OTG_GlobalTypeDef *USBx, uint8_t dma, const uint8_t *psetup) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); - - if (gSNPSiD > USB_OTG_CORE_ID_300A) - { - if ((USBx_OUTEP(0U)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) - { - return HAL_OK; - } - } - - USBx_OUTEP(0U)->DOEPTSIZ = 0U; - USBx_OUTEP(0U)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1U << 19)); - USBx_OUTEP(0U)->DOEPTSIZ |= (3U * 8U); - USBx_OUTEP(0U)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_STUPCNT; - - if (dma == 1U) - { - USBx_OUTEP(0U)->DOEPDMA = (uint32_t)psetup; - /* EP enable */ - USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_USBAEP; - } - - 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) -{ - __IO uint32_t count = 0U; - - /* Wait for AHB master IDLE state. */ - do - { - count++; - - if (count > HAL_USB_TIMEOUT) - { - return HAL_TIMEOUT; - } - } while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); - - /* Core Soft Reset */ - count = 0U; - USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST; - - do - { - count++; - - if (count > HAL_USB_TIMEOUT) - { - 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) -{ - HAL_StatusTypeDef ret = HAL_OK; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t i; - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - /* Enable USB PHY pulldown resistors */ - USBx->GCCFG |= USB_OTG_GCCFG_PULLDOWNEN; - } - - /* Restart the Phy Clock */ - USBx_PCGCCTL = 0U; - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - /* Disable VBUS override */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_VBVALOVAL | USB_OTG_GCCFG_VBVALEXTOEN); - } - - /* Disable VBUS sensing */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_VBDEN); - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) - { - /* Disable Battery chargin detector */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_BCDEN); - } - else - { - /* Disable Battery chargin detector */ - USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); - USBx->GCCFG &= ~(USB_OTG_GCCFG_SDEN); - } - - if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) - { - if (cfg.speed == USBH_FSLS_SPEED) - { - /* Force Device Enumeration to FS/LS mode only */ - USBx_HOST->HCFG |= USB_OTG_HCFG_FSLSS; - } - else - { - /* Set default Max speed support */ - USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSS); - } - } - else - { - /* Set default Max speed support */ - USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSS); - } - - /* Make sure the FIFOs are flushed. */ - if (USB_FlushTxFifo(USBx, 0x10U) != HAL_OK) /* all Tx FIFOs */ - { - ret = HAL_ERROR; - } - - if (USB_FlushRxFifo(USBx) != HAL_OK) - { - ret = HAL_ERROR; - } - - /* Clear all pending HC Interrupts */ - for (i = 0U; i < cfg.Host_channels; i++) - { - USBx_HC(i)->HCINT = CLEAR_INTERRUPT_MASK; - USBx_HC(i)->HCINTMSK = 0U; - } - - /* Disable all interrupts. */ - USBx->GINTMSK = 0U; - - /* Clear any pending interrupts */ - USBx->GINTSTS = CLEAR_INTERRUPT_MASK; -#if defined (USB_OTG_HS) - if (USBx == USB_OTG_HS) - { - /* set Rx FIFO size */ - USBx->GRXFSIZ = 0x200U; - USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t)(((0x100U << 16) & USB_OTG_NPTXFD) | 0x200U); - USBx->HPTXFSIZ = (uint32_t)(((0xE0U << 16) & USB_OTG_HPTXFSIZ_PTXFD) | 0x300U); - } - else -#endif /* defined (USB_OTG_HS) */ - { - /* set Rx FIFO size */ - USBx->GRXFSIZ = 0x80U; - USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t)(((0x60U << 16) & USB_OTG_NPTXFD) | 0x80U); - USBx->HPTXFSIZ = (uint32_t)(((0x40U << 16)& USB_OTG_HPTXFSIZ_PTXFD) | 0xE0U); - } - - /* Enable the common interrupts */ - if (cfg.dma_enable == 0U) - { - 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 ret; -} - -/** - * @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 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(const USB_OTG_GlobalTypeDef *USBx, uint8_t freq) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSPCS); - USBx_HOST->HCFG |= (uint32_t)freq & USB_OTG_HCFG_FSLSPCS; - - if (freq == HCFG_48_MHZ) - { - USBx_HOST->HFIR = HFIR_48_MHZ; - } - else if (freq == HCFG_6_MHZ) - { - USBx_HOST->HFIR = HFIR_6_MHZ; - } - else - { - return HAL_ERROR; - } - - 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(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - __IO uint32_t hprt0 = 0U; - - 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(100U); /* See Note #1 */ - USBx_HPRT0 = ((~USB_OTG_HPRT_PRST) & hprt0); - HAL_Delay(10U); - - return HAL_OK; -} - -/** - * @brief USB_DriveVbus : activate or de-activate vbus - * @param state VBUS state - * This parameter can be one of these values: - * 0 : Deactivate VBUS - * 1 : Activate VBUS - * @retval HAL status - */ -HAL_StatusTypeDef USB_DriveVbus(const USB_OTG_GlobalTypeDef *USBx, uint8_t state) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - __IO uint32_t hprt0 = 0U; - - 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) == 0U) && (state == 1U)) - { - USBx_HPRT0 = (USB_OTG_HPRT_PPWR | hprt0); - } - if (((hprt0 & USB_OTG_HPRT_PPWR) == USB_OTG_HPRT_PPWR) && (state == 0U)) - { - 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 these values: - * @arg HCD_SPEED_HIGH: High speed mode - * @arg HCD_SPEED_FULL: Full speed mode - * @arg HCD_SPEED_LOW: Low speed mode - */ -uint32_t USB_GetHostSpeed(USB_OTG_GlobalTypeDef const *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - __IO uint32_t hprt0 = 0U; - - 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 const *USBx) -{ - uint32_t USBx_BASE = (uint32_t)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 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 these values: - * @arg EP_TYPE_CTRL: Control type - * @arg EP_TYPE_ISOC: Isochronous 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 to 32K - * @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) -{ - HAL_StatusTypeDef ret = HAL_OK; - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t HCcharEpDir; - uint32_t HCcharLowSpeed; - uint32_t HostCoreSpeed; - - /* Clear old interrupt conditions for this host channel. */ - USBx_HC((uint32_t)ch_num)->HCINT = CLEAR_INTERRUPT_MASK; - - /* Enable channel interrupts required for this transfer. */ - switch (ep_type) - { - case EP_TYPE_CTRL: - case EP_TYPE_BULK: - USBx_HC((uint32_t)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 & 0x80U) == 0x80U) - { - USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM; - } - else - { -#if defined (USB_OTG_HS) - if (USBx == USB_OTG_HS) - { - USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_NYET | - USB_OTG_HCINTMSK_ACKM; - } -#endif /* defined (USB_OTG_HS) */ - } - break; - - case EP_TYPE_INTR: - USBx_HC((uint32_t)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 & 0x80U) == 0x80U) - { - USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM; - } - - break; - - case EP_TYPE_ISOC: - USBx_HC((uint32_t)ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM | - USB_OTG_HCINTMSK_ACKM | - USB_OTG_HCINTMSK_AHBERR | - USB_OTG_HCINTMSK_FRMORM; - - if ((epnum & 0x80U) == 0x80U) - { - USBx_HC((uint32_t)ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_TXERRM | USB_OTG_HCINTMSK_BBERRM); - } - break; - - default: - ret = HAL_ERROR; - break; - } - - /* Clear Hub Start Split transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT = 0U; - - /* Enable host channel Halt interrupt */ - USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_CHHM; - - /* Enable the top level host channel interrupt. */ - USBx_HOST->HAINTMSK |= 1UL << (ch_num & 0xFU); - - /* Make sure host channel interrupts are enabled. */ - USBx->GINTMSK |= USB_OTG_GINTMSK_HCIM; - - /* Program the HCCHAR register */ - if ((epnum & 0x80U) == 0x80U) - { - HCcharEpDir = (0x1U << 15) & USB_OTG_HCCHAR_EPDIR; - } - else - { - HCcharEpDir = 0U; - } - - HostCoreSpeed = USB_GetHostSpeed(USBx); - - /* LS device plugged to HUB */ - if ((speed == HPRT0_PRTSPD_LOW_SPEED) && (HostCoreSpeed != HPRT0_PRTSPD_LOW_SPEED)) - { - HCcharLowSpeed = (0x1U << 17) & USB_OTG_HCCHAR_LSDEV; - } - else - { - HCcharLowSpeed = 0U; - } - - USBx_HC((uint32_t)ch_num)->HCCHAR = (((uint32_t)dev_address << 22) & USB_OTG_HCCHAR_DAD) | - ((((uint32_t)epnum & 0x7FU) << 11) & USB_OTG_HCCHAR_EPNUM) | - (((uint32_t)ep_type << 18) & USB_OTG_HCCHAR_EPTYP) | - ((uint32_t)mps & USB_OTG_HCCHAR_MPSIZ) | - USB_OTG_HCCHAR_MC_0 | HCcharEpDir | HCcharLowSpeed; - - if ((ep_type == EP_TYPE_INTR) || (ep_type == EP_TYPE_ISOC)) - { - USBx_HC((uint32_t)ch_num)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM; - } - - return ret; -} - -/** - * @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 these values: - * 0 : DMA feature not used - * 1 : DMA feature used - * @retval HAL state - */ -HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t ch_num = (uint32_t)hc->ch_num; - __IO uint32_t tmpreg; - uint8_t is_oddframe; - uint16_t len_words; - uint16_t num_packets; - uint16_t max_hc_pkt_count = HC_MAX_PKT_CNT; - -#if defined (USB_OTG_HS) - if (USBx == USB_OTG_HS) - { - /* in DMA mode host Core automatically issues ping in case of NYET/NAK */ - if (dma == 1U) - { - if (((hc->ep_type == EP_TYPE_CTRL) || (hc->ep_type == EP_TYPE_BULK)) && (hc->do_ssplit == 0U)) - { - - USBx_HC((uint32_t)ch_num)->HCINTMSK &= ~(USB_OTG_HCINTMSK_NYET | - USB_OTG_HCINTMSK_ACKM | - USB_OTG_HCINTMSK_NAKM); - } - } - else - { - if ((hc->speed == USBH_HS_SPEED) && (hc->do_ping == 1U)) - { - (void)USB_DoPing(USBx, hc->ch_num); - return HAL_OK; - } - } - } -#endif /* defined (USB_OTG_HS) */ - - if (hc->do_ssplit == 1U) - { - /* Set number of packet to 1 for Split transaction */ - num_packets = 1U; - - if (hc->ep_is_in != 0U) - { - hc->XferSize = (uint32_t)num_packets * hc->max_packet; - } - else - { - if (hc->ep_type == EP_TYPE_ISOC) - { - if (hc->xfer_len > ISO_SPLT_MPS) - { - /* Isochrone Max Packet Size for Split mode */ - hc->XferSize = hc->max_packet; - hc->xfer_len = hc->XferSize; - - if ((hc->iso_splt_xactPos == HCSPLT_BEGIN) || (hc->iso_splt_xactPos == HCSPLT_MIDDLE)) - { - hc->iso_splt_xactPos = HCSPLT_MIDDLE; - } - else - { - hc->iso_splt_xactPos = HCSPLT_BEGIN; - } - } - else - { - hc->XferSize = hc->xfer_len; - - if ((hc->iso_splt_xactPos != HCSPLT_BEGIN) && (hc->iso_splt_xactPos != HCSPLT_MIDDLE)) - { - hc->iso_splt_xactPos = HCSPLT_FULL; - } - else - { - hc->iso_splt_xactPos = HCSPLT_END; - } - } - } - else - { - if ((dma == 1U) && (hc->xfer_len > hc->max_packet)) - { - hc->XferSize = (uint32_t)num_packets * hc->max_packet; - } - else - { - hc->XferSize = hc->xfer_len; - } - } - } - } - else - { - /* Compute the expected number of packets associated to the transfer */ - if (hc->xfer_len > 0U) - { - num_packets = (uint16_t)((hc->xfer_len + hc->max_packet - 1U) / hc->max_packet); - - if (num_packets > max_hc_pkt_count) - { - num_packets = max_hc_pkt_count; - hc->XferSize = (uint32_t)num_packets * hc->max_packet; - } - } - else - { - num_packets = 1U; - } - - /* - * For IN channel HCTSIZ.XferSize is expected to be an integer multiple of - * max_packet size. - */ - if (hc->ep_is_in != 0U) - { - hc->XferSize = (uint32_t)num_packets * hc->max_packet; - } - else - { - hc->XferSize = hc->xfer_len; - } - } - - /* Initialize the HCTSIZn register */ - USBx_HC(ch_num)->HCTSIZ = (hc->XferSize & USB_OTG_HCTSIZ_XFRSIZ) | - (((uint32_t)num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) | - (((uint32_t)hc->data_pid << 29) & USB_OTG_HCTSIZ_DPID); - - if (dma != 0U) - { - /* xfer_buff MUST be 32-bits aligned */ - USBx_HC(ch_num)->HCDMA = (uint32_t)hc->xfer_buff; - } - - is_oddframe = (((uint32_t)USBx_HOST->HFNUM & 0x01U) != 0U) ? 0U : 1U; - USBx_HC(ch_num)->HCCHAR &= ~USB_OTG_HCCHAR_ODDFRM; - USBx_HC(ch_num)->HCCHAR |= (uint32_t)is_oddframe << 29; - - if (hc->do_ssplit == 1U) - { - /* Set Hub start Split transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT = ((uint32_t)hc->hub_addr << USB_OTG_HCSPLT_HUBADDR_Pos) | - (uint32_t)hc->hub_port_nbr | USB_OTG_HCSPLT_SPLITEN; - - /* unmask ack & nyet for IN/OUT transactions */ - USBx_HC((uint32_t)ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_ACKM | - USB_OTG_HCINTMSK_NYET); - - if ((hc->do_csplit == 1U) && (hc->ep_is_in == 0U)) - { - USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_COMPLSPLT; - USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_NYET; - } - - if (((hc->ep_type == EP_TYPE_ISOC) || (hc->ep_type == EP_TYPE_INTR)) && - (hc->do_csplit == 1U) && (hc->ep_is_in == 1U)) - { - USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_COMPLSPLT; - } - - /* Position management for iso out transaction on split mode */ - if ((hc->ep_type == EP_TYPE_ISOC) && (hc->ep_is_in == 0U)) - { - /* Set data payload position */ - switch (hc->iso_splt_xactPos) - { - case HCSPLT_BEGIN: - /* First data payload for OUT Transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS_1; - break; - - case HCSPLT_MIDDLE: - /* Middle data payload for OUT Transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS_Pos; - break; - - case HCSPLT_END: - /* End data payload for OUT Transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS_0; - break; - - case HCSPLT_FULL: - /* Entire data payload for OUT Transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS; - break; - - default: - break; - } - } - } - else - { - /* Clear Hub Start Split transaction */ - USBx_HC((uint32_t)ch_num)->HCSPLT = 0U; - } - - /* Set host channel enable */ - tmpreg = USBx_HC(ch_num)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - - /* make sure to set the correct ep direction */ - if (hc->ep_is_in != 0U) - { - tmpreg |= USB_OTG_HCCHAR_EPDIR; - } - else - { - tmpreg &= ~USB_OTG_HCCHAR_EPDIR; - } - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(ch_num)->HCCHAR = tmpreg; - - if (dma != 0U) /* dma mode */ - { - return HAL_OK; - } - - if ((hc->ep_is_in == 0U) && (hc->xfer_len > 0U) && (hc->do_csplit == 0U)) - { - switch (hc->ep_type) - { - /* Non periodic transfer */ - case EP_TYPE_CTRL: - case EP_TYPE_BULK: - - len_words = (uint16_t)((hc->xfer_len + 3U) / 4U); - - /* check if there is enough space in FIFO space */ - if (len_words > (USBx->HNPTXSTS & 0xFFFFU)) - { - /* 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 = (uint16_t)((hc->xfer_len + 3U) / 4U); - /* check if there is enough space in FIFO space */ - if (len_words > (USBx_HOST->HPTXSTS & 0xFFFFU)) /* 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. */ - (void)USB_WritePacket(USBx, hc->xfer_buff, hc->ch_num, (uint16_t)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(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - return ((USBx_HOST->HAINT) & 0xFFFFU); -} - -/** - * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t hcnum = (uint32_t)hc_num; - __IO uint32_t count = 0U; - uint32_t HcEpType = (USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_EPTYP) >> 18; - uint32_t ChannelEna = (USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_CHENA) >> 31; - uint32_t SplitEna = (USBx_HC(hcnum)->HCSPLT & USB_OTG_HCSPLT_SPLITEN) >> 31; - - /* In buffer DMA, Channel disable must not be programmed for non-split periodic channels. - At the end of the next uframe/frame (in the worst case), the core generates a channel halted - and disables the channel automatically. */ - - if ((((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == USB_OTG_GAHBCFG_DMAEN) && (SplitEna == 0U)) && - ((ChannelEna == 0U) || (((HcEpType == HCCHAR_ISOC) || (HcEpType == HCCHAR_INTR))))) - { - return HAL_OK; - } - - /* Check for space in the request queue to issue the halt. */ - if ((HcEpType == HCCHAR_CTRL) || (HcEpType == HCCHAR_BULK)) - { - USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHDIS; - - if ((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == 0U) - { - if ((USBx->HNPTXSTS & (0xFFU << 16)) == 0U) - { - USBx_HC(hcnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA; - USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; - do - { - count++; - - if (count > 1000U) - { - break; - } - } while ((USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA); - } - else - { - USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; - } - } - else - { - USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; - } - } - else - { - USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHDIS; - - if ((USBx_HOST->HPTXSTS & (0xFFU << 16)) == 0U) - { - USBx_HC(hcnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA; - USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; - do - { - count++; - - if (count > 1000U) - { - break; - } - } while ((USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA); - } - else - { - USBx_HC(hcnum)->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(const USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - uint32_t chnum = (uint32_t)ch_num; - uint32_t num_packets = 1U; - uint32_t tmpreg; - - USBx_HC(chnum)->HCTSIZ = ((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) | - USB_OTG_HCTSIZ_DOPING; - - /* Set host channel enable */ - tmpreg = USBx_HC(chnum)->HCCHAR; - tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - tmpreg |= USB_OTG_HCCHAR_CHENA; - USBx_HC(chnum)->HCCHAR = tmpreg; - - return HAL_OK; -} - -/** - * @brief Stop Host Core - * @param USBx Selected device - * @retval HAL state - */ -HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx) -{ - HAL_StatusTypeDef ret = HAL_OK; - uint32_t USBx_BASE = (uint32_t)USBx; - __IO uint32_t count = 0U; - uint32_t value; - uint32_t i; - - (void)USB_DisableGlobalInt(USBx); - - /* Flush USB FIFO */ - if (USB_FlushTxFifo(USBx, 0x10U) != HAL_OK) /* all Tx FIFOs */ - { - ret = HAL_ERROR; - } - - if (USB_FlushRxFifo(USBx) != HAL_OK) - { - ret = HAL_ERROR; - } - - /* Flush out any leftover queued requests. */ - for (i = 0U; i <= 15U; 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 = 0U; i <= 15U; 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 - { - count++; - - if (count > 1000U) - { - break; - } - } while ((USBx_HC(i)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA); - } - - /* Clear any pending Host interrupts */ - USBx_HOST->HAINT = CLEAR_INTERRUPT_MASK; - USBx->GINTSTS = CLEAR_INTERRUPT_MASK; - - (void)USB_EnableGlobalInt(USBx); - - return ret; -} - -/** - * @brief USB_ActivateRemoteWakeup active remote wakeup signalling - * @param USBx Selected device - * @retval HAL status - */ -HAL_StatusTypeDef USB_ActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - if ((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS) - { - /* active Remote wakeup signalling */ - USBx_DEVICE->DCTL |= USB_OTG_DCTL_RWUSIG; - } - - return HAL_OK; -} - -/** - * @brief USB_DeActivateRemoteWakeup de-active remote wakeup signalling - * @param USBx Selected device - * @retval HAL status - */ -HAL_StatusTypeDef USB_DeActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) -{ - uint32_t USBx_BASE = (uint32_t)USBx; - - /* active Remote wakeup signalling */ - USBx_DEVICE->DCTL &= ~(USB_OTG_DCTL_RWUSIG); - - return HAL_OK; -} -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ -#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_usb.c + * @author MCD Application Team + * @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 + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Fill parameters of Init structure in USB_CfgTypeDef structure. + + (#) Call USB_CoreInit() API to initialize the USB Core peripheral. + + (#) The upper HAL HCD/PCD driver will call the right routines for its internal processes. + + @endverbatim + + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_hal.h" + +/** @addtogroup STM32H7RSxx_LL_USB_DRIVER + * @{ + */ + +#if defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +#if defined (USB_OTG_FS) || defined (USB_OTG_HS) +static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx); + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup USB_LL_Exported_Functions USB Low Layer Exported Functions + * @{ + */ + +/** @defgroup USB_LL_Exported_Functions_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + +@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) +{ + HAL_StatusTypeDef ret; +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) + { + if (cfg.phy_itface == USB_OTG_HS_EMBEDDED_PHY) + { + /* Init The UTMI Interface */ + USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_TSDPS); + } + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + + if (cfg.dma_enable == 1U) + { + USBx->GAHBCFG |= USB_OTG_GAHBCFG_HBSTLEN_2; + USBx->GAHBCFG |= USB_OTG_GAHBCFG_DMAEN; + } + } + else +#endif /* defined (USB_OTG_HS) */ + { + /* Select FS Embedded PHY */ + USBx->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL; + + /* Reset after a PHY select */ + ret = USB_CoreReset(USBx); + + if (cfg.battery_charging_enable == 0U) + { + /* Activate the USB Transceiver */ + USBx->GCCFG |= USB_OTG_GCCFG_PWRDWN; + } + else + { + /* Deactivate the USB Transceiver */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_PWRDWN); + } + } + + return ret; +} + + +/** + * @brief Set the USB turnaround time + * @param USBx USB Instance + * @param hclk: AHB clock frequency + * @retval USB turnaround time In PHY Clocks number + */ +HAL_StatusTypeDef USB_SetTurnaroundTime(USB_OTG_GlobalTypeDef *USBx, + uint32_t hclk, uint8_t speed) +{ + uint32_t UsbTrd; + + /* The USBTRD is configured according to the tables below, depending on AHB frequency + used by application. In the low AHB frequency range it is used to stretch enough the USB response + time to IN tokens, the USB turnaround time, so to compensate for the longer AHB read access + latency to the Data FIFO */ + if (speed == USBD_FS_SPEED) + { + if ((hclk >= 14200000U) && (hclk < 15000000U)) + { + /* hclk Clock Range between 14.2-15 MHz */ + UsbTrd = 0xFU; + } + else if ((hclk >= 15000000U) && (hclk < 16000000U)) + { + /* hclk Clock Range between 15-16 MHz */ + UsbTrd = 0xEU; + } + else if ((hclk >= 16000000U) && (hclk < 17200000U)) + { + /* hclk Clock Range between 16-17.2 MHz */ + UsbTrd = 0xDU; + } + else if ((hclk >= 17200000U) && (hclk < 18500000U)) + { + /* hclk Clock Range between 17.2-18.5 MHz */ + UsbTrd = 0xCU; + } + else if ((hclk >= 18500000U) && (hclk < 20000000U)) + { + /* hclk Clock Range between 18.5-20 MHz */ + UsbTrd = 0xBU; + } + else if ((hclk >= 20000000U) && (hclk < 21800000U)) + { + /* hclk Clock Range between 20-21.8 MHz */ + UsbTrd = 0xAU; + } + else if ((hclk >= 21800000U) && (hclk < 24000000U)) + { + /* hclk Clock Range between 21.8-24 MHz */ + UsbTrd = 0x9U; + } + else if ((hclk >= 24000000U) && (hclk < 27700000U)) + { + /* hclk Clock Range between 24-27.7 MHz */ + UsbTrd = 0x8U; + } + else if ((hclk >= 27700000U) && (hclk < 32000000U)) + { + /* hclk Clock Range between 27.7-32 MHz */ + UsbTrd = 0x7U; + } + else /* if(hclk >= 32000000) */ + { + /* hclk Clock Range between 32-200 MHz */ + UsbTrd = 0x6U; + } + } + else if (speed == USBD_HS_SPEED) + { + UsbTrd = USBD_HS_TRDT_VALUE; + } + else + { + UsbTrd = USBD_DEFAULT_TRDT_VALUE; + } + + USBx->GUSBCFG &= ~USB_OTG_GUSBCFG_TRDT; + USBx->GUSBCFG |= (uint32_t)((UsbTrd << 10) & USB_OTG_GUSBCFG_TRDT); + + 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 these values: + * @arg USB_DEVICE_MODE Peripheral mode + * @arg USB_HOST_MODE Host mode + * @retval HAL status + */ +HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx, USB_OTG_ModeTypeDef mode) +{ + uint32_t ms = 0U; + + USBx->GUSBCFG &= ~(USB_OTG_GUSBCFG_FHMOD | USB_OTG_GUSBCFG_FDMOD); + + if (mode == USB_HOST_MODE) + { + USBx->GUSBCFG |= USB_OTG_GUSBCFG_FHMOD; + + do + { + HAL_Delay(10U); + ms += 10U; + } while ((USB_GetMode(USBx) != (uint32_t)USB_HOST_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); + } + else if (mode == USB_DEVICE_MODE) + { + USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD; + + do + { + HAL_Delay(10U); + ms += 10U; + } while ((USB_GetMode(USBx) != (uint32_t)USB_DEVICE_MODE) && (ms < HAL_USB_CURRENT_MODE_MAX_DELAY_MS)); + } + else + { + return HAL_ERROR; + } + + if (ms == HAL_USB_CURRENT_MODE_MAX_DELAY_MS) + { + return HAL_ERROR; + } + + 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) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + + for (i = 0U; i < 15U; i++) + { + USBx->DIEPTXF[i] = 0U; + } + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + /* Disable USB PHY pulldown resistors */ + USBx->GCCFG &= ~USB_OTG_GCCFG_PULLDOWNEN; + } + + /* VBUS Sensing setup */ + if (cfg.vbus_sensing_enable == 0U) + { + USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS; + + /* Deactivate VBUS Sensing B */ + USBx->GCCFG &= ~USB_OTG_GCCFG_VBDEN; + + /* B-peripheral session valid override enable */ + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + USBx->GCCFG |= USB_OTG_GCCFG_VBVALEXTOEN; + USBx->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; + } + else + { + USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; + USBx->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; + } + } + else + { + /* B-peripheral session valid override disable */ + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + USBx->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN; + USBx->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL; + } + else + { + USBx->GOTGCTL &= ~USB_OTG_GOTGCTL_BVALOEN; + USBx->GOTGCTL &= ~USB_OTG_GOTGCTL_BVALOVAL; + } + + /* Enable HW VBUS sensing */ + USBx->GCCFG |= USB_OTG_GCCFG_VBDEN; + } + + /* Restart the Phy Clock */ + USBx_PCGCCTL = 0U; + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + if (cfg.speed == USBD_HS_SPEED) + { + /* Set Core speed to High speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH); + } + else + { + /* Set Core speed to Full speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_HIGH_IN_FULL); + } + } + else + { + /* Set Core speed to Full speed mode */ + (void)USB_SetDevSpeed(USBx, USB_OTG_SPEED_FULL); + } + + /* Flush the FIFOs */ + if (USB_FlushTxFifo(USBx, 0x10U) != HAL_OK) /* all Tx FIFOs */ + { + ret = HAL_ERROR; + } + + if (USB_FlushRxFifo(USBx) != HAL_OK) + { + ret = HAL_ERROR; + } + + /* Clear all pending Device Interrupts */ + USBx_DEVICE->DIEPMSK = 0U; + USBx_DEVICE->DOEPMSK = 0U; + USBx_DEVICE->DAINTMSK = 0U; + + for (i = 0U; i < cfg.dev_endpoints; i++) + { + if ((USBx_INEP(i)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) + { + if (i == 0U) + { + USBx_INEP(i)->DIEPCTL = USB_OTG_DIEPCTL_SNAK; + } + else + { + USBx_INEP(i)->DIEPCTL = USB_OTG_DIEPCTL_EPDIS | USB_OTG_DIEPCTL_SNAK; + } + } + else + { + USBx_INEP(i)->DIEPCTL = 0U; + } + + USBx_INEP(i)->DIEPTSIZ = 0U; + USBx_INEP(i)->DIEPINT = 0xFB7FU; + } + + for (i = 0U; i < cfg.dev_endpoints; i++) + { + if ((USBx_OUTEP(i)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) + { + if (i == 0U) + { + USBx_OUTEP(i)->DOEPCTL = USB_OTG_DOEPCTL_SNAK; + } + else + { + USBx_OUTEP(i)->DOEPCTL = USB_OTG_DOEPCTL_EPDIS | USB_OTG_DOEPCTL_SNAK; + } + } + else + { + USBx_OUTEP(i)->DOEPCTL = 0U; + } + + USBx_OUTEP(i)->DOEPTSIZ = 0U; + USBx_OUTEP(i)->DOEPINT = 0xFB7FU; + } + + USBx_DEVICE->DIEPMSK &= ~(USB_OTG_DIEPMSK_TXFURM); + + /* Disable all interrupts. */ + USBx->GINTMSK = 0U; + + /* Clear any pending interrupts */ + USBx->GINTSTS = 0xBFFFFFFFU; + + /* Enable the common interrupts */ + if (cfg.dma_enable == 0U) + { + 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 != 0U) + { + USBx->GINTMSK |= USB_OTG_GINTMSK_SOFM; + } + + if (cfg.vbus_sensing_enable == 1U) + { + USBx->GINTMSK |= (USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_OTGINT); + } + + return ret; +} + +/** + * @brief USB_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) +{ + __IO uint32_t count = 0U; + + /* Wait for AHB master IDLE state. */ + do + { + count++; + + if (count > HAL_USB_TIMEOUT) + { + return HAL_TIMEOUT; + } + } while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); + + /* Flush TX Fifo */ + count = 0U; + USBx->GRSTCTL = (USB_OTG_GRSTCTL_TXFFLSH | (num << 6)); + + do + { + count++; + + if (count > HAL_USB_TIMEOUT) + { + 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) +{ + __IO uint32_t count = 0U; + + /* Wait for AHB master IDLE state. */ + do + { + count++; + + if (count > HAL_USB_TIMEOUT) + { + return HAL_TIMEOUT; + } + } while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); + + /* Flush RX Fifo */ + count = 0U; + USBx->GRSTCTL = USB_OTG_GRSTCTL_RXFFLSH; + + do + { + count++; + + if (count > HAL_USB_TIMEOUT) + { + 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 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 + * @retval Hal status + */ +HAL_StatusTypeDef USB_SetDevSpeed(const USB_OTG_GlobalTypeDef *USBx, uint8_t speed) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + 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 these values: + * @arg USBD_HS_SPEED: High speed mode + * @arg USBD_FS_SPEED: Full speed mode + */ +uint8_t USB_GetDevSpeed(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint8_t speed; + uint32_t DevEnumSpeed = USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD; + + if (DevEnumSpeed == DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ) + { + speed = USBD_HS_SPEED; + } + else if ((DevEnumSpeed == DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ) || + (DevEnumSpeed == DSTS_ENUMSPD_FS_PHY_48MHZ)) + { + speed = USBD_FS_SPEED; + } + else + { + speed = 0xFU; + } + + 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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + if (ep->is_in == 1U) + { + USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK)); + + if ((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_USBAEP) == 0U) + { + USBx_INEP(epnum)->DIEPCTL |= (ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ) | + ((uint32_t)ep->type << 18) | (epnum << 22) | + USB_OTG_DIEPCTL_SD0PID_SEVNFRM | + USB_OTG_DIEPCTL_USBAEP; + } + } + else + { + USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16); + + if (((USBx_OUTEP(epnum)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0U) + { + USBx_OUTEP(epnum)->DOEPCTL |= (ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ) | + ((uint32_t)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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* Read DEPCTLn register */ + if (ep->is_in == 1U) + { + if (((USBx_INEP(epnum)->DIEPCTL) & USB_OTG_DIEPCTL_USBAEP) == 0U) + { + USBx_INEP(epnum)->DIEPCTL |= (ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ) | + ((uint32_t)ep->type << 18) | (epnum << 22) | + USB_OTG_DIEPCTL_SD0PID_SEVNFRM | + USB_OTG_DIEPCTL_USBAEP; + } + + USBx_DEVICE->DEACHMSK |= USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK)); + } + else + { + if (((USBx_OUTEP(epnum)->DOEPCTL) & USB_OTG_DOEPCTL_USBAEP) == 0U) + { + USBx_OUTEP(epnum)->DOEPCTL |= (ep->maxpacket & USB_OTG_DOEPCTL_MPSIZ) | + ((uint32_t)ep->type << 18) | (epnum << 22) | + USB_OTG_DOEPCTL_USBAEP; + } + + USBx_DEVICE->DEACHMSK |= USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* Read DEPCTLn register */ + if (ep->is_in == 1U) + { + if ((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SNAK; + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_EPDIS; + } + + USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); + USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); + USBx_INEP(epnum)->DIEPCTL &= ~(USB_OTG_DIEPCTL_USBAEP | + USB_OTG_DIEPCTL_MPSIZ | + USB_OTG_DIEPCTL_TXFNUM | + USB_OTG_DIEPCTL_SD0PID_SEVNFRM | + USB_OTG_DIEPCTL_EPTYP); + } + else + { + if ((USBx_OUTEP(epnum)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) + { + USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; + USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_EPDIS; + } + + USBx_DEVICE->DEACHMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); + USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 16)); + USBx_OUTEP(epnum)->DOEPCTL &= ~(USB_OTG_DOEPCTL_USBAEP | + USB_OTG_DOEPCTL_MPSIZ | + USB_OTG_DOEPCTL_SD0PID_SEVNFRM | + USB_OTG_DOEPCTL_EPTYP); + } + + 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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + /* Read DEPCTLn register */ + if (ep->is_in == 1U) + { + if ((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SNAK; + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_EPDIS; + } + + USBx_INEP(epnum)->DIEPCTL &= ~ USB_OTG_DIEPCTL_USBAEP; + USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_IEPM & (uint32_t)(1UL << (ep->num & EP_ADDR_MSK))); + } + else + { + if ((USBx_OUTEP(epnum)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) + { + USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SNAK; + USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_EPDIS; + } + + USBx_OUTEP(epnum)->DOEPCTL &= ~USB_OTG_DOEPCTL_USBAEP; + USBx_DEVICE->DAINTMSK &= ~(USB_OTG_DAINTMSK_OEPM & ((uint32_t)(1UL << (ep->num & EP_ADDR_MSK)) << 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 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) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + uint16_t pktcnt; + + /* IN endpoint */ + if (ep->is_in == 1U) + { + /* Zero Length Packet? */ + if (ep->xfer_len == 0U) + { + USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT); + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1U << 19)); + USBx_INEP(epnum)->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(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_XFRSIZ); + USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_PKTCNT); + + if (epnum == 0U) + { + if (ep->xfer_len > ep->maxpacket) + { + ep->xfer_len = ep->maxpacket; + } + + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & (1U << 19)); + } + else + { + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_PKTCNT & + (((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket) << 19)); + } + + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_XFRSIZ & ep->xfer_len); + + if (ep->type == EP_TYPE_ISOC) + { + USBx_INEP(epnum)->DIEPTSIZ &= ~(USB_OTG_DIEPTSIZ_MULCNT); + USBx_INEP(epnum)->DIEPTSIZ |= (USB_OTG_DIEPTSIZ_MULCNT & (1U << 29)); + } + } + + if (dma == 1U) + { + if ((uint32_t)ep->dma_addr != 0U) + { + USBx_INEP(epnum)->DIEPDMA = (uint32_t)(ep->dma_addr); + } + + if (ep->type == EP_TYPE_ISOC) + { + if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SODDFRM; + } + else + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; + } + } + + /* EP enable, IN data in FIFO */ + USBx_INEP(epnum)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA); + } + else + { + /* EP enable, IN data in FIFO */ + USBx_INEP(epnum)->DIEPCTL |= (USB_OTG_DIEPCTL_CNAK | USB_OTG_DIEPCTL_EPENA); + + if (ep->type != EP_TYPE_ISOC) + { + /* Enable the Tx FIFO Empty Interrupt for this EP */ + if (ep->xfer_len > 0U) + { + USBx_DEVICE->DIEPEMPMSK |= 1UL << (ep->num & EP_ADDR_MSK); + } + } + else + { + if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SODDFRM; + } + else + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; + } + + (void)USB_WritePacket(USBx, ep->xfer_buff, ep->num, (uint16_t)ep->xfer_len, dma); + } + } + } + else /* OUT endpoint */ + { + /* Program the transfer size and packet count as follows: + * pktcnt = N + * xfersize = N * maxpacket + */ + USBx_OUTEP(epnum)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_XFRSIZ); + USBx_OUTEP(epnum)->DOEPTSIZ &= ~(USB_OTG_DOEPTSIZ_PKTCNT); + + if (epnum == 0U) + { + if (ep->xfer_len > 0U) + { + ep->xfer_len = ep->maxpacket; + } + + /* Store transfer size, for EP0 this is equal to endpoint max packet size */ + ep->xfer_size = ep->maxpacket; + + USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & ep->xfer_size); + USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1U << 19)); + } + else + { + if (ep->xfer_len == 0U) + { + USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_XFRSIZ & ep->maxpacket); + USBx_OUTEP(epnum)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1U << 19)); + } + else + { + pktcnt = (uint16_t)((ep->xfer_len + ep->maxpacket - 1U) / ep->maxpacket); + ep->xfer_size = ep->maxpacket * pktcnt; + + USBx_OUTEP(epnum)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_PKTCNT & ((uint32_t)pktcnt << 19); + USBx_OUTEP(epnum)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_XFRSIZ & ep->xfer_size; + } + } + + if (dma == 1U) + { + if ((uint32_t)ep->xfer_buff != 0U) + { + USBx_OUTEP(epnum)->DOEPDMA = (uint32_t)(ep->xfer_buff); + } + } + + if (ep->type == EP_TYPE_ISOC) + { + if ((USBx_DEVICE->DSTS & (1U << 8)) == 0U) + { + USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SODDFRM; + } + else + { + USBx_OUTEP(epnum)->DOEPCTL |= USB_OTG_DOEPCTL_SD0PID_SEVNFRM; + } + } + /* EP enable */ + USBx_OUTEP(epnum)->DOEPCTL |= (USB_OTG_DOEPCTL_CNAK | USB_OTG_DOEPCTL_EPENA); + } + + return HAL_OK; +} + + +/** + * @brief USB_EPStoptXfer Stop transfer on an EP + * @param USBx usb device instance + * @param ep pointer to endpoint structure + * @retval HAL status + */ +HAL_StatusTypeDef USB_EPStopXfer(const USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) +{ + __IO uint32_t count = 0U; + HAL_StatusTypeDef ret = HAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + + /* IN endpoint */ + if (ep->is_in == 1U) + { + /* EP enable, IN data in FIFO */ + if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA) + { + USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_SNAK); + USBx_INEP(ep->num)->DIEPCTL |= (USB_OTG_DIEPCTL_EPDIS); + + do + { + count++; + + if (count > 10000U) + { + ret = HAL_ERROR; + break; + } + } while (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == USB_OTG_DIEPCTL_EPENA); + } + } + else /* OUT endpoint */ + { + if (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) + { + USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_SNAK); + USBx_OUTEP(ep->num)->DOEPCTL |= (USB_OTG_DOEPCTL_EPDIS); + + do + { + count++; + + if (count > 10000U) + { + ret = HAL_ERROR; + break; + } + } while (((USBx_OUTEP(ep->num)->DOEPCTL) & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA); + } + } + + return ret; +} + + +/** + * @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 these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @retval HAL status + */ +HAL_StatusTypeDef USB_WritePacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *src, + uint8_t ch_ep_num, uint16_t len, uint8_t dma) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint8_t *pSrc = src; + uint32_t count32b; + uint32_t i; + + if (dma == 0U) + { + count32b = ((uint32_t)len + 3U) / 4U; + for (i = 0U; i < count32b; i++) + { + USBx_DFIFO((uint32_t)ch_ep_num) = __UNALIGNED_UINT32_READ(pSrc); + pSrc++; + pSrc++; + pSrc++; + pSrc++; + } + } + + return HAL_OK; +} + +/** + * @brief USB_ReadPacket : read a packet from the RX FIFO + * @param USBx Selected device + * @param dest source pointer + * @param len Number of bytes to read + * @retval pointer to destination buffer + */ +void *USB_ReadPacket(const USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint8_t *pDest = dest; + uint32_t pData; + uint32_t i; + uint32_t count32b = (uint32_t)len >> 2U; + uint16_t remaining_bytes = len % 4U; + + for (i = 0U; i < count32b; i++) + { + __UNALIGNED_UINT32_WRITE(pDest, USBx_DFIFO(0U)); + pDest++; + pDest++; + pDest++; + pDest++; + } + + /* When Number of data is not word aligned, read the remaining byte */ + if (remaining_bytes != 0U) + { + i = 0U; + __UNALIGNED_UINT32_WRITE(&pData, USBx_DFIFO(0U)); + + do + { + *(uint8_t *)pDest = (uint8_t)(pData >> (8U * (uint8_t)(i))); + i++; + pDest++; + remaining_bytes--; + } while (remaining_bytes != 0U); + } + + return ((void *)pDest); +} + +/** + * @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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + if (ep->is_in == 1U) + { + if (((USBx_INEP(epnum)->DIEPCTL & USB_OTG_DIEPCTL_EPENA) == 0U) && (epnum != 0U)) + { + USBx_INEP(epnum)->DIEPCTL &= ~(USB_OTG_DIEPCTL_EPDIS); + } + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_STALL; + } + else + { + if (((USBx_OUTEP(epnum)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == 0U) && (epnum != 0U)) + { + USBx_OUTEP(epnum)->DOEPCTL &= ~(USB_OTG_DOEPCTL_EPDIS); + } + USBx_OUTEP(epnum)->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(const USB_OTG_GlobalTypeDef *USBx, const USB_OTG_EPTypeDef *ep) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t epnum = (uint32_t)ep->num; + + if (ep->is_in == 1U) + { + USBx_INEP(epnum)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL; + if ((ep->type == EP_TYPE_INTR) || (ep->type == EP_TYPE_BULK)) + { + USBx_INEP(epnum)->DIEPCTL |= USB_OTG_DIEPCTL_SD0PID_SEVNFRM; /* DATA0 */ + } + } + else + { + USBx_OUTEP(epnum)->DOEPCTL &= ~USB_OTG_DOEPCTL_STALL; + if ((ep->type == EP_TYPE_INTR) || (ep->type == EP_TYPE_BULK)) + { + USBx_OUTEP(epnum)->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) +{ + HAL_StatusTypeDef ret; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + + /* Clear Pending interrupt */ + for (i = 0U; i < 15U; i++) + { + USBx_INEP(i)->DIEPINT = 0xFB7FU; + USBx_OUTEP(i)->DOEPINT = 0xFB7FU; + } + + /* Clear interrupt masks */ + USBx_DEVICE->DIEPMSK = 0U; + USBx_DEVICE->DOEPMSK = 0U; + USBx_DEVICE->DAINTMSK = 0U; + + /* Flush the FIFO */ + ret = USB_FlushRxFifo(USBx); + if (ret != HAL_OK) + { + return ret; + } + + ret = USB_FlushTxFifo(USBx, 0x10U); + if (ret != HAL_OK) + { + return ret; + } + + return ret; +} + +/** + * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t address) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + USBx_DEVICE->DCFG &= ~(USB_OTG_DCFG_DAD); + USBx_DEVICE->DCFG |= ((uint32_t)address << 4) & USB_OTG_DCFG_DAD; + + return HAL_OK; +} + +/** + * @brief USB_DevConnect : Connect the USB device by enabling Rpu + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_DevConnect(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* In case phy is stopped, ensure to ungate and restore the phy CLK */ + USBx_PCGCCTL &= ~(USB_OTG_PCGCCTL_STOPCLK | USB_OTG_PCGCCTL_GATECLK); + + USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_SDIS; + + return HAL_OK; +} + +/** + * @brief USB_DevDisconnect : Disconnect the USB device by disabling Rpu + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_DevDisconnect(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* In case phy is stopped, ensure to ungate and restore the phy CLK */ + USBx_PCGCCTL &= ~(USB_OTG_PCGCCTL_STOPCLK | USB_OTG_PCGCCTL_GATECLK); + + USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS; + + return HAL_OK; +} + +/** + * @brief USB_ReadInterrupts: return the global USB interrupt status + * @param USBx Selected device + * @retval USB Global Interrupt status + */ +uint32_t USB_ReadInterrupts(USB_OTG_GlobalTypeDef const *USBx) +{ + uint32_t tmpreg; + + tmpreg = USBx->GINTSTS; + tmpreg &= USBx->GINTMSK; + + return tmpreg; +} + +/** + * @brief USB_ReadChInterrupts: return USB channel interrupt status + * @param USBx Selected device + * @param chnum Channel number + * @retval USB Channel Interrupt status + */ +uint32_t USB_ReadChInterrupts(const USB_OTG_GlobalTypeDef *USBx, uint8_t chnum) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_HC(chnum)->HCINT; + tmpreg &= USBx_HC(chnum)->HCINTMSK; + + return tmpreg; +} + +/** + * @brief USB_ReadDevAllOutEpInterrupt: return the USB device OUT endpoints interrupt status + * @param USBx Selected device + * @retval USB Device OUT EP interrupt status + */ +uint32_t USB_ReadDevAllOutEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_DEVICE->DAINT; + tmpreg &= USBx_DEVICE->DAINTMSK; + + return ((tmpreg & 0xffff0000U) >> 16); +} + +/** + * @brief USB_ReadDevAllInEpInterrupt: return the USB device IN endpoints interrupt status + * @param USBx Selected device + * @retval USB Device IN EP interrupt status + */ +uint32_t USB_ReadDevAllInEpInterrupt(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_DEVICE->DAINT; + tmpreg &= USBx_DEVICE->DAINTMSK; + + return ((tmpreg & 0xFFFFU)); +} + +/** + * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + + tmpreg = USBx_OUTEP((uint32_t)epnum)->DOEPINT; + tmpreg &= USBx_DEVICE->DOEPMSK; + + return tmpreg; +} + +/** + * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t epnum) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t tmpreg; + uint32_t msk; + uint32_t emp; + + msk = USBx_DEVICE->DIEPMSK; + emp = USBx_DEVICE->DIEPEMPMSK; + msk |= ((emp >> (epnum & EP_ADDR_MSK)) & 0x1U) << 7; + tmpreg = USBx_INEP((uint32_t)epnum)->DIEPINT & msk; + + return tmpreg; +} + +/** + * @brief USB_ClearInterrupts: clear a USB interrupt + * @param USBx Selected device + * @param 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 these values: + * 0 : Host + * 1 : Device + */ +uint32_t USB_GetMode(const USB_OTG_GlobalTypeDef *USBx) +{ + return ((USBx->GINTSTS) & 0x1U); +} + +/** + * @brief Activate EP0 for Setup transactions + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_ActivateSetup(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* Set the MPS of the IN EP0 to 64 bytes */ + USBx_INEP(0U)->DIEPCTL &= ~USB_OTG_DIEPCTL_MPSIZ; + + 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 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(const USB_OTG_GlobalTypeDef *USBx, uint8_t dma, const uint8_t *psetup) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t gSNPSiD = *(__IO const uint32_t *)(&USBx->CID + 0x1U); + + if (gSNPSiD > USB_OTG_CORE_ID_300A) + { + if ((USBx_OUTEP(0U)->DOEPCTL & USB_OTG_DOEPCTL_EPENA) == USB_OTG_DOEPCTL_EPENA) + { + return HAL_OK; + } + } + + USBx_OUTEP(0U)->DOEPTSIZ = 0U; + USBx_OUTEP(0U)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1U << 19)); + USBx_OUTEP(0U)->DOEPTSIZ |= (3U * 8U); + USBx_OUTEP(0U)->DOEPTSIZ |= USB_OTG_DOEPTSIZ_STUPCNT; + + if (dma == 1U) + { + USBx_OUTEP(0U)->DOEPDMA = (uint32_t)psetup; + /* EP enable */ + USBx_OUTEP(0U)->DOEPCTL |= USB_OTG_DOEPCTL_EPENA | USB_OTG_DOEPCTL_USBAEP; + } + + 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) +{ + __IO uint32_t count = 0U; + + /* Wait for AHB master IDLE state. */ + do + { + count++; + + if (count > HAL_USB_TIMEOUT) + { + return HAL_TIMEOUT; + } + } while ((USBx->GRSTCTL & USB_OTG_GRSTCTL_AHBIDL) == 0U); + + /* Core Soft Reset */ + count = 0U; + USBx->GRSTCTL |= USB_OTG_GRSTCTL_CSRST; + + do + { + count++; + + if (count > HAL_USB_TIMEOUT) + { + 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) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t i; + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + /* Enable USB PHY pulldown resistors */ + USBx->GCCFG |= USB_OTG_GCCFG_PULLDOWNEN; + } + + /* Restart the Phy Clock */ + USBx_PCGCCTL = 0U; + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + /* Disable VBUS override */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_VBVALOVAL | USB_OTG_GCCFG_VBVALEXTOEN); + } + + /* Disable VBUS sensing */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_VBDEN); + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) != 0U) + { + /* Disable Battery chargin detector */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_BCDEN); + } + else + { + /* Disable Battery chargin detector */ + USBx->GCCFG &= ~(USB_OTG_GCCFG_PDEN); + USBx->GCCFG &= ~(USB_OTG_GCCFG_SDEN); + } + + if ((USBx->GUSBCFG & USB_OTG_GUSBCFG_PHYSEL) == 0U) + { + if (cfg.speed == USBH_FSLS_SPEED) + { + /* Force Device Enumeration to FS/LS mode only */ + USBx_HOST->HCFG |= USB_OTG_HCFG_FSLSS; + } + else + { + /* Set default Max speed support */ + USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSS); + } + } + else + { + /* Set default Max speed support */ + USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSS); + } + + /* Make sure the FIFOs are flushed. */ + if (USB_FlushTxFifo(USBx, 0x10U) != HAL_OK) /* all Tx FIFOs */ + { + ret = HAL_ERROR; + } + + if (USB_FlushRxFifo(USBx) != HAL_OK) + { + ret = HAL_ERROR; + } + + /* Clear all pending HC Interrupts */ + for (i = 0U; i < cfg.Host_channels; i++) + { + USBx_HC(i)->HCINT = CLEAR_INTERRUPT_MASK; + USBx_HC(i)->HCINTMSK = 0U; + } + + /* Disable all interrupts. */ + USBx->GINTMSK = 0U; + + /* Clear any pending interrupts */ + USBx->GINTSTS = CLEAR_INTERRUPT_MASK; +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) + { + /* set Rx FIFO size */ + USBx->GRXFSIZ = 0x200U; + USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t)(((0x100U << 16) & USB_OTG_NPTXFD) | 0x200U); + USBx->HPTXFSIZ = (uint32_t)(((0xE0U << 16) & USB_OTG_HPTXFSIZ_PTXFD) | 0x300U); + } + else +#endif /* defined (USB_OTG_HS) */ + { + /* set Rx FIFO size */ + USBx->GRXFSIZ = 0x80U; + USBx->DIEPTXF0_HNPTXFSIZ = (uint32_t)(((0x60U << 16) & USB_OTG_NPTXFD) | 0x80U); + USBx->HPTXFSIZ = (uint32_t)(((0x40U << 16)& USB_OTG_HPTXFSIZ_PTXFD) | 0xE0U); + } + + /* Enable the common interrupts */ + if (cfg.dma_enable == 0U) + { + 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 ret; +} + +/** + * @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 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(const USB_OTG_GlobalTypeDef *USBx, uint8_t freq) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSPCS); + USBx_HOST->HCFG |= (uint32_t)freq & USB_OTG_HCFG_FSLSPCS; + + if (freq == HCFG_48_MHZ) + { + USBx_HOST->HFIR = HFIR_48_MHZ; + } + else if (freq == HCFG_6_MHZ) + { + USBx_HOST->HFIR = HFIR_6_MHZ; + } + else + { + return HAL_ERROR; + } + + 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(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + __IO uint32_t hprt0 = 0U; + + 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(100U); /* See Note #1 */ + USBx_HPRT0 = ((~USB_OTG_HPRT_PRST) & hprt0); + HAL_Delay(10U); + + return HAL_OK; +} + +/** + * @brief USB_DriveVbus : activate or de-activate vbus + * @param state VBUS state + * This parameter can be one of these values: + * 0 : Deactivate VBUS + * 1 : Activate VBUS + * @retval HAL status + */ +HAL_StatusTypeDef USB_DriveVbus(const USB_OTG_GlobalTypeDef *USBx, uint8_t state) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t hprt0 = 0U; + + 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) == 0U) && (state == 1U)) + { + USBx_HPRT0 = (USB_OTG_HPRT_PPWR | hprt0); + } + if (((hprt0 & USB_OTG_HPRT_PPWR) == USB_OTG_HPRT_PPWR) && (state == 0U)) + { + 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 these values: + * @arg HCD_SPEED_HIGH: High speed mode + * @arg HCD_SPEED_FULL: Full speed mode + * @arg HCD_SPEED_LOW: Low speed mode + */ +uint32_t USB_GetHostSpeed(USB_OTG_GlobalTypeDef const *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t hprt0 = 0U; + + 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 const *USBx) +{ + uint32_t USBx_BASE = (uint32_t)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 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 these values: + * @arg EP_TYPE_CTRL: Control type + * @arg EP_TYPE_ISOC: Isochronous 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 to 32K + * @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) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t HCcharEpDir; + uint32_t HCcharLowSpeed; + uint32_t HostCoreSpeed; + + /* Clear old interrupt conditions for this host channel. */ + USBx_HC((uint32_t)ch_num)->HCINT = CLEAR_INTERRUPT_MASK; + + /* Enable channel interrupts required for this transfer. */ + switch (ep_type) + { + case EP_TYPE_CTRL: + case EP_TYPE_BULK: + USBx_HC((uint32_t)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 & 0x80U) == 0x80U) + { + USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM; + } + else + { +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) + { + USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_NYET | + USB_OTG_HCINTMSK_ACKM; + } +#endif /* defined (USB_OTG_HS) */ + } + break; + + case EP_TYPE_INTR: + USBx_HC((uint32_t)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 & 0x80U) == 0x80U) + { + USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_BBERRM; + } + + break; + + case EP_TYPE_ISOC: + USBx_HC((uint32_t)ch_num)->HCINTMSK = USB_OTG_HCINTMSK_XFRCM | + USB_OTG_HCINTMSK_ACKM | + USB_OTG_HCINTMSK_AHBERR | + USB_OTG_HCINTMSK_FRMORM; + + if ((epnum & 0x80U) == 0x80U) + { + USBx_HC((uint32_t)ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_TXERRM | USB_OTG_HCINTMSK_BBERRM); + } + break; + + default: + ret = HAL_ERROR; + break; + } + + /* Clear Hub Start Split transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT = 0U; + + /* Enable host channel Halt interrupt */ + USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_CHHM; + + /* Enable the top level host channel interrupt. */ + USBx_HOST->HAINTMSK |= 1UL << (ch_num & 0xFU); + + /* Make sure host channel interrupts are enabled. */ + USBx->GINTMSK |= USB_OTG_GINTMSK_HCIM; + + /* Program the HCCHAR register */ + if ((epnum & 0x80U) == 0x80U) + { + HCcharEpDir = (0x1U << 15) & USB_OTG_HCCHAR_EPDIR; + } + else + { + HCcharEpDir = 0U; + } + + HostCoreSpeed = USB_GetHostSpeed(USBx); + + /* LS device plugged to HUB */ + if ((speed == HPRT0_PRTSPD_LOW_SPEED) && (HostCoreSpeed != HPRT0_PRTSPD_LOW_SPEED)) + { + HCcharLowSpeed = (0x1U << 17) & USB_OTG_HCCHAR_LSDEV; + } + else + { + HCcharLowSpeed = 0U; + } + + USBx_HC((uint32_t)ch_num)->HCCHAR = (((uint32_t)dev_address << 22) & USB_OTG_HCCHAR_DAD) | + ((((uint32_t)epnum & 0x7FU) << 11) & USB_OTG_HCCHAR_EPNUM) | + (((uint32_t)ep_type << 18) & USB_OTG_HCCHAR_EPTYP) | + ((uint32_t)mps & USB_OTG_HCCHAR_MPSIZ) | + USB_OTG_HCCHAR_MC_0 | HCcharEpDir | HCcharLowSpeed; + + if ((ep_type == EP_TYPE_INTR) || (ep_type == EP_TYPE_ISOC)) + { + USBx_HC((uint32_t)ch_num)->HCCHAR |= USB_OTG_HCCHAR_ODDFRM; + } + + return ret; +} + +/** + * @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 these values: + * 0 : DMA feature not used + * 1 : DMA feature used + * @retval HAL state + */ +HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t ch_num = (uint32_t)hc->ch_num; + __IO uint32_t tmpreg; + uint8_t is_oddframe; + uint16_t len_words; + uint16_t num_packets; + uint16_t max_hc_pkt_count = HC_MAX_PKT_CNT; + +#if defined (USB_OTG_HS) + if (USBx == USB_OTG_HS) + { + /* in DMA mode host Core automatically issues ping in case of NYET/NAK */ + if (dma == 1U) + { + if (((hc->ep_type == EP_TYPE_CTRL) || (hc->ep_type == EP_TYPE_BULK)) && (hc->do_ssplit == 0U)) + { + + USBx_HC((uint32_t)ch_num)->HCINTMSK &= ~(USB_OTG_HCINTMSK_NYET | + USB_OTG_HCINTMSK_ACKM | + USB_OTG_HCINTMSK_NAKM); + } + } + else + { + if ((hc->speed == USBH_HS_SPEED) && (hc->do_ping == 1U)) + { + (void)USB_DoPing(USBx, hc->ch_num); + return HAL_OK; + } + } + } +#endif /* defined (USB_OTG_HS) */ + + if (hc->do_ssplit == 1U) + { + /* Set number of packet to 1 for Split transaction */ + num_packets = 1U; + + if (hc->ep_is_in != 0U) + { + hc->XferSize = (uint32_t)num_packets * hc->max_packet; + } + else + { + if (hc->ep_type == EP_TYPE_ISOC) + { + if (hc->xfer_len > ISO_SPLT_MPS) + { + /* Isochrone Max Packet Size for Split mode */ + hc->XferSize = hc->max_packet; + hc->xfer_len = hc->XferSize; + + if ((hc->iso_splt_xactPos == HCSPLT_BEGIN) || (hc->iso_splt_xactPos == HCSPLT_MIDDLE)) + { + hc->iso_splt_xactPos = HCSPLT_MIDDLE; + } + else + { + hc->iso_splt_xactPos = HCSPLT_BEGIN; + } + } + else + { + hc->XferSize = hc->xfer_len; + + if ((hc->iso_splt_xactPos != HCSPLT_BEGIN) && (hc->iso_splt_xactPos != HCSPLT_MIDDLE)) + { + hc->iso_splt_xactPos = HCSPLT_FULL; + } + else + { + hc->iso_splt_xactPos = HCSPLT_END; + } + } + } + else + { + if ((dma == 1U) && (hc->xfer_len > hc->max_packet)) + { + hc->XferSize = (uint32_t)num_packets * hc->max_packet; + } + else + { + hc->XferSize = hc->xfer_len; + } + } + } + } + else + { + /* Compute the expected number of packets associated to the transfer */ + if (hc->xfer_len > 0U) + { + num_packets = (uint16_t)((hc->xfer_len + hc->max_packet - 1U) / hc->max_packet); + + if (num_packets > max_hc_pkt_count) + { + num_packets = max_hc_pkt_count; + hc->XferSize = (uint32_t)num_packets * hc->max_packet; + } + } + else + { + num_packets = 1U; + } + + /* + * For IN channel HCTSIZ.XferSize is expected to be an integer multiple of + * max_packet size. + */ + if (hc->ep_is_in != 0U) + { + hc->XferSize = (uint32_t)num_packets * hc->max_packet; + } + else + { + hc->XferSize = hc->xfer_len; + } + } + + /* Initialize the HCTSIZn register */ + USBx_HC(ch_num)->HCTSIZ = (hc->XferSize & USB_OTG_HCTSIZ_XFRSIZ) | + (((uint32_t)num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) | + (((uint32_t)hc->data_pid << 29) & USB_OTG_HCTSIZ_DPID); + + if (dma != 0U) + { + /* xfer_buff MUST be 32-bits aligned */ + USBx_HC(ch_num)->HCDMA = (uint32_t)hc->xfer_buff; + } + + is_oddframe = (((uint32_t)USBx_HOST->HFNUM & 0x01U) != 0U) ? 0U : 1U; + USBx_HC(ch_num)->HCCHAR &= ~USB_OTG_HCCHAR_ODDFRM; + USBx_HC(ch_num)->HCCHAR |= (uint32_t)is_oddframe << 29; + + if (hc->do_ssplit == 1U) + { + /* Set Hub start Split transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT = ((uint32_t)hc->hub_addr << USB_OTG_HCSPLT_HUBADDR_Pos) | + (uint32_t)hc->hub_port_nbr | USB_OTG_HCSPLT_SPLITEN; + + /* unmask ack & nyet for IN/OUT transactions */ + USBx_HC((uint32_t)ch_num)->HCINTMSK |= (USB_OTG_HCINTMSK_ACKM | + USB_OTG_HCINTMSK_NYET); + + if ((hc->do_csplit == 1U) && (hc->ep_is_in == 0U)) + { + USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_COMPLSPLT; + USBx_HC((uint32_t)ch_num)->HCINTMSK |= USB_OTG_HCINTMSK_NYET; + } + + if (((hc->ep_type == EP_TYPE_ISOC) || (hc->ep_type == EP_TYPE_INTR)) && + (hc->do_csplit == 1U) && (hc->ep_is_in == 1U)) + { + USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_COMPLSPLT; + } + + /* Position management for iso out transaction on split mode */ + if ((hc->ep_type == EP_TYPE_ISOC) && (hc->ep_is_in == 0U)) + { + /* Set data payload position */ + switch (hc->iso_splt_xactPos) + { + case HCSPLT_BEGIN: + /* First data payload for OUT Transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS_1; + break; + + case HCSPLT_MIDDLE: + /* Middle data payload for OUT Transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS_Pos; + break; + + case HCSPLT_END: + /* End data payload for OUT Transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS_0; + break; + + case HCSPLT_FULL: + /* Entire data payload for OUT Transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT |= USB_OTG_HCSPLT_XACTPOS; + break; + + default: + break; + } + } + } + else + { + /* Clear Hub Start Split transaction */ + USBx_HC((uint32_t)ch_num)->HCSPLT = 0U; + } + + /* Set host channel enable */ + tmpreg = USBx_HC(ch_num)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + + /* make sure to set the correct ep direction */ + if (hc->ep_is_in != 0U) + { + tmpreg |= USB_OTG_HCCHAR_EPDIR; + } + else + { + tmpreg &= ~USB_OTG_HCCHAR_EPDIR; + } + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(ch_num)->HCCHAR = tmpreg; + + if (dma != 0U) /* dma mode */ + { + return HAL_OK; + } + + if ((hc->ep_is_in == 0U) && (hc->xfer_len > 0U) && (hc->do_csplit == 0U)) + { + switch (hc->ep_type) + { + /* Non periodic transfer */ + case EP_TYPE_CTRL: + case EP_TYPE_BULK: + + len_words = (uint16_t)((hc->xfer_len + 3U) / 4U); + + /* check if there is enough space in FIFO space */ + if (len_words > (USBx->HNPTXSTS & 0xFFFFU)) + { + /* 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 = (uint16_t)((hc->xfer_len + 3U) / 4U); + /* check if there is enough space in FIFO space */ + if (len_words > (USBx_HOST->HPTXSTS & 0xFFFFU)) /* 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. */ + (void)USB_WritePacket(USBx, hc->xfer_buff, hc->ch_num, (uint16_t)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(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + return ((USBx_HOST->HAINT) & 0xFFFFU); +} + +/** + * @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(const USB_OTG_GlobalTypeDef *USBx, uint8_t hc_num) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t hcnum = (uint32_t)hc_num; + __IO uint32_t count = 0U; + uint32_t HcEpType = (USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_EPTYP) >> 18; + uint32_t ChannelEna = (USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_CHENA) >> 31; + uint32_t SplitEna = (USBx_HC(hcnum)->HCSPLT & USB_OTG_HCSPLT_SPLITEN) >> 31; + + /* In buffer DMA, Channel disable must not be programmed for non-split periodic channels. + At the end of the next uframe/frame (in the worst case), the core generates a channel halted + and disables the channel automatically. */ + + if ((((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == USB_OTG_GAHBCFG_DMAEN) && (SplitEna == 0U)) && + ((ChannelEna == 0U) || (((HcEpType == HCCHAR_ISOC) || (HcEpType == HCCHAR_INTR))))) + { + return HAL_OK; + } + + /* Check for space in the request queue to issue the halt. */ + if ((HcEpType == HCCHAR_CTRL) || (HcEpType == HCCHAR_BULK)) + { + USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHDIS; + + if ((USBx->GAHBCFG & USB_OTG_GAHBCFG_DMAEN) == 0U) + { + if ((USBx->HNPTXSTS & (0xFFU << 16)) == 0U) + { + USBx_HC(hcnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA; + USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; + do + { + count++; + + if (count > 1000U) + { + break; + } + } while ((USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA); + } + else + { + USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; + } + } + else + { + USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; + } + } + else + { + USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHDIS; + + if ((USBx_HOST->HPTXSTS & (0xFFU << 16)) == 0U) + { + USBx_HC(hcnum)->HCCHAR &= ~USB_OTG_HCCHAR_CHENA; + USBx_HC(hcnum)->HCCHAR |= USB_OTG_HCCHAR_CHENA; + do + { + count++; + + if (count > 1000U) + { + break; + } + } while ((USBx_HC(hcnum)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA); + } + else + { + USBx_HC(hcnum)->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(const USB_OTG_GlobalTypeDef *USBx, uint8_t ch_num) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + uint32_t chnum = (uint32_t)ch_num; + uint32_t num_packets = 1U; + uint32_t tmpreg; + + USBx_HC(chnum)->HCTSIZ = ((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) | + USB_OTG_HCTSIZ_DOPING; + + /* Set host channel enable */ + tmpreg = USBx_HC(chnum)->HCCHAR; + tmpreg &= ~USB_OTG_HCCHAR_CHDIS; + tmpreg |= USB_OTG_HCCHAR_CHENA; + USBx_HC(chnum)->HCCHAR = tmpreg; + + return HAL_OK; +} + +/** + * @brief Stop Host Core + * @param USBx Selected device + * @retval HAL state + */ +HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx) +{ + HAL_StatusTypeDef ret = HAL_OK; + uint32_t USBx_BASE = (uint32_t)USBx; + __IO uint32_t count = 0U; + uint32_t value; + uint32_t i; + + (void)USB_DisableGlobalInt(USBx); + + /* Flush USB FIFO */ + if (USB_FlushTxFifo(USBx, 0x10U) != HAL_OK) /* all Tx FIFOs */ + { + ret = HAL_ERROR; + } + + if (USB_FlushRxFifo(USBx) != HAL_OK) + { + ret = HAL_ERROR; + } + + /* Flush out any leftover queued requests. */ + for (i = 0U; i <= 15U; 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 = 0U; i <= 15U; 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 + { + count++; + + if (count > 1000U) + { + break; + } + } while ((USBx_HC(i)->HCCHAR & USB_OTG_HCCHAR_CHENA) == USB_OTG_HCCHAR_CHENA); + } + + /* Clear any pending Host interrupts */ + USBx_HOST->HAINT = CLEAR_INTERRUPT_MASK; + USBx->GINTSTS = CLEAR_INTERRUPT_MASK; + + (void)USB_EnableGlobalInt(USBx); + + return ret; +} + +/** + * @brief USB_ActivateRemoteWakeup active remote wakeup signalling + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_ActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + if ((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS) + { + /* active Remote wakeup signalling */ + USBx_DEVICE->DCTL |= USB_OTG_DCTL_RWUSIG; + } + + return HAL_OK; +} + +/** + * @brief USB_DeActivateRemoteWakeup de-active remote wakeup signalling + * @param USBx Selected device + * @retval HAL status + */ +HAL_StatusTypeDef USB_DeActivateRemoteWakeup(const USB_OTG_GlobalTypeDef *USBx) +{ + uint32_t USBx_BASE = (uint32_t)USBx; + + /* active Remote wakeup signalling */ + USBx_DEVICE->DCTL &= ~(USB_OTG_DCTL_RWUSIG); + + return HAL_OK; +} +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* defined (USB_OTG_FS) || defined (USB_OTG_HS) */ +#endif /* defined (HAL_PCD_MODULE_ENABLED) || defined (HAL_HCD_MODULE_ENABLED) */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_utils.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_utils.c index 938a75c7d..7439550de 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_utils.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_ll_utils.c @@ -1,866 +1,866 @@ -/** - ****************************************************************************** - * @file stm32h7rsxx_ll_utils.c - * @author MCD Application Team - * @brief UTILS LL module driver. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -/* Includes ------------------------------------------------------------------*/ -#include "stm32h7rsxx_ll_utils.h" -#include "stm32h7rsxx_ll_rcc.h" -#include "stm32h7rsxx_ll_pwr.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -/** @addtogroup STM32H7RSxx_LL_Driver - * @{ - */ - -/** @addtogroup UTILS_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup UTILS_LL_Private_Constants - * @{ - */ -#define UTILS_MAX_FREQUENCY_SCALE0 467000000U /*!< Maximum frequency for system clock at power scale 0, in Hz */ -#define UTILS_MAX_FREQUENCY_SCALE1 365000000U /*!< Maximum frequency for system clock at power scale 1, in Hz */ - -/* Defines used for PLL range */ -#define UTILS_PLLVCO_INPUT_MIN1 1000000U /*!< Frequency min for the medium range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MAX1 2000000U /*!< Frequency max for the medium range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MIN2 2000000U /*!< Frequency min for the wide range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MAX2 4000000U /*!< Frequency max for the wide range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MIN3 4000000U /*!< Frequency min for the wide range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MAX3 8000000U /*!< Frequency max for the wide range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MIN4 8000000U /*!< Frequency min for the wide range PLLVCO input, in Hz */ -#define UTILS_PLLVCO_INPUT_MAX4 16000000U /*!< Frequency max for the wide range PLLVCO input, in Hz */ - -#define UTILS_PLLVCO_MEDIUM_OUTPUT_MIN 150000000U /*!< Frequency min for the medium range PLLVCO output, in Hz */ -#define UTILS_PLLVCO_WIDE_OUTPUT_MIN 400000000U /*!< Frequency min for the wide range PLLVCO output, in Hz */ -#define UTILS_PLLVCO_MEDIUM_OUTPUT_MAX 420000000U /*!< Frequency max for the medium range PLLVCO output, in Hz */ -#define UTILS_PLLVCO_WIDE_OUTPUT_MAX 1600000000U /*!< Frequency max for the wide range PLLVCO output, in Hz */ - -/* Defines used for HSE range */ -#define UTILS_HSE_FREQUENCY_MIN 4000000U /*!< Frequency min for HSE frequency, in Hz */ -#define UTILS_HSE_FREQUENCY_MAX 50000000U /*!< Frequency max for HSE frequency, in Hz */ - -/* Defines used for FLASH latency according to HCLK Frequency at */ -/* VOS0 (highest power/frequency) or VOS1 (lowest power/frequency) */ -#define UTILS_SCALE0_LATENCY0_FREQ 40000000U /*!< HCLK frequency to set FLASH latency 0 in power scale 0 */ -#define UTILS_SCALE0_LATENCY1_FREQ 80000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 0 */ -#define UTILS_SCALE0_LATENCY2_FREQ 120000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 0 */ -#define UTILS_SCALE0_LATENCY3_FREQ 160000000U /*!< HCLK frequency to set FLASH latency 3 in power scale 0 */ -#define UTILS_SCALE0_LATENCY4_FREQ 200000000U /*!< HCLK frequency to set FLASH latency 4 in power scale 0 */ -#define UTILS_SCALE0_LATENCY5_FREQ 234000000U /*!< HCLK frequency to set FLASH latency 5 in power scale 0 */ - -#define UTILS_SCALE1_LATENCY0_FREQ 36000000U /*!< HCLK frequency to set FLASH latency 0 in power scale 1 */ -#define UTILS_SCALE1_LATENCY1_FREQ 72000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 1 */ -#define UTILS_SCALE1_LATENCY2_FREQ 108000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 1 */ -#define UTILS_SCALE1_LATENCY3_FREQ 144000000U /*!< HCLK frequency to set FLASH latency 3 in power scale 1 */ -#define UTILS_SCALE1_LATENCY4_FREQ 180000000U /*!< HCLK frequency to set FLASH latency 4 in power scale 1 */ -#define UTILS_SCALE1_LATENCY5_FREQ 183000000U /*!< HCLK frequency to set FLASH latency 5 in power scale 1 */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup UTILS_LL_Private_Macros - * @{ - */ -#define IS_LL_UTILS_SYSCLK_DIV(__VALUE__) (((__VALUE__) == LL_RCC_SYSCLK_DIV_1) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_2) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_4) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_8) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_16) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_64) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_128) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_256) \ - || ((__VALUE__) == LL_RCC_SYSCLK_DIV_512)) - -#define IS_LL_UTILS_AHB_DIV(__VALUE__) (((__VALUE__) == LL_RCC_AHB_DIV_1) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_2) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_4) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_8) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_16) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_64) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_128) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_256) \ - || ((__VALUE__) == LL_RCC_AHB_DIV_512)) - -#define IS_LL_UTILS_APB1_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB1_DIV_1) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_2) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_4) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_8) \ - || ((__VALUE__) == LL_RCC_APB1_DIV_16)) - -#define IS_LL_UTILS_APB2_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB2_DIV_1) \ - || ((__VALUE__) == LL_RCC_APB2_DIV_2) \ - || ((__VALUE__) == LL_RCC_APB2_DIV_4) \ - || ((__VALUE__) == LL_RCC_APB2_DIV_8) \ - || ((__VALUE__) == LL_RCC_APB2_DIV_16)) - -#define IS_LL_UTILS_APB4_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB4_DIV_1) \ - || ((__VALUE__) == LL_RCC_APB4_DIV_2) \ - || ((__VALUE__) == LL_RCC_APB4_DIV_4) \ - || ((__VALUE__) == LL_RCC_APB4_DIV_8) \ - || ((__VALUE__) == LL_RCC_APB4_DIV_16)) - -#define IS_LL_UTILS_APB5_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB5_DIV_1) \ - || ((__VALUE__) == LL_RCC_APB5_DIV_2) \ - || ((__VALUE__) == LL_RCC_APB5_DIV_4) \ - || ((__VALUE__) == LL_RCC_APB5_DIV_8) \ - || ((__VALUE__) == LL_RCC_APB5_DIV_16)) - -#define IS_LL_UTILS_PLLM_VALUE(__VALUE__) ((1U <= (__VALUE__)) && ((__VALUE__) <= 63U)) - -#define IS_LL_UTILS_PLLN_VALUE(__VALUE__) ((8U <= (__VALUE__)) && ((__VALUE__) <= 420U)) - -#define IS_LL_UTILS_PLLP_VALUE(__VALUE__) ((1U <= (__VALUE__)) && ((__VALUE__) <= 128U)) - -#define IS_LL_UTILS_FRACN_VALUE(__VALUE__) ((__VALUE__) <= 0x1FFFU) - -#define IS_LL_UTILS_PLLVCO_INPUT(__VALUE__, __RANGE__) \ - ((((__RANGE__) == LL_RCC_PLLINPUTRANGE_1_2) && \ - (UTILS_PLLVCO_INPUT_MIN1 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX1)) || \ - (((__RANGE__) == LL_RCC_PLLINPUTRANGE_2_4) && \ - (UTILS_PLLVCO_INPUT_MIN2 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX2)) || \ - (((__RANGE__) == LL_RCC_PLLINPUTRANGE_4_8) && \ - (UTILS_PLLVCO_INPUT_MIN3 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX3)) || \ - (((__RANGE__) == LL_RCC_PLLINPUTRANGE_8_16) && \ - (UTILS_PLLVCO_INPUT_MIN4 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX4))) - -#define IS_LL_UTILS_PLLVCO_OUTPUT(__VALUE__, __RANGE__) \ - ((((__RANGE__) == LL_RCC_PLLVCORANGE_MEDIUM) && \ - (UTILS_PLLVCO_MEDIUM_OUTPUT_MIN <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_MEDIUM_OUTPUT_MAX)) || \ - (((__RANGE__) == LL_RCC_PLLVCORANGE_WIDE) && \ - (UTILS_PLLVCO_WIDE_OUTPUT_MIN <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_WIDE_OUTPUT_MAX))) - -#define IS_LL_UTILS_CHECK_VCO_RANGES(__RANGEIN__, __RANGEOUT__) \ - ((((__RANGEIN__) == LL_RCC_PLLINPUTRANGE_1_2) && \ - ((__RANGEOUT__) == LL_RCC_PLLVCORANGE_MEDIUM)) || \ - (((__RANGEIN__) != LL_RCC_PLLINPUTRANGE_1_2) && \ - ((__RANGEOUT__) == LL_RCC_PLLVCORANGE_WIDE))) - -#define IS_LL_UTILS_PLL_FREQUENCY(__VALUE__) \ - ((LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE0) ? \ - ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE0) : ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE1)) - -#define IS_LL_UTILS_HSE_BYPASS(__STATE__) \ - (((__STATE__) == LL_UTILS_HSEBYPASS_ON) || ((__STATE__) == LL_UTILS_HSEBYPASS_OFF)) - -#define IS_LL_UTILS_HSE_FREQUENCY(__FREQUENCY__) \ - (((__FREQUENCY__) >= UTILS_HSE_FREQUENCY_MIN) && ((__FREQUENCY__) <= UTILS_HSE_FREQUENCY_MAX)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup UTILS_LL_Private_Functions UTILS Private functions - * @{ - */ -static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, - const LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct); -static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, - LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct); -static ErrorStatus UTILS_IsPLLsNotBusy(void); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup UTILS_LL_Exported_Functions - * @{ - */ - -/** @addtogroup UTILS_LL_EF_DELAY - * @{ - */ -/** - * @brief This function configures the Cortex-M SysTick source to have 1ms time base. - * @note When a RTOS is used, it is recommended to avoid changing the Systick - * configuration by calling this function, for a delay use rather osDelay RTOS service. - * @param CPU_Frequency Core frequency in Hz - * @note CPU_Frequency can be calculated thanks to RCC helper macro or function - * @ref LL_RCC_GetSystemClocksFreq - * @retval None - */ -void LL_Init1msTick(uint32_t CPU_Frequency) -{ - /* Use frequency provided in argument */ - LL_InitTick(CPU_Frequency, 1000U); -} - - -/** - * @brief This function provides accurate delay (in milliseconds) based - * on SysTick counter flag - * @note When a RTOS is used, it is recommended to avoid using blocking delay - * and use rather osDelay service. - * @note To respect 1ms timebase, user should call @ref LL_Init1msTick function which - * will configure Systick to 1ms - * @param Delay specifies the delay time length, in milliseconds. - * @retval None - */ -void LL_mDelay(uint32_t Delay) -{ - uint32_t count = Delay; - __IO uint32_t tmp = SysTick->CTRL; /* Clear the COUNTFLAG first */ - /* Add this code to indicate that local variable is not used */ - ((void)tmp); - - /* Add a period to ensure minimum wait */ - if (count < LL_MAX_DELAY) - { - count++; - } - - while (count != 0U) - { - if ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) != 0U) - { - count--; - } - } -} - -/** - * @} - */ - -/** @addtogroup UTILS_EF_SYSTEM - * @brief System Configuration functions - * - @verbatim - =============================================================================== - ##### System Configuration functions ##### - =============================================================================== - [..] - System, AXI, AHB and APB buses clocks configuration - - (+) The maximum frequency of the SYSCLK is 464 MHz and HCLK is 232 MHz. - (+) The maximum frequency of the PCLK1, PCLK2, PCLK4 and PCLK5 is 116 MHz. - @endverbatim - @internal - Depending on the device voltage range, the maximum frequency should be - adapted accordingly: - (++) +---------------------------------------------------------------------------+ - (++) | Wait states | AXI interface clock frequency (MHz) vs Vcore range | - (++) | |-----------------------------------------------------| - (++) | (Latency) | voltage scale 1 | voltage scale 0 | - (++) | | 1.15V - 1.26V | 1.26V - 1.40V | - (++) |---------------------|--------------------------|--------------------------| - (++) | 0WS (1 CPU cycle) | 0 < HCLK <= 36 | 0 < HCLK <= 40 | - (++) |---------------------|--------------------------|--------------------------| - (++) | 1WS (2 CPU cycles) | 36 < HCLK <= 72 | 40 < HCLK <= 80 | - (++) |---------------------|--------------------------|--------------------------| - (++) | 2WS (3 CPU cycles) | 72 < HCLK <= 108 | 80 < HCLK <= 120 | - (++) |---------------------|--------------------------|--------------------------| - (++) | 3WS (4 CPU cycles) | 108 < HCLK <= 144 | 120 < HCLK <= 160 | - (++) |---------------------|--------------------------|--------------------------| - (++) | 4WS (5 CPU cycles) | 144 < HCLK <= 180 | 160 < HCLK <= 200 | - (++) |---------------------|--------------------------|--------------------------| - (++) | 5WS (6 CPU cycles) | 180 < HCLK <= 216 | 200 < HCLK <= 240 | - (++) |---------------------|--------------------------|--------------------------| - (++) | 6WS (7 CPU cycles) | 216 < HCLK <= 252 | | - (++) |---------------------|--------------------------|--------------------------| - - @endinternal - * @{ - */ - -/** - * @brief This function sets directly SystemCoreClock CMSIS variable. - * @note Variable can be calculated also through SystemCoreClockUpdate function. - * @param CPU_Frequency Core frequency in Hz - * @note CPU_Frequency can be calculated thanks to RCC helper macro or function - * @ref LL_RCC_GetSystemClocksFreq - * @retval None - */ -void LL_SetSystemCoreClock(uint32_t CPU_Frequency) -{ - /* SYSCLK clock frequency */ - SystemCoreClock = CPU_Frequency; -} - -/** - * @brief This function configures system clock at maximum frequency with HSI as clock source of the PLL - * @note The application need to ensure that PLL is disabled. - * @note Function is based on the following formula: - * - PLL output frequency = (((HSI frequency / PLLM) * PLLN) / PLLP) - * - PLLM: ensure that the VCO input frequency ranges from 1 to 16 MHz (PLLVCO_input = HSI frequency / PLLM) - * - PLLN: ensure that the VCO output frequency is - * between 150 and 420 MHz (Medium) or - * between 400 to 1600 MHz (Wide) (PLLVCO_output = PLLVCO_input * PLLN) - * - PLLP: ensure that max frequency at 464 MHz is reached (PLLVCO_output / PLLP) - * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains - * the configuration information for the PLL. - * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains - * the configuration information for the BUS prescalers. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Max frequency configuration done - * - ERROR: Max frequency configuration not done - * - */ -ErrorStatus LL_PLL_ConfigSystemClock_HSI(LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, - LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) -{ - ErrorStatus status; -#ifdef USE_FULL_ASSERT - uint32_t vcoinput_freq; - uint32_t vcooutput_freq; -#endif /* USE_FULL_ASSERT */ - uint32_t pllfreq; - uint32_t hsi_clk; - - /* Check the parameters */ - assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); - assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); - assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); - assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); - - hsi_clk = (HSI_VALUE >> (LL_RCC_HSI_GetDivider() >> RCC_CR_HSIDIV_Pos)); - - /* Check VCO Input frequency */ -#ifdef USE_FULL_ASSERT - vcoinput_freq = hsi_clk / UTILS_PLLInitStruct->PLLM; - assert_param(IS_LL_UTILS_PLLVCO_INPUT(vcoinput_freq, UTILS_PLLInitStruct->VCO_Input)); -#endif /* USE_FULL_ASSERT */ - - /* Check VCO Output frequency */ -#ifdef USE_FULL_ASSERT - vcooutput_freq = LL_RCC_CalcPLLClockFreq(hsi_clk, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, - UTILS_PLLInitStruct->FRACN, 1UL); - assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(vcooutput_freq, UTILS_PLLInitStruct->VCO_Output)); -#endif /* USE_FULL_ASSERT */ - - /* Check VCO Input ranges */ - assert_param(IS_LL_UTILS_CHECK_VCO_RANGES(UTILS_PLLInitStruct->VCO_Input, UTILS_PLLInitStruct->VCO_Output)); - - /* Check that no PLL is enabled and thus ready for configuration */ - if (UTILS_IsPLLsNotBusy() == SUCCESS) - { - /* Calculate the new PLL output frequency */ - pllfreq = UTILS_GetPLLOutputFrequency(hsi_clk, UTILS_PLLInitStruct); - - /* Enable HSI if not enabled */ - if (LL_RCC_HSI_IsReady() != 1U) - { - LL_RCC_HSI_Enable(); - while (LL_RCC_HSI_IsReady() != 1U) - { - /* Wait for HSI ready */ - } - } - - /* Configure PLL */ - LL_RCC_PLL1FRACN_Disable(); - LL_RCC_PLL_SetSource(LL_RCC_PLLSOURCE_HSI); - LL_RCC_PLL1_SetVCOInputRange(UTILS_PLLInitStruct->VCO_Input); - LL_RCC_PLL1_SetVCOOutputRange(UTILS_PLLInitStruct->VCO_Output); - LL_RCC_PLL1_SetM(UTILS_PLLInitStruct->PLLM); - LL_RCC_PLL1_SetN(UTILS_PLLInitStruct->PLLN); - LL_RCC_PLL1_SetP(UTILS_PLLInitStruct->PLLP); - LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); - LL_RCC_PLL1FRACN_Enable(); - LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); - - /* Enable PLL and switch system clock to PLL */ - status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); - } - else - { - /* Current PLL configuration cannot be modified */ - status = ERROR; - } - - return status; -} - -/** - * @brief This function configures system clock at maximum frequency with CSI as clock source of the PLL - * @note The application need to ensure that PLL is disabled. - * @note Function is based on the following formula: - * - PLL output frequency = (((CSI frequency / PLLM) * PLLN) / PLLP) - * - PLLM: ensure that the VCO input frequency ranges from 1 to 4 MHz (PLLVCO_input = CSI frequency / PLLM) - * - PLLN: ensure that the VCO output frequency is - * between 150 and 420 MHz (Medium) or - * between 400 to 1600 MHz (Wide) (PLLVCO_output = PLLVCO_input * PLLN) - * - PLLP: ensure that max frequency at 464 MHz is reached (PLLVCO_output / PLLP) - * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains - * the configuration information for the PLL. - * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains - * the configuration information for the BUS prescalers. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Max frequency configuration done - * - ERROR: Max frequency configuration not done - * - */ -ErrorStatus LL_PLL_ConfigSystemClock_CSI(LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, - LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) -{ - ErrorStatus status; -#ifdef USE_FULL_ASSERT - uint32_t vcoinput_freq; - uint32_t vcooutput_freq; -#endif /* USE_FULL_ASSERT */ - uint32_t pllfreq; - - /* Check the parameters */ - assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); - assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); - assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); - assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); - - /* Check VCO Input frequency */ -#ifdef USE_FULL_ASSERT - vcoinput_freq = CSI_VALUE / UTILS_PLLInitStruct->PLLM; - assert_param(IS_LL_UTILS_PLLVCO_INPUT(vcoinput_freq, UTILS_PLLInitStruct->VCO_Input)); -#endif /* USE_FULL_ASSERT */ - - /* Check VCO Output frequency */ -#ifdef USE_FULL_ASSERT - vcooutput_freq = LL_RCC_CalcPLLClockFreq(CSI_VALUE, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, - UTILS_PLLInitStruct->FRACN, 1UL); - assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(vcooutput_freq, UTILS_PLLInitStruct->VCO_Output)); -#endif /* USE_FULL_ASSERT */ - - /* Check VCO Input ranges */ - assert_param(IS_LL_UTILS_CHECK_VCO_RANGES(UTILS_PLLInitStruct->VCO_Input, UTILS_PLLInitStruct->VCO_Output)); - - /* Check that no PLL is enabled and thus ready for configuration */ - if (UTILS_IsPLLsNotBusy() == SUCCESS) - { - /* Calculate the new PLL output frequency */ - pllfreq = UTILS_GetPLLOutputFrequency(CSI_VALUE, UTILS_PLLInitStruct); - - /* Enable CSI if not enabled */ - if (LL_RCC_CSI_IsReady() != 1U) - { - LL_RCC_CSI_Enable(); - while (LL_RCC_CSI_IsReady() != 1U) - { - /* Wait for CSI ready */ - } - } - - /* Configure PLL */ - LL_RCC_PLL1FRACN_Disable(); - LL_RCC_PLL_SetSource(LL_RCC_PLLSOURCE_CSI); - LL_RCC_PLL1_SetVCOInputRange(UTILS_PLLInitStruct->VCO_Input); - LL_RCC_PLL1_SetVCOOutputRange(UTILS_PLLInitStruct->VCO_Output); - LL_RCC_PLL1_SetM(UTILS_PLLInitStruct->PLLM); - LL_RCC_PLL1_SetN(UTILS_PLLInitStruct->PLLN); - LL_RCC_PLL1_SetP(UTILS_PLLInitStruct->PLLP); - LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); - LL_RCC_PLL1FRACN_Enable(); - LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); - - /* Enable PLL and switch system clock to PLL */ - status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); - } - else - { - /* Current PLL configuration cannot be modified */ - status = ERROR; - } - - return status; -} - -/** - * @brief This function configures system clock with HSE as clock source of the PLL - * @note The application need to ensure that PLL is disabled. - * @note Function is based on the following formula: - * - PLL output frequency = (((HSE frequency / PLLM) * PLLN) / PLLP) - * - PLLM: ensure that the VCO input frequency ranges from 1 to 4 MHz (PLLVCO_input = CSI frequency / PLLM) - * - PLLN: ensure that the VCO output frequency is - * between 150 and 420 MHz (Medium) or - * between 400 to 1600 MHz (Wide) (PLLVCO_output = PLLVCO_input * PLLN) - * - PLLP: ensure that max frequency at 464 MHz is reached (PLLVCO_output / PLLP) - * @param HSEFrequency Value between Min_Data = 4000000 and Max_Data = 50000000 - * @param HSEBypass This parameter can be one of the following values: - * @arg @ref LL_UTILS_HSEBYPASS_ON - * @arg @ref LL_UTILS_HSEBYPASS_OFF - * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains - * the configuration information for the PLL. - * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains - * the configuration information for the BUS prescalers. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Max frequency configuration done - * - ERROR: Max frequency configuration not done - * - */ -ErrorStatus LL_PLL_ConfigSystemClock_HSE(uint32_t HSEFrequency, uint32_t HSEBypass, - LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, - LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) -{ - ErrorStatus status; -#ifdef USE_FULL_ASSERT - uint32_t vcoinput_freq; - uint32_t vcooutput_freq; -#endif /* USE_FULL_ASSERT */ - uint32_t pllfreq; - - /* Check the parameters */ - assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); - assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); - assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); - assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); - assert_param(IS_LL_UTILS_HSE_FREQUENCY(HSEFrequency)); - assert_param(IS_LL_UTILS_HSE_BYPASS(HSEBypass)); - - /* Check VCO Input frequency */ -#ifdef USE_FULL_ASSERT - vcoinput_freq = HSEFrequency / UTILS_PLLInitStruct->PLLM; - assert_param(IS_LL_UTILS_PLLVCO_INPUT(vcoinput_freq, UTILS_PLLInitStruct->VCO_Input)); -#endif /* USE_FULL_ASSERT */ - - /* Check VCO output frequency */ -#ifdef USE_FULL_ASSERT - vcooutput_freq = LL_RCC_CalcPLLClockFreq(HSEFrequency, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, - UTILS_PLLInitStruct->FRACN, 1U); - assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(vcooutput_freq, UTILS_PLLInitStruct->VCO_Output)); -#endif /* USE_FULL_ASSERT */ - - /* Check VCO Input/output ranges compatibility */ - assert_param(IS_LL_UTILS_CHECK_VCO_RANGES(UTILS_PLLInitStruct->VCO_Input, UTILS_PLLInitStruct->VCO_Output)); - - /* Check that no PLL is enabled and thus ready for configuration */ - if (UTILS_IsPLLsNotBusy() == SUCCESS) - { - /* Calculate the new PLL output frequency */ - pllfreq = UTILS_GetPLLOutputFrequency(HSEFrequency, UTILS_PLLInitStruct); - - /* Enable HSE if not enabled */ - if (LL_RCC_HSE_IsReady() != 1U) - { - /* Check if need to enable HSE bypass feature or not */ - if (HSEBypass == LL_UTILS_HSEBYPASS_ON) - { - LL_RCC_HSE_EnableBypass(); - } - else - { - LL_RCC_HSE_DisableBypass(); - } - - /* Enable HSE */ - LL_RCC_HSE_Enable(); - while (LL_RCC_HSE_IsReady() != 1U) - { - /* Wait for HSE ready */ - } - } - - /* Configure PLL */ - LL_RCC_PLL1FRACN_Disable(); - LL_RCC_PLL_SetSource(LL_RCC_PLLSOURCE_HSE); - LL_RCC_PLL1_SetVCOInputRange(UTILS_PLLInitStruct->VCO_Input); - LL_RCC_PLL1_SetVCOOutputRange(UTILS_PLLInitStruct->VCO_Output); - LL_RCC_PLL1_SetM(UTILS_PLLInitStruct->PLLM); - LL_RCC_PLL1_SetN(UTILS_PLLInitStruct->PLLN); - LL_RCC_PLL1_SetP(UTILS_PLLInitStruct->PLLP); - LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); - LL_RCC_PLL1FRACN_Enable(); - LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); - LL_RCC_PLL1FRACN_Enable(); - - /* Enable PLL and switch system clock to PLL */ - status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); - } - else - { - /* Current PLL configuration cannot be modified */ - status = ERROR; - } - - return status; -} - -/** - * @} - */ - -/** - * @brief Update number of Flash wait states in line with new frequency and current - voltage range. - * @param HCLK_Frequency HCLK frequency - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Latency has been modified - * - ERROR: Latency cannot be modified - */ -ErrorStatus LL_SetFlashLatency(uint32_t HCLK_Frequency) -{ - ErrorStatus status = SUCCESS; - uint32_t timeout; - uint32_t getlatency; - uint32_t latency; - - /* Frequency cannot be equal to 0 */ - if (HCLK_Frequency == 0U) - { - status = ERROR; - } - else - { - if (LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE0) /* Scale 0 */ - { - if ((HCLK_Frequency > UTILS_SCALE0_LATENCY4_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY5_FREQ)) - { - latency = LL_FLASH_LATENCY_5; /* 5WS (6 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY3_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY4_FREQ)) - { - latency = LL_FLASH_LATENCY_4; /* 4WS (5 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY2_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY3_FREQ)) - { - latency = LL_FLASH_LATENCY_3; /* 3WS (4 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY1_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY2_FREQ)) - { - latency = LL_FLASH_LATENCY_2; /* 2WS (3 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY0_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY1_FREQ)) - { - latency = LL_FLASH_LATENCY_1; /* 1WS (2 CPU cycles) */ - } - else - { - latency = LL_FLASH_LATENCY_0; /* 0WS (1 CPU cycles) */ - } - } - else /* Scale 1 */ - { - if ((HCLK_Frequency > UTILS_SCALE1_LATENCY4_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY5_FREQ)) - { - latency = LL_FLASH_LATENCY_5; /* 5WS (6 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY3_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY4_FREQ)) - { - latency = LL_FLASH_LATENCY_4; /* 4WS (5 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY2_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY3_FREQ)) - { - latency = LL_FLASH_LATENCY_3; /* 3WS (4 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY1_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY2_FREQ)) - { - latency = LL_FLASH_LATENCY_2; /* 2WS (3 CPU cycles) */ - } - else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY0_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY1_FREQ)) - { - latency = LL_FLASH_LATENCY_1; /* 1WS (2 CPU cycles) */ - } - else - { - latency = LL_FLASH_LATENCY_0; /* 0WS (1 CPU cycles) */ - } - } - - LL_FLASH_SetLatency(latency); - - /* Check that the new number of wait states is taken into account to access the Flash - memory by reading the FLASH_ACR register */ - timeout = 2; - do - { - /* Wait for Flash latency to be updated */ - getlatency = LL_FLASH_GetLatency(); - timeout--; - } while ((getlatency != latency) && (timeout > 0U)); - - if (getlatency != latency) - { - status = ERROR; - } - } - - return status; -} - - -/** - * @} - */ - -/** @addtogroup UTILS_LL_Private_Functions - * @{ - */ - - -/** - * @brief Function to Get PLL Output frequency - * @param PLL_InputFrequency PLL input frequency (in Hz) - * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains - * the configuration information for the PLL. - * @retval PLL output frequency (in Hz) - */ -static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, - const LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct) -{ - uint32_t pllfreq; - - /* Check the parameters */ - assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); - assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); - assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); - assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); - - pllfreq = LL_RCC_CalcPLLClockFreq(PLL_InputFrequency, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, - UTILS_PLLInitStruct->FRACN, UTILS_PLLInitStruct->PLLP); - - return pllfreq; -} - -/** - * @brief Check that all PLLs are not busy therefore configuration can be done - * @retval An ErrorStatus enumeration value: - * - SUCCESS: All PLLs are ready so configuration can be done - * - ERROR: One PLL at least is busy - */ -static ErrorStatus UTILS_IsPLLsNotBusy(void) -{ - ErrorStatus status = SUCCESS; - - /* Check if one of the PLL1 is busy */ - if (LL_RCC_PLL1_IsReady() != 0U) - { - /* PLL1 configuration cannot be done */ - status = ERROR; - } - - /* Check if one of the PLL2 is busy */ - if (LL_RCC_PLL2_IsReady() != 0U) - { - /* PLL2 configuration cannot be done */ - status = ERROR; - } - - /* Check if one of the PLL3 is busy */ - if (LL_RCC_PLL3_IsReady() != 0U) - { - /* PLL3 configuration cannot be done */ - status = ERROR; - } - - return status; -} - -/** - * @brief Function to enable PLL and switch system clock to PLL - * @param SYSCLK_Frequency SYSCLK frequency - * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains - * the configuration information for the BUS prescalers. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: No problem to switch system to PLL - * - ERROR: Problem to switch system to PLL - */ -static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, - LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) -{ - ErrorStatus status = SUCCESS; - uint32_t new_sysclk_frequency; - uint32_t new_hclk_frequency; - - assert_param(IS_LL_UTILS_SYSCLK_DIV(UTILS_ClkInitStruct->SYSCLKDivider)); - assert_param(IS_LL_UTILS_AHB_DIV(UTILS_ClkInitStruct->AHBCLKDivider)); - assert_param(IS_LL_UTILS_APB1_DIV(UTILS_ClkInitStruct->APB1CLKDivider)); - assert_param(IS_LL_UTILS_APB2_DIV(UTILS_ClkInitStruct->APB2CLKDivider)); - assert_param(IS_LL_UTILS_APB4_DIV(UTILS_ClkInitStruct->APB4CLKDivider)); - assert_param(IS_LL_UTILS_APB5_DIV(UTILS_ClkInitStruct->APB5CLKDivider)); - - /* Calculate the new HCLK frequency */ - new_sysclk_frequency = LL_RCC_CALC_SYSCLK_FREQ(SYSCLK_Frequency, UTILS_ClkInitStruct->SYSCLKDivider); - new_hclk_frequency = LL_RCC_CALC_HCLK_FREQ(new_sysclk_frequency, UTILS_ClkInitStruct->AHBCLKDivider); - - /* Increasing the number of wait states because of higher CPU frequency */ - if (SystemCoreClock < new_sysclk_frequency) - { - /* Set FLASH latency to highest latency */ - status = LL_SetFlashLatency(new_hclk_frequency); - } - - /* Update system clock configuration */ - if (status == SUCCESS) - { - /* Enable PLL */ - LL_RCC_PLL1_Enable(); - while (LL_RCC_PLL1_IsReady() != 1U) - { - /* Wait for PLL ready */ - } - - LL_RCC_PLL1P_Enable(); - - /* Set All APBxPrescaler to the Highest Divider */ - LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_16); - LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_16); - LL_RCC_SetAPB4Prescaler(LL_RCC_APB4_DIV_16); - LL_RCC_SetAPB5Prescaler(LL_RCC_APB5_DIV_16); - - /* Set SYS prescaler*/ - LL_RCC_SetSysPrescaler(UTILS_ClkInitStruct->SYSCLKDivider); - - /* Set AHB prescaler*/ - LL_RCC_SetAHBPrescaler(UTILS_ClkInitStruct->AHBCLKDivider); - - /* Sysclk activation on the main PLL */ - LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL1); - while (LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL1) - { - /* Wait for system clock switch to PLL */ - } - - /* Set APBn prescaler*/ - LL_RCC_SetAPB1Prescaler(UTILS_ClkInitStruct->APB1CLKDivider); - LL_RCC_SetAPB2Prescaler(UTILS_ClkInitStruct->APB2CLKDivider); - LL_RCC_SetAPB4Prescaler(UTILS_ClkInitStruct->APB4CLKDivider); - LL_RCC_SetAPB5Prescaler(UTILS_ClkInitStruct->APB5CLKDivider); - - /* Decreasing the number of wait states because of lower CPU frequency */ - if (SystemCoreClock > new_sysclk_frequency) - { - /* Set FLASH latency to lowest latency */ - status = LL_SetFlashLatency(new_hclk_frequency); - } - - /* Update SystemCoreClock variable */ - if (status == SUCCESS) - { - LL_SetSystemCoreClock(new_sysclk_frequency); - } - } - - return status; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file stm32h7rsxx_ll_utils.c + * @author MCD Application Team + * @brief UTILS LL module driver. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7rsxx_ll_utils.h" +#include "stm32h7rsxx_ll_rcc.h" +#include "stm32h7rsxx_ll_pwr.h" + +#ifdef USE_FULL_ASSERT +#include "stm32_assert.h" +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +/** @addtogroup STM32H7RSxx_LL_Driver + * @{ + */ + +/** @addtogroup UTILS_LL + * @{ + */ + +/* Private types -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private constants ---------------------------------------------------------*/ +/** @addtogroup UTILS_LL_Private_Constants + * @{ + */ +#define UTILS_MAX_FREQUENCY_SCALE0 467000000U /*!< Maximum frequency for system clock at power scale 0, in Hz */ +#define UTILS_MAX_FREQUENCY_SCALE1 365000000U /*!< Maximum frequency for system clock at power scale 1, in Hz */ + +/* Defines used for PLL range */ +#define UTILS_PLLVCO_INPUT_MIN1 1000000U /*!< Frequency min for the medium range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MAX1 2000000U /*!< Frequency max for the medium range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MIN2 2000000U /*!< Frequency min for the wide range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MAX2 4000000U /*!< Frequency max for the wide range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MIN3 4000000U /*!< Frequency min for the wide range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MAX3 8000000U /*!< Frequency max for the wide range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MIN4 8000000U /*!< Frequency min for the wide range PLLVCO input, in Hz */ +#define UTILS_PLLVCO_INPUT_MAX4 16000000U /*!< Frequency max for the wide range PLLVCO input, in Hz */ + +#define UTILS_PLLVCO_MEDIUM_OUTPUT_MIN 150000000U /*!< Frequency min for the medium range PLLVCO output, in Hz */ +#define UTILS_PLLVCO_WIDE_OUTPUT_MIN 400000000U /*!< Frequency min for the wide range PLLVCO output, in Hz */ +#define UTILS_PLLVCO_MEDIUM_OUTPUT_MAX 420000000U /*!< Frequency max for the medium range PLLVCO output, in Hz */ +#define UTILS_PLLVCO_WIDE_OUTPUT_MAX 1600000000U /*!< Frequency max for the wide range PLLVCO output, in Hz */ + +/* Defines used for HSE range */ +#define UTILS_HSE_FREQUENCY_MIN 4000000U /*!< Frequency min for HSE frequency, in Hz */ +#define UTILS_HSE_FREQUENCY_MAX 50000000U /*!< Frequency max for HSE frequency, in Hz */ + +/* Defines used for FLASH latency according to HCLK Frequency at */ +/* VOS0 (highest power/frequency) or VOS1 (lowest power/frequency) */ +#define UTILS_SCALE0_LATENCY0_FREQ 40000000U /*!< HCLK frequency to set FLASH latency 0 in power scale 0 */ +#define UTILS_SCALE0_LATENCY1_FREQ 80000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 0 */ +#define UTILS_SCALE0_LATENCY2_FREQ 120000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 0 */ +#define UTILS_SCALE0_LATENCY3_FREQ 160000000U /*!< HCLK frequency to set FLASH latency 3 in power scale 0 */ +#define UTILS_SCALE0_LATENCY4_FREQ 200000000U /*!< HCLK frequency to set FLASH latency 4 in power scale 0 */ +#define UTILS_SCALE0_LATENCY5_FREQ 234000000U /*!< HCLK frequency to set FLASH latency 5 in power scale 0 */ + +#define UTILS_SCALE1_LATENCY0_FREQ 36000000U /*!< HCLK frequency to set FLASH latency 0 in power scale 1 */ +#define UTILS_SCALE1_LATENCY1_FREQ 72000000U /*!< HCLK frequency to set FLASH latency 1 in power scale 1 */ +#define UTILS_SCALE1_LATENCY2_FREQ 108000000U /*!< HCLK frequency to set FLASH latency 2 in power scale 1 */ +#define UTILS_SCALE1_LATENCY3_FREQ 144000000U /*!< HCLK frequency to set FLASH latency 3 in power scale 1 */ +#define UTILS_SCALE1_LATENCY4_FREQ 180000000U /*!< HCLK frequency to set FLASH latency 4 in power scale 1 */ +#define UTILS_SCALE1_LATENCY5_FREQ 183000000U /*!< HCLK frequency to set FLASH latency 5 in power scale 1 */ +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/** @addtogroup UTILS_LL_Private_Macros + * @{ + */ +#define IS_LL_UTILS_SYSCLK_DIV(__VALUE__) (((__VALUE__) == LL_RCC_SYSCLK_DIV_1) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_2) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_4) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_8) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_16) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_64) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_128) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_256) \ + || ((__VALUE__) == LL_RCC_SYSCLK_DIV_512)) + +#define IS_LL_UTILS_AHB_DIV(__VALUE__) (((__VALUE__) == LL_RCC_AHB_DIV_1) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_2) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_4) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_8) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_16) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_64) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_128) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_256) \ + || ((__VALUE__) == LL_RCC_AHB_DIV_512)) + +#define IS_LL_UTILS_APB1_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB1_DIV_1) \ + || ((__VALUE__) == LL_RCC_APB1_DIV_2) \ + || ((__VALUE__) == LL_RCC_APB1_DIV_4) \ + || ((__VALUE__) == LL_RCC_APB1_DIV_8) \ + || ((__VALUE__) == LL_RCC_APB1_DIV_16)) + +#define IS_LL_UTILS_APB2_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB2_DIV_1) \ + || ((__VALUE__) == LL_RCC_APB2_DIV_2) \ + || ((__VALUE__) == LL_RCC_APB2_DIV_4) \ + || ((__VALUE__) == LL_RCC_APB2_DIV_8) \ + || ((__VALUE__) == LL_RCC_APB2_DIV_16)) + +#define IS_LL_UTILS_APB4_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB4_DIV_1) \ + || ((__VALUE__) == LL_RCC_APB4_DIV_2) \ + || ((__VALUE__) == LL_RCC_APB4_DIV_4) \ + || ((__VALUE__) == LL_RCC_APB4_DIV_8) \ + || ((__VALUE__) == LL_RCC_APB4_DIV_16)) + +#define IS_LL_UTILS_APB5_DIV(__VALUE__) (((__VALUE__) == LL_RCC_APB5_DIV_1) \ + || ((__VALUE__) == LL_RCC_APB5_DIV_2) \ + || ((__VALUE__) == LL_RCC_APB5_DIV_4) \ + || ((__VALUE__) == LL_RCC_APB5_DIV_8) \ + || ((__VALUE__) == LL_RCC_APB5_DIV_16)) + +#define IS_LL_UTILS_PLLM_VALUE(__VALUE__) ((1U <= (__VALUE__)) && ((__VALUE__) <= 63U)) + +#define IS_LL_UTILS_PLLN_VALUE(__VALUE__) ((8U <= (__VALUE__)) && ((__VALUE__) <= 420U)) + +#define IS_LL_UTILS_PLLP_VALUE(__VALUE__) ((1U <= (__VALUE__)) && ((__VALUE__) <= 128U)) + +#define IS_LL_UTILS_FRACN_VALUE(__VALUE__) ((__VALUE__) <= 0x1FFFU) + +#define IS_LL_UTILS_PLLVCO_INPUT(__VALUE__, __RANGE__) \ + ((((__RANGE__) == LL_RCC_PLLINPUTRANGE_1_2) && \ + (UTILS_PLLVCO_INPUT_MIN1 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX1)) || \ + (((__RANGE__) == LL_RCC_PLLINPUTRANGE_2_4) && \ + (UTILS_PLLVCO_INPUT_MIN2 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX2)) || \ + (((__RANGE__) == LL_RCC_PLLINPUTRANGE_4_8) && \ + (UTILS_PLLVCO_INPUT_MIN3 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX3)) || \ + (((__RANGE__) == LL_RCC_PLLINPUTRANGE_8_16) && \ + (UTILS_PLLVCO_INPUT_MIN4 <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_INPUT_MAX4))) + +#define IS_LL_UTILS_PLLVCO_OUTPUT(__VALUE__, __RANGE__) \ + ((((__RANGE__) == LL_RCC_PLLVCORANGE_MEDIUM) && \ + (UTILS_PLLVCO_MEDIUM_OUTPUT_MIN <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_MEDIUM_OUTPUT_MAX)) || \ + (((__RANGE__) == LL_RCC_PLLVCORANGE_WIDE) && \ + (UTILS_PLLVCO_WIDE_OUTPUT_MIN <= (__VALUE__)) && ((__VALUE__) <= UTILS_PLLVCO_WIDE_OUTPUT_MAX))) + +#define IS_LL_UTILS_CHECK_VCO_RANGES(__RANGEIN__, __RANGEOUT__) \ + ((((__RANGEIN__) == LL_RCC_PLLINPUTRANGE_1_2) && \ + ((__RANGEOUT__) == LL_RCC_PLLVCORANGE_MEDIUM)) || \ + (((__RANGEIN__) != LL_RCC_PLLINPUTRANGE_1_2) && \ + ((__RANGEOUT__) == LL_RCC_PLLVCORANGE_WIDE))) + +#define IS_LL_UTILS_PLL_FREQUENCY(__VALUE__) \ + ((LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE0) ? \ + ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE0) : ((__VALUE__) <= UTILS_MAX_FREQUENCY_SCALE1)) + +#define IS_LL_UTILS_HSE_BYPASS(__STATE__) \ + (((__STATE__) == LL_UTILS_HSEBYPASS_ON) || ((__STATE__) == LL_UTILS_HSEBYPASS_OFF)) + +#define IS_LL_UTILS_HSE_FREQUENCY(__FREQUENCY__) \ + (((__FREQUENCY__) >= UTILS_HSE_FREQUENCY_MIN) && ((__FREQUENCY__) <= UTILS_HSE_FREQUENCY_MAX)) +/** + * @} + */ + +/* Private function prototypes -----------------------------------------------*/ +/** @defgroup UTILS_LL_Private_Functions UTILS Private functions + * @{ + */ +static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, + const LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct); +static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, + LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct); +static ErrorStatus UTILS_IsPLLsNotBusy(void); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup UTILS_LL_Exported_Functions + * @{ + */ + +/** @addtogroup UTILS_LL_EF_DELAY + * @{ + */ +/** + * @brief This function configures the Cortex-M SysTick source to have 1ms time base. + * @note When a RTOS is used, it is recommended to avoid changing the Systick + * configuration by calling this function, for a delay use rather osDelay RTOS service. + * @param CPU_Frequency Core frequency in Hz + * @note CPU_Frequency can be calculated thanks to RCC helper macro or function + * @ref LL_RCC_GetSystemClocksFreq + * @retval None + */ +void LL_Init1msTick(uint32_t CPU_Frequency) +{ + /* Use frequency provided in argument */ + LL_InitTick(CPU_Frequency, 1000U); +} + + +/** + * @brief This function provides accurate delay (in milliseconds) based + * on SysTick counter flag + * @note When a RTOS is used, it is recommended to avoid using blocking delay + * and use rather osDelay service. + * @note To respect 1ms timebase, user should call @ref LL_Init1msTick function which + * will configure Systick to 1ms + * @param Delay specifies the delay time length, in milliseconds. + * @retval None + */ +void LL_mDelay(uint32_t Delay) +{ + uint32_t count = Delay; + __IO uint32_t tmp = SysTick->CTRL; /* Clear the COUNTFLAG first */ + /* Add this code to indicate that local variable is not used */ + ((void)tmp); + + /* Add a period to ensure minimum wait */ + if (count < LL_MAX_DELAY) + { + count++; + } + + while (count != 0U) + { + if ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) != 0U) + { + count--; + } + } +} + +/** + * @} + */ + +/** @addtogroup UTILS_EF_SYSTEM + * @brief System Configuration functions + * + @verbatim + =============================================================================== + ##### System Configuration functions ##### + =============================================================================== + [..] + System, AXI, AHB and APB buses clocks configuration + + (+) The maximum frequency of the SYSCLK is 464 MHz and HCLK is 232 MHz. + (+) The maximum frequency of the PCLK1, PCLK2, PCLK4 and PCLK5 is 116 MHz. + @endverbatim + @internal + Depending on the device voltage range, the maximum frequency should be + adapted accordingly: + (++) +---------------------------------------------------------------------------+ + (++) | Wait states | AXI interface clock frequency (MHz) vs Vcore range | + (++) | |-----------------------------------------------------| + (++) | (Latency) | voltage scale 1 | voltage scale 0 | + (++) | | 1.15V - 1.26V | 1.26V - 1.40V | + (++) |---------------------|--------------------------|--------------------------| + (++) | 0WS (1 CPU cycle) | 0 < HCLK <= 36 | 0 < HCLK <= 40 | + (++) |---------------------|--------------------------|--------------------------| + (++) | 1WS (2 CPU cycles) | 36 < HCLK <= 72 | 40 < HCLK <= 80 | + (++) |---------------------|--------------------------|--------------------------| + (++) | 2WS (3 CPU cycles) | 72 < HCLK <= 108 | 80 < HCLK <= 120 | + (++) |---------------------|--------------------------|--------------------------| + (++) | 3WS (4 CPU cycles) | 108 < HCLK <= 144 | 120 < HCLK <= 160 | + (++) |---------------------|--------------------------|--------------------------| + (++) | 4WS (5 CPU cycles) | 144 < HCLK <= 180 | 160 < HCLK <= 200 | + (++) |---------------------|--------------------------|--------------------------| + (++) | 5WS (6 CPU cycles) | 180 < HCLK <= 216 | 200 < HCLK <= 240 | + (++) |---------------------|--------------------------|--------------------------| + (++) | 6WS (7 CPU cycles) | 216 < HCLK <= 252 | | + (++) |---------------------|--------------------------|--------------------------| + + @endinternal + * @{ + */ + +/** + * @brief This function sets directly SystemCoreClock CMSIS variable. + * @note Variable can be calculated also through SystemCoreClockUpdate function. + * @param CPU_Frequency Core frequency in Hz + * @note CPU_Frequency can be calculated thanks to RCC helper macro or function + * @ref LL_RCC_GetSystemClocksFreq + * @retval None + */ +void LL_SetSystemCoreClock(uint32_t CPU_Frequency) +{ + /* SYSCLK clock frequency */ + SystemCoreClock = CPU_Frequency; +} + +/** + * @brief This function configures system clock at maximum frequency with HSI as clock source of the PLL + * @note The application need to ensure that PLL is disabled. + * @note Function is based on the following formula: + * - PLL output frequency = (((HSI frequency / PLLM) * PLLN) / PLLP) + * - PLLM: ensure that the VCO input frequency ranges from 1 to 16 MHz (PLLVCO_input = HSI frequency / PLLM) + * - PLLN: ensure that the VCO output frequency is + * between 150 and 420 MHz (Medium) or + * between 400 to 1600 MHz (Wide) (PLLVCO_output = PLLVCO_input * PLLN) + * - PLLP: ensure that max frequency at 464 MHz is reached (PLLVCO_output / PLLP) + * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Max frequency configuration done + * - ERROR: Max frequency configuration not done + * + */ +ErrorStatus LL_PLL_ConfigSystemClock_HSI(LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, + LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status; +#ifdef USE_FULL_ASSERT + uint32_t vcoinput_freq; + uint32_t vcooutput_freq; +#endif /* USE_FULL_ASSERT */ + uint32_t pllfreq; + uint32_t hsi_clk; + + /* Check the parameters */ + assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); + assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); + assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); + assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); + + hsi_clk = (HSI_VALUE >> (LL_RCC_HSI_GetDivider() >> RCC_CR_HSIDIV_Pos)); + + /* Check VCO Input frequency */ +#ifdef USE_FULL_ASSERT + vcoinput_freq = hsi_clk / UTILS_PLLInitStruct->PLLM; + assert_param(IS_LL_UTILS_PLLVCO_INPUT(vcoinput_freq, UTILS_PLLInitStruct->VCO_Input)); +#endif /* USE_FULL_ASSERT */ + + /* Check VCO Output frequency */ +#ifdef USE_FULL_ASSERT + vcooutput_freq = LL_RCC_CalcPLLClockFreq(hsi_clk, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, + UTILS_PLLInitStruct->FRACN, 1UL); + assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(vcooutput_freq, UTILS_PLLInitStruct->VCO_Output)); +#endif /* USE_FULL_ASSERT */ + + /* Check VCO Input ranges */ + assert_param(IS_LL_UTILS_CHECK_VCO_RANGES(UTILS_PLLInitStruct->VCO_Input, UTILS_PLLInitStruct->VCO_Output)); + + /* Check that no PLL is enabled and thus ready for configuration */ + if (UTILS_IsPLLsNotBusy() == SUCCESS) + { + /* Calculate the new PLL output frequency */ + pllfreq = UTILS_GetPLLOutputFrequency(hsi_clk, UTILS_PLLInitStruct); + + /* Enable HSI if not enabled */ + if (LL_RCC_HSI_IsReady() != 1U) + { + LL_RCC_HSI_Enable(); + while (LL_RCC_HSI_IsReady() != 1U) + { + /* Wait for HSI ready */ + } + } + + /* Configure PLL */ + LL_RCC_PLL1FRACN_Disable(); + LL_RCC_PLL_SetSource(LL_RCC_PLLSOURCE_HSI); + LL_RCC_PLL1_SetVCOInputRange(UTILS_PLLInitStruct->VCO_Input); + LL_RCC_PLL1_SetVCOOutputRange(UTILS_PLLInitStruct->VCO_Output); + LL_RCC_PLL1_SetM(UTILS_PLLInitStruct->PLLM); + LL_RCC_PLL1_SetN(UTILS_PLLInitStruct->PLLN); + LL_RCC_PLL1_SetP(UTILS_PLLInitStruct->PLLP); + LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); + LL_RCC_PLL1FRACN_Enable(); + LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); + + /* Enable PLL and switch system clock to PLL */ + status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); + } + else + { + /* Current PLL configuration cannot be modified */ + status = ERROR; + } + + return status; +} + +/** + * @brief This function configures system clock at maximum frequency with CSI as clock source of the PLL + * @note The application need to ensure that PLL is disabled. + * @note Function is based on the following formula: + * - PLL output frequency = (((CSI frequency / PLLM) * PLLN) / PLLP) + * - PLLM: ensure that the VCO input frequency ranges from 1 to 4 MHz (PLLVCO_input = CSI frequency / PLLM) + * - PLLN: ensure that the VCO output frequency is + * between 150 and 420 MHz (Medium) or + * between 400 to 1600 MHz (Wide) (PLLVCO_output = PLLVCO_input * PLLN) + * - PLLP: ensure that max frequency at 464 MHz is reached (PLLVCO_output / PLLP) + * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Max frequency configuration done + * - ERROR: Max frequency configuration not done + * + */ +ErrorStatus LL_PLL_ConfigSystemClock_CSI(LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, + LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status; +#ifdef USE_FULL_ASSERT + uint32_t vcoinput_freq; + uint32_t vcooutput_freq; +#endif /* USE_FULL_ASSERT */ + uint32_t pllfreq; + + /* Check the parameters */ + assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); + assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); + assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); + assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); + + /* Check VCO Input frequency */ +#ifdef USE_FULL_ASSERT + vcoinput_freq = CSI_VALUE / UTILS_PLLInitStruct->PLLM; + assert_param(IS_LL_UTILS_PLLVCO_INPUT(vcoinput_freq, UTILS_PLLInitStruct->VCO_Input)); +#endif /* USE_FULL_ASSERT */ + + /* Check VCO Output frequency */ +#ifdef USE_FULL_ASSERT + vcooutput_freq = LL_RCC_CalcPLLClockFreq(CSI_VALUE, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, + UTILS_PLLInitStruct->FRACN, 1UL); + assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(vcooutput_freq, UTILS_PLLInitStruct->VCO_Output)); +#endif /* USE_FULL_ASSERT */ + + /* Check VCO Input ranges */ + assert_param(IS_LL_UTILS_CHECK_VCO_RANGES(UTILS_PLLInitStruct->VCO_Input, UTILS_PLLInitStruct->VCO_Output)); + + /* Check that no PLL is enabled and thus ready for configuration */ + if (UTILS_IsPLLsNotBusy() == SUCCESS) + { + /* Calculate the new PLL output frequency */ + pllfreq = UTILS_GetPLLOutputFrequency(CSI_VALUE, UTILS_PLLInitStruct); + + /* Enable CSI if not enabled */ + if (LL_RCC_CSI_IsReady() != 1U) + { + LL_RCC_CSI_Enable(); + while (LL_RCC_CSI_IsReady() != 1U) + { + /* Wait for CSI ready */ + } + } + + /* Configure PLL */ + LL_RCC_PLL1FRACN_Disable(); + LL_RCC_PLL_SetSource(LL_RCC_PLLSOURCE_CSI); + LL_RCC_PLL1_SetVCOInputRange(UTILS_PLLInitStruct->VCO_Input); + LL_RCC_PLL1_SetVCOOutputRange(UTILS_PLLInitStruct->VCO_Output); + LL_RCC_PLL1_SetM(UTILS_PLLInitStruct->PLLM); + LL_RCC_PLL1_SetN(UTILS_PLLInitStruct->PLLN); + LL_RCC_PLL1_SetP(UTILS_PLLInitStruct->PLLP); + LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); + LL_RCC_PLL1FRACN_Enable(); + LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); + + /* Enable PLL and switch system clock to PLL */ + status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); + } + else + { + /* Current PLL configuration cannot be modified */ + status = ERROR; + } + + return status; +} + +/** + * @brief This function configures system clock with HSE as clock source of the PLL + * @note The application need to ensure that PLL is disabled. + * @note Function is based on the following formula: + * - PLL output frequency = (((HSE frequency / PLLM) * PLLN) / PLLP) + * - PLLM: ensure that the VCO input frequency ranges from 1 to 4 MHz (PLLVCO_input = CSI frequency / PLLM) + * - PLLN: ensure that the VCO output frequency is + * between 150 and 420 MHz (Medium) or + * between 400 to 1600 MHz (Wide) (PLLVCO_output = PLLVCO_input * PLLN) + * - PLLP: ensure that max frequency at 464 MHz is reached (PLLVCO_output / PLLP) + * @param HSEFrequency Value between Min_Data = 4000000 and Max_Data = 50000000 + * @param HSEBypass This parameter can be one of the following values: + * @arg @ref LL_UTILS_HSEBYPASS_ON + * @arg @ref LL_UTILS_HSEBYPASS_OFF + * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Max frequency configuration done + * - ERROR: Max frequency configuration not done + * + */ +ErrorStatus LL_PLL_ConfigSystemClock_HSE(uint32_t HSEFrequency, uint32_t HSEBypass, + LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, + LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status; +#ifdef USE_FULL_ASSERT + uint32_t vcoinput_freq; + uint32_t vcooutput_freq; +#endif /* USE_FULL_ASSERT */ + uint32_t pllfreq; + + /* Check the parameters */ + assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); + assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); + assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); + assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); + assert_param(IS_LL_UTILS_HSE_FREQUENCY(HSEFrequency)); + assert_param(IS_LL_UTILS_HSE_BYPASS(HSEBypass)); + + /* Check VCO Input frequency */ +#ifdef USE_FULL_ASSERT + vcoinput_freq = HSEFrequency / UTILS_PLLInitStruct->PLLM; + assert_param(IS_LL_UTILS_PLLVCO_INPUT(vcoinput_freq, UTILS_PLLInitStruct->VCO_Input)); +#endif /* USE_FULL_ASSERT */ + + /* Check VCO output frequency */ +#ifdef USE_FULL_ASSERT + vcooutput_freq = LL_RCC_CalcPLLClockFreq(HSEFrequency, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, + UTILS_PLLInitStruct->FRACN, 1U); + assert_param(IS_LL_UTILS_PLLVCO_OUTPUT(vcooutput_freq, UTILS_PLLInitStruct->VCO_Output)); +#endif /* USE_FULL_ASSERT */ + + /* Check VCO Input/output ranges compatibility */ + assert_param(IS_LL_UTILS_CHECK_VCO_RANGES(UTILS_PLLInitStruct->VCO_Input, UTILS_PLLInitStruct->VCO_Output)); + + /* Check that no PLL is enabled and thus ready for configuration */ + if (UTILS_IsPLLsNotBusy() == SUCCESS) + { + /* Calculate the new PLL output frequency */ + pllfreq = UTILS_GetPLLOutputFrequency(HSEFrequency, UTILS_PLLInitStruct); + + /* Enable HSE if not enabled */ + if (LL_RCC_HSE_IsReady() != 1U) + { + /* Check if need to enable HSE bypass feature or not */ + if (HSEBypass == LL_UTILS_HSEBYPASS_ON) + { + LL_RCC_HSE_EnableBypass(); + } + else + { + LL_RCC_HSE_DisableBypass(); + } + + /* Enable HSE */ + LL_RCC_HSE_Enable(); + while (LL_RCC_HSE_IsReady() != 1U) + { + /* Wait for HSE ready */ + } + } + + /* Configure PLL */ + LL_RCC_PLL1FRACN_Disable(); + LL_RCC_PLL_SetSource(LL_RCC_PLLSOURCE_HSE); + LL_RCC_PLL1_SetVCOInputRange(UTILS_PLLInitStruct->VCO_Input); + LL_RCC_PLL1_SetVCOOutputRange(UTILS_PLLInitStruct->VCO_Output); + LL_RCC_PLL1_SetM(UTILS_PLLInitStruct->PLLM); + LL_RCC_PLL1_SetN(UTILS_PLLInitStruct->PLLN); + LL_RCC_PLL1_SetP(UTILS_PLLInitStruct->PLLP); + LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); + LL_RCC_PLL1FRACN_Enable(); + LL_RCC_PLL1_SetFRACN(UTILS_PLLInitStruct->FRACN); + LL_RCC_PLL1FRACN_Enable(); + + /* Enable PLL and switch system clock to PLL */ + status = UTILS_EnablePLLAndSwitchSystem(pllfreq, UTILS_ClkInitStruct); + } + else + { + /* Current PLL configuration cannot be modified */ + status = ERROR; + } + + return status; +} + +/** + * @} + */ + +/** + * @brief Update number of Flash wait states in line with new frequency and current + voltage range. + * @param HCLK_Frequency HCLK frequency + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Latency has been modified + * - ERROR: Latency cannot be modified + */ +ErrorStatus LL_SetFlashLatency(uint32_t HCLK_Frequency) +{ + ErrorStatus status = SUCCESS; + uint32_t timeout; + uint32_t getlatency; + uint32_t latency; + + /* Frequency cannot be equal to 0 */ + if (HCLK_Frequency == 0U) + { + status = ERROR; + } + else + { + if (LL_PWR_GetRegulVoltageScaling() == LL_PWR_REGU_VOLTAGE_SCALE0) /* Scale 0 */ + { + if ((HCLK_Frequency > UTILS_SCALE0_LATENCY4_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY5_FREQ)) + { + latency = LL_FLASH_LATENCY_5; /* 5WS (6 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY3_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY4_FREQ)) + { + latency = LL_FLASH_LATENCY_4; /* 4WS (5 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY2_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY3_FREQ)) + { + latency = LL_FLASH_LATENCY_3; /* 3WS (4 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY1_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY2_FREQ)) + { + latency = LL_FLASH_LATENCY_2; /* 2WS (3 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE0_LATENCY0_FREQ) && (HCLK_Frequency <= UTILS_SCALE0_LATENCY1_FREQ)) + { + latency = LL_FLASH_LATENCY_1; /* 1WS (2 CPU cycles) */ + } + else + { + latency = LL_FLASH_LATENCY_0; /* 0WS (1 CPU cycles) */ + } + } + else /* Scale 1 */ + { + if ((HCLK_Frequency > UTILS_SCALE1_LATENCY4_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY5_FREQ)) + { + latency = LL_FLASH_LATENCY_5; /* 5WS (6 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY3_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY4_FREQ)) + { + latency = LL_FLASH_LATENCY_4; /* 4WS (5 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY2_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY3_FREQ)) + { + latency = LL_FLASH_LATENCY_3; /* 3WS (4 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY1_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY2_FREQ)) + { + latency = LL_FLASH_LATENCY_2; /* 2WS (3 CPU cycles) */ + } + else if ((HCLK_Frequency > UTILS_SCALE1_LATENCY0_FREQ) && (HCLK_Frequency <= UTILS_SCALE1_LATENCY1_FREQ)) + { + latency = LL_FLASH_LATENCY_1; /* 1WS (2 CPU cycles) */ + } + else + { + latency = LL_FLASH_LATENCY_0; /* 0WS (1 CPU cycles) */ + } + } + + LL_FLASH_SetLatency(latency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACR register */ + timeout = 2; + do + { + /* Wait for Flash latency to be updated */ + getlatency = LL_FLASH_GetLatency(); + timeout--; + } while ((getlatency != latency) && (timeout > 0U)); + + if (getlatency != latency) + { + status = ERROR; + } + } + + return status; +} + + +/** + * @} + */ + +/** @addtogroup UTILS_LL_Private_Functions + * @{ + */ + + +/** + * @brief Function to Get PLL Output frequency + * @param PLL_InputFrequency PLL input frequency (in Hz) + * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains + * the configuration information for the PLL. + * @retval PLL output frequency (in Hz) + */ +static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, + const LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct) +{ + uint32_t pllfreq; + + /* Check the parameters */ + assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); + assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); + assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); + assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); + + pllfreq = LL_RCC_CalcPLLClockFreq(PLL_InputFrequency, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, + UTILS_PLLInitStruct->FRACN, UTILS_PLLInitStruct->PLLP); + + return pllfreq; +} + +/** + * @brief Check that all PLLs are not busy therefore configuration can be done + * @retval An ErrorStatus enumeration value: + * - SUCCESS: All PLLs are ready so configuration can be done + * - ERROR: One PLL at least is busy + */ +static ErrorStatus UTILS_IsPLLsNotBusy(void) +{ + ErrorStatus status = SUCCESS; + + /* Check if one of the PLL1 is busy */ + if (LL_RCC_PLL1_IsReady() != 0U) + { + /* PLL1 configuration cannot be done */ + status = ERROR; + } + + /* Check if one of the PLL2 is busy */ + if (LL_RCC_PLL2_IsReady() != 0U) + { + /* PLL2 configuration cannot be done */ + status = ERROR; + } + + /* Check if one of the PLL3 is busy */ + if (LL_RCC_PLL3_IsReady() != 0U) + { + /* PLL3 configuration cannot be done */ + status = ERROR; + } + + return status; +} + +/** + * @brief Function to enable PLL and switch system clock to PLL + * @param SYSCLK_Frequency SYSCLK frequency + * @param UTILS_ClkInitStruct pointer to a @ref LL_UTILS_ClkInitTypeDef structure that contains + * the configuration information for the BUS prescalers. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: No problem to switch system to PLL + * - ERROR: Problem to switch system to PLL + */ +static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, + LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) +{ + ErrorStatus status = SUCCESS; + uint32_t new_sysclk_frequency; + uint32_t new_hclk_frequency; + + assert_param(IS_LL_UTILS_SYSCLK_DIV(UTILS_ClkInitStruct->SYSCLKDivider)); + assert_param(IS_LL_UTILS_AHB_DIV(UTILS_ClkInitStruct->AHBCLKDivider)); + assert_param(IS_LL_UTILS_APB1_DIV(UTILS_ClkInitStruct->APB1CLKDivider)); + assert_param(IS_LL_UTILS_APB2_DIV(UTILS_ClkInitStruct->APB2CLKDivider)); + assert_param(IS_LL_UTILS_APB4_DIV(UTILS_ClkInitStruct->APB4CLKDivider)); + assert_param(IS_LL_UTILS_APB5_DIV(UTILS_ClkInitStruct->APB5CLKDivider)); + + /* Calculate the new HCLK frequency */ + new_sysclk_frequency = LL_RCC_CALC_SYSCLK_FREQ(SYSCLK_Frequency, UTILS_ClkInitStruct->SYSCLKDivider); + new_hclk_frequency = LL_RCC_CALC_HCLK_FREQ(new_sysclk_frequency, UTILS_ClkInitStruct->AHBCLKDivider); + + /* Increasing the number of wait states because of higher CPU frequency */ + if (SystemCoreClock < new_sysclk_frequency) + { + /* Set FLASH latency to highest latency */ + status = LL_SetFlashLatency(new_hclk_frequency); + } + + /* Update system clock configuration */ + if (status == SUCCESS) + { + /* Enable PLL */ + LL_RCC_PLL1_Enable(); + while (LL_RCC_PLL1_IsReady() != 1U) + { + /* Wait for PLL ready */ + } + + LL_RCC_PLL1P_Enable(); + + /* Set All APBxPrescaler to the Highest Divider */ + LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_16); + LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_16); + LL_RCC_SetAPB4Prescaler(LL_RCC_APB4_DIV_16); + LL_RCC_SetAPB5Prescaler(LL_RCC_APB5_DIV_16); + + /* Set SYS prescaler*/ + LL_RCC_SetSysPrescaler(UTILS_ClkInitStruct->SYSCLKDivider); + + /* Set AHB prescaler*/ + LL_RCC_SetAHBPrescaler(UTILS_ClkInitStruct->AHBCLKDivider); + + /* Sysclk activation on the main PLL */ + LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL1); + while (LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL1) + { + /* Wait for system clock switch to PLL */ + } + + /* Set APBn prescaler*/ + LL_RCC_SetAPB1Prescaler(UTILS_ClkInitStruct->APB1CLKDivider); + LL_RCC_SetAPB2Prescaler(UTILS_ClkInitStruct->APB2CLKDivider); + LL_RCC_SetAPB4Prescaler(UTILS_ClkInitStruct->APB4CLKDivider); + LL_RCC_SetAPB5Prescaler(UTILS_ClkInitStruct->APB5CLKDivider); + + /* Decreasing the number of wait states because of lower CPU frequency */ + if (SystemCoreClock > new_sysclk_frequency) + { + /* Set FLASH latency to lowest latency */ + status = LL_SetFlashLatency(new_hclk_frequency); + } + + /* Update SystemCoreClock variable */ + if (status == SUCCESS) + { + LL_SetSystemCoreClock(new_sysclk_frequency); + } + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_util_i3c.c b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_util_i3c.c index a7d1958e7..9ece90c92 100644 --- a/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_util_i3c.c +++ b/stm32cube/stm32h7rsxx/drivers/src/stm32h7rsxx_util_i3c.c @@ -1,409 +1,425 @@ -/** - ********************************************************************************************************************** - * @file stm32h7rsxx_util_i3c.c - * @author MCD Application Team - * @brief This utility help to calculate the different I3C Timing. - ********************************************************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ********************************************************************************************************************** - */ - -/* Includes ----------------------------------------------------------------------------------------------------------*/ -#include "stm32h7rsxx_util_i3c.h" - -/** @addtogroup STM32H7RSxx_UTIL_Driver - * @{ - */ - -/** @addtogroup UTILITY_I3C - * @{ - */ - -/* Private typedef ---------------------------------------------------------------------------------------------------*/ -/* Private define ----------------------------------------------------------------------------------------------------*/ -/** @defgroup I3C_UTIL_Private_Define I3C Utility Private Define - * @{ - */ -#define SEC210PSEC (uint64_t)100000000000 /*!< 10ps, to take two decimal float of ns calculation */ -#define TI3CH_MIN 3200U /*!< Open drain & push pull SCL high min, 32ns */ -#define TI3CH_OD_MAX 4100U /*!< Open drain SCL high max, 41 ns */ -#define TI3CL_OD_MIN 20000U /*!< Open drain SCL low min, 200 ns */ -#define TFMPL_OD_MIN 50000U /*!< Fast Mode Plus Open drain SCL low min, 500 ns */ -#define TFML_OD_MIN 130000U /*!< Fast Mode Open drain SCL low min, 1300 ns */ -#define TFM_MIN 250000U /*!< Fast Mode, period min for ti3cclk, 2.5us */ -#define TSM_MIN 1000000U /*!< Standard Mode, period min for ti3cclk, 10us */ -#define TI3C_CAS_MIN 3840U /*!< Time SCL after START min, 38.4 ns */ -#define TCAPA 35000U /*!< Capacitor effect Value measure on Nucleo around 350ns */ -/** - * @} - */ - -/* Private macro -----------------------------------------------------------------------------------------------------*/ -/** @defgroup I3C_UTIL_Private_Macro I3C Utility Private Macro - * @{ - */ -#define DIV_ROUND_CLOSEST(x, d) (((x) + ((d) / 2U)) / (d)) -/** - * @} - */ - -/* Private function prototypes ---------------------------------------------------------------------------------------*/ -/* Exported functions ------------------------------------------------------------------------------------------------*/ -/** @defgroup I3C_UTIL_Exported_Functions I3C Utility Exported Functions - * @{ - */ - -/** @defgroup I3C_UTIL_EF_Computation Computation - * @{ - */ -/** - * @brief Calculate the I3C Controller timing according current I3C clock source and required I3C bus clock. - * @param pInputTiming : [IN] Pointer to an I3C_CtrlTimingTypeDef structure that contains - * the required parameter for I3C timing computation. - * @param pOutputConfig : [OUT] Pointer to an LL_I3C_CtrlBusConfTypeDef structure that contains - * the configuration information for the specified I3C. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Timing calculation successfully - * - ERROR: Parameters or timing calculation error - */ -ErrorStatus I3C_CtrlTimingComputation(const I3C_CtrlTimingTypeDef *pInputTiming, - LL_I3C_CtrlBusConfTypeDef *pOutputConfig) -{ - ErrorStatus status = SUCCESS; - - /* MIPI Standard constants */ - /* I3C: Open drain & push pull SCL high min, tDIG_H & tDIG_H_MIXED: 32 ns */ - uint32_t ti3ch_min = TI3CH_MIN; - - /* I3C: Open drain SCL high max, t_HIGH: 41 ns */ - uint32_t ti3ch_od_max = TI3CH_OD_MAX; - - /* I3C: Open drain SCL high max, tHIGH: 41 ns (Ti3ch_od_max= 410) - I3C (pure bus): Open drain SCL low min, tLOW_OD: 200 ns */ - uint32_t ti3cl_od_min = TI3CL_OD_MIN; - - /* I3C (mixed bus): Open drain SCL low min, - tLOW: 500 ns (FM+ I2C on the bus) - tLOW: 1300 ns (FM I2C on the bus) */ - uint32_t tfmpl_od_min = TFMPL_OD_MIN; - uint32_t tfml_od_min = TFML_OD_MIN; - - /* I2C: min ti3cclk - fSCL: 1 MHz (FM+) - fSCL: 100 kHz (SM) */ - uint32_t tfm_min = TFM_MIN; - uint32_t tsm_min = TSM_MIN; - - /* I3C: time SCL after START min, Tcas: 38,4 ns */ - uint32_t ti3c_cas_min = TI3C_CAS_MIN; - - /* Period Clock source */ - uint32_t ti3cclk = 0U; - - /* I3C: Push pull period */ - uint32_t ti3c_pp_min = 0U; - - /* I2C: Open drain period */ - uint32_t ti2c_od_min = 0U; - - /* Time for SDA rise to 70% VDD from GND, capacitor effect */ - /* Value measure on Nucleo around 350ns */ - uint32_t tcapa = TCAPA; - - /* Compute variable */ - uint32_t sclhi3c; - uint32_t scllpp; - uint32_t scllod; - uint32_t sclhi2c; - uint32_t oneus; - uint32_t free; - uint32_t sdahold; - - /* Verify Parameters */ - if (((pInputTiming->clockSrcFreq == 0U) || (pInputTiming->i3cPPFreq == 0U)) && - (pInputTiming->busType == I3C_PURE_I3C_BUS)) - { - status = ERROR; - } - - if (((pInputTiming->clockSrcFreq == 0U) || (pInputTiming->i3cPPFreq == 0U) || (pInputTiming->i2cODFreq == 0U)) && - (pInputTiming->busType == I3C_MIXED_BUS)) - { - status = ERROR; - } - - if (status == SUCCESS) - { - /* Period Clock source */ - ti3cclk = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->clockSrcFreq / (uint64_t)2)) / - (uint64_t)pInputTiming->clockSrcFreq); - - if ((pInputTiming->dutyCycle > 50U) || (ti3cclk == 0U)) - { - status = ERROR; - } - } - - if ((status == SUCCESS) && (ti3cclk != 0U)) - { - /* I3C: Push pull period */ - ti3c_pp_min = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->i3cPPFreq / (uint64_t)2)) / - (uint64_t)pInputTiming->i3cPPFreq); - - /* I2C: Open drain period */ - ti2c_od_min = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->i2cODFreq / (uint64_t)2)) / - (uint64_t)pInputTiming->i2cODFreq); - - if ((pInputTiming->busType != I3C_PURE_I3C_BUS) && (ti2c_od_min > tsm_min)) - { - status = ERROR; - } - } - - /* SCL Computation */ - if ((status == SUCCESS) && (ti3cclk != 0U)) - { - /* I3C SCL high level (push-pull & open drain) */ - if (pInputTiming->busType == I3C_PURE_I3C_BUS) - { - sclhi3c = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(ti3c_pp_min * pInputTiming->dutyCycle, ti3cclk), 100U) - 1U; - - /* Check if sclhi3c < ti3ch_min, in that case calculate sclhi3c based on ti3ch_min */ - if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) - { - sclhi3c = DIV_ROUND_CLOSEST(ti3ch_min, ti3cclk) - 1U; - - /* Check if sclhi3c < ti3ch_min */ - if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) - { - sclhi3c += 1U; - } - - scllpp = DIV_ROUND_CLOSEST(ti3c_pp_min, ti3cclk) - (sclhi3c + 1U) - 1U; - } - else - { - sclhi3c = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(ti3c_pp_min * pInputTiming->dutyCycle, ti3cclk), 100U) - 1U; - - /* Check if sclhi3c < ti3ch_min */ - if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) - { - sclhi3c += 1U; - } - - scllpp = DIV_ROUND_CLOSEST((ti3c_pp_min - ((sclhi3c + 1U) * ti3cclk) + (ti3cclk / 2U)), ti3cclk) - 1U; - } - - } - else - { - /* Warning: (sclhi3c + 1) * ti3cclk > Ti3ch_od_max expected */ - sclhi3c = DIV_ROUND_CLOSEST(ti3ch_od_max, ti3cclk) - 1U; - - if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) - { - sclhi3c += 1U; - } - else if (((sclhi3c + 1U) * ti3cclk) > ti3ch_od_max) - { - sclhi3c = (ti3ch_od_max / ti3cclk); - } - else - { - /* Do nothing, keep sclhi3c as previously calculated */ - } - - /* I3C SCL low level (push-pull) */ - /* tscllpp = (scllpp + 1) x ti3cclk */ - scllpp = DIV_ROUND_CLOSEST((ti3c_pp_min - ((sclhi3c + 1U) * ti3cclk)), ti3cclk) - 1U; - } - - /* Check if scllpp is superior at (ti3c_pp_min + 1/2 clock source cycle) */ - /* Goal is to choice the scllpp approach lowest, to have a value frequency highest approach as possible */ - uint32_t ideal_scllpp = (ti3c_pp_min - ((sclhi3c + 1U) * ti3cclk)); - if (((scllpp + 1U) * ti3cclk) >= (ideal_scllpp + (ti3cclk / 2U) + 1U)) - { - scllpp -= 1U; - } - - /* Check if scllpp + sclhi3c is inferior at (ti3c_pp_min + 1/2 clock source cycle) */ - /* Goal is to increase the scllpp, to have a value frequency not out of the clock request */ - if (((scllpp + sclhi3c + 1U + 1U) * ti3cclk) < (ideal_scllpp + (ti3cclk / 2U) + 1U)) - { - scllpp += 1U; - } - - /* I3C SCL low level (pure I3C bus) */ - if (pInputTiming->busType == I3C_PURE_I3C_BUS) - { - if (ti3c_pp_min < ti3cl_od_min) - { - scllod = DIV_ROUND_CLOSEST(ti3cl_od_min, ti3cclk) - 1U; - - if (((scllod + 1U) * ti3cclk) < ti3cl_od_min) - { - scllod += 1U; - } - } - else - { - scllod = scllpp; - } - - /* Verify that SCL Open drain Low duration is superior as SDA rise time 70% */ - if (((scllod + 1U) * ti3cclk) < tcapa) - { - scllod = DIV_ROUND_CLOSEST(tcapa, ti3cclk) + 1U; - } - - sclhi2c = 0U; /* I2C SCL not used in pure I3C bus */ - } - /* SCL low level on mixed bus (open-drain) */ - /* I2C SCL high level (mixed bus with I2C) */ - else - { - scllod = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(ti2c_od_min * (100U - pInputTiming->dutyCycle), - ti3cclk), 100U) - 1U; - - /* Mix Bus Fast Mode plus */ - if (ti2c_od_min < tfm_min) - { - if (((scllod + 1U) * ti3cclk) < tfmpl_od_min) - { - scllod = DIV_ROUND_CLOSEST(tfmpl_od_min, ti3cclk) - 1U; - } - } - /* Mix Bus Fast Mode */ - else - { - if (((scllod + 1U) * ti3cclk) < tfml_od_min) - { - scllod = DIV_ROUND_CLOSEST(tfml_od_min, ti3cclk) - 1U; - } - } - - sclhi2c = DIV_ROUND_CLOSEST((ti2c_od_min - ((scllod + 1U) * ti3cclk)), ti3cclk) - 1U; - } - - /* Clock After Start computation */ - - /* I3C pure bus: (Tcas + tcapa)/2 */ - if (pInputTiming->busType == I3C_PURE_I3C_BUS) - { - free = DIV_ROUND_CLOSEST((ti3c_cas_min + tcapa), (2U * ti3cclk)) + 1U; - } - /* I3C, I2C mixed: (scllod + tcapa)/2 */ - else - { - free = DIV_ROUND_CLOSEST((((scllod + 1U) * ti3cclk) + tcapa), (2U * ti3cclk)); - } - - /* One cycle hold time addition */ - /* By default 1/2 cycle: must be > 3 ns */ - if (ti3cclk > 600U) - { - sdahold = 0U; - } - else - { - sdahold = 1U; - } - - /* 1 microsecond reference */ - oneus = DIV_ROUND_CLOSEST(100000U, ti3cclk) - 2U; - - if ((scllpp > 0xFFU) || (sclhi3c > 0xFFU) || (scllod > 0xFFU) || (sclhi2c > 0xFFU) || - (free > 0xFFU) || (oneus > 0xFFU)) - { - /* Case of value is over 8bits, issue may be due to clocksource have a rate too high for bus clock request */ - /* Update the return status */ - status = ERROR; - } - else - { - /* SCL configuration */ - pOutputConfig->SCLPPLowDuration = (uint8_t)scllpp; - pOutputConfig->SCLI3CHighDuration = (uint8_t)sclhi3c; - pOutputConfig->SCLODLowDuration = (uint8_t)scllod; - pOutputConfig->SCLI2CHighDuration = (uint8_t)sclhi2c; - - /* Free, Idle and SDA hold time configuration */ - pOutputConfig->BusFreeDuration = (uint8_t)free; - pOutputConfig->BusIdleDuration = (uint8_t)oneus; - pOutputConfig->SDAHoldTime = (uint32_t)(sdahold << I3C_TIMINGR1_SDA_HD_Pos); - } - } - - return status; -} - -/** - * @brief Calculate the I3C Controller timing according current I3C clock source and required I3C bus clock. - * @param pInputTiming : [IN] Pointer to an I3C_TgtTimingTypeDef structure that contains - * the required parameter for I3C timing computation. - * @param pOutputConfig : [OUT] Pointer to an LL_I3C_TgtBusConfTypeDef structure that contains - * the configuration information for the specified I3C. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Timing calculation successfully - * - ERROR: Parameters or timing calculation error - */ -ErrorStatus I3C_TgtTimingComputation(const I3C_TgtTimingTypeDef *pInputTiming, - LL_I3C_TgtBusConfTypeDef *pOutputConfig) -{ - ErrorStatus status = SUCCESS; - uint32_t oneus; - uint32_t ti3cclk = 0U; - - /* Verify Parameters */ - if (pInputTiming->clockSrcFreq == 0U) - { - status = ERROR; - } - - if (status == SUCCESS) - { - /* Period Clock source */ - ti3cclk = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->clockSrcFreq / (uint64_t)2)) / - (uint64_t)pInputTiming->clockSrcFreq); - - /* Verify Parameters */ - if (ti3cclk == 0U) - { - status = ERROR; - } - } - - if ((status == SUCCESS) && (ti3cclk != 0U)) - { - /* 1 microsecond reference */ - oneus = DIV_ROUND_CLOSEST(100000U, ti3cclk) - 2U; - - /* Bus available time configuration */ - pOutputConfig->BusAvailableDuration = (uint8_t)oneus; - } - - return status; -} -/** - * @} - */ -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** - * @} - */ - -/** - * @} - */ +/** + ********************************************************************************************************************** + * @file stm32h7rsxx_util_i3c.c + * @author MCD Application Team + * @brief This utility help to calculate the different I3C Timing. + ********************************************************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ********************************************************************************************************************** + */ + +/* Includes ----------------------------------------------------------------------------------------------------------*/ +#include "stm32h7rsxx_util_i3c.h" + +/** @addtogroup STM32H7RSxx_UTIL_Driver + * @{ + */ + +/** @addtogroup UTILITY_I3C + * @{ + */ + +#if (defined(USE_HAL_DRIVER) && defined(HAL_I3C_MODULE_ENABLED)) || defined(USE_FULL_LL_DRIVER) + +/* Private typedef ---------------------------------------------------------------------------------------------------*/ +/* Private define ----------------------------------------------------------------------------------------------------*/ +/** @defgroup I3C_UTIL_Private_Define I3C Utility Private Define + * @{ + */ +#define SEC210PSEC (uint64_t)100000000000 /*!< 10ps, to take two decimal float of ns calculation */ +#define TI3CH_MIN 3200U /*!< Open drain & push pull SCL high min, 32ns */ +#define TI3CH_OD_MAX 4100U /*!< Open drain SCL high max, 41 ns */ +#define TI3CL_OD_MIN 20000U /*!< Open drain SCL low min, 200 ns */ +#define TFMPL_OD_MIN 50000U /*!< Fast Mode Plus Open drain SCL low min, 500 ns */ +#define TFML_OD_MIN 130000U /*!< Fast Mode Open drain SCL low min, 1300 ns */ +#define TFM_MIN 250000U /*!< Fast Mode, period min for ti3cclk, 2.5us */ +#define TSM_MIN 1000000U /*!< Standard Mode, period min for ti3cclk, 10us */ +#define TI3C_CAS_MIN 3840U /*!< Time SCL after START min, 38.4 ns */ +#define TCAPA 35000U /*!< Capacitor effect Value measure on Nucleo around 350ns */ +#define I3C_FREQUENCY_MAX 257000000U /*!< Maximum I3C frequency */ +/** + * @} + */ + +/* Private macro -----------------------------------------------------------------------------------------------------*/ +/** @defgroup I3C_UTIL_Private_Macro I3C Utility Private Macro + * @{ + */ +#define DIV_ROUND_CLOSEST(x, d) (((x) + ((d) / 2U)) / (d)) +/** + * @} + */ + +/* Private function prototypes ---------------------------------------------------------------------------------------*/ +/* Exported functions ------------------------------------------------------------------------------------------------*/ +/** @defgroup I3C_UTIL_Exported_Functions I3C Utility Exported Functions + * @{ + */ + +/** @defgroup I3C_UTIL_EF_Computation Computation + * @{ + */ +/** + * @brief Calculate the I3C Controller timing according current I3C clock source and required I3C bus clock. + * @param pInputTiming : [IN] Pointer to an I3C_CtrlTimingTypeDef structure that contains + * the required parameter for I3C timing computation. + * @param pOutputConfig : [OUT] Pointer to an LL_I3C_CtrlBusConfTypeDef structure that contains + * the configuration information for the specified I3C. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Timing calculation successfully + * - ERROR: Parameters or timing calculation error + */ +ErrorStatus I3C_CtrlTimingComputation(const I3C_CtrlTimingTypeDef *pInputTiming, + LL_I3C_CtrlBusConfTypeDef *pOutputConfig) +{ + ErrorStatus status = SUCCESS; + + /* MIPI Standard constants */ + /* I3C: Open drain & push pull SCL high min, tDIG_H & tDIG_H_MIXED: 32 ns */ + uint32_t ti3ch_min = TI3CH_MIN; + + /* I3C: Open drain SCL high max, t_HIGH: 41 ns */ + uint32_t ti3ch_od_max = TI3CH_OD_MAX; + + /* I3C: Open drain SCL high max, tHIGH: 41 ns (Ti3ch_od_max= 410) + I3C (pure bus): Open drain SCL low min, tLOW_OD: 200 ns */ + uint32_t ti3cl_od_min = TI3CL_OD_MIN; + + /* I3C (mixed bus): Open drain SCL low min, + tLOW: 500 ns (FM+ I2C on the bus) + tLOW: 1300 ns (FM I2C on the bus) */ + uint32_t tfmpl_od_min = TFMPL_OD_MIN; + uint32_t tfml_od_min = TFML_OD_MIN; + + /* I2C: min ti3cclk + fSCL: 1 MHz (FM+) + fSCL: 100 kHz (SM) */ + uint32_t tfm_min = TFM_MIN; + uint32_t tsm_min = TSM_MIN; + + /* I3C: time SCL after START min, Tcas: 38,4 ns */ + uint32_t ti3c_cas_min = TI3C_CAS_MIN; + + /* Period Clock source */ + uint32_t ti3cclk = 0U; + + /* I3C: Push pull period */ + uint32_t ti3c_pp_min = 0U; + + /* I2C: Open drain period */ + uint32_t ti2c_od_min = 0U; + + /* Time for SDA rise to 70% VDD from GND, capacitor effect */ + /* Value measure on Nucleo around 350ns */ + uint32_t tcapa = TCAPA; + + /* Compute variable */ + uint32_t sclhi3c; + uint32_t scllpp; + uint32_t scllod; + uint32_t sclhi2c; + uint32_t oneus; + uint32_t free; + uint32_t sdahold; + + /* Verify Parameters */ + if (pInputTiming->clockSrcFreq > I3C_FREQUENCY_MAX) + { + /* Above this frequency, some timing register parameters are over than field value */ + status = ERROR; + } + + if ((pInputTiming->busType != I3C_PURE_I3C_BUS) && (pInputTiming->busType != I3C_MIXED_BUS)) + { + status = ERROR; + } + + if (((pInputTiming->clockSrcFreq == 0U) || (pInputTiming->i3cPPFreq == 0U)) && + (pInputTiming->busType == I3C_PURE_I3C_BUS)) + { + status = ERROR; + } + + if (((pInputTiming->clockSrcFreq == 0U) || (pInputTiming->i3cPPFreq == 0U) || (pInputTiming->i2cODFreq == 0U)) && + (pInputTiming->busType == I3C_MIXED_BUS)) + { + status = ERROR; + } + + if (status == SUCCESS) + { + /* Period Clock source */ + ti3cclk = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->clockSrcFreq / (uint64_t)2)) / + (uint64_t)pInputTiming->clockSrcFreq); + + if ((pInputTiming->dutyCycle > 50U) || (ti3cclk == 0U)) + { + status = ERROR; + } + } + + if ((status == SUCCESS) && (ti3cclk != 0U)) + { + /* I3C: Push pull period */ + ti3c_pp_min = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->i3cPPFreq / (uint64_t)2)) / + (uint64_t)pInputTiming->i3cPPFreq); + + /* I2C: Open drain period */ + ti2c_od_min = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->i2cODFreq / (uint64_t)2)) / + (uint64_t)pInputTiming->i2cODFreq); + + if ((pInputTiming->busType != I3C_PURE_I3C_BUS) && (ti2c_od_min > tsm_min)) + { + status = ERROR; + } + } + + /* SCL Computation */ + if ((status == SUCCESS) && (ti3cclk != 0U)) + { + /* I3C SCL high level (push-pull & open drain) */ + if (pInputTiming->busType == I3C_PURE_I3C_BUS) + { + sclhi3c = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(ti3c_pp_min * pInputTiming->dutyCycle, ti3cclk), 100U) - 1U; + + /* Check if sclhi3c < ti3ch_min, in that case calculate sclhi3c based on ti3ch_min */ + if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) + { + sclhi3c = DIV_ROUND_CLOSEST(ti3ch_min, ti3cclk) - 1U; + + /* Check if sclhi3c < ti3ch_min */ + if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) + { + sclhi3c += 1U; + } + + scllpp = DIV_ROUND_CLOSEST(ti3c_pp_min, ti3cclk) - (sclhi3c + 1U) - 1U; + } + else + { + sclhi3c = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(ti3c_pp_min * pInputTiming->dutyCycle, ti3cclk), 100U) - 1U; + + /* Check if sclhi3c < ti3ch_min */ + if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) + { + sclhi3c += 1U; + } + + scllpp = DIV_ROUND_CLOSEST((ti3c_pp_min - ((sclhi3c + 1U) * ti3cclk) + (ti3cclk / 2U)), ti3cclk) - 1U; + } + + } + else + { + /* Warning: (sclhi3c + 1) * ti3cclk > Ti3ch_od_max expected */ + sclhi3c = DIV_ROUND_CLOSEST(ti3ch_od_max, ti3cclk) - 1U; + + if (((sclhi3c + 1U) * ti3cclk) < ti3ch_min) + { + sclhi3c += 1U; + } + else if (((sclhi3c + 1U) * ti3cclk) > ti3ch_od_max) + { + sclhi3c = (ti3ch_od_max / ti3cclk); + } + else + { + /* Do nothing, keep sclhi3c as previously calculated */ + } + + /* I3C SCL low level (push-pull) */ + /* tscllpp = (scllpp + 1) x ti3cclk */ + scllpp = DIV_ROUND_CLOSEST((ti3c_pp_min - ((sclhi3c + 1U) * ti3cclk)), ti3cclk) - 1U; + } + + /* Check if scllpp is superior at (ti3c_pp_min + 1/2 clock source cycle) */ + /* Goal is to choice the scllpp approach lowest, to have a value frequency highest approach as possible */ + uint32_t ideal_scllpp = (ti3c_pp_min - ((sclhi3c + 1U) * ti3cclk)); + if (((scllpp + 1U) * ti3cclk) >= (ideal_scllpp + (ti3cclk / 2U) + 1U)) + { + scllpp -= 1U; + } + + /* Check if scllpp + sclhi3c is inferior at (ti3c_pp_min + 1/2 clock source cycle) */ + /* Goal is to increase the scllpp, to have a value frequency not out of the clock request */ + if (((scllpp + sclhi3c + 1U + 1U) * ti3cclk) < (ideal_scllpp + (ti3cclk / 2U) + 1U)) + { + scllpp += 1U; + } + + /* I3C SCL low level (pure I3C bus) */ + if (pInputTiming->busType == I3C_PURE_I3C_BUS) + { + if (ti3c_pp_min < ti3cl_od_min) + { + scllod = DIV_ROUND_CLOSEST(ti3cl_od_min, ti3cclk) - 1U; + + if (((scllod + 1U) * ti3cclk) < ti3cl_od_min) + { + scllod += 1U; + } + } + else + { + scllod = scllpp; + } + + /* Verify that SCL Open drain Low duration is superior as SDA rise time 70% */ + if (((scllod + 1U) * ti3cclk) < tcapa) + { + scllod = DIV_ROUND_CLOSEST(tcapa, ti3cclk) + 1U; + } + + sclhi2c = 0U; /* I2C SCL not used in pure I3C bus */ + } + /* SCL low level on mixed bus (open-drain) */ + /* I2C SCL high level (mixed bus with I2C) */ + else + { + scllod = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(ti2c_od_min * (100U - pInputTiming->dutyCycle), + ti3cclk), 100U) - 1U; + + /* Mix Bus Fast Mode plus */ + if (ti2c_od_min < tfm_min) + { + if (((scllod + 1U) * ti3cclk) < tfmpl_od_min) + { + scllod = DIV_ROUND_CLOSEST(tfmpl_od_min, ti3cclk) - 1U; + } + } + /* Mix Bus Fast Mode */ + else + { + if (((scllod + 1U) * ti3cclk) < tfml_od_min) + { + scllod = DIV_ROUND_CLOSEST(tfml_od_min, ti3cclk) - 1U; + } + } + + sclhi2c = DIV_ROUND_CLOSEST((ti2c_od_min - ((scllod + 1U) * ti3cclk)), ti3cclk) - 1U; + } + + /* Clock After Start computation */ + + /* I3C pure bus: (Tcas + tcapa)/2 */ + if (pInputTiming->busType == I3C_PURE_I3C_BUS) + { + free = DIV_ROUND_CLOSEST((ti3c_cas_min + tcapa), (2U * ti3cclk)) + 1U; + } + /* I3C, I2C mixed: (scllod + tcapa)/2 */ + else + { + free = DIV_ROUND_CLOSEST((((scllod + 1U) * ti3cclk) + tcapa), (2U * ti3cclk)); + } + + /* One cycle hold time addition */ + /* By default 1/2 cycle: must be > 3 ns */ + if (ti3cclk > 600U) + { + sdahold = 0U; + } + else + { + sdahold = 1U; + } + + /* 1 microsecond reference */ + oneus = DIV_ROUND_CLOSEST(100000U, ti3cclk) - 2U; + + if ((scllpp > 0xFFU) || (sclhi3c > 0xFFU) || (scllod > 0xFFU) || (sclhi2c > 0xFFU) || + (free > 0xFFU) || (oneus > 0xFFU)) + { + /* Case of value is over 8bits, issue may be due to clocksource have a rate too high for bus clock request */ + /* Update the return status */ + status = ERROR; + } + else + { + /* SCL configuration */ + pOutputConfig->SCLPPLowDuration = (uint8_t)scllpp; + pOutputConfig->SCLI3CHighDuration = (uint8_t)sclhi3c; + pOutputConfig->SCLODLowDuration = (uint8_t)scllod; + pOutputConfig->SCLI2CHighDuration = (uint8_t)sclhi2c; + + /* Free, Idle and SDA hold time configuration */ + pOutputConfig->BusFreeDuration = (uint8_t)free; + pOutputConfig->BusIdleDuration = (uint8_t)oneus; + pOutputConfig->SDAHoldTime = (uint32_t)(sdahold << I3C_TIMINGR1_SDA_HD_Pos); + } + } + + return status; +} + +/** + * @brief Calculate the I3C Controller timing according current I3C clock source and required I3C bus clock. + * @param pInputTiming : [IN] Pointer to an I3C_TgtTimingTypeDef structure that contains + * the required parameter for I3C timing computation. + * @param pOutputConfig : [OUT] Pointer to an LL_I3C_TgtBusConfTypeDef structure that contains + * the configuration information for the specified I3C. + * @retval An ErrorStatus enumeration value: + * - SUCCESS: Timing calculation successfully + * - ERROR: Parameters or timing calculation error + */ +ErrorStatus I3C_TgtTimingComputation(const I3C_TgtTimingTypeDef *pInputTiming, + LL_I3C_TgtBusConfTypeDef *pOutputConfig) +{ + ErrorStatus status = SUCCESS; + uint32_t oneus; + uint32_t ti3cclk = 0U; + + /* Verify Parameters */ + if (pInputTiming->clockSrcFreq == 0U) + { + status = ERROR; + } + + if (status == SUCCESS) + { + /* Period Clock source */ + ti3cclk = (uint32_t)((SEC210PSEC + ((uint64_t)pInputTiming->clockSrcFreq / (uint64_t)2)) / + (uint64_t)pInputTiming->clockSrcFreq); + + /* Verify Parameters */ + if (ti3cclk == 0U) + { + status = ERROR; + } + } + + if ((status == SUCCESS) && (ti3cclk != 0U)) + { + /* 1 microsecond reference */ + oneus = DIV_ROUND_CLOSEST(100000U, ti3cclk) - 2U; + + /* Bus available time configuration */ + pOutputConfig->BusAvailableDuration = (uint8_t)oneus; + } + + return status; +} +/** + * @} + */ +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ + +#endif /* (defined(USE_HAL_DRIVER) && defined(HAL_I3C_MODULE_ENABLED)) || defined(USE_FULL_LL_DRIVER) */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/release_note.html b/stm32cube/stm32h7rsxx/release_note.html new file mode 100644 index 000000000..83c5ab68d --- /dev/null +++ b/stm32cube/stm32h7rsxx/release_note.html @@ -0,0 +1,801 @@ + + + + + + + Release Notes for STM32CubeH7RS Firmware Package + + + + + + +
    +
    +
    +

    Release Notes for

    +

    STM32CubeH7RS Firmware Package

    +

    Copyright © 2024 STMicroelectronics
    +

    + +
    +

    Purpose

    +

    STM32Cube is an STMicroelectronics original initiative to ease developers life by reducing development efforts, time and cost.

    +

    STM32Cube covers STM32 portfolio.

    +

    STM32Cube Version 1.x includes:

    +
      +
    • The STM32CubeMX, a graphical software configuration tool that allows to generate C initialization code using graphical wizards.
    • +
    • A comprehensive embedded software platform, delivered per series +
        +
      • The STM32Cube HAL, an STM32 abstraction layer embedded software, ensuring maximized portability across STM32 portfolio.
      • +
      • Low-layer APIs (LL) offering a fast light-weight expert-oriented layer which is closer to the hardware than the HAL.
      • +
      • A consistent set of middleware components such as FAT file system, RTOS, USB and USB PD.
      • +
    • +
    +

    All embedded software utilities, delivered with a full set of examples.

    +

    The STM32Cube firmware solution offers a straightforward API with a modular architecture, making it simple to fine tune custom applications and scalable to fit most requirements.

    +
    +STM32Cube
    STM32Cube
    +
    +


    +

    +

    The HAL (Hardware Abstraction Layer) & LL (Low Layers) drivers provided within this package support the STM32H7R7xx/H7S7xx/H7R3xx/H7S3xx products.

    +

    The HAL and LL drivers provided within this package are compliant with MISRA-C:2012 guidelines, and have been reviewed with a static analysis tool to eliminate possible run-time errors. Reports are available on demand.

    +

    For quick getting started with the STM32CubeH7RS firmware package, you can refer to UM3294 and download firmware updates and all the latest documentation from www.st.com/stm32cubeH7RS

    +

    Here is the list of references to user documents:

    + +
    +
    +

    Update History

    +
    + +
    +

    Maintenance release

    +

    Maintenance Release of STM32CubeH7RS Firmware package supporting STM32H7R7xx/H7R3xx/H7S3xx/H7S7xx devices.

    +

    Contents

    +

    Features

    +

    STM32CubeH7RS gathers in one single package all the generic embedded software components required to develop an application on STM32H7Rx/7Sx microcontrollers.

    +
      +
    • Production–ready HAL and LL API drivers, checked with CodeSonar® static analysis tool, and developed in compliance with MISRA C® guidelines.
    • +
    • CMSIS CORE, DSP and RTOS software components.
    • +
    • Consistent set of middleware components (RTOS, USB Host, USB Device, USB Power Delivery, FAT file system, TCP/IP and Ethernet, OpenBootloader and mcuboot).
    • +
    • Up to 250 examples and applications for easy understanding, compatible with STM32CubeMX to facilitate the configuration through a graphical tool.
    • +
    • New Templates_Board project for NUCLEO-H7S3L8 demonstrating the STM32CubeMX “Start my project from ST Board” providing an easy access to ST boards’ features.
    • +
    • New STM32_ExtMem_Manager and STM32_ExtMem_Loader components provide software implementation that facilitates external memories integration.
    • +
    +

    The STM32CubeH7RS reference firmware supports all the different configurations of the SMT32H7Sx, it implements Secure Boot and Secure Firmware Update functions demonstrated thru OEMiRoT example.

    +

    Projects

    +

    The STM32CubeH7RS Firmware package contains project templates running on STMicroelectronics boards with preconfigured projects for the main supported toolchains.

    +

    Six template projects are provided in this release:

    +
      +
    • Projects\STM32H7S7S8-DK\Templates_LL +
        +
      • Execution only in the internal Flash based on Low Layer drivers
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template +
        +
      • Execution only in the internal Flash based on HAL drivers
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template_XIP +
        +
      • Boot from internal Flash and eXecution In Place from external NOR flash
      • +
      • The Template_XIP project is composed of three sub-projects: +
          +
        • Boot: boot execution from the internal Flash with jump to application in external memory
        • +
        • Appli: application code that executes in the external NOR flash memory
        • +
        • ExtMemLoader: build the external Flash loader for DK
        • +
      • +
      • Warning: User options bytes configuration is required to run at the highest frequency on the external memory (readme.html)
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template_LRUN +
        +
      • It boots from internal Flash, copies the application from external Flash to internal RAM and jumps to the application code in internal RAM (Sub-project Boot)
      • +
      • The Template_LRUN project is composed of two sub-projects: +
          +
        • Boot: copies the application from the external Flash to internal RAM and jumps to the application code in internal RAM
        • +
        • Appli: application code that will be executed in internal RAM
        • +
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template_ROT +
        +
      • This project provides two Root Of Trust boot path reference templates: +
          +
        • OEMiROT boot path reference template: boot is performed through OEMiROT / OEMuROT bootpath after authenticity and integrity checks of the project firmware image.
        • +
        • STiROT boot path reference template: boot is performed through STiROT boot path after authenticity and integrity checks of the project firmware image.
        • +
      • +
    • +
    • Projects\NUCLEO-H7S3L8\Templates_Board +
        +
      • Boot from internal Flash and eXecution In Place from external NOR flash
      • +
      • STM32CubeMX “Start my project from ST Board” providing an easy access to ST boards’ features with demonstration code based on HAL and BSP drivers
      • +
    • +
    • Same template projects are provided on both boards (except Template_ROT only provided on STM32H7S7S8-DK and Templates_Board only provided on NUCLEO-H7S3L8)
    • +
    +


    +

    +

    The exhaustive list of projects is provided in this table (STM32CubeProjectsList.html).

    + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    ProjectsV1.1.0 release notes
    +


    +

    +

    Components

    +

    The components flagged by “” have changed since the previous release. “” are new.

    +

    Drivers

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    CMSISV5.9.0release notes
    STM32H7RSxx CMSISV1.1.0 release notes
    STM32H7RSxx HALV1.1.0 release notes
    +

    BSP Drivers

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    STM32H7RSxx_NucleoV1.0.0release notes
    STM32H7S78-DKV1.0.0release notes
    aps256xxV1.0.6release notes
    CommonV7.3.0release notes
    wm8904V1.0.0release notes
    gt911V1.0.1release notes
    lan8742V1.0.3release notes
    mx25uw25645gV1.0.1 release notes
    mx66uw1g45gV1.1.0release notes
    ov5640V4.0.2release notes
    rk050hr18V1.0.0release notes
    tcpp0203V1.2.3release notes
    +


    +

    +

    Middlewares

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    FatFSR0.15release notes ST modified 230818 release notes
    FreeRTOSv10.5.1release notes ST modified 231117 release notes
    LwIPv2.1.3release notes ST modified 230818 release notes
    mbed-cryptov2.28.8_20240527 ST release notes
    mcubootv1.7.2.23release notes ST modified 240214 release notes
    OpenBootloaderv6.1.1release notes
    STM32_ExtMem_Loaderv1.1.0 release notes
    STM32_ExtMem_Managerv1.1.0 release notes
    STM32 USB Device Libraryv2.11.3release notes
    STM32 USB Host Libraryv3.5.2release notes
    STM32_USBPD_Library - Corev5.1.0release notes
    STM32_USBPD_Library - Devicesv1.2.1release notes
    +


    +

    +

    Utilities

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    Commonv1.6.1release notes
    CPUv1.1.4release notes
    Fontsv2.0.4release notes
    GUI_INTERFACEv3.0.1release notes
    JPEGv2.0.3release notes
    lcdv2.0.3release notes
    lcd_tracev2.0.2release notes
    logv1.0.4release notes
    ROT_AppliConfigv1.1.2release notes
    TRACER_EMBv1.11.0release notes
    +


    +

    +

    Development Toolchains and Compilers

    +
      +
    • IAR Embedded Workbench for ARM (EWARM) toolchain V9.20.1 + ST-Link
    • +
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.39 + ST-Link +
        +
      • Support of ARM Compiler 6 (AC-5 like warnings) for HAL/LL/BSP drivers and STMicroelectronics Middleware components
      • +
    • +
    • STM32CubeIDE V1.16.0 (GCC12)
    • +
    +


    +

    +

    Supported Devices and boards

    +
      +
    • ROT applications are compatible with SFSP V1.0.0 (or higher).
    • +
    • STM32H7R7xx/H7S7xx/H7R3xx/H7S3xx
    • +
    • STM32H7S78-DK
    • +
    • NUCLEO-H7S3L8
    • +
    +


    +

    +

    Known Limitations

    +
      +
    • Some examples and/or applications not supported by CubeMX
    • +
    • All projects not yet available on MDK-ARM & CubeIDE
    • +
    +

    Dependencies

    +

    Backward Compatibility

    +
      +
    • Not applicable
    • +
    +


    +

    +
    +
    +
    + +
    +

    First release

    +

    First Official Release of STM32CubeH7RS Firmware package supporting STM32H7R7xx/H7R3xx/H7S3xx/H7S7xx devices.

    +

    Contents

    +

    Features

    +

    STM32CubeH7RS gathers in one single package all the generic embedded software components required to develop an application on STM32H7Rx/7Sx microcontrollers.

    +
      +
    • Production–ready HAL and LL API drivers, checked with CodeSonar® static analysis tool, and developed in compliance with MISRA C® guidelines.
    • +
    • CMSIS CORE, DSP and RTOS software components.
    • +
    • Consistent set of middleware components (RTOS, USB Host, USB Device, USB Power Delivery, FAT file system, TCP/IP and Ethernet, OpenBootloader and mcuboot).
    • +
    • Up to 250 examples and applications for easy understanding, compatible with STM32CubeMX to facilitate the configuration through a graphical tool.
    • +
    • New Templates_Board project for NUCLEO-H7S3L8 demonstrating the STM32CubeMX “Start my project from ST Board” providing an easy access to ST boards’ features.
    • +
    • New STM32_ExtMem_Manager and STM32_ExtMem_Loader components provide software implementation that facilitates external memories integration.
    • +
    +

    The STM32CubeH7RS reference firmware supports all the different configurations of the SMT32H7Sx, it implements Secure Boot and Secure Firmware Update functions demonstrated thru OEMiRoT example.

    +

    Projects

    +

    The STM32CubeH7RS Firmware package contains project templates running on STMicroelectronics boards with preconfigured projects for the main supported toolchains.

    +

    SIx template projects are provided in this release:

    +
      +
    • Projects\STM32H7S7S8-DK\Templates_LL +
        +
      • Execution only in the internal Flash based on Low Layer drivers
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template +
        +
      • Execution only in the internal Flash based on HAL drivers
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template_XIP +
        +
      • Boot from internal Flash and eXecution In Place from external NOR flash
      • +
      • The Template_XIP project is composed of three sub-projects: +
          +
        • Boot: boot execution from the internal Flash with jump to application in external memory
        • +
        • Appli: application code that executes in the external NOR flash memory
        • +
        • ExtMemLoader: build the external Flash loader for DK
        • +
      • +
      • Warning: User options bytes configuration is required to run at the highest frequency on the external memory (readme.html)
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template_LRUN +
        +
      • It boots from internal Flash, copies the application from external Flash to internal RAM and jumps to the application code in internal RAM (Sub-project Boot)
      • +
      • The Template_LRUN project is composed of two sub-projects: +
          +
        • Boot: copies the application from the external Flash to internal RAM and jumps to the application code in internal RAM
        • +
        • Appli: application code that will be executed in internal RAM
        • +
      • +
    • +
    • Projects\STM32H7S7S8-DK\Templates\Template_ROT +
        +
      • This project provides two Root Of Trust boot path reference templates: +
          +
        • OEMiROT boot path reference template: boot is performed through OEMiROT / OEMuROT bootpath after authenticity and integrity checks of the project firmware image.
        • +
        • STiROT boot path reference template: boot is performed through STiROT boot path after authenticity and integrity checks of the project firmware image.
        • +
      • +
    • +
    • Projects\NUCLEO-H7S3L8\Templates_Board +
        +
      • Boot from internal Flash and eXecution In Place from external NOR flash
      • +
      • STM32CubeMX “Start my project from ST Board” providing an easy access to ST boards’ features with demonstration code based on HAL and BSP drivers
      • +
    • +
    • Same template projects are provided on both boards (except Template_ROT only provided on STM32H7S7S8-DK and Templates_Board only provided on NUCLEO-H7S3L8)
    • +
    +


    +

    +

    The exhaustive list of projects is provided in this table (STM32CubeProjectsList.html).

    + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    ProjectsV1.0.0release notes
    +


    +

    +

    Components

    +

    The components flagged by “” have changed since the previous release. “” are new.

    +

    Drivers

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    CMSISV5.9.0release notes
    STM32H7RSxx CMSISV1.0.0release notes
    STM32H7RSxx HALV1.0.0release notes
    +

    BSP Drivers

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    STM32H7RSxx_NucleoV1.0.0release notes
    STM32H7S78-DKV1.0.0release notes
    aps256xxV1.0.6release notes
    CommonV7.3.0release notes
    wm8904V1.0.0release notes
    gt911V1.0.1release notes
    lan8742V1.0.3release notes
    mx25uw25645gV1.0.0release notes
    mx66uw1g45gV1.1.0release notes
    ov5640V4.0.2release notes
    rk050hr18V1.0.0release notes
    tcpp0203V1.2.3release notes
    +


    +

    +

    Middlewares

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    FatFSR0.15release notes ST modified 230818 release notes
    FreeRTOSv10.5.1release notes ST modified 231117 release notes
    LwIPv2.1.3release notes ST modified 230818 release notes
    mcubootv1.7.2.23release notes ST modified 240214 release notes
    OpenBootloaderv6.1.1release notes
    STM32_ExtMem_Loaderv1.0.0release notes
    STM32_ExtMem_Managerv1.0.0release notes
    STM32 USB Device Libraryv2.11.3release notes
    STM32 USB Host Libraryv3.5.2release notes
    STM32_USBPD_Library - Corev5.1.0release notes
    STM32_USBPD_Library - Devicesv1.2.1release notes
    +


    +

    +

    Utilities

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    Commonv1.6.1release notes
    CPUv1.1.4release notes
    Fontsv2.0.4release notes
    GUI_INTERFACEv3.0.1release notes
    JPEGv2.0.3release notes
    lcdv2.0.3release notes
    lcd_tracev2.0.2release notes
    logv1.0.4release notes
    ROT_AppliConfigv1.1.2release notes
    TRACER_EMBv1.11.0release notes
    +


    +

    +

    Development Toolchains and Compilers

    +
      +
    • IAR Embedded Workbench for ARM (EWARM) toolchain V9.20.1 + ST-Link
    • +
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.38a + ST-Link +
        +
      • Support of ARM Compiler 6 (AC-5 like warnings) for HAL/LL/BSP drivers and STMicroelectronics Middleware components
      • +
    • +
    • STM32CubeIDE V1.15.0 (GCC12)
    • +
    +


    +

    +

    Supported Devices and boards

    +
      +
    • ROT applications are compatible with SFSP V1.0.0 (or higher).
    • +
    • STM32H7R7xx/H7S7xx/H7R3xx/H7S3xx
    • +
    • STM32H7S78-DK
    • +
    • NUCLEO-H7S3L8
    • +
    +


    +

    +

    Known Limitations

    +
      +
    • Some examples and/or applications not supported by CubeMX
    • +
    • All projects not yet available on MDK-ARM & CubeIDE
    • +
    +

    Those limitations will be corrected in maintenance release V1.1.0 planned in June 2024.

    +

    Dependencies

    +
      +
    • STM32CubeMX V6.11.0 +
        +
      • Projects (Applications and Examples) are generated using STM32CubeMX version V6.11.0.
      • +
    • +
    +

    Backward Compatibility

    +
      +
    • Not applicable
    • +
    +


    +

    +
    +
    +
    +
    +
    +
    +
    +

    For complete documentation on STM32H7Rx/Sx,

    +

    visit: stm32h7-series/stm32h7r3-7s3

    +

    visit: stm32h7-series/stm32h7r7-7s7

    +

    This release note uses up to date web standards and, for this reason, should not be opened with Internet Explorer but preferably with popular browsers such as Google Chrome, Mozilla Firefox, Opera or Microsoft Edge.

    +
    +

    Info

    +
    +
    +
    + + diff --git a/stm32cube/stm32h7rsxx/soc/stm32h7r3xx.h b/stm32cube/stm32h7rsxx/soc/stm32h7r3xx.h index 7545c6c82..ae76802b3 100644 --- a/stm32cube/stm32h7rsxx/soc/stm32h7r3xx.h +++ b/stm32cube/stm32h7rsxx/soc/stm32h7r3xx.h @@ -13153,7 +13153,7 @@ typedef struct #define XSPI_CR_DMM_Msk (0x1UL << XSPI_CR_DMM_Pos) /*!< 0x00000040 */ #define XSPI_CR_DMM XSPI_CR_DMM_Msk /*!< Dual Memory Mode */ #define XSPI_CR_FTHRES_Pos (8U) -#define XSPI_CR_FTHRES_Msk (0x3FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00003F00 */ +#define XSPI_CR_FTHRES_Msk (0x1FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00001F00 */ #define XSPI_CR_FTHRES XSPI_CR_FTHRES_Msk /*!< FIFO Threshold Level */ #define XSPI_CR_TEIE_Pos (16U) #define XSPI_CR_TEIE_Msk (0x1UL << XSPI_CR_TEIE_Pos) /*!< 0x00010000 */ @@ -21486,8 +21486,8 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ -#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ #define USB_OTG_GCCFG_SESSVLD USB_OTG_GCCFG_SESSVLD_Msk /*!< VBUS session valid indicator Vbus voltage level */ @@ -22140,6 +22140,9 @@ typedef struct #define USART_CR1_WAKE_Pos (11U) #define USART_CR1_WAKE_Msk (0x1UL << USART_CR1_WAKE_Pos) /*!< 0x00000800 */ #define USART_CR1_WAKE USART_CR1_WAKE_Msk /*!< Receiver Wakeup method */ +#define USART_CR1_M_Pos (12U) +#define USART_CR1_M_Msk (0x10001UL << USART_CR1_M_Pos) /*!< 0x10001000 */ +#define USART_CR1_M USART_CR1_M_Msk /*!< Word length */ #define USART_CR1_M0_Pos (12U) #define USART_CR1_M0_Msk (0x1UL << USART_CR1_M0_Pos) /*!< 0x00001000 */ #define USART_CR1_M0 USART_CR1_M0_Msk /*!< Word length - Bit 0 */ @@ -22177,7 +22180,6 @@ typedef struct #define USART_CR1_M1_Pos (28U) #define USART_CR1_M1_Msk (0x1UL << USART_CR1_M1_Pos) /*!< 0x10000000 */ #define USART_CR1_M1 USART_CR1_M1_Msk /*!< Word length - Bit 1 */ -#define USART_CR1_M (uint32_t)(USART_CR1_M1 | USART_CR1_M0) /*!< Word length */ #define USART_CR1_FIFOEN_Pos (29U) #define USART_CR1_FIFOEN_Msk (0x1UL << USART_CR1_FIFOEN_Pos) /*!< 0x20000000 */ #define USART_CR1_FIFOEN USART_CR1_FIFOEN_Msk /*!< FIFO mode enable */ diff --git a/stm32cube/stm32h7rsxx/soc/stm32h7r7xx.h b/stm32cube/stm32h7rsxx/soc/stm32h7r7xx.h index d769201e7..a707a872c 100644 --- a/stm32cube/stm32h7rsxx/soc/stm32h7r7xx.h +++ b/stm32cube/stm32h7rsxx/soc/stm32h7r7xx.h @@ -13553,7 +13553,7 @@ typedef struct #define XSPI_CR_DMM_Msk (0x1UL << XSPI_CR_DMM_Pos) /*!< 0x00000040 */ #define XSPI_CR_DMM XSPI_CR_DMM_Msk /*!< Dual Memory Mode */ #define XSPI_CR_FTHRES_Pos (8U) -#define XSPI_CR_FTHRES_Msk (0x3FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00003F00 */ +#define XSPI_CR_FTHRES_Msk (0x1FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00001F00 */ #define XSPI_CR_FTHRES XSPI_CR_FTHRES_Msk /*!< FIFO Threshold Level */ #define XSPI_CR_TEIE_Pos (16U) #define XSPI_CR_TEIE_Msk (0x1UL << XSPI_CR_TEIE_Pos) /*!< 0x00010000 */ @@ -21916,8 +21916,8 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ -#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ #define USB_OTG_GCCFG_SESSVLD USB_OTG_GCCFG_SESSVLD_Msk /*!< VBUS session valid indicator Vbus voltage level */ @@ -22570,6 +22570,9 @@ typedef struct #define USART_CR1_WAKE_Pos (11U) #define USART_CR1_WAKE_Msk (0x1UL << USART_CR1_WAKE_Pos) /*!< 0x00000800 */ #define USART_CR1_WAKE USART_CR1_WAKE_Msk /*!< Receiver Wakeup method */ +#define USART_CR1_M_Pos (12U) +#define USART_CR1_M_Msk (0x10001UL << USART_CR1_M_Pos) /*!< 0x10001000 */ +#define USART_CR1_M USART_CR1_M_Msk /*!< Word length */ #define USART_CR1_M0_Pos (12U) #define USART_CR1_M0_Msk (0x1UL << USART_CR1_M0_Pos) /*!< 0x00001000 */ #define USART_CR1_M0 USART_CR1_M0_Msk /*!< Word length - Bit 0 */ @@ -22607,7 +22610,6 @@ typedef struct #define USART_CR1_M1_Pos (28U) #define USART_CR1_M1_Msk (0x1UL << USART_CR1_M1_Pos) /*!< 0x10000000 */ #define USART_CR1_M1 USART_CR1_M1_Msk /*!< Word length - Bit 1 */ -#define USART_CR1_M (uint32_t)(USART_CR1_M1 | USART_CR1_M0) /*!< Word length */ #define USART_CR1_FIFOEN_Pos (29U) #define USART_CR1_FIFOEN_Msk (0x1UL << USART_CR1_FIFOEN_Pos) /*!< 0x20000000 */ #define USART_CR1_FIFOEN USART_CR1_FIFOEN_Msk /*!< FIFO mode enable */ diff --git a/stm32cube/stm32h7rsxx/soc/stm32h7rsxx.h b/stm32cube/stm32h7rsxx/soc/stm32h7rsxx.h index 3af7cd525..300327426 100644 --- a/stm32cube/stm32h7rsxx/soc/stm32h7rsxx.h +++ b/stm32cube/stm32h7rsxx/soc/stm32h7rsxx.h @@ -79,9 +79,9 @@ * @brief CMSIS Device version number */ #define __STM32H7RS_CMSIS_VERSION_MAIN (0x01U) /*!< [31:24] main version */ -#define __STM32H7RS_CMSIS_VERSION_SUB1 (0x00U) /*!< [23:16] sub1 version */ +#define __STM32H7RS_CMSIS_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */ #define __STM32H7RS_CMSIS_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */ -#define __STM32H7RS_CMSIS_VERSION_RC (0x04U) /*!< [7:0] release candidate */ +#define __STM32H7RS_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32H7RS_CMSIS_VERSION ((__STM32H7RS_CMSIS_VERSION_MAIN << 24U)\ |(__STM32H7RS_CMSIS_VERSION_SUB1 << 16U)\ |(__STM32H7RS_CMSIS_VERSION_SUB2 << 8U )\ diff --git a/stm32cube/stm32h7rsxx/soc/stm32h7s3xx.h b/stm32cube/stm32h7rsxx/soc/stm32h7s3xx.h index 950e63715..3d42a99d3 100644 --- a/stm32cube/stm32h7rsxx/soc/stm32h7s3xx.h +++ b/stm32cube/stm32h7rsxx/soc/stm32h7s3xx.h @@ -13785,7 +13785,7 @@ typedef struct #define XSPI_CR_DMM_Msk (0x1UL << XSPI_CR_DMM_Pos) /*!< 0x00000040 */ #define XSPI_CR_DMM XSPI_CR_DMM_Msk /*!< Dual Memory Mode */ #define XSPI_CR_FTHRES_Pos (8U) -#define XSPI_CR_FTHRES_Msk (0x3FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00003F00 */ +#define XSPI_CR_FTHRES_Msk (0x1FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00001F00 */ #define XSPI_CR_FTHRES XSPI_CR_FTHRES_Msk /*!< FIFO Threshold Level */ #define XSPI_CR_TEIE_Pos (16U) #define XSPI_CR_TEIE_Msk (0x1UL << XSPI_CR_TEIE_Pos) /*!< 0x00010000 */ @@ -22369,8 +22369,8 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ -#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ #define USB_OTG_GCCFG_SESSVLD USB_OTG_GCCFG_SESSVLD_Msk /*!< VBUS session valid indicator Vbus voltage level */ @@ -23023,6 +23023,9 @@ typedef struct #define USART_CR1_WAKE_Pos (11U) #define USART_CR1_WAKE_Msk (0x1UL << USART_CR1_WAKE_Pos) /*!< 0x00000800 */ #define USART_CR1_WAKE USART_CR1_WAKE_Msk /*!< Receiver Wakeup method */ +#define USART_CR1_M_Pos (12U) +#define USART_CR1_M_Msk (0x10001UL << USART_CR1_M_Pos) /*!< 0x10001000 */ +#define USART_CR1_M USART_CR1_M_Msk /*!< Word length */ #define USART_CR1_M0_Pos (12U) #define USART_CR1_M0_Msk (0x1UL << USART_CR1_M0_Pos) /*!< 0x00001000 */ #define USART_CR1_M0 USART_CR1_M0_Msk /*!< Word length - Bit 0 */ @@ -23060,7 +23063,6 @@ typedef struct #define USART_CR1_M1_Pos (28U) #define USART_CR1_M1_Msk (0x1UL << USART_CR1_M1_Pos) /*!< 0x10000000 */ #define USART_CR1_M1 USART_CR1_M1_Msk /*!< Word length - Bit 1 */ -#define USART_CR1_M (uint32_t)(USART_CR1_M1 | USART_CR1_M0) /*!< Word length */ #define USART_CR1_FIFOEN_Pos (29U) #define USART_CR1_FIFOEN_Msk (0x1UL << USART_CR1_FIFOEN_Pos) /*!< 0x20000000 */ #define USART_CR1_FIFOEN USART_CR1_FIFOEN_Msk /*!< FIFO mode enable */ diff --git a/stm32cube/stm32h7rsxx/soc/stm32h7s7xx.h b/stm32cube/stm32h7rsxx/soc/stm32h7s7xx.h index 5b089fc92..8da2a6c1b 100644 --- a/stm32cube/stm32h7rsxx/soc/stm32h7s7xx.h +++ b/stm32cube/stm32h7rsxx/soc/stm32h7s7xx.h @@ -14187,7 +14187,7 @@ typedef struct #define XSPI_CR_DMM_Msk (0x1UL << XSPI_CR_DMM_Pos) /*!< 0x00000040 */ #define XSPI_CR_DMM XSPI_CR_DMM_Msk /*!< Dual Memory Mode */ #define XSPI_CR_FTHRES_Pos (8U) -#define XSPI_CR_FTHRES_Msk (0x3FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00003F00 */ +#define XSPI_CR_FTHRES_Msk (0x1FUL << XSPI_CR_FTHRES_Pos) /*!< 0x00001F00 */ #define XSPI_CR_FTHRES XSPI_CR_FTHRES_Msk /*!< FIFO Threshold Level */ #define XSPI_CR_TEIE_Pos (16U) #define XSPI_CR_TEIE_Msk (0x1UL << XSPI_CR_TEIE_Pos) /*!< 0x00010000 */ @@ -22801,8 +22801,8 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ -#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ #define USB_OTG_GCCFG_SESSVLD USB_OTG_GCCFG_SESSVLD_Msk /*!< VBUS session valid indicator Vbus voltage level */ @@ -23455,6 +23455,9 @@ typedef struct #define USART_CR1_WAKE_Pos (11U) #define USART_CR1_WAKE_Msk (0x1UL << USART_CR1_WAKE_Pos) /*!< 0x00000800 */ #define USART_CR1_WAKE USART_CR1_WAKE_Msk /*!< Receiver Wakeup method */ +#define USART_CR1_M_Pos (12U) +#define USART_CR1_M_Msk (0x10001UL << USART_CR1_M_Pos) /*!< 0x10001000 */ +#define USART_CR1_M USART_CR1_M_Msk /*!< Word length */ #define USART_CR1_M0_Pos (12U) #define USART_CR1_M0_Msk (0x1UL << USART_CR1_M0_Pos) /*!< 0x00001000 */ #define USART_CR1_M0 USART_CR1_M0_Msk /*!< Word length - Bit 0 */ @@ -23492,7 +23495,6 @@ typedef struct #define USART_CR1_M1_Pos (28U) #define USART_CR1_M1_Msk (0x1UL << USART_CR1_M1_Pos) /*!< 0x10000000 */ #define USART_CR1_M1 USART_CR1_M1_Msk /*!< Word length - Bit 1 */ -#define USART_CR1_M (uint32_t)(USART_CR1_M1 | USART_CR1_M0) /*!< Word length */ #define USART_CR1_FIFOEN_Pos (29U) #define USART_CR1_FIFOEN_Msk (0x1UL << USART_CR1_FIFOEN_Pos) /*!< 0x20000000 */ #define USART_CR1_FIFOEN USART_CR1_FIFOEN_Msk /*!< FIFO mode enable */ diff --git a/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.c b/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.c index 2ab3733df..97d821bcb 100644 --- a/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.c +++ b/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.c @@ -1,285 +1,285 @@ -/** - ****************************************************************************** - * @file system_stm32h7rsxx.c - * @author MCD Application Team - * @brief CMSIS Cortex-M7 Device Peripheral Access Layer System Source File - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - * - * This file provides two functions and one global variable to be called from - * user application: - * - SystemInit(): This function is called at startup just after reset and - * before branch to main program. This call is made inside - * the "startup_stm32h7rsxx.s" file. - * - * - SystemCoreClock variable: Contains the core clock (sys_cpu_ck), it can - * be used by the user application to setup the - * SysTick timer or configure other parameters. - * - * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must - * be called whenever the core clock is changed - * during program execution. - * - * After each device reset the HSI (64 MHz) is used as system clock source. - * Then SystemInit() function is called, in "startup_stm32h7rsxx.s" file, to - * optionally configure the system clock before to branch to main program. - * - *============================================================================= - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup STM32H7RSxx_System - * @{ - */ - -/** @addtogroup STM32H7RSxx_System_Private_Includes - * @{ - */ - -#include "stm32h7rsxx.h" -#include - -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Private_TypesDefinitions - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Private_Defines - * @{ - */ -#if !defined (HSE_VALUE) - #define HSE_VALUE 24000000UL /*!< Value of the High-Speed External oscillator in Hz */ -#endif /* HSE_VALUE */ - -#if !defined (HSI_VALUE) - #define HSI_VALUE 64000000UL /*!< Value of the High-Speed Internal oscillator in Hz */ -#endif /* HSI_VALUE */ - -#if !defined (CSI_VALUE) - #define CSI_VALUE 4000000UL /*!< Value of the Low-power Internal oscillator in Hz */ -#endif /* CSI_VALUE */ - -/*!< The VTOR location information is based on information from the linker with a dependency - on the IDE, the cortex register is updated using the INTVECT_START. -*/ -#if defined(__ICCARM__) -extern uint32_t __vector_table; -#define INTVECT_START ((uint32_t)& __vector_table) -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) -extern void * __Vectors; -#define INTVECT_START ((uint32_t) & __Vectors) -#elif defined(__GNUC__) -extern void * g_pfnVectors; -#define INTVECT_START ((uint32_t)& g_pfnVectors) -#endif /* __ICCARM__*/ - - - -/******************************************************************************/ -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Private_Macros - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Private_Variables - * @{ - */ - /* The SystemCoreClock variable is updated in two ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the first function listed above, since SystemCoreClock - variable is updated automatically. - */ -uint32_t SystemCoreClock = HSI_VALUE; - -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Private_FunctionPrototypes - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Private_Functions - * @{ - */ - -/** - * @brief Setup the microcontroller system. - * @retval None - */ - -void SystemInit(void) -{ - /* Configure the Vector Table location -------------------------------------*/ - SCB->VTOR = INTVECT_START; - - /* FPU settings ------------------------------------------------------------*/ -#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 20U)|(3UL << 22U)); /* set CP10 and CP11 Full Access */ -#endif -} - -/** - * @brief Update SystemCoreClock variable according to RCC registers values. - * The SystemCoreClock variable contains the core clock (sys_cpu_ck), it can - * be used by the user application to setup the SysTick timer or configure - * other parameters. - * - * @note Each time the core clock changes, this function must be called - * to update SystemCoreClock variable value. Otherwise, any configuration - * based on this variable will be incorrect. - * - * @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: - * - * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) - * - * - If SYSCLK source is CSI, SystemCoreClock will contain the CSI_VALUE(**) - * - * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(***) - * - * - If SYSCLK source is PLL, SystemCoreClock will contain the HSI_VALUE(*) - * or CSI_VALUE(**) or HSE_VALUE(***) multiplied/divided by the PLL factors. - * - * (*) HSI_VALUE is a constant defined in stm32h7rsxx_hal.h file (default value - * 64 MHz) but the real value may vary depending on the variations - * in voltage and temperature. - * - * (**) CSI_VALUE is a constant defined in stm32h7rsxx_hal.h file (default value - * 4 MHz) but the real value may vary depending on the variations - * in voltage and temperature. - * - * (***) HSE_VALUE is a constant defined in stm32h7rsxx_hal.h file (default value - * 24 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. - * - * - The result of this function could be not correct when using fractional - * value for HSE crystal. - * - * @retval None - */ -void SystemCoreClockUpdate(void) -{ - uint32_t sysclk, hsivalue, pllsource, pllm, pllp, core_presc; - float_t pllfracn, pllvco; - - /* Get SYSCLK source -------------------------------------------------------*/ - switch (RCC->CFGR & RCC_CFGR_SWS) - { - case 0x00: /* HSI used as system clock source (default after reset) */ - sysclk = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> RCC_CR_HSIDIV_Pos)); - break; - - case 0x08: /* CSI used as system clock source */ - sysclk = CSI_VALUE; - break; - - case 0x10: /* HSE used as system clock source */ - sysclk = HSE_VALUE; - break; - - case 0x18: /* PLL1 used as system clock source */ - /* PLL1_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLLM) * PLLN - SYSCLK = PLL1_VCO / PLL1R - */ - pllsource = (RCC->PLLCKSELR & RCC_PLLCKSELR_PLLSRC); - pllm = ((RCC->PLLCKSELR & RCC_PLLCKSELR_DIVM1) >> RCC_PLLCKSELR_DIVM1_Pos) ; - if ((RCC->PLLCFGR & RCC_PLLCFGR_PLL1FRACEN) != 0U) - { - pllfracn = (float_t)(uint32_t)(((RCC->PLL1FRACR & RCC_PLL1FRACR_FRACN)>> RCC_PLL1FRACR_FRACN_Pos)); - } - else - { - pllfracn = (float_t)0U; - } - - if (pllm != 0U) - { - switch (pllsource) - { - case 0x02: /* HSE used as PLL1 clock source */ - pllvco = ((float_t)HSE_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVN) + (pllfracn/(float_t)0x2000) +(float_t)1 ); - break; - - case 0x01: /* CSI used as PLL1 clock source */ - pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVN) + (pllfracn/(float_t)0x2000) +(float_t)1 ); - break; - - case 0x00: /* HSI used as PLL1 clock source */ - default: - hsivalue = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> RCC_CR_HSIDIV_Pos)); - pllvco = ( (float_t)hsivalue / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVN) + (pllfracn/(float_t)0x2000) +(float_t)1 ); - break; - } - pllp = (((RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVP) >> RCC_PLL1DIVR1_DIVP_Pos) + 1U ) ; - sysclk = (uint32_t)(float_t)(pllvco/(float_t)pllp); - } - else - { - sysclk = 0U; - } - break; - - default: /* Unexpected, default to HSI used as system clock source (default after reset) */ - sysclk = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> RCC_CR_HSIDIV_Pos)); - break; - } - - /* system clock frequency : CM7 CPU frequency */ - core_presc = (RCC->CDCFGR & RCC_CDCFGR_CPRE); - if (core_presc >= 8U) - { - SystemCoreClock = (sysclk >> (core_presc - RCC_CDCFGR_CPRE_3 + 1U)); - } - else - { - SystemCoreClock = sysclk; - } -} - - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file system_stm32h7rsxx.c + * @author MCD Application Team + * @brief CMSIS Cortex-M7 Device Peripheral Access Layer System Source File + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + * + * This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32h7rsxx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (sys_cpu_ck), it can + * be used by the user application to setup the + * SysTick timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * After each device reset the HSI (64 MHz) is used as system clock source. + * Then SystemInit() function is called, in "startup_stm32h7rsxx.s" file, to + * optionally configure the system clock before to branch to main program. + * + *============================================================================= + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup STM32H7RSxx_System + * @{ + */ + +/** @addtogroup STM32H7RSxx_System_Private_Includes + * @{ + */ + +#include "stm32h7rsxx.h" +#include + +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Private_Defines + * @{ + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE 24000000UL /*!< Value of the High-Speed External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSI_VALUE) + #define HSI_VALUE 64000000UL /*!< Value of the High-Speed Internal oscillator in Hz */ +#endif /* HSI_VALUE */ + +#if !defined (CSI_VALUE) + #define CSI_VALUE 4000000UL /*!< Value of the Low-power Internal oscillator in Hz */ +#endif /* CSI_VALUE */ + +/*!< The VTOR location information is based on information from the linker with a dependency + on the IDE, the cortex register is updated using the INTVECT_START. +*/ +#if defined(__ICCARM__) +extern uint32_t __vector_table; +#define INTVECT_START ((uint32_t)& __vector_table) +#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) +extern void * __Vectors; +#define INTVECT_START ((uint32_t) & __Vectors) +#elif defined(__GNUC__) +extern void * g_pfnVectors; +#define INTVECT_START ((uint32_t)& g_pfnVectors) +#endif /* __ICCARM__*/ + + + +/******************************************************************************/ +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Private_Variables + * @{ + */ + /* The SystemCoreClock variable is updated in two ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the first function listed above, since SystemCoreClock + variable is updated automatically. + */ +uint32_t SystemCoreClock = HSI_VALUE; + +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Private_FunctionPrototypes + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system. + * @retval None + */ + +void SystemInit(void) +{ + /* Configure the Vector Table location -------------------------------------*/ + SCB->VTOR = INTVECT_START; + + /* FPU settings ------------------------------------------------------------*/ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 20U)|(3UL << 22U)); /* set CP10 and CP11 Full Access */ +#endif +} + +/** + * @brief Update SystemCoreClock variable according to RCC registers values. + * The SystemCoreClock variable contains the core clock (sys_cpu_ck), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @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: + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) + * + * - If SYSCLK source is CSI, SystemCoreClock will contain the CSI_VALUE(**) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(***) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSI_VALUE(*) + * or CSI_VALUE(**) or HSE_VALUE(***) multiplied/divided by the PLL factors. + * + * (*) HSI_VALUE is a constant defined in stm32h7rsxx_hal.h file (default value + * 64 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) CSI_VALUE is a constant defined in stm32h7rsxx_hal.h file (default value + * 4 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (***) HSE_VALUE is a constant defined in stm32h7rsxx_hal.h file (default value + * 24 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. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @retval None + */ +void SystemCoreClockUpdate(void) +{ + uint32_t sysclk, hsivalue, pllsource, pllm, pllp, core_presc; + float_t pllfracn, pllvco; + + /* Get SYSCLK source -------------------------------------------------------*/ + switch (RCC->CFGR & RCC_CFGR_SWS) + { + case 0x00: /* HSI used as system clock source (default after reset) */ + sysclk = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> RCC_CR_HSIDIV_Pos)); + break; + + case 0x08: /* CSI used as system clock source */ + sysclk = CSI_VALUE; + break; + + case 0x10: /* HSE used as system clock source */ + sysclk = HSE_VALUE; + break; + + case 0x18: /* PLL1 used as system clock source */ + /* PLL1_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLLM) * PLLN + SYSCLK = PLL1_VCO / PLL1R + */ + pllsource = (RCC->PLLCKSELR & RCC_PLLCKSELR_PLLSRC); + pllm = ((RCC->PLLCKSELR & RCC_PLLCKSELR_DIVM1) >> RCC_PLLCKSELR_DIVM1_Pos) ; + if ((RCC->PLLCFGR & RCC_PLLCFGR_PLL1FRACEN) != 0U) + { + pllfracn = (float_t)(uint32_t)(((RCC->PLL1FRACR & RCC_PLL1FRACR_FRACN)>> RCC_PLL1FRACR_FRACN_Pos)); + } + else + { + pllfracn = (float_t)0U; + } + + if (pllm != 0U) + { + switch (pllsource) + { + case 0x02: /* HSE used as PLL1 clock source */ + pllvco = ((float_t)HSE_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVN) + (pllfracn/(float_t)0x2000) +(float_t)1 ); + break; + + case 0x01: /* CSI used as PLL1 clock source */ + pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVN) + (pllfracn/(float_t)0x2000) +(float_t)1 ); + break; + + case 0x00: /* HSI used as PLL1 clock source */ + default: + hsivalue = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> RCC_CR_HSIDIV_Pos)); + pllvco = ( (float_t)hsivalue / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVN) + (pllfracn/(float_t)0x2000) +(float_t)1 ); + break; + } + pllp = (((RCC->PLL1DIVR1 & RCC_PLL1DIVR1_DIVP) >> RCC_PLL1DIVR1_DIVP_Pos) + 1U ) ; + sysclk = (uint32_t)(float_t)(pllvco/(float_t)pllp); + } + else + { + sysclk = 0U; + } + break; + + default: /* Unexpected, default to HSI used as system clock source (default after reset) */ + sysclk = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> RCC_CR_HSIDIV_Pos)); + break; + } + + /* system clock frequency : CM7 CPU frequency */ + core_presc = (RCC->CDCFGR & RCC_CDCFGR_CPRE); + if (core_presc >= 8U) + { + SystemCoreClock = (sysclk >> (core_presc - RCC_CDCFGR_CPRE_3 + 1U)); + } + else + { + SystemCoreClock = sysclk; + } +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.h b/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.h index c6c0e6e36..4758b62e7 100644 --- a/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.h +++ b/stm32cube/stm32h7rsxx/soc/system_stm32h7rsxx.h @@ -1,95 +1,95 @@ -/** - ****************************************************************************** - * @file system_stm32h7rsxx.h - * @author MCD Application Team - * @brief CMSIS Cortex-M7 Device System Source File for STM32H7RSxx devices. - ****************************************************************************** - * @attention - * - * Copyright (c) 2022 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup STM32H7RSxx_system - * @{ - */ - -#ifndef SYSTEM_STM32H7RSXX_H -#define SYSTEM_STM32H7RSXX_H - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup STM32H7RSxx_System_Includes - * @{ - */ -#include -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Exported_Variables - * @{ - */ - /* The SystemCoreClock variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetSysClockFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the 2 first functions listed above, since SystemCoreClock - variable is updated automatically. - */ -extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ - -/** - * @} - */ - -/** @addtogroup STM32H7RSxx_System_Exported_Functions - * @{ - */ - -/** - \brief Setup the microcontroller system. - - Initialize the System and update the SystemCoreClock variable. - */ -extern void SystemInit (void); - - -/** - \brief Update SystemCoreClock variable. - - Updates the SystemCoreClock with current core Clock retrieved from cpu registers. - */ -extern void SystemCoreClockUpdate (void); - - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_STM32H7RSXX_H */ - -/** - * @} - */ - -/** - * @} - */ +/** + ****************************************************************************** + * @file system_stm32h7rsxx.h + * @author MCD Application Team + * @brief CMSIS Cortex-M7 Device System Source File for STM32H7RSxx devices. + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup STM32H7RSxx_system + * @{ + */ + +#ifndef SYSTEM_STM32H7RSXX_H +#define SYSTEM_STM32H7RSXX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup STM32H7RSxx_System_Includes + * @{ + */ +#include +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Exported_Variables + * @{ + */ + /* The SystemCoreClock variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetSysClockFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ + +/** + * @} + */ + +/** @addtogroup STM32H7RSxx_System_Exported_Functions + * @{ + */ + +/** + \brief Setup the microcontroller system. + + Initialize the System and update the SystemCoreClock variable. + */ +extern void SystemInit (void); + + +/** + \brief Update SystemCoreClock variable. + + Updates the SystemCoreClock with current core Clock retrieved from cpu registers. + */ +extern void SystemCoreClockUpdate (void); + + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_STM32H7RSXX_H */ + +/** + * @} + */ + +/** + * @} + */ From 681e452fd6d6082cd17d6d37f24889956072e2f6 Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 16:30:16 +0200 Subject: [PATCH 08/11] stm32cube: update stm32u5 to cube version V1.6.0 Update Cube version for STM32U5xx series on https://github.com/STMicroelectronics from version v1.5.0 to version v1.6.0 Signed-off-by: Guillaume Gautier --- stm32cube/stm32u5xx/CMakeLists.txt | 1 + stm32cube/stm32u5xx/README | 9 +- .../drivers/include/stm32u5xx_hal_conf.h | 10 +- .../drivers/include/stm32u5xx_hal_pka.h | 3 + .../drivers/include/stm32u5xx_hal_sdio.h | 596 ++++ .../drivers/include/stm32u5xx_ll_dac.h | 2 +- .../drivers/include/stm32u5xx_ll_sdmmc.h | 281 +- .../stm32u5xx/drivers/src/stm32u5xx_hal.c | 4 +- .../drivers/src/stm32u5xx_hal_cortex.c | 2 +- .../stm32u5xx/drivers/src/stm32u5xx_hal_dac.c | 4 +- .../drivers/src/stm32u5xx_hal_dac_ex.c | 15 +- .../stm32u5xx/drivers/src/stm32u5xx_hal_dsi.c | 6 +- .../drivers/src/stm32u5xx_hal_mmc_ex.c | 2 - .../stm32u5xx/drivers/src/stm32u5xx_hal_pka.c | 122 +- .../drivers/src/stm32u5xx_hal_sdio.c | 2846 +++++++++++++++++ .../drivers/src/stm32u5xx_ll_sdmmc.c | 206 +- stm32cube/stm32u5xx/release_note.html | 723 ++++- stm32cube/stm32u5xx/soc/stm32u595xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u599xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u5a5xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u5a9xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u5f7xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u5f9xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u5g7xx.h | 2 +- stm32cube/stm32u5xx/soc/stm32u5g9xx.h | 2 +- 25 files changed, 4604 insertions(+), 244 deletions(-) create mode 100644 stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_sdio.h create mode 100644 stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_sdio.c diff --git a/stm32cube/stm32u5xx/CMakeLists.txt b/stm32cube/stm32u5xx/CMakeLists.txt index 506a6b490..b08b0f072 100644 --- a/stm32cube/stm32u5xx/CMakeLists.txt +++ b/stm32cube/stm32u5xx/CMakeLists.txt @@ -69,6 +69,7 @@ zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SAI drivers/src/stm32u5xx_hal_ zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SAI_EX drivers/src/stm32u5xx_hal_sai_ex.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SD drivers/src/stm32u5xx_hal_sd.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SD_EX drivers/src/stm32u5xx_hal_sd_ex.c) +zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SDIO drivers/src/stm32u5xx_hal_sdio.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SMARTCARD drivers/src/stm32u5xx_hal_smartcard.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SMARTCARD_EX drivers/src/stm32u5xx_hal_smartcard_ex.c) zephyr_library_sources_ifdef(CONFIG_USE_STM32_HAL_SMBUS drivers/src/stm32u5xx_hal_smbus.c) diff --git a/stm32cube/stm32u5xx/README b/stm32cube/stm32u5xx/README index fbc37681b..9a8dd5dd5 100644 --- a/stm32cube/stm32u5xx/README +++ b/stm32cube/stm32u5xx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubeu5.html Status: - version v1.5.0 + version v1.6.0 Purpose: ST Microelectronics official MCU package for STM32U5 series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeU5 Commit: - 5ad32958b27c2d447a9438503efa6c2d0ccd8030 + 6591004477fdd8fba04573c0373679f2be0da595 Maintained-by: External @@ -44,11 +44,6 @@ Patch List: -Added stm32cube/stm32u5xx/drivers/include/stm32_assert.h -Removed unused stm32cube/stm32u5xx/drivers/include/stm32_assert_template.h - *Fix GFXTIM HAL: Compilation issue - -"#if defined (GFXTIM)" is missing from drivers/include/stm32u5xx_hal_gfxtim.h - Impacted files: drivers/include/stm32u5xx_hal_gfxtim.h - Internal reference: 157095 - *Fix to remove PAGESIZE definition which conflicts with POSIX Impacted files: drivers/include/Legacy/stm32_hal_legacy.h diff --git a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_conf.h b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_conf.h index 2af324e4c..0d84f5f7c 100644 --- a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_conf.h +++ b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_conf.h @@ -81,6 +81,7 @@ extern "C" { #define HAL_RTC_MODULE_ENABLED #define HAL_SAI_MODULE_ENABLED #define HAL_SD_MODULE_ENABLED +#define HAL_SDIO_MODULE_ENABLED #define HAL_SMARTCARD_MODULE_ENABLED #define HAL_SMBUS_MODULE_ENABLED #define HAL_SPI_MODULE_ENABLED @@ -227,6 +228,7 @@ vary depending on the variations in voltage and temperature.*/ #define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */ #define USE_HAL_SAI_REGISTER_CALLBACKS 0U /* SAI register callback disabled */ #define USE_HAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */ +#define USE_HAL_SDIO_REGISTER_CALLBACKS 0U /* SDIO register callback disabled */ #define USE_HAL_SDRAM_REGISTER_CALLBACKS 0U /* SDRAM register callback disabled */ #define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */ #define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */ @@ -248,9 +250,11 @@ vary depending on the variations in voltage and temperature.*/ #define USE_SPI_CRC 1U /* ################## SDMMC peripheral configuration ######################### */ - #define USE_SD_TRANSCEIVER 0U +/* ################## SDIO peripheral configuration ########################## */ +#define USE_SDIO_TRANSCEIVER 0U +#define SDIO_MAX_IO_NUMBER 7U /*!< SDIO device support maximum IO number */ /* Includes ------------------------------------------------------------------*/ /** @@ -397,6 +401,10 @@ vary depending on the variations in voltage and temperature.*/ #include "stm32u5xx_hal_sd.h" #endif /* HAL_SD_MODULE_ENABLED */ +#ifdef HAL_SDIO_MODULE_ENABLED +#include "stm32u5xx_hal_sdio.h" +#endif /* HAL_SDIO_MODULE_ENABLED */ + #ifdef HAL_SMBUS_MODULE_ENABLED #include "stm32u5xx_hal_smbus.h" #endif /* HAL_SMBUS_MODULE_ENABLED */ diff --git a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_pka.h b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_pka.h index c13101249..9e7049384 100644 --- a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_pka.h +++ b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_pka.h @@ -107,6 +107,9 @@ typedef struct PKA_TypeDef *Instance; /*!< Register base address */ __IO HAL_PKA_StateTypeDef State; /*!< PKA state */ __IO uint32_t ErrorCode; /*!< PKA Error code */ + __IO uint32_t primeordersize; /*!< Elliptic curve prime order length */ + __IO uint32_t opsize; /*!< Modular exponentiation operand length */ + __IO uint32_t modulussize; /*!< Elliptic curve modulus length */ #if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) void (* OperationCpltCallback)(struct __PKA_HandleTypeDef *hpka); /*!< PKA End of operation callback */ void (* ErrorCallback)(struct __PKA_HandleTypeDef *hpka); /*!< PKA Error callback */ diff --git a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_sdio.h b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_sdio.h new file mode 100644 index 000000000..0368251ab --- /dev/null +++ b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_hal_sdio.h @@ -0,0 +1,596 @@ +/** + ********************************************************************************************************************** + * @file stm32u5xx_hal_sdio.h + * @author MCD Application Team + * @brief Header file of SDIO HAL module. + ********************************************************************************************************************** + * @attention + * + * Copyright (c) 2024 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ********************************************************************************************************************** + */ + +/* Define to prevent recursive inclusion -----------------------------------------------------------------------------*/ +#ifndef STM32U5xx_HAL_SDIO_H +#define STM32U5xx_HAL_SDIO_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Includes ----------------------------------------------------------------------------------------------------------*/ +#include "stm32u5xx_ll_sdmmc.h" + +/** @addtogroup STM32U5xx_HAL_Driver + * @{ + */ +#if defined (SDMMC1) || defined (SDMMC2) + +/** @defgroup SDIO SDIO + * @brief SDIO HAL module driver + * @{ + */ + +/* Exported types ----------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Exported_Types SDIO Exported Types + * @{ + */ + +/** @defgroup SDIO_Exported_Types_Group1 SDIO State enumeration structure + * @{ + + */ +typedef enum +{ + HAL_SDIO_STATE_RESET = 0x00U, /*!< SDIO not yet initialized or disabled */ + HAL_SDIO_STATE_READY = 0x01U, /*!< SDIO initialized and ready for us */ + HAL_SDIO_STATE_BUSY = 0x02U, /*!< SDIO process ongoing */ +} HAL_SDIO_StateTypeDef; + +/** + * @} + */ + +/** @defgroup SDIO_Exported_Types_Group2 SDIO Handle and Structure definition + * @{ + */ +/** + * @brief SDIO Card Common Control Register Structure definition + */ +typedef struct +{ + uint8_t sdio_revision; /*!< SDIO revision */ + uint8_t cccr_revision; /*!< CCCR version */ + uint8_t sd_spec_revision; /*!< SD revision */ + uint8_t bus_width_8Bit; /*!< SDIO bus width 8 bit support */ + uint32_t card_capability; /*!< SDIO card capability */ + uint32_t commonCISPointer; /*!< point to common CIS */ +} HAL_SDIO_CCCR_TypeDef; + +/** + * @brief sdio card FBR register(Function Basic Register) + */ +typedef struct +{ + uint8_t flags; /*!< SDIO current IO flags */ + uint8_t ioStdFunctionCode; /*!< SDIO current IO standard function code */ + uint8_t ioExtFunctionCode; /*!< SDIO current IO extended function code */ + uint32_t ioPointerToCIS; /*!< SDIO current IO pointer to CIS */ + uint32_t ioPointerToCSA; /*!< SDIO current IO pointer to CSA */ +} HAL_SDIO_FBR_t; + +/** + * @brief SDIO CMD52 Structure definition + */ +typedef struct +{ + uint32_t Reg_Addr; /*!< This is the address of the byte of data inside of the selected function to read or write */ + uint8_t ReadAfterWrite; /*!< This is the read after write flag, it is used for write access only. */ + uint8_t IOFunctionNbr; /*!< The number of the function within the IO card you wish to read or write */ +} HAL_SDIO_DirectCmd_TypeDef; + +/** + * @brief SDIO CMD53 Structure definition + */ +typedef struct +{ + uint32_t Reg_Addr; /*!< This is the address of the byte of data inside of the selected function to read or write */ + uint32_t OpCode; /*!< Read/Write operation mode */ + uint32_t Block_Mode; /*!< Bytes or Blocks mode */ + uint32_t IOFunctionNbr; /*!< The number of the function within the IO card you wish to read or write */ +} HAL_SDIO_ExtendedCmd_TypeDef; + +#define SDIO_InitTypeDef SDMMC_InitTypeDef +#define SDIO_TypeDef SDMMC_TypeDef + +/** + * @brief SDIO handle Structure definition + */ +typedef struct __SDIO_HandleTypeDef +{ + SDIO_TypeDef *Instance; /*!< SDIO registers base address */ + + SDIO_InitTypeDef Init; /*!< SDIO required parameters */ + + HAL_LockTypeDef Lock; /*!< SDIO locking object */ + + uint8_t *pTxBuffPtr; /*!< Pointer to SDIO Tx transfer Buffer */ + + uint32_t TxXferSize; /*!< SDIO Tx Transfer size */ + + uint8_t *pRxBuffPtr; /*!< Pointer to SDIO Rx transfer Buffer */ + + uint32_t RxXferSize; /*!< SDIO Rx Transfer size */ + + uint32_t remaining_data; /*!< Remaining data to transfer */ + + uint32_t next_data_addr; /*!< SDIO Next data address */ + + __IO uint32_t next_reg_addr; /*!< SDIO Next register address */ + + uint16_t block_size; /*!< SDIO Block size */ + + __IO uint32_t Context; /*!< SDIO transfer context */ + + __IO HAL_SDIO_StateTypeDef State; /*!< SDIO card State */ + + __IO uint32_t ErrorCode; /*!< SDIO Card Error codes */ + + uint8_t IOFunctionMask; /*!< SDIO used to record current enabled io interrupt */ + + volatile uint8_t IOInterruptNbr; /*!< SDIO used to record total enabled io interrupt numbers */ + + void (* SDIO_IOFunction_Callback[SDIO_MAX_IO_NUMBER])(struct __SDIO_HandleTypeDef *hsdio, uint32_t func); + +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) + void (* TxCpltCallback)(struct __SDIO_HandleTypeDef *hsdio); + void (* RxCpltCallback)(struct __SDIO_HandleTypeDef *hsdio); + void (* ErrorCallback)(struct __SDIO_HandleTypeDef *hsdio); + void (* MspInitCallback)(struct __SDIO_HandleTypeDef *hsdio); + void (* MspDeInitCallback)(struct __SDIO_HandleTypeDef *hsdio); + +#if (USE_SDIO_TRANSCEIVER != 0U) + void (* DriveTransceiver_1_8V_Callback)(struct __SDIO_HandleTypeDef *hsdio, FlagStatus status); +#endif /* USE_SDIO_TRANSCEIVER */ +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + + +} SDIO_HandleTypeDef; + +/** + * @} + */ +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) +/** @defgroup SDIO_Exported_Types_Group3 SDIO Callback ID enumeration definition + * @{ + */ +typedef enum +{ + HAL_SDIO_TX_CPLT_CB_ID = 0x00U, /*!< SDIO Tx Complete Callback ID */ + HAL_SDIO_RX_CPLT_CB_ID = 0x01U, /*!< SDIO Rx Complete Callback ID */ + HAL_SDIO_ERROR_CB_ID = 0x02U, /*!< SDIO Error Callback ID */ + HAL_SDIO_MSP_INIT_CB_ID = 0x10U, /*!< SDIO MspInit Callback ID */ + HAL_SDIO_MSP_DEINIT_CB_ID = 0x11U /*!< SDIO MspDeInit Callback ID */ +} HAL_SDIO_CallbackIDTypeDef; +/** + * @} + */ + +/** @defgroup SDIO_Exported_Types_Group4 SDIO Callback pointer definition + * @{ + */ +typedef void (*pSDIO_CallbackTypeDef)(SDIO_HandleTypeDef *hsdio); +#if (USE_SDIO_TRANSCEIVER != 0U) +typedef void (*pSDIO_TransceiverCallbackTypeDef)(SDIO_HandleTypeDef *hsdio, FlagStatus status); +#endif /* USE_SDIO_TRANSCEIVER */ +/** + * @} + */ +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + +typedef void (*HAL_SDIO_IOFunction_CallbackTypeDef)(SDIO_HandleTypeDef *hsdio, uint32_t func); +/** + * @} + */ + +/* Exported constants ------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Exported_Constants SDIO Exported Constants + * @{ + */ + +/** @defgroup SDIO_Exported_Constansts_Group1 SDIO Error status Structure definition + * @{ + */ +#define HAL_SDIO_ERROR_NONE SDMMC_ERROR_NONE /*!< No error */ +#define HAL_SDIO_ERROR_DATA_CRC_FAIL SDMMC_ERROR_DATA_CRC_FAIL /*!< Data block sent/received (CRC check failed) */ +#define HAL_SDIO_ERROR_DATA_TIMEOUT SDMMC_ERROR_DATA_TIMEOUT /*!< Data timeout */ +#define HAL_SDIO_ERROR_TX_UNDERRUN SDMMC_ERROR_TX_UNDERRUN /*!< Transmit FIFO underrun */ +#define HAL_SDIO_ERROR_RX_OVERRUN SDMMC_ERROR_RX_OVERRUN /*!< Receive FIFO overrun */ +#define HAL_SDIO_ERROR_TIMEOUT SDMMC_ERROR_TIMEOUT /*!< Timeout error */ +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) +#define HAL_SDIO_ERROR_INVALID_CALLBACK SDMMC_ERROR_INVALID_PARAMETER /*!< Invalid callback error */ +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group2 SDIO context enumeration + * @{ + */ +#define SDIO_CONTEXT_NONE 0x00U /*!< None */ +#define SDIO_CONTEXT_READ_SINGLE_BLOCK 0x01U /*!< Read single block operation */ +#define SDIO_CONTEXT_READ_MULTIPLE_BLOCK 0x02U /*!< Read multiple blocks operation */ +#define SDIO_CONTEXT_WRITE_SINGLE_BLOCK 0x10U /*!< Write single block operation */ +#define SDIO_CONTEXT_WRITE_MULTIPLE_BLOCK 0x20U /*!< Write multiple blocks operation */ +#define SDIO_CONTEXT_IT 0x08U /*!< Process in Interrupt mode */ +#define SDIO_CONTEXT_DMA 0x80U /*!< Process in DMA mode */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group3 SDIO Block mode enumeration + * @{ + */ +#define HAL_SDIO_MODE_BYTE SDMMC_SDIO_MODE_BYTE +#define HAL_SDIO_MODE_BLOCK SDMMC_SDIO_MODE_BLOCK +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group4 SDIO operation code enumeration + * @{ + */ +#define HAL_SDIO_OP_CODE_NO_INC SDMMC_SDIO_NO_INC +#define HAL_SDIO_OP_CODE_AUTO_INC SDMMC_SDIO_AUTO_INC +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group5 SDIO Read After Write(RAW) enumeration + * @{ + */ +#define HAL_SDIO_WRITE_ONLY SDMMC_SDIO_WO /*!< SDIO Write only */ +#define HAL_SDIO_READ_AFTER_WRITE SDMMC_SDIO_RAW /*!< SDIO Read after write */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group6 SDIO wire mode enumeration + * @{ + */ +#define HAL_SDIO_1_WIRE_MODE 0U /*!< SDIO wire support 1 wire */ +#define HAL_SDIO_4_WIRES_MODE 1U /*!< SDIO wire support 4 wires */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group7 SDIO Data block size enumeration + * @{ + */ +#define HAL_SDIO_DATA_BLOCK_SIZE_1BYTE 1U /*!< SDIO data block size 1 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_2BYTE 2U /*!< SDIO data block size 2 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_4BYTE 4U /*!< SDIO data block size 4 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_8BYTE 8U /*!< SDIO data block size 8 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_16BYTE 16U /*!< SDIO data block size 16 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_32BYTE 32U /*!< SDIO data block size 32 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_64BYTE 64U /*!< SDIO data block size 64 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_128BYTE 128U /*!< SDIO data block size 128 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_256BYTE 256U /*!< SDIO data block size 256 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_512BYTE 512U /*!< SDIO data block size 512 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_1024BYTE 1024U /*!< SDIO data block size 1024 byte */ +#define HAL_SDIO_DATA_BLOCK_SIZE_2048BYTE 2048U /*!< SDIO data block size 2048 byte */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group8 SDIO Data block size enumeration + * @{ + */ +#define HAL_SDIO_BUS_WIDTH_8BIT_NOT_SUPPORTED 0U /*!< SDIO bus width 8 bit is not supported */ +#define HAL_SDIO_BUS_WIDTH_8BIT_SUPPORTED 1U /*!< SDIO bus width 8 bit is supported */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group9 SDIO Data rate definitions + * @{ + */ +#define HAL_SDIOS_DATA_RATE_SDR12 0U /*!< SDIO Data rate SDR12 */ +#define HAL_SDIOS_DATA_RATE_SDR25 1U /*!< SDIO Data rate SDR25 */ +#define HAL_SDIOS_DATA_RATE_SDR50 2U /*!< SDIO Data rate SDR50 */ +#define HAL_SDIOS_DATA_RATE_DDR50 3U /*!< SDIO Data rate DDR50 */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group10 SDIO Functions definitions + * @{ + */ +#define HAL_SDIO_FUNCTION_0 0U /*!< SDIO function 0 */ +#define HAL_SDIO_FUNCTION_1 1U /*!< SDIO function 1 */ +#define HAL_SDIO_FUNCTION_2 2U /*!< SDIO function 2 */ +#define HAL_SDIO_FUNCTION_3 3U /*!< SDIO function 3 */ +#define HAL_SDIO_FUNCTION_4 4U /*!< SDIO function 4 */ +#define HAL_SDIO_FUNCTION_5 5U /*!< SDIO function 5 */ +#define HAL_SDIO_FUNCTION_6 6U /*!< SDIO function 6 */ +#define HAL_SDIO_FUNCTION_7 7U /*!< SDIO function 7 */ +/** + * @} + */ + +/** @defgroup SDIO_Exported_Constansts_Group11 SDIO FBR definitions + * @{ + */ +#define HAL_SDIO_FBR_SUPPORT_CSA 1U /*!< SDIO function support CSA */ +#define HAL_SDIO_FBR_SUPPORT_POWER_SELECTION 1U /*!< SDIO function support power selection */ +/** + * @} + */ + +/** + * @} + */ +/* Exported macro ----------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Exported_macros SDIO Exported Macros + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +/** + * @brief Enable the SDIO device interrupt. + * @param __HANDLE__ SDIO Handle. + * @param __INTERRUPT__ specifies the SDMMC interrupt sources to be enabled. + * This parameter can be one or a combination of @ref SDMMC_LL_Interrupt_sources. + * @retval None + */ +#define __HAL_SDIO_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDMMC_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Disable the SDIO device interrupt. + * @param __HANDLE__ SDIO Handle. + * @param __INTERRUPT__ specifies the SDMMC interrupt sources to be disabled. + * This parameter can be one or a combination of @ref SDMMC_LL_Interrupt_sources. + * @retval None + */ +#define __HAL_SDIO_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDMMC_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Check whether the specified SDIO flag is set or not. + * @param __HANDLE__ SDIO Handle. + * @param __FLAG__ specifies the flag to check. + * This parameter can be one of @ref SDMMC_LL_Flags. + * @retval The new state of SDIO FLAG (SET or RESET). + */ +#define __HAL_SDIO_GET_FLAG(__HANDLE__, __FLAG__) __SDMMC_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) + +/** + * @brief Clear the SDIO's pending flags. + * @param __HANDLE__ SDIO Handle. + * @param __FLAG__ specifies the flag to clear. + * This parameter can be one or a combination of @ref SDMMC_LL_Flags. + * @retval None + */ +#define __HAL_SDIO_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDMMC_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) + +/** + * @brief Check whether the specified SDIO interrupt has occurred or not. + * @param __HANDLE__ SDIO Handle. + * @param __INTERRUPT__ specifies the SDMMC interrupt source to check. + * This parameter can be one of @ref SDMMC_LL_Interrupt_sources. + * @retval The new state of SDIO IT (SET or RESET). + */ +#define __HAL_SDIO_GET_IT(__HANDLE__, __INTERRUPT__) __SDMMC_GET_IT((__HANDLE__)->Instance, (__INTERRUPT__)) + +/** + * @brief Checks whether the specified SDIO interrupt is enabled or not. + * @param __HANDLE__ : SDIO handle. + * @param __INTERRUPT__ : specifies the SDMMC interrupt source to check. + * @retval The state of SDIO IT (SET or RESET). + */ +#define __HAL_SDIO_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) \ + __SDMMC_GET_IT_SOURCE((__HANDLE__)->Instance, (__INTERRUPT__)) +/** + * @} + */ + +/* Exported functions ------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Exported_Functions SDIO Exported Functions + * @{ + */ +/** @defgroup SDIO_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ +HAL_StatusTypeDef HAL_SDIO_Init(SDIO_HandleTypeDef *hsdio); +HAL_StatusTypeDef HAL_SDIO_DeInit(SDIO_HandleTypeDef *hsdio); + +void HAL_SDIO_MspInit(SDIO_HandleTypeDef *hsdio); +void HAL_SDIO_MspDeInit(SDIO_HandleTypeDef *hsdio); +/** + * @} + */ + +/** @defgroup SDIO_Exported_Functions_Group2 Peripheral Control functions + * @{ + */ +HAL_StatusTypeDef HAL_SDIO_SetDataBusWidth(SDIO_HandleTypeDef *hsdio, uint32_t BusWide); +HAL_StatusTypeDef HAL_SDIO_ConfigFrequency(SDIO_HandleTypeDef *hsdio, uint32_t ClockSpeed); + +HAL_StatusTypeDef HAL_SDIO_SetBlockSize(SDIO_HandleTypeDef *hsdio, uint8_t function_nbr, uint16_t BlockSize); +HAL_StatusTypeDef HAL_SDIO_SetSpeedMode(SDIO_HandleTypeDef *hsdio, uint32_t DataRate); + +HAL_StatusTypeDef HAL_SDIO_CardReset(SDIO_HandleTypeDef *hsdio); +HAL_StatusTypeDef HAL_SDIO_GetCardCommonControlRegister(SDIO_HandleTypeDef *hsdio, HAL_SDIO_CCCR_TypeDef *pCccr); +HAL_StatusTypeDef HAL_SDIO_GetCardFBRRegister(SDIO_HandleTypeDef *hsdio, HAL_SDIO_FBR_t *pFbr); +/** + * @} + */ + +/** @defgroup SDIO_Exported_Functions_Group3 Process functions + * @{ + */ +HAL_StatusTypeDef HAL_SDIO_ReadDirect(SDIO_HandleTypeDef *hsdio, HAL_SDIO_DirectCmd_TypeDef *Argument, uint8_t *pData); +HAL_StatusTypeDef HAL_SDIO_WriteDirect(SDIO_HandleTypeDef *hsdio, HAL_SDIO_DirectCmd_TypeDef *Argument, uint8_t Data); + +HAL_StatusTypeDef HAL_SDIO_ReadExtended(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte, uint32_t Timeout_Ms); + +HAL_StatusTypeDef HAL_SDIO_WriteExtended(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte, uint32_t Timeout_Ms); + +HAL_StatusTypeDef HAL_SDIO_ReadExtended_DMA(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte); + +HAL_StatusTypeDef HAL_SDIO_WriteExtended_DMA(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte); +/** + * @} + */ + +/** @defgroup SDIO_Exported_Functions_Group4 IRQHandler and callback functions + * @{ + */ +void HAL_SDIO_IRQHandler(SDIO_HandleTypeDef *hsdio); + +void HAL_SDIO_TxCpltCallback(SDIO_HandleTypeDef *hsdio); +void HAL_SDIO_RxCpltCallback(SDIO_HandleTypeDef *hsdio); +void HAL_SDIO_ErrorCallback(SDIO_HandleTypeDef *hsdio); +void HAL_SDIO_IOFunctionCallback(SDIO_HandleTypeDef *hsdio, uint32_t func); +#if (USE_SDIO_TRANSCEIVER != 0U) +/* Callback to switch in 1.8V mode */ +void HAL_SDIO_DriveTransceiver_1_8V_Callback(SDIO_HandleTypeDef *hsdio, FlagStatus status); +#endif /* USE_SDIO_TRANSCEIVER */ + +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) +HAL_StatusTypeDef HAL_SDIO_RegisterCallback(SDIO_HandleTypeDef *hsdio, HAL_SDIO_CallbackIDTypeDef CallbackID, + pSDIO_CallbackTypeDef pCallback); + +HAL_StatusTypeDef HAL_SDIO_UnRegisterCallback(SDIO_HandleTypeDef *hsdio, HAL_SDIO_CallbackIDTypeDef CallbackID); + +#if (USE_SDIO_TRANSCEIVER != 0U) +HAL_StatusTypeDef HAL_SDIO_RegisterTransceiverCallback(SDIO_HandleTypeDef *hsdio, + pSDIO_TransceiverCallbackTypeDef pCallback); +HAL_StatusTypeDef HAL_SDIO_UnRegisterTransceiverCallback(SDIO_HandleTypeDef *hsdio); +#endif /* USE_SDIO_TRANSCEIVER */ +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + +HAL_StatusTypeDef HAL_SDIO_RegisterIOFunctionCallback(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction, + HAL_SDIO_IOFunction_CallbackTypeDef Callback); +/** + * @} + */ + +/** @defgroup SDIO_Exported_Functions_Group5 Peripheral State and Errors functions + * @{ + */ +HAL_SDIO_StateTypeDef HAL_SDIO_GetState(const SDIO_HandleTypeDef *hsdio); +uint32_t HAL_SDIO_GetError(const SDIO_HandleTypeDef *hsdio); +/** + * @} + */ + +/** @defgroup SDIO_Exported_Functions_Group6 Peripheral IO interrupt + * @{ + */ +HAL_StatusTypeDef HAL_SDIO_EnableIOFunctionInterrupt(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction); +HAL_StatusTypeDef HAL_SDIO_DisableIOFunctionInterrupt(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction); + +HAL_StatusTypeDef HAL_SDIO_EnableIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction); +HAL_StatusTypeDef HAL_SDIO_DisableIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction); + +HAL_StatusTypeDef HAL_SDIO_SelectIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction); +HAL_StatusTypeDef HAL_SDIO_AbortIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction); + +HAL_StatusTypeDef HAL_SDIO_EnableIOAsynInterrupt(SDIO_HandleTypeDef *hsdio); +HAL_StatusTypeDef HAL_SDIO_DisableIOAsynInterrupt(SDIO_HandleTypeDef *hsdio); + +/** + * @} + */ + +/* Private types -----------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Types SDIO Private Types + * @{ + */ + +/** + * @} + */ + +/* Private defines ---------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Defines SDIO Private Defines + * @{ + */ + +/** + * @} + */ + +/* Private variables -------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Variables SDIO Private Variables + * @{ + */ + +/** + * @} + */ + +/* Private constants -------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Constants SDIO Private Constants + * @{ + */ + +/** + * @} + */ + +/* Private macros ----------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Macros SDIO Private Macros + * @{ + */ + +/** + * @} + */ + +/* Private functions prototypes --------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Functions_Prototypes SDIO Private Functions Prototypes + * @{ + */ + +/** + * @} + */ + +/* Private functions -------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Functions SDIO Private Functions + * @{ + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +#endif /* SDMMC1 || SDMMC2 */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* STM32U5xx_HAL_SDIO_H */ diff --git a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_dac.h b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_dac.h index 3b51e5f06..0b421c152 100644 --- a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_dac.h +++ b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_dac.h @@ -552,7 +552,7 @@ typedef struct * @arg @ref LL_DAC_RESOLUTION_8B * @retval DAC conversion data (unit: digital value) */ -#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__, __DAC_VOLTAGE__, __DAC_RESOLUTION__) \ +#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__, __DAC_VOLTAGE__, __DAC_RESOLUTION__) \ ((__DAC_VOLTAGE__) * __LL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ / (__VREFANALOG_VOLTAGE__) \ ) diff --git a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_sdmmc.h b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_sdmmc.h index 70cd548f2..f714f38b2 100644 --- a/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_sdmmc.h +++ b/stm32cube/stm32u5xx/drivers/include/stm32u5xx_ll_sdmmc.h @@ -61,10 +61,10 @@ typedef struct uint32_t ClockDiv; /*!< Specifies the clock frequency of the SDMMC controller. This parameter can be a value between Min_Data = 0 and Max_Data = 1023 */ -#if (USE_SD_TRANSCEIVER != 0U) +#if (USE_SD_TRANSCEIVER != 0U) || (USE_SDIO_TRANSCEIVER != 0U) uint32_t TranceiverPresent; /*!< Specifies if there is a 1V8 Transceiver/Switcher. This parameter can be a value of @ref SDMMC_LL_TRANSCEIVER_PRESENT */ -#endif /* USE_SD_TRANSCEIVER */ +#endif /* USE_SD_TRANSCEIVER || USE_SDIO_TRANSCEIVER */ } SDMMC_InitTypeDef; @@ -182,84 +182,128 @@ typedef struct #define SDMMC_ERROR_DMA ((uint32_t)0x40000000U) /*!< Error while DMA transfer */ #define SDMMC_ERROR_TIMEOUT ((uint32_t)0x80000000U) /*!< Timeout error */ +/** + * @brief Masks for R5 Response + */ +/** this is the reserved for future use in spec RFU */ +#define SDMMC_SDIO_R5_ERROR ((uint32_t)0x00000400U) +/** Out of range error */ +#define SDMMC_SDIO_R5_OUT_OF_RANGE ((uint32_t)0x00000100U) +/** Invalid function number */ +#define SDMMC_SDIO_R5_INVALID_FUNCTION_NUMBER ((uint32_t)0x00000200U) +/** General or an unknown error */ +#define SDMMC_SDIO_R5_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00000800U) +/** SDIO Card current state + * 00=DIS (card not selected) + * 01=CMD (data line free) + * 10=TRN (transfer on data lines) */ +#define SDMMC_SDIO_R5_IO_CURRENT_STATE ((uint32_t)0x00003000U) +/** Illegal command error */ +#define SDMMC_SDIO_R5_ILLEGAL_CMD ((uint32_t)0x00004000U) +/** CRC check of previous cmd failed */ +#define SDMMC_SDIO_R5_COM_CRC_FAILED ((uint32_t)0x00008000U) + +#define SDMMC_SDIO_R5_ERRORBITS (SDMMC_SDIO_R5_COM_CRC_FAILED | \ + SDMMC_SDIO_R5_ILLEGAL_CMD | \ + SDMMC_SDIO_R5_GENERAL_UNKNOWN_ERROR | \ + SDMMC_SDIO_R5_INVALID_FUNCTION_NUMBER | \ + SDMMC_SDIO_R5_OUT_OF_RANGE) +/** + * @brief SDIO_CMD53_MODE + */ +#define SDMMC_SDIO_MODE_BYTE 0x00U /*!< Byte Mode */ +#define SDMMC_SDIO_MODE_BLOCK 0x01U /*!< Block Mode */ + +/** + * @brief SDIO_CMD53_OP_CODE + */ +#define SDMMC_SDIO_NO_INC 0x00U /*!< No auto indentation */ +#define SDMMC_SDIO_AUTO_INC 0x01U /*!< Auto indentation */ + +/** + * @brief SDIO_CMD53_RAW + */ +#define SDMMC_SDIO_WO 0x00U /*!< Write only Flag */ +#define SDMMC_SDIO_RAW 0x01U /*!< Read after write Flag */ + /** * @brief SDMMC Commands Index */ -#define SDMMC_CMD_GO_IDLE_STATE ((uint8_t)0U) /*!< Resets the SD memory card. */ -#define SDMMC_CMD_SEND_OP_COND ((uint8_t)1U) /*!< Sends host capacity support information and activates the card's initialization process. */ -#define SDMMC_CMD_ALL_SEND_CID ((uint8_t)2U) /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ -#define SDMMC_CMD_SET_REL_ADDR ((uint8_t)3U) /*!< Asks the card to publish a new relative address (RCA). */ -#define SDMMC_CMD_SET_DSR ((uint8_t)4U) /*!< Programs the DSR of all cards. */ -#define SDMMC_CMD_SDMMC_SEN_OP_COND ((uint8_t)5U) /*!< Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line.*/ -#define SDMMC_CMD_HS_SWITCH ((uint8_t)6U) /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ -#define SDMMC_CMD_SEL_DESEL_CARD ((uint8_t)7U) /*!< Selects the card by its own relative address and gets deselected by any other address */ -#define SDMMC_CMD_HS_SEND_EXT_CSD ((uint8_t)8U) /*!< Sends SD Memory Card interface condition, which includes host supply voltage information and asks the card whether card supports voltage. */ -#define SDMMC_CMD_SEND_CSD ((uint8_t)9U) /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ -#define SDMMC_CMD_SEND_CID ((uint8_t)10U) /*!< Addressed card sends its card identification (CID) on the CMD line. */ -#define SDMMC_CMD_VOLTAGE_SWITCH ((uint8_t)11U) /*!< SD card Voltage switch to 1.8V mode. */ -#define SDMMC_CMD_STOP_TRANSMISSION ((uint8_t)12U) /*!< Forces the card to stop transmission. */ -#define SDMMC_CMD_SEND_STATUS ((uint8_t)13U) /*!< Addressed card sends its status register. */ -#define SDMMC_CMD_HS_BUSTEST_READ ((uint8_t)14U) /*!< Reserved */ -#define SDMMC_CMD_GO_INACTIVE_STATE ((uint8_t)15U) /*!< Sends an addressed card into the inactive state. */ -#define SDMMC_CMD_SET_BLOCKLEN ((uint8_t)16U) /*!< Sets the block length (in bytes for SDSC) for all following block commands (read, write, lock). Default block length is fixed to 512 Bytes. Not effective */ +#define SDMMC_CMD_GO_IDLE_STATE 0U /*!< Resets the SD memory card. */ +#define SDMMC_CMD_SEND_OP_COND 1U /*!< Sends host capacity support information and activates the card's initialization process. */ +#define SDMMC_CMD_ALL_SEND_CID 2U /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ +#define SDMMC_CMD_SET_REL_ADDR 3U /*!< Asks the card to publish a new relative address (RCA). */ +#define SDMMC_CMD_SET_DSR 4U /*!< Programs the DSR of all cards. */ +#define SDMMC_CMD_SDMMC_SEN_OP_COND 5U /*!< Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line.*/ +#define SDMMC_CMD_HS_SWITCH 6U /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ +#define SDMMC_CMD_SEL_DESEL_CARD 7U /*!< Selects the card by its own relative address and gets deselected by any other address */ +#define SDMMC_CMD_HS_SEND_EXT_CSD 8U /*!< Sends SD Memory Card interface condition, which includes host supply voltage information and asks the card whether card supports voltage. */ +#define SDMMC_CMD_SEND_CSD 9U /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ +#define SDMMC_CMD_SEND_CID 10U /*!< Addressed card sends its card identification (CID) on the CMD line. */ +#define SDMMC_CMD_VOLTAGE_SWITCH 11U /*!< SD card Voltage switch to 1.8V mode. */ +#define SDMMC_CMD_STOP_TRANSMISSION 12U /*!< Forces the card to stop transmission. */ +#define SDMMC_CMD_SEND_STATUS 13U /*!< Addressed card sends its status register. */ +#define SDMMC_CMD_HS_BUSTEST_READ 14U /*!< Reserved */ +#define SDMMC_CMD_GO_INACTIVE_STATE 15U /*!< Sends an addressed card into the inactive state. */ +#define SDMMC_CMD_SET_BLOCKLEN 16U /*!< Sets the block length (in bytes for SDSC) for all following block commands (read, write, lock). Default block length is fixed to 512 Bytes. Not effective */ /*!< for SDHS and SDXC. */ -#define SDMMC_CMD_READ_SINGLE_BLOCK ((uint8_t)17U) /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ -#define SDMMC_CMD_READ_MULT_BLOCK ((uint8_t)18U) /*!< Continuously transfers data blocks from card to host until interrupted by STOP_TRANSMISSION command. */ -#define SDMMC_CMD_HS_BUSTEST_WRITE ((uint8_t)19U) /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ -#define SDMMC_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20U) /*!< Speed class control command. */ -#define SDMMC_CMD_SET_BLOCK_COUNT ((uint8_t)23U) /*!< Specify block count for CMD18 and CMD25. */ -#define SDMMC_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24U) /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ -#define SDMMC_CMD_WRITE_MULT_BLOCK ((uint8_t)25U) /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ -#define SDMMC_CMD_PROG_CID ((uint8_t)26U) /*!< Reserved for manufacturers. */ -#define SDMMC_CMD_PROG_CSD ((uint8_t)27U) /*!< Programming of the programmable bits of the CSD. */ -#define SDMMC_CMD_SET_WRITE_PROT ((uint8_t)28U) /*!< Sets the write protection bit of the addressed group. */ -#define SDMMC_CMD_CLR_WRITE_PROT ((uint8_t)29U) /*!< Clears the write protection bit of the addressed group. */ -#define SDMMC_CMD_SEND_WRITE_PROT ((uint8_t)30U) /*!< Asks the card to send the status of the write protection bits. */ -#define SDMMC_CMD_SD_ERASE_GRP_START ((uint8_t)32U) /*!< Sets the address of the first write block to be erased. (For SD card only). */ -#define SDMMC_CMD_SD_ERASE_GRP_END ((uint8_t)33U) /*!< Sets the address of the last write block of the continuous range to be erased. */ -#define SDMMC_CMD_ERASE_GRP_START ((uint8_t)35U) /*!< Sets the address of the first write block to be erased. Reserved for each command system set by switch function command (CMD6). */ -#define SDMMC_CMD_ERASE_GRP_END ((uint8_t)36U) /*!< Sets the address of the last write block of the continuous range to be erased. Reserved for each command system set by switch function command (CMD6). */ -#define SDMMC_CMD_ERASE ((uint8_t)38U) /*!< Reserved for SD security applications. */ -#define SDMMC_CMD_FAST_IO ((uint8_t)39U) /*!< SD card doesn't support it (Reserved). */ -#define SDMMC_CMD_GO_IRQ_STATE ((uint8_t)40U) /*!< SD card doesn't support it (Reserved). */ -#define SDMMC_CMD_LOCK_UNLOCK ((uint8_t)42U) /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by the SET_BLOCK_LEN command. */ -#define SDMMC_CMD_APP_CMD ((uint8_t)55U) /*!< Indicates to the card that the next command is an application specific command rather than a standard command. */ -#define SDMMC_CMD_GEN_CMD ((uint8_t)56U) /*!< Used either to transfer a data block to the card or to get a data block from the card for general purpose/application specific commands. */ -#define SDMMC_CMD_NO_CMD ((uint8_t)64U) /*!< No command */ +#define SDMMC_CMD_READ_SINGLE_BLOCK 17U /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ +#define SDMMC_CMD_READ_MULT_BLOCK 18U /*!< Continuously transfers data blocks from card to host until interrupted by STOP_TRANSMISSION command. */ +#define SDMMC_CMD_HS_BUSTEST_WRITE 19U /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ +#define SDMMC_CMD_WRITE_DAT_UNTIL_STOP 20U /*!< Speed class control command. */ +#define SDMMC_CMD_SET_BLOCK_COUNT 23U /*!< Specify block count for CMD18 and CMD25. */ +#define SDMMC_CMD_WRITE_SINGLE_BLOCK 24U /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of fixed 512 bytes in case of SDHC and SDXC. */ +#define SDMMC_CMD_WRITE_MULT_BLOCK 25U /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ +#define SDMMC_CMD_PROG_CID 26U /*!< Reserved for manufacturers. */ +#define SDMMC_CMD_PROG_CSD 27U /*!< Programming of the programmable bits of the CSD. */ +#define SDMMC_CMD_SET_WRITE_PROT 28U /*!< Sets the write protection bit of the addressed group. */ +#define SDMMC_CMD_CLR_WRITE_PROT 29U /*!< Clears the write protection bit of the addressed group. */ +#define SDMMC_CMD_SEND_WRITE_PROT 30U /*!< Asks the card to send the status of the write protection bits. */ +#define SDMMC_CMD_SD_ERASE_GRP_START 32U /*!< Sets the address of the first write block to be erased. (For SD card only). */ +#define SDMMC_CMD_SD_ERASE_GRP_END 33U /*!< Sets the address of the last write block of the continuous range to be erased. */ +#define SDMMC_CMD_ERASE_GRP_START 35U /*!< Sets the address of the first write block to be erased. Reserved for each command system set by switch function command (CMD6). */ +#define SDMMC_CMD_ERASE_GRP_END 36U /*!< Sets the address of the last write block of the continuous range to be erased. Reserved for each command system set by switch function command (CMD6). */ +#define SDMMC_CMD_ERASE 38U /*!< Reserved for SD security applications. */ +#define SDMMC_CMD_FAST_IO 39U /*!< SD card doesn't support it (Reserved). */ +#define SDMMC_CMD_GO_IRQ_STATE 40U /*!< SD card doesn't support it (Reserved). */ +#define SDMMC_CMD_LOCK_UNLOCK 42U /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by the SET_BLOCK_LEN command. */ +#define SDMMC_CMD_APP_CMD 55U /*!< Indicates to the card that the next command is an application specific command rather than a standard command. */ +#define SDMMC_CMD_GEN_CMD 56U /*!< Used either to transfer a data block to the card or to get a data block from the card for general purpose/application specific commands. */ +#define SDMMC_CMD_NO_CMD 64U /*!< No command */ /** * @brief Following commands are SD Card Specific commands. * SDMMC_APP_CMD should be sent before sending these commands. */ -#define SDMMC_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6U) /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus widths are given in SCR register. */ -#define SDMMC_CMD_SD_APP_STATUS ((uint8_t)13U) /*!< (ACMD13) Sends the SD status. */ -#define SDMMC_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22U) /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with 32bit+CRC data block. */ -#define SDMMC_CMD_SD_APP_OP_COND ((uint8_t)41U) /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ -#define SDMMC_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42U) /*!< (ACMD42) Connect/Disconnect the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card */ -#define SDMMC_CMD_SD_APP_SEND_SCR ((uint8_t)51U) /*!< Reads the SD Configuration Register (SCR). */ -#define SDMMC_CMD_SDMMC_RW_DIRECT ((uint8_t)52U) /*!< For SD I/O card only, reserved for security specification. */ -#define SDMMC_CMD_SDMMC_RW_EXTENDED ((uint8_t)53U) /*!< For SD I/O card only, reserved for security specification. */ +#define SDMMC_CMD_APP_SD_SET_BUSWIDTH 6U /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus widths are given in SCR register. */ +#define SDMMC_CMD_SD_APP_STATUS 13U /*!< (ACMD13) Sends the SD status. */ +#define SDMMC_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS 22U /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with 32bit+CRC data block. */ +#define SDMMC_CMD_SD_APP_OP_COND 41U /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to send its operating condition register (OCR) content in the response on the CMD line. */ +#define SDMMC_CMD_SD_APP_SET_CLR_CARD_DETECT 42U /*!< (ACMD42) Connect/Disconnect the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card */ +#define SDMMC_CMD_SD_APP_SEND_SCR 51U /*!< Reads the SD Configuration Register (SCR). */ +#define SDMMC_CMD_SDMMC_RW_DIRECT 52U /*!< For SD I/O card only, reserved for security specification. */ +#define SDMMC_CMD_SDMMC_RW_EXTENDED 53U /*!< For SD I/O card only, reserved for security specification. */ /** * @brief Following commands are MMC Specific commands. */ -#define SDMMC_CMD_MMC_SLEEP_AWAKE ((uint8_t)5U) /*!< Toggle the device between Sleep state and Standby state. */ +#define SDMMC_CMD_MMC_SLEEP_AWAKE 5U /*!< Toggle the device between Sleep state and Standby state. */ /** * @brief Following commands are SD Card Specific security commands. * SDMMC_CMD_APP_CMD should be sent before sending these commands. */ -#define SDMMC_CMD_SD_APP_GET_MKB ((uint8_t)43U) -#define SDMMC_CMD_SD_APP_GET_MID ((uint8_t)44U) -#define SDMMC_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45U) -#define SDMMC_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46U) -#define SDMMC_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47U) -#define SDMMC_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48U) -#define SDMMC_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18U) -#define SDMMC_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25U) -#define SDMMC_CMD_SD_APP_SECURE_ERASE ((uint8_t)38U) -#define SDMMC_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49U) -#define SDMMC_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48U) +#define SDMMC_CMD_SD_APP_GET_MKB 43U +#define SDMMC_CMD_SD_APP_GET_MID 44U +#define SDMMC_CMD_SD_APP_SET_CER_RN1 45U +#define SDMMC_CMD_SD_APP_GET_CER_RN2 46U +#define SDMMC_CMD_SD_APP_SET_CER_RES2 47U +#define SDMMC_CMD_SD_APP_GET_CER_RES1 48U +#define SDMMC_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK 18U +#define SDMMC_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK 25U +#define SDMMC_CMD_SD_APP_SECURE_ERASE 38U +#define SDMMC_CMD_SD_APP_CHANGE_SECURE_AREA 49U +#define SDMMC_CMD_SD_APP_SECURE_WRITE_MKB 48U /** * @brief Masks for errors Card Status R1 (OCR Register) @@ -688,6 +732,82 @@ typedef struct * @} */ +/** @defgroup SDMMC_SDIO_CCCR_Registers + * @{ + */ +/*-------------------------------- CCCR0 ----------------------------------*/ +#define SDMMC_SDIO_CCCR0 0x000U /*!< SDIOS Card Common Control Register 0 */ +#define SDMMC_SDIO_CCCR0_SD_BYTE0 0x000U /*!< SDIOS Card Common Control Register 0 Byte 0 */ +#define SDMMC_SDIO_CCCR0_SD_BYTE1 0x001U /*!< SDIOS Card Common Control Register 0 Byte 1 */ +#define SDMMC_SDIO_CCCR0_SD_BYTE2 0x002U /*!< SDIOS Card Common Control Register 0 Byte 2 */ +#define SDMMC_SDIO_CCCR0_SD_BYTE3 0x003U /*!< SDIOS Card Common Control Register 0 Byte 3 */ + +/*-------------------------------- CCCR4 ----------------------------------*/ +#define SDMMC_SDIO_CCCR4 0x004U /*!< SDIOS Card Common Control Register 4 */ +#define SDMMC_SDIO_CCCR4_SD_BYTE0 0x004U /*!< SDIOS Card Common Control Register 4 Byte 0 */ +#define SDMMC_SDIO_CCCR4_SD_BYTE1 0x005U /*!< SDIOS Card Common Control Register 4 Byte 1 */ +#define SDMMC_SDIO_CCCR4_SD_BYTE2 0x006U /*!< SDIOS Card Common Control Register 4 Byte 2 */ +#define SDMMC_SDIO_CCCR4_SD_BYTE3 0x007U /*!< SDIOS Card Common Control Register 4 Byte 3 */ + +/*-------------------------------- CCCR8 ----------------------------------*/ +#define SDMMC_SDIO_CCCR8 0x008U /*!< SDIOS Card Common Control Register 8 */ +#define SDMMC_SDIO_CCCR8_SD_BYTE0 0x008U /*!< SDIOS Card Common Control Register 8 Byte 0 */ +#define SDMMC_SDIO_CCCR8_SD_BYTE1 0x009U /*!< SDIOS Card Common Control Register 8 Byte 1 */ +#define SDMMC_SDIO_CCCR8_SD_BYTE2 0x00AU /*!< SDIOS Card Common Control Register 8 Byte 2 */ +#define SDMMC_SDIO_CCCR8_SD_BYTE3 0x00BU /*!< SDIOS Card Common Control Register 8 Byte 3 */ + +/*-------------------------------- CCCR12 ---------------------------------*/ +#define SDMMC_SDIO_CCCR12 0x00CU /*!< SDIOS Card Common Control Register 12 */ +#define SDMMC_SDIO_CCCR12_SD_BYTE0 0x00CU /*!< SDIOS Card Common Control Register 12 Byte 0 */ +#define SDMMC_SDIO_CCCR12_SD_BYTE1 0x00DU /*!< SDIOS Card Common Control Register 12 Byte 1 */ +#define SDMMC_SDIO_CCCR12_SD_BYTE2 0x00EU /*!< SDIOS Card Common Control Register 12 Byte 2 */ +#define SDMMC_SDIO_CCCR12_SD_BYTE3 0x00FU /*!< SDIOS Card Common Control Register 12 Byte 3 */ + +/*-------------------------------- CCCR16 ---------------------------------*/ +#define SDMMC_SDIO_CCCR16 0x010U /*!< SDIOS Card Common Control Register 16 */ +#define SDMMC_SDIO_CCCR16_SD_BYTE0 0x010U /*!< SDIOS Card Common Control Register 16 Byte 0 */ +#define SDMMC_SDIO_CCCR16_SD_BYTE1 0x011U /*!< SDIOS Card Common Control Register 16 Byte 1 */ +#define SDMMC_SDIO_CCCR16_SD_BYTE2 0x012U /*!< SDIOS Card Common Control Register 16 Byte 2 */ +#define SDMMC_SDIO_CCCR16_SD_BYTE3 0x013U /*!< SDIOS Card Common Control Register 16 Byte 3 */ + +/*-------------------------------- CCCR20 ---------------------------------*/ +#define SDMMC_SDIO_CCCR20 0x014U /*!< SDIOS Card Common Control Register 20 */ +#define SDMMC_SDIO_CCCR20_SD_BYTE0 0x014U /*!< SDIOS Card Common Control Register 20 Byte 0 */ +#define SDMMC_SDIO_CCCR20_SD_BYTE1 0x015U /*!< SDIOS Card Common Control Register 20 Byte 1 */ +#define SDMMC_SDIO_CCCR20_SD_BYTE2 0x016U /*!< SDIOS Card Common Control Register 20 Byte 2 */ +#define SDMMC_SDIO_CCCR20_SD_BYTE3 0x017U /*!< SDIOS Card Common Control Register 20 Byte 3 */ + +/*-------------------------------- F1BR0 ----------------------------------*/ +#define SDMMC_SDIO_F1BR0 0x100U /*!< SDIOS Function 1 Basic Register 0 */ +#define SDMMC_SDIO_F1BR0_SD_BYTE0 0x100U /*!< SDIOS Function 1 Basic Register 0 Byte 0 */ +#define SDMMC_SDIO_F1BR0_SD_BYTE1 0x101U /*!< SDIOS Function 1 Basic Register 0 Byte 1 */ +#define SDMMC_SDIO_F1BR0_SD_BYTE2 0x102U /*!< SDIOS Function 1 Basic Register 0 Byte 2 */ +#define SDMMC_SDIO_F1BR0_SD_BYTE3 0x103U /*!< SDIOS Function 1 Basic Register 0 Byte 3 */ + +/*-------------------------------- F1BR8 ----------------------------------*/ +#define SDMMC_SDIO_F1BR8 0x108U /*!< SDIOS Function 1 Basic Register 8 */ +#define SDMMC_SDIO_F1BR8_SD_BYTE0 0x108U /*!< SDIOS Function 1 Basic Register 8 Byte 0 */ +#define SDMMC_SDIO_F1BR8_SD_BYTE1 0x109U /*!< SDIOS Function 1 Basic Register 8 Byte 1 */ +#define SDMMC_SDIO_F1BR8_SD_BYTE2 0x10AU /*!< SDIOS Function 1 Basic Register 8 Byte 2 */ +#define SDMMC_SDIO_F1BR8_SD_BYTE3 0x10BU /*!< SDIOS Function 1 Basic Register 8 Byte 3 */ + +/*-------------------------------- F1BR12 ---------------------------------*/ +#define SDMMC_SDIO_F1BR12 0x10CU /*!< SDIOS Function 1 Basic Register 12 */ +#define SDMMC_SDIO_F1BR12_SD_BYTE0 0x10CU /*!< SDIOS Function 1 Basic Register 12 Byte 0 */ +#define SDMMC_SDIO_F1BR12_SD_BYTE1 0x10DU /*!< SDIOS Function 1 Basic Register 12 Byte 1 */ +#define SDMMC_SDIO_F1BR12_SD_BYTE2 0x10EU /*!< SDIOS Function 1 Basic Register 12 Byte 2 */ +#define SDMMC_SDIO_F1BR12_SD_BYTE3 0x10FU /*!< SDIOS Function 1 Basic Register 12 Byte 3 */ + +/*-------------------------------- F1BR16 ---------------------------------*/ +#define SDMMC_SDIO_F1BR16 0x110U /*!< SDIOS Function 1 Basic Register 16 */ +#define SDMMC_SDIO_F1BR16_SD_BYTE0 0x110U /*!< SDIOS Function 1 Basic Register 16 Byte 0 */ +#define SDMMC_SDIO_F1BR16_SD_BYTE1 0x111U /*!< SDIOS Function 1 Basic Register 16 Byte 1 */ +#define SDMMC_SDIO_F1BR16_SD_BYTE2 0x112U /*!< SDIOS Function 1 Basic Register 16 Byte 2 */ +#define SDMMC_SDIO_F1BR16_SD_BYTE3 0x113U /*!< SDIOS Function 1 Basic Register 16 Byte 3 */ +/** + * @} + */ + /** * @} */ @@ -902,6 +1022,38 @@ typedef struct */ #define __SDMMC_GET_IT(__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STA &(__INTERRUPT__)) == (__INTERRUPT__)) +/** + * @brief Checks the source of specified interrupt. + * @param __INSTANCE__ Pointer to SDMMC register base + * @param __INTERRUPT__ specifies the SDMMC interrupt source to check. + * This parameter can be one of the following values: + * @arg SDMMC_IT_CCRCFAIL: Command response received (CRC check failed) interrupt + * @arg SDMMC_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt + * @arg SDMMC_IT_CTIMEOUT: Command response timeout interrupt + * @arg SDMMC_IT_DTIMEOUT: Data timeout interrupt + * @arg SDMMC_IT_TXUNDERR: Transmit FIFO underrun error interrupt + * @arg SDMMC_IT_RXOVERR: Received FIFO overrun error interrupt + * @arg SDMMC_IT_CMDREND: Command response received (CRC check passed) interrupt + * @arg SDMMC_IT_CMDSENT: Command sent (no response required) interrupt + * @arg SDMMC_IT_DATAEND: Data end (data counter, DATACOUNT, is zero) interrupt + * @arg SDMMC_IT_DHOLD: Data transfer Hold interrupt + * @arg SDMMC_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt + * @arg SDMMC_IT_DABORT: Data transfer aborted by CMD12 interrupt + * @arg SDMMC_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt + * @arg SDMMC_IT_RXFIFOHF: Receive FIFO Half Full interrupt + * @arg SDMMC_IT_RXFIFOF: Receive FIFO full interrupt + * @arg SDMMC_IT_TXFIFOE: Transmit FIFO empty interrupt + * @arg SDMMC_IT_BUSYD0END: End of SDMMC_D0 Busy following a CMD response detected interrupt + * @arg SDMMC_IT_SDIOIT: SDIO interrupt received interrupt + * @arg SDMMC_IT_ACKFAIL: Boot Acknowledgment received interrupt + * @arg SDMMC_IT_ACKTIMEOUT: Boot Acknowledgment timeout interrupt + * @arg SDMMC_IT_VSWEND: Voltage switch critical timing section completion interrupt + * @arg SDMMC_IT_CKSTOP: SDMMC_CK stopped in Voltage switch procedure interrupt + * @arg SDMMC_IT_IDMABTC: IDMA buffer transfer complete interrupt + * @retval The new state of SDMMC_IT (SET or RESET). + */ +#define __SDMMC_GET_IT_SOURCE(__INSTANCE__, __INTERRUPT__) (((__HANDLE__)->Instance->STA & (__INTERRUPT__))) + /** * @brief Clears the SDMMC's interrupt pending bits. * @param __INSTANCE__ Pointer to SDMMC register base @@ -1105,6 +1257,9 @@ uint32_t SDMMC_CmdOpCondition(SDMMC_TypeDef *SDMMCx, uint32_t Argument); uint32_t SDMMC_CmdSwitch(SDMMC_TypeDef *SDMMCx, uint32_t Argument); uint32_t SDMMC_CmdSendEXTCSD(SDMMC_TypeDef *SDMMCx, uint32_t Argument); uint32_t SDMMC_CmdBlockCount(SDMMC_TypeDef *SDMMCx, uint32_t BlockCount); +uint32_t SDMMC_SDIO_CmdReadWriteDirect(SDMMC_TypeDef *SDMMCx, uint32_t Argument, uint8_t *pResponse); +uint32_t SDMMC_SDIO_CmdReadWriteExtended(SDMMC_TypeDef *SDMMCx, uint32_t Argument); +uint32_t SDMMC_CmdSendOperationcondition(SDMMC_TypeDef *SDMMCx, uint32_t Argument, uint32_t *pResp); /** * @} */ @@ -1116,6 +1271,8 @@ uint32_t SDMMC_CmdBlockCount(SDMMC_TypeDef *SDMMCx, uint32_t BlockCount); uint32_t SDMMC_GetCmdResp1(SDMMC_TypeDef *SDMMCx, uint8_t SD_CMD, uint32_t Timeout); uint32_t SDMMC_GetCmdResp2(SDMMC_TypeDef *SDMMCx); uint32_t SDMMC_GetCmdResp3(SDMMC_TypeDef *SDMMCx); +uint32_t SDMMC_GetCmdResp4(SDMMC_TypeDef *SDMMCx, uint32_t *pResp); +uint32_t SDMMC_GetCmdResp5(SDMMC_TypeDef *SDMMCx, uint8_t SDIO_CMD, uint8_t *pData); uint32_t SDMMC_GetCmdResp6(SDMMC_TypeDef *SDMMCx, uint8_t SD_CMD, uint16_t *pRCA); uint32_t SDMMC_GetCmdResp7(SDMMC_TypeDef *SDMMCx); /** diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal.c index 512e1441e..f1136de67 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal.c @@ -52,10 +52,10 @@ * @{ */ /** - * @brief STM32U5xx HAL Driver version number 1.5.0 + * @brief STM32U5xx HAL Driver version number 1.6.0 */ #define __STM32U5xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ -#define __STM32U5xx_HAL_VERSION_SUB1 (0x05U) /*!< [23:16] sub1 version */ +#define __STM32U5xx_HAL_VERSION_SUB1 (0x06U) /*!< [23:16] sub1 version */ #define __STM32U5xx_HAL_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */ #define __STM32U5xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32U5xx_HAL_VERSION ((__STM32U5xx_HAL_VERSION_MAIN << 24U)\ diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_cortex.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_cortex.c index 12f66ec59..9b800dd12 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_cortex.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_cortex.c @@ -771,7 +771,7 @@ static void MPU_ConfigRegion(MPU_Type *MPUx, const MPU_Region_InitTypeDef *const MPUx->RNR = pMPU_RegionInit->Number; /* Disable the Region */ - CLEAR_BIT(MPU->RLAR, MPU_RLAR_EN_Msk); + CLEAR_BIT(MPUx->RLAR, MPU_RLAR_EN_Msk); MPUx->RBAR = (((uint32_t)pMPU_RegionInit->BaseAddress & 0xFFFFFFE0UL) | ((uint32_t)pMPU_RegionInit->IsShareable << MPU_RBAR_SH_Pos) | diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac.c index 4b6539454..cbfc1ac14 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac.c @@ -53,13 +53,13 @@ (DAC_TRIGGER_T1_TRGO, DAC_TRIGGER_T2_TRGO...) (#) Low Power Timers TRGO: LPTIM1 and LPTIM3 - (DAC_TRIGGER_LPTIM1_OUT, DAC_TRIGGER_LPTIM3_OUT) + (DAC_TRIGGER_LPTIM1_CH1, DAC_TRIGGER_LPTIM3_CH1) (#) Software using DAC_TRIGGER_SOFTWARE [..] The trigger selection depends on the PWR mode: in stop0, stop1 and stop2 we should select DAC_TRIGGER_EXT_IT9, - DAC_TRIGGER_LPTIM1_OUT or DAC_TRIGGER_LPTIM3_OUT.The other triggers + DAC_TRIGGER_LPTIM1_CH1 or DAC_TRIGGER_LPTIM3_CH1.The other triggers are not functional. *** DAC Buffer mode feature *** diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac_ex.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac_ex.c index 2d599c079..bda154194 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac_ex.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dac_ex.c @@ -756,8 +756,8 @@ HAL_StatusTypeDef HAL_DACEx_SelfCalibrate(DAC_HandleTypeDef *hdac, DAC_ChannelCo /* Init trimming counter */ /* Medium value */ - trimmingvalue = 16UL; - delta = 8UL; + trimmingvalue = 0x10UL; + delta = 0x08UL; while (delta != 0UL) { /* Set candidate trimming */ @@ -803,8 +803,12 @@ HAL_StatusTypeDef HAL_DACEx_SelfCalibrate(DAC_HandleTypeDef *hdac, DAC_ChannelCo if ((hdac->Instance->SR & (DAC_SR_CAL_FLAG1 << (Channel & 0x10UL))) == 0UL) { - /* Trimming is actually one value more */ - trimmingvalue++; + /* Check trimming value below maximum */ + if (trimmingvalue < 0x1FU) + { + /* Trimming is actually one value more */ + trimmingvalue++; + } /* Set right trimming */ MODIFY_REG(hdac->Instance->CCR, (DAC_CCR_OTRIM1 << (Channel & 0x10UL)), (trimmingvalue << (Channel & 0x10UL))); } @@ -877,8 +881,7 @@ HAL_StatusTypeDef HAL_DACEx_SetUserTrimming(DAC_HandleTypeDef *hdac, 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 Trimming value : range: 0->31 - * + * @retval TrimmingValue Value between Min_Data=0x00 and Max_Data=0x1F */ uint32_t HAL_DACEx_GetTrimOffset(const DAC_HandleTypeDef *hdac, uint32_t Channel) { diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dsi.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dsi.c index 435e9506f..cfe40f630 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dsi.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_dsi.c @@ -463,6 +463,9 @@ HAL_StatusTypeDef HAL_DSI_Init(DSI_HandleTypeDef *hdsi, DSI_PLLInitTypeDef *PLLI ((PLLInit->PLLIDF) << DSI_WRPCR_PLL_IDF_Pos) | \ ((PLLInit->PLLODF) << DSI_WRPCR_PLL_ODF_Pos)); + /* Set PLL Tuning */ + DSI_SetWrapperPLLTuning(hdsi, PLLInit); + /* Enable the DSI PLL */ __HAL_DSI_PLL_ENABLE(hdsi); @@ -498,9 +501,6 @@ HAL_StatusTypeDef HAL_DSI_Init(DSI_HandleTypeDef *hdsi, DSI_PLLInitTypeDef *PLLI /* Set Band Control Frequency and LPX Offset */ DSI_ConfigBandControl(hdsi); - /* Set PLL Tuning */ - DSI_SetWrapperPLLTuning(hdsi, PLLInit); - hdsi->Instance->PCTLR |= DSI_PCTLR_CKE; diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_mmc_ex.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_mmc_ex.c index 9f280388d..79589f4b7 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_mmc_ex.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_mmc_ex.c @@ -60,7 +60,6 @@ */ - /** @addtogroup MMCEx_Exported_Functions_Group1 * @brief Linked List management functions * @@ -427,7 +426,6 @@ HAL_StatusTypeDef HAL_MMCEx_DMALinkedList_WriteBlocks(MMC_HandleTypeDef *hmmc, M } - /** * @} */ diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_pka.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_pka.c index 52374e7d4..5618ef5b0 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_pka.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_pka.c @@ -276,6 +276,7 @@ * @{ */ #define PKA_RAM_SIZE 1334U +#define PKA_RAM_ERASE_TIMEOUT 1000U /* Private macro -------------------------------------------------------------*/ #define __PKA_RAM_PARAM_END(TAB,INDEX) do{ \ @@ -287,9 +288,6 @@ */ /* Private variables ---------------------------------------------------------*/ -static uint32_t primeordersize; -static uint32_t opsize; -static uint32_t modulussize; /* Private function prototypes -----------------------------------------------*/ /** @defgroup PKA_Private_Functions PKA Private Functions * @{ @@ -399,8 +397,22 @@ HAL_StatusTypeDef HAL_PKA_Init(PKA_HandleTypeDef *hpka) /* Set the state to busy */ hpka->State = HAL_PKA_STATE_BUSY; - /* Reset the control register and enable the PKA */ - hpka->Instance->CR = PKA_CR_EN; + /* Get current tick */ + tickstart = HAL_GetTick(); + + /* Reset the control register and enable the PKA (wait the end of PKA RAM erase) */ + while ((hpka->Instance->CR & PKA_CR_EN) != PKA_CR_EN) + { + hpka->Instance->CR = PKA_CR_EN; + + /* Check the Timeout */ + if ((HAL_GetTick() - tickstart) > PKA_RAM_ERASE_TIMEOUT) + { + /* Set timeout status */ + err = HAL_TIMEOUT; + break; + } + } /* Get current tick */ tickstart = HAL_GetTick(); @@ -502,12 +514,50 @@ __weak void HAL_PKA_MspInit(PKA_HandleTypeDef *hpka) */ __weak void HAL_PKA_MspDeInit(PKA_HandleTypeDef *hpka) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hpka); - - /* NOTE : This function should not be modified, when the callback is needed, + /* NOTE : This function should not be modified, the HAL_PKA_MspDeInit can be implemented in the user file + user should take into consideration PKA RAM erase when resetting PKA */ + uint32_t tickstart = HAL_GetTick(); + + /* Enable PKA reset state */ + __HAL_RCC_PKA_FORCE_RESET(); + + /* Release PKA from reset state */ + __HAL_RCC_PKA_RELEASE_RESET(); + + /* Wait the INITOK flag Setting */ + while (hpka->Instance->CR != PKA_CR_EN) + { + hpka->Instance->CR = PKA_CR_EN; + + /* Check for the Timeout */ + if ((HAL_GetTick() - tickstart) > PKA_RAM_ERASE_TIMEOUT) + { + /* update the state */ + hpka->State = HAL_PKA_STATE_ERROR; + } + } + + /* Get current tick */ + tickstart = HAL_GetTick(); + + /* Wait the INITOK flag Setting */ + if (PKA_WaitOnFlagUntilTimeout(hpka, PKA_SR_INITOK, RESET, tickstart, PKA_RAM_ERASE_TIMEOUT) != HAL_OK) + { + /* update the state */ + hpka->State = HAL_PKA_STATE_ERROR; + } + + /* Reset any pending flag */ + SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC | PKA_CLRFR_OPERRFC); + + /* PKA Periph clock disable */ + hpka->Instance->CR = 0; + __HAL_RCC_PKA_CLK_DISABLE(); + + /* PKA Periph IRQ disable */ + HAL_NVIC_DisableIRQ(PKA_IRQn); } #if (USE_HAL_PKA_REGISTER_CALLBACKS == 1) @@ -811,9 +861,7 @@ HAL_StatusTypeDef HAL_PKA_ModExp(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *i { /* Set input parameter in PKA RAM */ PKA_ModExp_Set(hpka, in); - - opsize = in->OpSize; - + hpka->opsize = in->OpSize; /* Start the operation */ return PKA_Process(hpka, PKA_MODE_MODULAR_EXP, Timeout); } @@ -828,9 +876,7 @@ HAL_StatusTypeDef HAL_PKA_ModExp_IT(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef { /* Set input parameter in PKA RAM */ PKA_ModExp_Set(hpka, in); - - opsize = in->OpSize; - + hpka->opsize = in->OpSize; /* Start the operation */ return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP); } @@ -846,9 +892,7 @@ HAL_StatusTypeDef HAL_PKA_ModExpFastMode(PKA_HandleTypeDef *hpka, PKA_ModExpFast { /* Set input parameter in PKA RAM */ PKA_ModExpFastMode_Set(hpka, in); - - opsize = in->OpSize; - + hpka->opsize = in->OpSize; /* Start the operation */ return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE, Timeout); } @@ -863,9 +907,7 @@ HAL_StatusTypeDef HAL_PKA_ModExpFastMode_IT(PKA_HandleTypeDef *hpka, PKA_ModExpF { /* Set input parameter in PKA RAM */ PKA_ModExpFastMode_Set(hpka, in); - - opsize = in->OpSize; - + hpka->opsize = in->OpSize; /* Start the operation */ return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE); } @@ -883,9 +925,7 @@ HAL_StatusTypeDef HAL_PKA_ModExpProtectMode(PKA_HandleTypeDef *hpka, PKA_ModExpP { /* Set input parameter in PKA RAM */ PKA_ModExpProtectMode_Set(hpka, in); - - opsize = in->OpSize; - + hpka->opsize = in->OpSize; return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_PROTECT, Timeout); } @@ -900,9 +940,7 @@ HAL_StatusTypeDef HAL_PKA_ModExpProtectMode_IT(PKA_HandleTypeDef *hpka, PKA_ModE { /* Set input parameter in PKA RAM */ PKA_ModExpProtectMode_Set(hpka, in); - - opsize = in->OpSize; - + hpka->opsize = in->OpSize; return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_PROTECT); } @@ -918,7 +956,7 @@ void HAL_PKA_ModExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes) uint32_t size; /* Get output result size */ - size = opsize; + size = hpka->opsize; /* Move the result to appropriate location (indicated in out parameter) */ PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_RESULT], size); @@ -935,9 +973,7 @@ HAL_StatusTypeDef HAL_PKA_ECDSASign(PKA_HandleTypeDef *hpka, PKA_ECDSASignInType { /* Set input parameter in PKA RAM */ PKA_ECDSASign_Set(hpka, in); - - primeordersize = in->primeOrderSize; - + hpka->primeordersize = in->primeOrderSize; /* Start the operation */ return PKA_Process(hpka, PKA_MODE_ECDSA_SIGNATURE, Timeout); } @@ -952,9 +988,7 @@ HAL_StatusTypeDef HAL_PKA_ECDSASign_IT(PKA_HandleTypeDef *hpka, PKA_ECDSASignInT { /* Set input parameter in PKA RAM */ PKA_ECDSASign_Set(hpka, in); - - primeordersize = in->primeOrderSize; - + hpka->primeordersize = in->primeOrderSize; /* Start the operation */ return PKA_Process_IT(hpka, PKA_MODE_ECDSA_SIGNATURE); } @@ -971,7 +1005,7 @@ void HAL_PKA_ECDSASign_GetResult(PKA_HandleTypeDef *hpka, PKA_ECDSASignOutTypeDe uint32_t size; /* Get output result size */ - size = primeordersize; + size = hpka->primeordersize; if (out != NULL) @@ -1132,9 +1166,7 @@ HAL_StatusTypeDef HAL_PKA_ECCMul(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *i { /* Set input parameter in PKA RAM */ PKA_ECCMul_Set(hpka, in); - - modulussize = in->modulusSize; - + hpka->modulussize = in->modulusSize; /* Start the operation */ return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout); } @@ -1149,9 +1181,7 @@ HAL_StatusTypeDef HAL_PKA_ECCMul_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef { /* Set input parameter in PKA RAM */ PKA_ECCMul_Set(hpka, in); - - modulussize = in->modulusSize; - + hpka->modulussize = in->modulusSize; /* Start the operation */ return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL); } @@ -1166,9 +1196,7 @@ HAL_StatusTypeDef HAL_PKA_ECCMulEx(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTypeDe { /* Set input parameter in PKA RAM */ PKA_ECCMulEx_Set(hpka, in); - - modulussize = in->modulusSize; - + hpka->modulussize = in->modulusSize; /* Start the operation */ return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout); } @@ -1183,9 +1211,7 @@ HAL_StatusTypeDef HAL_PKA_ECCMulEx_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulExInTyp { /* Set input parameter in PKA RAM */ PKA_ECCMulEx_Set(hpka, in); - - modulussize = in->modulusSize; - + hpka->modulussize = in->modulusSize; /* Start the operation */ return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL); } @@ -1200,7 +1226,7 @@ void HAL_PKA_ECCMul_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCMulOutTypeDef *out uint32_t size; /* Get output result size */ - size = modulussize; + size = hpka->modulussize; /* If a destination buffer is provided */ if (out != NULL) diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_sdio.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_sdio.c new file mode 100644 index 000000000..a2d420733 --- /dev/null +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_hal_sdio.c @@ -0,0 +1,2846 @@ +/** + ****************************************************************************** + * @file stm32u5xx_hal_sdio.c + * @author MCD Application Team + * @brief SDIO HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Secure Digital Input Output (SDIO) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2024 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + This driver implements a high level communication layer for read and write from/to + this SDIO card. The needed STM32 hardware resources (SDMMC and GPIO) are performed by + the user in HAL_SDIO_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 SDMMC memories which uses the HAL + SDMMC driver functions to interface with SDIO cards devices. + It is used as follows: + + (#)Initialize the SDMMC low level resources by implementing the HAL_SDIO_MspInit() API: + (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE(); + (##) SDMMC pins configuration for SDIO card + (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE(); + (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init() + and according to your pin assignment; + (##) NVIC configuration if you need to use interrupt process (HAL_SDIO_ReadExtended_DMA() + and HAL_SDIO_WriteExtended_DMA() APIs). + (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority(); + (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ() + (+++) SDMMC interrupts are managed using the macros __HAL_SDIO_ENABLE_IT() + and __HAL_SDIO_DISABLE_IT() inside the communication process. + (+++) SDMMC interrupts pending bits are managed using the macros __HAL_SDIO_GET_IT(). + (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used. + + (#) At this stage, you can perform SDIO read/write/erase operations after SDIO card initialization. + + *** SDIO Card Initialization and configuration *** + ================================================ + [..] + To initialize the SDIO Card, use the HAL_SDIO_Init() function. It Initializes + SDMMC Peripheral(STM32 side) and the SDIO Card, and put it into StandBy State (Ready for data transfer). + This function provide the following operations: + + (#) Apply the SDIO Card initialization process at 400KHz. You can change or adapt this + frequency by adjusting the "ClockDiv" field. + The SDIO Card frequency (SDMMC_CK) is computed as follows: + + SDMMC_CK = SDMMCCLK / (2 * ClockDiv) + + In initialization mode and according to the SDIO Card standard, + make sure that the SDMMC_CK frequency doesn't exceed 400KHz. + + This phase of initialization is done through SDMMC_Init() and + SDMMC_PowerState_ON() SDMMC low level APIs. + + (#) Initialize the SDIO card. The API used is HAL_SDIO_Init(). + This phase allows the card initialization and identification. + + (#) Configure the SDIO Card Data transfer frequency. You can change or adapt this + frequency by adjusting the "ClockDiv" field by the API HAL_SDIO_ConfigFrequency(). + + (#) Configure the SDIO Card in wide bus mode: 4-bits data by the API HAL_SDIO_SetDataBusWidth(). + + (#) Configure the SDIO Card data block size by the API : HAL_SDIO_SetBlockSize(). + + (#) Configure the SDIO Card speed mode by the API : HAL_SDIO_SetSpeedMode(). + + *** SDIO Card Read operation *** + ============================== + [..] + (+) You can read from SDIO card in polling mode by using function HAL_SDIO_ReadExtended(). + This function support only 2048-bytes block length (the block size should be + chosen by using the API HAL_SDIO_SetBlockSize). + + (+) You can read from SDIO card in DMA mode by using function HAL_SDIO_ReadExtended_DMA(). + This function support only 2048-bytes block length (the block size should be + chosen by using the API HAL_SDIO_SetBlockSize). + After this, you have to ensure that the transfer is done correctly. + You could also check the DMA transfer process through the SDIO Rx interrupt event. + + *** SDIO Card Write operation *** + =============================== + [..] + (+) You can write to SDIO card in polling mode by using function HAL_SDIO_WriteExtended(). + This function support only 2048-bytes block length (the block size should be + chosen by using the API HAL_SDIO_SetBlockSize). + + (+) You can write to SDIO card in DMA mode by using function HAL_SDIO_WriteExtended_DMA(). + This function support only 2048-bytes block length (the block size should be + chosen by using the API HAL_SDIO_SetBlockSize). + You could also check the DMA transfer process through the SDIO Tx interrupt event. + + + *** SDIO card common control register (CCCR) *** + ====================== + [..] + (+) The SDIO CCCR allow for quick host checking and control of an IO card's enable and interrupts on a per card and + per function basis. + To get the Card common control registers field, you can use the API HAL_SDIO_GetCardCommonControlRegister(). + + *** SDIO card Function basic register (FBR) *** + =========================== + [..] + (+) The SDIO card function basic register are used to allow the host to quickly determine the abilities and + requirements of each function. + (+) To get the SDIO function basic register information, you can use the API HAL_SDIO_GetCardFBRRegister(). + + *** SDIO HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SDIO HAL driver. + + (+) __HAL_SDIO_ENABLE_IT: Enable the SDIO device interrupt + (+) __HAL_SDIO_DISABLE_IT: Disable the SDIO device interrupt + (+) __HAL_SDIO_GET_FLAG: Check whether the specified SDIO flag is set or not + (+) __HAL_SDIO_CLEAR_FLAG: Clear the SDIO's pending flags + (+) __HAL_SDIO_GET_IT: Check whether the specified SDIO interrupt has occurred or not + (+) __HAL_SDIO_GET_IT_SOURCE: Checks whether the specified SDIO interrupt is enabled or not + + (@) You can refer to the SDIO HAL driver header file for more useful macros + + *** Callback registration *** + ============================================= + [..] + The compilation define USE_HAL_SDIO_REGISTER_CALLBACKS when set to 1 + allows the user to configure dynamically the driver callbacks. + + Use Functions HAL_SDIO_RegisterCallback() to register a user callback, + it allows to register following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) MspInitCallback : SDIO MspInit. + (+) MspDeInitCallback : SDIO MspDeInit. + This function takes as parameters the HAL peripheral handle, the Callback ID + and a pointer to the user callback function. + For specific callbacks TransceiverCallback use dedicated register callbacks: + respectively HAL_SDIO_RegisterTransceiverCallback(). + + Use function HAL_SDIO_UnRegisterCallback() to reset a callback to the default + weak (overridden) function. It allows to reset following callbacks: + (+) TxCpltCallback : callback when a transmission transfer is completed. + (+) RxCpltCallback : callback when a reception transfer is completed. + (+) ErrorCallback : callback when error occurs. + (+) MspInitCallback : SDIO MspInit. + (+) MspDeInitCallback : SDIO MspDeInit. + This function) takes as parameters the HAL peripheral handle and the Callback ID. + For specific callbacks TransceiverCallback use dedicated unregister callbacks: + respectively HAL_SDIO_UnRegisterTransceiverCallback(). + + By default, after the HAL_SDIO_Init and if the state is HAL_SDIO_STATE_RESET + all callbacks are reset to the corresponding legacy weak (overridden) functions. + Exception done for MspInit and MspDeInit callbacks that are respectively + reset to the legacy weak (overridden) functions in the HAL_SDIO_Init + and HAL_SDIO_DeInit only when these callbacks are null (not registered beforehand). + If not, MspInit or MspDeInit are not null, the HAL_SDIO_Init and HAL_SDIO_DeInit + keep and use the user MspInit/MspDeInit callbacks (registered beforehand) + + Callbacks can be registered/unregistered in READY state only. + Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered + in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used + during the Init/DeInit. + In that case first register the MspInit/MspDeInit user callbacks + using HAL_SDIO_RegisterCallback before calling HAL_SDIO_DeInit + or HAL_SDIO_Init function. + + When The compilation define USE_HAL_SDIO_REGISTER_CALLBACKS is set to 0 or + not defined, the callback registering feature is not available + and weak (overridden) callbacks are used. + + *** SDIO peripheral IO interrupt *** + ============================================= + [..] + (+) Below the list of most used SDIO function to check and control the IO card's enable and interrupts on a per + functions basis. + + (+) HAL_SDIO_EnableIOFunctionInterrupt: Enable SDIO IO interrupt. + (+) HAL_SDIO_DisableIOFunctionInterrupt: Disable SDIO IO interrupt. + (+) HAL_SDIO_EnableIOFunction: Enable Function number(0-7) + (+) HAL_SDIO_DisableIOFunction: Disable Function number(0-7) + (+) HAL_SDIO_SelectIOFunction: Select a function number(0-7) + (+) HAL_SDIO_AbortIOFunction: Abort an IO read or write operation and free the SDIO bus. + (+) HAL_SDIO_EnableIOAsynInterrupt: Enable Bit of asynchronous interrupt + (+) HAL_SDIO_DisableIOAsynInterrupt: Disable Bit of asynchronous interrupt + + @endverbatim + ****************************************************************************** + */ + +/* Includes ----------------------------------------------------------------------------------------------------------*/ +#include "stm32u5xx_hal.h" + +/** @addtogroup STM32U5xx_HAL_Driver + * @{ + */ + +/** @addtogroup SDIO + * @{ + */ +#if defined (SDMMC1) || defined (SDMMC2) +#ifdef HAL_SDIO_MODULE_ENABLED + +/* Private define ----------------------------------------------------------------------------------------------------*/ +/** @addtogroup SDIO_Private_Defines + * @{ + */ +#define SDIO_INIT_FREQ 400000U /*!< Initialization phase : 400 kHz max */ +#define SDIO_TIMEOUT 1000U /*!< SDIO timeout millisecond */ + +#define SDIO_FUNCTION_0 0x00U /*!< SDIO_Functions 0 */ +#define SDIO_FUNCTION_1 0x01U /*!< SDIO_Functions 1 */ + +#define SDIO_READ 0x0U /*!< Read flag for cmd52 and cmd53 */ +#define SDIO_WRITE 0x1U /*!< Write flag for cmd52 and cmd53 */ + +#define SDIO_BUS_SPEED_SDR12 0x00U /*!< SDIO bus speed mode SDR12 */ +#define SDIO_BUS_SPEED_SDR25 0x02U /*!< SDIO bus speed mode SDR25 */ +#define SDIO_BUS_SPEED_SDR50 0x04U /*!< SDIO bus speed mode SDR50 */ +#define SDIO_BUS_SPEED_DDR50 0x08U /*!< SDIO bus speed mode DDR50 */ + +#define SDIO_CCCR_REG_NUMBER 0x16U /*!< SDIO card cccr register number */ + +#define SDIO_OCR_VDD_32_33 (1U << 20U) +#define SDIO_OCR_SDIO_S18R (1U << 24U) +/** + * @} + */ + +/* Private macro -----------------------------------------------------------------------------------------------------*/ +#define IS_SDIO_RAW_FLAG(ReadAfterWrite) (((ReadAfterWrite) == HAL_SDIO_WRITE_ONLY) || \ + ((ReadAfterWrite) == HAL_SDIO_READ_AFTER_WRITE)) + +#define IS_SDIO_FUNCTION(FN) (((FN) >= HAL_SDIO_FUNCTION_1) && ((FN) <= HAL_SDIO_FUNCTION_7)) + +#define IS_SDIO_SUPPORTED_BLOCK_SIZE(BLOCKSIZE) (((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_1BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_2BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_4BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_8BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_16BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_32BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_64BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_128BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_256BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_1024BYTE) || \ + ((BLOCKSIZE) == HAL_SDIO_DATA_BLOCK_SIZE_2048BYTE)) + +/* Private functions -------------------------------------------------------------------------------------------------*/ +/** @defgroup SDIO_Private_Functions SDIO Private Functions + * @{ + */ +static HAL_StatusTypeDef SDIO_InitCard(SDIO_HandleTypeDef *hsdio); +static HAL_StatusTypeDef SDIO_ReadDirect(SDIO_HandleTypeDef *hsdio, uint32_t addr, uint32_t raw, uint32_t function_nbr, + uint8_t *pData); +static HAL_StatusTypeDef SDIO_WriteDirect(SDIO_HandleTypeDef *hsdio, uint32_t addr, uint32_t raw, uint32_t function_nbr, + uint8_t *pData); +static HAL_StatusTypeDef SDIO_WriteExtended(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *cmd_arg, + uint8_t *pData, uint16_t Size_byte); +static uint8_t SDIO_Convert_Block_Size(SDIO_HandleTypeDef *hsdio, uint32_t block_size); +static HAL_StatusTypeDef SDIO_IOFunction_IRQHandler(SDIO_HandleTypeDef *hsdio); +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup SDIO_Exported_Functions + * @{ + */ +/** @addtogroup SDIO_Exported_Functions_Group1 + * @brief Initialization and de-initialization functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to initialize/de-initialize the SDIO + device to be ready for use. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the SDIO according to the specified parameters in the + SDIO_HandleTypeDef and create the associated handle. + * @param hsdio: Pointer to the SDIO handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_Init(SDIO_HandleTypeDef *hsdio) +{ + SDIO_InitTypeDef Init; + uint32_t sdmmc_clk; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDMMC_ALL_INSTANCE(hsdio->Instance)); + assert_param(IS_SDMMC_CLOCK_EDGE(hsdio->Init.ClockEdge)); + assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hsdio->Init.ClockPowerSave)); + assert_param(IS_SDMMC_BUS_WIDE(hsdio->Init.BusWide)); + assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hsdio->Init.HardwareFlowControl)); + assert_param(IS_SDMMC_CLKDIV(hsdio->Init.ClockDiv)); + + /* Check the SDIO handle allocation */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_RESET) + { +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) + /* Reset Callback pointers in HAL_SDIO_STATE_RESET only */ + hsdio->TxCpltCallback = HAL_SDIO_TxCpltCallback; + hsdio->RxCpltCallback = HAL_SDIO_RxCpltCallback; + hsdio->ErrorCallback = HAL_SDIO_ErrorCallback; +#if (USE_SDIO_TRANSCEIVER != 0U) + if (hsdio->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT) + { + hsdio->DriveTransceiver_1_8V_Callback = HAL_SDIO_DriveTransceiver_1_8V_Callback; + } +#endif /* USE_SDIO_TRANSCEIVER */ + + if (hsdio->MspInitCallback == NULL) + { + hsdio->MspInitCallback = HAL_SDIO_MspInit; + } + /* Init the low level hardware */ + hsdio->MspInitCallback(hsdio); +#else + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_SDIO_MspInit(hsdio); +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + } + + Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; + Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; + Init.BusWide = SDMMC_BUS_WIDE_1B; + Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE; + + sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC); + if (sdmmc_clk == 0U) + { + hsdio->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER; + return HAL_ERROR; + } + Init.ClockDiv = sdmmc_clk / (2U * SDIO_INIT_FREQ); + /* Initialize SDMMC peripheral interface with default configuration */ + (void)SDMMC_Init(hsdio->Instance, Init); + + /* Set Power State to ON */ + (void)SDMMC_PowerState_ON(hsdio->Instance); + + /* wait 74 Cycles: required power up waiting time before starting the SDIO initialization sequence */ + sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv); + HAL_Delay(1U + (74U * 1000U / (sdmmc_clk))); + + if (SDIO_InitCard(hsdio) != HAL_OK) + { + hsdio->State = HAL_SDIO_STATE_RESET; + return HAL_ERROR; + } + + hsdio->Context = SDIO_CONTEXT_NONE; + hsdio->State = HAL_SDIO_STATE_READY; + + return HAL_OK; +} + +/** + * @brief De-Initializes the SDIO device. + * @param hsdio: Pointer to the SDIO handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_DeInit(SDIO_HandleTypeDef *hsdio) +{ + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(hsdio->Instance)); + + /* Check the SDIO handle allocation */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + /* Set Power State to OFF */ + (void)SDMMC_PowerState_OFF(hsdio->Instance); + +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) + if (hsdio->MspDeInitCallback == NULL) + { + hsdio->MspDeInitCallback = HAL_SDIO_MspDeInit; + } + + /* DeInit the low level hardware */ + hsdio->MspDeInitCallback(hsdio); +#else + /* De-Initialize the MSP layer */ + HAL_SDIO_MspDeInit(hsdio); +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Initializes the SDIO MSP. + * @param hsdio: Pointer to SDIO handle + * @retval None + */ +__weak void HAL_SDIO_MspInit(SDIO_HandleTypeDef *hsdio) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_MspInit could be implemented in the user file + */ +} + +/** + * @brief De-Initialize SDIO MSP. + * @param hsdio: Pointer to SDIO handle + * @retval None + */ +__weak void HAL_SDIO_MspDeInit(SDIO_HandleTypeDef *hsdio) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_MspDeInit could be implemented in the user file + */ +} +/** + * @} + */ + +/** @addtogroup SDIO_Exported_Functions_Group2 + * @brief + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to re-configure the SDIO peripheral. + +@endverbatim + * @{ + */ +/** + * @brief Enables wide bus operation for the requested card if supported by card. + * @param hsdio: Pointer to SDIO handle + * @param BusWide: Specifies the SDIO card wide bus mode + * This parameter can be one of the following values: + * @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer + * @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer + * @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_SetDataBusWidth(SDIO_HandleTypeDef *hsdio, uint32_t BusWide) +{ + uint8_t data; + HAL_StatusTypeDef error_state = HAL_OK; + + /* Check the parameters */ + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + data = (BusWide == HAL_SDIO_4_WIRES_MODE) ? 2U : 0U; + MODIFY_REG(hsdio->Instance->CLKCR, SDMMC_CLKCR_WIDBUS, + (BusWide == HAL_SDIO_4_WIRES_MODE) ? SDMMC_BUS_WIDE_4B : SDMMC_BUS_WIDE_1B); + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR4_SD_BYTE3, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &data) != HAL_OK) + { + error_state = HAL_ERROR; + } + } + else + { + error_state = HAL_ERROR; + } + + return error_state; +} + +/** + * @brief Update the SDIO Clock. + * @param hsdio: Pointer to SDIO handle. + * @param ClockSpeed: SDIO Clock speed. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_ConfigFrequency(SDIO_HandleTypeDef *hsdio, uint32_t ClockSpeed) +{ + uint32_t ClockDiv; + + /* Check the parameters */ + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + ClockDiv = (HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC)) / (2U * ClockSpeed); + MODIFY_REG(hsdio->Instance->CLKCR, SDMMC_CLKCR_CLKDIV, ClockDiv); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Set the SDIO block size. + * @param hsdio: Pointer to SDIO handle + * @param function_nbr: Specifies the SDIO function number. + * @param BlockSize: Specifies the SDIO Block size to set. + * This parameter can be one of the following values @ref SDIO_Exported_Constansts_Group7. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_SetBlockSize(SDIO_HandleTypeDef *hsdio, uint8_t function_nbr, uint16_t BlockSize) +{ + HAL_SDIO_ExtendedCmd_TypeDef cmd53; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(function_nbr)); + assert_param(IS_SDIO_SUPPORTED_BLOCK_SIZE(BlockSize)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + /* Set SDIO F1 block size */ + cmd53.IOFunctionNbr = SDIO_FUNCTION_0; + cmd53.OpCode = HAL_SDIO_OP_CODE_AUTO_INC; + cmd53.Block_Mode = HAL_SDIO_MODE_BYTE; + cmd53.Reg_Addr = (function_nbr * 0x100UL) + 0x10UL; + if (SDIO_WriteExtended(hsdio, &cmd53, (uint8_t *)(&BlockSize), 2U) != HAL_OK) + { + return HAL_ERROR; + } + + hsdio->block_size = BlockSize; + + return HAL_OK; +} + +/** + * @brief Configure the data rate. + * @param hsdio: Pointer to SDIO handle + * @param DataRate: Specifies the SDIO data rate to set. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_SetSpeedMode(SDIO_HandleTypeDef *hsdio, uint32_t DataRate) +{ + HAL_StatusTypeDef errorstate = HAL_OK; + uint8_t data; + + /* Check the parameters */ + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + switch (DataRate) + { + case HAL_SDIOS_DATA_RATE_SDR25: + data = SDIO_BUS_SPEED_SDR25; + errorstate = SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR16_SD_BYTE3, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &data); + break; + + case HAL_SDIOS_DATA_RATE_SDR50: + data = SDIO_BUS_SPEED_SDR50; + errorstate = SDIO_WriteDirect(hsdio, ((SDIO_FUNCTION_0 << 2U) | (SDIO_FUNCTION_0 << 1U) | (SDIO_FUNCTION_0 << 14U) + | SDMMC_SDIO_CCCR16_SD_BYTE3), HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &data); + MODIFY_REG(hsdio->Instance->CLKCR, SDMMC_CLKCR_BUSSPEED, SDMMC_CLKCR_BUSSPEED); + break; + + case HAL_SDIOS_DATA_RATE_DDR50: + data = SDIO_BUS_SPEED_DDR50; + errorstate = SDIO_WriteDirect(hsdio, ((SDIO_FUNCTION_0 << 2) | (SDIO_FUNCTION_0 << 1) | (SDIO_FUNCTION_0 << 14) | + SDMMC_SDIO_CCCR16_SD_BYTE3), HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &data); + MODIFY_REG(hsdio->Instance->CLKCR, SDMMC_CLKCR_DDR | SDMMC_CLKCR_BUSSPEED, + SDMMC_CLKCR_DDR | SDMMC_CLKCR_BUSSPEED); + break; + default: /* SDR12 */ + break; + } + + return (errorstate != HAL_OK) ? HAL_ERROR : HAL_OK; +} + +/** + * @brief Reset SDIO Card + * @param hsdio: Pointer to SDIO handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_CardReset(SDIO_HandleTypeDef *hsdio) +{ + uint8_t data = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + /** To reset the SDIO module by CMD52 with writing to RES in CCCR or send CMD0 the card shall change the speed mode + * default speed mode. + * The reset cmd (cmd0) is only used for memory. In order to reset an I/O card or the I/O portion of a combo card, + * Use CMD52 to write 1 to the RES bit in the CCC(bit3 of register 6). + */ + if (SDIO_WriteDirect(hsdio, ((SDIO_FUNCTION_0 << 2) | (SDIO_FUNCTION_0 << 1) | (SDIO_FUNCTION_0 << 14) | + SDMMC_SDIO_CCCR4_SD_BYTE2), + HAL_SDIO_WRITE_ONLY, + 0U, + &data) != HAL_OK) + { + return HAL_ERROR; + } + + hsdio->State = HAL_SDIO_STATE_RESET; + + return HAL_OK; +} + +/** + * @brief Get Card Common Control register (CCCR). + * @param hsdio: Pointer to SDIO handle. + * @param pCccr: Pointer to Cccr register. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_GetCardCommonControlRegister(SDIO_HandleTypeDef *hsdio, HAL_SDIO_CCCR_TypeDef *pCccr) +{ + uint8_t tempBuffer[256] = {0U}; + uint32_t count; + + assert_param(hsdio != NULL); + assert_param(pCccr != NULL); + + if ((hsdio == NULL) || (pCccr == NULL)) + { + return HAL_ERROR; + } + + for (count = 0U; count <= SDIO_CCCR_REG_NUMBER; count++) + { + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR0 + count, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &tempBuffer[count]) != + HAL_OK) + { + return HAL_ERROR; + } + } + + pCccr->cccr_revision = tempBuffer[0] & 0x0FU; + pCccr->sdio_revision = (tempBuffer[0] & 0xF0U) >> 4U; + pCccr->sd_spec_revision = tempBuffer[0x01U] & 0x0FU; + pCccr->bus_width_8Bit = ((tempBuffer[0x07U] & 0x04U) != 0U) ? HAL_SDIO_BUS_WIDTH_8BIT_SUPPORTED + : HAL_SDIO_BUS_WIDTH_8BIT_NOT_SUPPORTED; + pCccr->card_capability = (tempBuffer[0x08U] & 0xDFUL); + /* common CIS pointer */ + pCccr->commonCISPointer = tempBuffer[0x09U] | ((uint32_t)tempBuffer[(uint32_t)0x09U + 1U] << 8U) | + ((uint32_t)tempBuffer[(uint32_t)0x09U + 2U] << 16U); + + return HAL_OK; +} + +/** + * @brief Get Card Function Basic register(FBR). + * @param hsdio: Pointer to SDIO handle. + * @param pFbr: Pointer to Fbr register. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_GetCardFBRRegister(SDIO_HandleTypeDef *hsdio, HAL_SDIO_FBR_t *pFbr) +{ + uint8_t tempBuffer[256] = {0U}; + uint32_t count; + uint8_t func_idx; + + assert_param(hsdio != NULL); + assert_param(pFbr != NULL); + + if ((hsdio == NULL) || (pFbr == NULL)) + { + return HAL_ERROR; + } + + for (func_idx = 2U; func_idx <= SDIO_MAX_IO_NUMBER; func_idx++) + { + for (count = 0U; count <= SDIO_CCCR_REG_NUMBER; count++) + { + if (SDIO_ReadDirect(hsdio, (((uint32_t)SDMMC_SDIO_F1BR0 * (uint32_t)func_idx) + count), + HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &tempBuffer[count]) != HAL_OK) + { + return HAL_ERROR; + } + } + pFbr[(uint32_t)func_idx - 1U].ioStdFunctionCode = tempBuffer[0U] & 0x0FU; + pFbr[(uint32_t)func_idx - 1U].ioExtFunctionCode = tempBuffer[1U]; + pFbr[(uint32_t)func_idx - 1U].ioPointerToCIS = tempBuffer[9U] | ((uint32_t)tempBuffer[10U] << 8U) | + ((uint32_t)tempBuffer[11U] << 16U); + pFbr[(uint32_t)func_idx - 1U].ioPointerToCSA = tempBuffer[12U] | ((uint32_t)tempBuffer[13U] << 8U) | + ((uint32_t)tempBuffer[14U] << 16U); + if ((tempBuffer[2U] & 0x01U) != 0U) + { + pFbr[(uint32_t)func_idx - 1U].flags |= (uint8_t)HAL_SDIO_FBR_SUPPORT_POWER_SELECTION; + } + if ((tempBuffer[0U] & 0x40U) != 0U) + { + pFbr[(uint32_t)func_idx - 1U].flags |= (uint8_t)HAL_SDIO_FBR_SUPPORT_CSA; + } + } + + return HAL_OK; +} +/** + * @} + */ + +/** @addtogroup SDIO_Exported_Functions_Group3 + * @brief + * +@verbatim + ============================================================================== + ##### Data management functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the data transfer from/to SDIO card. + +@endverbatim + * @{ + */ +/** + * @brief Read data from a specified address using the direct mode through cmd52. + * @param hsdio: Pointer to SDIO handle + * @param Argument: Specifies the SDIO Argument. + * @param pData: pointer to the buffer that will contain the received data. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_ReadDirect(SDIO_HandleTypeDef *hsdio, HAL_SDIO_DirectCmd_TypeDef *Argument, uint8_t *pData) +{ + uint32_t cmd; + uint32_t errorstate; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(Argument != NULL); + assert_param(pData != NULL); + assert_param(IS_SDIO_RAW_FLAG(Argument->ReadAfterWrite)); + + if ((hsdio == NULL) || (Argument == NULL) || (NULL == pData)) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_BUSY; + + cmd = SDIO_READ << 31U; + cmd |= (((uint32_t)Argument->IOFunctionNbr) << 28U); + cmd |= (((uint32_t)Argument->ReadAfterWrite) << 27U); + cmd |= (Argument->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= 0U; + errorstate = SDMMC_SDIO_CmdReadWriteDirect(hsdio->Instance, cmd, pData); + + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + if (errorstate != (SDMMC_ERROR_ADDR_OUT_OF_RANGE | SDMMC_ERROR_ILLEGAL_CMD | SDMMC_ERROR_COM_CRC_FAILED | + SDMMC_ERROR_GENERAL_UNKNOWN_ERR)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + } + + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + hsdio->State = HAL_SDIO_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + + +/** + * @brief Read data from a specified address using the direct mode through cmd52. + * @param hsdio: Pointer to SDIO handle + * @param Argument: Specifies the SDIO Argument. + * @param Data: pointer to the buffer that will contain the received data. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_WriteDirect(SDIO_HandleTypeDef *hsdio, HAL_SDIO_DirectCmd_TypeDef *Argument, uint8_t Data) +{ + uint32_t cmd; + uint32_t errorstate; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(Argument != NULL); + assert_param(IS_SDIO_RAW_FLAG(Argument->ReadAfterWrite)); + + if ((hsdio == NULL) || (Argument == NULL)) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_BUSY; + + cmd = SDIO_WRITE << 31U; + cmd |= ((uint32_t)Argument->IOFunctionNbr) << 28U; + cmd |= ((uint32_t)Argument->ReadAfterWrite) << 27U; + cmd |= (Argument->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= Data; + errorstate = SDMMC_SDIO_CmdReadWriteDirect(hsdio->Instance, cmd, &Data); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + if (errorstate != (SDMMC_ERROR_ADDR_OUT_OF_RANGE | SDMMC_ERROR_ILLEGAL_CMD | SDMMC_ERROR_COM_CRC_FAILED | + SDMMC_ERROR_GENERAL_UNKNOWN_ERR)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + } + + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + hsdio->State = HAL_SDIO_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Read data from a specified address using extended mode through cmd53. + * @param hsdio: Pointer to SDIO handle + * @param Argument: Pointer to SDIO argument + * @param pData: pointer to the buffer that will contain the data to transmit + * @param Size_byte: size to read. + * @param Timeout_Ms: Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_ReadExtended(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte, uint32_t Timeout_Ms) +{ + uint32_t cmd; + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t regCount; + uint8_t byteCount; + uint32_t data; + uint32_t dataremaining; + uint8_t *tempbuff = pData; + uint32_t nbr_of_block; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(Argument != NULL); + assert_param(pData != NULL); + + if ((hsdio == NULL) || (Argument == NULL) || (pData == NULL)) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_BUSY; + + /* Compute how many blocks are to be send for pData of length data_size to be send */ + nbr_of_block = (Size_byte & ~(hsdio->block_size & 1U)) >> __CLZ(__RBIT(hsdio->block_size)); + + /* Initialize data control register */ + if ((hsdio->Instance->DCTRL & SDMMC_DCTRL_SDIOEN) != 0U) + { + hsdio->Instance->DCTRL = SDMMC_DCTRL_SDIOEN; + } + else + { + hsdio->Instance->DCTRL = 0U; + } + + /* Configure the SDIO DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + /* (HAL_SDIO_MODE_BLOCK << 27) corresponds to the block mode bit of the CMD argument */ + if (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) + { + /* (Argument & 0x1FFU) is to get the 9 bits of Block/Byte counts */ + config.DataLength = (uint32_t)(nbr_of_block * hsdio->block_size); + config.DataBlockSize = SDIO_Convert_Block_Size(hsdio, hsdio->block_size); + } + else + { + /* (Argument & 0x1FFU) is to get the 9 bits of Block/Byte counts */ + config.DataLength = (Size_byte > 0U) ? Size_byte : HAL_SDIO_DATA_BLOCK_SIZE_512BYTE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_1B; + } + + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC ; + /* (HAL_SDIO_MODE_BLOCK << 27) corresponds to the block mode bit of the CMD argument */ + config.TransferMode = (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDMMC_TRANSFER_MODE_BLOCK : + SDMMC_TRANSFER_MODE_SDIO; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsdio->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hsdio->Instance); + + /* Correspond to the write or read bit of the CMD argument */ + /* Read */ + hsdio->Context = (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDIO_CONTEXT_READ_MULTIPLE_BLOCK : + SDIO_CONTEXT_READ_SINGLE_BLOCK; + cmd = SDIO_READ << 31U; + cmd |= Argument->IOFunctionNbr << 28U; + cmd |= Argument->Block_Mode << 27U; + cmd |= Argument->OpCode << 26U; + cmd |= (Argument->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= (Size_byte & 0x1FFU); + errorstate = SDMMC_SDIO_CmdReadWriteExtended(hsdio->Instance, cmd); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + if (errorstate != (SDMMC_ERROR_ADDR_OUT_OF_RANGE | SDMMC_ERROR_ILLEGAL_CMD | SDMMC_ERROR_COM_CRC_FAILED | + SDMMC_ERROR_GENERAL_UNKNOWN_ERR)) + { + MODIFY_REG(hsdio->Instance->DCTRL, SDMMC_DCTRL_FIFORST, SDMMC_DCTRL_FIFORST); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + } + /* (SDIO_WRITE << 31) correspond to the write or read bit of the CMD argument */ + /* Poll on SDMMC flags */ + dataremaining = config.DataLength; + + while (!__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | + SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND)) + { + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= 32U)) + { + /* Read data from SDMMC Rx FIFO */ + for (regCount = 0U; regCount < 8U; regCount++) + { + data = SDMMC_ReadFIFO(hsdio->Instance); + *tempbuff = (uint8_t)(data & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 8U) & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 16U) & 0xFFU); + tempbuff++; + *tempbuff = (uint8_t)((data >> 24U) & 0xFFU); + tempbuff++; + } + dataremaining -= 32U; + } + else if (dataremaining < 32U) + { + while ((dataremaining > 0U) && !(__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_RXFIFOE))) + { + data = SDMMC_ReadFIFO(hsdio->Instance); + for (byteCount = 0U; byteCount < 4U; byteCount++) + { + if (dataremaining > 0U) + { + *tempbuff = (uint8_t)((data >> (byteCount * 8U)) & 0xFFU); + tempbuff++; + dataremaining--; + } + } + } + } + else + { + /* Nothing to do */ + } + if ((HAL_GetTick() - tickstart) >= Timeout_Ms) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_TIMEOUT; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_TIMEOUT; + } + } + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + /* Get error state */ + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_DATA_TIMEOUT; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_DATA_CRC_FAIL; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_RXOVERR)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + /* (SDIO_WRITE << 31) correspond to the write or read bit of the CMD argument */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_RX_OVERRUN; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (hsdio->ErrorCode == SDMMC_ERROR_INVALID_PARAMETER) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + hsdio->State = HAL_SDIO_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Write data from a specified address using extended mode through cmd53. + * @param hsdio: Pointer to SDIO handle + * @param Argument: Pointer to SDIO argument + * @param pData: pointer to the buffer that will contain the data to transmit + * @param Size_byte: Block size to write. + * @param Timeout_Ms: Specify timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_WriteExtended(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte, uint32_t Timeout_Ms) +{ + uint32_t cmd; + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t regCount; + uint8_t byteCount; + uint32_t data; + uint32_t dataremaining; + uint8_t *u32tempbuff = pData; + uint32_t nbr_of_block; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(Argument != NULL); + assert_param(pData != NULL); + + if ((hsdio == NULL) || (Argument == NULL) || (pData == NULL)) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_BUSY; + + /* Compute how many blocks are to be send for pData of length data_size to be send */ + nbr_of_block = (Size_byte & ~(hsdio->block_size & 1U)) >> __CLZ(__RBIT(hsdio->block_size)); + + /* Initialize data control register */ + if ((hsdio->Instance->DCTRL & SDMMC_DCTRL_SDIOEN) != 0U) + { + hsdio->Instance->DCTRL = SDMMC_DCTRL_SDIOEN; + } + else + { + hsdio->Instance->DCTRL = 0U; + } + + /* Configure the SDIO DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + if (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) + { + config.DataLength = (uint32_t)(nbr_of_block * hsdio->block_size); + config.DataBlockSize = SDIO_Convert_Block_Size(hsdio, hsdio->block_size); + } + else + { + config.DataLength = (Size_byte > 0U) ? Size_byte : HAL_SDIO_DATA_BLOCK_SIZE_512BYTE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_1B; + } + + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + /* (HAL_SDIO_MODE_BLOCK << 27) corresponds to the block mode bit of the CMD argument */ + config.TransferMode = (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDMMC_TRANSFER_MODE_BLOCK : + SDMMC_TRANSFER_MODE_SDIO; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsdio->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hsdio->Instance); + + /* Correspond to the write or read bit of the CMD argument */ + hsdio->Context = (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDIO_CONTEXT_WRITE_MULTIPLE_BLOCK : + SDIO_CONTEXT_WRITE_SINGLE_BLOCK; + cmd = SDIO_WRITE << 31U; + cmd |= Argument->IOFunctionNbr << 28U; + cmd |= Argument->Block_Mode << 27U; + cmd |= Argument->OpCode << 26U; + cmd |= (Argument->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= (Size_byte & 0x1FFU); + errorstate = SDMMC_SDIO_CmdReadWriteExtended(hsdio->Instance, cmd); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + if (errorstate != (SDMMC_ERROR_ADDR_OUT_OF_RANGE | SDMMC_ERROR_ILLEGAL_CMD | SDMMC_ERROR_COM_CRC_FAILED | + SDMMC_ERROR_GENERAL_UNKNOWN_ERR)) + { + MODIFY_REG(hsdio->Instance->DCTRL, SDMMC_DCTRL_FIFORST, SDMMC_DCTRL_FIFORST); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + } + /* Write block(s) in polling mode */ + dataremaining = config.DataLength; + while (!__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | + SDMMC_FLAG_DATAEND)) + { + + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= 32U)) + { + /* Read data from SDMMC Rx FIFO */ + for (regCount = 0U; regCount < 8U; regCount++) + { + hsdio->Instance->FIFO = *u32tempbuff; + u32tempbuff++; + } + dataremaining -= 32U; + } + else if ((dataremaining < 32U) && (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXFIFOHE | SDMMC_FLAG_TXFIFOE))) + { + uint8_t *u8buff = (uint8_t *)u32tempbuff; + while (dataremaining > 0U) + { + data = 0U; + for (byteCount = 0U; (byteCount < 4U) && (dataremaining > 0U); byteCount++) + { + data |= ((uint32_t)(*u8buff) << (byteCount << 3U)); + u8buff++; + dataremaining--; + } + hsdio->Instance->FIFO = data; + } + } + if (((HAL_GetTick() - tickstart) >= Timeout_Ms)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_TIMEOUT; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_TIMEOUT; + } + } + + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + /* Get error state */ + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DTIMEOUT)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_DATA_TIMEOUT; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DCRCFAIL)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_DATA_CRC_FAIL; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXUNDERR)) + { + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + /* (SDIO_WRITE << 31) correspond to the write or read bit of the CMD argument */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_TX_UNDERRUN; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (hsdio->ErrorCode == SDMMC_ERROR_INVALID_PARAMETER) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + hsdio->State = HAL_SDIO_STATE_READY; + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Read data from a specified address using extended mode through cmd53 in DMA mode. + * @param hsdio: Pointer to SDIO handle + * @param Argument: Pointer to SDIO argument + * @param pData: pointer to the buffer that will contain the data to transmit + * @param Size_byte: Block size to write. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_ReadExtended_DMA(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint8_t *p_dma_buffer; + uint32_t cmd; + uint32_t nbr_of_block; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(Argument != NULL); + assert_param(pData != NULL); + + if ((hsdio == NULL) || (Argument == NULL) || (pData == NULL)) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_BUSY; + + /* Initialize data control register */ + if ((hsdio->Instance->DCTRL & SDMMC_DCTRL_SDIOEN) != 0U) + { + hsdio->Instance->DCTRL = SDMMC_DCTRL_SDIOEN; + } + else + { + hsdio->Instance->DCTRL = 0U; + } + + p_dma_buffer = (uint8_t *)pData; + hsdio->pRxBuffPtr = (uint8_t *)pData; + hsdio->RxXferSize = Size_byte; + hsdio->next_data_addr = (uint32_t)pData; + + /* Compute how many blocks are to be send for pData of length data_size to be send */ + nbr_of_block = (Size_byte & ~(hsdio->block_size & 1U)) >> __CLZ(__RBIT(hsdio->block_size)); + + if (nbr_of_block != 0U) + { + hsdio->remaining_data = (Size_byte - (hsdio->block_size * nbr_of_block)); + hsdio->next_reg_addr = (Argument->Reg_Addr) | ((((nbr_of_block * hsdio->block_size) >> 1U) & 0x3FFFU) << 1U) + | ((hsdio->remaining_data <= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? 1U : 0U); + hsdio->next_data_addr += (nbr_of_block * hsdio->block_size); + } + else + { + hsdio->next_data_addr += (Size_byte < HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? Size_byte : + HAL_SDIO_DATA_BLOCK_SIZE_512BYTE; + if (hsdio->remaining_data != 0U) + { + hsdio->remaining_data = (Size_byte >= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? + (Size_byte - HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) : + (Size_byte - hsdio->remaining_data); + hsdio->next_reg_addr += (Size_byte >= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? \ + (HAL_SDIO_DATA_BLOCK_SIZE_512BYTE + 1U) : (Size_byte + 1U); + } + } + + /* DMA configuration (use single buffer) */ + hsdio->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; + hsdio->Instance->IDMABASER = (uint32_t)p_dma_buffer; + + /* Configure the SD DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + if (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) + { + config.DataLength = (uint32_t)(nbr_of_block * hsdio->block_size); + config.DataBlockSize = SDIO_Convert_Block_Size(hsdio, hsdio->block_size); + } + else + { + config.DataLength = (Size_byte > 0U) ? Size_byte : HAL_SDIO_DATA_BLOCK_SIZE_512BYTE; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_1B; + } + + config.TransferDir = SDMMC_TRANSFER_DIR_TO_SDMMC ; + config.TransferMode = (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDMMC_TRANSFER_MODE_BLOCK : + SDMMC_TRANSFER_MODE_SDIO; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsdio->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hsdio->Instance); + + /* Read */ + hsdio->Context = (uint32_t)((Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDIO_CONTEXT_READ_MULTIPLE_BLOCK : + SDIO_CONTEXT_READ_SINGLE_BLOCK) | SDIO_CONTEXT_DMA; + + cmd = SDIO_READ << 31U; + cmd |= Argument->IOFunctionNbr << 28U; + cmd |= Argument->Block_Mode << 27U; + cmd |= Argument->OpCode << 26U; + cmd |= (Argument->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= ((nbr_of_block == 0U) ? Size_byte : nbr_of_block) & 0x1FFU; + errorstate = SDMMC_SDIO_CmdReadWriteExtended(hsdio->Instance, cmd); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + if (errorstate != (SDMMC_ERROR_ADDR_OUT_OF_RANGE | SDMMC_ERROR_ILLEGAL_CMD | SDMMC_ERROR_COM_CRC_FAILED | + SDMMC_ERROR_GENERAL_UNKNOWN_ERR)) + { + MODIFY_REG(hsdio->Instance->DCTRL, SDMMC_DCTRL_FIFORST, SDMMC_DCTRL_FIFORST); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + } + /* Enable interrupt */ + __HAL_SDIO_ENABLE_IT(hsdio, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND)); + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Write data from a specified address using extended mode through cmd53 in DMA mode. + * @param hsdio: Pointer to SDIO handle + * @param Argument: Pointer to SDIO argument + * @param pData: pointer to the buffer that will contain the data to transmit + * @param Size_byte: Block size to write. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_WriteExtended_DMA(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *Argument, + uint8_t *pData, uint32_t Size_byte) +{ + uint32_t cmd; + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint8_t *p_dma_buffer; + uint32_t nbr_of_block; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(Argument != NULL); + assert_param(pData != NULL); + + if ((hsdio == NULL) || (Argument == NULL) || (pData == NULL)) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + hsdio->State = HAL_SDIO_STATE_BUSY; + + /* Initialize data control register */ + if ((hsdio->Instance->DCTRL & SDMMC_DCTRL_SDIOEN) != 0U) + { + hsdio->Instance->DCTRL = SDMMC_DCTRL_SDIOEN; + } + else + { + hsdio->Instance->DCTRL = 0U; + } + + p_dma_buffer = (uint8_t *)pData; + hsdio->pTxBuffPtr = (uint8_t *)pData; + hsdio->TxXferSize = Size_byte; + hsdio->next_data_addr = (uint32_t)pData; + + nbr_of_block = (Size_byte & ~(hsdio->block_size & 1U)) >> __CLZ(__RBIT(hsdio->block_size)); + + if (nbr_of_block != 0U) + { + hsdio->remaining_data = (Size_byte - (hsdio->block_size * nbr_of_block)); + if (hsdio->block_size <= 128U) + { + hsdio->next_reg_addr = (Argument->Reg_Addr) | + ((((nbr_of_block * hsdio->block_size) >> 1U) & 0x3FFFU) << 1U) | + ((hsdio->remaining_data <= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? 1U : 0U); + } + else + { + hsdio->next_reg_addr = (nbr_of_block * hsdio->block_size) >> 1U; + } + hsdio->next_data_addr += (nbr_of_block * hsdio->block_size); + } + else + { + hsdio->remaining_data = (Size_byte >= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? + (Size_byte - HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) : + (Size_byte - hsdio->remaining_data); + if (hsdio->remaining_data != 0U) + { + hsdio->remaining_data = (Size_byte >= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? + (Size_byte - HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) : + (Size_byte - hsdio->remaining_data); + hsdio->next_reg_addr += ((Size_byte >= HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? \ + (HAL_SDIO_DATA_BLOCK_SIZE_512BYTE >> 1U) : (Size_byte >> 1U)) | + (((hsdio->remaining_data > 0U) ? 0U : 1U)); + } + hsdio->next_data_addr += (Size_byte < HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? Size_byte : + HAL_SDIO_DATA_BLOCK_SIZE_512BYTE; + } + + /* DMA configuration (use single buffer) */ + hsdio->Instance->IDMACTRL = SDMMC_ENABLE_IDMA_SINGLE_BUFF; + hsdio->Instance->IDMABASER = (uint32_t)p_dma_buffer; + + /* Configure the SDIO DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + if (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) + { + config.DataLength = (uint32_t)(nbr_of_block * hsdio->block_size); + config.DataBlockSize = SDIO_Convert_Block_Size(hsdio, hsdio->block_size); + } + else + { + config.DataLength = (Size_byte > HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? HAL_SDIO_DATA_BLOCK_SIZE_512BYTE : Size_byte; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_1B; + } + + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = (Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDMMC_TRANSFER_MODE_BLOCK + : SDMMC_TRANSFER_MODE_SDIO; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsdio->Instance, &config); + + __SDMMC_CMDTRANS_ENABLE(hsdio->Instance); + + /* Write */ + hsdio->Context = (uint32_t)((Argument->Block_Mode == HAL_SDIO_MODE_BLOCK) ? + SDIO_CONTEXT_WRITE_MULTIPLE_BLOCK : + SDIO_CONTEXT_WRITE_SINGLE_BLOCK) | SDIO_CONTEXT_DMA; + cmd = SDIO_WRITE << 31U; + cmd |= Argument->IOFunctionNbr << 28U; + cmd |= Argument->Block_Mode << 27U; + cmd |= Argument->OpCode << 26U; + cmd |= (Argument->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= ((nbr_of_block == 0U) ? ((Size_byte > HAL_SDIO_DATA_BLOCK_SIZE_512BYTE) ? + HAL_SDIO_DATA_BLOCK_SIZE_512BYTE : Size_byte) : nbr_of_block) & 0x1FFU; + errorstate = SDMMC_SDIO_CmdReadWriteExtended(hsdio->Instance, cmd); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + if (errorstate != (SDMMC_ERROR_ADDR_OUT_OF_RANGE | SDMMC_ERROR_ILLEGAL_CMD | SDMMC_ERROR_COM_CRC_FAILED | + SDMMC_ERROR_GENERAL_UNKNOWN_ERR)) + { + MODIFY_REG(hsdio->Instance->DCTRL, SDMMC_DCTRL_FIFORST, SDMMC_DCTRL_FIFORST); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + } + /* Enable interrupt */ + __HAL_SDIO_ENABLE_IT(hsdio, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND)); + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @} + */ + +/** @addtogroup SDIO_Exported_Functions_Group4 + * @brief + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set callback functions allowing to manage the data transfer from/to SDIO card. + +@endverbatim + * @{ + */ +/** + * @brief This function handles SDIO device interrupt request. + * @param hsdio: Pointer to SDIO handle + * @retval None + */ +void HAL_SDIO_IRQHandler(SDIO_HandleTypeDef *hsdio) +{ + HAL_SDIO_ExtendedCmd_TypeDef CMD53_desc; + HAL_StatusTypeDef errorstate; + uint32_t ctx = hsdio->Context; + uint32_t flags; + + flags = READ_REG(((SDMMC_TypeDef *)((uint32_t)(hsdio)->Instance))->STA); + + if (READ_BIT(flags, SDMMC_FLAG_SDIOIT) != 0U) + { + (void)SDIO_IOFunction_IRQHandler(hsdio); + } + + if (READ_BIT(flags, SDMMC_FLAG_DATAEND) != 0U) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_FLAG_DATAEND); + + hsdio->State = HAL_SDIO_STATE_READY; + + __HAL_SDIO_DISABLE_IT(hsdio, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | + SDMMC_IT_RXOVERR | SDMMC_IT_TXFIFOHE | SDMMC_IT_RXFIFOHF); + + __HAL_SDIO_DISABLE_IT(hsdio, SDMMC_IT_IDMABTC); + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + + if ((ctx & SDIO_CONTEXT_DMA) != 0U) + { + hsdio->Instance->DLEN = 0; + hsdio->Instance->IDMACTRL = SDMMC_DISABLE_IDMA; + if ((hsdio->Instance->DCTRL & SDMMC_DCTRL_SDIOEN) != 0U) + { + hsdio->Instance->DCTRL = SDMMC_DCTRL_SDIOEN; + } + else + { + hsdio->Instance->DCTRL = 0U; + } + + hsdio->Context = SDIO_CONTEXT_NONE; + hsdio->State = HAL_SDIO_STATE_READY; + } + + if (hsdio->remaining_data != 0U) + { + CMD53_desc.Block_Mode = HAL_SDIO_MODE_BYTE; + CMD53_desc.Reg_Addr = hsdio->next_reg_addr; + CMD53_desc.IOFunctionNbr = 1; + CMD53_desc.OpCode = 1; + if (((ctx & SDIO_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((ctx & SDIO_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { + hsdio->pRxBuffPtr = (uint8_t *)hsdio->next_data_addr; + errorstate = HAL_SDIO_ReadExtended_DMA(hsdio, &CMD53_desc, hsdio->pRxBuffPtr, hsdio->remaining_data); + } + else + { + hsdio->pTxBuffPtr = (uint8_t *)hsdio->next_data_addr; + errorstate = HAL_SDIO_WriteExtended_DMA(hsdio, &CMD53_desc, hsdio->pTxBuffPtr, hsdio->remaining_data); + } + if (errorstate != HAL_OK) + { +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1) + hsdio->ErrorCallback(hsdio); +#else + HAL_SDIO_ErrorCallback(hsdio); +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + } + } + else if (((ctx & SDIO_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((ctx & SDIO_CONTEXT_READ_MULTIPLE_BLOCK) != 0U)) + { +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) + hsdio->RxCpltCallback(hsdio); +#else + HAL_SDIO_RxCpltCallback(hsdio); +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + } + else + { +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) + hsdio->TxCpltCallback(hsdio); +#else + HAL_SDIO_TxCpltCallback(hsdio); +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + } + } + + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR | SDMMC_FLAG_TXUNDERR)) + { +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1) + hsdio->ErrorCallback(hsdio); +#else + HAL_SDIO_ErrorCallback(hsdio); +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ + } +} + +/** + * @brief Tx Transfer completed callbacks + * @param hsdio: Pointer to SDIO handle + * @retval None + */ +__weak void HAL_SDIO_TxCpltCallback(SDIO_HandleTypeDef *hsdio) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hsdio: Pointer SDIO handle + * @retval None + */ +__weak void HAL_SDIO_RxCpltCallback(SDIO_HandleTypeDef *hsdio) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief SDIO error callbacks + * @param hsdio: Pointer SDIO handle + * @retval None + */ +__weak void HAL_SDIO_ErrorCallback(SDIO_HandleTypeDef *hsdio) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief SDIO IO Function complete callback + * @param hsdio: Pointer SDIO handle + * @param func: SDIO IO Function + * @retval None + */ +__weak void HAL_SDIO_IOFunctionCallback(SDIO_HandleTypeDef *hsdio, uint32_t func) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + UNUSED(func); + + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_ErrorCallback can be implemented in the user file + */ +} + +#if (USE_SDIO_TRANSCEIVER != 0U) +/** + * @brief Enable/Disable the SDIO Transceiver 1.8V Mode Callback. + * @param hsdio: Pointer SDIO handle + * @param status: Voltage Switch State + * @retval None + */ +__weak void HAL_SDIO_DriveTransceiver_1_8V_Callback(SDIO_HandleTypeDef *hsdio, FlagStatus status) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsdio); + UNUSED(status); + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SDIO_EnableTransceiver could be implemented in the user file + */ +} +#endif /* USE_SDIO_TRANSCEIVER */ + +#if defined (USE_HAL_SDIO_REGISTER_CALLBACKS) && (USE_HAL_SDIO_REGISTER_CALLBACKS == 1U) +/** + * @brief Register a User SDIO Callback + * To be used instead of the weak (overridden) predefined callback + * @param hsdio : SDIO handle + * @param CallbackID : ID of the callback to be registered + * This parameter can be one of the following values: + * @arg @ref HAL_SDIO_TX_CPLT_CB_ID SDIO Tx Complete Callback ID + * @arg @ref HAL_SDIO_RX_CPLT_CB_ID SDIO Rx Complete Callback ID + * @arg @ref HAL_SDIO_ERROR_CB_ID SDIO Error Callback ID + * @arg @ref HAL_SDIO_MSP_INIT_CB_ID SDIO MspInit Callback ID + * @arg @ref HAL_SDIO_MSP_DEINIT_CB_ID SDIO MspDeInit Callback ID + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SDIO_RegisterCallback(SDIO_HandleTypeDef *hsdio, HAL_SDIO_CallbackIDTypeDef CallbackID, + pSDIO_CallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(pCallback != NULL); + + if (pCallback == NULL) + { + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + switch (CallbackID) + { + case HAL_SDIO_TX_CPLT_CB_ID : + hsdio->TxCpltCallback = pCallback; + break; + case HAL_SDIO_RX_CPLT_CB_ID : + hsdio->RxCpltCallback = pCallback; + break; + case HAL_SDIO_ERROR_CB_ID : + hsdio->ErrorCallback = pCallback; + break; + case HAL_SDIO_MSP_INIT_CB_ID : + hsdio->MspInitCallback = pCallback; + break; + case HAL_SDIO_MSP_DEINIT_CB_ID : + hsdio->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else if (hsdio->State == HAL_SDIO_STATE_RESET) + { + switch (CallbackID) + { + case HAL_SDIO_MSP_INIT_CB_ID : + hsdio->MspInitCallback = pCallback; + break; + case HAL_SDIO_MSP_DEINIT_CB_ID : + hsdio->MspDeInitCallback = pCallback; + break; + default : + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + break; + } + } + else + { + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User SDIO Callback + * SDIO Callback is redirected to the weak (overridden) predefined callback. + * @note The HAL_SDIO_UnRegisterCallback() may be called before HAL_SDIO_Init() in + * HAL_SDIO_STATE_RESET to register callbacks for HAL_SDIO_MSP_INIT_CB_ID + * and HAL_SDIO_MSP_DEINIT_CB_ID. + * @param hsdio : SDIO handle + * @param CallbackID : ID of the callback to be unregistered + * This parameter can be one of the following values @ref SDIO_Exported_Types_Group3. + * @retval status + */ +HAL_StatusTypeDef HAL_SDIO_UnRegisterCallback(SDIO_HandleTypeDef *hsdio, HAL_SDIO_CallbackIDTypeDef CallbackID) +{ + HAL_StatusTypeDef status = HAL_OK; + + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + switch (CallbackID) + { + case HAL_SDIO_TX_CPLT_CB_ID : + hsdio->TxCpltCallback = HAL_SDIO_TxCpltCallback; + break; + case HAL_SDIO_RX_CPLT_CB_ID : + hsdio->RxCpltCallback = HAL_SDIO_RxCpltCallback; + break; + case HAL_SDIO_ERROR_CB_ID : + hsdio->ErrorCallback = HAL_SDIO_ErrorCallback; + break; + case HAL_SDIO_MSP_INIT_CB_ID : + hsdio->MspInitCallback = HAL_SDIO_MspInit; + break; + case HAL_SDIO_MSP_DEINIT_CB_ID : + hsdio->MspDeInitCallback = HAL_SDIO_MspDeInit; + break; + default : + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else if (hsdio->State == HAL_SDIO_STATE_RESET) + { + switch (CallbackID) + { + case HAL_SDIO_MSP_INIT_CB_ID : + hsdio->MspInitCallback = HAL_SDIO_MspInit; + break; + case HAL_SDIO_MSP_DEINIT_CB_ID : + hsdio->MspDeInitCallback = HAL_SDIO_MspDeInit; + break; + default : + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + break; + } + } + else + { + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + status = HAL_ERROR; + } + + return status; +} + +#if (USE_SDIO_TRANSCEIVER != 0U) +/** + * @brief Register a User SDIO Transceiver Callback + * To be used instead of the weak (overridden) predefined callback + * @param hsdio : SDIO handle + * @param pCallback : pointer to the Callback function + * @retval status + */ +HAL_StatusTypeDef HAL_SDIO_RegisterTransceiverCallback(SDIO_HandleTypeDef *hsdio, + pSDIO_TransceiverCallbackTypeDef pCallback) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (pCallback == NULL) + { + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + return HAL_ERROR; + } + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->DriveTransceiver_1_8V_Callback = pCallback; + } + else + { + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Unregister a User SDIO Transceiver Callback + * SDIO Callback is redirected to the weak (overridden) predefined callback + * @param hsdio : SDIO handle + * @retval status + */ +HAL_StatusTypeDef HAL_SDIO_UnRegisterTransceiverCallback(SDIO_HandleTypeDef *hsdio) +{ + HAL_StatusTypeDef status = HAL_OK; + + if (hsdio->State == HAL_SDIO_STATE_READY) + { + hsdio->DriveTransceiver_1_8V_Callback = HAL_SDIO_DriveTransceiver_1_8V_Callback; + } + else + { + /* Update the error code */ + hsdio->ErrorCode |= HAL_SDIO_ERROR_INVALID_CALLBACK; + /* update return status */ + status = HAL_ERROR; + } + + return status; +} +#endif /* USE_SDIO_TRANSCEIVER */ + +#endif /* USE_HAL_SDIO_REGISTER_CALLBACKS */ +/** + * @} + */ + +/** @addtogroup SDIO_Exported_Functions_Group5 + * @brief + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the SDIO card operations. + +@endverbatim + * @{ + */ +/** + * @brief return the SDIO state + * @param hsdio: Pointer to SDIO handle + * @retval HAL state + */ +HAL_SDIO_StateTypeDef HAL_SDIO_GetState(const SDIO_HandleTypeDef *hsdio) +{ + return hsdio->State; +} + +/** + * @brief Return the SDIO error code + * @param hsdio : Pointer to a SDIO_HandleTypeDef structure that contains the configuration information. + * @retval SDIO Error Code + */ +uint32_t HAL_SDIO_GetError(const SDIO_HandleTypeDef *hsdio) +{ + return hsdio->ErrorCode; +} + +/** + * @} + */ + +/** @addtogroup SDIO_Exported_Functions_Group6 + * @brief + * +@verbatim + ============================================================================== + ##### Peripheral IO interrupt ##### + ============================================================================== + [..] + This subsection provides a set functions allowing to enable/disable IO functions interrupt features + on the SDIO card. + +@endverbatim + * @{ + */ +/** + * @brief Enable SDIO IO interrupt. + * @param hsdio: Pointer to SDIO handle + * @param IOFunction: Specifies the SDIO IO function. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_EnableIOFunctionInterrupt(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction) +{ + uint8_t intEn = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR4, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &intEn) != HAL_OK) + { + return HAL_ERROR; + } + + /* if already enable , do not need enable again */ + if ((((intEn >> (uint32_t)IOFunction) & 0x01U) == 0x01U) && ((intEn & 0x01U) != 0U)) + { + return HAL_OK; + } + else + { + intEn |= (1U << (uint32_t)IOFunction) | 0x01U; + hsdio->IOInterruptNbr++; + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR4, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, + &intEn) != HAL_OK) + { + return HAL_ERROR; + } + + __HAL_SDIO_ENABLE_IT(hsdio, SDMMC_IT_SDIOIT); + + /* Enable host SDIO interrupt operations */ + __SDMMC_OPERATION_ENABLE(hsdio->Instance); + + return HAL_OK; +} + +/** + * @brief Enable SDIO IO interrupt. + * @param hsdio: Pointer to SDIO handle + * @param IOFunction: Specifies the SDIO IO function. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_DisableIOFunctionInterrupt(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction) +{ + uint8_t intEn = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR4, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &intEn) != HAL_OK) + { + return HAL_ERROR; + } + + /* if already disable , do not need enable again */ + if (((intEn >> (uint32_t)IOFunction) & 0x01U) == 0x00U) + { + return HAL_OK; + } + else + { + /* disable the interrupt, don't disable the interrupt master here */ + intEn &= ~(1U << (uint32_t)IOFunction); + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR4, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, + &intEn) != HAL_OK) + { + return HAL_ERROR; + } + + if (hsdio->IOInterruptNbr > 1U) + { + hsdio->IOInterruptNbr--; + } + else + { + hsdio->IOInterruptNbr = 0U; + __HAL_SDIO_DISABLE_IT(hsdio, SDMMC_IT_SDIOIT); + } + return HAL_OK; +} + +/** + * @brief Enable SDIO IO Enable. + * @param hsdio: Pointer to SDIO handle + * @param IOFunction: Specifies the SDIO IO function. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_EnableIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction) +{ + uint8_t ioEn = 0U; + uint8_t ioReady = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR0_SD_BYTE2, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &ioEn) != HAL_OK) + { + return HAL_ERROR; + } + + /* if already enable , do not need to enable again */ + if (((ioEn >> (uint32_t)IOFunction) & 0x01U) == 0x01U) + { + return HAL_OK; + } + else + { + ioEn |= (1U << (uint32_t)IOFunction); + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR0_SD_BYTE2, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, &ioEn) != HAL_OK) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR0_SD_BYTE3, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &ioReady) != HAL_OK) + { + return HAL_ERROR; + } + /* check if IO ready */ + if ((ioReady & (1U << (uint32_t)IOFunction)) != 0U) + { + return HAL_OK; + } + + return HAL_ERROR; +} + +/** + * @brief Disable SDIO IO Enable. + * @param hsdio: Pointer to SDIO handle + * @param IOFunction: Specifies the SDIO IO function. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_DisableIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction) +{ + uint8_t ioEn = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR0_SD_BYTE2, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &ioEn) != HAL_OK) + { + return HAL_ERROR; + } + + /* if already enable , do not need enable again */ + if (((ioEn >> (uint32_t)IOFunction) & 0x01U) == 0x00U) + { + return HAL_OK; + } + else + { + ioEn &= ~(1U << (uint32_t)IOFunction); + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR0_SD_BYTE2, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, &ioEn) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Select SDIO IO Enable. + * @param hsdio: Pointer to SDIO handle + * @param IOFunction: Specifies the SDIO IO function. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_SelectIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction) +{ + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR12_SD_BYTE1, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, + (uint8_t *)&IOFunction) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Abort IO transfer. + * @param hsdio: Pointer to SDIO handle + * @param IOFunction IO number + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_AbortIOFunction(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction) +{ + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR4_SD_BYTE2, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, + (uint8_t *)&IOFunction) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Enable Assynchrone interrupt. + * @param hsdio: Pointer to SDIO handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_EnableIOAsynInterrupt(SDIO_HandleTypeDef *hsdio) +{ + uint8_t enable_asyn_it = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR20_SD_BYTE2, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &enable_asyn_it) + != HAL_OK) + { + return HAL_ERROR; + } + + /* if already enable , do not need enable again */ + if ((enable_asyn_it & 0x02U) == 0x02U) + { + return HAL_OK; + } + else + { + enable_asyn_it |= 0x02U; + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR20_SD_BYTE2, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, + &enable_asyn_it) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Disable Assynchrone interrupt. + * @param hsdio: Pointer to SDIO handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SDIO_DisableIOAsynInterrupt(SDIO_HandleTypeDef *hsdio) +{ + uint8_t enable_asyn_it = 0U; + + /* Check the parameters */ + assert_param(hsdio != NULL); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR20_SD_BYTE2, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &enable_asyn_it) + != HAL_OK) + { + return HAL_ERROR; + } + + /* if already disable , do not need disable again */ + if ((enable_asyn_it & 0x02U) == 0x00U) + { + return HAL_OK; + } + else + { + enable_asyn_it &= (uint8_t) ~(0x02U); + } + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR20_SD_BYTE2, HAL_SDIO_READ_AFTER_WRITE, SDIO_FUNCTION_0, + &enable_asyn_it) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief sdio set io IRQ handler. + * @param hsdio Pointer to SDIO handle + * @param IOFunction IO function io number. + * @param Callback io IRQ handler. + */ +HAL_StatusTypeDef HAL_SDIO_RegisterIOFunctionCallback(SDIO_HandleTypeDef *hsdio, uint32_t IOFunction, + HAL_SDIO_IOFunction_CallbackTypeDef Callback) +{ + /* Check the parameters */ + assert_param(hsdio != NULL); + assert_param(IS_SDIO_FUNCTION(IOFunction)); + + /* Check the SDIO peripheral handle parameter */ + if (hsdio == NULL) + { + return HAL_ERROR; + } + + hsdio->SDIO_IOFunction_Callback[(uint32_t)IOFunction] = Callback; + hsdio->IOFunctionMask |= (1U << (uint8_t)IOFunction); + + return HAL_OK; +} +/** + * @} + */ + +/** + * @} + */ + +/* Private function --------------------------------------------------------------------------------------------------*/ +/** @addtogroup SDIO_Private_Functions + * @{ + */ +/** + * @brief Initializes the SDIO device. + * @param hsdio: Pointer to the SDIO handle + * @retval HAL status + */ +static HAL_StatusTypeDef SDIO_InitCard(SDIO_HandleTypeDef *hsdio) +{ + uint32_t errorstate; + uint32_t timeout = 0U; + uint16_t sdio_rca = 1U; + uint32_t Resp4; + uint32_t nbr_of_func; + SDMMC_InitTypeDef Init; + + /* Identify card operating voltage */ + errorstate = SDMMC_CmdGoIdleState(hsdio->Instance); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + return HAL_ERROR; + } + + /* Check the power State */ + if (SDMMC_GetPowerState(hsdio->Instance) == 0U) + { + return HAL_ERROR; + } + + /* Send CMD5 */ + errorstate = SDMMC_CmdSendOperationcondition(hsdio->Instance, 0U, &Resp4); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + return HAL_ERROR; + } + + nbr_of_func = ((Resp4 & 0x70000000U) >> 28U); + /* Check if Nbr of function > 0 and OCR valid */ + if (nbr_of_func > 0U) + { + /* Send CMD5 with arg= S18R, WV*/ + if (SDMMC_CmdSendOperationcondition(hsdio->Instance, (SDIO_OCR_VDD_32_33 | SDIO_OCR_SDIO_S18R), &Resp4) + != HAL_SDIO_ERROR_NONE) + { + return HAL_ERROR; + } + /* Check if IORDY = 1 and S18A = 1 */ + if ((((Resp4 & 0x80000000U) >> 31U) != 0U) && (((Resp4 & 0x1000000U) >> 24U) != 0U)) + { + /* Send CMD11 to switch 1.8V mode */ + errorstate = SDMMC_CmdVoltageSwitch(hsdio->Instance); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + return HAL_ERROR; + } + } + else + { + /* S18A is not supported */ + } + } + + /** Cmd3 is sent while response is SDMMC_ERROR_ILLEGAL_CMD, due to the partial init test done before + * (sending cmd0 after the sequence cmd0/cmd3 is sent is considered illegal). + */ + do + { + errorstate = SDMMC_CmdSetRelAdd(hsdio->Instance, &sdio_rca); + timeout++; + HAL_Delay(1); + } while ((errorstate == SDMMC_ERROR_ILLEGAL_CMD) && (timeout != SDIO_TIMEOUT)); + + if ((timeout == SDIO_TIMEOUT) || (errorstate != HAL_SDIO_ERROR_NONE)) + { + return HAL_ERROR; + } + + /* Select the Card ( Sending CMD7)*/ + errorstate = SDMMC_CmdSelDesel(hsdio->Instance, (uint32_t)(((uint32_t)sdio_rca) << 16U)); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + return HAL_ERROR; + } + + /* Configure the SDMMC user parameters */ + Init.ClockEdge = hsdio->Init.ClockEdge; + Init.ClockPowerSave = hsdio->Init.ClockPowerSave; + Init.BusWide = hsdio->Init.BusWide; + Init.HardwareFlowControl = hsdio->Init.HardwareFlowControl; + Init.ClockDiv = hsdio->Init.ClockDiv; + (void)SDMMC_Init(hsdio->Instance, Init); + + uint8_t data = (hsdio->Init.BusWide == HAL_SDIO_4_WIRES_MODE) ? 2U : 0U; + + if (SDIO_WriteDirect(hsdio, SDMMC_SDIO_CCCR4_SD_BYTE3, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &data) != HAL_OK) + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Read 1 byte data. + * @param hsdio: Pointer to SDIO handle + * @param cmd_arg: formatted CMD52 structure + * @param pData: pointer to write or read data + * @retval HAL status + */ +static HAL_StatusTypeDef SDIO_ReadDirect(SDIO_HandleTypeDef *hsdio, uint32_t addr, uint32_t raw, + uint32_t function_nbr, uint8_t *pData) +{ + uint32_t errorstate; + uint32_t cmd; + + cmd = SDIO_READ << 31U; + cmd |= function_nbr << 28U; + cmd |= raw << 27U; + cmd |= (addr & 0x1FFFFU) << 9U; + errorstate = SDMMC_SDIO_CmdReadWriteDirect(hsdio->Instance, cmd, pData); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + return HAL_OK; +} + +/** + * @brief Write 1 byte data. + * @param hsdio: Pointer to SDIO handle + * @param cmd_arg: formatted CMD52 structure + * @param pData: pointer to write or read data + * @retval HAL status + */ +static HAL_StatusTypeDef SDIO_WriteDirect(SDIO_HandleTypeDef *hsdio, uint32_t addr, uint32_t raw, + uint32_t function_nbr, uint8_t *pData) +{ + uint32_t errorstate; + uint32_t cmd; + uint8_t response; + + cmd = SDIO_WRITE << 31U; + cmd |= function_nbr << 28U; + cmd |= raw << 27U; + cmd |= (addr & 0x1FFFFU) << 9U; + cmd |= ((uint32_t) * pData & 0x000000FFU); + errorstate = SDMMC_SDIO_CmdReadWriteDirect(hsdio->Instance, cmd, &response); + + if (errorstate != HAL_SDIO_ERROR_NONE) + { + hsdio->ErrorCode |= errorstate; + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + + /* Clear all the static flags */ + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + return HAL_OK; +} + +/** + * @brief Write multiple data with a single command. + * @param hsdio: Pointer to SDIO handle + * @param cmd_arg: formatted cmd53 structure + * @param Size_byte: block size if CMD53 defined in HAL_SDIO_MODE_BLOCK + * @param pData: pointer to write or read data + * @retval HAL status + */ +static HAL_StatusTypeDef SDIO_WriteExtended(SDIO_HandleTypeDef *hsdio, HAL_SDIO_ExtendedCmd_TypeDef *cmd_arg, + uint8_t *pData, uint16_t Size_byte) +{ + SDMMC_DataInitTypeDef config; + uint32_t errorstate; + uint32_t tickstart = HAL_GetTick(); + uint32_t regCount; + uint8_t byteCount; + uint32_t data; + uint32_t dataremaining; + uint32_t *u32tempbuff = (uint32_t *)(uint32_t)pData; + SDMMC_TypeDef *SDMMCx; + uint32_t cmd; + uint32_t nbr_of_block; + + hsdio->ErrorCode = HAL_SDIO_ERROR_NONE; + + /* Compute how many blocks are to be send for pData of length data_size to be send */ + nbr_of_block = (((uint32_t)Size_byte & ~((uint32_t)hsdio->block_size & 1U))) >> __CLZ(__RBIT(hsdio->block_size)); + + /* Initialize data control register */ + if ((hsdio->Instance->DCTRL & SDMMC_DCTRL_SDIOEN) != 0U) + { + hsdio->Instance->DCTRL = SDMMC_DCTRL_SDIOEN; + } + else + { + hsdio->Instance->DCTRL = 0U; + } + + /* Configure the SDIO DPSM (Data Path State Machine) */ + config.DataTimeOut = SDMMC_DATATIMEOUT; + if (cmd_arg->Block_Mode == HAL_SDIO_MODE_BLOCK) + { + config.DataLength = (uint32_t)(nbr_of_block * hsdio->block_size); + config.DataBlockSize = SDIO_Convert_Block_Size(hsdio, hsdio->block_size); + } + else + { + config.DataLength = Size_byte; + config.DataBlockSize = SDMMC_DATABLOCK_SIZE_1B; + } + + config.TransferDir = SDMMC_TRANSFER_DIR_TO_CARD; + config.TransferMode = (cmd_arg->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDMMC_TRANSFER_MODE_BLOCK : + SDMMC_TRANSFER_MODE_SDIO; + config.DPSM = SDMMC_DPSM_DISABLE; + (void)SDMMC_ConfigData(hsdio->Instance, &config); + __SDMMC_CMDTRANS_ENABLE(hsdio->Instance); + + hsdio->Context = (cmd_arg->Block_Mode == HAL_SDIO_MODE_BLOCK) ? SDIO_CONTEXT_WRITE_MULTIPLE_BLOCK : + SDIO_CONTEXT_WRITE_SINGLE_BLOCK; + cmd = SDIO_WRITE << 31U; + cmd |= cmd_arg->IOFunctionNbr << 28U; + cmd |= cmd_arg->Block_Mode << 27U; + cmd |= cmd_arg->OpCode << 26U; + cmd |= (cmd_arg->Reg_Addr & 0x1FFFFU) << 9U; + cmd |= (((uint32_t)Size_byte) & 0x1FFU); + errorstate = SDMMC_SDIO_CmdReadWriteExtended(hsdio->Instance, cmd); + if (errorstate != HAL_SDIO_ERROR_NONE) + { + MODIFY_REG(hsdio->Instance->DCTRL, SDMMC_DCTRL_FIFORST, SDMMC_DCTRL_FIFORST); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->ErrorCode |= errorstate; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + + SDMMCx = hsdio->Instance; + dataremaining = config.DataLength; + while (!__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | + SDMMC_FLAG_DATAEND)) + { + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= 32U)) + { + for (regCount = 8U; regCount > 0U; regCount--) + { + SDMMCx->FIFO = *u32tempbuff; + u32tempbuff++; + } + dataremaining -= 32U; + } + else if ((dataremaining < 32U) && (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXFIFOHE | SDMMC_FLAG_TXFIFOE))) + { + uint8_t *u8buff = (uint8_t *)u32tempbuff; + while (dataremaining > 0U) + { + data = 0U; + for (byteCount = 0U; (byteCount < 4U) && (dataremaining > 0U); byteCount++) + { + data |= ((uint32_t)(*u8buff) << (byteCount << 3U)); + u8buff++; + dataremaining--; + } + SDMMCx->FIFO = data; + } + } + if ((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_TIMEOUT; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_TIMEOUT; + } + } + + __SDMMC_CMDTRANS_DISABLE(hsdio->Instance); + if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DTIMEOUT)) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_DATA_TIMEOUT; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_DCRCFAIL)) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_DATA_CRC_FAIL; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (__HAL_SDIO_GET_FLAG(hsdio, SDMMC_FLAG_TXUNDERR)) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_FLAGS); + hsdio->ErrorCode |= HAL_SDIO_ERROR_TX_UNDERRUN; + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else if (hsdio->ErrorCode == SDMMC_ERROR_INVALID_PARAMETER) + { + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + hsdio->State = HAL_SDIO_STATE_READY; + hsdio->Context = SDIO_CONTEXT_NONE; + return HAL_ERROR; + } + else + { + /* Nothing to do */ + } + + __HAL_SDIO_CLEAR_FLAG(hsdio, SDMMC_STATIC_DATA_FLAGS); + + return HAL_OK; +} + +/** + * @brief Allows to convert a block size in the according SDMMC value for configuring the SDMMC when doing a CMD53 + * @param hsdio: Pointer to the SDIO handle. + * @param block_size: block size in bytes + * @retval block size as DBLOCKSIZE[3:0] bits format + */ +static uint8_t SDIO_Convert_Block_Size(SDIO_HandleTypeDef *hsdio, uint32_t block_size) +{ + UNUSED(hsdio); + + uint8_t most_bit = (uint8_t)__CLZ(__RBIT(block_size)); + /*(1 << most_bit) - 1) is the mask used for blocksize*/ + if (((uint8_t)block_size & ((1U << most_bit) - 1U)) != 0U) + { + return (uint8_t)SDMMC_DATABLOCK_SIZE_4B; + } + return most_bit << SDMMC_DCTRL_DBLOCKSIZE_Pos; +} + +/*! + * @brief SDIO card io pending interrupt handle function. + * @note This function is used to handle the pending io interrupt. + * To register a IO IRQ handler, Use HAL_SDIO_EnableIOInterrupt and HAL_SDIO_SetIOIRQHandler + * @param hsdio: Pointer to SDIO handle + * @retval HAL status + */ +static HAL_StatusTypeDef SDIO_IOFunction_IRQHandler(SDIO_HandleTypeDef *hsdio) +{ + uint8_t count; + uint8_t pendingInt; + + if (hsdio->IOInterruptNbr == 1U) + { + if ((hsdio->SDIO_IOFunction_Callback[hsdio->IOFunctionMask - 1U]) != NULL) + { + (hsdio->SDIO_IOFunction_Callback[hsdio->IOFunctionMask - 1U])(hsdio, hsdio->IOFunctionMask - 1U); + } + } + else if ((hsdio->IOInterruptNbr > 1U) && (hsdio->IOFunctionMask != 0U)) + { + /* Get pending int firstly */ + if (SDIO_ReadDirect(hsdio, SDMMC_SDIO_CCCR4_SD_BYTE1, HAL_SDIO_WRITE_ONLY, SDIO_FUNCTION_0, &pendingInt) != + HAL_OK) + { + return HAL_ERROR; + } + + if ((pendingInt != 0U) && (hsdio->IOFunctionMask != 0U)) + { + for (count = 1; count <= SDIO_MAX_IO_NUMBER; count++) + { + if (((pendingInt & (1U << count)) != 0U) && (((1U << count) & hsdio->IOFunctionMask) != 0U)) + { + if ((hsdio->SDIO_IOFunction_Callback[count - 1U]) != NULL) + { + (hsdio->SDIO_IOFunction_Callback[count - 1U])(hsdio, count); + } + } + } + } + } + else + { + /* Nothing to do */ + } + + return HAL_OK; +} +/** + * @} + */ +#endif /* HAL_SDIO_MODULE_ENABLED */ +#endif /* SDMMC1 || SDMMC2 */ +/** + * @} + */ + +/** + * @} + */ diff --git a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_ll_sdmmc.c b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_ll_sdmmc.c index 7349f78c3..2aea608e2 100644 --- a/stm32cube/stm32u5xx/drivers/src/stm32u5xx_ll_sdmmc.c +++ b/stm32cube/stm32u5xx/drivers/src/stm32u5xx_ll_sdmmc.c @@ -163,7 +163,7 @@ */ #if defined (SDMMC1) || defined (SDMMC2) -#if defined (HAL_SD_MODULE_ENABLED) || defined (HAL_MMC_MODULE_ENABLED) +#if defined (HAL_SD_MODULE_ENABLED) || defined (HAL_MMC_MODULE_ENABLED) || defined (HAL_SDIO_MODULE_ENABLED) /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ @@ -1256,6 +1256,78 @@ uint32_t SDMMC_CmdSendEXTCSD(SDMMC_TypeDef *SDMMCx, uint32_t Argument) return errorstate; } +/** + * @brief Execute a cmd52 to write single byte data and read single byte data if needed + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: SDMMC command argument which is sent to a card as part of a command message + * @param pData: pointer to read response if needed + * @retval SD Card error state + */ +uint32_t SDMMC_SDIO_CmdReadWriteDirect(SDMMC_TypeDef *SDMMCx, uint32_t Argument, uint8_t *pResponse) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SDMMC_RW_DIRECT; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp5(SDMMCx, SDMMC_CMD_SDMMC_RW_DIRECT, pResponse); + + return errorstate; +} + +/** + * @brief Execute a cmd53 to write or read multiple data with a single command + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: SDMMC command argument which is sent to a card as part of a command message + * @retval SD Card error state + */ +uint32_t SDMMC_SDIO_CmdReadWriteExtended(SDMMC_TypeDef *SDMMCx, uint32_t Argument) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SDMMC_RW_EXTENDED; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp5(SDMMCx, SDMMC_CMD_SDMMC_RW_EXTENDED, NULL); + + return errorstate; +} + +/** + * @brief Execute a cmd5 to write or read multiple data with a single command + * @param SDMMCx: Pointer to SDMMC register base + * @param Argument: SDMMC command argument which is sent to a card as part of a command message + * @retval SD Card error state + */ +uint32_t SDMMC_CmdSendOperationcondition(SDMMC_TypeDef *SDMMCx, uint32_t Argument, uint32_t *pResp) +{ + SDMMC_CmdInitTypeDef sdmmc_cmdinit; + uint32_t errorstate; + + sdmmc_cmdinit.Argument = Argument; + sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SDMMC_SEN_OP_COND; + sdmmc_cmdinit.Response = SDMMC_RESPONSE_SHORT; + sdmmc_cmdinit.WaitForInterrupt = SDMMC_WAIT_NO; + sdmmc_cmdinit.CPSM = SDMMC_CPSM_ENABLE; + (void)SDMMC_SendCommand(SDMMCx, &sdmmc_cmdinit); + + /* Check for error conditions */ + errorstate = SDMMC_GetCmdResp4(SDMMCx, pResp); + + return errorstate; +} /** * @} */ @@ -1491,6 +1563,138 @@ uint32_t SDMMC_GetCmdResp3(SDMMC_TypeDef *SDMMCx) return SDMMC_ERROR_NONE; } +/** + * @brief Checks for error conditions for R4 response. + * @param SDMMCx: Pointer to SDMMC register base + * @param pResp: pointer to response + * @retval error state + */ +uint32_t SDMMC_GetCmdResp4(SDMMC_TypeDef *SDMMCx, uint32_t *pResp) +{ + uint32_t sta_reg; + + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else + { + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + } + + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + + /* We have received response, retrieve it. */ + *pResp = SDMMC_GetResponse(SDMMCx, SDMMC_RESP1); + + return SDMMC_ERROR_NONE; +} + +/** + * @brief Checks for error conditions for R5 (cmd52/cmd53) response. + * @param SDMMCx: Pointer to SDMMC register base + * @param SDIO_CMD: The sent command index + * @param pData: pointer to the read/write buffer needed for cmd52 + * @retval SDIO Card error state + */ +uint32_t SDMMC_GetCmdResp5(SDMMC_TypeDef *SDMMCx, uint8_t SDIO_CMD, uint8_t *pData) +{ + uint32_t response_r5; + uint32_t sta_reg; + + /* 8 is the number of required instructions cycles for the below loop statement. + The SDMMC_CMDTIMEOUT is expressed in ms */ + uint32_t count = SDMMC_CMDTIMEOUT * (SystemCoreClock / 8U / 1000U); + + do + { + if (count-- == 0U) + { + return SDMMC_ERROR_TIMEOUT; + } + sta_reg = SDMMCx->STA; + } while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT)) == 0U) || + ((sta_reg & SDMMC_FLAG_CMDACT) != 0U)); + + if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CTIMEOUT); + + return SDMMC_ERROR_CMD_RSP_TIMEOUT; + } + else if (__SDMMC_GET_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL)) + { + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_FLAG_CCRCFAIL); + + return SDMMC_ERROR_CMD_CRC_FAIL; + } + else + { + /* Nothing to do */ + } + + /* Check response received is of desired command */ + if (SDMMC_GetCommandResponse(SDMMCx) != SDIO_CMD) + { + return SDMMC_ERROR_CMD_CRC_FAIL; + } + + /* Clear all the static flags */ + __SDMMC_CLEAR_FLAG(SDMMCx, SDMMC_STATIC_CMD_FLAGS); + + /* We have received response, retrieve it. */ + response_r5 = SDMMC_GetResponse(SDMMCx, SDMMC_RESP1); + + if ((response_r5 & SDMMC_SDIO_R5_ERRORBITS) == SDMMC_ALLZERO) + { + /* we only want 8 bit read or write data and the 8 bit response flags are masked in the data pointer */ + if (pData != NULL) + { + *pData = (uint8_t)(response_r5 & 0xFFU); + } + + return SDMMC_ERROR_NONE; + } + else if ((response_r5 & SDMMC_SDIO_R5_OUT_OF_RANGE) == SDMMC_SDIO_R5_OUT_OF_RANGE) + { + return SDMMC_ERROR_ADDR_OUT_OF_RANGE; + } + else if ((response_r5 & SDMMC_SDIO_R5_INVALID_FUNCTION_NUMBER) == SDMMC_SDIO_R5_INVALID_FUNCTION_NUMBER) + { + return SDMMC_ERROR_INVALID_PARAMETER; + } + else if ((response_r5 & SDMMC_SDIO_R5_ILLEGAL_CMD) == SDMMC_SDIO_R5_ILLEGAL_CMD) + { + return SDMMC_ERROR_ILLEGAL_CMD; + } + else if ((response_r5 & SDMMC_SDIO_R5_COM_CRC_FAILED) == SDMMC_SDIO_R5_COM_CRC_FAILED) + { + return SDMMC_ERROR_COM_CRC_FAILED; + } + else + { + return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; + } +} + /** * @brief Checks for error conditions for R6 (RCA) response. * @param hsd: SD handle diff --git a/stm32cube/stm32u5xx/release_note.html b/stm32cube/stm32u5xx/release_note.html index 0cddfcd85..17c62f5d5 100644 --- a/stm32cube/stm32u5xx/release_note.html +++ b/stm32cube/stm32u5xx/release_note.html @@ -64,11 +64,534 @@

    Purpose

    Update History

    - +

    Main Changes

    +
      +
    • Maintenance Release V1.6.0 of STM32CubeU5 Firmware Package to deploy the new HAL SDIO driver.
    • +
    • General updates to fix known defects and implementation enhancements.
    • +
    • Upgrade mbed-crypto Lib to use v2.28.8 (ST modified 2024-05-27).
    • +
    • Upgrade trustedfirmware Lib to use v1.3.0.11.
    • +
    • Upgrade mcuboot Lib to use v1.7.2.24.
    • +
    +

    Contents

    +

    HAL/LL Drivers updates

    +
      +
    • HAL GENERIC driver +
        +
      • update stm32u5xx_hal_conf_template file to add the support for the new HAL SDIO driver.
      • +
    • +
    • HAL CORTEX driver +
        +
      • Use MPUx instead of MPU inside MPU_ConfigRegion() API when disabling the region.
      • +
    • +
    • HAL DSI driver +
        +
      • Update startup sequence: PLL tuning must be done before PLL Enable.
      • +
    • +
    • HAL DAC driver +
        +
      • Fix HAL_DACEx_SelfCalibrate() API to manage case of calibration factor equal to range maximum value: Previously, in this case calibration factor was reset, leading to voltage accuracy not optimal.
      • +
      • Update trimming factor to use 6bits width.
      • +
    • +
    • HAL SDMMC driver +
        +
      • Support new HAL SDIO driver.
      • +
    • +
    +

    BSP Drivers updates

    +
      +
    • B-U585I-IOT02A/ STM32U5x9J-DK/ STM32U5xx_Nucleo/ STM32U575I-EV: +
        +
      • Fix printf() API implementation to be compliant with IAR 9.x.
      • +
    • +
    • B-U585I-IOT02A: +
        +
      • Update BSP_OSPI_RAM_Init() API to be compliant with MISRAC2012 rule 10.4.
      • +
    • +
    • STM32U5xx_Nucleo: +
        +
      • Update USBPD_PWR driver to be compliant with MISRAC2012 rules 2.3 and 10.4_a.
      • +
    • +
    +

    Middlewares updates

    +
      +
    • Upgrade mbed-crypto Lib to use v2.28.8_20240527
    • +
    • Upgrade trustedfirmware Lib to use v1.3.0.11
    • +
    • Upgrade mcuboot Lib to use v1.7.2.24
    • +
    +

    Projects updates

    +
      +
    • Fix printf() API implementation to be compliant with IAR 9.x.
    • +
    • Update Template projects to support new HAL SDIO driver.
    • +
    • Update HAL SMBUS examples available for NUCLEO-U575ZI-Q board to configure digital filter: +
        +
      • Add a call to HAL_SMBUS_ConfigDigitalFilter() API inside MX_I2Cx_SMBUS_Init() API.
      • +
    • +
    • General update to align user tags naming sections with STM32CubeMx V6.12.0
    • +
    • Update scripts of SBSFU and TFM applications to: +
        +
      • Add missing -M (–max-sectors) in the .sh files.
      • +
      • Use AppliCfg instead of imgtool flash commands.
      • +
      • Remove the –hardRst option to work with latest CubeProgrammer versions.
      • +
      • Use the correct –max-sectors value in imgtool command during image preparation.
      • +
    • +
    • Fix in TFM application for the test Protection failure issue when using STM32CubeIDE1.15.0
    • +
    • Update of mbeb-crypto projects for security fixes.
    • +
    • Update of mcuboot projects.
    • +
    +

    Utilities updates

    +
      +
    • Upgrade EWARM and MDK-ARM patches to support new STM32U5 part numbers.
    • +
    +

    +

    The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

    + + + + + + + + + + + + + + + +
    NameVersionRelease notes
    ProjectsV1.6.0release notes
    +

    Notes:

    +
      +
    • The following sequence is needed to disable TrustZone: +
        +
      • Boot from user Flash memory: +
          +
        • Make sure that secure and non-secure applications are well loaded and executed (jump done on non-secure application)
        • +
        • If not yet done, set RDP to level 1 through STM32CubeProgrammer. Then only Hotplug connection is possible during non-secure application execution
        • +
        • Use a power supply different from ST-LINK in order to be able to connect to the target
        • +
        • Uncheck the TZEN box and set RDP to level 0 (option byte value 0xAA), then click on Apply
        • +
      • +
      • Boot from RSS: +
          +
        • Make sure to apply a high level on BOOT0 pin (make sure that nSWBOOT0 Option Byte is checked)
        • +
        • If not yet done, set RDP to level 1 through STM32CubeProgrammer. Then only Hotplug connection is possible during non-secure application execution
        • +
        • Use a power supply different from ST-LINK in order to be able to connect to the target
        • +
        • Uncheck the TZEN box and set RDP to level 0 (option byte value 0xAA), then click on Apply Please refer to AN5347 for more details
        • +
      • +
    • +
    • The MicroLIB option should be enabled to display messages in HyperTerminal in the MDK-ARM projects. Detailed list is in the Project’s release notes.
    • +
    • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board.
    • +
    +

    Components

    +

    The components flagged by “” have changed since the previous release. “” are new.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Drivers
    NameVersionRelease note
    CMSISV5.9.0release notes
    STM32U5xx CMSISV1.4.0release notes
    STM32U5xx HAL V1.6.0release notes
    STM32U5xx NUCLEO V1.2.2release notes
    BSP STM32U575I-EV V1.4.1release notes
    BSP B-U585I-IOT02A V1.4.1release notes
    BSP STM32U5x9J-DK V1.3.1release notes
    BSP STM32U5G9J-DK2V1.2.0release notes
    BSP aps512xxV1.0.2release notes
    BSP aps6408V1.0.2release notes
    BSP CommonV7.2.1release notes
    BSP cs42l51V2.0.6release notes
    BSP gt911V1.0.0release notes
    BSP hts221V5.5.0release notes
    BSP hx8347iV2.0.3release notes
    BSP iis2mdcV1.3.0release notes
    BSP ism330dhcxV1.3.0release notes
    BSP lps22hhV1.4.0release notes
    BSP lsm6dsoV1.7.0release notes
    BSP m24256V1.0.2release notes
    BSP mfxstm32l152V4.0.1release notes
    BSP mx_wifiV2.3.4release notes
    BSP mx25lm51245gV2.0.9release notes
    BSP mx25um51245gV1.0.1release notes
    BSP mx66uw1g45gV1.0.0release notes
    BSP ov5640V3.2.4release notes
    BSP rk050hr18V1.0.0release notes
    BSP sitronixV1.0.3release notes
    BSP stm32wb_atV1.0.12release notes
    BSP stts22hV1.5.0release notes
    BSP sx8651V1.0.3release notes
    BSP tcpp0203V1.2.2release notes
    BSP veml3235V1.0.3release notes
    BSP vl53l5cxV1.0.7release notes
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Middlewares
    NameVersionRelease note
    STM32_TouchSensing_LibraryV2.2.11release notes
    STM32_Network_LibraryV2.3.0release notes
    STM32_USBPD_Core_LibraryV4.1.2release notes
    STM32_USBPD_Device_Libraryu5_v3.3.0release notes
    mbed-crypto mbed-tls-v2.28.8_20240527ST release notes
    STSAFE_A1xxMW_V3.3.5ST release notes
    SE_STSAFEA_APISE_STSAFEA_API_V1.0.0ST release notes
    trustedfirmware tfm/v1.3.0.11ST release notes
    mcuboot v1.7.2.24ST release notes
    OpenBootloaderV6.1.1release notes
    ThreadXthreadx-6.2.0.221223release notes
    NetXduonetxduo-6.2.0.221223release notes
    USBXusbx-6.2.0.221223release notes
    FileXfilex-6.2.0.221223release notes
    LevelXlevelx-6.2.0.221223release notes
    cmsis_rtos_threadxtx-cmsis-1.2.0.230421release notes
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Utilities
    NameVersionRelease note
    CommonV1.6.1release notes
    FontsV2.0.4release notes
    JPEGV2.0.3release notes
    GUI_INTERFACEGUI_V2.3.0release notes
    lcdV2.0.3release notes
    lpbamV1.4.0release notes
    TRACER_EMBV1.10.0release notes
    +

    Development toolchains and compilers

    + +

    Supported Devices and boards

    +
      +
    • Devices: +
        +
      • STM32U5F7/STM32U5G7/STM32U5F9/STM32U5G9 devices rev Z
      • +
      • STM32U575/STM32U585 devices rev W
      • +
      • STM32U595/STM32U5A5/STM32U599/STM32U5A9 devices rev W
      • +
      • STM32U535/STM32U545 devices rev Y
      • +
    • +
    • Boards: +
        +
      • NUCLEO-U575ZI-Q Nucleo board rev.C
      • +
      • NUCLEO-U5A5ZJ-Q Nucleo board rev.C
      • +
      • NUCLEO-U545RE-Q Nucleo board rev.D
      • +
      • STM32U575I-EV Evaluation board rev.C
      • +
      • B-U585I-IOT02A Discovery board rev.D
      • +
      • STM32U5A9J-DK Discovery board rev.B
      • +
      • STM32U5G9J-DK1 Discovery board rev.B
      • +
      • STM32U5G9J-DK2 Discovery board rev.C
      • +
    • +
    +

    Dependencies

    +
      +
    • This software release is compatible with: +
        +
      • STM32CubeMX version V6.12.0
      • +
      • STM32CubeProgrammer version V2.16.0
      • +
    • +
    • It is recommended to use CLI of STM32CubeProgrammer for execution of SBSFU and TFM applications, please refer to readme file of applications for more details
    • +
    • The BLE_AT_Client application requires to have Flash BLE_AT_Server module application using STM32CubeProgrammer: file BLE_AT_Server_reference.hex present in .\STM32Cube_FW_WB_V1.x.x\Projects\P-NUCLEO-WB55.Nucleo\Applications\BLE\BLE_AT_Server\Binary\BLE_AT_Server_reference.hex
    • +
    • The EMW3080B MXCHIP Wi-Fi module firmware version used is V2.3.4, for more details refer to Wi-Fi example readme files which can be found at Projects\B-U585I-IOT02A under Applications\NetXDuo and \Demonstrations\IOT_HTTP_WebServer.
    • +
    • The IOT_HTTP_WebServer demonstration uses an updated version of STM32CubeU5_Demo_U585I-IOT02A_v1.2.hex binaries. To upgrade your B-U585I-IOT02A Discovery board with the required version V1.2, please visit B-U585I-IOT02A compiled demo binary
    • +
    • The EVAL Demonstration requires to have STM32CubeU5_Demo_STM32U575I-EV.hex binaries on your STM32U575I-EV Evaluation board with the required version V1.0. To upgrade your board, please visit STM32U575I-EV compiled demo binary
    • +
    +

    Known Limitations

    +
      +
    • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to the table available in STM32CubeProjectsList.html
    • +
    • The component “USBX/CoreSystem” must be selected alongside either “USBX/UX Host CoreStack” or “USBX/UX Device CoreStack”
    • +
    • In NetXDuo, some configuration flags, that are not used in the STM32Cube FW package examples, might be non-functional when combined. This limitation will be fixed in upcoming releases
    • +
    • B-U585I-IOT02A\Applications\NetXDuo\Nx_HTTP_SSE project is not provided with STM32CubeIDE release configuration. This limitation will be fixed in upcoming releases
    • +
    • Comment error in “MX_WIFI BSP Component” Release_Notes : “The EMW3080B MXCHIP Wi-Fi module firmware version has to be V2.3.4 instead of V2.3.4 rc 13”
    • +
    • The devices MX66UW1G45G and MX66LM1G45G are driven by the same BSP component driver.
    • +
    +

    Backward compatibility

    +
      +
    • None.
    • +
    +
    +
    +
    + +
    +

    Main Changes

    Maintenance Release V1.5.0 of STM32CubeU5 Firmware Package supporting STM32U535xx, STM32U545xx, STM32U575xx, STM32U585xx, STM32U595xx, STM32U5A5xx, STM32U599xx, STM32U5A9xx, STM32U5F7xx, STM32U5G7xx, STM32U5F9xx and STM32U5G9xx devices

    -

    Contents

    +

    Contents

    CMSIS Drivers updates

    • CMSIS Device Maintenance Release version of bits and registers definition aligned with RM0456 (STM32U5 reference manual) (Please Refer to the release notes for details)
    • @@ -82,7 +605,7 @@

      CMSIS Drivers updates

    • Fix wrong declaration of g_pfnVectors size in GCC startup_stm32u5XXxx.s files
    • Update linker files to properly mark sections readonly for GCC
    -

    HAL/LL Drivers updates

    +

    HAL/LL Drivers updates

    • HAL and LL drivers Maintenance Release for STM32U5XX devices (Please Refer to the release notes for details)
    • Add the HAL MMC replay protected memory block management feature
    • @@ -263,20 +786,20 @@

      LL Drivers updates

    • Rename LL_UTILS_PACKAGETYPE_WLCSP144_SMPS to LL_UTILS_PACKAGETYPE_LQFP100_DSI_SMPS define
    -

    BSP Drivers updates

    +

    BSP Drivers updates

    • Add PWM backlight control in stm32u5g9j_discovery_lcd drivers of STM32U5G9J-DK2 board
    • Set DSI default clock in stm32u5x9j_discovery_lcd driver of STM32U5x9J-DK board
    • Restore GPIO configuration for I2C after being previously initialized in stm32u5x9j_discovery_ranging_sensor driver of STM32U5x9J-DK board
    -

    Projects updates

    +

    Projects updates

    • Add ADC_ContinuousConversion_TriggerSW_LowPower_Init project on NUCLEO-U575ZI-Q board with EWARM, MDK-ARM and STM32CubeIDE toolchains support available under:
      • Projects\NUCLEO-U575ZI-Q\Examples_LL\ADC\ADC_ContinuousConversion_TriggerSW_LowPower_Init
    -

    +

    The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

    @@ -316,7 +839,7 @@

  • The MicroLIB option should be enabled to display messages in HyperTerminal in the MDK-ARM projects. Detailed list is in the Project’s release notes.
  • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board.
  • -

    Components

    +

    Components

    The components flagged by “” have changed since the previous release. “” are new.

    @@ -639,7 +1162,7 @@

    Components

    Drivers
    -

    Development toolchains and compilers

    +

    Development toolchains and compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patches available here:
        @@ -669,7 +1192,7 @@

        Development toolchains and compile

    • STM32CubeIDE V1.15.0 (gcc12)
    -

    Supported Devices and boards

    +

    Supported Devices and boards

    • Devices:
        @@ -690,7 +1213,7 @@

        Supported Devices and boards

      • STM32U5G9J-DK2 Discovery board rev.C
    -

    Dependencies

    +

    Dependencies

    • This software release is compatible with:
        @@ -703,7 +1226,7 @@

        Dependencies

      • The IOT_HTTP_WebServer demonstration uses an updated version of STM32CubeU5_Demo_U585I-IOT02A_v1.2.hex binaries. To upgrade your B-U585I-IOT02A Discovery board with the required version V1.2, please visit B-U585I-IOT02A compiled demo binary
      • The EVAL Demonstration requires to have STM32CubeU5_Demo_STM32U575I-EV.hex binaries on your STM32U575I-EV Evaluation board with the required version V1.0. To upgrade your board, please visit STM32U575I-EV compiled demo binary
      -

      Known Limitations

      +

      Known Limitations

      • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to the table available in STM32CubeProjectsList.html
      • The component “USBX/CoreSystem” must be selected alongside either “USBX/UX Host CoreStack” or “USBX/UX Device CoreStack”
      • @@ -712,7 +1235,7 @@

        Known Limitations

      • Comment error in “MX_WIFI BSP Component” Release_Notes : “The EMW3080B MXCHIP Wi-Fi module firmware version has to be V2.3.4 instead of V2.3.4 rc 13”
      • The devices MX66UW1G45G and MX66LM1G45G are driven by the same BSP component driver.
      -

      Backward compatibility

      +

      Backward compatibility

      • veml6030 BSP is replaced by veml3235 BSP component Driver in B-U585I-IOT02A projects
      @@ -721,34 +1244,34 @@

      Backward compatibility

      -

      Main Changes

      +

      Main Changes

      Maintenance Release V1.4.0 of STM32CubeU5 Firmware Package supporting STM32U535xx, STM32U545xx, STM32U575xx, STM32U585xx, STM32U595xx, STM32U5A5xx, STM32U599xx, STM32U5A9xx, STM32U5F7xx, STM32U5G7xx, STM32U5F9xx and STM32U5G9xx devices

      -

      Contents

      +

      Contents

      CMSIS Drivers updates

      • CMSIS Device Official Release version of bits and registers definition aligned with RM0456 (STM32U5 reference manual) (Please Refer to the release notes for details)
      • Update STM32U5A5xx devices list with STM32U5A5QII3Q under “stm32u5xx.h” file
      -

      HAL/LL Drivers updates

      +

      HAL/LL Drivers updates

      • HAL and LL drivers Official Release for STM32U535xx/STM32U545xx, STM32U575xx/STM32U585xx, STM32U595xx/STM32U5A5xx, STM32U599xx/STM32U5A9xx, STM32U5F7xx/STM32U5G7xx and STM32U5F9xx/STM32U5G9xx devices (Please Refer to the release notes for details)
      • Update ADC HAL and LL drivers to fix known defects and add implementation enhancements
      • The HAL and LL drivers provided within this package are MISRA-C, MCU ASTYLE and CodeSonar compliant, and have been reviewed with a static analysis tool to eliminate possible run-time errors
      -

      BSP Drivers updates

      +

      BSP Drivers updates

      • Add stts22h BSP Component Driver
      • Add stm32u5x9j_discovery_env_sensors driver to support Temperature sensor on STM32U5x9J-DK board
      -

      Utilities updates

      +

      Utilities updates

      • Add of LPBAM utility version 1.4.0
      -

      Projects updates

      +

      Projects updates

      • Update BSP and HAL Templates (TZEN=0 and TZEN=1) projects on STM32U5x9J-DK board to support Temperature sensor with EWARM, MDK-ARM and STM32CubeIDE toolchains
      -

      +

      The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

      @@ -788,7 +1311,7 @@

    • The MicroLIB option should be enabled to display messages in HyperTerminal in the MDK-ARM projects. Detailed list is in the Project’s release notes.
    • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board.
    • -

      Components

      +

      Components

      The components flagged by “” have changed since the previous release. “” are new.

      @@ -1111,7 +1634,7 @@

      Components

      Drivers
      -

      Development toolchains and compilers

      +

      Development toolchains and compilers

      • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patches available here:
          @@ -1141,7 +1664,7 @@

          Development toolchains and compi

      • STM32CubeIDE V1.13.0 (gcc11.3.rel1.20230519-1941)
      -

      Supported Devices and boards

      +

      Supported Devices and boards

      • Devices:
          @@ -1162,7 +1685,7 @@

          Supported Devices and boards

        • STM32U5A9J-DK Discovery board rev.B
      -

      Dependencies

      +

      Dependencies

      • This software release is compatible with:
          @@ -1175,14 +1698,14 @@

          Dependencies

        • The IOT_HTTP_WebServer demonstration uses an updated version of STM32CubeU5_Demo_U585I-IOT02A_v1.2.hex binaries. To upgrade your B-U585I-IOT02A Discovery board with the required version V1.2, please visit B-U585I-IOT02A compiled demo binary
        • The EVAL Demonstration requires to have STM32CubeU5_Demo_STM32U575I-EV.hex binaries on your STM32U575I-EV Evaluation board with the required version V1.0. To upgrade your board, please visit STM32U575I-EV compiled demo binary
        -

        Known Limitations

        +

        Known Limitations

        • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to the table available in STM32CubeProjectsList.html
        • The component “USBX/CoreSystem” must be selected alongside either “USBX/UX Host CoreStack” or “USBX/UX Device CoreStack”
        • In NetXDuo, some configuration flags, that are not used in the STM32Cube FW package examples, might be non-functional when combined. This limitation will be fixed in upcoming releases
        • Comment error in “MX_WIFI BSP Component” Release_Notes : “The EMW3080B MXCHIP Wi-Fi module firmware version has to be V2.3.4 instead of V2.3.4 rc 13”
        -

        Backward compatibility

        +

        Backward compatibility

        • veml6030 BSP is replaced by veml3235 BSP component Driver in B-U585I-IOT02A projects
        @@ -1191,14 +1714,14 @@

        Backward compatibility

        -

        Main Changes

        +

        Main Changes

        First Official Release V1.3.0 of STM32CubeU5 Firmware Package supporting new STM32U5F9xx, STM32U5G9xx, STM32U5F7xx and STM32U5G7xx devices

        • Support of STM32U535xx, STM32U545xx, STM32U575xx, STM32U585xx, STM32U595xx, STM32U5A5xx, STM32U599xx, STM32U5A9xx, STM32U5F7xx, STM32U5G7xx, STM32U5F9xx and STM32U5G9xx devices
        • Add 2 new HAL drivers : GFXTIM and JPEG highlighting the graphics aspect of STM32U5F7/STM32U5G7/STM32U5F9/STM32U5G9 devices
        • Add 25 new projects on STM32U5G9J-DK2 board with EWARM, MDK-ARM and STM32CubeIDE toolchains
        -

        Contents

        +

        Contents

        CMSIS updates

        • Support of CMSIS version 5.9.0
        • @@ -1208,13 +1731,13 @@

          CMSIS Drivers updates

        • CMSIS Device Official Release version of bits and registers definition aligned with RM0456 (STM32U5 reference manual) (Please Refer to the release notes for details)
        • Add support of new STM32U5F9xx, STM32U5G9xx, STM32U5F7xx and STM32U5G7xx devices
        -

        HAL/LL Drivers updates

        +

        HAL/LL Drivers updates

        • HAL and LL drivers Official Release for STM32U535xx/STM32U545xx, STM32U575xx/STM32U585xx, STM32U595xx/STM32U5A5xx, STM32U599xx/STM32U5A9xx, STM32U5F7xx/STM32U5G7xx and STM32U5F9xx/STM32U5G9xx devices (Please Refer to the release notes for details)
        • Add 2 new HAL drivers : GFXTIM and JPEG highlighting the graphics aspect of STM32U5F7/STM32U5G7/STM32U5F9/STM32U5G9 devices
        • The HAL and LL drivers provided within this package are MISRA-C, MCU ASTYLE and CodeSonar compliant, and have been reviewed with a static analysis tool to eliminate possible run-time errors
        -

        BSP Drivers updates

        +

        BSP Drivers updates

        • Add STM32U5G9J-DK2 BSP Drivers to support STM32U5G9J-DK2 board for STM32U5F9xx and STM32U5G9xx devices
        • Update STM32U5GxJ-DK BSP Drivers to support STM32U5G9J-DK1 board for STM32U5F9xx and STM32U5G9xx devices
        • @@ -1223,17 +1746,17 @@

          BSP Drivers updates

        • Add rk050hr18 BSP Component Driver
        • Replace veml6030 by veml3235 BSP Component Driver
        -

        Middlewares updates

        +

        Middlewares updates

        • Support of STM32_USBPD_Core_Library version 4.1.2
        • Support of mcuboot version v1.7.2.10.20230607
        -

        Utilities updates

        +

        Utilities updates

        • Add JPEG utility
        • Add the support of stm32U5F9xx and stm32U5G9xx devices for LPBAM utility
        -

        Projects updates

        +

        Projects updates

        • Add 25 new projects on STM32U5G9J-DK2 board with EWARM, MDK-ARM and STM32CubeIDE toolchains support,
        • Add 1 new project “UART_WakeUpFromStopUsingFIFO” on NUCLEO-U575ZI-Q board with EWARM, MDK-ARM and STM32CubeIDE toolchains support,
        • @@ -1249,7 +1772,7 @@

          Projects updates

        • Add PWR_ModesSelection project on NUCLEO-U545RE-Q board with MDK-ARM toolchain support,
        • Add FLASH_SwapBanks project on NUCLEO-U575ZI-Q board with STM32CubeIDE toolchain support,
        -

        +

        The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

        @@ -1289,7 +1812,7 @@

      • The MicroLIB option should be enabled to display messages in HyperTerminal in the MDK-ARM projects. Detailed list is in the Project’s release notes.
      • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board.
      • -

        Components

        +

        Components

        The components flagged by “” have changed since the previous release. “” are new.

        @@ -1607,7 +2130,7 @@

        Components

        Drivers
        -

        Development toolchains and compilers

        +

        Development toolchains and compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patches available here:
            @@ -1637,7 +2160,7 @@

            Development toolchains and compi

        • STM32CubeIDE V1.13.0 (gcc11.3.rel1.20230519-1941)
        -

        Supported Devices and boards

        +

        Supported Devices and boards

        • Devices:
            @@ -1658,7 +2181,7 @@

            Supported Devices and boards

          • STM32U5A9J-DK Discovery board rev.B
        -

        Dependencies

        +

        Dependencies

        • This software release is compatible with:
            @@ -1671,14 +2194,14 @@

            Dependencies

          • The IOT_HTTP_WebServer demonstration uses an updated version of STM32CubeU5_Demo_U585I-IOT02A_v1.2.hex binaries. To upgrade your B-U585I-IOT02A Discovery board with the required version V1.2, please visit B-U585I-IOT02A compiled demo binary
          • The EVAL Demonstration requires to have STM32CubeU5_Demo_STM32U575I-EV.hex binaries on your STM32U575I-EV Evaluation board with the required version V1.0. To upgrade your board, please visit STM32U575I-EV compiled demo binary
          -

          Known Limitations

          +

          Known Limitations

          • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to the table available in STM32CubeProjectsList.html
          • The component “USBX/CoreSystem” must be selected alongside either “USBX/UX Host CoreStack” or “USBX/UX Device CoreStack”
          • In NetXDuo, some configuration flags, that are not used in the STM32Cube FW package examples, might be non-functional when combined. This limitation will be fixed in upcoming releases
          • Comment error in “MX_WIFI BSP Component” Release_Notes : “The EMW3080B MXCHIP Wi-Fi module firmware version has to be V2.3.4 instead of V2.3.4 rc 13”
          -

          Backward compatibility

          +

          Backward compatibility

          • veml6030 BSP is replaced by veml3235 BSP component Driver in B-U585I-IOT02A projects
          @@ -1687,9 +2210,9 @@

          Backward compatibility

          -

          Main Changes

          +

          Main Changes

          Official Release of STM32CubeU5 Firmware Package supporting STM32U535xx, STM32U545xx, STM32U575xx, STM32U585xx, STM32U595xx, STM32U5A5xx, STM32U599xx and STM32U5A9xx devices

          -

          Contents

          +

          Contents

          CMSIS Drivers updates

          CMSIS Device Official Release version of bits and registers definition aligned with RM0456 (STM32U5 reference manual) (Please Refer to the release notes for details)

            @@ -1697,14 +2220,14 @@

            CMSIS Drivers updates

          • Add startup files “startup_stm32u535xx.s” and “startup_stm32u545xx.s” for EWARM and STM32CUBEIDE toolchains
          • Add Universal serial bus full-speed host/device interface (USB) for STM32U535xx and STM32U545xx devices
          -

          HAL/LL Drivers updates

          +

          HAL/LL Drivers updates

          • HAL and LL drivers Official Release for STM32U535xx, STM32U545xx, STM32U575xx, STM32U585xx, STM32U595xx, STM32U5A5xx, STM32U599xx and STM32U5A9xx devices (Please Refer to the release notes for details)
          • Update USB HAL and LL drivers for STM32U535xx and STM32U545xx devices
          • General updates to fix known defects and implementation enhancements
          • The HAL and LL drivers provided within this package are MISRA-C and CodeSonar compliant, and have been reviewed with a static analysis tool to eliminate possible run-time errors
          -

          BSP Drivers updates

          +

          BSP Drivers updates

          • Add STM32U5x9J-DK BSP Driver to support STM32U5x9J-DK board for STM32U599xx and STM32U5A9xx devices
          • Update STM32U5xx_Nucleo BSP Driver to support NUCLEO-U545RE-Q board for STM32U535xx and STM32U545xx devices
          • @@ -1713,16 +2236,16 @@

            BSP Drivers updates

          • Add mx25um51245g BSP Component
          • Add sitronix BSP Component
          -

          Middlewares updates

          +

          Middlewares updates

          • Major update in AzureRTOS Middlewares (new version V6.2.0)
          • Major update in mbed-crypto Middleware
          -

          Utilities updates

          +

          Utilities updates

          • LPBAM: Add the support of stm32U535xx, stm32U545xx, stm32U595xx, stm32U5A5xx, stm32U599xx and stm32U5A9xx devices.
          -

          Projects updates

          +

          Projects updates

          • Add 45 new projects with EWARM, MDK-ARM and STM32CubeIDE toolchains. Detailed list is in the Project’s release notes:
          • Add 25 new projects on NUCLEO-U545RE-Q board: @@ -1763,7 +2286,7 @@

            Projects updates

        • TFM and SBSFU Applications runs on STM32U585xx devices and it is possible to tailor the applications for STM32U5A5xx or STM32U545xx devices (details are provided in the applications readme files)
        -

        +

        The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

        @@ -1803,7 +2326,7 @@

      • The MicroLIB option should be enabled to display messages in HyperTerminal in the MDK-ARM projects. Detailed list is in the Project’s release notes.
      • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board.
      • -

        Components

        +

        Components

        The components flagged by “” have changed since the previous release. “” are new.

        @@ -2096,7 +2619,7 @@

        Components

        Drivers
        -

        Development toolchains and compilers

        +

        Development toolchains and compilers

        • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patches available here:
            @@ -2114,7 +2637,7 @@

            Development toolchains and compi

        • STM32CubeIDE V1.12.0 (gcc10.3-2021.10)
        -

        Supported Devices and boards

        +

        Supported Devices and boards

        • STM32U575/STM32U585 devices
        • STM32U595/STM32U5A5/STM32U599/STM32U5A9 devices
        • @@ -2126,7 +2649,7 @@

          Supported Devices and boards

        • NUCLEO-U5A5ZJ-Q Nucleo board rev.C
        • STM32U5x9J-DK Discovery board rev.B
        -

        Dependencies

        +

        Dependencies

        • This software release is compatible with:
            @@ -2140,7 +2663,7 @@

            Dependencies

          • The IOT_HTTP_WebServer demonstration uses an updated version of STM32CubeU5_Demo_U585I-IOT02A_v1.2.hex binaries. To upgrade your B-U585I-IOT02A Discovery board with the required version V1.2, please visit B-U585I-IOT02A compiled demo binary
          • The EVAL Demonstration requires to have STM32CubeU5_Demo_STM32U575I-EV.hex binaries on your STM32U575I-EV Evaluation board with the required version V1.0, please visit STM32U575I-EV compiled demo binary
          -

          Known Limitations

          +

          Known Limitations

          • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to this table STM32CubeProjectsList.html
          • The component “USBX/CoreSystem” must be selected alongside either “USBX/UX Host CoreStack” or “USBX/UX Device CoreStack”
          • @@ -2152,7 +2675,7 @@

            Known Limitations

          • NUCLEO-U575ZI-Q\Examples\FLASH\FLASH_SwapBanks STM32CubeIDE support will be provided in the next release v1.3.0
          • B-U585I-IOT02A\Demonstrations\IOT_HTTP_WebServer with MDK-ARM and STM32CubeIDE toolchains will be reworked for the next release v1.3.0
          -

          Backward compatibility

          +

          Backward compatibility

          • m24lr64 BSP is replaced by m24256 BSP component in B-U585I-IOT02A and STM32U575I-EV projects
          @@ -2161,13 +2684,13 @@

          Backward compatibility

          -

          Main Changes

          +

          Main Changes

          Patch release of STM32CubeU5 Firmware Package

          • Update of ThreadX and NetDuoX Middlewares to new version V6.1.10
          • Add LPBAM application LPBAM_ADC_TempSense on NUCLEO-U575ZI-Q board
          -

          Contents

          +

          Contents

          Middlewares Drivers updates

          • Update of ThreadX and NetDuoX Middlewares to new version V6.1.10
          • @@ -2176,7 +2699,7 @@

            Utilities Drivers updates
          • Update of LPBAM Utility to new version V1.1.1
          -

          Projects updates

          +

          Projects updates

          • Add LPBAM application LPBAM_ADC_TempSense on NUCLEO-U575ZI-Q board in STM32CubeMX V6.5.0 supported with IAR, MDK-ARM and STM32CubeIDE toolchains
          @@ -2196,7 +2719,7 @@

          Projects updates

          -

          +

          The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

          @@ -2261,7 +2784,7 @@

        • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board
        • -

          Components

          +

          Components

          The components flagged by “” have changed since the previous release. “” are new.

          @@ -2534,7 +3057,7 @@

          Components

          Drivers
          -

          Development toolchains and compilers

          +

          Development toolchains and compilers

          • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patches available here:
              @@ -2552,7 +3075,7 @@

              Development toolchains and compi

          • STM32CubeIDE V1.9.0 (10.3-2021.10)
          -

          Supported Devices and Boards

          +

          Supported Devices and Boards

          • STM32U575/STM32U585 devices
          • STM32U595/STM32U5A5/STM32U599/STM32U5A9 devices
          • @@ -2560,7 +3083,7 @@

            Supported Devices and Boards

          • STM32U575I-EV Evaluation board rev.C
          • B-U585I-IOT02A Discovery board rev.C
          -

          Dependencies

          +

          Dependencies

          • This software release is compatible with:
              @@ -2571,7 +3094,7 @@

              Dependencies

            • The EMW3080B MXCHIP Wi-Fi module firmware used version is V2.1.11 and the way to update your board with it are available at x-wifi-emw3080b
            • The BLE_AT_Client application requires to have Flash BLE_AT_Server module application using STM32CubeProgrammer: file BLE_AT_Server_reference.hex present in .\STM32Cube_FW_WB_V1.x.x\Projects\P-NUCLEO-WB55.Nucleo\Applications\BLE\BLE_AT_Server\Binary\BLE_AT_Server_reference.hex
            -

            Known limitations

            +

            Known limitations

            • BSP MXCHIP: Access point mode with the TCP/IP mode on STM32 host is not functional. It works when TCP/IP runs on the EMW3080B module
            • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to this table STM32CubeProjectsList.html
            • @@ -2599,14 +3122,14 @@

              Known limitations

            • Nx_MDNS
          -

          Backward compatibility

          +

          Backward compatibility

          This release is compatible with the previous versions

          -

          Main Changes

          +

          Main Changes

          • Maintenance Release of STM32CubeU5 Firmware Package
          @@ -2635,7 +3158,7 @@

          CMSIS Device updates

        • Add TIM3 and TIM4 are missing in IS_TIM_32B_COUNTER_INSTANCE macro definition
      -

      HAL/LL Drivers updates

      +

      HAL/LL Drivers updates

      • HAL and LL drivers Maintenance Release for STM32U575xx / STM32U585xx devices and new support of STM32U595xx, STM32U5A5xx, STM32U599xx and STM32U5A9xx devices (Please Refer to the release notes for details)
      • Add New LTDC, GFXMMU, DSI, GPU2D HAL drivers highlighting the graphics aspect of STM32U595/STM32U5A5/STM32U599/STM32U5A9 devices
      • @@ -2865,13 +3388,13 @@

        Middlewares Drivers upda
      • Add support of data provisioning
    -

    BSP Drivers updates

    +

    BSP Drivers updates

    • Rework Audio BSP driver on B-U585I-IOT02A board
    • Add New ranging sensor BSP driver on B-U585I-IOT02A board
    • Add New VL53L5CX BSP component driver
    -

    Contents

    +

    Contents

    Projects

    The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

    This release contains all HAL drivers, LL drivers, BSP drivers, templates, projects, demonstrations and examples

    @@ -2965,7 +3488,7 @@

    Projects

  • The user should unplug then Plug STLINK connection on Slave Board to perform a power-on-reset when running I2C_WakeUpFromStop example on NUCLEO-U575ZI-Q board
  • -

    Components

    +

    Components

    The components flagged by “” have changed since the previous release. “” are new.

    @@ -3238,7 +3761,7 @@

    Components

    Drivers
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.9 + ST-LINK, patches available here:
        @@ -3256,7 +3779,7 @@

        Development Toolchains and Compi

    • STM32CubeIDE V1.9.0 (10.3-2021.10)
    -

    Supported Devices and boards

    +

    Supported Devices and boards

    • STM32U575/STM32U585 devices
    • STM32U595/STM32U5A5/STM32U599/STM32U5A9 devices
    • @@ -3264,13 +3787,13 @@

      Supported Devices and boards

    • STM32U575I-EV Evaluation board rev.C
    • B-U585I-IOT02A Discovery board rev.C
    -

    Dependencies

    +

    Dependencies

    • STM32CubeMX Version: Projects are generated using STM32CubeMX V6.5.0
    • The EMW3080B MXCHIP Wi-Fi module firmware used version is V2.1.11 and the way to update your board with it are available at x-wifi-emw3080b
    • The BLE_AT_Client application requires to have Flash BLE_AT_Server module application using STM32CubeProgrammer: file BLE_AT_Server_reference.hex present in .\STM32Cube_FW_WB_V1.x.x\Projects\P-NUCLEO-WB55.Nucleo\Applications\BLE\BLE_AT_Server\Binary\BLE_AT_Server_reference.hex
    -

    Known Limitations

    +

    Known Limitations

    • BSP MXCHIP: Access point mode with the TCP/IP mode on STM32 host is not functional. It works when TCP/IP runs on the EMW3080B module
    • Some project are not generated with STM32CubeMX tool for the exhaustive list please refer to this table STM32CubeProjectsList.html
    • @@ -3299,7 +3822,7 @@

      Known Limitations

    • Nx_MDNS
    -

    Backward Compatibility

    +

    Backward Compatibility

    • HAL RCC driver: Rename Clk48ClockSelection to IclkClockSelection in RCC_PeriphCLKInitTypeDef
    @@ -3308,11 +3831,11 @@

    Backward Compatibility

    -

    Main Changes

    +

    Main Changes

    • Patch Release of STM32CubeU5 Firmware Package
    -

    HAL/LL Drivers updates

    +

    HAL/LL Drivers updates

    • LL Drivers updates
        @@ -3327,7 +3850,7 @@

        HAL/LL Drivers updates

    • Backward compatibility ensured by legacy defines
    -

    Contents

    +

    Contents

    Projects

    The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

    This release contains all HAL drivers, LL drivers, BSP drivers, templates, projects and examples.

    @@ -3368,7 +3891,7 @@

    Projects

    Please refer to AN5347 for more details.

    -

    Components

    +

    Components

    The components flagged by “” have changed since the previous release. “” are new.

    @@ -3621,7 +4144,7 @@

    Components

    Drivers
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.6 + ST-LINK, patch available here:
        @@ -3635,14 +4158,14 @@

        Development Toolchains and Compi

    • STM32CubeIDE v1.7.0 (gcc9_2020_q2_update)
    -

    Supported Devices and boards

    +

    Supported Devices and boards

    • STM32U575/STM32U585 devices
    • NUCLEO-U575ZI-Q Nucleo board rev.C
    • STM32U575I-EV Evaluation board rev.C
    • B-U585I-IOT02A Discovery board rev.C
    -

    Dependencies

    +

    Dependencies

    • STM32CubeMX V6.3.0
        @@ -3651,7 +4174,7 @@

        Dependencies

      • The EMW3080B MXCHIP Wi-Fi module firmware used version is V2.1.11 and the way to update your board with it are available at x-wifi-emw3080b.
      • The BLE_AT_Client application requires to have Flash BLE_AT_Server module application using STM32CubeProgrammer: file BLE_AT_Server.hex is present in the BLE_AT_Client application under Module Binary folder.
      -

      Known Limitations

      +

      Known Limitations

      • The ThreadX “tx_queue_create” API is not correctly used in some Azure RTOS applications leading to potential instabilities. These limitations will be fixed in future releases.
      • BSP MXCHIP: Access point mode with the TCP/IP mode on STM32 host is not functional. It works when TCP/IP runs on the EMW3080B module.
      • @@ -3665,7 +4188,7 @@

        Known Limitations

      • Remove Audio IN functionality from B-U585I-IOT02A BSP example.
      • The SMPS regulator configuration in all projects is not supported by STM32CubeMX V6.3.0 (will be provided in next releases).
      -

      Backward Compatibility

      +

      Backward Compatibility

      • LPBAM Utility : This version breaks the compatibility with previous version for DAC, LPTIM, I2C and SPI modules.
      @@ -3674,7 +4197,7 @@

      Backward Compatibility

      -

      Main Changes

      +

      Main Changes

      • Patch Release of STM32CubeU5 Firmware Package
      @@ -3688,7 +4211,7 @@

      CMSIS Device updates

    • Fix wrong IRQn name in partition_stm32u5xx.h
    -

    HAL/LL Drivers updates

    +

    HAL/LL Drivers updates

    • HAL and LL drivers Patch Release for STM32U575xx / STM32U585xx devices (Please Refer to the release notes for details)
    • HAL Drivers @@ -3731,7 +4254,7 @@

      HAL/LL Drivers updates

    -

    BSP Drivers updates

    +

    BSP Drivers updates

    • B-U585I-IOT02A BSP Drivers Updated version of B-U585I-IOT02A BSP drivers
        @@ -3756,7 +4279,7 @@

        Projects

      • Update all projects to support SMPS regulator configuration to enhance power consumption
      • Add veml6030 and ism330dhcx new BSP components to B-U585I-IOT02A Templates and BSP example
      -

      Contents

      +

      Contents

      Projects

      The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

      This release contains all HAL drivers, LL drivers, BSP drivers, templates, projects and examples.

      @@ -3797,7 +4320,7 @@

      Projects

    Please refer to AN5347 for more details.

    -

    Components

    +

    Components

    The components flagged by “” have changed since the previous release. “” are new.

    @@ -4050,7 +4573,7 @@

    Components

    Drivers
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.6 + ST-LINK, patch available here:
        @@ -4064,14 +4587,14 @@

        Development Toolchains and Compi

    • STM32CubeIDE v1.7.0 (gcc9_2020_q2_update)
    -

    Supported Devices and boards

    +

    Supported Devices and boards

    • STM32U575/STM32U585 devices
    • NUCLEO-U575ZI-Q Nucleo board rev.C
    • STM32U575I-EV Evaluation board rev.C
    • B-U585I-IOT02A Discovery board rev.C
    -

    Dependencies

    +

    Dependencies

    • STM32CubeMX V6.3.0
        @@ -4080,7 +4603,7 @@

        Dependencies

      • The EMW3080B MXCHIP Wi-Fi module firmware used version is V2.1.11 and the way to update your board with it are available at x-wifi-emw3080b.
      • The BLE_AT_Client application requires to have Flash BLE_AT_Server module application using STM32CubeProgrammer: file BLE_AT_Server.hex is present in the BLE_AT_Client application under Module Binary folder.
      -

      Known Limitations

      +

      Known Limitations

      • The ThreadX “tx_queue_create” API is not correctly used in some Azure RTOS applications leading to potential instabilities. These limitations will be fixed in future releases.
      • BSP MXCHIP: Access point mode with the TCP/IP mode on STM32 host is not functional. It works when TCP/IP runs on the EMW3080B module.
      • @@ -4094,7 +4617,7 @@

        Known Limitations

      • Remove Audio IN functionality from B-U585I-IOT02A BSP example.
      • The SMPS regulator configuration in all projects is not supported by STM32CubeMX V6.3.0 (will be provided in next releases).
      -

      Backward Compatibility

      +

      Backward Compatibility

      • LPBAM Utility : This version breaks the compatibility with previous version for DAC, LPTIM, I2C and SPI modules.
      @@ -4103,11 +4626,11 @@

      Backward Compatibility

      -

      Main Changes

      +

      Main Changes

      • First Official Release of STM32CubeU5 Firmware Package
      -

      Contents

      +

      Contents

      Projects

      The STM32CubeU5 Firmware package comes with template running on STMicroelectronics boards, organized by board and provided with preconfigured projects for the main supported toolchains. The exhaustive list of projects is provided in this table STM32CubeProjectsList.html

      This release contains almost HAL drivers, LL drivers, BSP drivers, templates, projects and examples.

      @@ -4148,7 +4671,7 @@

      Projects

    Please refer to AN5347 for more details.

    -

    Components

    +

    Components

    The components flagged by “” have changed since the previous release. “” are new.

    @@ -4396,7 +4919,7 @@

    Components

    Drivers
    -

    Development Toolchains and Compilers

    +

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V8.50.6 + ST-LINK, patch available here:
        @@ -4410,14 +4933,14 @@

        Development Toolchains and Compi

    • STM32CubeIDE v1.7.0
    -

    Supported Devices and boards

    +

    Supported Devices and boards

    • STM32U575/STM32U585 devices
    • NUCLEO-U575ZI-Q Nucleo board rev.C
    • STM32U575I-EV Evaluation board rev.C
    • B-U585I-IOT02A Discovery board rev.C
    -

    Dependencies

    +

    Dependencies

    • STM32CubeMX V6.3.0
        @@ -4425,7 +4948,7 @@

        Dependencies

    • The EMW3080B MXCHIP Wi-Fi module firmware and the way to update your board with it are available at https://www.st.com/en/development-tools/x-wifi-emw3080b.html. Before using the projects with Wi-Fi connectivity, you shall update your B-U585I-IOT02A RevC board with the EMW3080B firmware version 2.1.11. To achieve this, follow the instructions given at the above link, using the EMW3080updateV2.1.11RevC.bin flasher under the V2.1.11/SPI folder.
    -

    Known Limitations

    +

    Known Limitations

    • BSP MXCHIP: Access point mode with the TCP/IP mode on STM32 host is not functional. It works when TCP/IP runs on the EMW3080B module.
    • When using STM32CubeIDE v1.7.0 with an STM32U575-EV Evaluation board, the user should either use ST-LINK(OpenOCD) or set the SWD frequency to 1MHz or 8 MHz manually if using STLINK(GDB server).
    • @@ -4474,7 +4997,7 @@

      Known Limitations

    • All AzureRTOS Applications are not provided with MDK-ARM
    -

    Backward Compatibility

    +

    Backward Compatibility

    • Not applicable
    diff --git a/stm32cube/stm32u5xx/soc/stm32u595xx.h b/stm32cube/stm32u5xx/soc/stm32u595xx.h index 2f477ea19..826be4886 100644 --- a/stm32cube/stm32u5xx/soc/stm32u595xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u595xx.h @@ -22847,7 +22847,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u599xx.h b/stm32cube/stm32u5xx/soc/stm32u599xx.h index 42a51354e..4d0490618 100644 --- a/stm32cube/stm32u5xx/soc/stm32u599xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u599xx.h @@ -26681,7 +26681,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u5a5xx.h b/stm32cube/stm32u5xx/soc/stm32u5a5xx.h index 99ff521aa..9a59e8c71 100644 --- a/stm32cube/stm32u5xx/soc/stm32u5a5xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u5a5xx.h @@ -23509,7 +23509,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u5a9xx.h b/stm32cube/stm32u5xx/soc/stm32u5a9xx.h index fd32351f8..d0fb1444b 100644 --- a/stm32cube/stm32u5xx/soc/stm32u5a9xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u5a9xx.h @@ -27343,7 +27343,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u5f7xx.h b/stm32cube/stm32u5xx/soc/stm32u5f7xx.h index 6d864ad12..8737137c0 100644 --- a/stm32cube/stm32u5xx/soc/stm32u5f7xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u5f7xx.h @@ -24528,7 +24528,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u5f9xx.h b/stm32cube/stm32u5xx/soc/stm32u5f9xx.h index d3312a480..d53b4ceed 100644 --- a/stm32cube/stm32u5xx/soc/stm32u5f9xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u5f9xx.h @@ -27681,7 +27681,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u5g7xx.h b/stm32cube/stm32u5xx/soc/stm32u5g7xx.h index 95bc2d721..2d0abbb6e 100644 --- a/stm32cube/stm32u5xx/soc/stm32u5g7xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u5g7xx.h @@ -25190,7 +25190,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ diff --git a/stm32cube/stm32u5xx/soc/stm32u5g9xx.h b/stm32cube/stm32u5xx/soc/stm32u5g9xx.h index ad46cc19a..d83b0017f 100644 --- a/stm32cube/stm32u5xx/soc/stm32u5g9xx.h +++ b/stm32cube/stm32u5xx/soc/stm32u5g9xx.h @@ -28343,7 +28343,7 @@ typedef struct #define USB_OTG_GCCFG_FSVPLUS_Msk (0x1U << USB_OTG_GCCFG_FSVPLUS_Pos) /*!< 0x00000002 */ #define USB_OTG_GCCFG_FSVPLUS USB_OTG_GCCFG_FSVPLUS_Msk /*!< Single-Ended DP2 indicator DP voltage level */ #define USB_OTG_GCCFG_FSVMINUS_Pos (2U) -#define USB_OTG_GCCFG_FSVMINUS_Msk 0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ +#define USB_OTG_GCCFG_FSVMINUS_Msk (0x1U << USB_OTG_GCCFG_FSVMINUS_Pos) /*!< 0x00000004 */ #define USB_OTG_GCCFG_FSVMINUS USB_OTG_GCCFG_FSVMINUS_Msk /*!< Single-Ended DM2 indicator DM voltage level */ #define USB_OTG_GCCFG_SESSVLD_Pos (3U) #define USB_OTG_GCCFG_SESSVLD_Msk (0x1U << USB_OTG_GCCFG_SESSVLD_Pos) /*!< 0x00000008 */ From dfa0b99160b84ecc365785e35099ac5dea3a65d1 Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 16:36:50 +0200 Subject: [PATCH 09/11] stm32cube: update stm32wb to cube version V1.20.0 Update Cube version for STM32WBxx series on https://github.com/STMicroelectronics from version v1.19.1 to version v1.20.0 Signed-off-by: Guillaume Gautier --- stm32cube/stm32wbxx/README | 4 +- .../drivers/include/Legacy/stm32_hal_legacy.h | 25 +- .../drivers/include/stm32wbxx_hal_comp.h | 70 +-- .../drivers/include/stm32wbxx_hal_uart.h | 5 +- .../drivers/include/stm32wbxx_ll_lpuart.h | 15 + .../drivers/include/stm32wbxx_ll_rng.h | 2 +- .../stm32wbxx/drivers/src/stm32wbxx_hal.c | 2 +- .../drivers/src/stm32wbxx_hal_comp.c | 8 +- .../stm32wbxx/drivers/src/stm32wbxx_hal_i2c.c | 40 +- .../drivers/src/stm32wbxx_hal_smbus_ex.c | 2 + .../drivers/src/stm32wbxx_hal_uart.c | 2 + .../drivers/src/stm32wbxx_hal_uart_ex.c | 2 +- .../stm32wbxx/drivers/src/stm32wbxx_ll_comp.c | 10 +- .../stm32wbxx/drivers/src/stm32wbxx_ll_rng.c | 2 +- stm32cube/stm32wbxx/release_note.html | 448 +++++++++--------- stm32cube/stm32wbxx/soc/stm32wbxx.h | 2 +- 16 files changed, 358 insertions(+), 281 deletions(-) diff --git a/stm32cube/stm32wbxx/README b/stm32cube/stm32wbxx/README index 16ab6a366..941f12cbc 100644 --- a/stm32cube/stm32wbxx/README +++ b/stm32cube/stm32wbxx/README @@ -6,7 +6,7 @@ Origin: http://www.st.com/en/embedded-software/stm32cubewb.html Status: - version v1.19.1 + version v1.20.0 Purpose: ST Microelectronics official MCU package for STM32WB series. @@ -23,7 +23,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeWB Commit: - ea5475b0d214489a3a3556f7b3f66d0954d006e0 + 529e571e91c93d4bf1aae6e0d69b9a5dcf4d828d Maintained-by: External diff --git a/stm32cube/stm32wbxx/drivers/include/Legacy/stm32_hal_legacy.h b/stm32cube/stm32wbxx/drivers/include/Legacy/stm32_hal_legacy.h index d1f4f7e67..73ae9eedd 100644 --- a/stm32cube/stm32wbxx/drivers/include/Legacy/stm32_hal_legacy.h +++ b/stm32cube/stm32wbxx/drivers/include/Legacy/stm32_hal_legacy.h @@ -806,6 +806,21 @@ extern "C" { #define GPIO_AF0_S2DSTOP GPIO_AF0_SRDSTOP #define GPIO_AF11_LPGPIO GPIO_AF11_LPGPIO1 #endif /* STM32U5 */ + +#if defined(STM32WBA) +#define GPIO_AF11_RF_ANTSW0 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW1 GPIO_AF11_RF +#define GPIO_AF11_RF_ANTSW2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO1 GPIO_AF11_RF +#define GPIO_AF11_RF_IO2 GPIO_AF11_RF +#define GPIO_AF11_RF_IO3 GPIO_AF11_RF +#define GPIO_AF11_RF_IO4 GPIO_AF11_RF +#define GPIO_AF11_RF_IO5 GPIO_AF11_RF +#define GPIO_AF11_RF_IO6 GPIO_AF11_RF +#define GPIO_AF11_RF_IO7 GPIO_AF11_RF +#define GPIO_AF11_RF_IO8 GPIO_AF11_RF +#define GPIO_AF11_RF_IO9 GPIO_AF11_RF +#endif /* STM32WBA */ /** * @} */ @@ -1817,7 +1832,7 @@ extern "C" { #define HAL_FMPI2CEx_AnalogFilter_Config HAL_FMPI2CEx_ConfigAnalogFilter #define HAL_FMPI2CEx_DigitalFilter_Config HAL_FMPI2CEx_ConfigDigitalFilter -#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) ((cmd == ENABLE)? \ +#define HAL_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus, cmd) (((cmd) == ENABLE)? \ HAL_I2CEx_EnableFastModePlus(SYSCFG_I2CFastModePlus): \ HAL_I2CEx_DisableFastModePlus(SYSCFG_I2CFastModePlus)) @@ -2731,6 +2746,12 @@ extern "C" { #define __APB1_RELEASE_RESET __HAL_RCC_APB1_RELEASE_RESET #define __APB2_FORCE_RESET __HAL_RCC_APB2_FORCE_RESET #define __APB2_RELEASE_RESET __HAL_RCC_APB2_RELEASE_RESET +#if defined(STM32C0) +#define __HAL_RCC_APB1_FORCE_RESET __HAL_RCC_APB1_GRP1_FORCE_RESET +#define __HAL_RCC_APB1_RELEASE_RESET __HAL_RCC_APB1_GRP1_RELEASE_RESET +#define __HAL_RCC_APB2_FORCE_RESET __HAL_RCC_APB1_GRP2_FORCE_RESET +#define __HAL_RCC_APB2_RELEASE_RESET __HAL_RCC_APB1_GRP2_RELEASE_RESET +#endif /* STM32C0 */ #define __BKP_CLK_DISABLE __HAL_RCC_BKP_CLK_DISABLE #define __BKP_CLK_ENABLE __HAL_RCC_BKP_CLK_ENABLE #define __BKP_FORCE_RESET __HAL_RCC_BKP_FORCE_RESET @@ -3910,7 +3931,7 @@ extern "C" { */ #if defined (STM32G0) || defined (STM32L5) || defined (STM32L412xx) || defined (STM32L422xx) || \ defined (STM32L4P5xx)|| defined (STM32L4Q5xx) || defined (STM32G4) || defined (STM32WL) || defined (STM32U5) || \ - defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) + defined (STM32WBA) || defined (STM32H5) || defined (STM32C0) || defined (STM32H7RS) || defined (STM32U0) #else #define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG #endif diff --git a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_comp.h b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_comp.h index a45165d43..2ec9ee9e6 100644 --- a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_comp.h +++ b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_comp.h @@ -159,13 +159,15 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer /** @defgroup COMP_WindowMode COMP Window Mode * @{ */ -#define COMP_WINDOWMODE_DISABLE (0x00000000UL) /*!< Window mode disable: Comparators instances - pair COMP1 and COMP2 are independent */ -#define COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON (COMP_CSR_WINMODE) /*!< Window mode enable: Comparators instances - pair COMP1 and COMP2 have their input plus - connected together. The common input is - COMP1 input plus - (COMP2 input plus is no more accessible). */ +#define COMP_WINDOWMODE_DISABLE (0x00000000UL) /*!< Window mode disable: Comparators + instances pair COMP1 and COMP2 are + independent */ +#define COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON (COMP_CSR_WINMODE) /*!< Window mode enable: Comparators instances + pair COMP1 and COMP2 have their input + plus connected together. + The common input is COMP1 input plus + (COMP2 input plus is no more accessible). + */ /** * @} */ @@ -383,16 +385,16 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP1 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP1); \ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP1);\ +#define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP1); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP1); \ } while(0) /** * @brief Disable the COMP1 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ +#define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP1); \ LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP1);\ } while(0) @@ -468,16 +470,16 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer * @brief Enable the COMP2 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ - LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP2); \ - LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP2); \ +#define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_FALLING_EDGE() do { \ + LL_EXTI_EnableRisingTrig_0_31(COMP_EXTI_LINE_COMP2); \ + LL_EXTI_EnableFallingTrig_0_31(COMP_EXTI_LINE_COMP2); \ } while(0) /** * @brief Disable the COMP2 EXTI line rising & falling edge trigger. * @retval None */ -#define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ +#define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_FALLING_EDGE() do { \ LL_EXTI_DisableRisingTrig_0_31(COMP_EXTI_LINE_COMP2); \ LL_EXTI_DisableFallingTrig_0_31(COMP_EXTI_LINE_COMP2);\ } while(0) @@ -613,25 +615,25 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer /* Note: On this STM32 series, comparator input minus parameters are */ /* the same on all COMP instances. */ /* However, comparator instance kept as macro parameter for */ -/* compatibility with other STM32 families. */ +/* compatibility with other STM32 series. */ #if defined(COMP_INPUT_MINUS_IO2) -#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO3) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO4) ||\ +#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO3) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO4) || \ ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO5)) #else -#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO3) ||\ - ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO4) ||\ +#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO3) || \ + ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO4) || \ ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO5)) #endif @@ -644,9 +646,9 @@ typedef void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer ((__POL__) == COMP_OUTPUTPOL_INVERTED)) #define IS_COMP_BLANKINGSRCE(__OUTPUT_BLANKING_SOURCE__) \ - ( ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5) \ - || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3) \ + (((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_NONE) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5) \ + || ((__OUTPUT_BLANKING_SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3) \ ) /* Note: Output blanking source common to all COMP instances */ diff --git a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_uart.h b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_uart.h index d37c25d10..763bfb229 100644 --- a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_uart.h +++ b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_hal_uart.h @@ -1232,7 +1232,7 @@ typedef void (*pUART_RxEventCallbackTypeDef) /** @defgroup UART_Private_Macros UART Private Macros * @{ */ -/** @brief Get UART clok division factor from clock prescaler value. +/** @brief Get UART clock division factor from clock prescaler value. * @param __CLOCKPRESCALER__ UART prescaler value. * @retval UART clock division factor */ @@ -1247,8 +1247,7 @@ typedef void (*pUART_RxEventCallbackTypeDef) ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV16) ? 16U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV32) ? 32U : \ ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV64) ? 64U : \ - ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : \ - ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV256) ? 256U : 1U) + ((__CLOCKPRESCALER__) == UART_PRESCALER_DIV128) ? 128U : 256U) #if defined(LPUART1) /** @brief BRR division operation to set BRR register with LPUART. diff --git a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_lpuart.h b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_lpuart.h index bfb37a9d8..d29d2ddd6 100644 --- a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_lpuart.h +++ b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_lpuart.h @@ -2605,6 +2605,21 @@ __STATIC_INLINE void LL_LPUART_RequestRxDataFlush(USART_TypeDef *LPUARTx) SET_BIT(LPUARTx->RQR, (uint16_t)USART_RQR_RXFRQ); } +/** + * @brief Request a Transmit data FIFO flush + * @note TXFRQ bit is set to flush the whole FIFO when FIFO mode is enabled. This + * also sets the flag TXFE (TXFIFO empty bit in the LPUART_ISR register). + * @note Macro IS_UART_FIFO_INSTANCE(USARTx) can be used to check whether or not + * FIFO mode feature is supported by the USARTx instance. + * @rmtoll RQR TXFRQ LL_LPUART_RequestTxDataFlush + * @param LPUARTx LPUART Instance + * @retval None + */ +__STATIC_INLINE void LL_LPUART_RequestTxDataFlush(USART_TypeDef *LPUARTx) +{ + SET_BIT(LPUARTx->RQR, (uint16_t)USART_RQR_TXFRQ); +} + /** * @} */ diff --git a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_rng.h b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_rng.h index 462fad33b..00bb4cd50 100644 --- a/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_rng.h +++ b/stm32cube/stm32wbxx/drivers/include/stm32wbxx_ll_rng.h @@ -369,7 +369,7 @@ __STATIC_INLINE uint32_t LL_RNG_ReadRandData32(const RNG_TypeDef *RNGx) /** @defgroup RNG_LL_EF_Init Initialization and de-initialization functions * @{ */ -ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, LL_RNG_InitTypeDef *RNG_InitStruct); +ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, const LL_RNG_InitTypeDef *RNG_InitStruct); void LL_RNG_StructInit(LL_RNG_InitTypeDef *RNG_InitStruct); ErrorStatus LL_RNG_DeInit(const RNG_TypeDef *RNGx); diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal.c index e19fb9a97..2dcc929e6 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal.c @@ -56,7 +56,7 @@ */ #define __STM32WBxx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ #define __STM32WBxx_HAL_VERSION_SUB1 (0x0EU) /*!< [23:16] sub1 version */ -#define __STM32WBxx_HAL_VERSION_SUB2 (0x02U) /*!< [15:8] sub2 version */ +#define __STM32WBxx_HAL_VERSION_SUB2 (0x03U) /*!< [15:8] sub2 version */ #define __STM32WBxx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32WBxx_HAL_VERSION ((__STM32WBxx_HAL_VERSION_MAIN << 24U)\ |(__STM32WBxx_HAL_VERSION_SUB1 << 16U)\ diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_comp.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_comp.c index 3da9a711d..c5b28e170 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_comp.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_comp.c @@ -28,9 +28,7 @@ [..] The STM32WBxx device family integrates two analog comparators instances: COMP1, COMP2 except for the STM32WB15xx, STM32WB10xx products featuring only - one instance: COMP1. - In the rest of the file, all comments related to a pair of comparators are not - applicable to STM32WB15xx, STM32WB10xx. + one instance: COMP1 (in this case, all comments related to pair of comparators are not applicable) (#) Comparators input minus (inverting input) and input plus (non inverting input) can be set to internal references or to GPIO pins (refer to GPIO list in reference manual). @@ -260,7 +258,7 @@ HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp) #if defined(COMP2) assert_param(IS_COMP_WINDOWMODE(hcomp->Init.WindowMode)); -#endif +#endif /* COMP2 */ if (hcomp->State == HAL_COMP_STATE_RESET) @@ -318,7 +316,7 @@ HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp) #else MODIFY_REG(hcomp->Instance->CSR, COMP_CSR_PWRMODE | COMP_CSR_INMSEL | COMP_CSR_INPSEL | - COMP_CSR_POLARITY | COMP_CSR_HYST | + COMP_CSR_POLARITY | COMP_CSR_HYST | COMP_CSR_BLANKING | COMP_CSR_BRGEN | COMP_CSR_SCALEN | COMP_CSR_INMESEL, tmp_csr ); diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_i2c.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_i2c.c index de3805e86..ef5eaf81a 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_i2c.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_i2c.c @@ -90,7 +90,7 @@ add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. @@ -156,7 +156,7 @@ HAL_I2C_Master_Seq_Receive_IT() or using HAL_I2C_Master_Seq_Receive_DMA() (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (++) Abort a master or memory IT or DMA I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() @@ -214,7 +214,7 @@ add their own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and users can add their own code by customization of function pointer HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() + (+) Abort a master or memory I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and users can add their own code by customization of function pointer HAL_I2C_AbortCpltCallback() (+) Discard a slave I2C process communication using __HAL_I2C_GENERATE_NACK() macro. @@ -1413,14 +1413,6 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData /* Enable Address Acknowledge */ hi2c->Instance->CR2 &= ~I2C_CR2_NACK; - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) - { - /* Disable Address Acknowledge */ - hi2c->Instance->CR2 |= I2C_CR2_NACK; - return HAL_ERROR; - } - /* Preload TX data if no stretch enable */ if (hi2c->Init.NoStretchMode == I2C_NOSTRETCH_ENABLE) { @@ -1434,6 +1426,18 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData hi2c->XferCount--; } + /* Wait until ADDR flag is set */ + if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + + return HAL_ERROR; + } + /* Clear ADDR flag */ __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); @@ -1445,6 +1449,10 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData { /* Disable Address Acknowledge */ hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + return HAL_ERROR; } @@ -1457,6 +1465,10 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData { /* Disable Address Acknowledge */ hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Flush TX register */ + I2C_Flush_TXDR(hi2c); + return HAL_ERROR; } @@ -4574,7 +4586,7 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) } /** - * @brief Abort a master I2C IT or DMA process communication with Interrupt. + * @brief Abort a master or memory I2C IT or DMA process communication with Interrupt. * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress Target device address: The device 7 bits address value @@ -4583,7 +4595,9 @@ HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) */ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) { - if (hi2c->Mode == HAL_I2C_MODE_MASTER) + HAL_I2C_ModeTypeDef tmp_mode = hi2c->Mode; + + if ((tmp_mode == HAL_I2C_MODE_MASTER) || (tmp_mode == HAL_I2C_MODE_MEM)) { /* Process Locked */ __HAL_LOCK(hi2c); diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_smbus_ex.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_smbus_ex.c index 12492be75..73d5620be 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_smbus_ex.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_smbus_ex.c @@ -6,6 +6,8 @@ * This file provides firmware functions to manage the following * functionalities of SMBUS Extended peripheral: * + Extended features functions + * + WakeUp Mode Functions + * + FastModePlus Functions * ****************************************************************************** * @attention diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart.c index 735ac8cdf..97c320a22 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart.c @@ -4605,6 +4605,7 @@ static void UART_RxISR_8BIT_FIFOEN(UART_HandleTypeDef *huart) HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } + break; } } @@ -4778,6 +4779,7 @@ static void UART_RxISR_16BIT_FIFOEN(UART_HandleTypeDef *huart) HAL_UART_RxCpltCallback(huart); #endif /* USE_HAL_UART_REGISTER_CALLBACKS */ } + break; } } diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart_ex.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart_ex.c index 12740d66d..09745ecad 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart_ex.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_hal_uart_ex.c @@ -576,7 +576,7 @@ HAL_StatusTypeDef HAL_UARTEx_DisableFifoMode(UART_HandleTypeDef *huart) /* Disable UART */ __HAL_UART_DISABLE(huart); - /* Enable FIFO mode */ + /* Disable FIFO mode */ CLEAR_BIT(tmpcr1, USART_CR1_FIFOEN); huart->FifoMode = UART_FIFOMODE_DISABLE; diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_comp.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_comp.c index 85961c13b..6e564db79 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_comp.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_comp.c @@ -58,7 +58,7 @@ /* Note: On this STM32 series, comparator input plus parameters are */ /* the same on all COMP instances. */ /* However, comparator instance kept as macro parameter for */ -/* compatibility with other STM32 families. */ +/* compatibility with other STM32 series. */ #if defined(LL_COMP_INPUT_PLUS_IO1) #define IS_LL_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) \ (((__INPUT_PLUS__) == LL_COMP_INPUT_PLUS_IO1) \ @@ -75,10 +75,10 @@ /* Note: On this STM32 series, comparator input minus parameters are */ /* the same on all COMP instances. */ /* However, comparator instance kept as macro parameter for */ -/* compatibility with other STM32 families. */ +/* compatibility with other STM32 series. */ #if defined(LL_COMP_INPUT_MINUS_IO2) #define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \ - (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) \ + (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) \ || ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) \ || ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) \ || ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) \ @@ -90,7 +90,7 @@ ) #else #define IS_LL_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) \ - (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) \ + (((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_4VREFINT) \ || ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_1_2VREFINT) \ || ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_3_4VREFINT) \ || ((__INPUT_MINUS__) == LL_COMP_INPUT_MINUS_VREFINT) \ @@ -114,7 +114,7 @@ ) #define IS_LL_COMP_OUTPUT_BLANKING_SOURCE(__OUTPUT_BLANKING_SOURCE__) \ - (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) \ + (((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_NONE) \ || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM1_OC5) \ || ((__OUTPUT_BLANKING_SOURCE__) == LL_COMP_BLANKINGSRC_TIM2_OC3) \ ) diff --git a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_rng.c b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_rng.c index 3d6dab377..78cd5d202 100644 --- a/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_rng.c +++ b/stm32cube/stm32wbxx/drivers/src/stm32wbxx_ll_rng.c @@ -99,7 +99,7 @@ ErrorStatus LL_RNG_DeInit(const RNG_TypeDef *RNGx) * - SUCCESS: RNG registers are initialized according to RNG_InitStruct content * - ERROR: not applicable */ -ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, LL_RNG_InitTypeDef *RNG_InitStruct) +ErrorStatus LL_RNG_Init(RNG_TypeDef *RNGx, const LL_RNG_InitTypeDef *RNG_InitStruct) { /* Check the parameters */ assert_param(IS_RNG_ALL_INSTANCE(RNGx)); diff --git a/stm32cube/stm32wbxx/release_note.html b/stm32cube/stm32wbxx/release_note.html index d4057d087..c8b17f7a3 100644 --- a/stm32cube/stm32wbxx/release_note.html +++ b/stm32cube/stm32wbxx/release_note.html @@ -83,27 +83,59 @@

    Purpose

    Update History

    - +

    Main Changes

    -

    Patch Release for BLE, Thread and Zigbee.

    +

    Maintenance Release for BLE, 802.15.4, Concurrent, Thread and Zigbee updates

    • BLE updates:
        -
      • Full stack updates for STM32WB5x with respect to:

        +
      • A new command ACI_HAL_EAD_ENCRYPT_DECRYPT is added to ease implementation of Encrypted Advertising Data feature.
      • +
    • +
    • MAC updates: 
        -
      • The BLE stack better handles the collision between local GATT client request and remote GATT indication.
      • -
      • A new SMP configuration is added to forbid use of peer debug key for Secure Connections
      • -
      • While waiting for PKA end of computation CPU2 is now in sleep mode to save power consumption.
      • +
      • To reduce the ROM footprint, optional features have been excluded from the MAC RFD configuration.
      • +
      • Correct PANID conflict notification that might return wrong channel.
    • +
    • Thread updates: +
        +
      • Increased speed of Thread commissioning and SRP key exchanges, using PKA HW accelerator when possible.
      • +
      • Increased Thread RCP stability, robustness and efficiency.
    • Zigbee updates:
        -
      • Fix implemented inside the stack to solve an issue when sending unicast messages after restarting from persistence.
      • +
      • Fix startup memory leak issue when using TouchLink.
      • +
      • Fixed zcl_send_response issue for loopback Default Response.
    • -
    • Thread updates: +
    • BLE Thread updates:
        -
      • Bug resolution when using the CLI command that made impossible to send further commands.
      • +
      • Corrected a low-power over consumption when BLE advertising is started or stopped during runtime.
      • +
      • Corrected a bug that prevented to erase flash during BLE activity.
      • +
    • +
    • BLE Zigbee updates: +
        +
      • Corrected a bug that prevented to erase flash during BLE activity.
      • +
    • +
    +


    +

    +

    Maintenance Release for HAL/LL Drivers and Projects updates

    +
      +
    • HAL/LL Drivers updates +
        +
      • Update HAL/LL drivers to include latest corrections +
          +
        • Update of HAL CRYP, I2C, QSPI, TIM, UART drivers.
        • +
        • Update of LL LPUART, TIM drivers.
        • +
      • +
      • Refer to release notes for further details
      • +
    • +
    • Projects updates +
        +
      • Update of FW projects following changes in latest version of HAL/LL and Middlewares and alignments with CubeMx +
          +
        • P-NUCLEO-WB55.Nucleo/Examples_LL/TIM/TIM_PWMOutput.
        • +


    @@ -126,27 +158,27 @@

    Projects

    Projects/P-NUCLEO-WB55.Nucleo -V1.19.0 +V1.20.0 release notes Projects/P-NUCLEO-WB55.USBDongle -V1.19.0 +V1.20.0 release notes Projects/STM32WB5MM-DK -V1.19.0 +V1.20.0 release notes Projects/NUCLEO-WB15CC -V1.19.0 +V1.20.0 release notes Projects/B-WB1M-WPAN1 -V1.19.0 +V1.20.0 release notes @@ -225,17 +257,17 @@

    Components

    stm32wb5x_BLE_HCI_AdvScan_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_HCILayer_extended_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_HCILayer_fw.bin -V1.19.1 +V1.20.0 release notes @@ -245,102 +277,102 @@

    Components

    stm32wb5x_BLE_Mac_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_BLE_Stack_full_extended_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_Stack_full_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_Stack_light_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_Thread_dynamic_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_BLE_Thread_static_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_BLE_Zigbee_FFD_dynamic_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_Zigbee_FFD_static_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_Zigbee_RFD_dynamic_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_BLE_Zigbee_RFD_static_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_Mac_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_Phy_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_Thread_FTD_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_Thread_MTD_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_Thread_RCP_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_Zigbee_FFD_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb5x_Zigbee_RFD_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_BLE_HCI_AdvScan_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_BLE_HCILayer_extended_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_BLE_HCILayer_fw.bin -V1.19.1 +V1.20.0 release notes @@ -350,72 +382,72 @@

    Components

    stm32wb3x_BLE_Mac_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb3x_BLE_Stack_full_extended_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_BLE_Stack_full_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_BLE_Stack_light_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_Mac_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb3x_Phy_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb3x_Thread_FTD_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb3x_Thread_MTD_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb3x_Thread_RCP_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb3x_Zigbee_FFD_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb3x_Zigbee_RFD_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb1x_BLE_HCI_AdvScan_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb1x_BLE_HCILayer_extended_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb1x_BLE_HCILayer_fw.bin -V1.19.1 +V1.20.0 release notes @@ -425,17 +457,17 @@

    Components

    stm32wb1x_BLE_Stack_full_extended_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb1x_BLE_Stack_full_fw.bin -V1.19.1 +V1.20.0 release notes stm32wb1x_BLE_Stack_light_fw.bin -V1.19.1 +V1.20.0 release notes @@ -457,12 +489,12 @@

    Components

    STM32WB CMSIS -V1.12.1 +V1.12.2 release notes STM32WBxx_HAL_Driver -V1.14.2 +V1.14.3 release notes @@ -554,7 +586,7 @@

    Components

    STM32 USB Device Library -V2.11.2 +V2.11.3 release notes @@ -564,7 +596,7 @@

    Components

    STM32 WPAN -V1.19.1 +V1.20.0 release notes @@ -574,7 +606,7 @@

    Components

    Azure RTOS ThreadX -V6.2.0 +V6.2.1 release notes ST @@ -634,12 +666,6 @@

    Known Limitations

    • /B-WB1M-WPAN1/Examples/BSP/BSP_Example/MDK-ARM.
    -
  • BLE: -
      -
    • /P-NUCLEO-WB55.Nucleo/Applications/BLE/APPLI_BLE_MESH_LIGHTING_LPN : limitation on Led behavior on LPN2.
    • -
    • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_MESH_LIGHTING_PRF_NODE: limitation on Led behavior on LPN2.
    • -
    • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_MESH_LIGHTING_PROVISIONER: limitation on serial terminal during self-provisioning.
    • -
  • THREAD:
    • Thread FTD all roles are supported excepting Border router.
    • @@ -649,10 +675,6 @@

      Known Limitations

      • Latest Zigbee Compliant Platform Certification - FFD RFD - done on Cube_FW_WB V1.16.
      -
    • BLE Thread / BLE Zigbee : -
        -
      • Flash erase operation cannot be performed with BLE Thread / BLE Zigbee applications.
      • -
    • FUS upgrade:
      • If Anti-Rollback needs to be activated, please make sure to activate it only after installing the latest FUS version (>= V1.2.0) and after successfully installing a wireless stack (without deleting it). Otherwise, further wireless stack installation will be blocked.
      • @@ -661,33 +683,37 @@

        Known Limitations

        • For STM32CubeIDE project, some elements inside the traces are not correctly displayed (uint64_t formatting only). Not observable on IAR and MDK-ARM project.
        +
      • The projects are not available for the following applications and examples: +
          +
        • /NUCLEO-WB15CC/Applications/BLE_LLD/BLE_LLD_Lowpower
        • +
      • The MDK-ARM projects are not available for the following applications and examples:
        • /P-NUCLEO-WB55.USBDongle/Applications/BLE_LLD/BLE_LLD_Datarate.
        • -
        • /STM32WB5MM-DK/Applications/Thread/Thread_Coap_Generic.
        • -
        • /P-NUCLEO-WB55.Nucleo/Applications/Thread/Thread_Coap_Generic_Ota.
        • -
        • /P-NUCLEO-WB55.USBDongle/Applications/Thread/Thread_Cli_Cmd.
      • The STM32CubeIDE projects are not available for the following applications and examples:
          -
        • /P-NUCLEO-WB55.USBDongle/Applications/BLE_LLD/BLE_LLD_Datarate.
        • -
        • /P-NUCLEO-WB55.USBDongle/Applications/Thread/Thread_Cli_Cmd.
        • -
        • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_p2pServerThreadX.
        • /P-NUCLEO-WB55.Nucleo/Applications/Thread/Thread_Coap_Generic_ThreadX.
        • -
        • /P-NUCLEO-WB55.Nucleo/Applications/Thread/Thread_RCP_Cli_Cmd.
      • The Debug configuration is not available with STM32CubeIDE projects for the following application:
        • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_Ota/STM32CubeIDE.
        • /NUCLEO-WB15CC/Applications/BLE/BLE_Ota/STM32CubeIDE.
      • +
      • The CubeMX projects are not available for the following applications and examples: +
          +
        • /NUCLEO-WB15CC/Applications/FreeRTOS/FreeRTOS_Mutexes
        • +
        • /P-NUCLEO-WB55.Nucleo/Applications/FreeRTOS/FreeRTOS_Mutexes
        • +
        • /P-NUCLEO-WB55.Nucleo/Applications/FreeRTOS/FreeRTOS_Semaphore
        • +
        • /P-NUCLEO-WB55.Nucleo/Applications/FreeRTOS/FreeRTOS_SemaphoreFromISR
        • +
      • If you face issue to access some files during compilation (e.g. “cannot open source input file”) with some examples on partner IDEs, please consider to move either the full package manually or just the example using the “Example Selector” from STM32CubeMX, closer to the root of the disk (long path issue).

      Development Toolchains and Compilers

        -
      • IAR Embedded Workbench for ARM (EWARM) toolchain V9.20.1 + ST-Link
      • -
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.38 + ST-Link. Support of ARM Compiler 6 (AC5 like warning) for HAL/LL/BSP drivers and STMicroelectronics Middleware components
      • -
      • STM32CubeIDE toolchain V1.14.0 (native GNU ARM 11.3-2023-10) + ST-Link
      • +
      • IAR Embedded Workbench for ARM (EWARM) toolchain V9.20.1 + ST-Link.
      • +
      • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.38 + ST-Link. Support of ARM Compiler 6 (AC5 like warning) for HAL/LL/BSP drivers and STMicroelectronics Middleware components.
      • +
      • STM32CubeIDE toolchain V1.15.0 (GCC 12.3) + ST-Link.

      Supported Devices and boards

        @@ -726,40 +752,27 @@

        Dependencies

  • - +

    Main Changes

    -

    Maintenance Release for BLE, Thread and Zigbee updates

    +

    Patch Release for BLE, Thread and Zigbee.

      -
    • Update Examples and Applications to MDK-ARM (Keil) v5.38.

    • BLE updates:
        -
      • BLE Light stack support 2Mbit TX/RX PHY update.
      • -
    • -
    • BLE Zigbee updates: +
    • Full stack updates for STM32WB5x with respect to:

        -
      • Correct an issue in the management of the AES driver when Zigbee is used in concurrency mode with BLE.
      • +
      • The BLE stack better handles the collision between local GATT client request and remote GATT indication.
      • +
      • A new SMP configuration is added to forbid use of peer debug key for Secure Connections
      • +
      • While waiting for PKA end of computation CPU2 is now in sleep mode to save power consumption.
    • -
    • Thread updates: -
        -
      • OT stack update to SHA-1: 8bc25042ba5cde20605eec2a329c0dff575303f4 (07/07/2023).
      • -
      • OpenThread Command Line Interface (CLI) moved from M0 to M4 in order to optimize memory footprint on the coprocessor.
    • -
    -

    Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

    -
      -
    • HAL/LL Drivers updates -
        -
      • Update HAL/LL drivers to include latest corrections +
      • Zigbee updates:
          -
        • Update of HAL GPIO, CRYP, I2C, SMBUS, QSPI, CORTEX, TIM, LPTIM drivers.
        • -
        • Update of LL UTILS drivers.
        • -
      • -
      • Refer to release notes for further details
      • +
      • Fix implemented inside the stack to solve an issue when sending unicast messages after restarting from persistence.
    • -
    • Projects updates +
    • Thread updates:
        -
      • Update of FW projects following changes in latest version of HAL/LL and Middlewares and alignments with CubeMx /STM32WB5MM-DK/Examples/BSP/BSP_Example.
      • +
      • Bug resolution when using the CLI command that made impossible to send further commands.


    @@ -782,27 +795,27 @@

    Projects

    Projects/P-NUCLEO-WB55.Nucleo -V1.19.0 +V1.19.0 release notes Projects/P-NUCLEO-WB55.USBDongle -V1.19.0 +V1.19.0 release notes Projects/STM32WB5MM-DK -V1.19.0 +V1.19.0 release notes Projects/NUCLEO-WB15CC -V1.19.0 +V1.19.0 release notes Projects/B-WB1M-WPAN1 -V1.19.0 +V1.19.0 release notes @@ -881,17 +894,17 @@

    Components

    stm32wb5x_BLE_HCI_AdvScan_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_HCILayer_extended_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_HCILayer_fw.bin -V1.19.0 +V1.19.1 release notes @@ -901,102 +914,102 @@

    Components

    stm32wb5x_BLE_Mac_802_15_4_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_BLE_Stack_full_extended_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_Stack_full_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_Stack_light_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_Thread_dynamic_fw.bin -V1.19.0 +V1.20.0 release notes stm32wb5x_BLE_Thread_static_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb5x_BLE_Zigbee_FFD_dynamic_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_Zigbee_FFD_static_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_Zigbee_RFD_dynamic_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_BLE_Zigbee_RFD_static_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_Mac_802_15_4_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb5x_Phy_802_15_4_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb5x_Thread_FTD_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb5x_Thread_MTD_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb5x_Thread_RCP_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb5x_Zigbee_FFD_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb5x_Zigbee_RFD_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_BLE_HCI_AdvScan_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_BLE_HCILayer_extended_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_BLE_HCILayer_fw.bin -V1.19.0 +V1.19.1 release notes @@ -1006,72 +1019,72 @@

    Components

    stm32wb3x_BLE_Mac_802_15_4_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb3x_BLE_Stack_full_extended_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_BLE_Stack_full_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_BLE_Stack_light_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_Mac_802_15_4_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb3x_Phy_802_15_4_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb3x_Thread_FTD_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb3x_Thread_MTD_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb3x_Thread_RCP_fw.bin -V1.19.0 +V1.19.0 release notes stm32wb3x_Zigbee_FFD_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb3x_Zigbee_RFD_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb1x_BLE_HCI_AdvScan_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb1x_BLE_HCILayer_extended_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb1x_BLE_HCILayer_fw.bin -V1.19.0 +V1.19.1 release notes @@ -1081,17 +1094,17 @@

    Components

    stm32wb1x_BLE_Stack_full_extended_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb1x_BLE_Stack_full_fw.bin -V1.19.0 +V1.19.1 release notes stm32wb1x_BLE_Stack_light_fw.bin -V1.19.0 +V1.19.1 release notes @@ -1113,12 +1126,12 @@

    Components

    STM32WB CMSIS -V1.12.1 +V1.12.1 release notes STM32WBxx_HAL_Driver -V1.14.2 +V1.14.2 release notes @@ -1133,7 +1146,7 @@

    Components

    STM32WB5MM-DK -V1.0.6 +V1.0.6 release notes @@ -1220,7 +1233,7 @@

    Components

    STM32 WPAN -V1.19.0 +V1.19.1 release notes @@ -1382,25 +1395,27 @@

    Dependencies

    - +

    Main Changes

    -

    Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

    +

    Maintenance Release for BLE, Thread and Zigbee updates

      +
    • Update Examples and Applications to MDK-ARM (Keil) v5.38.

    • BLE updates:
        -
      • RC1
      • +
      • BLE Light stack support 2Mbit TX/RX PHY update.
    • -
    • MAC 802.15.4 / Thread / Zigbee  and concurrent mode updates: +
    • BLE Zigbee updates:
        -
      • RC1
      • +
      • Correct an issue in the management of the AES driver when Zigbee is used in concurrency mode with BLE.
    • -
    • Zigbee updates: +
    • Thread updates:
        -
      • RC1
      • +
      • OT stack update to SHA-1: 8bc25042ba5cde20605eec2a329c0dff575303f4 (07/07/2023).
      • +
      • OpenThread Command Line Interface (CLI) moved from M0 to M4 in order to optimize memory footprint on the coprocessor.
    -

    Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

    +

    Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

    • HAL/LL Drivers updates
        @@ -1413,7 +1428,7 @@

        Main

    • Projects updates
        -
      • Update of STM32CubeIDE projects to fix the location of .size directive in startup code to allow proper size information of vector table.
      • +
      • Update of FW projects following changes in latest version of HAL/LL and Middlewares and alignments with CubeMx /STM32WB5MM-DK/Examples/BSP/BSP_Example.


    @@ -1554,8 +1569,8 @@

    Components

    release notes -stm32wb5x_BLE_Mac_812_15_4_fw.bin -V1.18.0 +stm32wb5x_BLE_Mac_802_15_4_fw.bin +V1.19.0 release notes @@ -1575,67 +1590,67 @@

    Components

    stm32wb5x_BLE_Thread_dynamic_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_BLE_Thread_static_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_BLE_Zigbee_FFD_dynamic_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_BLE_Zigbee_FFD_static_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_BLE_Zigbee_RFD_dynamic_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_BLE_Zigbee_RFD_static_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Mac_802_15_4_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Phy_802_15_4_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Thread_FTD_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Thread_MTD_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Thread_RCP_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Zigbee_FFD_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb5x_Zigbee_RFD_fw.bin -V1.18.0 +V1.19.0 release notes @@ -1660,7 +1675,7 @@

    Components

    stm32wb3x_BLE_Mac_802_15_4_fw.bin -V1.18.0 +V1.19.0 release notes @@ -1680,37 +1695,37 @@

    Components

    stm32wb3x_Mac_802_15_4_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb3x_Phy_802_15_4_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb3x_Thread_FTD_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb3x_Thread_MTD_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb3x_Thread_RCP_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb3x_Zigbee_FFD_fw.bin -V1.18.0 +V1.19.0 release notes stm32wb3x_Zigbee_RFD_fw.bin -V1.18.0 +V1.19.0 release notes @@ -1787,7 +1802,7 @@

    Components

    STM32WB5MM-DK -V1.0.5 +V1.0.6 release notes @@ -1942,21 +1957,22 @@

    Known Limitations

    • Following applications are not supported:
        -
      • /B-WB1M-WPAN1/Examples/BSP/BSP_Example/MDK-ARM
      • +
      • /B-WB1M-WPAN1/Examples/BSP/BSP_Example/MDK-ARM.
    • BLE:
        -
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/APPLI_BLE_MESH_LIGHTING_LPN : limitation on Led behavior on LPN2
      • -
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_MESH_LIGHTING_PRF_NODE: limitation on Led behavior on LPN2
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/APPLI_BLE_MESH_LIGHTING_LPN : limitation on Led behavior on LPN2.
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_MESH_LIGHTING_PRF_NODE: limitation on Led behavior on LPN2.
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_MESH_LIGHTING_PROVISIONER: limitation on serial terminal during self-provisioning.
    • THREAD:
        -
      • Thread FTD all roles are supported excepting Border router
      • -
      • Thread MTD all roles are supported excepting Border router
      • +
      • Thread FTD all roles are supported excepting Border router.
      • +
      • Thread MTD all roles are supported excepting Border router.
    • ZIGBEE :
        -
      • Latest Zigbee Compliant Platform Certification - FFD RFD - done on Cube_FW_WB V1.16
      • +
      • Latest Zigbee Compliant Platform Certification - FFD RFD - done on Cube_FW_WB V1.16.
    • BLE Thread / BLE Zigbee :
        @@ -1972,25 +1988,31 @@

        Known Limitations

    • The MDK-ARM projects are not available for the following applications and examples:
        -
      • /P-NUCLEO-WB55.USBDongle/Applications/BLE_LLD/BLE_LLD_Datarate
      • -
      • /NUCLEO-WB15CC/Applications/BLE/BLE_HeartRate
      • +
      • /P-NUCLEO-WB55.USBDongle/Applications/BLE_LLD/BLE_LLD_Datarate.
      • +
      • /STM32WB5MM-DK/Applications/Thread/Thread_Coap_Generic.
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/Thread/Thread_Coap_Generic_Ota.
      • +
      • /P-NUCLEO-WB55.USBDongle/Applications/Thread/Thread_Cli_Cmd.
    • The STM32CubeIDE projects are not available for the following applications and examples:
        -
      • /P-NUCLEO-WB55.USBDongle/Applications/BLE_LLD/BLE_LLD_Datarate
      • -
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_p2pServerThreadX
      • +
      • /P-NUCLEO-WB55.USBDongle/Applications/BLE_LLD/BLE_LLD_Datarate.
      • +
      • /P-NUCLEO-WB55.USBDongle/Applications/Thread/Thread_Cli_Cmd.
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_p2pServerThreadX.
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/Thread/Thread_Coap_Generic_ThreadX.
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/Thread/Thread_RCP_Cli_Cmd.
    • The Debug configuration is not available with STM32CubeIDE projects for the following application:
        -
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_Ota/STM32CubeIDE
      • +
      • /P-NUCLEO-WB55.Nucleo/Applications/BLE/BLE_Ota/STM32CubeIDE.
      • +
      • /NUCLEO-WB15CC/Applications/BLE/BLE_Ota/STM32CubeIDE.
    • If you face issue to access some files during compilation (e.g. “cannot open source input file”) with some examples on partner IDEs, please consider to move either the full package manually or just the example using the “Example Selector” from STM32CubeMX, closer to the root of the disk (long path issue).

    Development Toolchains and Compilers

    • IAR Embedded Workbench for ARM (EWARM) toolchain V9.20.1 + ST-Link
    • -
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.31 + ST-Link. Support of ARM Compiler 6 (AC5 like warning) for HAL/LL/BSP drivers and STMicroelectronics Middleware components
    • -
    • STM32CubeIDE toolchain V1.11.0 (native GNU ARM 10.3-2021-10 or optional GNU ARM 9-2020-q2-update) + ST-Link
    • +
    • RealView Microcontroller Development Kit (MDK-ARM) toolchain V5.38 + ST-Link. Support of ARM Compiler 6 (AC5 like warning) for HAL/LL/BSP drivers and STMicroelectronics Middleware components
    • +
    • STM32CubeIDE toolchain V1.14.0 (native GNU ARM 11.3-2023-10) + ST-Link

    Supported Devices and boards

      @@ -2005,11 +2027,13 @@

      Dependencies

      • STM32WB_Copro_Wireless_Binaries available under Projects/STM32WB_Copro_Wireless_Binaries
      -

      Several applications (BLE (Bluetooth low energy), Thread or Mac 802-15-4) are available under:

      +

      Several applications (BLE (Bluetooth low energy), BLE_Thread, BLE_Zigbee, BLE_LLD, Thread, Zigbee or Mac 802-15-4) are available under:

        +
      • Projects/B-WB1M-WPAN1/Applications
      • +
      • Projects/NUCLEO-WB15CC/Applications
      • Projects/P-NUCLEO-WB55.Nucleo/Applications
      • Projects/P-NUCLEO-WB55.USBDongle/Applications
      • -
      • Projects/NUCLEO-WB15CC/Applications
      • +
      • Projects/STM32WB5MM-DK/Applications

      All of them are provided in source code and some of them are also available in binary format directly for ready to use usage:

        @@ -2030,7 +2054,7 @@

        Dependencies

        Main Changes

        -

        Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

        +

        Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

        • BLE  updates:
            @@ -2049,7 +2073,7 @@

            Mainte
          • Inter core communication improvement (M4-M0+) on all Zigbee applications making it more robust in very extreme conditions (Environment in which with multiple messages need to be processed at the same time).
        -

        Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

        +

        Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

        • HAL/LL Drivers updates
            @@ -4594,7 +4618,7 @@

            Dependencies

            Main Changes

            -

            Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

            +

            Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

            • THREAD  updates:
                @@ -4627,7 +4651,7 @@

                Mainte
              • Bug corrected in Dynamic Concurrent applications to prevent switching from 802.15.4 to BLE while radio is in an incorrect state.
            -

            Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

            +

            Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

            • HAL/LL Drivers updates
                @@ -5268,7 +5292,7 @@

                Dependencies

                Main Changes

                -

                Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                +

                Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                Porting IAR toolChain 9.20.1.

                • THREAD  updates: @@ -5298,7 +5322,7 @@

                  Mainte
                • Improve robustness when switching from BLE to Zigbee.
              -

              Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

              +

              Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

              • HAL/LL Drivers updates
                  @@ -5938,7 +5962,7 @@

                  Dependencies

                  Main Changes

                  -

                  Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                  +

                  Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                  • THREAD updates:
                      @@ -5962,7 +5986,7 @@

                      Maintenance Release for Midd
                    • Update of Touchsensing Library
                    • Update of Azure RTOS ThreadX
                    -

                    Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                    +

                    Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                    • CMSIS Device updates
                        @@ -7236,7 +7260,7 @@

                        Dependencies

                        Main Changes

                        -

                        Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                        +

                        Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                        • BLE updates:
                            @@ -7267,7 +7291,7 @@

                            Mainte
                          • Add support of Azure RTOS-ThreadX Middleware, Provide Connectivity examples.
                        -

                        Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                        +

                        Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                        • HAL/LL Drivers updates:
                            @@ -9704,7 +9728,7 @@

                            Dependencies

                            Main Changes

                            -

                            Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                            +

                            Maintenance Release for BLE, 802.15.4, Thread and Zigbee updates

                            • BLE updates
                                @@ -9748,7 +9772,7 @@

                                Mainte


                              -

                              Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                              +

                              Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                              • General updates
                                  @@ -10927,7 +10951,7 @@

                                  Maintenance Rel


                                -

                                Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                                +

                                Maintenance Release for CMSIS, HAL/LL Drivers and Projects updates

                                • CMSIS Device updates
                                    diff --git a/stm32cube/stm32wbxx/soc/stm32wbxx.h b/stm32cube/stm32wbxx/soc/stm32wbxx.h index e43460630..b112bef74 100644 --- a/stm32cube/stm32wbxx/soc/stm32wbxx.h +++ b/stm32cube/stm32wbxx/soc/stm32wbxx.h @@ -69,7 +69,7 @@ extern "C" { */ #define __STM32WBxx_CMSIS_VERSION_MAIN (0x01U) /*!< [31:24] main version */ #define __STM32WBxx_CMSIS_VERSION_SUB1 (0x0CU) /*!< [23:16] sub1 version */ -#define __STM32WBxx_CMSIS_VERSION_SUB2 (0x01U) /*!< [15:8] sub2 version */ +#define __STM32WBxx_CMSIS_VERSION_SUB2 (0x02U) /*!< [15:8] sub2 version */ #define __STM32WBxx_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */ #define __STM32WBxx_CMSIS_DEVICE_VERSION ((__STM32WBxx_CMSIS_VERSION_MAIN << 24)\ |(__STM32WBxx_CMSIS_VERSION_SUB1 << 16)\ From d8469c6c8d66af38645aa34edd0f9aea559357b8 Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 16:38:11 +0200 Subject: [PATCH 10/11] lib/stm32: update stm32wb to cube version V1.20.0 Update Cube version for STM32WBxx series on https://github.com/STMicroelectronics from version v1.19.1 to version v1.20.0 Signed-off-by: Guillaume Gautier --- lib/stm32wb/hci/README | 4 ++-- lib/stm32wb/hci/app_conf.h | 1 + lib/stm32wb/hci/shci.h | 5 ++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/stm32wb/hci/README b/lib/stm32wb/hci/README index 81d004088..a6ef2e392 100644 --- a/lib/stm32wb/hci/README +++ b/lib/stm32wb/hci/README @@ -6,7 +6,7 @@ Origin: https://github.com/STMicroelectronics/STM32CubeWB Status: - version v1.19.1 + version v1.20.0 Purpose: This library is used on stm32wb series to enable HCI communication between @@ -48,7 +48,7 @@ URL: https://github.com/STMicroelectronics/STM32CubeWB Commit: - ea5475b0d214489a3a3556f7b3f66d0954d006e0 + 529e571e91c93d4bf1aae6e0d69b9a5dcf4d828d Maintained-by: External diff --git a/lib/stm32wb/hci/app_conf.h b/lib/stm32wb/hci/app_conf.h index 6978506b0..2ded89a03 100644 --- a/lib/stm32wb/hci/app_conf.h +++ b/lib/stm32wb/hci/app_conf.h @@ -627,6 +627,7 @@ typedef enum #define PUSH_BUTTON_SW1_EXTI_IRQHandler EXTI4_IRQHandler #define PUSH_BUTTON_SW2_EXTI_IRQHandler EXTI0_IRQHandler +#define PUSH_BUTTON_SW3_EXTI_IRQHandler EXTI1_IRQHandler /* USER CODE END Defines */ /****************************************************************************** * Scheduler diff --git a/lib/stm32wb/hci/shci.h b/lib/stm32wb/hci/shci.h index 30ae10cb4..59c6fd463 100644 --- a/lib/stm32wb/hci/shci.h +++ b/lib/stm32wb/hci/shci.h @@ -882,6 +882,7 @@ extern "C" { #define SHCI_C2_CONFIG_CONFIG1_BIT0_BLE_NVM_DATA_TO_SRAM (1<<0) #define SHCI_C2_CONFIG_CONFIG1_BIT1_THREAD_NVM_DATA_TO_INTERNAL_FLASH (0<<1) #define SHCI_C2_CONFIG_CONFIG1_BIT1_THREAD_NVM_DATA_TO_SRAM (1<<1) +#define SHCI_C2_CONFIG_CONFIG1_BIT2_SET_EUI64_FORMAT (1<<2) /** * EvtMask1 @@ -1340,7 +1341,9 @@ typedef struct { * 1 - BLE NVM Data are written in SRAM cache pointed by BleNvmRamAddress * - bit1 : 0 - THREAD NVM Data data are flushed in internal secure flash * 1 - THREAD NVM Data are written in SRAM cache pointed by ThreadNvmRamAddress - * - bit2 to bit7 : Unused, shall be set to 0 + * - bit2 : 0 - Thread EUI64 is set to new (and current) format + * 1 - Thread EUI64 is set to old format + * - bit3 to bit7 : Unused, shall be set to 0 * uint8_t EvtMask1 : * When a bit is set to 0, the event is not reported * bit0 : Asynchronous Event with Sub Evt Code 0x9201 (= SHCI_SUB_EVT_ERROR_NOTIF) From 7bc0e5ca635dba537a50a591afd392aef66c5442 Mon Sep 17 00:00:00 2001 From: Guillaume Gautier Date: Tue, 24 Sep 2024 16:57:54 +0200 Subject: [PATCH 11/11] stm32cube: common_ll: Regeneration after cube updates Re - generate common_ll headers after Cube updates Signed-off-by: Guillaume Gautier --- stm32cube/common_ll/README.rst | 16 ++++++++-------- stm32cube/common_ll/include/stm32_ll_crs.h | 4 +++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/stm32cube/common_ll/README.rst b/stm32cube/common_ll/README.rst index 5f0b37e16..da5f63ada 100644 --- a/stm32cube/common_ll/README.rst +++ b/stm32cube/common_ll/README.rst @@ -10,17 +10,17 @@ below. =============== =============== Series CubeMX version =============== =============== -stm32c0xx 1.1.0 +stm32c0xx 1.2.0 stm32f0xx 1.11.5 -stm32f1xx 1.8.5 -stm32f2xx 1.9.4 +stm32f1xx 1.8.6 +stm32f2xx 1.9.5 stm32f3xx 1.11.5 -stm32f4xx 1.28.0 +stm32f4xx 1.28.1 stm32f7xx 1.17.2 stm32g0xx 1.6.2 -stm32g4xx 1.5.2 -stm32h5xx 1.2.0 -stm32h7rsxx 1.0.0 +stm32g4xx 1.6.0 +stm32h5xx 1.3.0 +stm32h7rsxx 1.1.0 stm32h7xx 1.11.2 stm32l0xx 1.12.2 stm32l1xx 1.10.4 @@ -28,7 +28,7 @@ stm32l4xx 1.18.1 stm32l5xx 1.5.1 stm32mp1xx 1.6.0 stm32u0xx 1.1.0 -stm32u5xx 1.5.0 +stm32u5xx 1.6.0 stm32wb0x 1.0.0 stm32wbaxx 1.3.1 stm32wbxx 1.19.1 diff --git a/stm32cube/common_ll/include/stm32_ll_crs.h b/stm32cube/common_ll/include/stm32_ll_crs.h index 180346e81..c3632cad5 100644 --- a/stm32cube/common_ll/include/stm32_ll_crs.h +++ b/stm32cube/common_ll/include/stm32_ll_crs.h @@ -4,7 +4,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -#if defined(CONFIG_SOC_SERIES_STM32F0X) +#if defined(CONFIG_SOC_SERIES_STM32C0X) +#include +#elif defined(CONFIG_SOC_SERIES_STM32F0X) #include #elif defined(CONFIG_SOC_SERIES_STM32G0X) #include